text:
/**
 * Remote data business object with intelligent cache managment.
 *
 * * Uses unify.bom.Storage for storing data between application runs.
 * * Supports HTTP-proxying for cross-domain communication
 * * Supports basic HTTP authentification
 * * Make use of modification dates to optimize data loading via GET
 */
core.Class("unify.business.RemoteData",
{
	include : [unify.business.StaticData],

	/*
	----------------------------------------------------------------------------
		 CONSTRUCTOR
	----------------------------------------------------------------------------
	*/

	// overridden
	construct : function()
	{
		// TODO: RIGHT?
		unify.business.StaticData.call(this);

		/** {Map} In-Memory Cache */
		this.__cache = {};

		/** {Map} Custom http headers */
		this.__headers = {};

		/** {String} Prefix used for storage */
		var prefix = core.String.hyphenate(this.constructor.className).toLowerCase();
		this.__storageDataPrefix = prefix + "/data/";
		this.__storageMetaPrefix = prefix + "/meta/";
		// TODO : lowland.events.EventManager.addListener(unify.bom.Storage,"quota_exceeded_err",this.__onQuotaExceeded,this);
	},

	/*
	----------------------------------------------------------------------------
		 EVENTS
	----------------------------------------------------------------------------
	*/

	events :
	{
		/**
		 * Fired whenever a communication with a service has been completed.
		 *
		 * Identify whether the event is interesting for you by the events ID property.
		 */
		"completed" : unify.business.CompletedEvent
	},

	/*
	----------------------------------------------------------------------------
		 PROPERTIES
	----------------------------------------------------------------------------
	*/

	properties :
	{
		/** Whether client-side storage should be used to keep data when app is relaunched */
		enableStorage : {
			type : "Boolean",
			init : true
		},

		/** Whether the proxy should be enabled (globally) */
		enableProxy : {
			type : "Boolean",
			init : false
		},

		/**
		 * Option for GET request to allow the request to be successful only, if the response
		 * has changed since the last request. This is done by checking the Last-Modified header.
		 */
		enableCacheRefresh : {
			type : "Boolean",
			init : true
		},

		/** Whether automatic conversion of xml format to json format should be executed */
		enableXmlConverter : {
			type : "Boolean",
			init : true
		},

		/** Whether it's OK no have no content from the service (HTTP 204 response)*/
		enableNoContent : {
			type : "Boolean",
			init : false
		},

		/** URL of proxy to fix cross domain communication */
		proxyUrl : {
			type : "String",
			init : "generic-proxy.appspot.com"
		},

		/** Request mime type */
		requestType : {
			type : ["application/x-www-form-urlencoded", "application/json", "application/xml", "text/plain", "text/javascript", "text/html" ],
			init : "application/x-www-form-urlencoded"
		},

		/** Response mime type */
		responseType : {
			type : [ "application/json", "application/xml", "text/plain", "text/javascript", "text/html" ],
			init : "application/json"
		},

		/** Time after communication should be regarded as failed (in seconds) */
		timeout : {
			type : "Integer",
			init : 10
		},

		/** Which authentication method is needed for all services */
		authMethod : {
			type : ["basic"],
			nullable : true
		},

		/** User name for authentification (basic auth) */
		user : {
			type : "String",
			nullable : true
		},

		/** Password for authentification (basic auth) */
		password : {
			type : "String",
			nullable : true
		},

		domainRequest : {
			type: "Boolean",
			init: false
		}
	},

	/*
	----------------------------------------------------------------------------
		 MEMBERS
	----------------------------------------------------------------------------
	*/

	members :
	{
		/*
		---------------------------------------------------------------------------
			OVERRIDDEN
		---------------------------------------------------------------------------
		*/

		// overridden
		_readData : function(service, params)
		{
			var entry = this.getCachedEntry(service, params);
			return entry ? entry.data : null;
		},

		/*
		---------------------------------------------------------------------------
			PUBLIC API :: CACHE
		---------------------------------------------------------------------------
		*/

		/**
		 * Returns the cache status for the given service.
		 *
		 * * 0: cache is disabled
		 * * 1: nothing cached
		 * * 2: cache is old
		 * * 3: cache is valid
		 *
		 * @param service {String} One the supported services
		 * @param params {Map?null} Optional map of params
		 * @return {Integer} Number from 0-3 ass listed above
		 */
		getCacheStatus : function(service, params)
		{
			var keep = this._getService(service).keep;
			if (!(keep > 0)) {
				return 0;
			}

			var checked = this.getCachedField(service, params, "checked");
			return checked != null ? Math.round((new Date - checked) / 1000) > keep ? 2 : 3 : 1;
		},

		/**
		 * Whether the cache is available and valid
		 *
		 * @param service {String} One the supported services
		 * @param params {Map?null} Optional map of params
		 * @return {Boolean} Whether cached data is available and valid
		 */
		isCacheValid : function(service, params) {
			return this.getCacheStatus(service, params) == 3;
		},

		/**
		 * Whether there is a cache available for the given service. This method
		 * does not check the age of the cache - just if it's available.
		 *
		 * @param service {String} One the supported services
		 * @param params {Map?null} Optional map of params
		 * @return {Boolean} Whether cached data is available
		 */
		isCached : function(service, params)
		{
			var cacheId = this.__getCacheId(service, params);
			return !!(this.__cache[cacheId] || (this.getEnableStorage() && unify.bom.Storage.get(this.__storageMetaPrefix + cacheId)));
		},

		/**
		 * Returns the value of the given field inside the cache for the given service.
		 *
		 * @param service {String} One the supported services
		 * @param params {Map?null} Optional map of params
		 * @param field {String} Any supported field name: "created", "checked", "modified" and "type"
		 * @return {String|Number} Value stored on the given field or null
		 */
		getCachedField : function(service, params, field)
		{
			var cacheId = this.__getCacheId(service, params);
			var cache = this.__cache;
			var entry = cache[cacheId];

			if (entry) {
				return entry[field] || null;
			}

			if (this.getEnableStorage())
			{
				var meta = unify.bom.Storage.get(this.__storageMetaPrefix + cacheId);
				if (meta != null)
				{
					meta = JSON.parse(meta);
					return meta[field] || null;
				}
			}

			return null;
		},

		/**
		 * Reads an entry (all data stored for the given service/param combination) from the cache.
		 *
		 * Each entry consists of
		 * the keys data and type
		 * (the data and type of data) and the timestamps created,
		 * checked and modified. There is also
		 * an id which could be used in an easy way to compare
		 * whether one have used the same version of cache entry before. This
		 * ID is updated every time new data was loaded.
		 *
		 * @param service {String} One the supported services
		 * @param params {Map?null} Optional map of params
		 * @return {Map} Returns the entry as stored in the cache.
		 */
		getCachedEntry : function(service, params)
		{
			var cacheId = this.__getCacheId(service, params);
			var cache = this.__cache;
			var entry = cache[cacheId] || null;
			if (!entry && this.getEnableStorage())
			{
				entry = unify.bom.Storage.get(this.__storageMetaPrefix + cacheId);
				if (entry)
				{
					entry = JSON.parse(entry);

					// Recover json/xml data
					var data = unify.bom.Storage.get(this.__storageDataPrefix + cacheId);
					var start;
					if (entry.type == "application/json")
					{
						start = new Date;
						data = JSON.parse(data);
						if (jasy.Env.getValue("debug")) {
							this.debug("Restored JSON in: " + (new Date - start) + "ms");
						}
					}
					else if (entry.type == "application/xml")
					{
						start = new Date;
						throw new Error("XML not supported now"); // TODO!!!
						data = xml.Document.fromString(data);
						if (jasy.Env.getValue("debug")) {
							this.debug("Recovered XML in: " + (new Date - start) + "ms");
						}
					}

					// Store data
					entry.data = data;

					// Parse timestamps
					entry.created = parseInt(entry.created, 10);
					entry.checked = parseInt(entry.checked, 10);

					// Copy over to in-memory cache
					cache[cacheId] = entry;
				}
			}

			return entry;
		},

		/**
		 * Clears the cache for the given service & param combination. Also
		 * deletes data stored on local storage.
		 *
		 * @param service {String} One the supported services
		 * @param params {Map?null} Optional map of params
		 */
		clearCache : function(service, params)
		{
			var cacheId = this.__getCacheId(service, params);
			delete this.__cache[cacheId];

			if (this.getEnableStorage())
			{
				unify.bom.Storage.remove(this.__storageMetaPrefix + cacheId);
				unify.bom.Storage.remove(this.__storageDataPrefix + cacheId);
			}
		},

		/*
		---------------------------------------------------------------------------
			PUBLIC API :: REQUESTS
		---------------------------------------------------------------------------
		*/

		/**
		 * Sends a OPTIONS request to the given service
		 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.2
		 *
		 * @param service {String} One the supported services
		 * @param params {Map?null} Optional map of params
		 * @return {String} Unique ID to identify service/param combination in the "completed" event
		 */
		options : function(service, params) {
			var id = this._getCommunicationId();
			return this._communicate(service, params, "OPTIONS", id);
		},

		/**
		 * Sends a GET request to the given service
		 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.3
		 *
		 * @param service {String} One the supported services
		 * @param params {Map?null} Optional map of params
		 * @return {String} Unique ID to identify service/param combination in the "completed" event
		 */
		get : function(service, params) {
			var id = this._getCommunicationId();
			return this._communicate(service, params, "GET", id);
		},

		/**
		 * Sends a POST request to the given service. Attaches the given data to the request.
		 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5
		 *
		 * @param service {String} One the supported services
		 * @param params {Map?null} Optional map of params
		 * @param data {var} Data to attach
		 * @return {String} Unique ID to identify service/param combination in the "completed" event
		 */
		post : function(service, params, data) {
			var id = this._getCommunicationId();
			return this._communicate(service, params, "POST", id, data);
		},

		/**
		 * Sends a PUT request to the given service
		 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.6
		 *
		 * @param service {String} One the supported services
		 * @param params {Map?null} Optional map of params
		 * @return {String} Unique ID to identify service/param combination in the "completed" event
		 */
		put : function(service, params, data) {
			var id = this._getCommunicationId();
			return this._communicate(service, params, "PUT", id, data);
		},

		/**
		 * Sends a DELETE request to the given service
		 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.7
		 *
		 * @param service {String} One the supported services
		 * @param params {Map?null} Optional map of params
		 * @return {String} Unique ID to identify service/param combination in the "completed" event
		 */
		del : function(service, params) {
			var id = this._getCommunicationId();
			return this._communicate(service, params, "DELETE", id);
		},

		/**
		 * Sends a HEAD request to the given service
		 * http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4
		 *
		 * @param service {String} One the supported services
		 * @param params {Map?null} Optional map of params
		 * @return {String} Unique ID to identify service/param combination in the "completed" event
		 */
		head : function(service, params) {
			var id = this._getCommunicationId();
			return this._communicate(service, params, "HEAD", id);
		},

		/*
		---------------------------------------------------------------------------
			PROTECTED API
		---------------------------------------------------------------------------
		*/
		/**
		 * called before caching data
		 *
		 * override this if you want to prevent caching of data based on arbitrary conditions
		 * use keep: 0 service configuration to prevent caching altogether!
		 *
		 * @param data {Var} Caching data
		 * @return {Boolean} Is caching allowed?
		 */
		_allowCaching: function(data){
			 return true;
		},

		/*
		---------------------------------------------------------------------------
			INTERNALS
		---------------------------------------------------------------------------
		*/

		/** {Map} In-Memory cache for reponse data */
		__cache : null,

		__storageDataPrefix : null,
		__storageMetaPrefix : null,

		/** {Integer} Number of requests made (used for unique request IDs) */
		__requestCounter : 0,

		/** {Map} Custom request headers */
		__headers : null,

		_getCommunicationId : function() {
			return this.__requestCounter++;
		},

		/**
		 * Returns the cache ID for the given argument set.
		 *
		 * @param service {String} One the supported services
		 * @param params {Map} Optional map of params
		 * @return {String} Cache ID
		 */
		__getCacheId : function(service, params)
		{
			if (jasy.Env.getValue("debug"))
			{
				if (service == null) {
					throw new Error("Please define at least a service name!");
				}
			}

			return params ? service + "=" + JSON.stringify(params) : service;
		},

		/**
		 * Patches the given URL to fill template fields with
		 * given params and add support for proxying of the request.
		 *
		 * @param url {String} The original URL
		 * @param params {Map?null} Optional map of params
		 * @return {String} Patched URL
		 */
		__patchUrl : function(url, params)
		{
			// Replace dynamic fields in URL
			if (params)
			{
				var value;
				for (var key in params)
				{
					value = params[key];
					if (value == "" || value == null) {
						continue;
					}

					url = url.replace("{" + key + "}", params[key]);
				}
			}

			if (url.indexOf("{") > 0) {
				throw new Error("Unresolved params in template URL: " + url);
			}

			if (this.getEnableProxy())
			{
				var match = url.match(/^(https|http):\/\//);
				if (match) {
					url = match[0] + this.getProxyUrl() + "/" + url.substring(match[0].length);
				} else if (jasy.Env.getValue("debug")) {
					throw new Error("Proxy could not be added to url: " + url);
				}
			}

			return url;
		},

		/**
		 * Sets custom request headers
		 *
		 * @param name {String} Name of header
		 * @param value {String} Value of header
		 */
		setRequestHeader : function(name, value) {
			this.__headers[name] = value;

			if(value === null){ //if no value is supplied, we delete the request header from the map
				delete this.__headers[name];
			}
		},

		/**
		 * Checks if request is marked as modified
		 *
		 * @param req {Request} Request object
		 * @return {Boolean} Whether the resource is modified
		 */
		__isModified : function(req) {
			return !(req.getStatus() === 304 || req.getResponseHeader("Last-Modified") === unify.business.SyncRegistry.get(req.getUrl()));
		},

		/**
		 * Main communication routine. Called by most developer-level APIs.
		 *
		 * @param service {String} Identifier of the service to communicate to
		 * @param params {Map?null} Optional map of parameters to patch URL with / use for filter method
		 * @param method {String} Any supported HTTP method: OPTIONS, GET, POST, PUT, DELETE and HEAD
		 * @param id {Integer} Unique id of request, can be generated via _getCommunicationId
		 * @param data {var?null} Data to attach to a POST request
		 * @return {String} Returns a unique ID based on the service/param combination
		 */
		_communicate : function(service, params, method, id, data)
		{
			var config = this._getService(service);

			var url;
			try {
				url = this.__patchUrl(config.url, params);
			}
			catch(ex)
			{
				this.warn("Unable to communicate with service: " + service);
				this.warn("Parameter/Configuration problem: " + ex);
				return false;
			}

			// Create request object
			var req = new lowland.bom.Xhr();
			req.setDomainRequest(this.getDomainRequest());
			req.setUrl(url);

			var requestHeaders = req.getRequestHeaders() || {};
			// Sync mime type
			requestHeaders.Accept = this.getResponseType();

			// Sync timeout
			req.setTimeout(this.getTimeout()*1000);

			// Enable load cache
			if (method == "GET")
			{
				req.setCache(true);
				if (this.getEnableCacheRefresh()) {
					var cacheModified = this.getCachedField(service, params, "modified");
					if (cacheModified != null) {
						unify.business.SyncRegistry.sync(url, cacheModified);
						requestHeaders["If-Modified-Since"] = cacheModified;
					} else {
						unify.business.SyncRegistry.clear(url);
						requestHeaders["If-Modified-Since"] = "Thu, 01 Jan 1970 00:00:00 GMT";
					}
				}
			}

			// Apply method
			if (method != null && method != "GET") {
				req.setMethod(method);
			}

			// Support for authentification methods
			var auth = this.getAuthMethod();
			if (auth == "basic") {
				var key = this.getEnableProxy() ? "X-Proxy-Authorization" : "Authorization";
				var value = "Basic " + lowland.util.Base64.encode(this.getUser() + ":" + this.getPassword());

				requestHeaders[key] = value;
			}

			// Add custom headers
			var headers = this.__headers;
			for (var name in headers) {
				requestHeaders[name] = headers[name];
			}

			// Add post and put data
			if (method == "POST" || method == "PUT")
			{
				var reqType = this.getRequestType();
				if (reqType == "application/json" && typeof data != "string") {
					data = JSON.stringify(data);
				}

				requestHeaders["Content-Type"] = reqType;
				req.setRequestData(data);
			}

			// Add listeners
			/*req.addListener("load", this.__onRequestDone, this);
			req.addListener("error", this.__onRequestDone, this);
			req.addListener("timeout", this.__onRequestDone, this);*/
			req.addListener("done", this.__onRequestDone, this);

			// Attach incoming data to request
			req.setUserData("service", service);
			req.setUserData("params", params);

			// Every request has a unique identifier
			req.setUserData("id", id);
			if (jasy.Env.getValue("debug")) {
				this.debug("Sending request to: " + service + "[id=" + id + "]...");
			}

			req.setRequestHeaders(requestHeaders);
			// Finally send request
			req.send();

			return id;
		},

		/**
		 * Event listener for request object
		 *
		 * @param e {lowland.events.Event} Event object of request
		 */
		__onRequestDone : function(e)
		{
			var Json = JSON;

			// Read event data
			var req = e.getTarget();
			var eventType = e.getData();
			var status = req.getStatus();
			var isErrornous = eventType == "error" || eventType == "timeout" || (status >= 400);
			var isMalformed = eventType == "timeout";

			// Read request specific data
			var id = req.getUserData("id");
			var service = req.getUserData("service");
			var params = req.getUserData("params");

			// Debug
			if (jasy.Env.getValue("debug")) {
				this.debug("Request done: " + service + "[id=" + id + "]");
			}

			var now = +new Date;
			var text = req.getResponseText();
			var start;

			// Prepare data (Parse JSON/XML)
			var isModified = !isErrornous && !isMalformed; // TODO : && this.__isModified(req);
			if (isModified)
			{
				if (jasy.Env.getValue("debug")) {
					//this.debug("Loaded: " + text.length + " bytes in " + req.getDuration() + "ms");//TODO replace getDuration
				}

				var type = this.getResponseType();
				//debugger;
				if (text.length > 0)
				{
					// data is only defined if response text is available
					// otherwise function scope data is "undefined"
					var data = text;
					switch(type)
					{
						case "application/json":
							start = new Date;
							try{
								data = Json.parse(text);
							} catch(ex){
								this.error("failed to parse json: "+ex);
								isMalformed=true;
							}
							if (jasy.Env.getValue("debug")) {
								this.debug("Parsed JSON in: " + (new Date - start) + "ms");
							}
							break;

						case "application/xml":
							data = req.getTransport().responseXML; //req.getResponseXml();
							// Modify data and modify text
							if (this.getEnableXmlConverter())
							{
								start = new Date;
								data = unify.util.XmlToJson.convert(data);
								if (jasy.Env.getValue("debug")) {
									this.debug("Converted to JSON in: " + (new Date - start) + "ms");
								}
								// Fix type as we now deal with JSON only
								type = "application/json";

								// Overwrite original text from service with stringified converted json
								start = new Date;
								text = Json.stringify(data);
								if (jasy.Env.getValue("debug")) {
									this.debug("Prepared to cache in: " + (new Date - start) + "ms");
								}
							}
							break;
					}
				}

				if (this.getEnableNoContent() && (req.getStatus() == 204 || req.getStatus() == 200))
				{
					// pass: not modified + no content
				}
				else if (!data)
				{
					this.error("Malformed data returned. Does not validate as: " + type);
					isMalformed = true;
				}
			}//TODO add else block here to handle isModified=false response? e.g. get data from cache to enrich completed event before firing it

			// Cache data
			if (!isErrornous && !isMalformed && this._getService(service).keep > 0 && this._allowCaching(data))
			{
				var cacheId = this.__getCacheId(service, params);
				var modified = req.getResponseHeader("Last-Modified");
				var cache = this.__cache;

				if (isModified)
				{
					cache[cacheId] =
					{
						id : id,
						created : now,
						checked : now,
						modified : modified,
						data : data,
						type : type
					};
				}
				else
				{
					cache[cacheId].checked = now;
				}

				// Store additionally in local storage
				if (this.getEnableStorage())
				{
					// We split the storage of the time from the other stuff for faster access
					// without parsing the whole data into objects
					var storageMetaId = this.__storageMetaPrefix + cacheId;

					if (isModified)
					{
						start = new Date;

						var metaData = Json.stringify(
						{
							id : id,
							created : now,
							checked : now,
							modified : modified,
							type : type
						});
						var metaStored=false;
						var Storage=unify.bom.Storage;
						try
						{
							Storage.set(storageMetaId, metaData);
							metaStored=true;
							var storageDataId = this.__storageDataPrefix + cacheId;
							Storage.set(storageDataId, text);
							if (jasy.Env.getValue("debug")) {
								this.debug("Stored in: " + (new Date - start) + "ms");
							}
						}
						catch(ex) {
							this.warn("Could not store data: " + ex);
							if(metaStored){
								Storage.remove(storageMetaId);
							}
						}

					}
					else
					{
						// Parse meta data, update time field, and store again
						var meta = Json.parse(unify.bom.Storage.get(storageMetaId));
						meta.checked = now;
						try{
							unify.bom.Storage.set(storageMetaId, Json.stringify(meta));
						} catch(ex) {
							this.warn("Could not store data: " + ex);
						}
					}
				}
			}

			if (!(isErrornous || isMalformed)) {
				var lastModified = req.getResponseHeader("Last-Modified");
				if (lastModified) {
					unify.business.SyncRegistry.sync(req.getUrl(), lastModified);
				}
			}

			// Fire event
      var event = unify.business.CompletedEvent.obtain("completed", id, data, isModified, isErrornous, isMalformed, req);
  		this.dispatchEvent(event);
      event.release();

			// Dispose request
			//req.dispose();
		},

		/**
		 * event handler for storage quota exceeded event.
		 * purges expired data in localStorage
		 */
		__onQuotaExceeded: function(){
			if(!window.localStorage){
				return;
			}
			var start = new Date();
			var services=this._getServices();
			for (var serviceName in services) {
				var keep = services[serviceName].keep;
				if(keep>0){
					this.__purgeCache(serviceName,start-keep*1000);
				}
			}
			if (jasy.Env.getValue("debug")){
				var end=new Date();
				this.debug('garbage collection took: '+(end-start)+'ms');
			}
		},
		/**
		 * removes localStorage entries of a service that have not been accessed within its keep time
		 *
		 * @param serviceName {String} Service name to purge cache of
		 * @param expiredWhenCheckedBefore {Integer} Last check as timestamp
		 */
		__purgeCache : function(serviceName,expiredWhenCheckedBefore) {

			var
				dataPrefix = unify.bom.Storage.prefix + this.__storageDataPrefix + serviceName,
				metaPrefix = unify.bom.Storage.prefix + this.__storageMetaPrefix + serviceName,
				metaRegExp = new RegExp("^" + metaPrefix + "(.*)"),
				matched,
				meta,
				key;
			if (jasy.Env.getValue("debug")){
				this.debug('Cached entries of service "' + serviceName + '" are expired when last checked before: ' + new Date(expiredWhenCheckedBefore));
			}
			for (key in localStorage) {
				matched = metaRegExp.exec(key);
				if (matched) {
					meta = JSON.parse(localStorage.getItem(key));
					if (meta && meta.checked && meta.checked < expiredWhenCheckedBefore) {
						if (jasy.Env.getValue("debug")){
							this.debug('*** Expired Cache Entry "' + key + '", checked: ' + new Date(meta.checked));
						}
						localStorage.removeItem(dataPrefix + matched[1]);
						localStorage.removeItem(key);
					}
				}
			}
		}

	}

	/*
	----------------------------------------------------------------------------
		 DESTRUCTOR
	----------------------------------------------------------------------------
	*/

	/*destruct : function()
	{
		// Dereference native binding
		this.__cache = null;
		Registration.removeListener(unify.bom.Storage,"quota_exceeded_err",this.__onQuotaExceeded,this);
	}*/
});


text:
<!doctype html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NexGen Learn to code app</title>

    <!-- Disable tap highlight on IE -->
    <meta name="msapplication-tap-highlight" content="no">

    <!-- Web Application Manifest -->
    <link rel="manifest" href="/manifest.json">

    <!-- Add to homescreen for Chrome on Android -->
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="application-name" content="Web Starter Kit">
    <link rel="icon" sizes="192x192" href="/images/touch/chrome-touch-icon-192x192.png">

    <!-- Add to homescreen for Safari on iOS -->
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-title" content="Web Starter Kit">
    <link rel="apple-touch-icon" href="/images/touch/apple-touch-icon.png">

    <!-- Tile icon for Win8 (144x144 + tile color) -->
    <meta name="msapplication-TileImage" content="/images/touch/ms-touch-icon-144x144-precomposed.png">
    <meta name="msapplication-TileColor" content="#2F3BA2">

    <!-- Color the status bar on mobile devices -->
    <meta name="theme-color" content="#2F3BA2">

    <!-- SEO: If your mobile URL is different from the desktop URL, add a canonical link to the desktop page https://developers.google.com/webmasters/smartphone-sites/feature-phones -->
    <!--
    <link rel="canonical" href="http://www.example.com/">
    -->

    <!-- Material Design Lite page styles:
    You can choose other color schemes from the CDN, more info here http://www.getmdl.io/customize/index.html
    Format: material.color1-color2.min.css, some examples:
    material.red-teal.min.css
    material.blue-orange.min.css
    material.purple-indigo.min.css
    -->

    <!-- Your styles -->
    <link rel="stylesheet" href="/styles/main.css">
    <link rel="stylesheet" href="/styles/material.indigo-pink.min.css">
    <link rel="stylesheet" href="/styles/codemirror.min.css">

    <script src="/scripts/vendor/webcomponents.min.js"></script>

    <link id="component-reactContainer" rel="import" href="/html/reactContainer.html">
    <link id="component-about" rel="import" href="/html/aboutApp.html" >
    <link id="component-footer" rel="import" href="/html/footer.html" >
    <link id="component-header" rel="import" href="/html/header.html" >
  </head>
  <body class="mdl-demo mdl-color--grey-100 mdl-color-text--grey-700 mdl-base">
    <div id="container" class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
      <main id="content" class="mdl-layout__content">
      </main>
    </div>

    <script src="/scripts/vendor/material.min.js"></script>
    <!-- build:js /scripts/main.min.js -->
    <script src="/scripts/main.js"></script>
    <script src="/scripts/utils/waitForComponentToLoad.js"></script>
    <script src="/scripts/components/codingWindow.js"></script>
    <script src="/scripts/components/chooseCourse.js"></script>
    <script src="/scripts/components/importWebComponents.js"></script>
    <script src="/scripts/vendor/codemirror.min.js"></script>
    <script src="/scripts/vendor/material.min.js"></script>
    <script src="/scripts/vendor/mdl-select.min.js"></script>
    <script src="/scripts/vendor/webcomponents.min.js"></script>
    <!-- endbuild -->

    <!-- Material Design icons -->
    <link rel="stylesheet" href="/styles/material-design-icons.css">
  </body>
</html>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections;

namespace SharpVectors.Dom.Css
{
	internal struct CssProperty
	{
		internal CssProperty(bool isInherited, string initialValue)
		{
			IsInherited = isInherited;
			InitialValue = initialValue;
			InitialCssValue = null;
		}
        internal bool IsInherited;
		internal string InitialValue;
		internal CssValue InitialCssValue;
	}

		public class CssPropertyProfile
		{
		#region Static fields
			private static CssPropertyProfile _svgProfile = null;
			public static CssPropertyProfile SvgProfile
			{
				get
				{
					if(_svgProfile == null)
					{
						_svgProfile = new CssPropertyProfile();
						_svgProfile.Add("alignment-baseline", false, String.Empty);
						_svgProfile.Add("baseline-shift", false, "baseline");
						_svgProfile.Add("clip", false, "auto");
						_svgProfile.Add("clip-path", false, "none");
						_svgProfile.Add("clip-rule", true, "nonzero");
						_svgProfile.Add("color", true, "black");
						_svgProfile.Add("color-interpolation", true, "sRGB");
						_svgProfile.Add("color-interpolation-filters", true, "linearRGB");
						_svgProfile.Add("color-profile", true, "auto");
						_svgProfile.Add("color-rendering", true, "auto");
						_svgProfile.Add("cursor", true, "auto");
						_svgProfile.Add("direction", true, "ltr");
						_svgProfile.Add("display", false, "inline");
						_svgProfile.Add("dominant-baseline", false, "auto");
						_svgProfile.Add("enable-background", false, "accumulate");
						_svgProfile.Add("fill", true, "black");
						_svgProfile.Add("fill-opacity", true, "1");
						_svgProfile.Add("fill-rule", true, "nonzero");
						_svgProfile.Add("filter", false, "none");
						_svgProfile.Add("flood-color", false, "black");
						_svgProfile.Add("flood-opacity", false, "1");
						_svgProfile.Add("font", true, String.Empty);
						_svgProfile.Add("font-family", true, "Arial");
						_svgProfile.Add("font-size", true, "medium");
						_svgProfile.Add("font-size-adjust", true, "none");
						_svgProfile.Add("font-stretch", true, "normal");
						_svgProfile.Add("font-style", true, "normal");
						_svgProfile.Add("font-variant", true, "normal");
						_svgProfile.Add("font-weight", true, "normal");
						_svgProfile.Add("glyph-orientation-horizontal", true, "0deg");
						_svgProfile.Add("glyph-orientation-vertical", true, "auto");
						_svgProfile.Add("image-rendering", true, "auto");
						_svgProfile.Add("kerning", true, "auto");
						_svgProfile.Add("letter-spacing", true, "normal");
						_svgProfile.Add("lighting-color", false, "white");
						_svgProfile.Add("marker", true, "none");
						_svgProfile.Add("marker-end", true, "none");
						_svgProfile.Add("marker-mid", true, "none");
						_svgProfile.Add("marker-start", true, "none");
						_svgProfile.Add("mask", false, "none");
						_svgProfile.Add("opacity", false, "1");
						_svgProfile.Add("overflow", false, "visible");
						_svgProfile.Add("pointer-events", true, "visiblePainted");
						_svgProfile.Add("shape-rendering", true, "auto");
						_svgProfile.Add("stop-color", false, "black");
						_svgProfile.Add("stop-opacity", false, "1");
						_svgProfile.Add("stroke", true, "none");
						_svgProfile.Add("stroke-dasharray", true, "none");
						_svgProfile.Add("stroke-dashoffset", true, "0");
						_svgProfile.Add("stroke-linecap", true, "butt");
						_svgProfile.Add("stroke-linejoin", true, "miter");
						_svgProfile.Add("stroke-miterlimit", true, "4");
						_svgProfile.Add("stroke-opacity", true, "1");
						_svgProfile.Add("stroke-width", true, "1");
						_svgProfile.Add("text-anchor", true, "start");
						_svgProfile.Add("text-decoration", false, "none");
						_svgProfile.Add("text-rendering", true, "auto");
						_svgProfile.Add("unicode-bidi", false, "normal");
						_svgProfile.Add("visibility", true, "visible");
						_svgProfile.Add("word-spacing", true, "normal");
						_svgProfile.Add("writing-mode", true, "lr-tb");
					}

					return _svgProfile;
				}
			}

		#endregion

			private Hashtable properties = new Hashtable();

			public CssPropertyProfile()
			{

			}

			public ICollection GetAllPropertyNames()
			{
				return properties.Keys;
			}
			public string GetInitialValue(string propertyName)
			{
				if(properties.ContainsKey(propertyName))
				{
                    return ((CssProperty)properties[propertyName]).InitialValue;
				}
				else
				{
					return null;
				}
			}

			public CssValue GetInitialCssValue(string propertyName)
			{
				if(properties.ContainsKey(propertyName))
				{
					CssProperty cssProp = (CssProperty)properties[propertyName];
					if(cssProp.InitialCssValue == null)
					{
						cssProp.InitialCssValue = CssValue.GetCssValue(cssProp.InitialValue, false);
					}
					return cssProp.InitialCssValue;
				}
				else
				{
					return null;
				}
			}

			public bool IsInherited(string propertyName)
			{
				if(properties.ContainsKey(propertyName))
				{
					return ((CssProperty)properties[propertyName]).IsInherited;
				}
				else
				{
					return true;
				}
			}

			public void Add(string propertyName, bool isInherited, string initialValue)
			{
				properties.Add(propertyName, new CssProperty(isInherited, initialValue));
			}

			public int Length
			{
				get
				{
					return properties.Count;
				}
			}

		}
	}


text:
<?php

namespace misaret\utils\storage;

/**
 * Storage engine: file
 */
class File implements \misaret\utils\StorageInterface
{
	public $localBasePath;
	public $externalBaseUri;
	/**
	 * How many sublevels.
	 * 12345.jpg -> 5/45/12345.jpg
	 *
	 * @var integer
	 */
	public $levelsCount;

	public function __construct($localBasePath, $externalBaseUri = null, $levelsCount = null)
	{
		$this->localBasePath = $localBasePath;
		$this->externalBaseUri = $externalBaseUri;
		$this->levelsCount = $levelsCount;
	}

	protected function _getLocalPart($name)
	{
		if (!$this->levelsCount) {
			return $name;
		}

		$result = [];
		$id = intval($name);
		for ($i = 0; $i < $this->levelsCount; $i++) {
			$result[] = ($id % pow(10, $i + 1));
		}
		$result[] = $name;

		return implode('/', $result);
	}

	protected function _getLocalPath($name)
	{
		return $this->localBasePath . $this->_getLocalPart($name);
	}

	public function get($name)
	{
		return file_get_contents($this->_getLocalPath($name));
	}

	public function getFile($name, $outFile)
	{
		return copy($this->_getLocalPath($name), $outFile);
	}

	public function put($name, $content, $modTime = null)
	{
		$res = file_put_contents($this->_getLocalPath($name), $content);
		if ($res && $modTime) {
			touch($this->_getLocalPath($name), $modTime);
		}

		return $res;
	}

	public function putFile($name, $inFile, $modTime = null, $fileSize = null)
	{
		$res = copy($inFile, $this->_getLocalPath($name));
		if ($res && $modTime) {
			touch($this->_getLocalPath($name), $modTime);
		}

		return $res;
	}

	public function exists($name)
	{
		return file_exists($this->_getLocalPath($name));
	}

	public function getSize($name)
	{
		return @filesize($this->_getLocalPath($name));
	}

	public function getModTime($name)
	{
		return @filemtime($this->_getLocalPath($name));
	}

	public function delete($name)
	{
		return unlink($this->_getLocalPath($name));
	}

	public function touch($name, $modTime = null)
	{
		return touch($this->_getLocalPath($name), $modTime);
	}

	public function move($name, $newName)
	{
		return rename($this->_getLocalPath($name), $this->_getLocalPath($newName));
	}

	public function getExternalUri($name)
	{
		return $this->externalBaseUri . $this->_getLocalPart($name);
	}
}


text:
namespace game {

class PathOptimizerInterface {
 public:
   // Returns all possible decisions with associated score
   // score means the loss of time (lap-wise) compared to optimal choice
   // so atleast one lane will always have value of 0
   virtual std::map<Switch, double> Score(const Position& position) = 0;

 private:
};

}  // namespace game

#endif  // CPP_GAME_PATH_OPTIMIZER_INTERFACE_H_


text:
ACCEPTED

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

#### Published in
Mycotaxon 58: 15 (1996)

#### Original name
Boidinia cana Sheng H. Wu, 1996

### Remarks
null


text:
from __future__ import unicode_literals
import inspect

import math
import time
import warnings

from django import template
from django.core.cache import cache
from django.template.base import get_library, InvalidTemplateLibrary, TemplateSyntaxError, TOKEN_BLOCK
from django.template.defaulttags import LoadNode, CommentNode, IfNode
from django.template.smartif import Literal
from django.utils.safestring import mark_safe
from django.utils.encoding import smart_text
from django.utils.html import escape
from django.utils.translation import ugettext as _
from django.utils import dateformat
from django.utils.timezone import timedelta
from django.utils.timezone import now as tznow

try:
    import pytils
    pytils_enabled = True
except ImportError:
    pytils_enabled = False

from pybb.models import TopicReadTracker, ForumReadTracker, PollAnswerUser, Topic, Post
from pybb.permissions import perms
from pybb import defaults, util

register = template.Library()

#noinspection PyUnusedLocal
@register.tag
def pybb_time(parser, token):
    try:
        tag, context_time = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError('pybb_time requires single argument')
    else:
        return PybbTimeNode(context_time)

class PybbTimeNode(template.Node):
    def __init__(self, time):
    #noinspection PyRedeclaration
        self.time = template.Variable(time)

    def render(self, context):
        context_time = self.time.resolve(context)

        delta = tznow() - context_time
        today = tznow().replace(hour=0, minute=0, second=0)
        yesterday = today - timedelta(days=1)
        tomorrow = today + timedelta(days=1)

        if delta.days == 0:
            if delta.seconds < 60:
                if pytils_enabled and context.get('LANGUAGE_CODE', '').startswith('ru'):
                    msg = _('seconds ago,seconds ago,seconds ago')
                    msg = pytils.numeral.choose_plural(delta.seconds, msg)
                else:
                    msg = _('seconds ago')
                return '%d %s' % (delta.seconds, msg)

            elif delta.seconds < 3600:
                minutes = int(delta.seconds / 60)
                if pytils_enabled and context.get('LANGUAGE_CODE', '').startswith('ru'):
                    msg = _('minutes ago,minutes ago,minutes ago')
                    msg = pytils.numeral.choose_plural(minutes, msg)
                else:
                    msg = _('minutes ago')
                return '%d %s' % (minutes, msg)
        if context['user'].is_authenticated():
            if time.daylight:
                tz1 = time.altzone
            else:
                tz1 = time.timezone
            tz = tz1 + util.get_pybb_profile(context['user']).time_zone * 60 * 60
            context_time = context_time + timedelta(seconds=tz)
        if today < context_time < tomorrow:
            return _('today, %s') % context_time.strftime('%H:%M')
        elif yesterday < context_time < today:
            return _('yesterday, %s') % context_time.strftime('%H:%M')
        else:
            return dateformat.format(context_time, 'd M, Y H:i')

@register.simple_tag
def pybb_link(object, anchor=''):
    """
    Return A tag with link to object.
    """

    url = hasattr(object, 'get_absolute_url') and object.get_absolute_url() or None
    #noinspection PyRedeclaration
    anchor = anchor or smart_text(object)
    return mark_safe('%s' % (url, escape(anchor)))

@register.filter
def pybb_topic_moderated_by(topic, user):
    """
    Check if user is moderator of topic's forum.
    """
    warnings.warn("pybb_topic_moderated_by filter is deprecated and will be removed in later releases. "
                  "Use pybb_may_moderate_topic(user, topic) filter instead",
                  DeprecationWarning)
    return perms.may_moderate_topic(user, topic)

@register.filter
def pybb_editable_by(post, user):
    """
    Check if the post could be edited by the user.
    """
    warnings.warn("pybb_editable_by filter is deprecated and will be removed in later releases. "
                  "Use pybb_may_edit_post(user, post) filter instead",
                  DeprecationWarning)
    return perms.may_edit_post(user, post)

@register.filter
def pybb_posted_by(post, user):
    """
    Check if the post is writed by the user.
    """
    return post.user == user

@register.filter
def pybb_is_topic_unread(topic, user):
    if not user.is_authenticated():
        return False

    last_topic_update = topic.updated or topic.created

    unread = not ForumReadTracker.objects.filter(
        forum=topic.forum,
        user=user.id,
        time_stamp__gte=last_topic_update).exists()
    unread &= not TopicReadTracker.objects.filter(
        topic=topic,
        user=user.id,
        time_stamp__gte=last_topic_update).exists()
    return unread

@register.filter
def pybb_topic_unread(topics, user):
    """
    Mark all topics in queryset/list with .unread for target user
    """
    topic_list = list(topics)

    if user.is_authenticated():
        for topic in topic_list:
            topic.unread = True

        forums_ids = [f.forum_id for f in topic_list]
        forum_marks = dict([(m.forum_id, m.time_stamp)
                            for m
                            in ForumReadTracker.objects.filter(user=user, forum__in=forums_ids)])
        if len(forum_marks):
            for topic in topic_list:
                topic_updated = topic.updated or topic.created
                if topic.forum.id in forum_marks and topic_updated <= forum_marks[topic.forum.id]:
                    topic.unread = False

        qs = TopicReadTracker.objects.filter(user=user, topic__in=topic_list).select_related('topic')
        topic_marks = list(qs)
        topic_dict = dict(((topic.id, topic) for topic in topic_list))
        for mark in topic_marks:
            if topic_dict[mark.topic.id].updated <= mark.time_stamp:
                topic_dict[mark.topic.id].unread = False
    return topic_list

@register.filter
def pybb_forum_unread(forums, user):
    """
    Check if forum has unread messages.
    """
    forum_list = list(forums)
    if user.is_authenticated():
        for forum in forum_list:
            forum.unread = forum.topic_count > 0
        forum_marks = ForumReadTracker.objects.filter(
            user=user,
            forum__in=forum_list
        ).select_related('forum')
        forum_dict = dict(((forum.id, forum) for forum in forum_list))
        for mark in forum_marks:
            curr_forum = forum_dict[mark.forum.id]
            if (curr_forum.updated is None) or (curr_forum.updated <= mark.time_stamp):
                if not any((f.unread for f in pybb_forum_unread(curr_forum.child_forums.all(), user))):
                    forum_dict[mark.forum.id].unread = False
    return forum_list

@register.filter
def pybb_topic_inline_pagination(topic):
    page_count = int(math.ceil(topic.post_count / float(defaults.PYBB_TOPIC_PAGE_SIZE)))
    if page_count <= 5:
        return range(1, page_count+1)
    return range(1, 5) + ['...', page_count]

@register.filter
def pybb_topic_poll_not_voted(topic, user):
    return not PollAnswerUser.objects.filter(poll_answer__topic=topic, user=user).exists()

@register.filter
def endswith(str, substr):
    return str.endswith(substr)

@register.assignment_tag
def pybb_get_profile(*args, **kwargs):
    try:
        return util.get_pybb_profile(kwargs.get('user') or args[0])
    except:
        return util.get_pybb_profile_model().objects.none()

@register.assignment_tag(takes_context=True)
def pybb_get_latest_topics(context, cnt=5, user=None):
    qs = Topic.objects.all().order_by('-updated', '-created', '-id')
    if not user:
        user = context['user']
    qs = perms.filter_topics(user, qs)
    return qs[:cnt]

@register.assignment_tag(takes_context=True)
def pybb_get_latest_posts(context, cnt=5, user=None):
    qs = Post.objects.all().order_by('-created', '-id')
    if not user:
        user = context['user']
    qs = perms.filter_posts(user, qs)
    return qs[:cnt]

def load_perms_filters():
    def partial(func_name, perms_obj):
        def newfunc(user, obj):
            return getattr(perms_obj, func_name)(user, obj)
        return newfunc

    def partial_no_param(func_name, perms_obj):
        def newfunc(user):
            return getattr(perms_obj, func_name)(user)
        return newfunc

    for method in inspect.getmembers(perms):
        if inspect.ismethod(method[1]) and inspect.getargspec(method[1]).args[0] == 'self' and\
                (method[0].startswith('may') or method[0].startswith('filter')):
            if len(inspect.getargspec(method[1]).args) == 3:
                register.filter('%s%s' % ('pybb_', method[0]), partial(method[0], perms))
            elif len(inspect.getargspec(method[1]).args) == 2: # only user should be passed to permission method
                register.filter('%s%s' % ('pybb_', method[0]), partial_no_param(method[0], perms))
load_perms_filters()

# next two tags copied from https://bitbucket.org/jaap3/django-friendly-tag-loader

@register.tag
def friendly_load(parser, token):
    """
    Tries to load a custom template tag set. Non existing tag libraries
    are ignored.

    This means that, if used in conjuction with ``if_has_tag``, you can try to
    load the comments template tag library to enable comments even if the
    comments framework is not installed.

    For example::

        {% load friendly_loader %}
        {% friendly_load comments webdesign %}

        {% if_has_tag render_comment_list %}
            {% render_comment_list for obj %}
        {% else %}
            {% if_has_tag lorem %}
                {% lorem %}
            {% endif_has_tag %}
        {% endif_has_tag %}
    """
    bits = token.contents.split()
    for taglib in bits[1:]:
        try:
            lib = get_library(taglib)
            parser.add_library(lib)
        except InvalidTemplateLibrary:
            pass
    return LoadNode()

@register.tag
def if_has_tag(parser, token):
    """
    The logic for both ``{% if_has_tag %}`` and ``{% if not_has_tag %}``.

    Checks if all the given tags exist (or not exist if ``negate`` is ``True``)
    and then only parses the branch that will not error due to non-existing
    tags.

    This means that the following is essentially the same as a
    ``{% comment %}`` tag::

      {% if_has_tag non_existing_tag %}
          {% non_existing_tag %}
      {% endif_has_tag %}

    Another example is checking a built-in tag. This will alway render the
    current year and never FAIL::

      {% if_has_tag now %}
          {% now \"Y\" %}
      {% else %}
          FAIL
      {% endif_has_tag %}
    """
    bits = list(token.split_contents())
    if len(bits) < 2:
        raise TemplateSyntaxError("%r takes at least one arguments" % bits[0])
    end_tag = 'end%s' % bits[0]
    has_tag = all([tag in parser.tags for tag in bits[1:]])
    nodelist_true = nodelist_false = CommentNode()
    if has_tag:
        nodelist_true = parser.parse(('else', end_tag))
        token = parser.next_token()
        if token.contents == 'else':
            parser.skip_past(end_tag)
    else:
        while parser.tokens:
            token = parser.next_token()
            if token.token_type == TOKEN_BLOCK and token.contents == end_tag:
                try:
                    return IfNode([(Literal(has_tag), nodelist_true),
                                   (None, nodelist_false)])
                except TypeError:  # < 1.4
                    return IfNode(Literal(has_tag), nodelist_true, nodelist_false)
            elif token.token_type == TOKEN_BLOCK and token.contents == 'else':
                break
        nodelist_false = parser.parse((end_tag,))
        token = parser.next_token()
    try:
        return IfNode([(Literal(has_tag), nodelist_true),
                       (None, nodelist_false)])
    except TypeError:  # < 1.4
        return IfNode(Literal(has_tag), nodelist_true, nodelist_false)

@register.filter
def pybbm_calc_topic_views(topic):
    cache_key = util.build_cache_key('anonymous_topic_views', topic_id=topic.id)
    return topic.views + cache.get(cache_key, 0)


text:
from paramiko.ssh_exception import SSHException
from paramiko.ssh_exception import AuthenticationException

class NetMikoTimeoutException(SSHException):
    '''
    SSH session timed trying to connect to the device

    Based on Paramiko SSHException
    '''
    pass

class NetMikoAuthenticationException(AuthenticationException):
    '''
    SSH authentication exception based on Paramiko AuthenticationException
    '''
    pass


text:
<!DOCTYPE html>

<html>
	<head>
    <meta charset="utf-8" />
	    <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="shortcut icon" type="image/png" href="../../../external/jasmine/jasmine_favicon.png">

	    <title>gsoft.js widgets library tests</title>

        <!--Dependent frameworks / librairies -->
        <script src="../../../external/core/jquery-1.11.2.js" type="text/javascript"></script>

        <!-- Jasmine -->
        <link href="../../../external/jasmine/jasmine.css" rel="stylesheet" type="text/css" />
        <script src="../../../external/jasmine/jasmine.js" type="text/javascript"></script>
	    <script src="../../../external/jasmine/jasmine-html.js" type="text/javascript"></script>
	    <script src="../../../external/jasmine/boot.js" type="text/javascript"></script>

        <!-- GSoft libraries -->
	    <script src="../../../dist/core/gsoft.js" type="text/javascript"></script>
	    <script src="../../../dist/core/widgets/gsoft.widgets.notifier.js" type="text/javascript"></script>

	    <!-- Tests helpers -->
        <script src="../../helpers.js" type="text/javascript"></script>

	    <!-- Specifications -->
        <script src="../../specifications/core.widgets.specifications.js" type="text/javascript"></script>

        <!-- Phantom -->
        <script src="../../phantom/reporter.console.js" type="text/javascript"></script>
        <script src="../../phantom/reporter.teamcity.js" type="text/javascript"></script>
        <script src="../../phantom/reporter.visualstudio.js" type="text/javascript"></script>
        <script src="../../phantom/setup.js" type="text/javascript"></script>
	</head>
	<body>
	</body>
</html>


text:
<?php

namespace PiggyBox\ShopBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * Menu
 *
 * @ORM\Table(name="piggybox_menu")
 * @Gedmo\SoftDeleteable(fieldName="deletedAt")
 * @ORM\Entity()
 */
class Menu
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255)
     */
    private $title;

    /**
     * @var \DateTime
     *
     * @Gedmo\Timestampable(on="create")
     * @ORM\Column(name="createdAt", type="datetime")
     */
    private $createdAt;

    /**
     * @var \DateTime
     *
     * @Gedmo\Timestampable(on="update")
     * @ORM\Column(name="updatedAt", type="datetime")
     */
    private $updatedAt;

    /**
     * @var float
     *
     * @ORM\Column(name="price", type="float")
     */
    private $price;

    /**
     * @var integer
     *
     * @ORM\Column(name="stepsNumber", type="integer")
     */
    private $stepsNumber;

    /**
     * @var string $slug
     *
     * @Gedmo\Slug(fields={"title"})
     * @ORM\Column(length=255, unique=true)
     */
    private $slug;

    /**
     * @ORM\ManyToOne(targetEntity="PiggyBox\ShopBundle\Entity\Shop")
     * @ORM\JoinColumn(name="shop_id", referencedColumnName="id")
     **/
    private $shop;

    /**
     * @ORM\OneToMany(targetEntity="PiggyBox\ShopBundle\Entity\MenuItem", mappedBy="menu", cascade={"persist"})
     **/
    private $menuItems;

    /**
     * @ORM\Column(name="deletedAt", type="datetime", nullable=true)
     */
    private $deletedAt;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param  string $title
     * @return Menu
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Set price
     *
     * @param  float $price
     * @return Menu
     */
    public function setPrice($price)
    {
        $this->price = $price;

        return $this;
    }

    /**
     * Get price
     *
     * @return float
     */
    public function getPrice()
    {
        return $this->price;
    }

    /**
     * Set shop
     *
     * @param  \PiggyBox\ShopBundle\Entity\Shop $shop
     * @return Menu
     */
    public function setShop(\PiggyBox\ShopBundle\Entity\Shop $shop = null)
    {
        $this->shop = $shop;

        return $this;
    }

    /**
     * Get shop
     *
     * @return \PiggyBox\ShopBundle\Entity\Shop
     */
    public function getShop()
    {
        return $this->shop;
    }

    /**
     * Set createdAt
     *
     * @param  \DateTime $createdAt
     * @return Menu
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Set updatedAt
     *
     * @param  \DateTime $updatedAt
     * @return Menu
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Set stepsNumber
     *
     * @param  integer $stepsNumber
     * @return Menu
     */
    public function setStepsNumber($stepsNumber)
    {
        $this->stepsNumber = $stepsNumber;

        return $this;
    }

    /**
     * Get stepsNumber
     *
     * @return integer
     */
    public function getStepsNumber()
    {
        return $this->stepsNumber;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->menuItems = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add menuItems
     *
     * @param  \PiggyBox\ShopBundle\Entity\MenuItem $menuItems
     * @return Menu
     */
    public function addMenuItem(\PiggyBox\ShopBundle\Entity\MenuItem $menuItems)
    {
        $this->menuItems[] = $menuItems;

        return $this;
    }

    /**
     * Remove menuItems
     *
     * @param \PiggyBox\ShopBundle\Entity\MenuItem $menuItems
     */
    public function removeMenuItem(\PiggyBox\ShopBundle\Entity\MenuItem $menuItems)
    {
        $this->menuItems->removeElement($menuItems);
    }

    /**
     * Get menuItems
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getMenuItems()
    {
        return $this->menuItems;
    }

    /**
     * Set slug
     *
     * @param  string $slug
     * @return Menu
     */
    public function setSlug($slug)
    {
        $this->slug = $slug;

        return $this;
    }

    /**
     * Get slug
     *
     * @return string
     */
    public function getSlug()
    {
        return $this->slug;
    }

    /**
     * Set deletedAt
     *
     * @param  \DateTime $deletedAt
     * @return Menu
     */
    public function setDeletedAt($deletedAt)
    {
        $this->deletedAt = $deletedAt;

        return $this;
    }

    /**
     * Get deletedAt
     *
     * @return \DateTime
     */
    public function getDeletedAt()
    {
        return $this->deletedAt;
    }
}


