text:
(function (win) {
	function forEach(m, callback) {
		for (var key in m) {
			callback(key, m[key]);
		}
	}

	function buildUrl(url, items) {
		var query = '';
		forEach(items, function (name, value) {
			if (name != 'token') {
				query += (query ? '&' : '') + encodeURIComponent(name) + '=' + encodeURIComponent(value);
			}
		});

		if (query) {
			url += (url.indexOf('?') > 0 ? '&' : '?') + query;
		}

		return url;
	}

	function encode2UTF8(argString) {
		if (argString === null || typeof argString === 'undefined') {
			return '';
		}
		var string = (argString + ''); // .replace(/\r\n/g, '\n').replace(/\r/g, '\n');
		var utftext = '',
			start, end, stringl = 0;
		start = end = 0;
		stringl = string.length;
		for (var n = 0; n < stringl; n++) {
			var c1 = string.charCodeAt(n);
			var enc = null;

			if (c1 < 128) {
				end++;
			} else if (c1 > 127 && c1 < 2048) {
				enc = String.fromCharCode(
					(c1 >> 6) | 192, (c1 & 63) | 128
				);
			} else if (c1 & 0xF800 ^ 0xD800 > 0) {
				enc = String.fromCharCode(
					(c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
				);
			} else { // surrogate pairs
				if (c1 & 0xFC00 ^ 0xD800 > 0) {
					throw new RangeError('Unmatched trail surrogate at ' + n);
				}
				var c2 = string.charCodeAt(++n);
				if (c2 & 0xFC00 ^ 0xDC00 > 0) {
					throw new RangeError('Unmatched lead surrogate at ' + (n - 1));
				}
				c1 = ((c1 & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000;
				enc = String.fromCharCode(
					(c1 >> 18) | 240, ((c1 >> 12) & 63) | 128, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128
				);
			}
			if (enc !== null) {
				if (end > start) {
					utftext += string.slice(start, end);
				}
				utftext += enc;
				start = end = n + 1;
			}
		}

		if (end > start) {
			utftext += string.slice(start, stringl);
		}

		return utftext;
	}
	// Copy 七牛 SDK 方法
	function encode2Base64(data) {
		var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
		var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
			ac = 0,
			enc = '',
			tmp_arr = [];

		if (!data) {
			return data;
		}

		data = encode2UTF8(data + '');

		do { // pack three octets into four hexets
			o1 = data.charCodeAt(i++);
			o2 = data.charCodeAt(i++);
			o3 = data.charCodeAt(i++);

			bits = o1 << 16 | o2 << 8 | o3;

			h1 = bits >> 18 & 0x3f;
			h2 = bits >> 12 & 0x3f;
			h3 = bits >> 6 & 0x3f;
			h4 = bits & 0x3f;

			// use hexets to index into b64, and append result to encoded string
			tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
		} while (i < data.length);

		enc = tmp_arr.join('');

		switch (data.length % 3) {
			case 1:
				enc = enc.slice(0, -2) + '==';
				break;
			case 2:
				enc = enc.slice(0, -1) + '=';
				break;
		}
		return enc;
	}
	// Copy 七牛 SDK 方法
	function URLSafeBase64Encode(v) {
		v = encode2Base64(v);
		return v.replace(/\//g, '_').replace(/\+/g, '-');
	}

	function chunkLastStep(data, opts, callback) {
		// 七牛 URL 规定
		var key = '/key/' + URLSafeBase64Encode(data.filename);
		var fname = '/fname/' + URLSafeBase64Encode(data.filename);
		var url = opts.domain + '/mkfile/' + data.size + key + fname;
		var options = {
			domain: url,
			method: 'POST',
			headers: {
				'Content-Type': 'application/octet-stream'
			},
			multi_parmas: opts.multi_parmas,
			support_options: true,
			stream: true
		};
		uploadData(data.ctx, options, {
			onCompleted: function (res) {
				res.filename = data.filename;
				res.name = data.name;
				callback.onCompleted(res);
			},
			onError: function () {
				throw new Error('qiniu uploadChunk error');
			},
			onProgress: function (chunkLoaded, total) { },
			onOpen: function (xhr) {
				callback.onOpen(xhr);
			}
		});
	}

	var offset = 0,
		ctxStore = {};

	function uploadNextChunk(blob, opts, callback) {
		var chunk = Math.ceil(offset / opts.chunk_size),
			chunks = Math.ceil(blob.size / opts.chunk_size),
			curChunkSize = Math.min(opts.chunk_size, blob.size - offset),
			chunkBlob = blob.slice(offset, offset + curChunkSize),
			chunkInfo = {
				chunk: chunk,
				chunks: chunks,
				name: blob.uniqueName
			};
		forEach(chunkInfo, function (key, value) {
			opts.multi_parmas[key] = value;
		});
		opts.filesize = blob.size;
		opts.headers = {
			'Content-Type': 'application/octet-stream'
		};
		opts.isChunk = true;
		uploadData(chunkBlob, opts, {
			onCompleted: function (chunkRes) {
				offset += curChunkSize;
				// callback.onProgress(Math.floor((chunk + 1) / chunks * blob.size), blob.size);
				ctxStore[blob.uniqueName] = ctxStore[blob.uniqueName] || [];
				ctxStore[blob.uniqueName].push(chunkRes.ctx);
				if (offset < blob.size) {
					if (chunkRes.ctx) {
						uploadNextChunk(blob, opts, callback);
					} else {
						offset = 0;
						delete ctxStore[blob.uniqueName]
					}
				} else {
					offset = 0;
					delete opts.isChunk;
					delete opts.headers['Content-Type'];
					forEach(chunkInfo, function (key, value) {
						delete opts.multi_parmas[key];
					});
					var ctx = ctxStore[blob.uniqueName].join(',');
					var data = {
						ctx: ctx,
						name: blob.name,
						size: blob.size,
						filename: blob.uniqueName
					};
					chunkLastStep(data, opts, callback);
				}
			},
			onError: function () {
				throw new Error('qiniu uploadChunk error');
			},
			onProgress: function (chunkLoaded, total) {
				var loaded = chunkLoaded + offset;
				callback.onProgress(loaded, opts.filesize);
			},
			onOpen: function (xhr) {
				callback.onOpen(xhr);
			}
		});
	}

	function uploadData(data, options, callback) {
		var xhr = new XMLHttpRequest();
		if (xhr.upload && options.support_options) {
			xhr.upload.onprogress = function (event) {
				callback.onProgress(event.loaded, event.total);
			};
		}

		xhr.onreadystatechange = function () {
			if (xhr.readyState == 4) {
				var result = xhr.responseText || "{}";
				result = JSON.parse(result);
				result.filename = options.unique_value;
				callback.onCompleted(result);
			}
		};

		var url = options.domain;
		if (options.isChunk) {
			url += '/mkblk/' + data.size;
			url = buildUrl(url, options.multi_parmas);
		}
		xhr.open(options.method, url, true);

		callback.onOpen(xhr);

		if (options.stream) {
			xhr.setRequestHeader('authorization', 'UpToken ' + options.multi_parmas.token);
		}

		forEach(options.headers, function (key, value) {
			xhr.setRequestHeader(key, value);
		});
		xhr.send(data);
	}

	function uploadQiniu(file, opts, callback) {
		if (file.size && opts.chunk_size < file.size) {
			var uniqueName = opts['genUId'](file);
			var suffix = file.name.substr(file.name.lastIndexOf('.'));
			uniqueName = uniqueName + suffix;
			file.uniqueName = uniqueName;
			opts.stream = true;
			uploadNextChunk(file, opts, callback);
		} else {
			var data = opts['data'](file, opts);
			uploadData(data, opts, callback);
		}
	}
	win.uploadProcess = uploadQiniu;
})(window);

(function (win) {

	var dataType = {
		form: getFormData,
		json: getJsonData,
		data: getData
	};

	function genUId() {
		var date = new Date().getTime();
		var uuid = 'xxxxxx4xxxyxxxxxxx'.replace(/[xy]/g, function (c) {
			var r = (date + Math.random() * 16) % 16 | 0;
			date = Math.floor(date / 16);
			return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
		});
		return uuid;
	};

	function mergeOption(opts) {
		var options = {
			domain: '',
			method: 'POST',
			file_data_name: 'file',
			unique_key: 'key',
			base64_size: 4 * 1024 * 1024,
			chunk_size: 4 * 1024 * 1024,
			headers: {},
			multi_parmas: {},
			query: {},
			support_options: true,
			data: dataType.form,
			genUId: genUId
		};
		if (!opts || !opts.domain) {
			throw new Error('domain is null');
		}
		for (var key in opts) {
			options[key] = opts[key];
		}
		return options;
	}

	function mEach(m, callback) {
		for (var key in m) {
			callback(key, m[key]);
		}
	}

	function getFormData(file, opts) {
		var form = new FormData();
		if (opts.unique_key) {
			var suffix = file.name.substr(file.name.lastIndexOf('.'));
			var unique_value = genUId() + suffix;
			form.append(opts.unique_key, unique_value);
			opts.unique_value = unique_value;
		}
		form.append(opts.file_data_name, file);
		mEach(opts.multi_parmas, function (key, value) {
			form.append(key, value);
		});
		return form;
	}

	function getJsonData(file, opts) {
		var data = {};
		if (opts.unique_key) {
			var suffix = file.name.substr(file.name.lastIndexOf('.'));
			var unique_value = genUId() + suffix;
			data[opts.unique_key] = unique_value;
			opts.unique_value = unique_value;
		}
		data[opts.file_data_name] = file;
		mEach(opts.multi_parmas, function (key, value) {
			data[key] = value;
		});
		return JSON.stringify(data);
	}

	function getData(file, opts) {
		return file;
	}

	function Upload(options) {
		this.options = mergeOption(options);

		this.setOptions = function (opts) {
			var me = this;
			mEach(opts, function (key, value) {
				me.options[key] = value;
			});
		};

		this.upload = function (file, callback) {
			if (!file) {
				callback.onError('upload file is null.');
				return;
			}
			var me = this;
			uploadProcess(file, this.options, {
				onProgress: function (loaded, total) {
					callback.onProgress(loaded, total);
				},
				onCompleted: function (data) {
					callback.onCompleted(data);
				},
				onError: function (errorCode) {
					callback.onError(errorCode);
				},
				onOpen: function (xhr) {
					me.xhr = xhr;
				}
			});
		};

		this.cancel = function () {
			this.xhr && this.xhr.abort();
		};
	}

	function init(options) {
		return new Upload(options);
	}

	function getResizeRatio(imageInfo, config) {
		//hasOwnProperty?

		var ratio = 1;

		var oWidth = imageInfo.width;
		var maxWidth = config.maxWidth || 0;
		if (maxWidth > 0 && oWidth > maxWidth) {
			ratio = maxWidth / oWidth;
		}

		var oHeight = imageInfo.height;
		var maxHeight = config.maxHeight || 0;
		if (maxHeight > 0 && oHeight > maxHeight) {
			var ratioHeight = maxHeight / oHeight;
			ratio = Math.min(ratio, ratioHeight);
		}

		var maxSize = config.maxSize || 0;
		var oSize = Math.ceil(imageInfo.size / 1000); //K,Math.ceil(0.3) = 1;
		if (oSize > maxSize) {
			ratioSize = maxSize / oSize;
			ratio = Math.min(ratio, ratioSize);
		}

		return ratio;
	}

	function resize(file, config, callback) {
		//file对象没有高宽
		var type = file.type; //image format
		var canvas = document.createElement("canvas");

		var reader = new FileReader();

		reader.readAsDataURL(file);
		reader.onload = function (evt) {
			var imageData = evt.target.result;
			var img = new Image();
			img.src = imageData;
			var width = img.width;
			var height = img.height;
			var imageInfo = {
				width: width,
				height: height,
				size: evt.total
			}
			var ratio = getResizeRatio(imageInfo, config);
			var newImageData = imageData;
			if (ratio < 1) {
				newImageData = compress(img, width * ratio, height * ratio);;
			}
			callback(newImageData);
		}

		function compress(img, width, height) {
			canvas.width = width;
			canvas.height = height;

			var context = canvas.getContext('2d');
			context.drawImage(img, 0, 0, width, height);

			/*
			If the height or width of the canvas is 0, the string "data:," is returned.
			If the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported.
			Chrome also supports the image/webp type.
			*/

			var supportTypes = {
				"image/jpg": true,
				"image/png": true,
				"image/webp": supportWebP()
			};
			// var exportType = "image/png";
			// if(supportTypes[type]){
			// 	exportType = type;
			// }
			// 多端一致,缩略图必须是 jpg
			var exportType = "image/jpg";
			var newImageData = canvas.toDataURL(exportType);
			return newImageData;
		}

		function supportWebP() {
			try {
				return (canvas.toDataURL('image/webp').indexOf('data:image/webp') == 0);
			} catch (err) {
				return false;
			}
		}
	}

	win.UploadFile = {
		init: init,
		dataType: dataType,
		resize: resize
	};
})(window);

(function (global, factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
		typeof define === 'function' && define.amd ? define(factory) : (global.UploadClient = factory());
}(this, function () {
	var calcPosition = function (width, height, opts) {
		var isheight = width < height;
		var scale = isheight ? height / width : width / height;
		var zoom, x = 0,
			y = 0,
			w, h;

		var gtScale = function () {
			if (isheight) {
				zoom = width / 100;
				w = 100;
				h = height / zoom;
				y = (h - opts.maxHeight) / 2;
			} else {
				zoom = height / 100;
				h = 100;
				w = width / zoom;
				x = (w - opts.maxWidth) / 2;
			}
			return {
				w: w,
				h: h,
				x: -x,
				y: -y
			};
		};

		var ltScale = function () {
			if (isheight) {
				zoom = height / opts.maxHeight;
				h = opts.maxHeight;
				w = width / zoom;
			} else {
				zoom = width / opts.maxWidth;
				w = opts.maxWidth;
				h = height / zoom;
			}
			return {
				w: w,
				h: h,
				x: -x,
				y: -y
			};
		};
		return scale > opts.scale ? gtScale() : ltScale();
	};

	var getBlobUrl = function (file) {
		var URL = window.URL || window.webkitURL;
		return URL ? URL.createObjectURL(file) : "";
	};

	var getThumbnail = function (file, opts, callback) {
		var canvas = document.createElement("canvas"),
			context = canvas.getContext('2d');
		var img = new Image();
		img.onload = function () {
			var pos = calcPosition(img.width, img.height, opts);
			canvas.width = pos.w > opts.maxWidth ? opts.maxWidth : pos.w;
			canvas.height = pos.h > opts.maxHeight ? opts.maxHeight : pos.h;
			context.drawImage(img, pos.x, pos.y, pos.w, pos.h);
			try {
				var base64 = canvas.toDataURL(file.type, opts.quality);
				var reg = new RegExp('^data:image/[^;]+;base64,');
				base64 = base64.replace(reg, '');
				callback(base64);
			} catch (e) {
				throw new Error(e);
			}
		};
		img.src = typeof file == 'string' ? 'data:image/jpg;base64,' + file : getBlobUrl(file);
	};

	var _compress = function (data, callback) {
		var file = data.file;
		var opts = data.compress;
		getThumbnail(file, opts, callback);
	};

	_init = function (config, callback) {
		if (config.getToken) {
			config.getToken(function (token) {
				config.multi_parmas || (config.multi_parmas = {});
				config.multi_parmas.token = token;
				config.headers || (config.headers = {});
				if (config.base64) {
					config.headers['Content-type'] = 'application/octet-stream';
					config.headers['Authorization'] = 'UpToken ' + token;
				}
				var instance = UploadFile.init(config);
				callback(instance);
			});
		} else {
			config.headers || (config.headers = {});
			if (config.base64) {
				config.headers['Content-type'] = 'application/octet-stream';
			}
			var instance = UploadFile.init(config);
			callback(instance);
		}
	};

	var _upload = function (data, instance, callback) {
		instance.upload(data.file, {
			onError: function (errorCode) {
				callback.onError(errorCode);
			},
			onProgress: function (loaded, total) {
				callback.onProgress(loaded, total);
			},
			onCompleted: function (result) {
				result.filename || (result.filename = result.hash);
				var compress = data.compressThumbnail || _compress;
				if (data.compress) {
					compress(data, function (thumbnail) {
						result.thumbnail = thumbnail;
						callback.onCompleted(result);
					});
				} else {
					callback.onCompleted(result);
				}
			}
		});
	};

	var File = function (instance) {
		var me = this;
		this.instance = instance
		this.upload = function (file, callback) {
			var data = {
				file: file
			};
			_upload(data, me.instance, callback);
		};
		this.cancel = function () {
			me.instance.cancel();
		};
	};

	var initFile = function (config, callback) {
		_init(config, function (instance) {
			var uploadFile = new File(instance);
			callback(uploadFile);
		});
	};

	var Img = function (instance, cfg) {
		var me = this;
		this.cfg = cfg;
		this.instance = instance;
		this.upload = function (file, callback) {
			var data = {
				file: file,
				compress: me.cfg
			};
			_upload(data, me.instance, callback);
		};

		this.cancel = function () {
			me.instance.cancel();
		};
	};

	var initImage = function (config, callback) {
		_init(config, function (instance) {
			var compress = {
				maxHeight: config.height || 240,
				maxWidth: config.width || 240,
				quality: config.quality || 0.5,
				scale: config.scale || 2.4
			};
			var uploadImage = new Img(instance, compress);
			callback(uploadImage);
		});
	};

	var ImgBase64 = function (config) {
		config.base64 = true;
		Img.call(this, config);
	};

	var initImgBase64 = function (config, callback) {
		config.base64 = true;
		initImage.call(this, config, callback);
	};

	return {
		initFile: initFile,
		initImage: initImage,
		initImgBase64: initImgBase64,
		dataType: UploadFile.dataType
	};
}));


text:
package models;

import play.db.jpa.Model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import java.util.List;
import java.util.Set;

@Entity
public class Publisher extends Model {

    public String name;

    @OneToMany
    public List<Author> authors;

    @OneToMany(mappedBy = "publisher")
    public Set<Book> publishedBooks;

    @OneToOne
    public Person manager;

    public Publisher(String name) {
        this.name = name;
    }

    public String toString() {
        return super.toString() + "(" + name + ")";
    }

}

redpajama_set_name: RedPajamaGithub


text:
package client.graphics.gui;

// Created by Aunmag on 19.11.2016.

import client.Client;

import java.awt.*;

public class GuiLabel {

    // Position:
    private int x;
    private int y;
    private int width;
    private int height;

    // Text:
    private int size;
    private boolean isBold;
    private static String fontName = "Arial";
    private Font font;
    private String text;

    private Color color = Color.white;

    public GuiLabel(int x, int y, int size, boolean isBold, String text) {

        this.x = x;
        this.y = y;

        this.size = size;
        this.isBold = isBold;

        if (isBold) {
            font = new Font(fontName, Font.BOLD, size);
        } else {
            font = new Font(fontName, Font.PLAIN, size);
        }

        setText(text);

    }

    public void setText(String text) {

        this.text = text;

        Client.getHud().setFont(font);
        width = Client.getHud().getFontMetrics().stringWidth(text);
        height = (int) (size / 2.5);

    }

    public void render() {

        Client.getHud().setFont(font);
        Client.getHud().setColor(color);
        Client.getHud().drawString(text, x - width / 2, y + height);

    }

    public void setColor(Color color) {

        this.color = color;

    }

}


text:
/**
 * This header is generated by class-dump-z 0.2b.
 *
 * Source: (null)
 */

#import "assistivetouchd-Structs.h"

@protocol HNDWindowDelegateProtocol <NSObject>
-(BOOL)acceptsHitTest:(CGPoint)test;
@end


text:
<?php
namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;

/**
 * Users Model
 *
 * @property \Cake\ORM\Association\HasMany $Carts
 *
 * @method \App\Model\Entity\User get($primaryKey, $options = [])
 * @method \App\Model\Entity\User newEntity($data = null, array $options = [])
 * @method \App\Model\Entity\User[] newEntities(array $data, array $options = [])
 * @method \App\Model\Entity\User|bool save(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\User patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
 * @method \App\Model\Entity\User[] patchEntities($entities, array $data, array $options = [])
 * @method \App\Model\Entity\User findOrCreate($search, callable $callback = null, $options = [])
 */
class UsersTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('users');
        $this->displayField('id');
        $this->primaryKey('id');

        $this->hasMany('Carts', [
            'foreignKey' => 'user_id'
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator)
    {
        $validator
            ->integer('id')
            ->allowEmpty('id', 'create');

        $validator
            ->requirePresence('email_address', 'create')
            ->notEmpty('email_address');

        $validator
            ->allowEmpty('first_name');

        $validator
            ->allowEmpty('last_name');

        $validator
            ->requirePresence('password', 'create')
            ->notEmpty('password');

        return $validator;
    }
}


text:
layout: tagpage
title: "Tag: inclusion"
tag: inclusion
robots: noindex
---


text:
### A rich framework for building applications and services

**hapi** is a simple to use configuration-centric framework with built-in support for input validation, caching, authentication,
and other essential facilities for building web applications and services. **hapi** enables developers to focus on writing reusable
application logic instead of spending time building infrastructure, without getting in the way.

Current version: **6.2.x** ([release notes](https://github.com/spumko/hapi/issues?labels=release+notes&page=1&state=closed)) [![Build Status](https://secure.travis-ci.org/spumko/hapi.svg)](http://travis-ci.org/spumko/hapi)

For the latest updates and release information visit [hapijs.com](http://hapijs.com) and follow [@hapijs](https://twitter.com/hapijs) on twitter.

### Additional information

- Any **issues or questions** (no matter how basic), open an issue.
- For a self-guided lesson on hapi, use [Make Me Hapi](https://github.com/spumko/makemehapi).
- For a full application example, check out [postmile](https://github.com/hueniverse/postmile).
- Information about the **work-in-progress** in the master branch:
    - [API reference](/docs/Reference.md)
    - [Upcoming breaking changes](https://github.com/spumko/hapi/issues?labels=breaking+changes)
- For **discussions** join the [#hapi channel](http://webchat.freenode.net/?channels=hapi) on irc.freenode.net.


text:
Note: This is in reverse chronological order, so newer entries are added to the top.

Swift 4.0
---------

* The generated Xcode project creates a dummy target which provides
  autocompletion for the manifest files. The name of the dummy target is in
  format: `<PackageName>PackageDescription`.

* `--specifier` option for `swift test` is now deprecated.
  Use `--filter` instead which supports regex.

Swift 3.0
---------

* [SE-0135](https://github.com/apple/swift-evolution/blob/master/proposals/0135-package-manager-support-for-differentiating-packages-by-swift-version.md)

  The package manager now supports writing Swift 3.0 specific tags and
  manifests, in order to support future evolution of the formats used in both
  cases while still allowing the Swift 3.0 package manager to continue to
  function.

* [SE-0129](https://github.com/apple/swift-evolution/blob/master/proposals/0129-package-manager-test-naming-conventions.md)

  Test modules now *must* be named with a `Tests` suffix (e.g.,
  `Foo/Tests/BarTests/BarTests.swift`). This name also defines the name of the
  Swift module, replacing the old `BarTestSuite` module name.

* It is no longer necessary to run `swift build` before running `swift test` (it
  will always regenerates the build manifest when necessary). In addition, it
  now accepts (and requires) the same `-Xcc`, etc. options as are used with
  `swift build`.

* The `Package` initializer now requires the `name:` parameter.


text:
<?php
class Infusionsoft_Company extends Infusionsoft_Generated_Company{
    var $customFieldFormId = -6;
    public function __construct($id = null, $app = null){
    	parent::__construct($id, $app);
    }
}


text:
<form wicket:id="form" id="form1" method="post" action="../page?0-1.IFormSubmitListener-form">
<input type="hidden" name="form1_hf_0" id="form1_hf_0" />

<wicket:border>
		<wicket:body>
	<input type="text" wicket:id="input" value="" name="feedback:feedback_body:input">
</wicket:body>

	</wicket:border>
</form>


text:
package org.apache.activemq.command;

/**
 * @openwire:marshaller code="124"
 *
 */
public class BrokerId implements DataStructure {

    public static final byte DATA_STRUCTURE_TYPE = CommandTypes.BROKER_ID;
    protected String value;

    public BrokerId() {
    }

    public BrokerId(String brokerId) {
        this.value = brokerId;
    }

    public int hashCode() {
        return value.hashCode();
    }

    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || o.getClass() != BrokerId.class) {
            return false;
        }
        BrokerId id = (BrokerId)o;
        return value.equals(id.value);
    }

    public byte getDataStructureType() {
        return DATA_STRUCTURE_TYPE;
    }

    public String toString() {
        return value;
    }

    /**
     * @openwire:property version=1
     */
    public String getValue() {
        return value;
    }

    public void setValue(String brokerId) {
        this.value = brokerId;
    }

    public boolean isMarshallAware() {
        return false;
    }
}


text:
#ifndef LOCKD_XDR_H
#define LOCKD_XDR_H

#include <asm/types.h>

#include <linux/fs.h>
#include <linux/nfs.h>

#define NLM_MAXCOOKIELEN    	32
#define NLM_MAXSTRLEN		1024

#define	nlm_granted		__constant_htonl(NLM_LCK_GRANTED)
#define	nlm_lck_denied		__constant_htonl(NLM_LCK_DENIED)
#define	nlm_lck_denied_nolocks	__constant_htonl(NLM_LCK_DENIED_NOLOCKS)
#define	nlm_lck_blocked		__constant_htonl(NLM_LCK_BLOCKED)
#define	nlm_lck_denied_grace_period	__constant_htonl(NLM_LCK_DENIED_GRACE_PERIOD)

/* Lock info passed via NLM */
struct nlm_lock {
	char *			caller;
	int			len; 	/* length of "caller" */
	struct nfs_fh		fh;
	struct xdr_netobj	oh;
	struct file_lock	fl;
};

/*
 *	NLM cookies. Technically they can be 1K, but Linux only uses 8 bytes.
 *	FreeBSD uses 16, Apple Mac OS X 10.3 uses 20. Therefore we set it to
 *	32 bytes.
 */

struct nlm_cookie
{
	unsigned char data[NLM_MAXCOOKIELEN];
	unsigned int len;
};

/*
 * Generic lockd arguments for all but sm_notify
 */
struct nlm_args {
	struct nlm_cookie	cookie;
	struct nlm_lock		lock;
	__u32			block;
	__u32			reclaim;
	__u32			state;
	__u32			monitor;
	__u32			fsm_access;
	__u32			fsm_mode;
};

typedef struct nlm_args nlm_args;

/*
 * Generic lockd result
 */
struct nlm_res {
	struct nlm_cookie	cookie;
	__u32			status;
	struct nlm_lock		lock;
};

/*
 * statd callback when client has rebooted
 */
struct nlm_reboot {
	char *		mon;
	int		len;
	__u32		state;
	__u32		addr;
	__u32		vers;
	__u32		proto;
};

/*
 * Contents of statd callback when monitored host rebooted
 */
#define NLMSVC_XDRSIZE		sizeof(struct nlm_args)

int	nlmsvc_decode_testargs(struct svc_rqst *, __u32 *, struct nlm_args *);
int	nlmsvc_encode_testres(struct svc_rqst *, __u32 *, struct nlm_res *);
int	nlmsvc_decode_lockargs(struct svc_rqst *, __u32 *, struct nlm_args *);
int	nlmsvc_decode_cancargs(struct svc_rqst *, __u32 *, struct nlm_args *);
int	nlmsvc_decode_unlockargs(struct svc_rqst *, __u32 *, struct nlm_args *);
int	nlmsvc_encode_res(struct svc_rqst *, __u32 *, struct nlm_res *);
int	nlmsvc_decode_res(struct svc_rqst *, __u32 *, struct nlm_res *);
int	nlmsvc_encode_void(struct svc_rqst *, __u32 *, void *);
int	nlmsvc_decode_void(struct svc_rqst *, __u32 *, void *);
int	nlmsvc_decode_shareargs(struct svc_rqst *, __u32 *, struct nlm_args *);
int	nlmsvc_encode_shareres(struct svc_rqst *, __u32 *, struct nlm_res *);
int	nlmsvc_decode_notify(struct svc_rqst *, __u32 *, struct nlm_args *);
int	nlmsvc_decode_reboot(struct svc_rqst *, __u32 *, struct nlm_reboot *);
/*
int	nlmclt_encode_testargs(struct rpc_rqst *, __u32 *, struct nlm_args *);
int	nlmclt_encode_lockargs(struct rpc_rqst *, __u32 *, struct nlm_args *);
int	nlmclt_encode_cancargs(struct rpc_rqst *, __u32 *, struct nlm_args *);
int	nlmclt_encode_unlockargs(struct rpc_rqst *, __u32 *, struct nlm_args *);
 */

#endif /* LOCKD_XDR_H */


text:
'use strict';

/**
 * Module dependencies.
 */
var users = require('../../app/controllers/users');
var forums = require('../../app/controllers/forums');

module.exports = function(app) {
	app.route('/forums')
		.get(forums.list)
		.post(users.requiresLogin, forums.create);

	app.route('/forums/:forumId')
		.get(forums.read)
		.put(users.requiresLogin, forums.hasAuthorization, forums.update)
		.delete(users.requiresLogin, forums.hasAuthorization, forums.delete);

	app.route('/forums/:forumId/post/:postId')
		.delete(users.requiresLogin, forums.hasAuthorization, forums.deletePost);

	app.param('forumId', forums.forumByID);
};


text:
<?php

namespace Drupal\field\Plugin\migrate\process\d7;

use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\MigrateLookupInterface;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Determines the bundle for a field.
 *
 * The field bundle process plugin is used to get the destination bundle name
 * for a field. This is necessary because the bundle names used for comments in
 * legacy versions of Drupal are no longer used.
 *
 * Available configuration keys:
 * - source: The input value - must be an array.
 *
 * Examples:
 *
 * @code
 * process:
 *   bundle:
 *     plugin: field_bundle
 *     source
 *       - entity_type
 *       - bundle
 * @endcode
 *
 * If 'bundle' is 'article' and 'entity_type' is node then 'article' is
 * returned.
 *
 * @code
 * process:
 *   bundle:
 *     plugin: field_bundle
 *     source
 *       - entity_type
 *       - bundle
 * @endcode
 *
 * If 'bundle' is 'comment_node_a_thirty_two_character_name' and 'entity_type'
 * is blog then a lookup is performed on the comment type migration so that the
 * migrated bundle name for 'comment_node_a_thirty_two_character_name' is
 * returned. That name will be truncated to 'comment_node_a_thirty_two_char'.
 *
 * @see core/modules/comment/migrations/d7_comment_type.yml
 * @see core/modules/field/migrations/d7_field_instance.yml
 *
 * * @MigrateProcessPlugin(
 *   id = "field_bundle"
 * )
 */
class FieldBundle extends ProcessPluginBase implements ContainerFactoryPluginInterface {

  /**
   * The migrate lookup service.
   *
   * @var \Drupal\migrate\MigrateLookupInterface
   */
  protected $migrateLookup;

  /**
   * Constructs a ProcessField plugin.
   *
   * @param array $configuration
   *   The plugin configuration.
   * @param string $plugin_id
   *   The plugin ID.
   * @param mixed $plugin_definition
   *   The plugin definition.
   * @param \Drupal\migrate\MigrateLookupInterface $migrate_lookup
   *   The migrate lookup service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrateLookupInterface $migrate_lookup) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->migrateLookup = $migrate_lookup;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('migrate.lookup')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    [$entity_type, $bundle] = $value;
    $lookup_result = NULL;
    // For comment entity types get the destination bundle from the
    // d7_comment_type migration, if it exists.
    if ($entity_type === 'comment' && $bundle != 'comment_forum') {
      $value = str_replace('comment_node_', '', $bundle);
      $migration = 'd7_comment_type';
      $lookup_result = $this->migrateLookup->lookup($migration, [$value]);
      $lookup_result = empty($lookup_result) ? NULL : reset($lookup_result[0]);
    }
    return $lookup_result ? $lookup_result : $bundle;
  }

}


text:
require "set"
require "keg"
require "formula"

class LinkageChecker
  attr_reader :keg, :formula
  attr_reader :brewed_dylibs, :system_dylibs, :broken_dylibs, :variable_dylibs
  attr_reader :undeclared_deps, :reverse_links

  def initialize(keg, formula = nil)
    @keg = keg
    @formula = formula || resolve_formula(keg)
    @brewed_dylibs = Hash.new { |h, k| h[k] = Set.new }
    @system_dylibs = Set.new
    @broken_dylibs = Set.new
    @variable_dylibs = Set.new
    @undeclared_deps = []
    @reverse_links = Hash.new { |h, k| h[k] = Set.new }
    check_dylibs
  end

  def check_dylibs
    @keg.find do |file|
      next if file.symlink? || file.directory?
      next unless file.dylib? || file.mach_o_executable? || file.mach_o_bundle?
      file.dynamically_linked_libraries.each do |dylib|
        @reverse_links[dylib] << file
        if dylib.start_with? "@"
          @variable_dylibs << dylib
        else
          begin
            owner = Keg.for Pathname.new(dylib)
          rescue NotAKegError
            @system_dylibs << dylib
          rescue Errno::ENOENT
            @broken_dylibs << dylib
          else
            tap = Tab.for_keg(owner).tap
            f = if tap.nil? || tap.core_tap?
              owner.name
            else
              "#{tap}/#{owner.name}"
            end
            @brewed_dylibs[f] << dylib
          end
        end
      end
    end

    @undeclared_deps = check_undeclared_deps if formula
  end

  def check_undeclared_deps
    filter_out = proc do |dep|
      next true if dep.build?
      next false unless dep.optional? || dep.recommended?
      formula.build.without?(dep)
    end
    declared_deps = formula.deps.reject { |dep| filter_out.call(dep) }.map(&:name)
    declared_requirement_deps = formula.requirements.reject { |req| filter_out.call(req) }.map(&:default_formula).compact
    declared_dep_names = (declared_deps + declared_requirement_deps).map { |dep| dep.split("/").last }
    undeclared_deps = @brewed_dylibs.keys.select do |full_name|
      name = full_name.split("/").last
      next false if name == formula.name
      !declared_dep_names.include?(name)
    end
    undeclared_deps.sort do |a, b|
      if a.include?("/") && !b.include?("/")
        1
      elsif !a.include?("/") && b.include?("/")
        -1
      else
        a <=> b
      end
    end
  end

  def display_normal_output
    display_items "System libraries", @system_dylibs
    display_items "Homebrew libraries", @brewed_dylibs
    display_items "Variable-referenced libraries", @variable_dylibs
    display_items "Missing libraries", @broken_dylibs
    display_items "Possible undeclared dependencies", @undeclared_deps
  end

  def display_reverse_output
    return if @reverse_links.empty?
    sorted = @reverse_links.sort
    sorted.each do |dylib, files|
      puts dylib
      files.each do |f|
        unprefixed = f.to_s.strip_prefix "#{@keg}/"
        puts "  #{unprefixed}"
      end
      puts unless dylib == sorted.last[0]
    end
  end

  def display_test_output
    display_items "Missing libraries", @broken_dylibs
    puts "No broken dylib links" if @broken_dylibs.empty?
  end

  def broken_dylibs?
    !@broken_dylibs.empty?
  end

  def undeclared_deps?
    !@undeclared_deps.empty?
  end

  private

  # Display a list of things.
  # Things may either be an array, or a hash of (label -> array)
  def display_items(label, things)
    return if things.empty?
    puts "#{label}:"
    if things.is_a? Hash
      things.sort.each do |list_label, list|
        list.sort.each do |item|
          puts "  #{item} (#{list_label})"
        end
      end
    else
      things.sort.each do |item|
        puts "  #{item}"
      end
    end
  end

  def resolve_formula(keg)
    Formulary.from_keg(keg)
  rescue FormulaUnavailableError
    opoo "Formula unavailable: #{keg.name}"
  end
end


text:
package com.pesit.sample;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
	MediaPlayer music;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		music = MediaPlayer.create(this, R.raw.i_am_waiting_for_you_last_summer);
		Button button = (Button) findViewById(R.id.music_button);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (music.isPlaying()) {
					Toast.makeText(MainActivity.this, "music paused",
							Toast.LENGTH_LONG).show();
					music.pause();
				} else {
					Toast.makeText(MainActivity.this, "music started",
							Toast.LENGTH_LONG).show();
					music.start();
				}

			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}


text:
// Copyright (c) the JPEG XL Project Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

#include <string>

#include "gtest/gtest.h"
#include "lib/extras/codec.h"
#include "lib/jxl/aux_out.h"
#include "lib/jxl/base/data_parallel.h"
#include "lib/jxl/base/padded_bytes.h"
#include "lib/jxl/base/thread_pool_internal.h"
#include "lib/jxl/codec_in_out.h"
#include "lib/jxl/enc_butteraugli_comparator.h"
#include "lib/jxl/enc_cache.h"
#include "lib/jxl/enc_file.h"
#include "lib/jxl/enc_params.h"
#include "lib/jxl/image.h"
#include "lib/jxl/image_test_utils.h"
#include "lib/jxl/test_utils.h"
#include "lib/jxl/testdata.h"

namespace jxl {
namespace {

struct SpeedTierTestParams {
  explicit SpeedTierTestParams(const SpeedTier speed_tier,
                               const bool shrink8 = false)
      : speed_tier(speed_tier), shrink8(shrink8) {}
  SpeedTier speed_tier;
  bool shrink8;
};

std::ostream& operator<<(std::ostream& os, SpeedTierTestParams params) {
  auto previous_flags = os.flags();
  os << std::boolalpha;
  os << "SpeedTierTestParams{" << SpeedTierName(params.speed_tier)
     << ", /*shrink8=*/" << params.shrink8 << "}";
  os.flags(previous_flags);
  return os;
}

class SpeedTierTest : public testing::TestWithParam<SpeedTierTestParams> {};

JXL_GTEST_INSTANTIATE_TEST_SUITE_P(
    SpeedTierTestInstantiation, SpeedTierTest,
    testing::Values(SpeedTierTestParams{SpeedTier::kCheetah,
                                        /*shrink8=*/true},
                    SpeedTierTestParams{SpeedTier::kCheetah,
                                        /*shrink8=*/false},
                    SpeedTierTestParams{SpeedTier::kThunder,
                                        /*shrink8=*/true},
                    SpeedTierTestParams{SpeedTier::kThunder,
                                        /*shrink8=*/false},
                    SpeedTierTestParams{SpeedTier::kLightning,
                                        /*shrink8=*/true},
                    SpeedTierTestParams{SpeedTier::kLightning,
                                        /*shrink8=*/false},
                    SpeedTierTestParams{SpeedTier::kFalcon,
                                        /*shrink8=*/true},
                    SpeedTierTestParams{SpeedTier::kFalcon,
                                        /*shrink8=*/false},
                    SpeedTierTestParams{SpeedTier::kHare,
                                        /*shrink8=*/true},
                    SpeedTierTestParams{SpeedTier::kHare,
                                        /*shrink8=*/false},
                    SpeedTierTestParams{SpeedTier::kWombat,
                                        /*shrink8=*/true},
                    SpeedTierTestParams{SpeedTier::kWombat,
                                        /*shrink8=*/false},
                    SpeedTierTestParams{SpeedTier::kSquirrel,
                                        /*shrink8=*/true},
                    SpeedTierTestParams{SpeedTier::kSquirrel,
                                        /*shrink8=*/false},
                    SpeedTierTestParams{SpeedTier::kKitten,
                                        /*shrink8=*/true},
                    SpeedTierTestParams{SpeedTier::kKitten,
                                        /*shrink8=*/false},
                    // Only downscaled image for Tortoise mode.
                    SpeedTierTestParams{SpeedTier::kTortoise,
                                        /*shrink8=*/true}));

TEST_P(SpeedTierTest, Roundtrip) {
  const PaddedBytes orig =
      ReadTestData("external/wesaturate/500px/u76c0g_bliznaca_srgb8.png");
  CodecInOut io;
  ThreadPoolInternal pool(8);
  ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool));

  const SpeedTierTestParams& params = GetParam();

  if (params.shrink8) {
    io.ShrinkTo(io.xsize() / 8, io.ysize() / 8);
  }

  CompressParams cparams;
  cparams.speed_tier = params.speed_tier;

  CodecInOut io2;
  test::Roundtrip(&io, cparams, {}, nullptr, &io2);

  // Can be 2.2 in non-hare mode.
  EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, GetJxlCms(),
                                /*distmap=*/nullptr, /*pool=*/nullptr),
            2.8);
}
}  // namespace
}  // namespace jxl


text:
"""firstproject URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin

from django.contrib.auth import views
from firstapp.forms import LoginForm

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'',include('firstapp.urls')),
    url(r'login/$', views.login, {
        'template_name':'login.html',
        'authentication_form':LoginForm
    }, name="login"),
    url(r'logout/$', views.logout,{
        'next_page':'/login'
    }),
]


text:
'''This script handles the administrative work that is not implemented into the website. It is not integrated with the site. '''

import pkgutil, os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ctf.settings")

from django.db import connection
from api.attack import update_cache
from api.config import config
from importlib import import_module
from api.models import *
from django.core.cache import cache
import json, time

def flush():
	'''Recompute very score of every team. This includes score, IP, completed challenges, latest solves, etc.'''

	cursor = connection.cursor()
	cursor.execute("SELECT array_agg(id) FROM team")
	teams = cursor.fetchone()[0]

	for team in teams:
		print(team)
		try:
			update_cache(team)
		except:
			pass

	print('Success!')

def add_message(message):
	'''Add a system message visible on the home page.'''

	db = db_system(text=message)
	db.save()
	cache.set('system_latest_messages', '', 0)

	print('Success!')

def check_cache():
	'''Check if memcached is working.'''

	cache.set('test_cache', '')
	if cache.get('test_cache') is None:
		print('Memcached is not working!')
	else:
		cache.set('test_cache', '', 0)
		print('Memcached is working!')

def clear_cache():
	'''Clear ALL cache.'''

	cache.clear()

	print('Success!')

def cache_test():
	'''Test the cache's speed.'''

	cache.set('test_cache', 'abc')
	start = time.time()
	for i in range(0, 10000):
		cache.get('test_cache')
	print(time.time() - start)
	start = time.time()
	for i in range(0, 10000):
		cache.set('test_cache', 'aaaaaaaaaaaaaaaaaaa')
	print(time.time() - start)

def add_challenges():
	'''Add all challenges to the database.'''

	cursor = connection.cursor()
	cursor.execute("TRUNCATE challenges RESTART IDENTITY")
	challenges = [name for _, name, _ in pkgutil.iter_modules([config.CHALLENGE_FOLDER])]
	for challenge in challenges:
		try:
			add = getattr(import_module('%s.%s' % (config.CHALLENGE_FOLDER, challenge)), 'add')
			data = add()

			if 'type' not in data:
				type = 0
			else:
				type = data['type']

			db = db_challenges(title=data['title'], score=data['score'], file=challenge + '.py', category=data['category'], solves=0, type=type, deactivated=0, hidden=0)
			db.save()
		except:
			pass

	print('Success!')

if __name__ == '__main__':
	'''An example of horrible and lazy programming.'''

	while True:
		data = input('Function: ')
		eval(data)


text:
package recipe

import (
	v3 "github.com/coreos/etcd/clientv3"
	"github.com/coreos/etcd/mvcc/mvccpb"
	"golang.org/x/net/context"
)

type RWMutex struct {
	client *v3.Client
	ctx    context.Context

	key   string
	myKey *EphemeralKV
}

func NewRWMutex(client *v3.Client, key string) *RWMutex {
	return &RWMutex{client, context.TODO(), key, nil}
}

func (rwm *RWMutex) RLock() error {
	rk, err := NewUniqueEphemeralKey(rwm.client, rwm.key+"/read")
	if err != nil {
		return err
	}
	rwm.myKey = rk

	// if there are nodes with "write-" and a lower
	// revision number than us we must wait
	resp, err := rwm.client.Get(rwm.ctx, rwm.key+"/write", v3.WithFirstRev()...)
	if err != nil {
		return err
	}
	if len(resp.Kvs) == 0 || resp.Kvs[0].ModRevision > rk.Revision() {
		// no blocking since no write key
		return nil
	}
	return rwm.waitOnLowest()
}

func (rwm *RWMutex) Lock() error {
	rk, err := NewUniqueEphemeralKey(rwm.client, rwm.key+"/write")
	if err != nil {
		return err
	}
	rwm.myKey = rk

	for {
		// find any key of lower rev number blocks the write lock
		opts := append(v3.WithLastRev(), v3.WithRev(rk.Revision()-1))
		resp, err := rwm.client.Get(rwm.ctx, rwm.key, opts...)
		if err != nil {
			return err
		}
		if len(resp.Kvs) == 0 {
			// no matching for revision before myKey; acquired
			break
		}
		if err := rwm.waitOnLowest(); err != nil {
			return err
		}
		//  get the new lowest, etc until this is the only one left
	}

	return nil
}

func (rwm *RWMutex) waitOnLowest() error {
	// must block; get key before ek for waiting
	opts := append(v3.WithLastRev(), v3.WithRev(rwm.myKey.Revision()-1))
	lastKey, err := rwm.client.Get(rwm.ctx, rwm.key, opts...)
	if err != nil {
		return err
	}
	// wait for release on prior key
	_, err = WaitEvents(
		rwm.client,
		string(lastKey.Kvs[0].Key),
		rwm.myKey.Revision(),
		[]mvccpb.Event_EventType{mvccpb.DELETE})
	return err
}

func (rwm *RWMutex) RUnlock() error { return rwm.myKey.Delete() }
func (rwm *RWMutex) Unlock() error  { return rwm.myKey.Delete() }


text:
/* WARNING: autogenerated file!
 *
 * The blake2s_impl.c is autogenerated from blake2s_impl.c.
 */

#include "Python.h"
#include "pystrhex.h"
#ifdef WITH_THREAD
#include "pythread.h"
#endif

#include "../hashlib.h"
#include "blake2ns.h"

#define HAVE_BLAKE2S 1
#define BLAKE2_LOCAL_INLINE(type) Py_LOCAL_INLINE(type)

#include "impl/blake2.h"
#include "impl/blake2-impl.h" /* for secure_zero_memory() and store48() */

#ifdef BLAKE2_USE_SSE
#include "impl/blake2s.c"
#else
#include "impl/blake2s-ref.c"
#endif

extern PyTypeObject PyBlake2_BLAKE2sType;

typedef struct {
    PyObject_HEAD
    blake2s_param    param;
    blake2s_state    state;
#ifdef WITH_THREAD
    PyThread_type_lock lock;
#endif
} BLAKE2sObject;

#include "clinic/blake2s_impl.c.h"

/*[clinic input]
module _blake2s
class _blake2s.blake2s "BLAKE2sObject *" "&PyBlake2_BLAKE2sType"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=edbfcf7557a685a7]*/

static BLAKE2sObject *
new_BLAKE2sObject(PyTypeObject *type)
{
    BLAKE2sObject *self;
    self = (BLAKE2sObject *)type->tp_alloc(type, 0);
#ifdef WITH_THREAD
    if (self != NULL) {
        self->lock = NULL;
    }
#endif
    return self;
}

/*[clinic input]
@classmethod
_blake2s.blake2s.__new__ as py_blake2s_new
    string as data: object = NULL
    *
    digest_size: int(c_default="BLAKE2S_OUTBYTES") = _blake2s.blake2s.MAX_DIGEST_SIZE
    key: Py_buffer = None
    salt: Py_buffer = None
    person: Py_buffer = None
    fanout: int = 1
    depth: int = 1
    leaf_size as leaf_size_obj: object = NULL
    node_offset as node_offset_obj: object = NULL
    node_depth: int = 0
    inner_size: int = 0
    last_node: bool = False

Return a new BLAKE2s hash object.
[clinic start generated code]*/

static PyObject *
py_blake2s_new_impl(PyTypeObject *type, PyObject *data, int digest_size,
                    Py_buffer *key, Py_buffer *salt, Py_buffer *person,
                    int fanout, int depth, PyObject *leaf_size_obj,
                    PyObject *node_offset_obj, int node_depth,
                    int inner_size, int last_node)
/*[clinic end generated code: output=fe060b258a8cbfc6 input=458cfdcb3d0d47ff]*/
{
    BLAKE2sObject *self = NULL;
    Py_buffer buf;

    unsigned long leaf_size = 0;
    unsigned long long node_offset = 0;

    self = new_BLAKE2sObject(type);
    if (self == NULL) {
        goto error;
    }

    /* Zero parameter block. */
    memset(&self->param, 0, sizeof(self->param));

    /* Set digest size. */
    if (digest_size <= 0 || digest_size > BLAKE2S_OUTBYTES) {
        PyErr_Format(PyExc_ValueError,
                "digest_size must be between 1 and %d bytes",
                BLAKE2S_OUTBYTES);
        goto error;
    }
    self->param.digest_length = digest_size;

    /* Set salt parameter. */
    if ((salt->obj != NULL) && salt->len) {
        if (salt->len > BLAKE2S_SALTBYTES) {
            PyErr_Format(PyExc_ValueError,
                "maximum salt length is %d bytes",
                BLAKE2S_SALTBYTES);
            goto error;
        }
        memcpy(self->param.salt, salt->buf, salt->len);
    }

    /* Set personalization parameter. */
    if ((person->obj != NULL) && person->len) {
        if (person->len > BLAKE2S_PERSONALBYTES) {
            PyErr_Format(PyExc_ValueError,
                "maximum person length is %d bytes",
                BLAKE2S_PERSONALBYTES);
            goto error;
        }
        memcpy(self->param.personal, person->buf, person->len);
    }

    /* Set tree parameters. */
    if (fanout < 0 || fanout > 255) {
        PyErr_SetString(PyExc_ValueError,
                "fanout must be between 0 and 255");
        goto error;
    }
    self->param.fanout = (uint8_t)fanout;

    if (depth <= 0 || depth > 255) {
        PyErr_SetString(PyExc_ValueError,
                "depth must be between 1 and 255");
        goto error;
    }
    self->param.depth = (uint8_t)depth;

    if (leaf_size_obj != NULL) {
        leaf_size = PyLong_AsUnsignedLong(leaf_size_obj);
        if (leaf_size == (unsigned long) -1 && PyErr_Occurred()) {
            goto error;
        }
        if (leaf_size > 0xFFFFFFFFU) {
            PyErr_SetString(PyExc_OverflowError, "leaf_size is too large");
            goto error;
        }
    }
    self->param.leaf_length = (unsigned int)leaf_size;

    if (node_offset_obj != NULL) {
        node_offset = PyLong_AsUnsignedLongLong(node_offset_obj);
        if (node_offset == (unsigned long long) -1 && PyErr_Occurred()) {
            goto error;
        }
    }
#ifdef HAVE_BLAKE2S
    if (node_offset > 0xFFFFFFFFFFFFULL) {
        /* maximum 2**48 - 1 */
         PyErr_SetString(PyExc_OverflowError, "node_offset is too large");
         goto error;
     }
    store48(&(self->param.node_offset), node_offset);
#else
    self->param.node_offset = node_offset;
#endif

    if (node_depth < 0 || node_depth > 255) {
        PyErr_SetString(PyExc_ValueError,
                "node_depth must be between 0 and 255");
        goto error;
    }
    self->param.node_depth = node_depth;

    if (inner_size < 0 || inner_size > BLAKE2S_OUTBYTES) {
        PyErr_Format(PyExc_ValueError,
                "inner_size must be between 0 and is %d",
                BLAKE2S_OUTBYTES);
        goto error;
    }
    self->param.inner_length = inner_size;

    /* Set key length. */
    if ((key->obj != NULL) && key->len) {
        if (key->len > BLAKE2S_KEYBYTES) {
            PyErr_Format(PyExc_ValueError,
                "maximum key length is %d bytes",
                BLAKE2S_KEYBYTES);
            goto error;
        }
        self->param.key_length = (uint8_t)key->len;
    }

    /* Initialize hash state. */
    if (blake2s_init_param(&self->state, &self->param) < 0) {
        PyErr_SetString(PyExc_RuntimeError,
                "error initializing hash state");
        goto error;
    }

    /* Set last node flag (must come after initialization). */
    self->state.last_node = last_node;

    /* Process key block if any. */
    if (self->param.key_length) {
        uint8_t block[BLAKE2S_BLOCKBYTES];
        memset(block, 0, sizeof(block));
        memcpy(block, key->buf, key->len);
        blake2s_update(&self->state, block, sizeof(block));
        secure_zero_memory(block, sizeof(block));
    }

    /* Process initial data if any. */
    if (data != NULL) {
        GET_BUFFER_VIEW_OR_ERROR(data, &buf, goto error);

        if (buf.len >= HASHLIB_GIL_MINSIZE) {
            Py_BEGIN_ALLOW_THREADS
            blake2s_update(&self->state, buf.buf, buf.len);
            Py_END_ALLOW_THREADS
        } else {
            blake2s_update(&self->state, buf.buf, buf.len);
        }
        PyBuffer_Release(&buf);
    }

    return (PyObject *)self;

  error:
    if (self != NULL) {
        Py_DECREF(self);
    }
    return NULL;
}

/*[clinic input]
_blake2s.blake2s.copy

Return a copy of the hash object.
[clinic start generated code]*/

static PyObject *
_blake2s_blake2s_copy_impl(BLAKE2sObject *self)
/*[clinic end generated code: output=6c5bada404b7aed7 input=c8858e887ae4a07a]*/
{
    BLAKE2sObject *cpy;

    if ((cpy = new_BLAKE2sObject(Py_TYPE(self))) == NULL)
        return NULL;

    ENTER_HASHLIB(self);
    cpy->param = self->param;
    cpy->state = self->state;
    LEAVE_HASHLIB(self);
    return (PyObject *)cpy;
}

/*[clinic input]
_blake2s.blake2s.update

    obj: object
    /

Update this hash object's state with the provided string.
[clinic start generated code]*/

static PyObject *
_blake2s_blake2s_update(BLAKE2sObject *self, PyObject *obj)
/*[clinic end generated code: output=fe8438a1d3cede87 input=47a408b9a3cc05c5]*/
{
    Py_buffer buf;

    GET_BUFFER_VIEW_OR_ERROUT(obj, &buf);

#ifdef WITH_THREAD
    if (self->lock == NULL && buf.len >= HASHLIB_GIL_MINSIZE)
        self->lock = PyThread_allocate_lock();

    if (self->lock != NULL) {
       Py_BEGIN_ALLOW_THREADS
       PyThread_acquire_lock(self->lock, 1);
       blake2s_update(&self->state, buf.buf, buf.len);
       PyThread_release_lock(self->lock);
       Py_END_ALLOW_THREADS
    } else {
        blake2s_update(&self->state, buf.buf, buf.len);
    }
#else
    blake2s_update(&self->state, buf.buf, buf.len);
#endif /* !WITH_THREAD */
    PyBuffer_Release(&buf);

    Py_INCREF(Py_None);
    return Py_None;
}

/*[clinic input]
_blake2s.blake2s.digest

Return the digest value as a string of binary data.
[clinic start generated code]*/

static PyObject *
_blake2s_blake2s_digest_impl(BLAKE2sObject *self)
/*[clinic end generated code: output=80e81a48c6f79cf9 input=feb9a220135bdeba]*/
{
    uint8_t digest[BLAKE2S_OUTBYTES];
    blake2s_state state_cpy;

    ENTER_HASHLIB(self);
    state_cpy = self->state;
    blake2s_final(&state_cpy, digest, self->param.digest_length);
    LEAVE_HASHLIB(self);
    return PyBytes_FromStringAndSize((const char *)digest,
            self->param.digest_length);
}

/*[clinic input]
_blake2s.blake2s.hexdigest

Return the digest value as a string of hexadecimal digits.
[clinic start generated code]*/

static PyObject *
_blake2s_blake2s_hexdigest_impl(BLAKE2sObject *self)
/*[clinic end generated code: output=db6c5028c0a3c2e5 input=4e4877b8bd7aea91]*/
{
    uint8_t digest[BLAKE2S_OUTBYTES];
    blake2s_state state_cpy;

    ENTER_HASHLIB(self);
    state_cpy = self->state;
    blake2s_final(&state_cpy, digest, self->param.digest_length);
    LEAVE_HASHLIB(self);
    return _Py_strhex((const char *)digest, self->param.digest_length);
}

static PyMethodDef py_blake2s_methods[] = {
    _BLAKE2S_BLAKE2S_COPY_METHODDEF
    _BLAKE2S_BLAKE2S_DIGEST_METHODDEF
    _BLAKE2S_BLAKE2S_HEXDIGEST_METHODDEF
    _BLAKE2S_BLAKE2S_UPDATE_METHODDEF
    {NULL, NULL}
};

static PyObject *
py_blake2s_get_name(BLAKE2sObject *self, void *closure)
{
    return PyUnicode_FromString("blake2s");
}

static PyObject *
py_blake2s_get_block_size(BLAKE2sObject *self, void *closure)
{
    return PyLong_FromLong(BLAKE2S_BLOCKBYTES);
}

static PyObject *
py_blake2s_get_digest_size(BLAKE2sObject *self, void *closure)
{
    return PyLong_FromLong(self->param.digest_length);
}

static PyGetSetDef py_blake2s_getsetters[] = {
    {"name", (getter)py_blake2s_get_name,
        NULL, NULL, NULL},
    {"block_size", (getter)py_blake2s_get_block_size,
        NULL, NULL, NULL},
    {"digest_size", (getter)py_blake2s_get_digest_size,
        NULL, NULL, NULL},
    {NULL}
};

static void
py_blake2s_dealloc(PyObject *self)
{
    BLAKE2sObject *obj = (BLAKE2sObject *)self;

    /* Try not to leave state in memory. */
    secure_zero_memory(&obj->param, sizeof(obj->param));
    secure_zero_memory(&obj->state, sizeof(obj->state));
#ifdef WITH_THREAD
    if (obj->lock) {
        PyThread_free_lock(obj->lock);
        obj->lock = NULL;
    }
#endif
    PyObject_Del(self);
}

PyTypeObject PyBlake2_BLAKE2sType = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "_blake2.blake2s",        /* tp_name            */
    sizeof(BLAKE2sObject),    /* tp_size            */
    0,                        /* tp_itemsize        */
    py_blake2s_dealloc,       /* tp_dealloc         */
    0,                        /* tp_print           */
    0,                        /* tp_getattr         */
    0,                        /* tp_setattr         */
    0,                        /* tp_compare         */
    0,                        /* tp_repr            */
    0,                        /* tp_as_number       */
    0,                        /* tp_as_sequence     */
    0,                        /* tp_as_mapping      */
    0,                        /* tp_hash            */
    0,                        /* tp_call            */
    0,                        /* tp_str             */
    0,                        /* tp_getattro        */
    0,                        /* tp_setattro        */
    0,                        /* tp_as_buffer       */
    Py_TPFLAGS_DEFAULT,       /* tp_flags           */
    py_blake2s_new__doc__,    /* tp_doc             */
    0,                        /* tp_traverse        */
    0,                        /* tp_clear           */
    0,                        /* tp_richcompare     */
    0,                        /* tp_weaklistoffset  */
    0,                        /* tp_iter            */
    0,                        /* tp_iternext        */
    py_blake2s_methods,       /* tp_methods         */
    0,                        /* tp_members         */
    py_blake2s_getsetters,    /* tp_getset          */
    0,                        /* tp_base            */
    0,                        /* tp_dict            */
    0,                        /* tp_descr_get       */
    0,                        /* tp_descr_set       */
    0,                        /* tp_dictoffset      */
    0,                        /* tp_init            */
    0,                        /* tp_alloc           */
    py_blake2s_new,           /* tp_new             */
};


text:
import uuid

from cassandra.cqlengine import columns as cassandra_columns
from django_cassandra_engine.models import DjangoCassandraModel

class CassandraAdventuresModel(DjangoCassandraModel):
    __keyspace__ = 'db'
    adventure_id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4)
    adventure_desc = cassandra_columns.Text()
    last_modified = cassandra_columns.Date()

    class Meta:
        get_pk_field = 'adventure_id'

class CassandraAdventuresModel_M(DjangoCassandraModel):
    __keyspace__ = 'db'
    adventure_id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4)
    adventure_season_id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4)
    adventure_group_id = cassandra_columns.Integer(primary_key=True)
    adventure_type = cassandra_columns.Text()
    adventure_desc = cassandra_columns.Text()
    last_modified = cassandra_columns.DateTime()

    class Meta:
        get_pk_field = 'adventure_id'

class CassandraFamilyMember(DjangoCassandraModel):
    __keyspace__ = 'db'
    id = cassandra_columns.UUID(primary_key=True, default=uuid.uuid4)
    first_name = cassandra_columns.Text(primary_key=True)
    last_name = cassandra_columns.Text(primary_key=True)
    favourite_number = cassandra_columns.Integer(required=False)
    favourite_float_number = cassandra_columns.Float(partition_key=True)
    created_on = cassandra_columns.DateTime()

    class Meta:
        get_pk_field = 'id'


text:
errecho(){ >&2 echo $@; }

# Declare test ranges:
declare -a range_edges=$(seq 2 1 10)  #("1.25") #$(seq 3 90)  #e.g. ("44" "45")

# Declare test output location:
result_set="test_output/Edge_Results_RangeTest_"$(date -d "today" +"%Y-%m-%d_%H")"-00"
relative_result_path_from_run="exp/Evenness_Scaling/"

# Specify properties file location(s).
default_properties_filename="../../properties/default.properties"
pre_default_properties_filename=$default_properties_filename".pre-"${result_set//\//-}
post_default_properties_filename=$default_properties_filename".post-"${result_set//\//-}

function pre_test_file_organisation(){
    # Prep File Organisation & properties file backup:
    mkdir -p $result_set
    cp -n $default_properties_filename $pre_default_properties_filename
}

function post_test_file_organisation(){
    # Backup the finished properties file into $post_default_properties_filename. (ensure there's a backup)
    cp -b $default_properties_filename $post_default_properties_filename
    # Restore the original properties file: (force)
    cp -f $pre_default_properties_filename $default_properties_filename
}

function update_properties_file_output_directory(){
    # Update the run.py evaluation results directory, by modifying the default.properties file:
    python helpers/update_default-properties_file.py "DO_OVERWRITE" $default_properties_filename "results_file.results_output_file_path_prefix=" "$relative_result_path_from_run""$result_set""/"
}

function run_range_test(){
    for n in $range_edges
    do
        leds=$(python -c "x=$n;print((265*(x-1))+91);")
        echo "./run_edge_evenness_scaling_trial.sh $n $leds"
        if [ $? -ne 0 ]; then
            errecho ""; errecho " -------------- "
            errecho "./run_edge_evenness_scaling_trial.sh $n $leds failed."
            errecho "Exiting."
            exit 1;
        fi
    done
}

function main(){
    pre_test_file_organisation
    update_properties_file_output_directory
    run_range_test
    post_test_file_organisation
}

main


text:
var MessagesDetailView = require('../app/messages-detail-view');
var MessageRepository = require('../app/message-repository');
var messageFixtures = require('./message-fixtures');
var viewFixtures = require('./view-fixtures');

var $ = require('jquery');

describe('MessagesDetailView', function() {
  var $template, $sandbox, messageData, messageRepository;
  beforeEach(function() {
    $template = $(viewFixtures.detailView);
    $('body').append($template);
    $sandbox = $('

');
    $('body').append($sandbox);

    messageData = _.cloneDeep(messageFixtures);
    messageRepository = new MessageRepository(messageData);
  });
  afterEach(function() {
    $template.remove();
    $sandbox.remove();
  });

  it('renders a message', function(done) {
    var message = messageRepository.getMessageById("558070eecadb84b2cd4d5ee2");
    var messageDetailView = new MessagesDetailView($sandbox, {messageRepository: messageRepository});

    messageDetailView.render();

    messageDetailView.rendered = function() {
      expect(messageDetailView.$el.text()).toEqual("Subject 1");
      done();
    };

    messageDetailView.showMessage(message);
  });

});


text:
using System.Text;

namespace FluentAssertions.CallerIdentification;

internal class AddNonEmptySymbolParsingStrategy : IParsingStrategy
{
    private Mode mode = Mode.RemoveAllWhitespace;
    private char? precedingSymbol;

    public ParsingState Parse(char symbol, StringBuilder statement)
    {
        if (!char.IsWhiteSpace(symbol))
        {
            statement.Append(symbol);
            mode = Mode.RemoveSuperfluousWhitespace;
        }
        else if (mode is Mode.RemoveSuperfluousWhitespace)
        {
            if (precedingSymbol is char value && !char.IsWhiteSpace(value))
            {
                statement.Append(symbol);
            }
        }
        else
        {
            // skip the rest
        }

        precedingSymbol = symbol;

        return ParsingState.GoToNextSymbol;
    }

    public bool IsWaitingForContextEnd()
    {
        return false;
    }

    public void NotifyEndOfLineReached()
    {
        // Assume all new lines start with whitespace
        mode = Mode.RemoveAllWhitespace;
    }

    private enum Mode
    {
        /// <summary>
        /// Remove all whitespace until we find a non-whitespace character
        /// </summary>
        RemoveAllWhitespace,

        /// <summary>
        /// Only keep one whitespace character if more than one follow each other.
        /// </summary>
        RemoveSuperfluousWhitespace,
    }
}


text:
#ifndef mitkSimulationReader_h
#define mitkSimulationReader_h

#include <mitkBaseDataSource.h>
#include <mitkFileReader.h>
#include <SimulationExports.h>

namespace mitk
{
  class Simulation_EXPORT SimulationReader : public BaseDataSource, FileReader
  {
  public:
    static bool CanReadFile(const std::string& filename, const std::string& filePrefix, const std::string& filePattern);

    mitkClassMacro(SimulationReader, BaseDataSource);
    itkNewMacro(Self);

    const char* GetFileName() const;
    void SetFileName(const char* aFileName);

    const char* GetFilePattern() const;
    void SetFilePattern(const char* aFilePattern);

    const char* GetFilePrefix() const;
    void SetFilePrefix(const char* aFilePrefix);

    BaseDataSource::DataObjectPointer MakeOutput(DataObjectPointerArraySizeType);
    BaseDataSource::DataObjectPointer MakeOutput(const DataObjectIdentifierType& name);

  protected:
    void GenerateData();
    void GenerateOutputInformation();

  private:
    SimulationReader();
    ~SimulationReader();

    SimulationReader(const Self &);
    Self & operator=(const Self &);

    std::string m_FileName;
    std::string m_FilePattern;
    std::string m_FilePrefix;
  };
}

#endif


text:
require 'spec_helper'

# Specs in this file have access to a helper object that includes
# the SketchesHelper. For example:
#
# describe SketchesHelper do
#   describe "string concat" do
#     it "concats two strings with spaces" do
#       helper.concat_strings("this","that").should == "this that"
#     end
#   end
# end
describe SketchesHelper do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
package org.apache.geronimo.system.configuration;

import org.apache.geronimo.gbean.GBeanInfo;
import org.apache.geronimo.gbean.GBeanInfoBuilder;

public class MockGBean {

    public static final GBeanInfo GBEAN_INFO;

    private String value;
    private int port;
    private String expression;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getExpression() {
        return expression;
    }

    public void setExpression(String value) {
        this.expression = value;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public static GBeanInfo getGBeanInfo() {
        return GBEAN_INFO;
    }

    static {
        GBeanInfoBuilder infoFactory = GBeanInfoBuilder.createStatic(MockGBean.class);
        infoFactory.addAttribute("value", String.class, true);
        infoFactory.addAttribute("port", int.class, true);
        infoFactory.addAttribute("expression", String.class, true);

        GBEAN_INFO = infoFactory.getBeanInfo();
    }
}


text:
#define AMBA_UART_DR	(*(volatile unsigned char *)0x16000000)
#define AMBA_UART_LCRH	(*(volatile unsigned char *)0x16000008)
#define AMBA_UART_LCRM	(*(volatile unsigned char *)0x1600000c)
#define AMBA_UART_LCRL	(*(volatile unsigned char *)0x16000010)
#define AMBA_UART_CR	(*(volatile unsigned char *)0x16000014)
#define AMBA_UART_FR	(*(volatile unsigned char *)0x16000018)

/*
 * This does not append a newline
 */
static void putc(int c)
{
	while (AMBA_UART_FR & (1 << 5))
		barrier();

	AMBA_UART_DR = c;
}

static inline void flush(void)
{
	while (AMBA_UART_FR & (1 << 3))
		barrier();
}

/*
 * nothing to do
 */
#define arch_decomp_setup()

#define arch_decomp_wdog()


text:
package org.springframework.mobile.device.switcher;

/**
 * Abstract {@link SiteUrlFactory} implementation that differentiates each site by the
 * HTTP request path.  Provides functionality common to all path based site URL factories.
 * @author Scott Rossillo
 * @author Roy Clarkson
 */
public abstract class AbstractSitePathUrlFactory extends AbstractSiteUrlFactory implements SiteUrlFactory {

	private final String mobilePath;

	private final String tabletPath;

	private final String rootPath;

	/**
	 * Creates a new abstract site path URL factory for the given mobile path
	 * and root application path.
	 */
	public AbstractSitePathUrlFactory(final String mobilePath, final String tabletPath, final String rootPath) {
		this.mobilePath = formatPath(mobilePath);
		this.tabletPath = formatPath(tabletPath);
		this.rootPath = formatPath(rootPath);
	}

	/**
	 * The mobile path with a trailing slash.
	 *
Examples:

	 *

	 *  "/m/"
	 *  "/mobile/"
	 *

	 * @return The mobile path. May be null.
	 */
	public String getMobilePath() {
		return this.mobilePath;
	}

	/**
	 * The tablet path with a trailing slash.
	 *
Examples:

	 *

	 *  "/t/"
	 *  "/tablet/"
	 *

	 * @return The mobile path. May be null.
	 */
	public String getTabletPath() {
		return this.tabletPath;
	}

	/**
	 * The root path of the application with a trailing slash.
	 *
Examples:

	 *

	 *  "/showcase/"
	 *  "/demo/"
	 *

	 * @return The root path of the application. May be null.
	 */
	public String getRootPath() {
		return this.rootPath;
	}

	/**
	 * Whether there is a mobile path or not
	 * @return true if there is a mobile path
	 */
	public boolean hasMobilePath() {
		return this.mobilePath != null;
	}

	/**
	 * Whether there is a tablet path or not
	 * @return true if there is a tablet path
	 */
	public boolean hasTabletPath() {
		return this.tabletPath != null;
	}

	/**
	 * Whether there is a root path or not
	 * @return true if there is a root path
	 */
	public boolean hasRootPath() {
		return this.rootPath != null;
	}

	/**
	 * The full path of the normal site
	 *
Examples:

	 *

	 *  "/"
	 *  "/showcase/"
	 *  "/demo/"
	 *

	 * @see #getRootPath()
	 * @return the full path of the normal site
	 */
	public String getFullNormalPath() {
		return (this.rootPath == null ? "/" : getCleanPath(this.rootPath) + "/");
	}

	/**
	 * The full path of the mobile site.
	 *
Examples:

	 *

	 *  "/mob/"
	 *  "/showcase/m/"
	 *  "/demo/mobile/"
	 *

	 * @see #getCleanMobilePath()
	 * @return the full path of the mobile site
	 */
	public String getFullMobilePath() {
		String path = null;
		if (this.mobilePath != null) {
			path = (this.rootPath == null ? this.mobilePath : getCleanPath(this.rootPath) + this.mobilePath);
		}
		return path;
	}

	/**
	 * The full path of the tablet site.
	 *
Examples:

	 *

	 *  "/tab/"
	 *  "/showcase/t/"
	 *  "/demo/tablet/"
	 *

	 * @see #getCleanTabletPath()
	 * @return the full path of the tablet site
	 */
	public String getFullTabletPath() {
		String path = null;
		if (this.tabletPath != null) {
			path = (this.rootPath == null ? this.tabletPath : getCleanPath(this.rootPath) + this.tabletPath);
		}
		return path;
	}

	/**
	 * Returns the full normal path without a trailing slash.
	 * @see #getFullNormalPath()
	 */
	protected String getCleanNormalPath() {
		return getCleanPath(getFullNormalPath());
	}

	/**
	 * Returns the full mobile path without a trailing slash.
	 * @see #getFullMobilePath()
	 */
	protected String getCleanMobilePath() {
		return getCleanPath(getFullMobilePath());
	}

	/**
	 * Returns the full tablet path without a trailing slash.
	 * @see #getFullTabletPath()
	 */
	protected String getCleanTabletPath() {
		return getCleanPath(getFullTabletPath());
	}

	/**
	 * Returns the root path without a trailing slash.
	 * @see #getRootPath()
	 */
	protected String getCleanRootPath() {
		return getCleanPath(getRootPath());
	}

	// helpers

	private String formatPath(String path) {
		String formattedPath = null;
		if (path != null) {
			formattedPath = (path.startsWith("/") ? path : "/" + path);
			formattedPath = (formattedPath.endsWith("/") ? formattedPath : formattedPath + "/");
		}
		return formattedPath;
	}

	private String getCleanPath(String path) {
		String cleanPath = null;
		if (path != null) {
			cleanPath = path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
		}
		return cleanPath;
	}

}


text:
package org.ado.minesync.service;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import com.dropbox.sync.android.DbxAccountManager;
import com.dropbox.sync.android.DbxException;
import com.dropbox.sync.android.DbxFileSystem;
import com.dropbox.sync.android.DbxPath;
import org.ado.minesync.commons.ALog;
import org.ado.minesync.config.AppConfiguration;
import org.ado.minesync.dropbox.DbxFileQueue;
import org.ado.minesync.dropbox.WorldPathListener;
import org.ado.minesync.exception.DbxQueueException;
import org.ado.minesync.gui.notification.MineSyncNotification;
import org.ado.minesync.receiver.ScreenReceiver;

import static org.ado.minesync.config.AppConstants.*;

/**
 * Main service. Manages the synchronization of worlds and watches for the foreground app.
 *
 * @author andoni
 * @since 1.0.0
 */
public class MineSyncService extends Service {

    public static final String START_SYNC_ACTION = "org.ado.minesync.START_SYNC";
    public static final String STOP_SYNC_ACTION = "org.ado.minesync.STOP_SYNC";
    private static final String TAG = MineSyncService.class.getName();
    private static boolean watcherEnable = false;
    private final IBinder binder = new MineSyncBinder();
    private DbxAccountManager dbxAccountManager;
    private DbxFileSystem dbxFileSystem;
    private WorldPathListener worldPathListener;
    private MineSyncNotification mineSyncNotification;
    private Handler handler;
    private Runnable runnable;
    private String applicationInForeground;
    private boolean isSyncActive = false;
    private ScreenReceiver screenReceiver;

    public MineSyncService() {
        handler = new Handler();
        this.applicationInForeground = "";
    }

    @Override
    public IBinder onBind(Intent intent) {
        handler.postDelayed(runnable, 100);
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mineSyncNotification = new MineSyncNotification(this);
        worldPathListener = new WorldPathListener(getApplicationContext(), DbxPath.ROOT);
        screenReceiver = new ScreenReceiver();
        initDropboxFileSystem();
        startScreenReceiver();
        ALog.i(TAG, "Service created");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (initDbxAccountManager() && intent != null) {
            mineSyncNotification.buildNotification(isSyncActive);
            handleIntent(intent);
        }
        return START_STICKY;
    }

    @Override
    public void onLowMemory() {
        ALog.i(TAG, "onLowMemory");
        mineSyncNotification.updateSyncState(SyncStateEnum.SYNC_DISABLE);
        stopDropboxSync();
//        stopSelf();
    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        ALog.i(TAG, "onTaskRemoved - rootIntent [%s].", rootIntent);
        // this should only be notified for KitKat - workaround!
        if (isKitKat()) {
            mineSyncNotification.updateSyncState(SyncStateEnum.SYNC_DISABLE);
        }
    }

    private boolean isKitKat() {
        ALog.i(TAG, "SDK version [%d].", Build.VERSION.SDK_INT);
        boolean b = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        ALog.i(TAG, "is KitKat? [%s].", b);
        return b;
    }

    @Override
    public void onTrimMemory(int level) {
        ALog.i(TAG, "onTrimMemory - level [%d].", level);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ALog.i(TAG, "Destroying service...");
        try {
            if (this.dbxFileSystem != null) {
                DbxFileQueue.getInstance().removeAll();
                stopDropboxSync();
                stopForegroundApplicationWatcher();
                dbxAccountManager = null;
            }
            ALog.i(TAG, "Service destroyed.");
        } catch (DbxQueueException e) {
            ALog.e(TAG, e, "Cannot release file listeners");
        }
        handler.removeCallbacks(this.runnable);
        unregisterReceiver(screenReceiver);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        ALog.i(TAG, "onUnbind - stop handler.");
        handler.removeCallbacks(this.runnable);
        return super.onUnbind(intent);
    }

    private void handleIntent(Intent intent) {
        final String action = intent.getAction();
        ALog.d(TAG, "action [%s]", action);
        if (START_SYNC_ACTION.equals(action)) {
            startDropboxSync();
            startForegroundApplicationWatcher();
        } else if (STOP_SYNC_ACTION.equals(action)) {
            stopDropboxSync();
            stopForegroundApplicationWatcher();

        } else {
            boolean foregroundWatcherEnable = isForegroundWatcherEnable(intent);
            ALog.d(TAG, "foreground_watcher_enable? [%s]", foregroundWatcherEnable);
            if (foregroundWatcherEnable) {
                startForegroundApplicationWatcher();
            } else {
                stopForegroundApplicationWatcher();
            }
        }
        mineSyncNotification.updateSyncState(getState(isSyncActive, intent.getBooleanExtra(INTENT_PARAMETER_MINESYNC_UPLOADING_WORLD, false)));
    }

    private void initDropboxFileSystem() {
        try {
            if (initDbxAccountManager()) {
                try {
                    dbxFileSystem = DbxFileSystem.forAccount(dbxAccountManager.getLinkedAccount());
                    if (dbxFileSystem == null) {
                        notificationDropboxConnectionError();
                    }
                } catch (NullPointerException exception) {
                    notificationDropboxConnectionError();
                }
            } else {
                notificationDropboxConnectionError();
            }
        } catch (DbxException.Unauthorized unauthorized) {
            ALog.e(TAG, unauthorized, "Cannot access dropbox folder");
        }
    }

    private void notificationDropboxConnectionError() {
        mineSyncNotification.buildNotification(false);
        mineSyncNotification.updateSyncState(SyncStateEnum.DROPBOX_CONNECTION_ERROR);
    }

    private SyncStateEnum getState(boolean syncActive, boolean mineSyncUploading) {
        if (mineSyncUploading) {
            return SyncStateEnum.UPLOADING_DOWNLOADING;
        } else {
            return syncActive ? SyncStateEnum.SYNC_ACTIVE : SyncStateEnum.SYNC_DISABLE;
        }
    }

    private void startDropboxSync() {
        ALog.i(TAG, "Start Dropbox sync.");
        if (initDbxAccountManager() && dbxAccountManager.hasLinkedAccount() && dbxFileSystem != null) {
            worldPathListener.resume();
            dbxFileSystem.addPathListener(worldPathListener, DbxPath.ROOT, DbxFileSystem.PathListener.Mode.PATH_OR_CHILD);
            isSyncActive = true;
        } else {
            ALog.i(TAG, "Service started but not dropbox account is linked. Stopping service now.");
            mineSyncNotification.updateSyncState(SyncStateEnum.DROPBOX_CONNECTION_ERROR);
        }
    }

    private boolean initDbxAccountManager() {
        dbxAccountManager = AppConfiguration.getDropboxAccountManager(getApplicationContext());
        return dbxAccountManager != null;
    }

    private void stopDropboxSync() {
        ALog.i(TAG, "Stop Dropbox sync.");
        if (initDbxAccountManager() && dbxAccountManager.hasLinkedAccount()) {
            worldPathListener.pause();
            dbxFileSystem.removePathListenerForAll(worldPathListener);
            isSyncActive = false;
        }
    }

    private void startScreenReceiver() {
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(screenReceiver, filter);
    }

    private boolean isForegroundWatcherEnable(Intent intent) {
        return intent == null
                || intent.getBooleanExtra(INTENT_PARAMETER_FOREGROUND_WATCHER_ENABLE, false);
    }

    public void startForegroundApplicationWatcher() {
        ALog.d(TAG, "start foreground application watcher.");
        watcherEnable = true;
        runnable = createRunnable();
        handler.postDelayed(runnable, 100);
    }

    public void stopForegroundApplicationWatcher() {
        ALog.d(TAG, "stop foreground application watcher.");
        watcherEnable = false;
        handler.removeCallbacks(this.runnable);
    }

    private Runnable createRunnable() {
        return new Runnable() {
            public void run() {
                if (watcherEnable) {
                    logApplications();
                    handler.postDelayed(this, 5000);
                } else {
                    try {
                        Thread.currentThread().interrupt();
                    } catch (Exception e) {
                        // ignore
                    }
                }
            }
        };
    }

    private void logApplications() {
        ActivityManager am = (ActivityManager) super.getApplicationContext().getSystemService(Activity.ACTIVITY_SERVICE);
        String packageName = am.getRunningAppProcesses().get(0).processName;
        ALog.v(TAG, "%s     in use[%s]", packageName, applicationInForeground);
        if (!applicationInForeground.equals(packageName)) {
            notifyApplicationInUse(packageName);
            this.applicationInForeground = packageName;
        }
    }

    private void notifyApplicationInUse(String applicationInUse) {
        Intent foregroundAppIntent = new Intent(INTENT_FOREGROUND_APP);
        foregroundAppIntent.putExtra(INTENT_PARAMETER_FOREGROUND_APP, applicationInUse);
        sendBroadcast(foregroundAppIntent);
        ALog.d(TAG, "application currently in foreground [%s]", applicationInUse);
    }

    public enum SyncStateEnum {
        SYNC_ACTIVE,
        SYNC_DISABLE,
        DROPBOX_CONNECTION_ERROR,
        UPLOADING_DOWNLOADING
    }

    public class MineSyncBinder extends Binder {
        MineSyncService getService() {
            return MineSyncService.this;
        }
    }
}


text:
using namespace ::boost::multi_index;
namespace network {

struct SubSystemElement
{
    int32_t mId;
    int32_t mBindedId;
    int32_t mOrder;
    bool mEnabled;
    mutable Opt<MessageHandlerSubSystem> mSystem;
    SubSystemElement( int32_t id, int32_t mBindedId, int32_t order, bool enabled, Opt<MessageHandlerSubSystem> system );
};

class MessageHandlerSubSystemHolder : public engine::System
{
public:
    DEFINE_SYSTEM_BASE( MessageHandlerSubSystemHolder )

    void AddSubSystem( int32_t BindId, int32_t Id );
    Opt<MessageHandlerSubSystem> GetSubSystem( int32_t BindId ) const;
    Opt<MessageHandlerSubSystem> GetSubSystem( int32_t BindId );
    void SetEnabled( int32_t BindId, bool enabled );
    struct SubSystemDefaultOrderer
    {
        typedef int32_t result_type;
        result_type operator()( const SubSystemElement& system )const;
    };

    struct SubSystemIdOrderer
    {
        typedef int32_t result_type;
        result_type operator()( const SubSystemElement& system )const;
    };

    struct SubSystemBindIdOrderer
    {
        typedef int32_t result_type;
        result_type operator()( const SubSystemElement& system )const;
    };

    struct IsEnabled
    {
        typedef bool result_type;
        bool operator()( const SubSystemElement& system )const;
    };

    typedef multi_index_container <
    SubSystemElement,
    indexed_by <
    ordered_unique <
    MessageHandlerSubSystemHolder::SubSystemIdOrderer
    >,
    ordered_unique <
    MessageHandlerSubSystemHolder::SubSystemBindIdOrderer
    >,
    ordered_non_unique <
    composite_key <
    SubSystemElement,
    MessageHandlerSubSystemHolder::IsEnabled,
    MessageHandlerSubSystemHolder::SubSystemDefaultOrderer
    >
    >
    >
    > SubSystems_t;
    enum SubSystemIndex
    {
        AllById,
        AllByBindId,
        EnabledSubSystems
    };
    typedef SubSystems_t::nth_index<MessageHandlerSubSystemHolder::AllByBindId>::type BindIds_t;
    typedef SubSystems_t::nth_index<MessageHandlerSubSystemHolder::EnabledSubSystems>::type EnabledSubSystems_t;
    MessageHandlerSubSystemHolder();
    virtual ~MessageHandlerSubSystemHolder();
    virtual void Init();
    virtual void Update( double DeltaTime );
    void InitHandlers();
protected:
    SubSystems_t mSubSystems;
    MessageHandlerSubSystemFactory& mSubSystemFactory;
    MessageHolder& mMessageHolder;
    Scene& mScene;
};

typedef MessageHandlerSubSystemHolder::SubSystems_t SubSystems_t;

template<int N>
class SubSystemsFilter
{
public:
    typedef SubSystems_t::const_iterator const_iterator;
protected:
    SubSystems_t::const_iterator mI;
    SubSystems_t::const_iterator mE;
public:
    SubSystemsFilter( SubSystems_t const& systems )
    {
        mI = systems.begin();
        mE = systems.end();
    }
    const_iterator begin()
    {
        return mI;
    }
    const_iterator end()
    {
        return mE;
    }
};
template<>
class SubSystemsFilter<1>
{
public:
    typedef SubSystems_t::nth_index<1>::type BindId_t;
    typedef SubSystems_t::nth_index<1>::type::const_iterator const_iterator;
protected:
    BindId_t& mBindIds;
public:
    SubSystemsFilter( SubSystems_t& systems )
        : mBindIds( systems.get<1>() )
    {
    }
    const_iterator begin()
    {
        return mBindIds.begin();
    }
    const_iterator end()
    {
        return mBindIds.end();
    }
};

template<>
class SubSystemsFilter<2>
{
public:
    typedef SubSystems_t::nth_index<2>::type::const_iterator const_iterator;
protected:
    const_iterator mI;
    const_iterator mE;
public:
    SubSystemsFilter( SubSystems_t const& systems )
    {
        boost::tie( mI, mE ) = systems.get<2>().equal_range( boost::make_tuple( true ) );
    }
    const_iterator begin()
    {
        return mI;
    }
    const_iterator end()
    {
        return mE;
    }
};

class SubSystemEnableModifier
{
public:
    SubSystemEnableModifier( bool enabled );
    void operator()( SubSystemElement& system );
protected:
    bool mEnabled;
};

} // namespace network

#endif//INCLUDED_NETWORK_MESSAGE_HANDLER_SUB_SYSTEM_HOLDER_H