text:
#ifndef LIBAFTERIMAGE_XIMAGE_HEADER_FILE_INCLUDED
#define LIBAFTERIMAGE_XIMAGE_HEADER_FILE_INCLUDED

#include "asvisual.h"
#include "blender.h"
#include "asimage.h"

#ifdef __cplusplus
extern "C" {
#endif

/****h* libAfterImage/ximage.h
 * NAME
 * ximage - Defines conversion to and from XImages and Pixmaps.
 * DESCRIPTION
 * ximage2asimage()	- convert XImage structure into ASImage
 * pixmap2asimage()	- convert X11 pixmap into ASImage
 * asimage2ximage()	- convert ASImage into XImage
 * asimage2mask_ximage() - convert alpha channel of ASImage into XImage
 * asimage2pixmap()	- convert ASImage into Pixmap ( possibly using
 * 					  precreated XImage )
 * asimage2mask() 	- convert alpha channel of ASImage into 1 bit
 * 				  	  mask Pixmap.
 * SEE ALSO
 * Other libAfterImage modules :
 *          ascmap.h asfont.h asimage.h asvisual.h blender.h export.h
 *          import.h transform.h ximage.h
 * AUTHOR
 * Sasha Vasko <sasha at aftercode dot net>
 *******/

/****f* libAfterImage/picture_ximage2asimage()
 * NAME
 * picture_ximage2asimage()
 * SYNOPSIS
 * ASImage *picture_ximage2asimage ( struct ASVisual *asv,
 *                                   XImage * xim, XImage *alpha_xim,
 *                                   unsigned int compression );
 * INPUTS
 * asv           - pointer to valid ASVisual structure
 * xim           - source XImage
 * alpha_xim     - source XImage for Alpha channel
 * compression   - degree of compression of resulting ASImage.
 * RETURN VALUE
 * pointer to newly allocated ASImage, containing encoded data, on
 * success. NULL on failure.
 * DESCRIPTION
 * picture_ximage2asimage will attempt to create new ASImage with the same
 * dimensions as supplied XImage. If both XImages are supplied - they must
 * have same dimentions. XImage will be decoded based on
 * supplied ASVisual, and resulting scanlines will be encoded into
 * ASImage.
 *********/
/****f* libAfterImage/ximage2asimage()
 * NAME
 * ximage2asimage() - same as picture_ximage2asimage with alpha_ximage
 * set to NULL. Supplied for compatibility with older versions and for
 * convinience.
 * SYNOPSIS
 * ASImage *ximage2asimage ( struct ASVisual *asv, XImage * xim,
 *                           unsigned int compression );
 * INPUTS
 * asv  		 - pointer to valid ASVisual structure
 * xim  		 - source XImage
 * compression - degree of compression of resulting ASImage.
 * RETURN VALUE
 * pointer to newly allocated ASImage, containing encoded data, on
 * success. NULL on failure.
 * DESCRIPTION
 *********/
/****f* libAfterImage/pixmap2asimage()
 * NAME
 * pixmap2asimage()
 * SYNOPSIS
 * ASImage *pixmap2ximage( ASVisual *asv, Pixmap p, int x, int y,
 *                         unsigned int width, unsigned int height,
 *						   unsigned long plane_mask,
 *                         unsigned int compression);
 * INPUTS
 * asv  		  - pointer to valid ASVisual structure
 * p    		  - source Pixmap
 * x, y,
 * width, height- rectangle on Pixmap to be encoded into ASImage.
 * plane_mask   - limits color planes to be copied from Pixmap.
 * keep_cache   - indicates if we should keep XImage, used to copy
 *                image data from the X server, and attached it to
 * 				  ximage member of resulting ASImage.
 * compression  - degree of compression of resulting ASImage.
 * RETURN VALUE
 * pointer to newly allocated ASImage, containing data in XImage format,
 * on success. NULL on failure.
 * DESCRIPTION
 * pixmap2ximage will obtain XImage of the requested area of the
 * X Pixmap, and it will attach it to newly created ASImage using
 * alt.ximage member. After that newly created ASImage could be used
 * in any transformations.
 *********/
/****f* libAfterImage/picture2asimage()
 * NAME
 * picture2asimage()
 * SYNOPSIS
 * ASImage *picture2asimage (struct ASVisual *asv,
 *                           Pixmap rgb, Pixmap a,
 *                           int x, int y,
 *                           unsigned int width,
 *                           unsigned int height,
 *                           unsigned long plane_mask,
 *                           Bool keep_cache,
 *                           unsigned int compression );
 * INPUTS
 * asv  		  - pointer to valid ASVisual structure
 * rgb    		  - source Pixmap for red, green and blue channels
 * a    		  - source Pixmap for the alpha channel
 * x, y,
 * width, height- rectangle on Pixmap to be encoded into ASImage.
 * plane_mask   - limits color planes to be copied from Pixmap.
 * keep_cache   - indicates if we should keep XImage, used to copy
 *                image data from the X server, and attached it to
 * 				  ximage member of resulting ASImage.
 * compression  - degree of compression of resulting ASImage.
 * RETURN VALUE
 * pointer to newly allocated ASImage, containing encoded data, on
 * success. NULL on failure.
 * DESCRIPTION
 * picture2asimage will obtain XImage of the requested area of the
 * X Pixmap, If alpha channel pixmap is supplied - it will be used to
 * encode ASImage's alpha channel. Alpha channel pixmap must be either
 * 8 or 1 bit deep, and it must have the same dimentions as main Pixmap.
 *********/
/****f* libAfterImage/pixmap2asimage()
 * NAME
 * pixmap2asimage()
 * SYNOPSIS
 * ASImage *pixmap2asimage ( struct ASVisual *asv, Pixmap p,
 *                           int x, int y,
 *                           unsigned int width,
 *                           unsigned int height,
 *                           unsigned long plane_mask,
 *                           Bool keep_cache,
 *                           unsigned int compression );
 * INPUTS
 * asv  		  - pointer to valid ASVisual structure
 * p    		  - source Pixmap
 * x, y,
 * width, height- rectangle on Pixmap to be encoded into ASImage.
 * plane_mask   - limits color planes to be copied from Pixmap.
 * keep_cache   - indicates if we should keep XImage, used to copy
 *                image data from the X server, and attached it to
 *                ximage member of resulting ASImage.
 * compression  - degree of compression of resulting ASImage.
 * RETURN VALUE
 * pointer to newly allocated ASImage, containing encoded data, on
 * success. NULL on failure.
 * DESCRIPTION
 * same as picture2asimage() with alpha pixmap set to None. Supplied for
 * compatibility and convinience.
 *********/
ASImage *picture_ximage2asimage (ASVisual *asv, XImage *xim, XImage *alpha_xim, unsigned int compression);
ASImage *ximage2asimage (struct ASVisual *asv, XImage * xim, unsigned int compression);
ASImage *pixmap2ximage( ASVisual *asv, Pixmap p, int x, int y,
                        unsigned int width, unsigned int height,
						unsigned long plane_mask, unsigned int compression);
ASImage *picture2asimage(ASVisual *asv, Pixmap rgb, Pixmap a , int x, int y,
                         unsigned int width, unsigned int height,
						 unsigned long plane_mask, Bool keep_cache, unsigned int compression);
ASImage *pixmap2asimage (struct ASVisual *asv, Pixmap p, int x, int y,
	                     unsigned int width, unsigned int height,
		  				 unsigned long plane_mask, Bool keep_cache, unsigned int compression);

/****f* libAfterImage/asimage2ximage()
 * NAME
 * asimage2ximage()
 * SYNOPSIS
 * XImage  *asimage2ximage  (struct ASVisual *asv, ASImage *im);
 * INPUTS
 * asv  		- pointer to valid ASVisual structure
 * im    		- source ASImage
 * RETURN VALUE
 * On success returns newly created and encoded XImage of the same
 * colordepth as the supplied ASVisual. NULL on failure.
 * DESCRIPTION
 * asimage2ximage() creates new XImage of the exact same size as
 * supplied ASImage, and depth of supplied ASVisual. REd, Green and
 * Blue channels of ASImage then gets decoded, and encoded into XImage.
 * Missing scanlines get filled with black color.
 * NOTES
 * Returned pointer to XImage will also be stored in im->alt.ximage,
 * and It will be destroyed when XImage is destroyed, or reused in any
 * subsequent calls to asimage2ximage(). If any other behaviour is
 * desired - make sure you set im->alt.ximage to NULL, to dissociate
 * XImage object from ASImage.
 * SEE ALSO
 * create_visual_ximage()
 *********/
/****f* libAfterImage/asimage2alpha_ximage()
 * NAME
 * asimage2alpha_ximage()
 * SYNOPSIS
 * XImage  *asimage2alpha_ximage (struct ASVisual *asv,
 *                                ASImage *im, Bool bitmap);
 * INPUTS
 * asv   		- pointer to valid ASVisual structure
 * im    		- source ASImage
 * bitmap       - if True resulting XImage will have depth of 1 bit -
 *                traditional X mask; otherwise it will have depth of 8
 *                (useful for XFree86 RENDER extension)
 * RETURN VALUE
 * On success returns newly created and encoded XImage of the depth 1 or 8.
 * NULL on failure.
 * DESCRIPTION
 * asimage2alpha_ximage() creates new XImage of the exact same size as
 * supplied ASImage, and depth 1 or 8. Alpha channels of ASImage then gets
 * decoded, and encoded into XImage. In case requested depth is 1 then
 * alpha channel is interpreted like so: 127 or greater is encoded as 1,
 * otherwise as 0.
 * Missing scanlines get filled with 1s as they signify absence of mask.
 * NOTES
 * Returned pointer to XImage will also be stored in im->alt.mask_ximage,
 * and It will be destroyed when XImage is destroyed, or reused in any
 * subsequent calls to asimage2mask_ximage(). If any other behaviour is
 * desired - make sure you set im->alt.mask_ximage to NULL, to dissociate
 * XImage object from ASImage.
 *********/
/****f* libAfterImage/asimage2mask_ximage()
 * NAME
 * asimage2mask_ximage() - same as asimage2alpha_ximage(). Supplied for
 * convinience and compatibility with older versions.
 * SYNOPSIS
 * XImage  *asimage2mask_ximage (struct ASVisual *asv, ASImage *im);
 * INPUTS
 * asv   		- pointer to valid ASVisual structure
 * im    		- source ASImage
 * RETURN VALUE
 * On success returns newly created and encoded XImage of the depth 1.
 * NULL on failure.
 *********/
/****f* libAfterImage/asimage2pixmap()
 * NAME
 * asimage2pixmap()
 * SYNOPSIS
 * Bool	 asimage2drawable( struct ASVisual *asv, Drawable d, ASImage *im,
 *                         GC gc,
 *        			       int src_x, int src_y, int dest_x, int dest_y,
 *       		  		   unsigned int width, unsigned int height,
 *				  		   Bool use_cached);
 * INPUTS
 * asv  		- pointer to valid ASVisual structure
 * d  			- destination drawable - Pixmap or Window
 * im    		- source ASImage
 * gc   		- precreated GC to use for XImage transfer. If NULL,
 *  			  asimage2drawable() will use DefaultGC.
 * src_x        - Specifies the offset in X from the left edge of the image
 *                defined by the ASImage structure.
 * src_y        - Specifies the offset in Y from the top edge of the image
 *                defined by the ASImage structure.
 * dest_x,dest_y- Specify the x and y coordinates, which are relative to
 *                the origin of the drawable and are the coordinates of
 *                the subimage.
 * width,height - Specify the width and height of the subimage, which
 *                define the dimensions of the rectangle.
 * use_cached	- If True will make asimage2pixmap() to use XImage
 *  			  attached to ASImage, instead of creating new one. Only
 *  			  works if ASImage->ximage data member is not NULL.
 * RETURN VALUE
 * On success returns True.
 * DESCRIPTION
 * asimage2drawable() creates will copy portion of ASImage onto the X
 * Drawable. It checks if it needs to encode XImage
 * from ASImage data, and calls asimage2ximage() if yes, it has to.
 * It then supplied gc or DefaultGC of the screen to transfer
 * XImage to the server.
 * Missing scanlines get filled with black color.
 * SEE ALSO
 * asimage2ximage()
 * asimage2pixmap()
 * create_visual_pixmap()
 *********/

/****f* libAfterImage/asimage2pixmap()
 * NAME
 * asimage2pixmap()
 * SYNOPSIS
 * Pixmap   asimage2pixmap  ( struct ASVisual *asv, Window root,
 *                            ASImage *im, GC gc, Bool use_cached);
 * INPUTS
 * asv  		- pointer to valid ASVisual structure
 * root 		- root window of destination screen
 * im    		- source ASImage
 * gc   		- precreated GC to use for XImage transfer. If NULL,
 *  			  asimage2pixmap() will use DefaultGC.
 * use_cached	- If True will make asimage2pixmap() to use XImage
 *  			  attached to ASImage, instead of creating new one. Only
 *  			  works if ASImage->ximage data member is not NULL.
 * RETURN VALUE
 * On success returns newly pixmap of the same colordepth as ASVisual.
 * None on failure.
 * DESCRIPTION
 * asimage2pixmap() creates new pixmap of exactly same size as
 * supplied ASImage. It then calls asimage2drawable to copy entire content
 * of the ASImage onto that created pixmap.
 * EXAMPLE
 * asview.c: ASView.5
 * SEE ALSO
 * asimage2ximage()
 * asimage2drawable()
 * create_visual_pixmap()
 *********/
/****f* libAfterImage/asimage2mask()
 * NAME
 * asimage2mask()
 * SYNOPSIS
 * Pixmap   asimage2mask ( struct ASVisual *asv, Window root,
 *                         ASImage *im, GC gc, Bool use_cached);
 * asv        - pointer to valid ASVisual structure
 * root       - root window of destination screen
 * im         - source ASImage
 * gc         - precreated GC for 1 bit deep drawables to use for
 *              XImage transfer. If NULL, asimage2mask() will create one.
 * use_cached - If True will make asimage2mask() to use mask XImage
 *  			attached to ASImage, instead of creating new one. Only
 *  			works if ASImage->alt.mask_ximage data member is not NULL.
 * RETURN VALUE
 * On success returns newly created pixmap of the colordepth 1.
 * None on failure.
 * DESCRIPTION
 * asimage2mask() creates new pixmap of exactly same size as
 * supplied ASImage. It then calls asimage2mask_ximage().
 * It then uses supplied gc, or creates new gc, to transfer
 * XImage to the server and put it on Pixmap.
 * Missing scanlines get filled with 1s.
 * SEE ALSO
 * asimage2mask_ximage()
 **********/
XImage  *asimage2ximage  (struct ASVisual *asv, ASImage *im);
Bool     subimage2ximage (struct ASVisual *asv, ASImage *im, int x, int y, XImage* xim);
Bool     put_ximage( ASVisual *asv, XImage *xim, Drawable d, GC gc,
                     int src_x, int src_y, int dest_x, int dest_y,
  		             unsigned int width, unsigned int height );

XImage  *asimage2alpha_ximage (ASVisual *asv, ASImage *im, Bool bitmap );
XImage  *asimage2mask_ximage (struct ASVisual *asv, ASImage *im);
Bool	 asimage2drawable( struct ASVisual *asv, Drawable d, ASImage *im, GC gc,
         			       int src_x, int src_y, int dest_x, int dest_y,
        		  		   unsigned int width, unsigned int height,
				  		   Bool use_cached);
/* these will do the same, but will use OpenGL API where available */
Bool asimage2drawable_gl(	ASVisual *asv, Drawable d, ASImage *im,
                  		int src_x, int src_y, int dest_x, int dest_y,
        		  		int width, int height, int d_width, int d_height,
						Bool force_direct );

Bool	 asimage2alpha_drawable( ASVisual *asv, Drawable d, ASImage *im, GC gc,
      	    		  	   int src_x, int src_y, int dest_x, int dest_y,
        				   unsigned int width, unsigned int height,
						   Bool use_cached);
Pixmap   asimage2pixmap  (struct ASVisual *asv, Window root, ASImage *im, GC gc, Bool use_cached);
Pixmap	 asimage2alpha   (struct ASVisual *asv, Window root, ASImage *im, GC gc, Bool use_cached, Bool bitmap);
Pixmap   asimage2mask    (struct ASVisual *asv, Window root, ASImage *im, GC gc, Bool use_cached);

#ifdef __cplusplus
}
#endif