text:
============
Rocket Snake
============
.. image:: https://readthedocs.org/projects/rocket-snake/badge/?version=latest
    :target: http://rocket-snake.readthedocs.io/en/latest/?badge=latest
    :alt: Documentation Status

.. image:: https://travis-ci.org/Drummersbrother/rocket-snake.svg?branch=master
    :target: https://travis-ci.org/Drummersbrother/rocket-snake
    :alt: Travis Continuous Integration Status

A python async API client for the https://rocketleaguestats.com/ api.
Get an api key here_.
    .. _here: https://developers.rocketleaguestats.com/
------
Status
------
Stable and supports all the RLS features.

--------------
Documentation?
--------------

Check the docs_ directory or read the online documentation on readthedocs_.
    .. _docs: https://github.com/Drummersbrother/rocket-snake/tree/master/docs
    .. _readthedocs: http://rocket-snake.readthedocs.io/

.. image:: https://github.com/Drummersbrother/rocket-snake/raw/master/rls_partner_horizontal_large.png
    :target: https://github.com/Drummersbrother/rocket-snake/raw/master/rls_partner_horizontal_large.png
    :alt: This app uses data provided by Rocket League Stats.


text:
cdb.admin.CartoDBLayer = cdb.geo.CartoDBLayer.extend({
  MAX_HISTORY: 5,
  MAX_HISTORY_QUERY: 5,
  MAX_HISTORY_TILE_STYLE: 5,

  initialize: function() {
    this.sync = _.debounce(this.sync, 1000);
    this.error = false;

    this.set('use_server_style', true);

    this.initHistory('query');
    this.initHistory('tile_style');

    this.table = new cdb.admin.CartoDBTableMetadata({
      id: this.get('table_name')
    });

    this.infowindow = new cdb.geo.ui.InfowindowModel({
      template_name:  'infowindow_light'
    });

    this.tooltip = new cdb.geo.ui.InfowindowModel({
      template_name:  'tooltip_light'
    });

    var wizard_properties = this.get('wizard_properties');

    this.wizard_properties = new cdb.admin.WizardProperties(_.extend({},
      wizard_properties, {
        table: this.table,
        layer: this
      }
    ));

    //this.wizard_properties.properties(wizard_properties);

    this.wizard_properties.bind('change:type', this._manageInteractivity, this);

    this.legend = new cdb.geo.ui.LegendModel();

    // Bindings
    this.bind('change:table_name', function() {
      this.table.set('id', this.get('table_name')).fetch();
    }, this);

    // schema changes should affect first to infowindow, tooltip
    // and legend before table
    this.bindInfowindow(this.infowindow, 'infowindow');
    this.bindInfowindow(this.tooltip, 'tooltip');
    this.bindLegend(this.legend);
    this.bindTable(this.table);

    this.tooltip.bind('change:fields', this._manageInteractivity, this);

    if (this.get('table')) {
      table_attr = this.get('table');
      delete this.attributes.table;
      this.table.set(table_attr);
    }
    if (!this.isTableLoaded()) {
      this.table.fetch();
    }
  },

  isTableLoaded: function() {
    return this.table.get('id') && this.table.get('privacy');
  },

  getLayerDef: function() {
    var attr = this.attributes;
    var query = attr.query || "select * from " + attr.table_name;
    if(attr.query_wrapper) {
      query = _.template(attr.query_wrapper)({ sql: query });
    }
    return {
      type: 'cartodb',
      options: {
        sql: query,
        cartocss: this.get('tile_style'),
        cartocss_version: '2.1.1',
        interactivity: this.get('interactivity')
      }
    }
  },

  toLayerGroup: function() {
    var attr = _.clone(this.attributes);
    attr.layer_definition = {
      version:'1.0.1',
      layers: [this.getLayerDef()]
    };
    attr.type = 'layergroup'
    return attr;
  },

  /**
   * Initializes the history if it doesn't exits and sets the position pointer to 0
   * @param  {string} property
   */
  initHistory: function(property) {
    if(!this.get(property+'_history')) {
      this.set(property+'_history', []);
    }
    this[property+'_history_position'] = 0;
    this[property+'_storage'] = new cdb.admin.localStorage(property+'_storage_'+this.get('table_name'));
  },
  /**
   * Add a value to the property history if it's not the same than the last one
   * @param {string} property
   * @param {string} value
   */
  addToHistory: function(property, value) {
    if(value != this.get(property+'_history')[this.get(property+'_history').length - 1]) {
      this.get(property+'_history').push(value);
      this.trimHistory(property);
      this[property+'_history_position'] = this.get(property+'_history').length - 1;
    }
  },
  /**
   * Trim the history array to make sure its length isn't over MAX_HISTORY
   * @param  {String} property [description]
   */
  trimHistory: function(property) {
    var limit = this['MAX_HISTORY_'+property.toUpperCase()] ?
      this['MAX_HISTORY_'+property.toUpperCase()] :
      this.MAX_HISTORY;
    while(this.get(property+'_history').length > limit) {
      var removedValue = this.get(property+'_history').splice(0,1);
      this[property+'_storage'].add(removedValue[0]);
    }
  },
  /**
   * Moves the history position pointer n positions and notify that the property needs to be refreshed on views
   * @param  {String} property
   * @param  {Integer} n
   */
  moveHistoryPosition: function(property, n) {
      var newPosition = this[property+'_history_position'] + n;
    if(newPosition >= 0 && newPosition < this.get(property+'_history').length) {
      this[property+'_history_position'] = newPosition;
    } else {
      if(newPosition < 0 && Math.abs(newPosition) <= this[property+'_storage'].get().length) {
        this[property+'_history_position'] = newPosition;
      }
    }
  },
  /**
   * returns the value saved on the position of the current _history_position, either from memory of from localStorage
   * @param  {String} property
   * @return {String}
   */
  getCurrentHistoryPosition: function(property) {
    var currentPosition = this[property+'_history_position'];
    if(this[property+'_history_position'] >= 0) {
      return this.get(property+'_history')[currentPosition];
    } else {
      if(Math.abs(currentPosition) <= this[property+'_storage'].get().length) {

        return this[property+'_storage'].get(this[property+'_storage'].get().length - Math.abs(currentPosition));
      } else {
        return this.get(property+'_history')[0]
      }
    }

  },
  /**
   * Advances by one the history_position and returns the value saved on that pos
   * @param  {String} property
   * @return {String}
   */
  redoHistory: function(property) {
    this.moveHistoryPosition(property, 1);
    return this.getCurrentHistoryPosition(property);
  },
  /**
   * Reduces by one the history_position and returns the value saved on that pos
   * @param  {String} property
   * @return {String}
   */
  undoHistory: function(property) {
    var h = this.getCurrentHistoryPosition(property);
    this.moveHistoryPosition(property, -1);
    return h;
  },

  isHistoryAtLastPosition: function(property) {
    if(this.get(property+'_history').length === 0) {
      return true;
    }
    return ((this.get(property+'_history').length-1) == this[property+'_history_position']);
  },

  isHistoryAtFirstPosition: function(property) {
    if(this.get(property+'_history').length === 0) {
      return true;
    }
    var stored = this[property+'_storage'].get();
    if(stored && stored.length === 0) {
      if(this[property+'_history_position'] === 0) {
        return true;
      }
    } else {
      var storedSize = stored ? 1*stored.length : 0;
      var minimumPos = -1* storedSize;
      return (minimumPos == this[property+'_history_position']);
    }
    return false;
  },

  clone: function() {
    var attr = _.clone(this.attributes);
    delete attr.id;
    attr.table = this.table.toJSON();
    return new cdb.admin.CartoDBLayer(attr);
  },

  toJSON: function() {
    var c = _.clone(this.attributes);
    // remove api key
    if(c.extra_params) {
      c.extra_params = _.clone(this.attributes.extra_params);
      if(c.extra_params.api_key) {
        delete c.extra_params.api_key;
      }
      if(c.extra_params.map_key) {
        delete c.extra_params.map_key;
      }
    }

    delete c.infowindow;
    delete c.tooltip;
    c.wizard_properties = this.wizard_properties.toJSON();
    c.legend = this.legend.toJSON();
    var d = {
      // for some reason backend does not accept cartodb as layer type
      kind: c.type.toLowerCase() === 'cartodb' ? 'carto': c.type,
      options: c,
      order: c.order,
      infowindow: null,
      tooltip: this.tooltip.toJSON()
    };

    // Don't send infowindow data if wizard doesn't support it
    // It will make the tiler fails
    if (this.wizard_properties.supportsInteractivity()) {
      d.infowindow = this.infowindow.toJSON();
    }

    if(c.id !== undefined) {
      d.id = c.id;
    }
    return d;
  },

  parse: function(data, xhr) {
    var c = {};
    // in case this is a response of saving the layer discard
    // values from the server
    if (!data || this._saving && !this.isNew()) {
      return c;
    }

    // if api_key exist alread, set in params to not lose it
    if(data.options.extra_params && this.attributes && this.attributes.extra_params) {
      data.options.extra_params.map_key = this.attributes.extra_params.map_key;
    }

    var attrs = this.attributes;
    var wp = attrs && attrs.wizard_properties;

    if(wp && wp.properties && wp.properties.metadata) {
      if (data.options.wizard_properties && data.options.wizard_properties.properties) {
        data.options.wizard_properties.properties.metadata = wp.properties.metadata;
      }
    }

    if (this.wizard_properties && data.options.wizard_properties) {
      this.wizard_properties.properties(data.options.wizard_properties);
    }

    _.extend(c, data.options, {
      id: data.id,
      type: data.kind === 'carto' ? 'CartoDB': data.kind,
      infowindow: data.infowindow,
      tooltip: data.tooltip,
      order: data.order,
      parent_id: data.parent_id
    });

    return c;
  },

  sync: function(method, model, options) {
    if(method != 'read') {
      options.data =  JSON.stringify(model.toJSON());
    }
    options.contentType = 'application/json';
    options.url = model.url();
    return Backbone.syncAbort(method, this, options);
  },

  unbindSQLView: function(sqlView) {
    this.sqlView.unbind(null, null, this);
    this.sqlView = null;
  },

  getCurrentState: function() {
    if (this.error) {
      return "error";
    }
    return "success";
  },

  bindSQLView: function(sqlView) {
    var self = this;
    this.sqlView = sqlView;
    this.sqlView.bind('error', this.errorSQLView, this);

    // on success and no modify rows save the query!
    this.sqlView.bind('reset', function() {
      // if the query was cleared while fetchin the data
      if (!self.table.isInSQLView()) return;
      self.error = false;
      if(self.sqlView.modify_rows) {
        self.set({ query: null });
        self.invalidate();
        self.table.useSQLView(null, { force_data_fetch: true });
        self.trigger('clearSQLView');
      } else {
        self.save({
          query: sqlView.getSQL(),
          sql_source: sqlView.sqlSource()
        });
      }
    }, this);

    // Set sql view if query was applied
    var sql = this.get('query');
    if (sql) {
      this.applySQLView(sql, { add_to_history: false });
    } else {
      this.table.data().fetch();
    }
  },

  bindTable: function(table) {
    this.table = table;
    var self = this;
    self.table.bind('change:name', function() {
      if (self.get('table_name') != self.table.get('name')) {
        self.fetch({
          success: function() {
            self.updateCartoCss(self.table.previous('name'), self.table.get('name'));
          }
        });
      }
    });

    this.table.bind('change:schema', this._manageInteractivity, this);
  },

  _manageInteractivity: function() {
    var interactivity = null;
    if (this.wizard_properties.supportsInteractivity()) {
      if(this.table.containsColumn('cartodb_id')) {
        interactivity = ['cartodb_id'];
      }
      var tooltipColumns = this.tooltip.getInteractivity();
      if (tooltipColumns.length) {
        interactivity = (interactivity || []).concat(tooltipColumns);
      }
      if (interactivity) {
        interactivity = interactivity.join(',');
      }
    }
    if(this.get('interactivity') !== interactivity) {
      if (this.isNew()) {
        this.set({ interactivity: interactivity });
      } else {
        this.save({ interactivity: interactivity });
      }
    }
  },

  /**
   * Updates the style chaging the table name for a new one
   * @param  {String} previousName
   * @param  {String} newName
   */
  updateCartoCss: function(previousName, newName) {
    var tileStyle = this.get('tile_style');
    if (!tileStyle) return;
    var replaceRegexp = new RegExp('#'+previousName, 'g');
    tileStyle = tileStyle.replace(replaceRegexp, '#'+newName);
    this.save({'tile_style': tileStyle});
  },

  bindLegend: function(legend) {

    var data = this.get('legend');

    if (data) {
      this.legend.set(data);
    }

    this.legend.bind('change:template change:type change:title change:show_title change:items', _.debounce(function() {
      // call with silent so the layer is no realoded
      // if some view needs to be changed when the legend is changed it should be
      // subscribed to the legend model not to dataLayer
      // (which is only a data container for the legend)
      if (!this.isNew()) {
        this.save(null, { silent: true });
      }
    }, 250), this);

  },

  bindInfowindow: function(infowindow, attr) {
    attr = attr || 'infowindow';
    var infowindowData = this.get(attr);
    if(infowindowData) {
      infowindow.set(infowindowData);
    } else {
      // assign a position from start
      var pos = 0;
      _(this.table.get('schema')).each(function(v) {
        if(!_.contains(['the_geom', 'created_at', 'updated_at', 'cartodb_id'], v[0])) {
          infowindow.addField(v[0], pos);
          ++pos;
        }
      });
    }

    this.table.linkToInfowindow(infowindow);

    var watchedFields = 'change:fields change:template_name change:alternative_names change:template change:disabled change:width change:maxHeight';
    var deferredSave = _.debounce(function() {
      // call with silent so the layer is no realoded
      // if some view needs to be changed when infowindow is changed it should be
      // subscribed to infowindow model not to dataLayer
      // (which is only a data container for infowindow)

      // since removeMissingFields changes fields, unbind changes temporally
      infowindow.unbind(watchedFields, deferredSave, this);
      // assert all the fields are where they should
      infowindow.removeMissingFields(this.table.columnNames());
      infowindow.bind(watchedFields, deferredSave, this);
      if (!this.isNew()) {
        this.save(null, { silent: true });
      }
    }, 250);

    infowindow.bind(watchedFields, deferredSave, this);
  },

  resetQuery: function() {
    if (this.get('query')) {
      this.save({
        query: undefined,
        sql_source: null
      });
    }
  },

  errorSQLView: function(m, e) {
    this.save({ query: null }, { silent: true });
    this.trigger('errorSQLView', e);
    this.error = true;
  },

  clearSQLView: function() {
    // before reset query we should remove the view
    this.table.useSQLView(null);
    this.addToHistory("query", "SELECT * FROM " + this.table.get('name'));
    // undo history to move backwards the history pointer
    this.undoHistory("query");
    this.resetQuery();
    this.trigger('clearSQLView');
  },

  applySQLView: function(sql, options) {
    options = options || {
      add_to_history: true,
      sql_source: null
    };
    // if the sql change the table data do not save in the data layer
    // pass though and launch the query directly to the table
    this.table.useSQLView(this.sqlView);
    this.sqlView.setSQL(sql, {
      silent: true,
      sql_source: options.sql_source || null
    });
    if(options.add_to_history) {
      this.addToHistory("query", sql);
    }
    // if there is some error the query is rollbacked
    this.sqlView.fetch();
    this.trigger('applySQLView', sql);
  },

  moveToFront: function(opts) {
    this.save({
      'order': this.collection.last().get('order') + 1
    }, opts);
  },

  //save: Backbone.saveAbort

}, {

  createDefaultLayerForTable: function(tableName, userName) {
    return new cdb.admin.CartoDBLayer({
      user_name: userName,
      table_name: tableName,
      tile_style: "#" + tableName + cdb.admin.CartoStyles.DEFAULT_GEOMETRY_STYLE,
      style_version: '2.1.0',
      visible: true,
      interactivity: 'cartodb_id',
      sql_api_domain: cdb.config.get('sql_api_domain'),
      sql_api_endpoint: cdb.config.get('sql_api_endpoint'),
      sql_api_port: cdb.config.get('sql_api_port'),
      tiler_domain: cdb.config.get('tiler_domain'),
      tiler_port: cdb.config.get('tiler_port'),
      no_cdn: true
    });
  }

});


