text:
iTweenFluent
============

A set of wrapper classes to manage [iTween](http://code.google.com/p/itween/) using fluent interfaces in Unity.

Example
-------

using iTweenFluent:

    using System.Collections;
    using iTweenFluent;
    using UnityEngine;

    public class TweenTests : MonoBehaviour {

        // Use this for initialization
        void Start () {
            iTween.CameraFadeAdd();
        }

        // Update is called once per frame
        void Update () {
            if (Input.GetKeyDown( KeyCode.Q )) {
                iTweenCameraFadeFrom.Create()
                    .Amount( .5f )
                    .EaseType( iTween.EaseType.easeInOutBack )
                    .LoopType( iTween.LoopType.pingPong )
                    .Name( "CameraFade" )
                    .Launch();
            }

            if (Input.GetKeyDown( KeyCode.W )) {
                iTweenColorTo.Create( gameObject )
                    .Color( Color.cyan )
                    .NamedColorValue( "_Color" )
                    .Time( 2 )
                    .OnComplete( "color2" )
                    .OnCompleteTarget( this.gameObject )
                    .Launch();
            }

            if (Input.GetKeyDown( KeyCode.E )) {
                iTweenFadeTo.Create( gameObject )
                    .Alpha( 1 )
                    .Amount( 0 )
                    .Delay( .5f )
                    .Time( 1 )
                    .Launch();
            }

            if (Input.GetKeyDown( KeyCode.R )) {
                iTweenFadeTo.Create( gameObject )
                    .Amount( 1 )
                    .Time( 1 )
                    .Launch();
            }

            if (Input.GetKeyDown( KeyCode.T )) {
                iTweenMoveBy.Create( gameObject )
                    .Amount( new Vector3( 1, 2, 4 ) )
                    .Axis( "x" )
                    .Speed( 1 )
                    .LoopType( iTween.LoopType.pingPong )
                    .Launch();
            }

        }

        private void color2() {
            iTweenColorTo.Create( gameObject )
                .Color( Color.green )
                .Time( 1 )
                .OnComplete( "color3" )
                .OnCompleteTarget( gameObject )
                .Launch();

        }

        private void color3() {
            iTweenColorFrom.Create( gameObject )
                .Color( Color.red )
                .Time( 1 )
                .Launch();
        }
    }

Compared to using iTween:

    using System.Collections;
    using UnityEngine;

    public class TweenTests : MonoBehaviour {

        // Use this for initialization
        void Start () {
            iTween.CameraFadeAdd();
        }

        // Update is called once per frame
        void Update () {
            if (Input.GetKeyDown( KeyCode.Q )) {
                iTween.CameraFadeFrom(
                    new Hashtable() {
                        { "amount", .5f },
                        { "easetype", iTween.EaseType.easeInOutBack },
                        { "looptype", iTween.LoopType.pingPong },
                        { "name", "CameraFade" }
                    } );
            }

            if (Input.GetKeyDown( KeyCode.W )) {
                iTween.ColorTo(
                    gameObject,
                    new Hashtable() {
                        { "color", Color.cyan },
                        { "NamedColorValue", "_Color" },
                        { "time", 2 },
                        { "oncomplete", "color2" },
                        { "oncompletetarget", this.gameObject }
                    } );
            }

            if (Input.GetKeyDown( KeyCode.E )) {
                iTween.FadeTo(
                    gameObject,
                    new Hashtable() {
                        { "alpha", 1 },
                        { "amount", 0 },
                        { "delay", .5f },
                        { "time", 1 }
                    } );
            }

            if (Input.GetKeyDown( KeyCode.R )) {
                iTween.FadeTo(
                    gameObject,
                    new Hashtable() {
                        { "amount",  1 },
                        { "time", 1 }
                    } );
            }

            if (Input.GetKeyDown( KeyCode.T )) {
                iTween.MoveBy(
                    gameObject,
                    new Hashtable() {
                        { "amount", new Vector3( 1, 2, 4 ) },
                        { "axis", "x" },
                        { "speed", 1 },
                        { "looptype", iTween.LoopType.pingPong }
                    } );
            }

        }

        private void color2() {
            iTween.ColorTo(
                gameObject,
                new Hashtable() {
                    { "color", Color.green },
                    { "time",  1 },
                    { "oncomplete", "color3" },
                    { "oncompletetarget", gameObject }
                } );

        }

        private void color3() {
            iTween.ColorFrom(
                gameObject,
                new Hashtable() {
                    { "color", Color.red },
                    { "time", 1 }
                } );
        }
    }

License
-------
This project is released under the MIT License. Check the LICENSE file included
with the project, or each individual file for details.

Basically, you are free to do as you please, except change the license.


text:
"""SSD training target generator."""
from mxnet import nd
from mxnet.gluon import Block
from gluoncv.nn.matcher import CompositeMatcher, BipartiteMatcher, MaximumMatcher
from gluoncv.nn.sampler import OHEMSampler, NaiveSampler
from gluoncv.nn.coder import MultiClassEncoder, NormalizedBoxCenterEncoder
from gluoncv.nn.bbox import BBoxCenterToCorner

class SSDTargetGenerator(Block):
    """Training targets generator for Single-shot Object Detection.

    Parameters
    ----------
    iou_thresh : float
        IOU overlap threshold for maximum matching, default is 0.5.
    neg_thresh : float
        IOU overlap threshold for negative mining, default is 0.5.
    negative_mining_ratio : float
        Ratio of hard vs positive for negative mining.
    stds : array-like of size 4, default is (0.1, 0.1, 0.2, 0.2)
        Std value to be divided from encoded values.
    """
    def __init__(self, iou_thresh=0.5, neg_thresh=0.5, negative_mining_ratio=3,
                 stds=(0.1, 0.1, 0.2, 0.2), **kwargs):
        super(SSDTargetGenerator, self).__init__(**kwargs)
        self._matcher = CompositeMatcher(
            [BipartiteMatcher(share_max=False), MaximumMatcher(iou_thresh)])
        if negative_mining_ratio > 0:
            self._sampler = OHEMSampler(negative_mining_ratio, thresh=neg_thresh)
            self._use_negative_sampling = True
        else:
            self._sampler = NaiveSampler()
            self._use_negative_sampling = False
        self._cls_encoder = MultiClassEncoder()
        self._box_encoder = NormalizedBoxCenterEncoder(stds=stds)
        self._center_to_corner = BBoxCenterToCorner(split=False)

    # pylint: disable=arguments-differ
    def forward(self, anchors, cls_preds, gt_boxes, gt_ids):
        """Generate training targets."""
        anchors = self._center_to_corner(anchors.reshape((-1, 4)))
        ious = nd.transpose(nd.contrib.box_iou(anchors, gt_boxes), (1, 0, 2))
        matches = self._matcher(ious)
        if self._use_negative_sampling:
            samples = self._sampler(matches, cls_preds, ious)
        else:
            samples = self._sampler(matches)
        cls_targets = self._cls_encoder(samples, matches, gt_ids)
        box_targets, box_masks = self._box_encoder(samples, matches, anchors, gt_boxes)
        return cls_targets, box_targets, box_masks

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var fs = require('fs');
var path = require('path');
var toFile = require('to-file');
var extname = require('gulp-extname');
var runtimes = require('composer-runtimes');
var matter = require('parser-front-matter');
var assemble = require('..');

module.exports = function smithy(dir, filepath) {
  var app = assemble();
  app.use(runtimes());

  app.engine('*', require('engine-handlebars'));
  app.onLoad(/./, function (view, next) {
    matter.parse(view, next);
  });

  app.create('files', {engine: '*'});
  toViews(dir, filepath, function (fp, opts) {
    app.files.addView(toFile(fp, opts));
  });

  app.task('default', function() {
    return app.toStream('files')
      .pipe(app.renderFile('*'))
      .pipe(extname())
      .pipe(app.dest('build'))
  });

  app.build = app.build.bind(app, 'default');
  return app;
};

function toViews(dir, filepath, fn) {
  var base = path.resolve(dir, filepath || 'src');
  var files = fs.readdirSync(base);

  var len = files.length, i = -1;
  while (++i < len) {
    var name = files[i];
    var fp = path.resolve(base, name);
    var stat = fs.lstatSync(fp);
    if (stat.isFile()) {
      fn(fp, {base: base, stat: stat});
    }
  }
}


text:
using TAlex.BeautifulFractals.Rendering;

namespace TAlex.BeautifulFractals.Fractals
{
    public abstract class Fractal3D : Fractal
    {
        public abstract void Render(IGraphics3DContext context);
    }
}


text:
'use strict';

/**
 * @constructor
 *
 * @param {Object} [options] null, or an object containing the following properties:
 * 		@param {String} options.userName - Rackspace user name (specify here, or when calling {@link authenticate})
 * 		@param {String} options.apiKey	- Rackspace API key (specify here, or when calling {@link authenticate})
 * 		@param {String} [options.region] - Rackspace default region. Can be one of: iad, ord, dfw, hkg, lon, syd - defaults to dfw
 * 		@param {String} [options.clientId] - A GUID identifying the current queue client. Defaults to a random GUID
 * 		@param {String} [options.persistedTokenPath] - If provided, auth token will be persisted locally, and looked for at this path
 */
var RacQ = function(options) {
	//external libraries
	var util = require('util'),
		fs = require('fs'),
		_ = require('lodash'),
		request = require('request'),
		dbg = require('debug'),
		debug = dbg('racq'),
		statistics = dbg('racq:statistics'),
		errors = require('./errors');

	//private variables
	var _userName,
		_apiKey,
		_token,
		_persistedTokenPath,
		_clientId,
		_defaultRegion,
		_authUrl,
		_queueUrl,
		_statistics;

	///////////////////////
	// Private function  //
	///////////////////////
	//persist auth token to file
	var persistToken = function() {
		fs.writeFileSync(_persistedTokenPath, JSON.stringify(_token), {encoding: 'utf-8'});
		debug('token persisted to file %s', _persistedTokenPath);
	};

	//get auth token from file
	var getPersistedToken = function() {
		var token = null;
		if(_persistedTokenPath) {
			if(fs.existsSync(_persistedTokenPath)) {
				token = JSON.parse(fs.readFileSync(_persistedTokenPath), {encoding: 'utf-8'});
				debug('token read from file %s', _persistedTokenPath);
			}
			else {
				debug('file %s does not exist', _persistedTokenPath);
			}
		}
		else {
			debug('no path provided');
		}
		return token;
	};

	//Request wrapper, enabling statistics capture
	var httpRequest = function(method, options, callback) {
		var objectLength = function(o) {
			var length = 0;
			if(!_.isNull(o) && !_.isUndefined(o)) {
				if(_.isString(o)) {
					length = o.length;
				}
				else if(_.isObject(o)) {
					length = JSON.stringify(o).length;
				}
				else {
					debug('object type: %s', typeof o);
				}
			}
			return length;
		};

		var func = request[method];
		func(options, function(error, response, body) {
			_statistics.calls++;
			_statistics.bytesReceived += objectLength(body);
			_statistics.bytesSent += objectLength(options.json);
			statistics('Statistics:', _statistics);
			return callback(error, response, body);
		});
	};

	//return error object for function, based on response status code
	var returnError = function(functionName, statusCode) {
		statusCode = statusCode.toString();
		debug('Error: function=%s, status=%s', functionName, statusCode);
		if(Object.keys(errors.shared).indexOf(statusCode) !== -1) {
			return new Error(errors.shared[statusCode]);
		}
		else if(errors[functionName] && Object.keys(errors[functionName]).indexOf(statusCode) !== -1) {
			return new Error(errors[functionName][statusCode]);
		}
		else {
			return new Error('Status code: ' + statusCode);
		}
	};

	//turn a JSON object into a query string
	var objectToQueryString = function(obj) {
		return _.reduce(obj, function(result, value, key) {
				return (!_.isNull(value) && !_.isUndefined(value)) ? (result += key + '=' + value + '&') : result;
		}, '').slice(0, -1);
	};

	//get value from a query string
	var getValueFromQueryString = function(url, key) {
		return (new RegExp('[?|&]' + key + '=' + '([^&;]+?)(&|#|;|$)').exec(url) || [,""])[1].replace(/\+/g, '%20') || null;
	};

	//build url for queue/message operations
	var getQueueUrl = function(queue, messages) {
		var url = _queueUrl;
		if(queue) {
			url += '/' + queue;
		}
		if(messages) {
			url += '/messages';
		}
		return url;
	};

	//set default request headers
	var getRequestHeaders = function(includeClientId) {
		var headers = {
			'Content-type': 'application/json',
			'Accept': 'application/json',
			'X-Auth-Token': _token.id
		};
		if(includeClientId) {
			headers['Client-ID'] = _clientId;
		}
		return headers;
	};

	//parse body and return messages object
	var processMessages = function(body) {
		var messages = JSON.parse(body),
			result = {
				messages: [],
				marker: getValueFromQueryString(_.findWhere(messages.links, {rel: 'next'}).href, 'marker')
			};
		for(var i = 0; i < messages.messages.length; i++) {
			var message = messages.messages[i];
			result.messages.push({
				id: message.href.split('/').pop(),
				body: message.body,
				ttl: message.ttl,
				age: message.age
			});
		}
		return result;
	};

	//parse body and return messages object
	var processClaims = function(body) {
		var claims = body || [],
			result = [];
		for(var i = 0; i < claims.length; i++) {
			var claim = claims[i];
			result.push({
				id: claim.href.split('/').pop().split('?')[0],
				claimId: getValueFromQueryString(claim.href, 'claim_id'),
				body: claim.body,
				ttl: claim.ttl,
				age: claim.age
			});
		}
		return result;
	};

	//constructor - process user options
	(function(options) {
		var guid = require('guid'),
			urls = require('./urls');

		_defaultRegion =  (options && options.region) ? options.region : 'dfw';
		_authUrl = urls.authUrl;
		_queueUrl = urls.queueUrl.replace('REGION', _defaultRegion);
		_clientId = (options && options.clientId) ? options.clientId : guid.raw();
		_statistics = {
			calls: 0,
			bytesReceived: 0,
			bytesSent: 0
		};
		if(options && options.userName) {
			_userName = options.userName;
		}
		if(options && options.apiKey) {
			_apiKey = options.apiKey;
		}
		if(options && options.persistedTokenPath) {
			_persistedTokenPath = options.persistedTokenPath;
			_token = getPersistedToken();
		}
	}(options));

	/////////////////////
	// Authentication  //
	/////////////////////
	/**
	 * Get current client ID
	 * @return {String} client ID GUID
	 */
	this.getClientId = function() {
		return _clientId;
	};

	/**
	 * Deletes the currently used token, making it possible to re-authenticate even if the actual token hasn't expired yet
	 */
	this.deleteToken = function() {
		_token = null;
	};

	/**
	 * Get current network statistics (for accounting purposes)
	 * @return {Object} statistics object containing number of calls, bytes sent, and bytes recieved so far
	 */
	this.getStatistics = function() {
		return _statistics;
	};

	/**
	 * Authenticate API calls
	 *
	 * Authenticates credentials against Rackspace auth endpoint, receiveing the auth token used in the rest of the calls.
	 * If a path has been specified in constructor, token will be taken from local file,
	 * and received token will be persisted to local file.
	 *
	 * @param {String} [userName] - Rackspace user name (if not provided to constructor)
	 * @param {String} [apiKey] - Rackspace user name (if not provided to constructor)
	 * @param {Function} callback - the function to call when authentication ends. Returns with null on success, or error object
	 */
	this.authenticate = function(userName, apiKey, callback) {
		//if userName and apiKey have been provided earlier
		if(arguments.length === 1) {
			userName = _userName;
			apiKey = _apiKey;
			callback = arguments[0];
		}
		//if we already have a valid token, return
		if(_token && (new Date(_token.expires)) > Date.now()) {
			return callback(null);
		}

		var options = {
				url: _authUrl,
				json: {
					auth: {
						'RAX-KSKEY:apiKeyCredentials': {
							'username': userName,
							'apiKey': apiKey
						}
					}
				}
			};
		httpRequest('post', options, function(error, response, body) {
			if (!error && (response.statusCode === 200 || response.statusCode === 203)) {
				_token = body.access.token;
				debug('authenticate: ' + util.inspect(_token, true, null));
				if(_persistedTokenPath) {
					persistToken();
				}
				return callback(null);
			}
			else {
				_token = null;
				debug('authenticate: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('authenticate', response.statusCode), null);
			}
		});
	};

	///////////////////////
	// Queue operations  //
	///////////////////////
	/**
	 * List all queues in account, in alphabetical order
	 *
	 * @param {Object} [parameters] - query parameters. Can be null, or an object with one or more of the following:
	 * 		@param {Integer} [parameters.limit] - limit number of queues returned (1-10, default: 10)
	 * 		@param {Integer} [parameters.marker] - The marker to use to get the next batch of messages
	 * 		@param {Boolean} [parameters.detailed] - should queue data include metadata (default: false)
	 * @param  {Function} callback - Returns with array of queues on success, or error object
	 */
	this.listQueues = function(parameters, callback) {
		var url = getQueueUrl();
		if(arguments.length === 1) {	//no parameters object supplied
			callback = parameters;
		}
		else {
			url += '?' + objectToQueryString(parameters);
			debug(url);
		}
		var options = {
				url: url,
				headers: getRequestHeaders(false)
			};
		httpRequest('get', options, function(error, response, body) {
			if (!error && response.statusCode === 200) {
				var result = JSON.parse(body).queues;
				debug(util.inspect(result));
				return callback(null, result);
			}
			else {
				debug('listQueues: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('listQueues', response.statusCode), null);
			}
		});
	};

	/**
	 * Create new queue
	 * @param  {String}   queueName
	 * @param  {Function} callback - Returns with null on success, or error object
	 */
	this.createQueue = function(queueName, callback) {
		var options = {
				url: getQueueUrl(queueName),
				headers: getRequestHeaders(false)
			};
		httpRequest('put', options, function(error, response) {
			if (!error && (response.statusCode === 201 || response.statusCode === 204)) {
				return callback(null);
			}
			else {
				debug('createQueue: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('createQueue', response.statusCode));
			}
		});
	};

	/**
	 * Delete queue
	 * @param  {String}   queueName
	 * @param  {Function} callback - Returns with null on success, or error object
	 */
	this.deleteQueue = function(queueName, callback) {
		var options = {
				url: getQueueUrl(queueName),
				headers: getRequestHeaders(false)
			};
		httpRequest('del', options, function(error, response) {
			if (!error && (response.statusCode === 200 || response.statusCode === 204)) {
				debug('queue %s deleted', queueName);
				return callback(null);
			}
			else {
				debug('deleteQueue: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('deleteQueue', response.statusCode));
			}
		});
	};

	/**
	 * Checks whether a queue exists
	 * @param  {String}   queueName
	 * @param  {Function} callback - Returns with true if queue exists, false otherwise, or error object
	 */
	this.queueExists = function(queueName, callback) {
		var options = {
				url: getQueueUrl(queueName),
				headers: getRequestHeaders(false)
			};
		httpRequest('get', options, function(error, response) {
			if (!error  && (response.statusCode === 204 || response.statusCode === 404)) {
				if(response.statusCode === 204) {
					debug('queue %s exists', queueName);
					return callback(null, true);
				}
				else if(response.statusCode === 404) {
					debug('queue %s does not exist', queueName);
					return callback(null, false);
				}
			}
			else {
				debug('queueExists: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('queueExists', response.statusCode));
			}
		});
	};

	/**
	 * Get queue statistics
	 * @param  {String}   queueName
	 * @param  {Function} callback - Returns with stats, or error object
	 */
	this.getQueueStats = function(queueName, callback) {
		var options = {
				url: getQueueUrl(queueName) + '/stats',
				headers: getRequestHeaders(false)
			};
		httpRequest('get', options, function(error, response, body) {
			if (!error && response.statusCode === 200) {
				var result = JSON.parse(body);
				debug('getQueueStats: %s', util.inspect(result));
				return callback(null, result);
			}
			else {
				debug('getQueueStats: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('getQueueStats', response.statusCode), null);
			}
		});
	};

	/**
	 * Set queue metatdata
	 *
	 * @param {String}   queueName
	 * @param {Object}   metadata
	 * @param {Function} callback - Returns null on success, or error object
	 */
	this.setQueueMetadata = function(queueName, metadata, callback) {
		var options = {
				url: getQueueUrl(queueName) + '/metadata',
				headers: getRequestHeaders(false),
				json: metadata
			};
		httpRequest('put', options, function(error, response) {
			if (!error && response.statusCode === 204) {
				return callback(null);
			}
			else {
				debug('setQueueMetadata: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('setQueueMetadata', response.statusCode));
			}
		});
	};

	/**
	 * Get queue metadata
	 *
	 * @param  {String}   queueName
	 * @param  {Function} callback - Returns with queue metadata, or error object
	 */
	this.getQueueMetadata = function(queueName, callback) {
		var options = {
				url: getQueueUrl(queueName) + '/metadata',
				headers: getRequestHeaders(false)
			};
		httpRequest('get', options, function(error, response, body) {
			if (!error && response.statusCode === 200) {
				var result = JSON.parse(body);
				debug('getQueueMetadata: %s', util.inspect(result));
				return callback(null, result);
			}
			else {
				debug('getQueueMetadata: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('getQueueMetadata', response.statusCode), null);
			}
		});
	};

	//////////////////////////
	// Message operations   //
	//////////////////////////
	/**
	 * Put message/s in queue
	 *
	 * @param  {String}			queueName
	 * @param  {Object|Array}	messages - Object, or Array of Objects, 1-10 messages in the following format:
	 * 							@param {Integer} messages.ttl Time-To-Live for message in seconds (min. value 60)
	 *							@param {Object} messages.body A JSON message object
	 * @param  {Function} callback - Returns null if successful, or error object
	 */
	this.postMessages = function(queueName, messages, callback) {
		if(!_.isArray(messages)) {
			debug('single message posted');
			messages = [messages];
		}
		var options = {
				url: getQueueUrl(queueName, true),
				headers: getRequestHeaders(true),
				json: messages
			};
		httpRequest('post', options, function(error, response) {
			if (!error && (response.statusCode === 200 || response.statusCode === 201)) {
				debug('postMessages: %s messages posted', messages.length);
				return callback(null);
			}
			else {
				debug('postMessages: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('postMessages', response.statusCode));
			}
		});
	};

	/**
	 * Get messages from queue
	 * Can be invoked with 2, 3 or 4 parameters: queueName, [echo], [limit], callback
	 *
	 * @param {String} queueName
	 * @param {Object} [parameters] - query parameters. Can be null, or an object with one or more of the following:
	 * 		@param {Integer} [parameters.limit] - limit number of messages returned (1-10, default: 10)
	 * 		@param {Integer} [parameters.marker] - The marker to use to get the next batch of messages
	 * 		@param {Boolean} [parameters.echo] - should messages put by this client be returned (default: false)
	 * 		@param {Boolean} [parameters.include_claimed] - should claimed messages be returned (default: false)
	 * @param {Function} callback - Returns array of message objects on success, or error object
	 */
	this.getMessages = function(queueName, parameters, callback) {
		var url = getQueueUrl(queueName, true);
		if(arguments.length === 2) {	//no parameters object supplied
			callback = parameters;
		}
		else {
			url += '?' + objectToQueryString(parameters);
			debug(url);
		}
		var options = {
				url: url,
				headers: getRequestHeaders(true)
			};
		httpRequest('get', options, function(error, response, body) {
			if (!error && response.statusCode === 200) {
				var result = processMessages(body);
				debug('getMessages: %s messages retrieved', result.length);
				return callback(null, result);
			}
			else {
				debug('getMessages: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('getMessages', response.statusCode), null);
			}
		});
	};

	/**
	 * Get message/s by id/s
	 *
	 * @param  {String}   queueName
	 * @param  {String}   messageIds - one or more message ids, seperated by comma
	 * @param  {Function} callback - Returns array of message objects on success, or error object
	 */
	this.getMessagesById = function(queueName, messageIds, callback) {
        var separator = messageIds.indexOf(',') > -1 ? '?ids=' : '/',
            options = {
				url: getQueueUrl(queueName, true) + separator + messageIds,
				headers: getRequestHeaders(true)
			};
		httpRequest('get', options, function(error, response, body) {
			if (!error && response.statusCode === 200) {
				return callback(null, JSON.parse(body));
			}
			else {
				debug('getMessageById: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('getMessagesById', response.statusCode), null);
			}
		});
	};

	/**
	 * Delete message from queue
	 *
	 * @param  {String}   queueName
	 * @param  {String}   messageIds - one or more message ids, separated by comma
	 * @param {String} [claimId] - if provided, will provide the claim Id for a SINGLE message to be deleted
	 * @param  {Function} callback - Returns null on success, or error object
	 */
	this.deleteMessages = function(queueName, messageIds, claimId, callback) {
        var separator = messageIds.indexOf(',') > -1 ? '?ids=' : '/',
            claim = messageIds.indexOf(',') > -1 ? '&' : '?',
            url = getQueueUrl(queueName, true) + separator + messageIds;

		if(arguments.length === 3) {
			callback = claimId;
		}
		else {
			url += claim + 'claim_id=' + claimId;
			debug(url);
		}
		var options = {
				url: url,
				headers: getRequestHeaders(true)
			};
		httpRequest('del', options, function(error, response) {
			if(!error && (response.statusCode === 200 || response.statusCode === 204)) {
				debug('%s deleted from %s', messageIds, queueName);
				return callback(null);
			}
			else {
				debug('deleteMessage: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('deleteMessage', response.statusCode));
			}
		});
	};

	/////////////
	// Claims  //
	/////////////
	/**
	 * Claim messages: a client can mark messages it's handling with a claim, delete them upon process end,
	 * or releasing the claim if it takes too long to process
	 *
	 * @param  {String}   queueName
	 * @param  {Object}   [parameters] - claim paramters:
	 *					@param {Integer} [parameters.limit] maximum number of messages to claim. Can be 1-20, default 10
	 *					@param {Integer} [parameters.ttl]	time before server releases the claim. Can be 60-43200 seconds (12 hours), default 60
	 *					@param {Integer} [parameters.grace] grace period to extend claimed message's life. Can be 60-43200 seconds (12 hours), default 60
	 * @param  {Function} callback - Returns array of message objects on success, or error object
	 */
	this.claimMessages = function(queueName, parameters, callback) {
		var url = getQueueUrl(queueName) + '/claims';
		if(arguments.length === 2) {
			callback = parameters;
		}
		else {
			url += '?limit=' + parameters.limit;
		}
		var options = {
			url: url,
			headers: getRequestHeaders(true),
			json: parameters
		};
		httpRequest('post', options, function(error, response, body) {
			if(!error && response.statusCode === 201) {
				//debug('claimMessages: %s', util.inspect(body, true, 2));
				var claims = processClaims(body);
				debug('claimMessages: %s messages claimed', claims.length);
				return callback(null, claims);
			}
			else if(response.statusCode === 204) {
				debug('claimMessages: no messages claimed');
				return callback(null, null);
			}
			else {
				debug('claimMessages: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('claimMessages', response.statusCode), null);
			}
		});
	};

	/**
	 * Check which massages are claimed by claim ids
	 *
	 * @param  {String}   queueName
	 * @param  {String}   claimIds - one, or more claim ids to verify, separated by comma
	 * @param  {Function} callback - Returns array of message objects on success, or error object
	 */
	this.queryClaims = function(queueName, claimIds, callback) {
		var url = getQueueUrl(queueName, false) + '/claims/' + claimIds,
			options = {
				url: url,
				headers: getRequestHeaders(true)
			};
		debug(url);
		httpRequest('get', options, function(error, response, body) {
			if(!error && response.statusCode === 200) {
				var messages = JSON.parse(body).messages || [];
				debug('queryClaims: %s messages claimed', messages.length);
				return callback(null, processClaims(messages));
			}
			else {
				debug('queryClaims: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('queryClaims', response.statusCode), null);
			}
		});
	};

	/**
	 * Update the TTL and grace period of claimed messages
	 *
	 * @param  {String}   queueName
	 * @param  {String}   claimIds - one, or more claim ids to verify, separated by comma
	 * @param  {Object}   parameters
	 * 			@param {Integer} parameters.ttl	time before server releases the claim. Can be 60-43200 seconds (12 hours), default 60
	 *			@param {Integer} parameters.grace grace period to extend claimed message's life. Can be 60-43200 seconds (12 hours), default 60
	 * @param  {Function} callback - Returns null on success, or error object
	 */
	this.updateClaims = function(queueName, claimIds, parameters, callback) {
		var url = getQueueUrl(queueName) + '/claims/' + claimIds,
			options = {
				url: url,
				headers: getRequestHeaders(true),
				json: parameters
			};
		httpRequest('patch', options, function(error, response) {
			debug('updateClaims: ' + response.statusCode);
			if(!error && (response.statusCode === 200 || response.statusCode === 204)) {
				return callback(null);
			}
			else {
				debug('updateClaims: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('updateClaims', response.statusCode));
			}
		});

	};

	/**
	 * Release claim on messages, allowing them to be claimed by a different client
	 *
	 * @param  {String}   queueName
	 * @param  {String}   claimIds - one, or more claim ids to verify, separated by comma
	 * @param  {Function} callback - Returns null on success, or error object
	 */
	this.releaseClaims = function(queueName, claimIds, callback) {
		var url = getQueueUrl(queueName) + '/claims/' + claimIds,
			options = {
				url: url,
				headers: getRequestHeaders(true)
			};
		httpRequest('del', options, function(error, response) {
			if(!error && (response.statusCode === 200 || response.statusCode === 204)) {
				return callback(null);
			}
			else {
				debug('releaseClaims: ' + (error || 'statusCode: ' + response.statusCode));
				return callback(error || returnError('releaseClaims', response.statusCode));
			}
		});
	};
};

module.exports = RacQ;


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:stretchMode="columnWidth" >

    <ImageView
        android:id="@id/quickaction_arrow_up"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10.0dip"
        android:src="@drawable/quickaction_arrow_up_black" />

    <FrameLayout
        android:id="@id/quickaction_popup_header"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="-1.0dip"
        android:background="@drawable/quickaction_top_frame_black" >

        <Button
            android:id="@id/quickaction_dialog_close"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_weight="0.0"
            android:background="@android:color/transparent"
            android:drawableLeft="@drawable/quickaction_dialog_close"
            android:gravity="right|center"
            android:paddingRight="7.0dip"
            android:paddingTop="7.0dip"
            android:visibility="gone" />
    </FrameLayout>

    <TextView
        android:id="@id/quickaction_popup_title"
        style="@style/PopupTitle"
        android:layout_below="@id/quickaction_popup_header" />

    <LinearLayout
        android:id="@id/quickaction_content_panel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/quickaction_popup_header"
        android:background="@drawable/quickaction_popup_with_arrow_background_black"
        android:fadingEdgeLength="0.0dip"
        android:orientation="vertical"
        android:paddingLeft="1.0px"
        android:paddingRight="1.0px"
        android:stretchMode="columnWidth" />

    <FrameLayout
        android:id="@id/quickaction_popup_footer"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/quickaction_content_panel"
        android:background="@drawable/quickaction_bottom_frame_black" />

    <ImageView
        android:id="@id/quickaction_arrow_down"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/quickaction_popup_footer"
        android:layout_marginTop="-1.0dip"
        android:src="@drawable/quickaction_arrow_down_black" />

</LinearLayout>


text:
static __weak id currentFirstResponder;

@implementation UIResponder (FirstResponder)

+(id)currentFirstResponder {
    currentFirstResponder = nil;
    [[UIApplication sharedApplication] sendAction:@selector(findFirstResponder:) to:nil from:nil forEvent:nil];
    return currentFirstResponder;
}

-(void)findFirstResponder:(id)sender {
    currentFirstResponder = self;
}

@end


text:
all: synthesize translate map placeandroute
	@echo Everything is done! log files are in log/
synthesize:
	xst -ifn "./scripts/SimCore.xst" -ofn "./log/xst.log"

translate: synthesize
	ngdbuild -intstyle ise -dd _ngo -nt timestamp -uc virtex5.ucf -p xc5vlx110t-ff1136-2 SimCore.ngc SimCore.ngd > ./log/ngdbuild.log

map: translate
	map -intstyle ise -p xc5vlx110t-ff1136-2 -w -logic_opt off -ol high -t 1 -register_duplication off -global_opt off -mt off -cm area -ir off -pr off -lc off -power off -o SimCore_map.ncd SimCore.ngd SimCore.pcf > ./log/map.log

placeandroute: map
	par -w -intstyle ise -ol high -mt off SimCore_map.ncd SimCore.ncd SimCore.pcf > ./log/par.log

clean:
	ls | grep -v -E "\w*\.vhd|SimCore.ncd|\.gitignore|\.git|\.xise|RS232.ngc|\.ucf|\.prj" | grep -E "\w*\.\w*" | xargs rm -v -f
	ls | grep -v -E "\w*\.vhd|SimCore.ncd|\.gitignore|\.git|\.xise|RS232.ngc|\.ucf|\.prj|log|scripts|src|Makefile" | xargs rm -v -f -r

clean_log:
	rm -f -v ./log/*.log


text:
typedef struct _node *Node;
typedef struct _list *List;

typedef struct _list {
    Node first;
    Node last;
    int size;
} list;

typedef struct _node {
    int data;
    Node next;
} node;

List createList(void);
Node createNode(int i);

int isSorted(List l);


text:
<?php

declare(strict_types=1);

namespace Biplane\YandexDirect\Api\V4\Contract;

use AllowDynamicProperties;

/**
 * Auto-generated code.
 */
#[AllowDynamicProperties]
class EnableSharedAccountRequest
{
    protected $Login = null;

    /**
     * @return static
     */
    public static function create()
    {
        return new static();
    }

    public function getLogin(): string
    {
        return $this->Login;
    }

    /**
     * @return $this
     */
    public function setLogin(string $value)
    {
        $this->Login = $value;

        return $this;
    }
}


text:
"""Support for Alpha2 IO device battery sensors."""

from homeassistant.components.binary_sensor import (
    BinarySensorDeviceClass,
    BinarySensorEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import EntityCategory
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from . import Alpha2BaseCoordinator
from .const import DOMAIN

async def async_setup_entry(
    hass: HomeAssistant,
    config_entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Add Alpha2 sensor entities from a config_entry."""

    coordinator: Alpha2BaseCoordinator = hass.data[DOMAIN][config_entry.entry_id]

    async_add_entities(
        Alpha2IODeviceBatterySensor(coordinator, io_device_id)
        for io_device_id, io_device in coordinator.data["io_devices"].items()
        if io_device["_HEATAREA_ID"]
    )

class Alpha2IODeviceBatterySensor(
    CoordinatorEntity[Alpha2BaseCoordinator], BinarySensorEntity
):
    """Alpha2 IO device battery binary sensor."""

    _attr_device_class = BinarySensorDeviceClass.BATTERY
    _attr_entity_category = EntityCategory.DIAGNOSTIC

    def __init__(self, coordinator: Alpha2BaseCoordinator, io_device_id: str) -> None:
        """Initialize Alpha2IODeviceBatterySensor."""
        super().__init__(coordinator)
        self.io_device_id = io_device_id
        self._attr_unique_id = f"{io_device_id}:battery"
        io_device = self.coordinator.data["io_devices"][io_device_id]
        heat_area = self.coordinator.data["heat_areas"][io_device["_HEATAREA_ID"]]
        self._attr_name = (
            f"{heat_area['HEATAREA_NAME']} IO device {io_device['NR']} battery"
        )

    @property
    def is_on(self):
        """Return the state of the sensor."""
        # 0=empty, 1=weak, 2=good
        return self.coordinator.data["io_devices"][self.io_device_id]["BATTERY"] < 2


text:
package org.apache.ignite.internal.processors.database;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.configuration.DataRegionConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.configuration.DataStorageConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.internal.processors.cache.IgniteCacheProxy;
import org.apache.ignite.internal.processors.cache.persistence.DataStructure;
import org.junit.Test;

import static org.apache.ignite.IgniteSystemProperties.getInteger;

/**
 * Base class for memory leaks tests.
 */
public abstract class IgniteDbMemoryLeakAbstractTest extends IgniteDbAbstractTest {
    /** */
    private static final int CONCURRENCY_LEVEL = 16;

    /** */
    private static final int MIN_PAGE_CACHE_SIZE = 1048576 * CONCURRENCY_LEVEL;

    /** */
    private volatile Exception ex;

    /** */
    private long warmUpEndTime;

    /** */
    private long endTime;

    /** */
    private long loadedPages;

    /** */
    private long delta;

    /** */
    private long probeCnt;

    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        super.beforeTest();

        DataStructure.rnd = null;

        long startTime = System.nanoTime();

        warmUpEndTime = startTime + TimeUnit.SECONDS.toNanos(warmUp());

        endTime = warmUpEndTime + TimeUnit.SECONDS.toNanos(duration());
    }

    /** {@inheritDoc} */
    @Override protected void configure(IgniteConfiguration cfg) {
        cfg.setMetricsLogFrequency(5000);
    }

    /** {@inheritDoc} */
    @Override protected void configure(DataStorageConfiguration mCfg) {
        mCfg.setConcurrencyLevel(CONCURRENCY_LEVEL);

        long size = (1024 * (isLargePage() ? 16 : 4) + 24) * pagesMax();

        mCfg.setDefaultDataRegionConfiguration(
            new DataRegionConfiguration().setMaxSize(Math.max(size, MIN_PAGE_CACHE_SIZE)).setName("default"));
    }

    /**
     * @return Test duration in seconds.
     */
    protected int duration() {
        return getInteger("IGNITE_MEMORY_LEAKS_TEST_DURATION", 300);
    }

    /**
     * @return Warm up duration in seconds.
     */
    @SuppressWarnings("WeakerAccess")
    protected int warmUp() {
        return getInteger("IGNITE_MEMORY_LEAKS_TEST_WARM_UP", 450);
    }

    /** {@inheritDoc} */
    @Override protected int gridCount() {
        return 1;
    }

    /** {@inheritDoc} */
    @Override protected boolean indexingEnabled() {
        return false;
    }

    /** {@inheritDoc} */
    @Override protected long getTestTimeout() {
        return (warmUp() + duration() + 10) * 1000; // Extra seconds to stop all threads.
    }

    /**
     * @param ig Ignite instance.
     * @return IgniteCache.
     */
    protected abstract IgniteCache<Object, Object> cache(IgniteEx ig);

    /**
     * @return Cache key to perform an operation.
     */
    protected abstract Object key();

    /**
     * @param key Cache key to perform an operation.
     * @return Cache value to perform an operation.
     */
    protected abstract Object value(Object key);

    /**
     * @param cache IgniteCache.
     */
    protected void operation(IgniteCache<Object, Object> cache) {
        Object key = key();
        Object val = value(key);

        switch (nextInt(3)) {
            case 0:
                cache.getAndPut(key, val);

                break;

            case 1:
                cache.get(key);

                break;

            case 2:
                cache.getAndRemove(key);
        }
    }

    /**
     * @param bound Upper bound (exclusive). Must be positive.
     * @return Random int value.
     */
    protected static int nextInt(int bound) {
        return ThreadLocalRandom.current().nextInt(bound);
    }

    /**
     * @return Random int value.
     */
    protected static int nextInt() {
        return ThreadLocalRandom.current().nextInt();
    }

    /**
     * @throws Exception If failed.
     */
    @Test
    public void testMemoryLeak() throws Exception {
        final IgniteEx ignite = grid(0);

        final IgniteCache<Object, Object> cache = cache(ignite);

        Runnable target = new Runnable() {
            @Override public void run() {
                while (ex == null && System.nanoTime() < endTime) {
                    try {
                        operation(cache);
                    }
                    catch (Exception e) {
                        ex = e;

                        break;
                    }
                }
            }
        };

        Thread[] threads = new Thread[CONCURRENCY_LEVEL];

        info("Warming up is started.");

        for (int i = 0; i < threads.length; i++) {
            threads[i] = new Thread(target);
            threads[i].start();
        }

        while (ex == null && System.nanoTime() < warmUpEndTime)
            Thread.sleep(100);

        if (ex != null)
            throw ex;

        info("Warming up is ended.");

        while (ex == null && System.nanoTime() < endTime) {
            try {
                check(cache);
            }
            catch (Exception e) {
                ex = e;

                break;
            }

            Thread.sleep(TimeUnit.SECONDS.toMillis(5));
        }

        if (ex != null)
            throw ex;
    }

    /**
     * Callback to check the current state.
     *
     * @param cache Cache instance.
     * @throws Exception If failed.
     */
    protected final void check(IgniteCache cache) throws Exception {
        long pagesActual = ((IgniteCacheProxy)cache).context().dataRegion().pageMemory().loadedPages();

        if (loadedPages > 0) {
            delta += pagesActual - loadedPages;

            int allowedDelta = pagesDelta();

            if (probeCnt++ > 12) { // We need some statistic first. Minimal statistic is taken for a minute.
                long actualDelta = delta / probeCnt;

                assertTrue(
                    "Average growth pages in the number is more than expected [allowed=" + allowedDelta + ", actual=" + actualDelta + "]",
                    actualDelta <= allowedDelta);
            }
        }

        long pagesAllowed = pagesMax();

        assertTrue("Allocated pages count is more than expected [allowed=" + pagesAllowed + ", actual=" + pagesActual + "]", pagesActual < pagesAllowed);

        loadedPages = pagesActual;
    }

    /**
     * @return Maximal allowed pages number.
     */
    protected abstract long pagesMax();

    /**
     * @return Expected average number of pages, on which their total number can grow per 5 seconds.
     */
    @SuppressWarnings("WeakerAccess")
    protected int pagesDelta() {
        return 3;
    }
}


text:
package io.quarkus.qute.deployment.typesafe;

import java.util.Collections;
import java.util.List;

public class Machine {

    public Integer ping = 1;

    private MachineStatus status;

    public Machine setStatus(MachineStatus status) {
        this.status = status;
        return this;
    }

    public MachineStatus getStatus() {
        return status;
    }

    public List<String> getNames(int pings) {
        return Collections.singletonList("ping");
    }

}


text:
#include <boost/asio.hpp>
#include <boost/asio/ip/address.hpp>
#include <testing/gunit.h>

#include "bfd/bfd_client.h"
#include "bfd/bfd_control_packet.h"
#include "bfd/bfd_server.h"
#include "bfd/bfd_session.h"
#include "bfd/test/bfd_test_utils.h"

#include "io/test/event_manager_test.h"
#include "base/test/task_test_util.h"

using namespace BFD;
using namespace std;

using std::pair;
using std::size_t;

class Communicator : public Connection {
public:
    struct LinksKey {
        LinksKey(const boost::asio::ip::address &remote_address,
                 const boost::asio::ip::address &local_address,
                 const SessionIndex &session_index = SessionIndex()) :
                remote_address(remote_address), local_address(local_address),
                session_index(session_index) {
        }
        bool operator<(const LinksKey &other) const {
            BOOL_KEY_COMPARE(remote_address, other.remote_address);
            BOOL_KEY_COMPARE(local_address, other.local_address);
            BOOL_KEY_COMPARE(session_index, other.session_index);
            return false;
        }
        boost::asio::ip::address remote_address;
        boost::asio::ip::address local_address;
        SessionIndex             session_index;
    };

    typedef map<LinksKey, Connection *> Links;
    Communicator() { }
    virtual ~Communicator() { }
    virtual void SendPacket(
            const boost::asio::ip::udp::endpoint &local_endpoint,
            const boost::asio::ip::udp::endpoint &remote_endpoint,
            const SessionIndex &session_index,
            const boost::asio::mutable_buffer &buffer, int pktSize) {
        // Find other end-point from the links map.
        Links::const_iterator it = links_.find(
            LinksKey(remote_endpoint.address(), local_endpoint.address(),
                     session_index));
        if (it != links_.end()) {
            boost::system::error_code error;
            it->second->HandleReceive(buffer, remote_endpoint,
                local_endpoint, session_index, pktSize, error);
        }
    }
    virtual void NotifyStateChange(const SessionKey &key, const bool &up) { }
    virtual Server *GetServer() const { return server_; }
    virtual void SetServer(Server *server) { server_ = server; }
    Links *links() { return &links_; }

private:
    Server *server_;
    Links links_;
};

class ClientTest : public ::testing::Test {
 protected:
    ClientTest() :
        server_(&evm_, &cm_), client_(&cm_),
        server_test_(&evm_, &cm_test_), client_test_(&cm_test_) {
    }

    virtual void SetUp() {
        thread_.reset(new ServerThread(&evm_));
        thread_->Start();
    }

    virtual void TearDown() {
        server_.DeleteClientSessions();
        server_test_.DeleteClientSessions();
        TASK_UTIL_EXPECT_TRUE(server_.event_queue()->IsQueueEmpty());
        TASK_UTIL_EXPECT_TRUE(server_test_.event_queue()->IsQueueEmpty());
        task_util::WaitForIdle();
        server_.event_queue()->Shutdown();
        server_test_.event_queue()->Shutdown();
        evm_.Shutdown();
        thread_->Join();
    }

    void GetSessionCb(const Server *server, const SessionKey &key,
                      Session **session) const {
        *session = server->SessionByKey(key);
    }

    Session *GetSession(const Server &server, const SessionKey &key) const {
        Session *session;
        task_util::TaskFire(boost::bind(&ClientTest::GetSessionCb, this,
                                        &server, key, &session), "BFD");
        return session;
    }

    void UpCb(const Client *client, const SessionKey &key, bool *up) const {
        *up = client->Up(key);
    }

    bool Up(const Client &client, const SessionKey &key) const {
        bool up;
        task_util::TaskFire(boost::bind(&ClientTest::UpCb, this, &client, key,
                                        &up), "BFD");
        return up;
    }

    EventManager evm_;
    auto_ptr<ServerThread> thread_;
    Communicator cm_;
    Server server_;
    Client client_;

    // Test BFD end-points
    Communicator cm_test_;
    Server server_test_;
    Client client_test_;
};

TEST_F(ClientTest, BasicSingleHop1) {
    boost::asio::ip::address client_address =
        boost::asio::ip::address::from_string("10.10.10.1");
    boost::asio::ip::address client_test_address =
        boost::asio::ip::address::from_string("10.10.10.2");
    SessionKey client_key = SessionKey(client_address, SessionIndex(),
                                       kSingleHop, client_test_address);
    SessionKey client_test_key = SessionKey(client_test_address,
                                            SessionIndex(), kSingleHop,
                                            client_address);
    // Connect two bfd links
    cm_.links()->insert(make_pair(
        Communicator::LinksKey(client_address, client_test_address,
                               SessionIndex()), &cm_test_));
    cm_test_.links()->insert(
        make_pair(Communicator::LinksKey(client_test_address, client_address,
                                         SessionIndex()),&cm_));
    SessionConfig sc;
    sc.desiredMinTxInterval = boost::posix_time::milliseconds(30);
    sc.requiredMinRxInterval = boost::posix_time::milliseconds(10000);
    sc.detectionTimeMultiplier = 3;
    client_.AddSession(client_key, sc);

    SessionConfig sc_t;
    sc_t.desiredMinTxInterval = boost::posix_time::milliseconds(30);
    sc_t.requiredMinRxInterval = boost::posix_time::milliseconds(10000);
    sc_t.detectionTimeMultiplier = 3;
    client_test_.AddSession(client_test_key, sc_t);
    TASK_UTIL_EXPECT_TRUE(Up(client_, client_key));
    TASK_UTIL_EXPECT_TRUE(Up(client_test_, client_test_key));

    client_.DeleteSession(client_key);
    TASK_UTIL_EXPECT_FALSE(Up(client_, client_key));
}

// Multiple sessions with same IPs (but with different ifindex)
TEST_F(ClientTest, BasicSingleHop2) {
    boost::asio::ip::address client_address =
        boost::asio::ip::address::from_string("10.10.10.1");
    boost::asio::ip::address client_test_address =
        boost::asio::ip::address::from_string("10.10.10.2");
    SessionKey client_key = SessionKey(client_address, SessionIndex(),
                                       kSingleHop, client_test_address);
    SessionKey client_test_key = SessionKey(client_test_address,
                                            SessionIndex(), kSingleHop,
                                            client_address);
    // Connect two bfd links
    cm_.links()->insert(make_pair(
        Communicator::LinksKey(client_address, client_test_address,
                               client_key.index), &cm_test_));
    cm_test_.links()->insert(
        make_pair(Communicator::LinksKey(client_test_address, client_address,
                                         client_test_key.index), &cm_));
    SessionConfig sc;
    sc.desiredMinTxInterval = boost::posix_time::milliseconds(30);
    sc.requiredMinRxInterval = boost::posix_time::milliseconds(10000);
    sc.detectionTimeMultiplier = 3;

    client_.AddSession(client_key, sc);
    client_test_.AddSession(client_test_key, sc);
    TASK_UTIL_EXPECT_TRUE(Up(client_, client_key));
    TASK_UTIL_EXPECT_TRUE(Up(client_test_, client_test_key));

    SessionKey client_key2 = SessionKey(client_address, SessionIndex(1),
                                        kSingleHop, client_test_address);
    SessionKey client_test_key2 = SessionKey(client_test_address,
                                             SessionIndex(1), kSingleHop,
                                             client_address);
    cm_.links()->insert(make_pair(
        Communicator::LinksKey(client_address, client_test_address,
                               client_key2.index), &cm_test_));
    cm_test_.links()->insert(
        make_pair(Communicator::LinksKey(client_test_address, client_address,
                                         client_test_key2.index), &cm_));

    client_.AddSession(client_key2, sc);
    client_test_.AddSession(client_test_key2, sc);

    TASK_UTIL_EXPECT_NE(static_cast<Session *>(NULL),
                        GetSession(server_, client_key));
    TASK_UTIL_EXPECT_NE(GetSession(server_, client_key),
                        GetSession(server_, client_key2));
    TASK_UTIL_EXPECT_NE(static_cast<Session *>(NULL),
              GetSession(server_test_, client_test_key));
    TASK_UTIL_EXPECT_NE(static_cast<Session *>(NULL),
              GetSession(server_test_, client_test_key2));

    TASK_UTIL_EXPECT_NE(GetSession(server_, client_key),
              GetSession(server_, client_key2));
    TASK_UTIL_EXPECT_NE(GetSession(server_test_, client_test_key),
              GetSession(server_test_, client_test_key2));

    TASK_UTIL_EXPECT_TRUE(Up(client_, client_key2));
    TASK_UTIL_EXPECT_TRUE(Up(client_test_, client_test_key2));

    client_.DeleteSession(client_key);
    TASK_UTIL_EXPECT_FALSE(Up(client_, client_key));

    client_.DeleteSession(client_key2);
    TASK_UTIL_EXPECT_FALSE(Up(client_, client_key2));
}

// Multiple sessions with same same ifindex connected to different IPs
TEST_F(ClientTest, BasicSingleHop3) {
    boost::asio::ip::address client_address =
        boost::asio::ip::address::from_string("10.10.10.66");
    boost::asio::ip::address client_test_address1 =
        boost::asio::ip::address::from_string("10.10.10.1");
    boost::asio::ip::address client_test_address2 =
        boost::asio::ip::address::from_string("10.10.10.2");

    SessionKey client_key1 = SessionKey(client_address, SessionIndex(2),
                                        kSingleHop, client_test_address1);
    SessionKey client_key2 = SessionKey(client_address, SessionIndex(2),
                                        kSingleHop, client_test_address2);

    SessionKey client_test_key1 = SessionKey(client_test_address1,
                                             SessionIndex(2), kSingleHop,
                                             client_address);
    SessionKey client_test_key2 = SessionKey(client_test_address2,
                                             SessionIndex(2), kSingleHop,
                                             client_address);

    // Connect two bfd links
    cm_.links()->insert(make_pair(
        Communicator::LinksKey(client_address, client_test_address1,
                               client_key1.index), &cm_test_));
    cm_test_.links()->insert(
        make_pair(Communicator::LinksKey(client_test_address1, client_address,
                                         client_test_key1.index), &cm_));

    SessionConfig sc;
    sc.desiredMinTxInterval = boost::posix_time::milliseconds(30);
    sc.requiredMinRxInterval = boost::posix_time::milliseconds(10000);
    sc.detectionTimeMultiplier = 3;

    client_.AddSession(client_key1, sc);
    client_test_.AddSession(client_test_key1, sc);
    TASK_UTIL_EXPECT_TRUE(Up(client_, client_key1));
    TASK_UTIL_EXPECT_TRUE(Up(client_test_, client_test_key1));

    // Connect two bfd links
    cm_.links()->insert(make_pair(
        Communicator::LinksKey(client_address, client_test_address2,
                               client_key2.index), &cm_test_));
    cm_test_.links()->insert(
        make_pair(Communicator::LinksKey(client_test_address2, client_address,
                                         client_test_key2.index), &cm_));

    client_.AddSession(client_key2, sc);
    client_test_.AddSession(client_test_key2, sc);
    TASK_UTIL_EXPECT_TRUE(Up(client_, client_key2));
    TASK_UTIL_EXPECT_TRUE(Up(client_test_, client_test_key2));

    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_NE(static_cast<Session *>(NULL),
                        GetSession(server_, client_key1));
    TASK_UTIL_EXPECT_NE(static_cast<Session *>(NULL),
                        GetSession(server_, client_key2));
    TASK_UTIL_EXPECT_NE(GetSession(server_, client_key1),
                        GetSession(server_, client_key2));

    TASK_UTIL_EXPECT_NE(static_cast<Session *>(NULL),
              GetSession(server_test_, client_test_key1));
    TASK_UTIL_EXPECT_NE(static_cast<Session *>(NULL),
              GetSession(server_test_, client_test_key2));
    TASK_UTIL_EXPECT_NE(GetSession(server_test_, client_test_key1),
                        GetSession(server_test_, client_test_key2));

    task_util::WaitForIdle();
    // Check state of all sessions
    Server *server = client_.GetConnection()->GetServer();
    Sessions *client_sessions = server->GetSessions();
    TASK_UTIL_EXPECT_EQ(client_sessions->size(),2);
    stringstream ss;
    for (Sessions::iterator it = client_sessions->begin(), next ;
         it != client_sessions->end(); it = next) {
        SessionKey key = *it;
        next = ++it;
        Session *session =  server->SessionByKey(key);
        TASK_UTIL_EXPECT_GE(session->Stats().rx_count, 2);
        TASK_UTIL_EXPECT_GE(session->Stats().tx_count, 2);
        ss.str("");
        ss << session->local_state();
        TASK_UTIL_EXPECT_EQ(kUp, BFDStateFromString(ss.str().c_str()));
    }

    task_util::WaitForIdle();
    Server *server_test = client_test_.GetConnection()->GetServer();
    Sessions *client_test_sessions = server_test->GetSessions();
    TASK_UTIL_EXPECT_EQ(client_test_sessions->size(),2);
    stringstream ss2;
    for (Sessions::iterator it = client_test_sessions->begin(), next ;
         it != client_test_sessions->end(); it = next) {
        SessionKey key = *it;
        next = ++it;
        Session *session =  server_test->SessionByKey(key);
        TASK_UTIL_EXPECT_GE(session->Stats().rx_count, 2);
        TASK_UTIL_EXPECT_GE(session->Stats().tx_count, 2);

        ss2.str("");
        ss2 << session->local_state();
        TASK_UTIL_EXPECT_EQ(kUp, BFDStateFromString(ss2.str().c_str()));
    }

    client_.DeleteSession(client_key1);
    TASK_UTIL_EXPECT_FALSE(Up(client_, client_key1));

    client_.DeleteSession(client_key2);
    TASK_UTIL_EXPECT_FALSE(Up(client_, client_key2));

    client_test_.DeleteSession(client_test_key1);
    TASK_UTIL_EXPECT_FALSE(Up(client_test_, client_test_key1));

    client_test_.DeleteSession(client_test_key2);
    TASK_UTIL_EXPECT_FALSE(Up(client_test_, client_test_key2));

    task_util::WaitForIdle();
    TASK_UTIL_EXPECT_EQ(client_sessions->size(),0);
    TASK_UTIL_EXPECT_EQ(client_test_sessions->size(),0);
}

TEST_F(ClientTest, BasicMultiHop1) {
    boost::asio::ip::address client_address =
        boost::asio::ip::address::from_string("10.10.10.1");
    boost::asio::ip::address client_test_address =
        boost::asio::ip::address::from_string("20.10.10.2");
    SessionKey client_key = SessionKey(client_address, SessionIndex(),
                                       kMultiHop, client_test_address);
    SessionKey client_test_key = SessionKey(client_test_address,
                                            SessionIndex(), kMultiHop,
                                            client_address);
    // Connect two bfd links
    cm_.links()->insert(make_pair(
        Communicator::LinksKey(client_address, client_test_address,
                               SessionIndex()), &cm_test_));
    cm_test_.links()->insert(
        make_pair(Communicator::LinksKey(client_test_address, client_address,
                                         SessionIndex()), &cm_));
    SessionConfig sc;
    sc.desiredMinTxInterval = boost::posix_time::milliseconds(30);
    sc.requiredMinRxInterval = boost::posix_time::milliseconds(10000);
    sc.detectionTimeMultiplier = 3;
    client_.AddSession(client_key, sc);

    SessionConfig sc_t;
    sc_t.desiredMinTxInterval = boost::posix_time::milliseconds(30);
    sc_t.requiredMinRxInterval = boost::posix_time::milliseconds(10000);
    sc_t.detectionTimeMultiplier = 3;
    client_test_.AddSession(client_test_key, sc_t);
    TASK_UTIL_EXPECT_TRUE(client_.Up(client_key));
    TASK_UTIL_EXPECT_TRUE(client_test_.Up(client_test_key));

    client_.DeleteSession(client_key);
    TASK_UTIL_EXPECT_FALSE(Up(client_, client_key));
}

// Multihop sessions with same IPs (but with different vrf index)
TEST_F(ClientTest, BasicMultipleHop2) {
    boost::asio::ip::address client_address =
        boost::asio::ip::address::from_string("10.10.10.1");
    boost::asio::ip::address client_test_address =
        boost::asio::ip::address::from_string("20.10.10.2");
    SessionKey client_key = SessionKey(client_address, SessionIndex(),
                                       kMultiHop, client_test_address);
    SessionKey client_test_key = SessionKey(client_test_address,
                                            SessionIndex(), kMultiHop,
                                            client_address);
    // Connect two bfd links
    cm_.links()->insert(make_pair(
        Communicator::LinksKey(client_address, client_test_address,
                               client_key.index), &cm_test_));
    cm_test_.links()->insert(
        make_pair(Communicator::LinksKey(client_test_address, client_address,
                                         client_test_key.index), &cm_));
    SessionConfig sc;
    sc.desiredMinTxInterval = boost::posix_time::milliseconds(30);
    sc.requiredMinRxInterval = boost::posix_time::milliseconds(10000);
    sc.detectionTimeMultiplier = 3;

    client_.AddSession(client_key, sc);
    client_test_.AddSession(client_test_key, sc);
    TASK_UTIL_EXPECT_TRUE(Up(client_, client_key));
    TASK_UTIL_EXPECT_TRUE(Up(client_test_, client_test_key));

    SessionKey client_key2 = SessionKey(client_address, SessionIndex(0, 2),
                                       kMultiHop, client_test_address);
    SessionKey client_test_key2 = SessionKey(client_test_address,
                                            SessionIndex(0, 2), kMultiHop,
                                            client_address);
    cm_.links()->insert(make_pair(
        Communicator::LinksKey(client_address, client_test_address,
                               client_key2.index), &cm_test_));
    cm_test_.links()->insert(
        make_pair(Communicator::LinksKey(client_test_address, client_address,
                                         client_test_key2.index), &cm_));

    client_.AddSession(client_key2, sc);
    client_test_.AddSession(client_test_key2, sc);

    TASK_UTIL_EXPECT_NE(static_cast<Session *>(NULL),
                        GetSession(server_, client_key));
    TASK_UTIL_EXPECT_NE(GetSession(server_, client_key),
                        GetSession(server_, client_key2));
    TASK_UTIL_EXPECT_NE(static_cast<Session *>(NULL),
              GetSession(server_test_, client_test_key));
    TASK_UTIL_EXPECT_NE(static_cast<Session *>(NULL),
              GetSession(server_test_, client_test_key2));

    TASK_UTIL_EXPECT_NE(GetSession(server_, client_key),
              GetSession(server_, client_key2));
    TASK_UTIL_EXPECT_NE(GetSession(server_test_, client_test_key),
              GetSession(server_test_, client_test_key2));
    TASK_UTIL_EXPECT_TRUE(Up(client_, client_key2));
    TASK_UTIL_EXPECT_TRUE(Up(client_test_, client_test_key2));

    client_.DeleteSession(client_key);
    TASK_UTIL_EXPECT_FALSE(Up(client_, client_key));

    client_.DeleteSession(client_key2);
    TASK_UTIL_EXPECT_FALSE(Up(client_, client_key2));
}

TEST_F(ClientTest, BasicSingleHop_CfgChange_MinRxInterval) {
    boost::asio::ip::address client_address =
        boost::asio::ip::address::from_string("10.10.10.1");
    boost::asio::ip::address client_test_address =
        boost::asio::ip::address::from_string("10.10.10.2");
    SessionKey client_key = SessionKey(client_address, SessionIndex(),
                                       kSingleHop, client_test_address);
    SessionKey client_test_key = SessionKey(client_test_address,
                                            SessionIndex(), kSingleHop,
                                            client_address);
    // Connect two bfd links
    cm_.links()->insert(make_pair(
        Communicator::LinksKey(client_address, client_test_address,
                               SessionIndex()), &cm_test_));
    cm_test_.links()->insert(
        make_pair(Communicator::LinksKey(client_test_address, client_address,
                                         SessionIndex()),&cm_));
    SessionConfig sc;
    sc.desiredMinTxInterval = boost::posix_time::milliseconds(1000);
    sc.requiredMinRxInterval = boost::posix_time::milliseconds(1000);
    sc.detectionTimeMultiplier = 3;
    client_.AddSession(client_key, sc);

    SessionConfig sc_t;
    sc_t.desiredMinTxInterval = boost::posix_time::milliseconds(1000);
    sc_t.requiredMinRxInterval = boost::posix_time::milliseconds(1000);
    sc_t.detectionTimeMultiplier = 3;
    client_test_.AddSession(client_test_key, sc_t);
    TASK_UTIL_EXPECT_TRUE(Up(client_, client_key));
    TASK_UTIL_EXPECT_TRUE(Up(client_test_, client_test_key));

    task_util::WaitForIdle();
    Server *server = client_.GetConnection()->GetServer();
    Sessions *client_sessions = server->GetSessions();
    TASK_UTIL_EXPECT_EQ(client_sessions->size(),1);
    stringstream ss;
    Session *session =  server->SessionByKey(client_key);
    TASK_UTIL_EXPECT_GE(session->Stats().rx_count, 2);
    TASK_UTIL_EXPECT_GE(session->Stats().tx_count, 2);
    ss << session->local_state();
    TASK_UTIL_EXPECT_EQ(kUp, BFDStateFromString(ss.str().c_str()));

    task_util::WaitForIdle();
    Server *server_test = client_test_.GetConnection()->GetServer();
    Sessions *client_test_sessions = server_test->GetSessions();
    TASK_UTIL_EXPECT_EQ(client_test_sessions->size(),1);
    stringstream ss2;
    Session *session_test =  server_test->SessionByKey(client_test_key);
    TASK_UTIL_EXPECT_GE(session_test->Stats().rx_count, 2);
    TASK_UTIL_EXPECT_GE(session_test->Stats().tx_count, 2);
    ss2 << session_test->local_state();
    TASK_UTIL_EXPECT_EQ(kUp, BFDStateFromString(ss2.str().c_str()));

    // Config update bfd.RequiredMinRxInterval
    SessionConfig sc_updt;
    sc_updt.desiredMinTxInterval = boost::posix_time::milliseconds(1000);
    sc_updt.requiredMinRxInterval = boost::posix_time::milliseconds(500);
    sc_updt.detectionTimeMultiplier = 3;
    client_.AddSession(client_key, sc_updt);
    TASK_UTIL_EXPECT_TRUE(Up(client_, client_key));
    TASK_UTIL_EXPECT_TRUE(Up(client_test_, client_test_key));

    TASK_UTIL_EXPECT_EQ(client_sessions->size(),1);
    TASK_UTIL_EXPECT_EQ(client_test_sessions->size(),1);

    TASK_UTIL_EXPECT_GE(session_test->Stats().rx_count, 4);
    TASK_UTIL_EXPECT_EQ(sc_updt.requiredMinRxInterval,
                        session_test->remote_state().minRxInterval);
    TASK_UTIL_EXPECT_GE(session_test->Stats().rx_count*2 ,
                        session->Stats().rx_count);

    client_.DeleteSession(client_key);
    TASK_UTIL_EXPECT_FALSE(Up(client_, client_key));

    client_.DeleteSession(client_test_key);
    TASK_UTIL_EXPECT_FALSE(Up(client_, client_test_key));
}

TEST_F(ClientTest, BasicSingleHop_CfgChange_DesiredMinTxInterval) {
    boost::asio::ip::address client_address =
        boost::asio::ip::address::from_string("10.10.10.1");
    boost::asio::ip::address client_test_address =
        boost::asio::ip::address::from_string("10.10.10.2");
    SessionKey client_key = SessionKey(client_address, SessionIndex(),
                                       kSingleHop, client_test_address);
    SessionKey client_test_key = SessionKey(client_test_address,
                                            SessionIndex(), kSingleHop,
                                            client_address);
    // Connect two bfd links
    cm_.links()->insert(make_pair(
        Communicator::LinksKey(client_address, client_test_address,
                               SessionIndex()), &cm_test_));
    cm_test_.links()->insert(
        make_pair(Communicator::LinksKey(client_test_address, client_address,
                                         SessionIndex()),&cm_));
    SessionConfig sc;
    sc.desiredMinTxInterval = boost::posix_time::milliseconds(1000);
    sc.requiredMinRxInterval = boost::posix_time::milliseconds(1000);
    sc.detectionTimeMultiplier = 3;
    client_.AddSession(client_key, sc);

    SessionConfig sc_t;
    sc_t.desiredMinTxInterval = boost::posix_time::milliseconds(1000);
    sc_t.requiredMinRxInterval = boost::posix_time::milliseconds(1000);
    sc_t.detectionTimeMultiplier = 3;
    client_test_.AddSession(client_test_key, sc_t);
    TASK_UTIL_EXPECT_TRUE(Up(client_, client_key));
    TASK_UTIL_EXPECT_TRUE(Up(client_test_, client_test_key));

    task_util::WaitForIdle();
    Server *server = client_.GetConnection()->GetServer();
    Sessions *client_sessions = server->GetSessions();
    TASK_UTIL_EXPECT_EQ(client_sessions->size(),1);
    stringstream ss;
    Session *session =  server->SessionByKey(client_key);
    TASK_UTIL_EXPECT_GE(session->Stats().rx_count, 2);
    TASK_UTIL_EXPECT_GE(session->Stats().tx_count, 2);
    ss << session->local_state();
    TASK_UTIL_EXPECT_EQ(kUp, BFDStateFromString(ss.str().c_str()));

    task_util::WaitForIdle();
    Server *server_test = client_test_.GetConnection()->GetServer();
    Sessions *client_test_sessions = server_test->GetSessions();
    TASK_UTIL_EXPECT_EQ(client_test_sessions->size(),1);
    stringstream ss2;
    Session *session_test =  server_test->SessionByKey(client_test_key);
    TASK_UTIL_EXPECT_GE(session_test->Stats().rx_count, 2);
    TASK_UTIL_EXPECT_GE(session_test->Stats().tx_count, 2);
    ss2 << session->local_state();
    TASK_UTIL_EXPECT_EQ(kUp, BFDStateFromString(ss2.str().c_str()));

    // Config update bfd.DesiredMinTxInterval
    SessionConfig sc_updt;
    sc_updt.desiredMinTxInterval = boost::posix_time::milliseconds(2000);
    sc_updt.requiredMinRxInterval = boost::posix_time::milliseconds(1000);
    sc_updt.detectionTimeMultiplier = 3;
    client_.AddSession(client_key, sc_updt);
    TASK_UTIL_EXPECT_TRUE(Up(client_, client_key));
    TASK_UTIL_EXPECT_TRUE(Up(client_test_, client_test_key));

    TASK_UTIL_EXPECT_EQ(client_sessions->size(),1);
    TASK_UTIL_EXPECT_EQ(client_test_sessions->size(),1);

    TASK_UTIL_EXPECT_GE(session_test->Stats().rx_count, 4);
    TASK_UTIL_EXPECT_EQ(sc_updt.desiredMinTxInterval, session_test->remote_state().minTxInterval);
    TASK_UTIL_EXPECT_GE(session->Stats().rx_count*2, session_test->Stats().rx_count);

    client_.DeleteSession(client_key);
    TASK_UTIL_EXPECT_FALSE(Up(client_, client_key));

    client_.DeleteSession(client_test_key);
    TASK_UTIL_EXPECT_FALSE(Up(client_, client_test_key));
}

int main(int argc, char **argv) {
    LoggingInit();
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


text:
<?php namespace Codesleeve\AssetPipeline\Composers;

class StylesheetComposer extends BaseComposer implements ComposerInterface
{
    /**
     * Process the paths that come through the asset pipeline
     *
     * @param  array $paths
     * @param  array $absolutePaths
     * @param  array $attributes
     * @return void
     */
    public function process($paths, $absolutePaths, $attributes)
    {
        $url = url();
        $attributesAsText = $this->attributesArrayToText($attributes);

        foreach ($paths as $path)
        {
            print "<link href=\"{$url}{$path}\" {$attributesAsText} rel=\"stylesheet\" type=\"text/css\">" . PHP_EOL;
        }
    }
}


text:
module.exports = function(RED) {
    function changeSign(config) {
        RED.nodes.createNode(this, config);
        var node = this;

        this.on('input', function(msg) {
            if (!isNaN(msg.payload)) {
                msg.payload *= -1;
                node.send(msg);
            }
        });

        //clean up when re-deploying
        this.on('close', function() {
        });
    }

    RED.nodes.registerType("change-sign", changeSign);
}


text:
FROM centos:centos7
RUN yum -y clean all
RUN yum -y update

RUN yum -y install epel-release
RUN yum -y install gcc gcc-c++ python-devel
RUN yum -y install python-matplotlib numpy scipy

ADD calculate_phist.py /calculate_phist.py
ADD single_pop.py /single_pop.py

ENTRYPOINT ["python", "/single_pop.py"]


text:
'use strict';

require('./_user.scss');

module.exports = {
  template: require('./user.html'),
  controller: ['$log', 'profileService', 'authService', UserController],
  controllerAs: 'userCtrl',
  bindings: {
    user: '<'
  }
};

function UserController($log, profileService, authService) {
  $log.debug('userCtrl()');

  this.changeEdit = {
    showEditProfile: false
  };

  this.user = null;

  this.fetchUserData = function() {
    profileService.fetchUserData()
    .then( user => {
      $log.log('user data retrieved');
      this.user = user;
    });
  };

  this.fetchUserData();
}


text:
from great_expectations.expectations.set_based_column_map_expectation import (
    SetBasedColumnMapExpectation,
)

class ExpectColumnValuesToBeValidHTTPMethods(SetBasedColumnMapExpectation):
    """Ensures all values are a valid http method:
    GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH
    """

    # These values will be used to configure the metric created by your expectation
    set_ = [
        "GET",
        "HEAD",
        "POST",
        "PUT",
        "DELETE",
        "CONNECT",
        "OPTIONS",
        "TRACE",
        "PATCH",
    ]

    set_camel_name = "HTTPMethods"
    set_semantic_name = None

    examples = [
        {
            "data": {
                "uppercase_http_methods": [
                    "GET",
                    "HEAD",
                    "POST",
                    "PUT",
                    "DELETE",
                    "CONNECT",
                    "OPTIONS",
                    "TRACE",
                    "PATCH",
                ],
                "bad_stuff": [
                    "GET",
                    "foo",
                    "POST",
                    "bar",
                    "GET",
                    "GET",
                    "GET",
                    "PUT",
                    "baz",
                ],
            },
            "tests": [
                {
                    "title": "positive_test_lowercase",
                    "exact_match_out": False,
                    "in": {"column": "uppercase_http_methods"},
                    "out": {
                        "success": True,
                    },
                    "include_in_gallery": True,
                },
                {
                    "title": "negative_test",
                    "exact_match_out": False,
                    "in": {"column": "bad_stuff"},
                    "out": {"success": False, "unexpected_index_list": [1, 3, 8]},
                    "include_in_gallery": True,
                },
            ],
            "test_backends": [
                {
                    "backend": "pandas",
                    "dialects": None,
                }
            ],
        }
    ]

    map_metric = SetBasedColumnMapExpectation.register_metric(
        set_camel_name=set_camel_name,
        set_=set_,
    )

    library_metadata = {
        "tags": ["type-entities", "hackathon", "set-based"],
        "contributors": [
            "@zachlindsey",
        ],
    }

if __name__ == "__main__":
    ExpectColumnValuesToBeValidHTTPMethods().print_diagnostic_checklist()


text:
package org.olat.test.functional.group.management;

import org.olat.test.util.selenium.BaseSeleneseTestCase;
import org.olat.test.util.selenium.olatapi.OLATWorkflowHelper;
import org.olat.test.util.selenium.olatapi.course.editor.CourseEditor;
import org.olat.test.util.selenium.olatapi.course.editor.EnrolmentEditor;
import org.olat.test.util.selenium.olatapi.course.run.CourseRun;
import org.olat.test.util.selenium.olatapi.course.run.EnrolmentRun;
import org.olat.test.util.selenium.olatapi.group.GroupAdmin;
import org.olat.test.util.selenium.olatapi.group.GroupManagement;
import org.olat.test.util.selenium.olatapi.lr.LRDetailedView;
import org.olat.test.util.selenium.olatapi.lr.LearningResources;
import org.olat.test.util.selenium.olatapi.lr.LearningResources.LR_Types;
import org.olat.test.util.setup.OlatLoginInfos;
import org.olat.test.util.setup.SetupType;
import org.olat.test.util.setup.context.Context;

/**
 *
 * Test Jira Issue OLAT-5022:

 * define a learning group with a place limitation (assert that the place limitation is saved), waiting list and automatic adding. Add users until the group is full,
 * remove one user, assert that the first on the waiting list is included in the group

 *
 Test case:

 * create groupWithLimitation

 * define a learning group with a place limitation

 * open course editor

 * insert enrolment element

 * publish and close

 * author enrolls in groupWithLimitation

 * assert -> author is enrolled!

 * student tries to enroll in groupWithLimitation that is already full!

 * student opens course and navigates to enrollment course element

 * assert -> student is on waiting list!

 * author cancels enrollment

 * assert author enrollment was canceled

 * assert -> student is now enrolled!

 * Delete groups

 * Test the same adding several groups separated with a comma at one time

 * Delete course

 *
 * @author alberto
 */
public class EnrollmentWithSizeLimitationTest extends BaseSeleneseTestCase {
    private final String COURSE_NAME = "CourseName" + System.currentTimeMillis();
    private final String COURSE_DESCRIPTION = "CourseDescription" + System.currentTimeMillis();

    public void testEnrolmentWaitingList() throws Exception {
        Context context = Context.setupContext(getFullName(), SetupType.TWO_NODE_CLUSTER);

        String standardPassword = context.getStandardStudentOlatLoginInfos(1).getPassword();

        OLATWorkflowHelper olatWorkflow_0 = context.getOLATWorkflowHelper(context.getStandardAuthorOlatLoginInfos(1));

        // author creates course with learning group (max 1 participant) and enrollment course element

        LearningResources learningResources_0 = olatWorkflow_0.getLearningResources();
        LRDetailedView lRDetailedView_0 = learningResources_0.createResource(COURSE_NAME, "Enrolment Test", LR_Types.COURSE);
        CourseRun courseRun_0 = learningResources_0.searchAndShowMyCourseContent(COURSE_NAME);

        // create groupWithLimitation
        GroupManagement groupManagement_0 = courseRun_0.getGroupManagement();
        GroupAdmin groupAdmin = groupManagement_0.createLearningGroup("groupWithLimitation", "group description", 1, true, true);
        // assert that the place limitation is saved
        assertTrue(groupAdmin.getMaxNumParticipants().equals("1"));
        ;
        courseRun_0 = groupManagement_0.close();

        // open course editor
        CourseEditor courseEditor_0 = courseRun_0.getCourseEditor();

        // insert enrollment element
        EnrolmentEditor enrollmentElement_0 = (EnrolmentEditor) courseEditor_0.insertCourseElement(CourseEditor.CourseElemTypes.ENROLMENT, true, null);
        enrollmentElement_0.selectLearningGroups("groupWithLimitation");

        // publish and close
        courseEditor_0.publishCourse();
        courseEditor_0.closeToCourseRun();
        olatWorkflow_0.logout();

        // author enrolls in groupWithLimitation
        courseRun_0 = this.selectEnrolment(context.getStandardAuthorOlatLoginInfos(1), COURSE_NAME);
		EnrolmentRun enrolmentRun_0 =  courseRun_0.selectEnrolment("Enrollment");
        enrolmentRun_0.enrol("groupWithLimitation");

        // assert -> author is enrolled!
        // assertTrue(courseRun_0.isTextPresent("enrolled"));

        assertTrue(enrolmentRun_0.alreadyEnrolled("groupWithLimitation"));

        // student opens course and navigates to enrollment course element
        CourseRun courseRun_1 = this.selectEnrolment(context.getStandardStudentOlatLoginInfos(1), COURSE_NAME);
		EnrolmentRun enrolmentRun_1 = courseRun_1.selectEnrolment("Enrollment");

        // student tries to enroll in groupWithLimitation that is already full!
        enrolmentRun_1.enrol("groupWithLimitation");

        // assert -> student is on waiting list!
        assertTrue(enrolmentRun_1.isTextPresent("On waiting list (1)"));

        // author cancels enrollment
        enrolmentRun_0.cancelEnrolment("groupWithLimitation");

        // assert author enrollment was canceled
        assertTrue(courseRun_0.isTextPresent("Choose one of the learning groups below to enrol"));

        // assert -> student is now enrolled!
		enrolmentRun_1 = courseRun_1.selectEnrolment("Enrollment");
        assertTrue(enrolmentRun_1.alreadyEnrolled("groupWithLimitation"));

	}
    private CourseRun selectEnrolment(OlatLoginInfos student, String courseName) {
        Context context = Context.getContext();
        OLATWorkflowHelper olatWorkflow = context.getOLATWorkflowHelper(student);
        CourseRun courseRun = olatWorkflow.getLearningResources().searchAndShowCourseContent(courseName);
		courseRun.selectCourseElement("Enrollment");
        return courseRun;
    }

    @Override
    protected void cleanUpAfterRun() {
        System.out.println("***************** cleanUpAfterRun STARTED *********************");
        // author01 deletes course
        Context context = Context.getContext();
        OLATWorkflowHelper olatWorkflow = context.getOLATWorkflowHelper(context.getStandardAuthorOlatLoginInfos(1));
        LRDetailedView lRDetailedView = olatWorkflow.getLearningResources().searchMyResource(COURSE_NAME);
        try {
            lRDetailedView.deleteLR();
		} catch (Exception e) {}
        System.out.println("***************** cleanUpAfterRun ENDED *********************");
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions id="definitions"
    xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:activiti="http://activiti.org/bpmn"
    targetNamespace="Examples">

    <signal id="theSignal" name="The Signal" />

    <process id="processWithSignalStart1">
        <startEvent id="theStart">
          <signalEventDefinition id="theSignalEventDefinition" signalRef="theSignal" />
        </startEvent>
        <sequenceFlow id="flow1" sourceRef="theStart" targetRef="theTask" />
        <userTask id="theTask" name="Task in process A" />
        <sequenceFlow id="flow2" sourceRef="theTask" targetRef="theEnd" />
        <endEvent id="theEnd" />
    </process>

</definitions>


text:
package io.truthencode.ddo.model.enhancement.enhancements

trait ParentClassEnhancement {
  val subEnhancements: Seq[ClassEnhancement with SubEnhancement]
}


text:
<?php include "includes/header.php";    ?>
<?php
         $id = $_GET['id'];

          //Create Database object
          $db = new Database();

		  //Create Query
		  $query = "SELECT * FROM posts WHERE id =" .$id;
		  //Run Query
		  $post = $db->select($query)->fetch_assoc();

		    //Create Query
		  $query = "SELECT * FROM categories";
		  //Run Query
		  $categories = $db->select($query);
  ?>

  <?php

   if(isset($_POST['submit']))  {

	  $title= mysqli_real_escape_string($db->link, $_POST['title']);
	   $body= mysqli_real_escape_string($db->link, $_POST['body']);
	   $category= mysqli_real_escape_string($db->link, $_POST['category']);
	   $author= mysqli_real_escape_string($db->link, $_POST['author']);
	   $tags= mysqli_real_escape_string($db->link, $_POST['tags']);

	   //Basic Validation

	   if ($title=='' || $body=='' || $category=='' || $author=='') {

		//Set error message
		$error= 'Please fill out all required fields';

	   } else {
	   	   $query = "UPDATE posts
	   	                  SET  title = '$title',
	   	                   body = '$body',
	   	                   category ='$category',
	   	                   author = '$author',
	   	                   tags = '$tags'
	   	                   WHERE id = "  .$id;

		   $update_row = $db->update($query);
	   }

   }

 ?>

 <?php

   if(isset($_POST['delete']))  {

	   $query = "DELETE FROM posts WHERE id = ".$id;
	   $delete_row = $db->delete($query);

   }?>

  <form role="form" method="post" action="edit_post.php?id= <?php echo  $id;?>">

      Post Title
      <input name="title" type="text" class="form-control"  placeholder="Enter Title" value="<?php echo $post['title'] ?>">

      Post Body
      <textarea name="body" class="form-control"  placeholder="Enter Post" ><?php echo $post['body'] ?></textarea>

      Category
      <select name="category" class="form-control" >

      	<?php  while($row = $categories->fetch_assoc())  :  ?>
      		<?php  if($row['id'] == $post['category']) {
      			 $selected = 'selected';
      		}       else { $selected = '';   	         }

      		?>
      	    <option value="<?php echo  $row['id']; ?>"<?php echo $selected;?> ><?php  echo $row['name']; ?></option>
      	<?php  endwhile; ?>
      </select>

      Author
      <input name="author" type="text" class="form-control"  placeholder="Enter Name" value="<?php echo $post['author'] ?>">

      Tags
      <input name="tags" type="text" class="form-control"  placeholder="Enter Tags" value="<?php echo $post['tags'] ?>">

    <input name="submit"  type="submit" class="btn btn-default" value="Submit">
    Cancel
    <input name="delete"  type="submit" class="btn btn-danger" value="Delete">

  </form>

<?php include "includes/footer.php";    ?>


text:
--
-- Version: Each entry records an act of worship. For example, attending mass.  Supports Azure SQL Server.
-- URL: http://ostlog.org/schema/Worship_log.json
--
CREATE TABLE [dbo].[Worship log]
(
	[id] INT IDENTITY (1,1) NOT NULL,
	[meta_id] INT NULL,
	[calendar_date_id] INT DEFAULT CONVERT (char(8), GETDATE(), 112) NOT NULL,
	[timestamp] TIME(0) NOT NULL,
	[location_id] INT NULL,
	[domain] NVARCHAR (15) DEFAULT 'spiritual' NOT NULL,
	[person_id] INT NOT NULL,
	[remarks] NVARCHAR (4000) NULL,
	CONSTRAINT [PK_Worship log] PRIMARY KEY CLUSTERED ([id] ASC),
	CONSTRAINT [FK_Worship log-Calendar_date] FOREIGN KEY ([calendar_date_id]) REFERENCES [dbo].[Calendar dates] ([date_id]),
	CONSTRAINT [FK_Worship log-People] FOREIGN KEY ([person_id]) REFERENCES [dbo].[People] ([id]),
	CONSTRAINT [FK_Worship log-Meta log] FOREIGN KEY ([meta_id]) REFERENCES [dbo].[Meta log] ([id]),
	CONSTRAINT [FK_Worship log-Location] FOREIGN KEY ([location_id]) REFERENCES [dbo].[Location] ([location_id]),

	CHECK ([domain] = 'spiritual' OR [domain] = 'social' OR [domain] = 'physical' OR [domain] = 'intellectual' OR [domain] = 'financial' OR [domain] = 'emotional' OR [domain] = 'environmental')
)


text:
package org.hbird.osgi.xtceosgi;

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.net.URL;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;

import org.hbird.core.spacesystemmodel.SpaceSystemModelUpdateListener;
import org.hbird.core.xtce.XtceSpaceSystemModelFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class XtceManagedConfigUpdaterTest {

	private XtceManagedConfigUpdater updater;

	@Mock
	private XtceSpaceSystemModelFactory mockFactory;

	@Mock
	private SpaceSystemModelUpdateListener mockListener;

	private List<SpaceSystemModelUpdateListener> mockUpdateListeners;

	private final static String TEST_NAME = "SpaceshipAce";

	@SuppressWarnings("rawtypes")
	// OSGi supports 1.4 and therefore passes untyped classes instead of generics.
	private final Dictionary config = new Hashtable(1);

	private static final String SPACE_SYSTEM_MODLE_FILENAME_FIELD = "spaceSystemModelFilename";

	private String fullFilePath;

	@Before
	public final void setupTestFilePath() {
		URL testFileUri = getClass().getResource(TEST_NAME);
		fullFilePath = testFileUri.getPath();
	}

	@Before
	public void setup() {
		updater = new XtceManagedConfigUpdater();

		updater.setFactory(mockFactory);

		mockUpdateListeners = new ArrayList<SpaceSystemModelUpdateListener>(1);
		mockUpdateListeners.add(mockListener);
		updater.setModelUpdateListeners(mockUpdateListeners);
	}

	// OSGi supports 1.4 and therefore passes untyped classes instead of generics.
	@SuppressWarnings("unchecked")
	@Test
	public void testUpdated() {
		config.put(SPACE_SYSTEM_MODLE_FILENAME_FIELD, fullFilePath);

		updater.updated(config);

		verify(mockFactory, times(1)).setSpaceSystemModelFilename(fullFilePath);
		verify(mockListener, times(1)).modelChanged();
	}

}


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

namespace Elasticsearch.Net
{
	public class StaticConnectionPool : IConnectionPool
	{
		protected IDateTimeProvider DateTimeProvider { get; }
		protected Random Random { get; } = new Random();
		protected bool Randomize { get; }

		protected List<Node> InternalNodes { get; set; }

		public virtual IReadOnlyCollection<Node> Nodes => this.InternalNodes;

		public int MaxRetries => this.InternalNodes.Count - 1;

		public virtual bool SupportsReseeding => false;
		public virtual bool SupportsPinging => true;

		public virtual void Reseed(IEnumerable<Node> nodes) { } //ignored

		public bool UsingSsl { get; }

		public bool SniffedOnStartup { get; set; }

		public DateTime LastUpdate { get; protected set; }

		public StaticConnectionPool(IEnumerable<Uri> uris, bool randomize = true, IDateTimeProvider dateTimeProvider = null)
			: this(uris.Select(uri => new Node(uri)), randomize, dateTimeProvider)
		{ }

		public StaticConnectionPool(IEnumerable<Node> nodes, bool randomize = true, IDateTimeProvider dateTimeProvider = null)
		{
			nodes.ThrowIfEmpty(nameof(nodes));

			this.Randomize = randomize;
			this.DateTimeProvider = dateTimeProvider ?? Elasticsearch.Net.DateTimeProvider.Default;

			var nn = nodes.ToList();
			var uris = nn.Select(n => n.Uri).ToList();
			if (uris.Select(u => u.Scheme).Distinct().Count() > 1)
				throw new ArgumentException("Trying to instantiate a connection pool with mixed URI Schemes");

			this.UsingSsl = uris.Any(uri => uri.Scheme == Uri.UriSchemeHttps);

			this.InternalNodes = nn
				.OrderBy(item => randomize ? this.Random.Next() : 1)
				.DistinctBy(n => n.Uri)
				.ToList();
			this.LastUpdate = this.DateTimeProvider.Now();
		}

		protected int GlobalCursor = -1;
		/// <summary>
		/// Creates a view of all the live nodes with changing starting positions that wraps over on each call
		/// e.g Thread A might get 1,2,3,4,5 and thread B will get 2,3,4,5,1.
		/// if there are no live nodes yields a different dead node to try once
		/// </summary>
		public virtual IEnumerable<Node> CreateView(Action<AuditEvent, Node> audit = null)
		{
			//var count = this.InternalNodes.Count;

			var now = this.DateTimeProvider.Now();
			var nodes = this.InternalNodes.Where(n => n.IsAlive || n.DeadUntil <= now)
				.ToList();
			var count = nodes.Count;
			Node node;
			var globalCursor = Interlocked.Increment(ref GlobalCursor);

			if (count == 0)
			{
				//could not find a suitable node retrying on first node off globalCursor
				audit?.Invoke(AuditEvent.AllNodesDead, null);
				node = this.InternalNodes[globalCursor % this.InternalNodes.Count];
				node.IsResurrected = true;
				audit?.Invoke(AuditEvent.Resurrection, node);
				yield return node;
				yield break;
			}

			var localCursor = globalCursor % count;

			for (var attempts = 0; attempts < count; attempts++)
			{
				node = nodes[localCursor];
				localCursor = (localCursor + 1) % count;
				//if this node is not alive or no longer dead mark it as resurrected
				if (!node.IsAlive)
				{
					audit?.Invoke(AuditEvent.Resurrection, node);
					node.IsResurrected = true;
				}
				yield return node;
			}
		}

	}
}


text:
web_service='nginx'
le_path='/home/ubuntu/letsencrypt'
exp_limit=30;
domain='malice.io'
cert_file="/etc/letsencrypt/live/$domain/fullchain.pem"

exp=$(date -d "`openssl x509 -in $cert_file -text -noout|grep "Not After"|cut -c 25-`" +%s)
datenow=$(date -d "now" +%s)
days_exp=$(echo \( $exp - $datenow \) / 86400 |bc)

echo "Checking expiration date for $domain..."

if [ "$days_exp" -gt "$exp_limit" ] ; then
    echo "The certificate is up to date, no need for renewal ($days_exp days left)."
    exit 0;
else
    echo "The certificate for $domain is about to expire soon. Starting webroot renewal script..."
        $le_path/lletsencrypt-auto certonly -a webroot --agree-tos --renew-by-default --webroot-path=/home/ubuntu/server/public/ -d malice.io -d www.malice.io
    echo "Reloading $web_service"
    /usr/sbin/service $web_service reload
    echo "Renewal process finished for domain $domain"
    exit 0;
fi

# sudo crontab -e
#
# 30 2 * * 1 /home/ubuntu/le-renew.sh >> /var/log/le-renewal.log

# A few notes about the above cron job:
#  - Run every Monday at 2:30 am
#  - Outputs the value of the script at /var/log/le-renewal.log


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

public class DescendantPropertyChangedEventArgs
{
	public string PropertyName { get; set; }
	public Dictionary<string, string> Data { get; } = new Dictionary<string, string>();
}