#endif


text:
package com.cube.storm.content.lib.manager;

import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.cube.storm.ContentSettings;
import com.cube.storm.content.lib.Constants;
import com.cube.storm.content.lib.handler.GZIPTarCacheResponseHandler;
import com.cube.storm.content.lib.helper.BundleHelper;
import com.cube.storm.content.lib.helper.FileHelper;
import com.cube.storm.content.model.UpdateContentProgress;
import com.cube.storm.content.model.UpdateContentRequest;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.subjects.BehaviorSubject;
import io.reactivex.subjects.Subject;
import net.callumtaylor.asynchttp.AsyncHttpClient;
import net.callumtaylor.asynchttp.response.JsonResponseHandler;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * This is the manager class responsible for checking for and downloading updates from the server
 * <p/>
 * Access this class via {@link ContentSettings#getUpdateManager()}. Do not instantiate this class directly
 *
 * @author Callum Taylor
 * @project LightningContent
 */
public class DefaultUpdateManager implements UpdateManager
{
	private AsyncHttpClient apiClient;

	private Subject<UpdateContentRequest> updates = BehaviorSubject.create();

	/**
	 * Downloads the latest full bundle from the server
	 */
	@Override
	public UpdateContentRequest checkForBundle(@Nullable Long buildTimestamp)
	{
		Subject<UpdateContentProgress> observer = BehaviorSubject.create();
		UpdateContentRequest updateContentRequest = UpdateContentRequest.fullBundle(buildTimestamp, observer);
		updates.onNext(updateContentRequest);
		checkForBundle(buildTimestamp, observer);
		return updateContentRequest;
	}

	private void checkForBundle(@Nullable Long buildTime, Observer<UpdateContentProgress> observer)
	{
		observer.onNext(UpdateContentProgress.checking());

		long buildTimeParam = buildTime == null ? -1 : buildTime;
		apiClient = ContentSettings.getInstance().getApiManager().checkForBundle(buildTimeParam, new JsonResponseHandler()
		{
			@Override public void onSuccess()
			{
				apiClient = null;

				boolean toDownload = false;

				if (getConnectionInfo().responseCode < 300 && getConnectionInfo().responseCode >= 200)
				{
					try
					{
						if (getConnectionInfo().responseCode == 200)
						{
							JsonElement response = getContent();

							if (response != null && response.isJsonObject())
							{
								if (response.getAsJsonObject().has("file"))
								{
									String endpoint = response.getAsJsonObject().get("file").getAsString();
									downloadUpdates(endpoint, observer);
									toDownload = true;
								}
							}
						}
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
				else if (getConnectionInfo().responseCode == 303)
				{
					if (!TextUtils.isEmpty(getConnectionInfo().responseHeaders.get("Location")))
					{
						String location = getConnectionInfo().responseHeaders.get("Location");
						downloadUpdates(location, observer);
						toDownload = true;
					}
				}

				if (!toDownload)
				{
					observer.onComplete();
				}

				if (ContentSettings.getInstance().getUpdateListener() != null)
				{
					ContentSettings.getInstance().getUpdateListener().onUpdateCheckFinished(toDownload);
				}
			}

			@Override public void onFailure()
			{
				observer.onError(new IOException("Unexpected response when checking for bundle: " + getConnectionInfo().toString()));

				if (ContentSettings.getInstance().getUpdateListener() != null)
				{
					ContentSettings.getInstance().getUpdateListener().onUpdateCheckFailed(getConnectionInfo());
				}
			}
		});
	}

	/**
	 * Checks for updates on the server and downloads any new files in the form of a delta bundle
	 *
	 * @param lastUpdate The time of the last update. Usually found in the {@code manifest.json} file
	 */
	@Override
	public UpdateContentRequest checkForUpdates(final long lastUpdate)
	{
		Subject<UpdateContentProgress> observer = BehaviorSubject.create();
		UpdateContentRequest updateContentRequest = UpdateContentRequest.deltaUpdate(lastUpdate, observer);
		updates.onNext(updateContentRequest);
		checkForUpdates(lastUpdate, observer);
		return updateContentRequest;
	}

	private void checkForUpdates(long lastUpdate, Observer<UpdateContentProgress> observer)
	{
		observer.onNext(UpdateContentProgress.checking());
		apiClient = ContentSettings.getInstance().getApiManager().checkForDelta(lastUpdate, new JsonResponseHandler()
		{
			@Override public void onSuccess()
			{
				apiClient = null;

				boolean toDownload = false;

				if (getConnectionInfo().responseCode < 300 && getConnectionInfo().responseCode >= 200)
				{
					try
					{
						if (getConnectionInfo().responseCode == 200)
						{
							JsonElement response = getContent();

							if (response != null && response.isJsonObject())
							{
								if (response.getAsJsonObject().has("file"))
								{
									String endpoint = response.getAsJsonObject().get("file").getAsString();
									downloadUpdates(endpoint, observer);
									toDownload = true;
								}
							}
						}
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
				else if (getConnectionInfo().responseCode == 303)
				{
					if (!TextUtils.isEmpty(getConnectionInfo().responseHeaders.get("Location")))
					{
						String location = getConnectionInfo().responseHeaders.get("Location");
						downloadUpdates(location, observer);
						toDownload = true;
					}
				}

				if (!toDownload)
				{
					observer.onComplete();
				}

				if (ContentSettings.getInstance().getUpdateListener() != null)
				{
					ContentSettings.getInstance().getUpdateListener().onUpdateCheckFinished(toDownload);
				}
			}

			@Override public void onFailure()
			{
				observer.onError(new IllegalStateException("Unexpected response when checking for delta update: " + getConnectionInfo().toString()));
				if (ContentSettings.getInstance().getUpdateListener() != null)
				{
					ContentSettings.getInstance().getUpdateListener().onUpdateCheckFailed(getConnectionInfo());
				}
			}
		});
	}

	/**
	 * Downloads a tar.gz file from the given endpoint
	 *
	 * @param endpoint The endpoint to the tar.gz bundle/delta file
	 */
	public UpdateContentRequest downloadUpdates(@NonNull String endpoint)
	{
		Subject<UpdateContentProgress> observer = BehaviorSubject.create();
		UpdateContentRequest updateContentRequest = UpdateContentRequest.directDownload(observer);
		updates.onNext(updateContentRequest);
		downloadUpdates(endpoint, observer);
		return updateContentRequest;
	}

	public void downloadUpdates(String endpoint, Observer<UpdateContentProgress> observer)
	{
		observer.onNext(UpdateContentProgress.downloading(0, 0));

		if (!TextUtils.isEmpty(ContentSettings.getInstance().getStoragePath()))
		{
			// download to temp file
			File deltaDirectory = new File(ContentSettings.getInstance().getStoragePath() + "/delta");
			FileHelper.deleteRecursive(deltaDirectory);
			deltaDirectory.mkdir();

			apiClient = new AsyncHttpClient(endpoint);
			apiClient.get(new GZIPTarCacheResponseHandler(ContentSettings.getInstance().getStoragePath() + "/delta")
			{
				@Override public void onByteChunkReceivedProcessed(long totalProcessed, long totalLength)
				{
					super.onByteChunkReceivedProcessed(totalProcessed, totalLength);

					observer.onNext(UpdateContentProgress.downloading(totalProcessed, totalLength));
					if (ContentSettings.getInstance().getDownloadListener() != null)
					{
						ContentSettings.getInstance().getDownloadListener().onDownloadProgress(totalProcessed, totalLength);
					}
				}

				@Override public void onSuccess()
				{
					super.onSuccess();
					try
					{
						observer.onNext(UpdateContentProgress.verifying());

						// delete the bundle
						new File(getFilePath() + "/bundle.tar").delete();

						File path = new File(ContentSettings.getInstance().getStoragePath());

						// Check the integrity of the unpacked bundle
						if (ContentSettings.getInstance().getBundleIntegrityManager().integrityCheck(getFilePath()))
						{
							observer.onNext(UpdateContentProgress.deploying());
							// Move files from /delta to ../
							FileHelper.copyDirectory(new File(getFilePath()), path);
							FileHelper.deleteRecursive(new File(getFilePath()));
							// Enforce the integrity of the deployed directory
							ContentSettings.getInstance().getBundleIntegrityManager().enforceIntegrityAfterDeployment(path);
						}
						observer.onComplete();
					}
					catch (Exception e)
					{
						e.printStackTrace();

						observer.onError(e);
						if (ContentSettings.getInstance().getUpdateListener() != null)
						{
							ContentSettings.getInstance().getUpdateListener().onUpdateFailed(1, getConnectionInfo());
						}
					}
				}

				@Override public void onFailure()
				{
					observer.onError(new IllegalStateException("Failed to download bundle"));
					if (ContentSettings.getInstance().getUpdateListener() != null)
					{
						ContentSettings.getInstance().getUpdateListener().onUpdateFailed(1, getConnectionInfo());
					}
				}

				@Override public void onFinish()
				{
					apiClient = null;

					if (getConnectionInfo().responseCode >= 200 && getConnectionInfo().responseCode < 300)
					{
						if (ContentSettings.getInstance().getUpdateListener() != null)
						{
							ContentSettings.getInstance().getUpdateListener().onUpdateDownloaded();
						}
					}
					else
					{
						if (ContentSettings.getInstance().getUpdateListener() != null)
						{
							ContentSettings.getInstance().getUpdateListener().onUpdateFailed(0, getConnectionInfo());
						}
					}
				}
			});
		}
	}

	/**
	 * Cancels any pending api requests
	 */
	@Override
	public void cancelPendingRequests()
	{
		if (apiClient != null)
		{
			apiClient.cancel();
		}
	}

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

	@Override
	public Observable<UpdateContentRequest> updates()
	{
		return updates;
	}
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';
var grpc = require('grpc');
var math_math_pb = require('../math/math_pb.js');

function serialize_DivArgs(arg) {
  if (!(arg instanceof math_math_pb.DivArgs)) {
    throw new Error('Expected argument of type DivArgs');
  }
  return new Buffer(arg.serializeBinary());
}

function deserialize_DivArgs(buffer_arg) {
  return math_math_pb.DivArgs.deserializeBinary(new Uint8Array(buffer_arg));
}

function serialize_DivReply(arg) {
  if (!(arg instanceof math_math_pb.DivReply)) {
    throw new Error('Expected argument of type DivReply');
  }
  return new Buffer(arg.serializeBinary());
}

function deserialize_DivReply(buffer_arg) {
  return math_math_pb.DivReply.deserializeBinary(new Uint8Array(buffer_arg));
}

function serialize_FibArgs(arg) {
  if (!(arg instanceof math_math_pb.FibArgs)) {
    throw new Error('Expected argument of type FibArgs');
  }
  return new Buffer(arg.serializeBinary());
}

function deserialize_FibArgs(buffer_arg) {
  return math_math_pb.FibArgs.deserializeBinary(new Uint8Array(buffer_arg));
}

function serialize_Num(arg) {
  if (!(arg instanceof math_math_pb.Num)) {
    throw new Error('Expected argument of type Num');
  }
  return new Buffer(arg.serializeBinary());
}

function deserialize_Num(buffer_arg) {
  return math_math_pb.Num.deserializeBinary(new Uint8Array(buffer_arg));
}

var MathService = exports.MathService = {
  // Div divides args.dividend by args.divisor and returns the quotient and
  // remainder.
  div: {
    path: '/math.Math/Div',
    requestStream: false,
    responseStream: false,
    requestType: math_math_pb.DivArgs,
    responseType: math_math_pb.DivReply,
    requestSerialize: serialize_DivArgs,
    requestDeserialize: deserialize_DivArgs,
    responseSerialize: serialize_DivReply,
    responseDeserialize: deserialize_DivReply,
  },
  // DivMany accepts an arbitrary number of division args from the client stream
  // and sends back the results in the reply stream.  The stream continues until
  // the client closes its end; the server does the same after sending all the
  // replies.  The stream ends immediately if either end aborts.
  divMany: {
    path: '/math.Math/DivMany',
    requestStream: true,
    responseStream: true,
    requestType: math_math_pb.DivArgs,
    responseType: math_math_pb.DivReply,
    requestSerialize: serialize_DivArgs,
    requestDeserialize: deserialize_DivArgs,
    responseSerialize: serialize_DivReply,
    responseDeserialize: deserialize_DivReply,
  },
  // Fib generates numbers in the Fibonacci sequence.  If args.limit > 0, Fib
  // generates up to limit numbers; otherwise it continues until the call is
  // canceled.  Unlike Fib above, Fib has no final FibReply.
  fib: {
    path: '/math.Math/Fib',
    requestStream: false,
    responseStream: true,
    requestType: math_math_pb.FibArgs,
    responseType: math_math_pb.Num,
    requestSerialize: serialize_FibArgs,
    requestDeserialize: deserialize_FibArgs,
    responseSerialize: serialize_Num,
    responseDeserialize: deserialize_Num,
  },
  // Sum sums a stream of numbers, returning the final result once the stream
  // is closed.
  sum: {
    path: '/math.Math/Sum',
    requestStream: true,
    responseStream: false,
    requestType: math_math_pb.Num,
    responseType: math_math_pb.Num,
    requestSerialize: serialize_Num,
    requestDeserialize: deserialize_Num,
    responseSerialize: serialize_Num,
    responseDeserialize: deserialize_Num,
  },
};

exports.MathClient = grpc.makeGenericClientConstructor(MathService);


text:
<?php

namespace Handlers\Request\Source\Abstracts;

/**
 * Generated by PHPUnit_SkeletonGenerator 1.2.1 on 2014-04-18 at 15:56:31.
 */
class RequestTest extends \PHPUnit_Framework_TestCase {

    /**
     * @var Request
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     */
    protected function setUp() {
        $this->object = new Request;
    }

    /**
     * Tears down the fixture, for example, closes a network connection.
     * This method is called after a test is executed.
     */
    protected function tearDown() {

    }

    /**
     * @covers Handlers\Request\Source\Abstracts\Request::getConnection
     * @todo   Implement testGetConnection().
     */
    public function testGetConnection() {
        // Remove the following lines when you implement this test.
        $this->markTestIncomplete(
                'This test has not been implemented yet.'
        );
    }

    /**
     * @covers Handlers\Request\Source\Abstracts\Request::getEncoding
     * @todo   Implement testGetEncoding().
     */
    public function testGetEncoding() {
        // Remove the following lines when you implement this test.
        $this->markTestIncomplete(
                'This test has not been implemented yet.'
        );
    }

    /**
     * @covers Handlers\Request\Source\Abstracts\Request::getHost
     * @todo   Implement testGetHost().
     */
    public function testGetHost() {
        // Remove the following lines when you implement this test.
        $this->markTestIncomplete(
                'This test has not been implemented yet.'
        );
    }

    /**
     * @covers Handlers\Request\Source\Abstracts\Request::getRemoteUser
     * @todo   Implement testGetRemoteUser().
     */
    public function testGetRemoteUser() {
        // Remove the following lines when you implement this test.
        $this->markTestIncomplete(
                'This test has not been implemented yet.'
        );
    }

}


text:
@interface MainPageViewController () <UIPageViewControllerDelegate, UIPageViewControllerDataSource>
@property (nonatomic, strong) NSArray *mainTableViewControllers;
@end

@implementation MainPageViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self setupViewControllers];
}

- (void)setupViewControllers
{
    MainTableViewController *beepMainTableViewController = [MainTableViewController mainTableViewControllerBeep];
    MainTableViewController *boopMainTableViewController = [MainTableViewController mainTableViewControllerBoop];

    self.mainTableViewControllers = @[beepMainTableViewController, boopMainTableViewController];
}

- (MainTableViewController *)mainTableViewControllerWithCurrentPageIndex
{
    MainTableViewController *mainTableViewController = self.mainTableViewControllers[self.currentPageIndex];

    return mainTableViewController;
}

- (void)updateCurrentPageViewControllerAnimated:(BOOL)animated
{
    MainTableViewController *mainTableViewController = [self mainTableViewControllerWithCurrentPageIndex];
    UIPageViewControllerNavigationDirection direction = (self.currentPageIndex == 0)
    ? UIPageViewControllerNavigationDirectionReverse
    : UIPageViewControllerNavigationDirectionForward;

    // FIXME: it seems the UIScrollView delegate is lost
    [self setViewControllers:@[mainTableViewController]
                   direction:direction
                    animated:animated
                  completion:nil];
}

#pragma mark - UIPageViewControllerDataSource

- (MainTableViewController *)pageViewController:(UIPageViewController *)pageViewController
      viewControllerBeforeViewController:(MainTableViewController *)viewController
{
    NSUInteger mainTableViewControllerIndex = [self.mainTableViewControllers indexOfObject:viewController];

    if (mainTableViewControllerIndex == 0) {
        return nil;
    }

    return self.mainTableViewControllers[mainTableViewControllerIndex - 1];
}

- (MainTableViewController *)pageViewController:(UIPageViewController *)pageViewController
       viewControllerAfterViewController:(MainTableViewController *)viewController
{
    NSUInteger mainTableViewControllerIndex = [self.mainTableViewControllers indexOfObject:viewController];

    if (mainTableViewControllerIndex == (self.mainTableViewControllers.count - 1)) {
        return nil;
    }

    return self.mainTableViewControllers[mainTableViewControllerIndex + 1];
}

#pragma mark - Accessors

- (void)setCurrentPageIndex:(NSUInteger)currentPageIndex
{
    _currentPageIndex = currentPageIndex;
    // TODO: Reflect the value change
    [self updateCurrentPageViewControllerAnimated:YES];
}

@end


text:
class IBlock_Accessible;

namespace Structure
{
    void makePyramid(IBlock_Accessible& access,
                      const Block::Position& pos,
                      Random::Generator<std::mt19937>& random);

}

#endif // BUILDINGS_H_INCLUDED


text:
<resources>
    <string name="app_name">TwitterClient</string>
    <string name="view_more_tweets_button">View More Tweets</string>
</resources>


text:
<?php

namespace Monolog\Processor;

use Monolog\ResettableInterface;

/**
 * Adds a unique identifier into records
 *
 * @author Simon Mönch <sm@webfactory.de>
 */
class UidProcessor implements ProcessorInterface, ResettableInterface
{
    private $uid;

    public function __construct($length = 7)
    {
        if (!is_int($length) || $length > 32 || $length < 1) {
            throw new \InvalidArgumentException('The uid length must be an integer between 1 and 32');
        }

        $this->uid = $this->generateUid($length);
    }

    public function __invoke(array $record)
    {
        $record['extra']['uid'] = $this->uid;

        return $record;
    }

    /**
     * @return string
     */
    public function getUid()
    {
        return $this->uid;
    }

    public function reset()
    {
        $this->uid = $this->generateUid(strlen($this->uid));
    }

    private function generateUid($length)
    {
        return substr(hash('md5', uniqid('', true)), 0, $length);
    }
}


text:
ccflags-y +=-I${ZEPHYR_BASE}/net/ip/contiki
ccflags-y +=-I${ZEPHYR_BASE}/net/ip/contiki/os/lib
ccflags-y +=-I${ZEPHYR_BASE}/net/ip/contiki/os/sys
ccflags-y +=-I${ZEPHYR_BASE}/net/ip/contiki/os
ccflags-y +=-I${ZEPHYR_BASE}/net/ip/tinydtls
ccflags-y +=-I${ZEPHYR_BASE}/net/ip/er-coap
ccflags-y +=-I${ZEPHYR_BASE}/net/ip/rest-engine
ccflags-y +=-I${ZEPHYR_BASE}/net/ip
ccflags-y +=-I${ZEPHYR_BASE}/samples/bluetooth/

obj-y = coap-server.o

ifeq ($(CONFIG_NETWORKING_WITH_BT), y)
	obj-y += ../../../bluetooth/gatt/ipss.o
endif

ifeq ($(CONFIG_NET_TESTING), y)
ccflags-y +=-I${ZEPHYR_BASE}/samples/net/common/
ccflags-y +=-DNET_TESTING_SERVER=1
endif

obj-y += \
	resources/res-plugtest-create1.o \
	resources/res-plugtest-create2.o \
	resources/res-plugtest-create3.o \
	resources/res-plugtest-large.o \
	resources/res-plugtest-large-create.o \
	resources/res-plugtest-large-update.o \
	resources/res-plugtest-links.o \
	resources/res-plugtest-locquery.o \
	resources/res-plugtest-longpath.o \
	resources/res-plugtest-multi.o \
	resources/res-plugtest-obs.o \
	resources/res-plugtest-path.o \
	resources/res-plugtest-query.o \
	resources/res-plugtest-separate.o \
	resources/res-plugtest-test.o \
	resources/res-plugtest-validate.o


text:
var Library = (function() {
    var lib = ["event_title", "event_text", "event_effects", "event_buttons", "event_requirements", "location_name", "location_description",
               "location_threat", "location_ontravel", "location_enemies", "location_event", "location_discover", "location_master",
               "enemy_name", "enemy_health", "enemy_damage", "enemy_event", "item_name", "item_price", "item_event", "item_use", "special_name",
               "special_effect", "special_description"];
    $.each(lib, function(index, value) {
        lib[value] = [];
    });
    return{
        get: function(key, index) {
            if(index !== "undefined" || lib[key][index] !== "undefined") {
                return lib[key][index];
            }else if(index === "undefined" && lib[key] !== "undefined") {
                return lib[key];
            }
            return "undefined";
        },
        set: function(key, id, value) {
            id = parseInt(id);
            key = String(key);
            value = String(value);
            if(id === "undefined" || id === "NaN" || key === "undefined" || value === "undefined") {
                return false;
            }
            lib[key][id] = value;
        }
    }
}());

function xmlparser(txt) {
    var itemId = [], i = 0, use, effects, discoverables, enemies, but, temp, req, event, placeinarr, id, name,
        tags = ["items item", "locations location", "data > enemies enemy", "data > events event", "data > specials special"],
        validreq = ["health", "mana", "strength", "stamina", "agility", "intelligence", "charisma", "libido", "energy", "lust" ,"special" ,"origin", "location", "level"],
        validbuttons = ["event", "travel"], debug = "";
    if($(txt).find("log").text() === "1" || "true") {
        debug = true;
    } else {
        debug = false;
    }
    $.each(tags, function (index, value) {
    itemId = [];
        $(txt).find(value).each(function() {
            use = "";
            discoverables = "";
            enemies = "";
            but = "";
            req = "";
            event = "";
            id = "";
            name = "";
            if($(this).find("id").text() === "") {
                //Empty IDs are not loaded.
                if(debug) {
                    console.log("XMLParser: No ID defined.");
                }
                return;
            }
            if($.inArray($(this).find("id").text(), itemId) !== -1) {
                //Duplicated IDs are not loaded.
                if(debug) {
                    console.log("XMLParser: Did not load duplicated ID.");
                    }
                return;
            }
            id = $(this).find("id").text();
            name = $(this).find("name").text();;
            itemId[i++] = id;
            effects = $(this).find("effects");
            if($(effects).find("heal").length > 0) { use += (use.length > 0 ? "," : "") + "hp;" + $(effects).find("heal").text(); }
            if($(effects).find("mana").length > 0) { use += (use.length > 0 ? "," : "") + "mp;" + $(effects).find("mana").text(); }
            if($(effects).find("experience").length > 0) { use += (use.length > 0 ? "," : "") + "xp;" + $(effects).find("experience").text(); }
            if($(effects).find("libido").length > 0) { use += (use.length > 0 ? "," : "") + "lb;" + $(effects).find("libido").text(); }

            $(this).find("events event").each(function(x, v) {
                event += (event.length > 0 ? "," : "") + $(v).text() + ";" + ($(v).attr("chance") ? $(v).attr("chance") : "100");
            });

            temp = $(this).find("requirement").text();
            $.each(validreq, function(x, v) {
                if($(temp).find(v).length > 0) {
                    req += (req.length > 0 ? "," : "") + v + ";" + $(temp).find(v).text() + ($(temp).find(v).attr("operator") ? $(temp).find(v).attr("operator") : "=");
                }
            });

            if(index === 0) {
                if(name, $(this).find("price").text()) {
                    Library.set("item_name", id, name);
                    Library.set("item_price", id, $(this).find("price").text());
                    Library.set("item_use", id, use);
                    Library.set("item_event", id, event);
                } else {
                    if(debug) {
                        console.log("XMLParser: Item must contain Name and Price.");
                    }
                }
            } else if (index === 1) {
                if(name && $(this).find("onTravel").text() && $(this).find("threat").text()) {
                    $(this).find("discoverable discover").each(function (x, v) {
                        discoverables += (discoverables.length > 0 ? "," : "") + $(v).text();
                    });
                    $(this).find("enemies enemy").each(function (x, v) {
                        enemies += (enemies.length > 0 ? "," : "") + $(v).text();
                    });
                    Library.set("location_name", id, name);
                    Library.set("location_ontravel", id, $(this).find("onTravel").text());
                    Library.set("location_threat", id, $(this).find("threat").text());
                    Library.set("location_discover", id, discoverables);
                    Library.set("location_enemies", id, enemies);
                    Library.set("location_event", id, event);
                    Library.set("location_master", id, $(this).find("master").text());
                } else {
                    if(debug) {
                        console.log("XMLParser: Location must contain Name, OnTravel and Threat.");
                    }
                }
            } else if (index === 2) {
                if(name && $(this).find("health").text() && $(this).find("damage").text()) {
                    Library.set("enemy_name", id, name);
                    Library.set("enemy_health", id, $(this).find("health").text());
                    Library.set("enemy_damage", id, $(this).find("damage").text());
                    Library.set("enemy_event", id, event);
                } else {
                    if(debug) {
                        console.log("XMLParser: Enemy must contain Name, Health and Damage.");
                    }
                }
            } else if (index === 3) {
                if($(this).find("title").text() && $(this).find("text").text()) {
                    temp = $(this).find("buttons button");
                    $.each(temp, function() {
                        placeinarr = $.inArray($(this).attr("type"), validbuttons);
                        if(placeinarr !== -1) {
                            but += (but.length > 0 ? "," : "") + validbuttons[placeinarr] + ";" + $(this).attr("id") + ";" + $(this).text();
                        }
                    });
                    Library.set("event_title", id, $(this).find("title").text());
                    Library.set("event_text", id, $(this).find("text").text());
                    Library.set("event_effects", id, use);
                    Library.set("event_buttons", id, but);
                    Library.set("event_requirements", id, req);
                } else {
                    if(debug) {
                        console.log("XMLParser: Event must contain Title and Text.");
                    }
                }
            } else if (index === 4) {
                if(name && $(this).find("description").text() && use) {
                    Library.set("special_name", id, name);
                    Library.set("special_description", id, $(this).find("description").text());
                    Library.set("special_effect", id, use);
                } else {
                    if(debug) {
                        console.log("XMLParser: Special must contain Name, Description and Effects.");
                    }
                }
            }
        });
    });
}

$.ajax({
url: "data.xml",
isLocal: true,
processData: false,
async: false // Firefox fix
}).done(function(data) {
    xmlparser($(data).find("data"));
}).fail(function() {
});

var player = (function () {
    var stats = {},
        key,
        changeExceptions = ["health", "mana", "energy", "lust"],
        maxValue = ["healthMax", "manaMax", "energyMax", "lustMax"],
        numInArr;
    stats.stamina = 1;
    stats.agility = 1;
    stats.strength = 1;
    stats.libido = 1;
    stats.charisma = 1;
    stats.intelligence = 1;
    stats.skillpoint = 10;
    stats.health = 30;
    stats.healthMax = 30;
    stats.energy = 100;
    stats.energyMax = 100;
    stats.level = 1;
    stats.experience = 0;
    stats.experienceMax = 150;
    stats.lust = 0;
    stats.lustMax = 100;
    stats.gender = 0;
    stats.bodytype = 0;
    stats.haircolor = 0;
    stats.skincolor = 0;
    stats.origin = 0;
    stats.special = 0;
    stats.difficulty = 0;
    stats.name = "";
    stats.surname = "";
    stats.events = "";
    stats.location = 0;
    stats.money = 0;
    stats.inventory = "";
    stats.mana = 20;
    stats.manaMax = 20;
    stats.twelvehourclock = 0;
    stats.home = 0;
    stats.time = 0; //Hours past we started the game.
    stats.customitems = "";
    stats.bgcolorsetting = "";
    stats.locationsdiscovered = "9";
    stats.placesdiscovered = "0";
    stats.equiped_weapon = "";
    stats.equiped_helm = "";
    stats.equiped_chest = "";
    stats.equiped_boots = "";
    stats.equiped_hands = "";
    stats.barter = 1;
    return {
        update_stats : function () {
            stats.healthMax = parseInt(20 * (1 + (stats.stamina * 0.1)), 10);
            stats.experienceMax = parseInt(150 * stats.level, 10);
            stats.lustMax = parseInt(100 + (stats.stamina * 0.5), 10);
            stats.manaMax = parseInt(20 * (1 + (stats.intelligence * 0.1)), 10);
        },
        get: function (key) {
            player.update_stats();
            return stats[key];
        },
        set: function (key, value) {
            if (stats[key] === "undefined") {
                return false;
            }
            player.update_stats();
            stats[key] = value;
            $(".stat ." + key).text(value);
        },
        change: function (key, value) {
            /* Contrary to set, change adds or remove the value. */
            player.update_stats();
            stats[key] = parseInt(stats[key], 10) + parseInt(value, 10);
            if (stats[key] < 0) {
                stats[key] = 0;
            }
            if($.inArray(key, changeExceptions) !== -1) {
                numInArr = $.inArray(key, changeExceptions);
                if(stats[key] > stats[maxValue[numInArr]]) {
                    stats[key] = stats[maxValue[numInArr]];
                }
            }
            $(".stat ." + key).text(stats[key]);
        },
        add : function (key, value) {
            /*  String version of change */
            if (typeof stats[key] !== "string") {
                return false;
            }
            stats[key] += (stats[key].length > 0 ? "," + value : value);
        },
        arr: function (key, divider) {
            if (typeof stats[key] !== "string") {
                return false;
            }
            if (!divider) {
                divider = ";";
            }
            return stats[key].split(divider);
        },
        len : function(key) {
            if (typeof stats[key] === "undefined") {
                return false;
            }
            return stats[key].length;
        },
        savegame : function() {
            if ('localStorage' in window && window.localStorage !== null) {
                localStorage.clear();
                localStorage.setItem("acceptwarning", true);
                $.each(stats, function (index, value) {
                    localStorage.setItem(index, Base64.encode(String(value)));
                });
            }
        },
        savefile : function () {
            if (url){ URL.revokeObjectURL(url); }else { var url; }
            var savefile = "";
            $.each(stats, function (index, value) {
                if (!value && value !== 0){ value = ""; }
                savefile += Base64.encode(String(index))+ " " +Base64.encode(String(value))+ "\n";
            });
            window.open("data:text/save;base64," + Base64.encode(savefile));

        },
        loadgame : function () {
            if ('localStorage' in window && window.localStorage !== null) {
                var checklist = ["stamina","agility","strength","libido","charisma","intelligence","skillpoint","health","health_max","energy","energy_max","level","experience","experience_max","lust","lust_max","gender","bodytype","haircolor","skincolor","origin","special","difficulty","name","surname","events","location","money","inventory","mana","mana_max","bj_bet","twelvehourclock","home","time","customitems","bgcolorsetting","locationsdiscovered","placesdiscovered","costumitems", "equiped_weapon", "equiped_chest", "equiped_boots", "equiped_helm", "equiped_hands"],
                i;
              for (i = 0; i < checklist.length; i++) {
                    player.set(checklist[i], (localStorage.getItem(checklist[i])?Base64.decode(String(localStorage.getItem(checklist[i]))):""));
                    $(".stat ." + checklist[i]).text(stats[checklist[i]]);
                }
            }
            go2base();
        }
    };
}());
var c = [];
c.id = -1;
c.hp = -1;
c.hp_max = -1;
c.gender = -1;
c.level = -1;
c.combatlog = "";
var overlaylock = "",
    spendingskillpoints = 0,
    rolling = 0,
    isplayingdj = 0,
    havepressedstand = 1,
    tempcustomitem = "",
    difficulty_multiplier = [0.5, 0.75, 1, 1.25, 1.5];
var openmenu = {};
openmenu.save = 0;
openmenu.load = 0;
var currentSmallWindow = "";
var listofvalues = ["strength", "agility", "charisma", "stamina", "energy", "intelligence"];
var short_listofvalues = ["str", "agi", "cha", "sta", "ene", "int"];
var page_settings_colors = ["#468966","#FFF0A5", "#FFB03B", "#B64926", "#8E2800", "#39322f", "#94bce0", "#466fb0", "#5c3547", "#ffffff", "#cec5c2", "#323233"];
var valid = ["health", "lust", "energy", "experience", "mana", "chealth"];

$(document).ready(function () {
  "use strict";
    startgame();
    $(".page_settings_rgb_input").keyup(function (event) {
        $(event.target).val($(event.target).val().replace(/[^\d]/g, ""));
        if ($(event.target).val()>255){
            $(event.target).val(255);
        }
        preview_color($("#page_settings_rgb_red").val()+ "," +$("#page_settings_rgb_green").val()+ "," +$("#page_settings_rgb_blue").val());
    });
    $.each(page_settings_colors, function (index, value) {
        $("#page_settings_color_frame").append("

");
    });

    var URL = window.webkitURL || window.URL;

    var url;

    $("#text_save_button").click(function () {
        player.savefile();
    });
    $("#save_button").click(function () {
        player.savegame();
        open_menu('save', '#save_context_menu_button');
    });

    $("#savecolor, #dontsavecolor").click(function() {
        if($(this).text() === "Save") {
            savecolor(1);
        }else{
            savecolor(0);
        }
    });

    $("#ng_load button, #load_file").click(function() {
        small_window('load');
    });

    $("#load_game").click(function() {
        player.loadgame();
    });

    $("#new_game").click(function() {
        new_game();
    });

    $("#overlay").click(function() {
        if(!localStorage.getItem("acceptwarning")) { return; }
        if($("#small_window").css("display") === "block") {
            overlay("#small_window");
        }else if($("#page_settings").css("display") === "block") {
            overlay("#page_settings");
        }
    });
});

function sortSparseArray(arr) {
    "use strict";
    var tempArr = [];
    var indexes = [];
    for (var i = 0; i < arr.length; i++) {
        // find all array elements that exist
        if (arr[i] !== undefined) {
            tempArr.push(arr[i]);    // save value
            indexes.push(i);         // save index
        }
    }
    // sort values
    tempArr.sort();
    // put sorted values back into the indexes in the original array that were used
    for (i = 0; i < indexes.length; i++) {
        arr[indexes[i]] = tempArr[i];
    }
    return(arr);
}

function event(id) {
    if(Library.get("event_title", id) === false) {
        return false;
    }
    var tmp;
    $.each(Events.arr("requirement", id, ";"), function(index, value) {
        switch(value[2]) {
            case "=":
                if(Player.get(value[0]) === value[1]) {
                    return false;
                }
            break;
            case ">":
                if(value[1] < Player.get(value[0])) {
                    return false;
                }
            break;
            case "<":
                if(value[1] > Player.get(value[0])) {
                    return false;
                }
            break;
            case ">=":
                if(value[1] <= Player.get(value[0])) {
                    return false;
                }
            break;
            case "<=":
                if(value[1] >= Player.get(value[0])) {
                    return false;
                }
            break;
        }
    });
    $("#content").html("
" + Library.get("event_title", id) + "
" + Library.get("event_text", id));
    if(Library.get("event_buttons", id)) {
        tmp = Library.get("event_buttons", id).split(";");
        action_bar(tmp[0] + ";" + tmp[1] + (tmp[2] ? ";" + tmp[2] : ""));
    }
}

function equip_item(custom_item_id) {
    "use strict";
    var item = player.arr("customitems")[custom_item_id],
        olditem,
        itemtype = parseInt(item.split(",")[9], 10);

    var tmp_customitem = player.arr("customitems");
        tmp_customitem.splice(custom_item_id, 1);
        player.set("customitems", tmp_customitem.join(";"));

    if(itemtype === 0) {
        //Weapon
        olditem = player.get("equiped_weapon");
        player.set("equiped_weapon", item);
    }else if(itemtype === 1) {
        //Chest
        olditem = player.get("equiped_chest");
       player.set("equiped_chest", item);
    }else if(itemtype === 2) {
        //Boots
        olditem = player.get("equiped_boots");
        player.set("equiped_boots", item);
    }else if(itemtype === 3) {
        //Helm
        olditem = player.get("equiped_helm");
        player.set("equiped_helm", item);
    }else if(itemtype === 4) {
        //Gloves
        olditem = player.get("equiped_hands");
        player.set("equiped_hands", item);
    }else {
        //If something were to happen just return the item we tried to equip.
        olditem = item;
        return;
    }
    /*  Strength, Stamina, Agility, Charisma, Intelligence, Damage  */
    if (olditem.length > 0) {
        player.add("customitems", olditem);
        olditem = olditem.split(",");
        player.change("strength", -olditem[1]);
        player.change("stamina", -olditem[2]);
        player.change("agility", -olditem[3]);
        player.change("charisma", -olditem[4]);
        player.change("intelligence", -olditem[5]);
    }
    item = item.split(",");
    player.change("strength", item[1]);
    player.change("stamina", item[2]);
    player.change("agility", item[3]);
    player.change("charisma", item[4]);
    player.change("intelligence", item[5]);
    initiate();

    if ($("#small_window").css("display")==="block"){ $("#item_hover").hide(); show_inventory(true); }
}

function rgb2hex(rgb) {
    "use strict";
    rgb = rgb.replace(/#/, "");
    if (rgb.length<6){ return -1; }
    var hex = parseInt(rgb.slice(0,2), 16)+ "," +parseInt(rgb.slice(2,4), 16)+ "," +parseInt(rgb.slice(4,6), 16);
    return hex;
}
function savecolor(v) {
    "use strict";
    if (v===0) {
        overlay("#page_settings");
        preview_color(player.get("bgcolorsetting"));
    }else if (v===1) {
        overlay("#page_settings");
        player.set("bgcolorsetting", $("#page_settings_rgb_red").val()+ "," +$("#page_settings_rgb_green").val()+ "," +$("#page_settings_rgb_blue").val());
    }
    return;
}
function preview_color(c) {
    "use strict";
    if (/#/.test(c) === true){ c=rgb2hex(c); }
    $("#page_settings_rgb_red").val(c.split(",")[0]);
    $("#page_settings_rgb_green").val(c.split(",")[1]);
    $("#page_settings_rgb_blue").val(c.split(",")[2]);
    $("#page_settings_rgb_preview").css("background", "rgb(" +c.split(",")[0]+ "," +c.split(",")[1]+ "," +c.split(",")[2]+ ")");
    document.body.style.backgroundColor = "rgb(" +c+ ")";
}
function new_game() {
    "use strict";
    var r = confirm("Are you sure you want to start a new game?\nYour current save will be DELETED.\nIf you want to start a new game but be able to return, please use the Text Save button first.");
    if (r === true) {
        localStorage.clear();
        $("#new_character").fadeIn(300);
        startgame();
    }
    return;
}

function shuffle(array) {
    "use strict";
    var tmp, current, top = array.length;
    if (top) {
    while (--top) {
        current = Math.floor(Math.random() * (top + 1));
        tmp = array[current];
        array[current] = array[top];
        array[top] = tmp;
        }
    }
    return array;
}

function overlay(element) {
    "use strict";
    if($("#overlay").css("display") === "none") {
        $(element).fadeIn(150);
        $("#overlay").fadeIn(150);
    }else{
        $(element).fadeOut(150);
        $("#overlay").fadeOut(150);
        if(currentSmallWindow.length>0) {
            $(currentSmallWindow).fadeOut(150);
            currentSmallWindow = "";
        }
    }
}

function ng_slide(page) {
    "use strict";
    $("#ng_slider").css({ "left": "-" + (page * 1200) + "px" });
    $(".ng_select").eq(page).css({
        "background": "#188acb",
        "color" : "#ffffff"
    });
    $(".ng_select").filter(function (index) {
        return index !== page;
    }).css({
        "background": "",
        "color" : "#333"
    });
    return;
}

function meter(id, value, max, cname) {
    "use strict";
    var dist = 0,
        i;
    if ($.inArray(id.replace(/#/, ""), valid) < 0) {
        return;
    }
    if (value > max) {
        value = max;
    }
    value = Math.floor(value);
    var oval = ($(id).data("value") ? $(id).data("value") : 0);
    $(id).data("value", value);
    var multiplier = 176/100,
    y = 0,
    obj = $(id).find('.meter').css("width").replace(/px/, "");
    $(id).find('.meter').css("width", (multiplier * ((value / max) * 100)));
    $(id).find('.text').html((cname?cname:id.slice(1)) + "" + value + "/" + max + "");
}

function initiate() {
    "use strict";
    meter('#health', player.get("health"), player.get("healthMax"));
    meter('#experience', player.get("experience"), player.get("experienceMax"));
    meter('#energy', player.get("energy"), player.get("energyMax"));
    meter('#lust', player.get("lust"), player.get("lustMax"));
    meter('#mana', player.get("mana"), player.get("manaMax"));
    $('.charactername').text(player.get("name") + (player.len("surname") > 0 ? "" + player.get("surname") : ""));
    clock(0);
}

function item_description(id) {
    "use strict";
    var out = "";
    if (Library.get("item_use", id) !== "undefined"){
        $.each(Library.get("item_use", id).split(","), function (index, value) {
            switch(value.split(";")[0]) {
                case 'hp':
                    out += "Restores " + value.split(";")[1] * (player.get("special")===12 ? 1.25 : 1) + " health.";
                break;
                case 'mp':
                    out += "Restores " + value.split(";")[1] * (player.get("special")===12 ? 1.25 : 1) + " mana.";
                break;
                case 'uk':
                    out += "Unknown effect.";
                break;
            }
        });
    }
    return out;
}

function use_item(id) {
    "use strict";
    editinventory(id, 1, true);
    if ($("#small_window").css("display")==="block"){
        overlay("#small_window");
    }
    $.each(Library.get("item_use", id).split(","), function (index, value) {
        switch(value.split(";")[0]) {
            case 'hp':
                player_hp(value.split(";")[1] * (player.get("special")===12 ? 1.25 : 1));
            break;
            case 'mp':
                player_mp(value.split(";")[1] * (player.get("special")===12 ? 1.25 : 1));
            break;
            case 'uk':
                switch(Math.floor(Math.random()*5))
                    {
                        case 0:
                             player_hp(10 * (player.get("special")===12 ? 1.25 : 1));
                        break;
                        case 1:
                             player_mp(10 * (player.get("special")===12 ? 1.25 : 1));
                        break;
                        case 2:
                             player_hp(-(10  * (player.get("special")===12 ? 1.25 : 1)));
                        break;
                        case 3:
                             player_mp(String(-(10 * (player.get("special") === 12 ? 1.25 : 1))));
                        break;
                        case 4:
                            xp(player.get("level") * 1000);
                        break;
                    }
            break;
        }
    });
}

function xp(add) {
    "use strict";
    player.change("experience", parseInt(add, 10) * (player.get("special") === 14 ? 1.10 : 1));
    while (player.get("experience") >= player.get("experienceMax")) { /*  Level up  */
        player.change("level", 1);
        player.change("skillpoint", 5);
        player.change("experience", -player.get("experienceMax"));
        $(".level").text(player.get("level"));
        $(".skillpoint").text(player.get("skillpoint"));
        player.set("experienceMax", 150 * player.get("level"));
    }
    meter('#experience',player.get("experience"), player.get("experienceMax"));
}

function player_mp(nval) {
    "use strict";
    player.change("mana", nval);
    meter("#mana", player.get("mana"), player.get("manaMax"));
}

function player_hp(nval) {
    "use strict";
    player.change("health", nval)
    meter('#health', player.get("health"), player.get("healthMax"));
}

var SkillSelect = function (element) {
    "use strict";
    var atr = {};
    atr.strength = 0,
    atr.intelligence = 0,
    atr.agility = 0,
    atr.charisma = 0,
    atr.stamina = 0,
    atr.skillpoint = 0;
    return {
        updateAtr : function () {
            $.each(atr, function(index) {
                atr[index] = player.get(index);
                $(element + " input." + index).val(atr[index]);
            });
        },
        increase : function (key) {
            if(atr.skillpoint<1){
                return;
            }
            atr.skillpoint--;
            atr[key]++
            $(element + " input." + key).val(atr[key]);
            $(element + " input.skillpoint").val(atr.skillpoint);
        },
        decrease : function (key) {
            if(atr[key] - 1 < player.get(key)) {
                return;
            }
            atr.skillpoint++;
            atr[key]--;
            $(element + " input." + key).val(atr[key]);
            $(element + " input.skillpoint").val(atr.skillpoint);
        },
        save : function () {
            $.each(atr, function(index, value) {
                player.set(index, value);
            });
            player.savegame();
            initiate();
        }
    }
}

var NewGame = function () {
    var atr = {}, error;
    atr.gender;
    atr.bodytype;
    atr.haircolor;
    atr.skincolor;
    atr.origin;
    atr.special;
    atr.difficulty;
    atr.name;
    atr.surname;

    return {
        set : function (key, change) {
            atr[key] = change;
            error = 0;
            if(typeof atr.gender === "undefined") { error = 1; }
            if(typeof atr.bodytype === "undefined") { error = 1; }
            if(typeof atr.haircolor === "undefined") { error = 1; }
            if(typeof atr.skincolor === "undefined") { error = 1; }
            if(typeof atr.origin === "undefined") { error = 1; }
            if(typeof atr.special === "undefined") { error = 1; }
            if(typeof atr.difficulty === "undefined") { error = 1; }
            if(typeof atr.name === "undefined") { error = 1; }
            if(error !== 1) {
                $('#ng_finish_button').removeAttr("disabled").addClass("focus");
            }
        },
        save : function () {
            $.each(atr, function(index, value) {
                player.set(index, value);
            });
        $('#new_character').fadeOut(400);
        $('#main').fadeIn(600);
        $('#content').html("" + story[0] + "..." + startingtext[atr.origin] + "
");
        action_bar("5");
        player.savegame();
        initiate();
        }
    }
};

function finish_ng() {
    "use strict";
    go2base();
    $('#new_character').fadeOut(400);
    $('#main').fadeIn(600);
    player.savegame();
    initiate();
}

function popup(preset, title, desc) {
    "use strict";
    if (!preset) {
        preset = false;
    }
    overlay("#popup");
    if (preset !== false) {
        title = popup_preset[preset].split("|")[0];
        desc = popup_preset[preset].split("|")[1];
    }
    $("#popup").find("h2").text(title);
    $("#popup").find("span").text(desc);
}

function small_window(preset, custom) {
    "use strict";
    overlay("#small_window");
    switch(preset) {
        case 'warning':
            $("#explicit").show();
            currentSmallWindow = "#explicit";
        break;
        case 'load':
            $("#loadfromfile").show();
            currentSmallWindow = "#loadfromfile";
        break;
        case 'skill':
            $("#spendpoints").show();
            currentSmallWindow = "#spendpoints";
            var skill = new SkillSelect("#spendpoints");
            skill.updateAtr();
            $("#spendpoints").find("button").mousedown(function() {
                var key = $(this).parent().attr("id");
                if($.inArray(key, ["strength", "stamina", "charisma", "intelligence", "agility", "skillpoint"]) === -1) {
                    return;
                }
                if($(this).text() === "+") {
                    skill.increase(key);
                }else{
                    skill.decrease(key);
                }
            });
            $("#saveskillpoints").click(function() {
                skill.save();
                overlay("#small_window");
            });
        break;
    }
    if(custom) {
        $("#customwindow").html("
✖
" + custom);
        $("#customwindow").show();
        currentSmallWindow = "#customwindow";
    }
    if (preset==='load') {
        var dropZone = document.getElementById('drop_zone');
        dropZone.addEventListener('dragover', handleDragOver, false);
        dropZone.addEventListener('drop', readBlob, false);
    }
}

function explore() {
    "use strict";
    var tmp = "
Exploration & Travel
",
    exploration = "",
    travel = "";

    $.each(player.arr("locationsdiscovered", ","), function (index, value) {
        if (location_place_master[value]){
            travel += "
" + Library.get("location_name", value) + "
";
        }else{
             exploration += "
" + Library.get("location_name", value) + "
";
        }
    });

    tmp += "

Exploration
" + exploration + "
";
    tmp += "

Travel
" + travel + "
";
    $("#content").html(tmp);
}

function go2location(id) {
    "use strict";
    var temp;
    if(Library.get("location_event", id)) {
        temp = shuffle(Library.get("location_event", id).split(","));
        $.each(temp, function(index, value) {
            if(Math.random() * value.split(";")[1] > Math.random() * 100) {
                if(event(value) !== false) {
                    return;
                }
            }
        });
    }
    if (parseInt(player.get("energy"), 10) - 8 < 0) {
        popup(2);
        return;
    } /*  Not enough energy  */
    var tmp = Math.floor(Math.random()*5)+1,
        i;
    clock(tmp);
    player.set("location", id);
    if (5 * tmp>player.get("energy")){ tmp = player.get("energy") / 10; }
    energy(-5 * tmp);
    if (Math.random() * Library.get("location_threat", id) > Math.random() * 100) {
        combat(); return;
    }
    var out = "
" + Library.get("location_name", id) + "
dfgfdgfdgfd
" + Library.get("location_description", id) + "
",
        randomlyselecteddiscovery = false;
    if (Library.get("location_discover", id)){
        var chanceofdiscoveryarray = [];
        var chanceofdiscoverysum = 0;
        $.each(Library.get("location_discover", id).split(","), function (index, value) {
            if ($.inArray(value, player.arr("locationsdiscovered", ","))===-1) {
                chanceofdiscoverysum += (value.split(";")||value.split(";")===0?(value.split(";")?100:value.split(";")):10)+1;
                chanceofdiscoveryarray[index] = chanceofdiscoverysum;
            }
        });
        var n = Math.random()*chanceofdiscoverysum;
        if (Math.random()*100<(n*tmp)) { /*  I know, it's ugly, I'm rusty at chance. I figured this will give an estimate. It's no big deal really. */
            for(i=0;i<chanceofdiscoveryarray.length;i++) {
            if (n<chanceofdiscoveryarray[i]){ randomlyselecteddiscovery = i; break; }
        }
        player.add("locationsdiscovered", Library.get("location_discover", id).split(",")[randomlyselecteddiscovery]);
        out += "After " +tmp+ " hour(s) of exploring you spot something. ";
        out += "You have discovered " + Library.get("location_name", randomlyselecteddiscovery) + ".";
        }
    }
    if (!randomlyselecteddiscovery&&!Library.get("location_master", id)) {
        out += "After scouering around for " + tmp + " hour(s), you decide to head back to your camp.";
    }
    if (Library.get("location_master", id)) {
        out += Library.get("location_description", id);
        action_bar("0;0,6");
    }else{
        action_bar("6");
    }
    $("#content").html(out);
}
function go2base() {
   "use strict";
    player.set("location", -1);
    var out = "
Camp
";
    action_bar("5,0");
    $("#content").html(out);
}

function combat(action, enemy_id) {
  "use strict";
    if (c.id===-1) {
        if (!enemy_id) {
            if (!location_spawn[player.get("location")]) {
                return -1;
            }
            c.id = location_spawn[player.get("location")].split(",")[Math.floor(Math.random() * location_spawn[player.get("location")].split(",").length)];
        }
        c.combatlog = "";
        c.gender = (!enemy_gender[enemy_id]?Math.floor(Math.random()*3)+1:enemy_gender[enemy_id]);
        c.level = player.get("level");
        c.hp = Math.floor((enemy_basehp[c.id]*(c.level*0.25))*(1+Math.random()*0.1));
        c.hp_max = c.hp;
        action_bar("7;1,7;5", "Attack,Escape");
        var out = "
" +c.level+ " " +gender_name[c.gender]+ " " +enemy_name[c.id]+ "

";
        $("#content").html(out);
        meter('#chealth', c.hp, c.hp_max, enemy_name[c.id]);
    }
    if (player.get("energy") < 1 && c.hp > 1){ c.combatlog += "You are so exhausted that you simply cannot muster anymore resistance. You are now at the whim of " +enemy_name[c.id]+ "."; action=4; }
        switch(action) {
        case 0:
            action_bar("7;1,7;5", "Attack,Escape");
        break;
        case 1:
            var player_damage = parseInt(player.get("strength"), 10);
            if (Math.random() * 100 < (Math.random()*player.get("agility")) / 2.66) {
                /* Critical Strike, 75% chance at 200 agility. */
                player_damage = player_damage*2;
            }
            c.hp = parseInt(c.hp, 10)-player_damage;
            meter('#chealth', c.hp, c.hp_max, enemy_name[c.id]);
            energy(-3);
            c.combatlog += "You attack " +enemy_name[c.id]+ " for " +player_damage+ " health.
";
            if (c.hp<0) { combat(3); } else { combat(2); }
        break;
        case 2:
            var monster_damage = (enemy_basedmg[c.id]*c.level) * difficulty_multiplier[player.get("difficulty")];
            player_hp(-monster_damage);
            if (player.get("health") <= 0){ combat(4); return; }else{
                combat(0);
                c.combatlog += enemy_name[c.id]+ " attacks you for " +monster_damage+ " health.
";
            }
        break;
        case 3:
            var monster_value = Math.floor(((c.level*enemy_basedmg[c.id])*Math.random()*5+1)*(player.get("special") === 11 ? 1.10 : 1));
            var monster_xp = Math.floor((c.level*0.25)*((c.hp_max/enemy_basedmg[c.id])));
            player.change("money", monster_value);
            xp(monster_xp);
            c.combatlog += "You quickly finish " +enemy_name[c.id]+ ". On the body you find $" +monster_value+ ". You recive " +monster_xp+ " experience points.";
            c.id = -1;
            c.hp = -1;
            c.hp_max = -1;
            c.gender = -1;
            c.level = -1;
            action_bar("6");
        break;
        case 4:
            var passouttime = Math.floor(Math.random()*12);
            var coinlost = Math.floor(((c.level*enemy_basedmg[c.id])*Math.random()*5+1));
            c.combatlog += "You pass out. You wake up " +passouttime+ " hour(s) later. Missing $" +coinlost+ ". You head back to camp, tail between your legs.
";
            player.change("money", -coinlost);
            player_sleep(passouttime);
            action_bar("6");
            c.id = -1;
            c.hp = -1;
            c.hp_max = -1;
            c.gender = -1;
            c.level = -1;
        break;
        case 5:
            energy(-10);
            if (Math.random()*(player.get("agility") * 2.66) > Math.random() * 100) {
                c.combatlog += "You managed to escape unharmed.
";
                c.id = -1;
                c.hp = -1;
                c.hp_max = -1;
                c.gender = -1;
                c.level = -1;
                action_bar("5");
            }else{
                c.combatlog += "You try to run, but ultimately it's just a waste of breath. You quickly find yourself engaged in combat again.
";
                action_bar("6;2", "Next");
            }
        break;
    }
    $("#combat-log").html(c.combatlog);
    $("#combat-log").scrollTop(document.getElementById("combat-log").scrollHeight);
}

function generate_item(itemtype) {
    "use strict";
    if (!itemtype && itemtype !== 0) { /*  Decides if it's a weapon or a piece of armor  */
        itemtype = Math.round(Math.random() * 4);
    }
    var itemtypebasearmor = [1, 1, 0.6, 0.8, 0.6],
        itemlowerlimit = player.get("level"),
        itemupperlimit = Math.round(player.get("level") * 3),
        rarity = Math.floor(Math.random() * 175) + 25; /*  Let minimum value be around 25 or so or items will be shit.  */
    if (Math.random() * 100 > 20 && rarity > 100) {
        rarity = Math.floor(rarity / 2);
    } /*  80% Chance that the rarity value will be cut by half.  */
    var itemvalue = Math.floor((Math.random() * itemupperlimit) * (rarity / 100) + itemlowerlimit),
        pointsleft = itemvalue,
        highest = 0,
        temp = [0, 1, 2, 3, 4, 5],
        tmp;
    /*  Strength, Stamina, Agility, Charisma, Intelligence, Damage  */
    var attributes = [];
    attributes[0] = 0;
    attributes[1] = 0;
    attributes[2] = 0;
    attributes[3] = 0;
    attributes[4] = 0;
    attributes[5] = 0;
    shuffle(temp);
    var x = 0,
        hi = 0;
    $.each(attributes, function (index) {
        tmp = Math.round(Math.random() * pointsleft);
        attributes[temp[x]] = tmp;
        pointsleft -= tmp;
        if (tmp > highest) {
            highest = tmp;
            hi = temp[x];
        }
        x++;
    });
    var damagearmor = (parseInt(itemvalue, 10) + parseInt(pointsleft, 10) + attributes[5])*itemtypebasearmor[itemtype];
    if (damagearmor<1){ damagearmor = 1; }
    var itemtypename = "";
    switch(itemtype) {
        case 0:
            itemtypename = GI_weapon_names[Math.floor(Math.random()*GI_weapon_names.length+1)];
        break;
        case 1:
            itemtypename = GI_chest_names[Math.floor(Math.random()*GI_chest_names.length+1)];
        break;
        case 2:
            itemtypename = GI_boots_names[Math.floor(Math.random()*GI_boots_names.length+1)];
        break;
        case 3:
            itemtypename = GI_helm_names[Math.floor(Math.random()*GI_helm_names.length+1)];
        break;
        case 4:
            itemtypename = GI_gloves_names[Math.floor(Math.random()*GI_gloves_names.length+1)];
        break;
    }
    var itemname = GI_rarity_names[Math.floor(rarity / (200 / GI_rarity_names.length))] + " " + itemtypename + " of " + GI_stat_name[hi];
    return new Array(itemname, attributes, damagearmor, rarity, itemtype, itemvalue); /*  <itemname>, (attribute), <damage/armor>  */
}

function accept_warning() {
    "use strict";
    localStorage.setItem("acceptwarning", true);
    overlay("#small_window", true);
}

function startgame() {
    "use strict";
    var ob;
    if (localStorage.getItem("stamina")) {
        player.loadgame();
        $('#new_character').hide();
        $('#main').fadeIn(300);
    } else {
        if ($("#main").css("display") === "block") {
            $('#main').fadeOut(300);
        }
        $("#new_character").fadeIn(400);
        if (!localStorage.getItem("acceptwarning")) {
            small_window("warning");
        }
        ng_slide(0);
        var ng = NewGame();
        $.each(specialDesc, function(index, value) {
            $("
", {
                "class": "choice",
                "html": value
            }).appendTo("#ng_special_select");
        });
        $("#ng_gender_select .choice").on("click", function() {
        ng.set("gender", $(this).index());
        $("#ng_gender_select .choice").removeClass("selected");
        $(this).addClass("selected");
        });
        $("#ng_finish_button").click(function() {
            ng.save();
        });
        $("#ng_difficulty_select .choice").on("click", function() {
            ng.set("difficulty", $(this).index());
            $("#ng_difficulty_select .choice").removeClass("selected");
            $(this).addClass("selected");
        });
        $("#ng_special_select .choice").on("click", function() {
            ng.set("special", $(this).index());
            $("#ng_special_select .choice").removeClass("selected");
            $(this).addClass("selected");
        });
        $("#ng_skincolor_select .choice").on("click", function() {
            ng.set("skincolor", $(this).index());
            $("#ng_skincolor_select .choice").removeClass("selected");
            $(this).addClass("selected");
        });
        $("#ng_bodytype_select .choice").on("click", function() {
            ng.set("bodytype", $(this).index());
            $("#ng_bodytype_select .choice").removeClass("selected");
            $(this).addClass("selected");
        });
        $("#ng_haircolor_select .choice").on("click", function() {
            ng.set("haircolor", $(this).index());
            $("#ng_haircolor_select .choice").removeClass("selected");
            $(this).addClass("selected");
        });
        var skill = new SkillSelect("#ng_skill_select");
        skill.updateAtr();
        $("#ng_skill_select").find("button").mousedown(function() {
            var key = $(this).parent().attr("id");
            if ($.inArray(key, ["strength", "stamina", "charisma", "intelligence", "agility", "skillpoint"]) === -1) {
                return;
            }
            if ($(this).text() === "+") {
                skill.increase(key);
            } else {
                skill.decrease(key);
            }
        });
        $.each(origin, function (index) {
            ob="";
            $.each(origin_bonus[index].split(","), function (index, value){ ob += (index>0?"
":"")+listofvalues[$.inArray(value.split(":")[0], short_listofvalues)]+ " + " +value.split(":")[1]+ " "; });
            $("
", {
                "class" : "choice",
                "html" : "" + origin[index] + "
" + ob + "
"
            }).appendTo("#ng_origin_select");
        });
        $("#ng_origin_select .choice").on("click", function() {
        ng.set("origin", $(this).index());
        $("#ng_origin_select .choice").removeClass("selected");
        $(this).addClass("selected");
        });
        $('#cname').keyup(function (event) {
            document.getElementById("cname").value = document.getElementById("cname").value.replace(/[^A-Za-z]/g, "");
            setTimeout(function () {
                ng.set("name", $('#cname').val().text());
            }, 10);
        });
        $('#surname').keyup(function () {
            document.getElementById("surname").value = document.getElementById("surname").value.replace(/[^A-Za-z]/g, "");
            setTimeout(function () {
                ng.set("surname", $('#cname').val().text());
            }, 10);
        });
    }
    preview_color(player.get("bgcolorsetting"));
    initiate();
}

function get_price(n, sell) {
    "use strict";
    n = Math.round(n * ((100 - (player.get("charisma") / 2)) / 100))*(player.get("special") === 9 ? 0.95 : 1);
    if (sell) {
        n = n * (player.get("special") === 9 ? 0.55 : 0.5);
    }
    if (n < 0) {
        n = 0;
    }
    return parseInt(n, 10);
}

function energy(nval) {
    "use strict";
    player.change("energy", nval);
    meter('#energy', player.get("energy"), player.get("energyMax"));
}

function readBlob(evt) {
    "use strict";
    evt.stopPropagation();
    evt.preventDefault();
    var files = evt.dataTransfer.files;
    var file = files[0];
    var start = 0;
    var stop = file.size - 1;
    var reader = new FileReader();
    reader.onloadend = function (evt) {
        var checklist = ["c3RhbWluYQ==","YWdpbGl0eQ==","c3RyZW5ndGg=","bGliaWRv","Y2hhcmlzbWE=","aW50ZWxsaWdlbmNl","c2tpbGxwb2ludA==","aGVhbHRo","aGVhbHRoX21heA==","ZW5lcmd5","ZW5lcmd5X21heA==","bGV2ZWw=","ZXhwZXJpZW5jZQ==","ZXhwZXJpZW5jZV9tYXg=","bHVzdA==","bHVzdF9tYXg=","Z2VuZGVy","Ym9keXR5cGU=","aGFpcmNvbG9y","c2tpbmNvbG9y","b3JpZ2lu","c3BlY2lhbA==","ZGlmZmljdWx0eQ==","bmFtZQ==","c3VybmFtZQ==","ZXZlbnRz","bG9jYXRpb24=","bW9uZXk=","aW52ZW50b3J5","bWFuYQ==","bWFuYV9tYXg=","YmpfYmV0","dHdlbHZlaG91cmNsb2Nr","aG9tZQ==","dGltZQ==","Y3VzdG9taXRlbXM=","Ymdjb2xvcnNldHRpbmc=","bG9jYXRpb25zZGlzY292ZXJlZA==","cGxhY2VzZGlzY292ZXJlZA==","ZXF1aXBlZF93ZWFwb24=","ZXF1aXBlZF9oZWxt","ZXF1aXBlZF9jaGVzdA==","ZXF1aXBlZF9ib290cw==","ZXF1aXBlZF9oYW5kcw=="],
        loadgame = evt.target.result,
        temp = String(loadgame.split("\n")),
        i = null;

        var error = "";
        for (i = 0; i < checklist.length; i++) {
            if (checklist[i] !== temp.split(",")[i].split(" ")[0]) {
                error += "\nLooked for: " +checklist[i]+ " But found: " +temp.split(",")[i].split(" ")[0];
            }
        }
        if (error.length>0) {
            alert(error + "!\nThe save file is corrupt!\nIf you think it should work, try another version of the game.");
            return;
        }
        for (i = 0; i < checklist.length; i++) {
            player.set(Base64.decode(temp.split(",")[i].split(" ")[0]), Base64.decode(temp.split(",")[i].split(" ")[1]));
        }
        overlay("#small_window");
        finish_ng(1);
    };
    var blob = file.slice(start, stop + 1);
    reader.readAsBinaryString(blob);
}

function vendor(id) {
    "use strict";
    if (!id && id!==0) {
        return;
    }
    var tmp = "
" + vendor_name[id] + "
" + vendor_dialogue[id] + "
";
    $.each(vendor_items[id], function (index, value) {
        tmp += "
" + Library.get("item_name", value) + "$" + get_price(Library.get("item_price", value)) + "" + item_description(value) + "
";
    });
    $("#content").html(tmp);
    action_bar("4;" +id+ ",3");
}
function gamble(action) {
    "use strict";
    var out = "
Gamble
";
        out += "All of the prices are " +get_price(player.get("level")*50)+ "";
        action_bar("8;0;Buy Weapon,8;1;Buy Chest piece,8;2;Buy Boots,8;3;Buy Helmet,8;4;Buy Gloves,6");
        var attributes_names = ["Strength", "Stamina", "Agility", "Charisma", "Intelligence", "Damage"];
    if (action || action === 0) {
        var tempcustomitem = generate_item(action);
        out += item_display(tempcustomitem);
    }
    player.set("customitems", (player.len("customitems") > 0 ? ";" : "") + String(tempcustomitem));
    $("#content").html(out);
}
function buy_item(id, amount) {
    "use strict";
    if (!amount){ amount = 1; }
    if (get_price(Library.get("item_price", id)*amount)>player.get("money")){ popup(1); return; }
    player.change("money",-get_price(Library.get("item_price", id)));
    editinventory(id, amount);
}
function sell_item_menu() {
    "use strict";
    var out="
Sell Items
";
    if (player.len("inventory") <= 0){ out+="Your inventory is empty!"; }else{
        $.each(player.arr("inventory", ","), function (index, value) {
            out += "
" + Library.get("item_name", value.split(";")[0]) + "$" + get_price(Library.get("item_price", value.split(";")[0]), true) + "Amount: " + value.split(";")[1] + "" + item_description(value.split(";")[0]) + "
";
        });
    }
    $("#content").html(out);
}
function sell_item(id, amount) {
    "use strict";
    if (!amount){ amount = 1; }
    player.change("money", get_price(Library.get("item_price", id)));
    editinventory(id, amount, true);
    sell_item_menu();
}
function editinventory(id, amount, remove) {
    "use strict";
    /* If remove isn't set, the item*amount will be ADDED. */
    var position = null,
        available_amount = null,
        tmp = null;
    if ($.inArray(String(id), player.get("inventory").replace(/[;](\d*)($|,)/g, ",").split(","))!==-1){
        position = $.inArray(String(id), player.get("inventory").replace(/[;](\d*)($|,)/g, ",").split(","));
        available_amount = parseInt(player.arr("inventory", ",")[position].split(";")[1], 10);
    }
    if (!remove) {
        if (!position&&position!==0) {
            /* Item doesn't exist in inventory, add new item.*/
            player.add("inventory", id+ ";" +amount);
        }else{
            /* Item DOES exist, edit current. */
            tmp = player.arr("inventory", ",");
            tmp[position] = id+ ";" +(available_amount+parseInt(amount, 10));
            player.set("inventory", String(tmp));
        }
    }else{
        if (position===-1){ return false; }
        if (available_amount<=amount) {
            tmp = player.get("inventory");
            tmp = tmp.split(",");
            tmp.splice(position, 1);
            player.set("inventory", String(tmp));
        }else{
            tmp = player.arr("inventory", ",");
            tmp[position] = id+ ";" +parseInt(available_amount-amount, 10);
            player.set("inventory", String(tmp));
        }
    }
}

function show_inventory(update) {
    "use strict";
    var out = "";
    if (!update) {
    out = "
Inventory

Misc.

Weapon & Armor

";
    }
    if (player.len("inventory") > 0) {
        $.each(player.arr("inventory", ","), function (index, value) {
            out += "
" + (value.split(";")[1]?value.split(";")[1]:1) + " " + Library.get("item_name", value.split(";")[0]) + "" +item_description(value.split(";")[0])+ "
";
        });
    }
    if (!update) {
        out += "

";
    }
    if (update) {
        $("#inventory-mi").html(out);
        out = "";
        $("#inventory-wa").html("");
    }
    if (!update) {
        out += "
";
        small_window('', out);
    }
    /*  Strength, Stamina, Agility, Charisma, Intelligence, Damage  */
    var itemtypes = ["equiped_weapon", "equiped_chest", "equiped_boots", "equiped_helm", "equiped_hands"];
    if (player.len("customitems") > 0) {
            $.each(player.arr("customitems"), function (index, value) {
                $("
", {
                    "class": "item",
                    html: item_display(value, index, true),
                    mouseenter: function () {
                        var pos = $(this).offset();
                        $('#item_hover').show().css({
                            left: pos.left - 430 + "px",
                            top: pos.top + "px"
                        }).html(item_display(player.get([itemtypes[value.split(",")[9]]])));
                    },
                    mouseleave: function () {
                            $('#item_hover').hide();
                    }
                }).appendTo("#inventory-wa");
            });

        }
}

function item_display(item, id, compare) {
    "use strict";
    if (item.length<1){
        return "You have nothing equiped in this slot.";
    }
    var attributes_names = ["Strength", "Stamina", "Agility", "Charisma", "Intelligence", "Damage"],
    itemtypes = ["equiped_weapon", "equiped_chest", "equiped_boots", "equiped_helm", "equiped_hands"],
    attributes = "",
    compclass = "",
    value = String(item).split(","),
    i = 1;
    compare = (player.len(itemtypes[value[9]]) > 0 ? player.arr(itemtypes[value[9]])[8] : 0);
    attributes = (value[9]===0?"<div class='extra-object " +(compare?(compare<value[7]?"better":"worse"):"")+ "'>Damage " +value[7]+ "(+ " +value[6]+ ")
":"<div class='extra-object " +(compare<value[7]?"better":"worse")+ "'>Armor " +value[7]+ "
");
    var b = (value[9]===0?6:7);
    for(i;i0) {
            compare = (player.len(itemtypes[value[9]]) > 0 ? player.arr(itemtypes[value[9]])[i]:0);
            if (compare===value[i]) { compclass = ""; }
            if (compare<value[i]) { compclass = "better"; }
            if (compare>value[i]) { compclass = "worse"; }
            attributes += (attributes.length>0?"":"")+ "
" +attributes_names[i-1]+ " + " +value[i]+ "
";
        }
    }
    var raritycolor = Math.floor(value[8]/33.4);
        return "
" +value[0]+ " ilvl " +value[10]+ "

" +attributes+ "
" +(id||id===0? "<button onclick='equip_item(" +id+ ")' class='item-equip-button'>Equip</button>" : "");
}

function handleDragOver(evt) {
    "use strict";
    evt.stopPropagation();
    evt.preventDefault();
    evt.dataTransfer.dropEffect = 'copy';
}

function action_bar(x) {
    "use strict";
    var out="",
        buttons = ["Travel", "vendor", "dwelling", "Sell Items", "Buy Items", "Sleep", "Leave", "Combat", "Gabmle", "Travel", "Event"],
        buttons_function_name = ["explore", "vendor", "buy_dwelling", "sell_item_menu", "vendor", "player_sleep", "go2base", "combat", "gamble", "go2location", "event"];
    $.each(x.split(","), function (index, value) {
        if(typeof parseInt(value.split(";")[0]) !== "number") {
            value = $.inArray(String(value).split(";")[0], buttons_function_name) + (String(value).split(";")[1] ? ";" + String(value).split(";")[1] : "") + (String(value).split(";")[2] ? ";" + String(value).split(";")[2] : "");
        }
        out += "<button onclick='" + buttons_function_name[value.split(";")[0]] + "(" + (value.split(";")[1] ? value.split(";")[1] : "") + ")'>" + (value.split(";")[2] ? value.split(";")[2] : buttons[value.split(";")[0]]) + "</button>";
    });
    $("#action_control").html(out);
}

function change_clock_type() {
    "use strict";
    if (player.get("twelvehourclock") === 0) {
        player.set("twelvehourclock", 1);
        clock(0);
    } else {
        player.set("twelvehourclock", 0);
        clock(0);
    }
}

function clock(t) {
    "use strict";
    var time = Math.floor(parseInt(player.get("time") + t, 10) / 24),
    out;
    time = Math.floor(parseInt(player.get("time") + t, 10) - (time * 24));
    player.change("time", parseInt(t, 10));
    if (player.get("twelvehourclock") === 1) {
        out = (time > 12 ? parseInt(time-12) + ":00 PM" : time + ":00 AM");
    } else {
        out = (time < 10 ? "0" + time : time) + ":00";
    }
    $(".time").text(out);
    $(".day").text(Math.floor(player.get("time")/24));
}

function player_sleep(definedtime) {
    "use strict";
    var energy_per_hour = 12,
        health_percent_per_hour = 0.07,
        mana_percent_per_hour = 0.07,
        timeslept,
        out = "
Camp
";
    if(player.get("energy")===player.get("energyMax")&&player.get("health")===player.get("healthMax")&&player.get("mana")===player.get("manaMax")) {
        out += "You try to sleep, but in vain. All of your stats are as good as they ever are going to be.";
    } else {
        if (!definedtime) {

            if ((player.get("energyMax") - player.get("energy")) / energy_per_hour < 8&&player.get("health")===player.get("healthMax")&&player.get("mana")===player.get("manaMax")) {
                timeslept = Math.floor((player.get("energyMax") - player.get("energy")) / energy_per_hour );
                energy(player.get("energyMax"));
                out += "You slept for " + timeslept + " hour(s), restoring your all of your energy.";
            } else {
                timeslept = 8;
                energy(energy_per_hour * timeslept);
                out += "You slept for 8 hours restoring " + energy_per_hour * 8 + " energy.";
            } /*  Make sure the player doesn't sleep for a really long time if energy is high.  */
            clock(timeslept);
            player_hp(timeslept*(player.get("healthMax")*health_percent_per_hour));
            player_mp(timeslept*(player.get("manaMax")*mana_percent_per_hour));
            out += "
You restored " +Math.floor(timeslept*(player.get("manaMax")*mana_percent_per_hour))+ " mana, ";
            out += Math.floor(timeslept*(player.get("healthMax")*health_percent_per_hour))+ " health, while sleeping.
";

        }else{
            timeslept = definedtime;
            clock(timeslept);
            energy(energy_per_hour * timeslept);
            player_hp(timeslept*(player.get("healthMax")*health_percent_per_hour));
            player_mp(timeslept*(player.get("manaMax")*mana_percent_per_hour));
        }
        }
        $("#content").html(out);
}

function open_menu(id, buttonId) {
    "use strict";
    if (openmenu[id] !== 0) { return; } else { openmenu[id] = 1; }
    if ($("#" +id+ "_menu").css("display")==="none") {
        $("#" +id+ "_menu").css("display", "block");
        $("#" +id+ "_menu").css({height: 51});
        $(buttonId).addClass("menu_button_pressed");
        setTimeout(function() {
            openmenu[id] = 0;
        }, 100);
    }else{
        $(buttonId).attr("class", "menu_button");
        $("#" +id+ "_menu").css({height: 0});
        setTimeout(function() {
            $("#" +id+ "_menu").css("display", "none");
            openmenu[id] = 0;
        }, 100);
    }
}


text:
class TestModelsController < ApplicationController
  include RestfulController
end


text:
public class JavaFieldRead {
    public static void main(String[] args) {
        Main m = new Main().variable;
    }
}


text:
package com.anuragkapur.misc;

import org.junit.Test;

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

import static org.junit.Assert.*;

/**
 * @author anuragkapur
 */
public class StringSerializerTest {

    StringSerializer serializer = new StringSerializer();

    @Test
    public void testSerializeAndDeserialize() throws Exception {
        List<String> strings = new ArrayList<>();
        strings.add("abcd22£$$%.11");
        strings.add("abc");

        String serialized = serializer.serialize(strings);

        List<String> stringsActual = serializer.deserialize(serialized, null);
        assertEquals("[abc, abcd22£$$%.11]", stringsActual.toString());
    }

    @Test
    public void testDeserialize1() throws Exception {

        List<String> strings = serializer.deserialize("abc.3def..4", null);
        System.out.println(strings.toString());
    }
}


text:
package org.argus.jawa.core.ast.javafile

import com.github.javaparser.JavaParser
import com.github.javaparser.ast.body.{BodyDeclaration, TypeDeclaration}
import com.github.javaparser.ast.{CompilationUnit, NodeList}
import org.argus.jawa.core.Global
import org.argus.jawa.core.ast.{MyClass, CompilationUnit => JawaCompilationUnit}
import org.argus.jawa.core.elements.JawaType
import org.argus.jawa.core.io.{AbstractFile, DefaultSourceFile, Reporter}
import org.argus.jawa.core.ast.jawafile.JawaAstParser
import org.argus.jawa.core.util.{IMap, ISet, MSet, msetEmpty}
import scala.collection.JavaConverters._

class JavaSourceFile(global: Global, file: AbstractFile) extends DefaultSourceFile(file) {
  private var javacu: Option[CompilationUnit] = None

  def getJavaCU: CompilationUnit = {
    javacu match {
      case Some(cu) => cu
      case None =>
        val cu = JavaParser.parse(file.input)
        javacu = Some(cu)
        cu
    }
  }
  private def visitTypes(typ: JawaType, members: NodeList[BodyDeclaration[_ <: BodyDeclaration[_]]]): ISet[JawaType] = {
    val types: MSet[JawaType] = msetEmpty
    members.asScala.foreach {
      case td: TypeDeclaration[_] =>
        val innerTyp = new JawaType(s"${typ.jawaName}$$${td.getNameAsString}")
        types += innerTyp
        types ++= visitTypes(innerTyp, td.getMembers)
      case _ =>
    }
    types.toSet
  }

  def getTypes: ISet[JawaType] = {
    val types: MSet[JawaType] = msetEmpty
    val cu = getJavaCU
    var packageName = ""
    if(cu.getPackageDeclaration.isPresent) {
      packageName = cu.getPackageDeclaration.get().getName.asString() + "."
    }
    cu.getTypes.asScala.foreach { typ =>
      val classType = new JawaType(s"$packageName${typ.getNameAsString}")
      types += classType
      types ++= visitTypes(classType, typ.getMembers)
    }
    types.toSet
  }

  private val j2j = new Java2Jawa(global, this)

  def parse(reporter: Reporter): IMap[JawaType, MyClass] = {
    val cids = j2j.process()
    cids.map { cid =>
      cid.typ -> JawaAstParser.resolveClass(cid)
    }.toMap
  }

  /**
    * Be aware this will parse method body
    */
  def getJawaCU: JawaCompilationUnit = {
    j2j.genCU()
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel</title>

    <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <?php if(Session::has('success')): ?>

<?php echo e(Session::get("success")); ?>

    <?php endif; ?>

    <?php if($errors->any()): ?>
            <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $erro): $__env->incrementLoopIndices(); $loop = $__env->getFirstLoop(); ?>
                <?php echo e($erro); ?>

            <?php endforeach; $__env->popLoop(); $loop = $__env->getFirstLoop(); ?>
    <?php endif; ?>
    <?php echo $__env->yieldContent("content"); ?>