text:
class AddUserIdToProfile < ActiveRecord::Migration[5.0]
  def change
    add_column :profiles, :user_id, :integer
  end
end


text:
#include "spdif_fifo.h"

static _SPDIF_FIFO_t pstFifoHandle;

/**************************************************************************
*  FUNCTION NAME :
*      void SPDIF_FIFO_InitBuffer(unsigned int size, unsigned char* ptrBuffer );
*
*  DESCRIPTION :
*  INPUT:
*  OUTPUT:	void - Return Type
*  REMARK  :
**************************************************************************/
void SPDIF_FIFO_InitBuffer(unsigned int size, unsigned char* ptrBuffer )
{
	int i;

 	pstFifoHandle.ptrBuffer = ptrBuffer;
	pstFifoHandle.uiMaxSize = size;

	pstFifoHandle.ReadBufPtr = 0;
	pstFifoHandle.WriteBufPtr = 0;
	pstFifoHandle.ReadFrmIdx = 0;
	pstFifoHandle.WriteFrmIdx = 0;

	pstFifoHandle.IdxNum = SPDIF_FIFO_FRAME_NUM;
 	pstFifoHandle.fState = SPDIF_FIFO_EMPTY;

	memset(ptrBuffer, 0, size);
	for( i=0 ; i < SPDIF_FIFO_FRAME_NUM ; i++ )
		memset(&pstFifoHandle.stFrameInfo[i], 0, sizeof(_SPDIF_FIFO_FRAME_t) );
}

/**********************************************************
*
*	Function of	SPDIF_FIFO_GetLength
*
*	Input	:
*	Output	:
*	Return	:
*
*	Description	: data°¡ Á¸Àç ÇÏ´Â FIFOÀÇ ¼ö¸¦ ¸®ÅÏ ÇÔ.
**********************************************************/
int SPDIF_FIFO_GetLength(void)
{
	int lRemainSize = 0;
	unsigned int	uiTail, uiHead;

	uiTail = pstFifoHandle.ReadFrmIdx;
	uiHead = pstFifoHandle.WriteFrmIdx;
	if(pstFifoHandle.fState != SPDIF_FIFO_EMPTY)
	{
		if( uiTail < uiHead )	//	Tail  < 	Head
		{
			 lRemainSize = uiHead - uiTail;
		}
		else
		{
			lRemainSize = (pstFifoHandle.IdxNum - uiTail) +  uiHead;
		}
		return lRemainSize;
	}
/*	else
		lRemainSize = pstFifoHandle[nHandle].IdxNum;*/

	return lRemainSize;
}

/**********************************************************
*
*	Function of	SPDIF_FIFO_GetOneFrame
*
*	Input	:
*	Output	:
*	Return	:
*
*	Description	: data°¡ º¹»çÇÑÈÄ ¹öÆÛ ¾÷µ¥ÀÌÆ®
**********************************************************/
unsigned char *SPDIF_FIFO_GetOneFrame(int *Len,int* channel,int* samplerate ,int* mode, int* endian, int* codec, int* bitpersample)
{
	unsigned int	uiTail;
	unsigned char	*ptrData;

	if(pstFifoHandle.fState == SPDIF_FIFO_EMPTY)
	{
		*Len = 0;
		return 0;
	}

	uiTail = pstFifoHandle.ReadFrmIdx;

	ptrData = pstFifoHandle.ptrBuffer + pstFifoHandle.stFrameInfo[uiTail].offset;

	*Len = pstFifoHandle.stFrameInfo[uiTail].size;
	*channel = pstFifoHandle.stFrameInfo[uiTail].channel;
	*samplerate = pstFifoHandle.stFrameInfo[uiTail].samplerate;
	*mode = pstFifoHandle.stFrameInfo[uiTail].mode;
	*endian = pstFifoHandle.stFrameInfo[uiTail].endian;
	*codec = pstFifoHandle.stFrameInfo[uiTail].codec;
	*bitpersample = pstFifoHandle.stFrameInfo[uiTail].bitpersample;

	return ptrData;
}

/**********************************************************
*
*	Function of	SPDIF_FIFO_PopFrame
*
*	Input	:
*	Output	:
*	Return	:
*
*	Description	: data°¡ º¹»çÇÑÈÄ ¹öÆÛ ¾÷µ¥ÀÌÆ®
**********************************************************/
int SPDIF_FIFO_PopFrame(void)
{
	unsigned int	uiTail, uiHead;
	unsigned int	ReadBufPtr;

	if(pstFifoHandle.fState == SPDIF_FIFO_EMPTY)
		return 0;

	uiTail = pstFifoHandle.ReadFrmIdx;
	uiHead = pstFifoHandle.WriteFrmIdx;

	ReadBufPtr = pstFifoHandle.stFrameInfo[uiTail].offset + pstFifoHandle.stFrameInfo[uiTail].size;

	uiTail++;
	if( uiTail == pstFifoHandle.IdxNum )
		uiTail = 0;

	if(uiTail  == uiHead)
		pstFifoHandle.fState = SPDIF_FIFO_EMPTY;
	else
		pstFifoHandle.fState = SPDIF_FIFO_NORMAL;

	pstFifoHandle.ReadFrmIdx = uiTail;
	pstFifoHandle.ReadBufPtr = ReadBufPtr;
	return 1;
}

int SPDIF_FIFO_Push(void)
{
	unsigned int	uiTail, uiHead;

	if(pstFifoHandle.fState == SPDIF_FIFO_FULL)
		return 0;

	uiTail = pstFifoHandle.ReadFrmIdx;
	uiHead = pstFifoHandle.WriteFrmIdx;
	uiHead++;
	if( uiHead == pstFifoHandle.IdxNum )
		uiHead = 0;

	if(uiTail  == uiHead)
		pstFifoHandle.fState = SPDIF_FIFO_FULL;
	else
		pstFifoHandle.fState = SPDIF_FIFO_NORMAL;

	pstFifoHandle.WriteFrmIdx = uiHead;

	return 1;
}

/**************************************************************************
*  FUNCTION NAME :
*      int SPDIF_FIFO_GetOneFifo(int ReqSize,int channel, int samplerate, int mode ,int endian)
*
*  DESCRIPTION :
*  INPUT:
*			iFlags	=
*			nHandle	=
*			ptrPESInfo	=
*			ReqSize	=
*
*  OUTPUT:	int - Return Type
*  			=
*  REMARK  :
**************************************************************************/
int SPDIF_FIFO_GetOneFifo(int ReqSize,int channel, int samplerate, int mode ,int endian,int codec,int bitpersample)
{
	unsigned int	uiHead;
	unsigned int	ReadBufPtr, WriteBufPtr;
	unsigned int 	lRemainSize = 0;

	if(pstFifoHandle.fState == SPDIF_FIFO_FULL)
		return 0;

	ReadBufPtr = pstFifoHandle.ReadBufPtr;
	WriteBufPtr = pstFifoHandle.WriteBufPtr;

	uiHead = pstFifoHandle.WriteFrmIdx;

	if( ReqSize <= 0 ) /* [DMP:0213] */
		ReqSize = (32*1024);

	if( ReadBufPtr > WriteBufPtr )	//	Tail  < 	Head
	{
		lRemainSize = ReadBufPtr -  WriteBufPtr;

		if( lRemainSize <= ReqSize )
		{
			pstFifoHandle.fState = SPDIF_FIFO_FULL;
			return 0;
		}
	}
	else
	{
		 lRemainSize = pstFifoHandle.uiMaxSize - WriteBufPtr;

		 if( ReqSize >= lRemainSize )
		 {
		 	WriteBufPtr = 0;
		 	lRemainSize = ReadBufPtr;
			if( lRemainSize <= ReqSize )
			{
				pstFifoHandle.fState = SPDIF_FIFO_FULL;
				return 0;
			}
		 }
	}

	pstFifoHandle.stFrameInfo[uiHead].offset = WriteBufPtr;
	pstFifoHandle.stFrameInfo[uiHead].size = ReqSize;

	pstFifoHandle.stFrameInfo[uiHead].channel = channel;
	pstFifoHandle.stFrameInfo[uiHead].samplerate = samplerate;

	pstFifoHandle.stFrameInfo[uiHead].mode = mode;
	pstFifoHandle.stFrameInfo[uiHead].endian = endian;
	pstFifoHandle.stFrameInfo[uiHead].codec = codec;
	pstFifoHandle.stFrameInfo[uiHead].bitpersample = bitpersample;

	pstFifoHandle.WriteBufPtr = WriteBufPtr;

	return 1;
}

/**************************************************************************
*  FUNCTION NAME :
*      int SPDIF_FIFO_WriteFifo(unsigned char *ptrData, unsigned int ReqSize)
*
*  DESCRIPTION :
*  INPUT:
*			nHandle	=
*			ptrData	=
*			ReqSize	=
*
*  OUTPUT:	int - Return Type
*  			=
*  REMARK  :
**************************************************************************/
int SPDIF_FIFO_WriteFifo(unsigned char *ptrData, unsigned int ReqSize)
{
	unsigned int	WriteBufPtr;
	unsigned char 	*ptrWrite;
	unsigned int	MaxSize;
	int	lRemainSize;

	if(pstFifoHandle.fState == SPDIF_FIFO_FULL)
		return 0;

	MaxSize =  pstFifoHandle.uiMaxSize;
	WriteBufPtr = pstFifoHandle.WriteBufPtr;
	lRemainSize = MaxSize - WriteBufPtr;

	 if( lRemainSize < 0 )
	 {
	 	printf("Buffer OverFlow\n");
	 	return 0;
	 }
	else
	{
		ptrWrite = pstFifoHandle.ptrBuffer + WriteBufPtr;
		 if( ReqSize >= lRemainSize )
		 {
	 		memcpy( ptrWrite, ptrData, lRemainSize );
			ptrWrite = pstFifoHandle.ptrBuffer;
			ReqSize -= lRemainSize;
			ptrData += lRemainSize;
			WriteBufPtr = 0;
		 }
	}
	memcpy( ptrWrite, ptrData, ReqSize );

	pstFifoHandle.WriteBufPtr = WriteBufPtr + ReqSize;

	return ReqSize;
}


text:
module CdmMigrator
  class CreateWorkJob < ActiveJob::Base
    queue_as Hyrax.config.ingest_queue_name

    def perform(ingest_work, user, admin_set_id, collection_id)
      admin_set = ::AdminSet.find(admin_set_id) rescue nil
      collection = ::Collection.find(collection_id) rescue nil
      work = Object.const_get(ingest_work.work_type).new
      #status_after, embargo_date, lease_date = nil, nil, nil
      work.apply_depositor_metadata(user)
      work.attributes = ingest_work.data
      if ingest_work.data.has_key? 'downloadable'
        # Convert string to boolean
        work.downloadable = ActiveModel::Type::Boolean.new.cast(ingest_work.data['downloadable'])
      elsif work.attributes.include? 'downloadable' # Set work to downloadable by default
        work.downloadable = true
      end
      work.member_of_collections = [collection] if collection
      work.admin_set = admin_set if admin_set
      work.date_uploaded = DateTime.now
      work.save
      BatchCreateFilesJob.perform_later work, ingest_work, user

    end
  end
end


text:
package com.xtremelabs.imageutils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;

class HashedStack<T> implements Iterable<T> {
	private Node<T> mHead = null;
	private Node<T> mTail = null;
	private final Map<T, Node<T>> mNodeMap = new HashMap<T, Node<T>>();

	private static class Node<T> {
		T data;
		private Node<T> next = null;
		private Node<T> previous = null;

		Node(T data) {
			this.data = data;
		}

		public Node<T> getNext() {
			return next;
		}

		public void setNext(Node<T> next) {
			this.next = next;
		}

		public Node<T> getPrevious() {
			return previous;
		}

		public void setPrevious(Node<T> previous) {
			this.previous = previous;
		}
	}

	public synchronized void clear() {
		mHead = null;
		mTail = null;
		mNodeMap.clear();
	}

	public synchronized boolean contains(Object object) {
		return mNodeMap.containsKey(object);
	}

	public synchronized boolean isEmpty() {
		return mHead == null;
	}

	@Override
	public synchronized Iterator<T> iterator() {
		return new Iterator<T>() {
			private Node<T> current = mHead;

			@Override
			public boolean hasNext() {
				return current != null;
			}

			@Override
			public T next() {
				if (current == null) {
					throw new NoSuchElementException("No more elements inside of the iterator.");
				}

				T data = current.data;
				current = current.getNext();
				return data;
			}

			@Override
			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}

	public synchronized boolean remove(T object) {
		Node<T> node = mNodeMap.remove(object);
		if (node == null) {
			return false;
		}

		Node<T> previous, next;
		previous = node.getPrevious();
		next = node.getNext();

		if (previous != null) {
			previous.setNext(next);
		}
		if (next != null) {
			next.setPrevious(previous);
		}

		if (previous == null) {
			mHead = next;
		}

		if (next == null) {
			mTail = previous;
		}

		return true;
	}

	public synchronized int size() {
		return mNodeMap.size();
	}

	public synchronized boolean push(T e) {
		Node<T> node;
		if (mNodeMap.containsKey(e)) {
			node = mNodeMap.get(e);

			/*
			 * TODO: This "remove" call is not high performance in this case. We want the node removed from the queue but not the map.
			 */
			remove(e);

			node.next = null;
			node.previous = null;
		} else {
			node = new Node<T>(e);
		}

		if (mTail == null) {
			mHead = node;
			mTail = node;
		} else {
			mTail.setNext(node);
			node.setPrevious(mTail);
			mTail = node;
		}
		mNodeMap.put(e, node);
		return true;
	}

	public synchronized T pop() {
		T data = null;
		if (mTail != null) {
			data = mTail.data;
			mTail = mTail.previous;
			if (mTail != null) {
				mTail.next = null;
			}
			mNodeMap.remove(data);
		}
		return data;
	}

	public synchronized void bump(T e) {
		if (remove(e))
			push(e);
	}

	public T peek() {
		T data = null;
		if (mTail != null) {
			data = mTail.data;
		}
		return data;
	}
}


text:
typedef int (* AuthGetUserPw)(HttpdConnData *connData, int no, char *user, int userLen, char *pass, int passLen);

int ICACHE_FLASH_ATTR authBasic(HttpdConnData *connData);

#endif


text:
// Sanity check integration test for ulimit_info
// Spec file: specs/posix/ulimit_info.table

#include <osquery/tests/integration/tables/helper.h>

namespace osquery {

class ulimitInfo : public IntegrationTableTest {};

TEST_F(ulimitInfo, test_sanity) {
  // 1. Query data
  // QueryData data = execute_query("select * from ulimit_info");
  // 2. Check size before validation
  // ASSERT_GE(data.size(), 0ul);
  // ASSERT_EQ(data.size(), 1ul);
  // ASSERT_EQ(data.size(), 0ul);
  // 3. Build validation map
  // See IntegrationTableTest.cpp for avaialbe flags
  // Or use custom DataCheck object
  // ValidatatioMap row_map = {
  //      {"type", NormalType}
  //      {"soft_limit", NormalType}
  //      {"hard_limit", NormalType}
  //}
  // 4. Perform validation
  // validate_rows(data, row_map);
}

} // namespace osquery


text:
/*
 *
 * LegendShop 多用户商城系统
 *
 *  版权所有,并保留所有权利。
 *
 */
package com.legendshop.business.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

/**
 * The Class AuthenticationFailureHandler.
 */
public class AuthenticationFailureHandlerImpl extends SimpleUrlAuthenticationFailureHandler {

	/** The Constant TRY_LOGIN_COUNT. */
	public static final String TRY_LOGIN_COUNT = "TRY_LOGIN_COUNT";

	/*
	 * (non-Javadoc)
	 *
	 * @see org.springframework.security.web.authentication.
	 * SimpleUrlAuthenticationFailureHandler
	 * #onAuthenticationFailure(javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse,
	 * org.springframework.security.core.AuthenticationException)
	 */
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
			throws IOException, ServletException {
		increaseTryLoginCount(request);
		super.onAuthenticationFailure(request, response, exception);
	}

	/**
	 * Increase try login count.
	 *
	 * @param request
	 *            the request
	 */
	private void increaseTryLoginCount(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if (session == null) {
			return;
		}

		Integer count = (Integer) session.getAttribute(TRY_LOGIN_COUNT);
		if (count == null) {
			count = 0;
		}
		count++;
		session.setAttribute(TRY_LOGIN_COUNT, count);
	}
}


text:
/*
 * Authors:
 *   Kevin E. Martin <kem@redhat.com>
 *
 */

/** \file
 * Provide configuration define's and undef's to build Xdmx in X.Org's
 * modular source tree.
 */

#ifndef DMX_CONFIG_H
#define DMX_CONFIG_H

#include <dix-config.h>

/*
 * Note 1: This is a signed int that is printed as a decimal number.
 *         Since we want to make it human-interpretable, the fields are
 *         defined as:
 *         2147483648
 *         AAbbyymmdd
 *         AA: major version 01-20
 *         bb: minor version 00-99
 *         yy: year          00-99 [See Note 2]
 *         mm: month         01-12
 *         dd: day           01-31
 *
 * Note 2: The default epoch for the year is 2000.
 *         To change the default epoch, change the DMX_VENDOR_RELEASE
 *         macro below, bumb the minor version number, and change
 *         xdpyinfo to key off the major/minor version to determine the
 *         new epoch.  Remember to do this on January 1, 2100 and every
 *         100 years thereafter.
 */
#define DMX_VENDOR_RELEASE(major,minor,year,month,day) \
    ((major)     * 100000000) + \
    ((minor)     *   1000000) + \
    ((year-2000) *     10000) + \
    ((month)     *       100) + \
    ((day)       *         1)
#define VENDOR_RELEASE  DMX_VENDOR_RELEASE(1,2,2007,4,24)
#define VENDOR_STRING   "DMX Project"

/* Enable the DMX extension */
#define DMXEXT

#endif                          /* DMX_CONFIG_H */


text:
package org.xcolab.view.theme;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class PopulateLayoutVariablesFilter extends HandlerInterceptorAdapter {

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
            Object handler, ModelAndView modelAndView) {

        if (modelAndView != null && !isRedirectView(modelAndView)) {
            final Object attribute =
                    request.getAttribute(ThemeVariableFilter.REQUEST_ATTRIBUTE_NAME);

            if (attribute == null) {
                throw new IllegalStateException("ThemeContext variable was not populated in request: "
                                + request.getRequestURI());
            }
            ThemeContext themeContext = (ThemeContext) attribute;
            themeContext.repopulateMessages(request);
            modelAndView.addObject("_themeContext", themeContext);
        }
    }

    private boolean isRedirectView(ModelAndView modelAndView) {
        return (modelAndView.getView() != null && modelAndView.getView() instanceof RedirectView)
                || modelAndView.getViewName().startsWith("redirect:");
    }
}


text:
package com.AssassinAndroid.AsyncTasks;

import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.AssassinAndroid.Tools.Utilities;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * User: AnubhawArya
 * Date: 2/9/14
 * Time: 8:25 AM
 */
public class LocationAsyncTask extends AsyncTask<Location, Integer, JSONObject> {

    Context context;

    public LocationAsyncTask(Context context) {
        this.context = context;
    }

    protected void onPreExecute() {
        if (!Utilities.isNetworkAvailable(context))
            cancel(true);
    }

    protected JSONObject doInBackground(Location... params) {
        if (isCancelled())
            return null;
        Location loc = params[0];
        List<NameValuePair> loginParams = new ArrayList<NameValuePair>();
        loginParams.add(new BasicNameValuePair("user_id", Utilities.userId));
        loginParams.add(new BasicNameValuePair("latitude", loc.getLatitude() + ""));
        loginParams.add(new BasicNameValuePair("longitude", loc.getLongitude() + ""));
        try {
            return Utilities.getResponse(Utilities.API_URL + "location_update.php", loginParams);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    protected void onPostExecute(JSONObject o) {
        if (o == null) {
            Toast.makeText(context, "Problem logging in!", Toast.LENGTH_SHORT).show();
            return;
        }
        Log.d(Utilities.TAG, o.toString());
    }
}


text:
/* tslint:disable:typedef no-invalid-this */

/**
 * Factory decorator used to bind the this to the decorated function.
 *
 * @return    a new descriptor representing the binded function.
 * @see        https://github.com/NoHomey/bind-decorator
 * @see        https://github.com/andreypopp/autobind-decorator
 */
export function Bind(): MethodDecorator {

	return function(target: Function, propertyKey: string, descriptor: TypedPropertyDescriptor<any>):
		TypedPropertyDescriptor<any> {

		// seems that the decorator is calling once for the class also, so this if is necessary to avoid bad bindings
		if(!descriptor || (typeof descriptor.value !== 'function')) {
			// throw new TypeError(`Only functions can be decorated with @bind. <${propertyKey}> is not a function!`);
			return;
		}

		return {
			configurable: true,
			get(this) {

				let bound = descriptor.value.bind(this);
				Object.defineProperty(this, propertyKey, {
					value: bound,
					configurable: true,
					writable: true
				});

				return bound;
			}
		};

	};

}