text:
function loginError()
{
	nursApp.system.activityIndicator.hide();
	alert('Incorrect username or password');
}

function restError()
{
	nursApp.system.activityIndicator.hide();
	alert('Poor internet conection. Could not connect to Laulima.');
	nursApp.system.deleteUserData();
}

function classError()
{
	alert('No classes listed in Laulima!!');
	nursApp.system.deleteUserData();
}

function blogError()
{
	nursApp.system.activityIndicator.hide();
	alert('You have no classes with blogs!');
	nursApp.system.deleteUserData();
}

function incCount ()
{
	Ti.API.info('incrementing');
	nursApp.system.initCounter = nursApp.system.initCounter + 1;
}

function decCount()
{
	Ti.API.info('decrementing');
	nursApp.system.initCounter = nursApp.system.initCounter - 1;

	if(nursApp.system.initCounter === 0)
	{
		Ti.API.info('nursApp.system.initCounter === 0');
		nursApp.system.storeUserData();
		nursApp.ui.createBlogSelectionView();
	}
}

exports.getLaulimaData = function(un, pw)
{
	Ti.API.info('in getLaulimaData');
	// send RESTful request
	var restCall = require('postRequest');
	nursApp.system.activityIndicator.show();

	var url = 'https://laulima.hawaii.edu/direct/session/new/?_username=' + un + '&_password=' + pw;

	restCall.RESTfulCall('POST', url, postLoginProcess, loginError);
}

function postLoginProcess(rawData)
{
	Ti.API.info('in postLoginProcess');
	var restCall = require('postRequest');

    nursApp.userData.sessionID = rawData;

    // Get the user's Id, this will be used later for submitting blog entries
    var url = "https://laulima.hawaii.edu/direct/user/" + nursApp.userData.username + ".json?sakai.session=" + rawData;
    restCall.RESTfulCall('GET', url, storeUserId, restError);

    // Start blog search
    var surl = "https://laulima.hawaii.edu/direct/site.json?sakai.session=" + nursApp.userData.sessionID;
    restCall.RESTfulCall('GET', surl, storeBlogSearch, restError);
}

function storeUserId(rawData)
{
	Ti.API.info('in storeUserId');
	var parsedData = JSON.parse(rawData);
	nursApp.userData.userId = parsedData.id;
	Ti.API.info("UserID = " + nursApp.userData.userId);
}

function storeBlogSearch(rawData)
{
	Ti.API.info('in storeBlogSearch');
	var parsedData = JSON.parse(rawData);
	getClassList(parsedData);
}

function getClassList(parsedData)
{
	Ti.API.info('in getClassList');
	var url = '';
	var restCall = require('postRequest');

	if(parsedData.site_collection.length > 0)
	{
		// Store class information entityReference and entityURL in an associative array using entityID as the key
		// This object should probably be initialized in app.js. Start w/ everything undefined or false. Change later
		for (var i = 0; i < parsedData.site_collection.length; i++)
		{
			nursApp.userData.classes[parsedData.site_collection[i].entityId] = {
				entityReference: parsedData.site_collection[i].entityReference,
				entityURL : parsedData.site_collection[i].entityURL,
				title : parsedData.site_collection[i].title,
				entityId : parsedData.site_collection[i].entityId,
				shortDescription : parsedData.site_collection[i].shortDescription,
				doesBlogExist : false,
				blogId : undefined
			};

			url = "https://laulima.hawaii.edu/direct" + parsedData.site_collection[i].entityReference + "/pages.json?sakai.session=" + nursApp.userData.sessionID;
			Ti.API.info('about to call: ' + url);
			restCall.RESTfulCall('GET', url, checkForBlog, restError);
		}
	} else {
		classError();
	}

}

function checkForBlog(rawData)
{
	Ti.API.info('In check for blog')
	var parsedData = JSON.parse(rawData);
	var y = 0;
	var url = '';
	var restCall = require('postRequest');

	if (parsedData.length > 0)
	{
		// Go through class info one section at a time
		for (y=0; y < parsedData.length; y++)
		{
			// Go through each class info sections tool list
			for(z=0; z < parsedData[y].tools.length; z++)
			{
				// Look for sakai.blogwow in the tool list
				if(parsedData[y].tools[z].toolId == 'sakai.blogwow')
				{
					incCount();
					// If the class has a blog then save the siteId so we can find the blogId
					nursApp.userData.blogList.push(parsedData[y].tools[z].siteId);

					// Save a spot for the blogId
					nursApp.userData.blogId.push('');

					// Gather Blog Info
					url = "https://laulima.hawaii.edu/direct/blog-blog.json?sakai.session=" + nursApp.userData.sessionID + "&location=" + nursApp.userData.classes[parsedData[y].tools[z].siteId].entityReference;
					Ti.API.info('Blog Entity Reference = ' + nursApp.userData.classes[parsedData[y].tools[z].siteId].entityReference);
					restCall.RESTfulCall('GET', url, extractBlogId, restError);
				}
			}
		}
	} else {
		blogError();
	}
}

// Extract our users blog from the full list of course blogs
// We are looking to match the userId with the blog's owner.Id
function extractBlogId(rawData)
{
	Ti.API.info('in blog ID');
	var parsedData = JSON.parse(rawData);
	// Check all the details on every blog in the class
	for (var blog in parsedData['blog-blog_collection'])
	{
		// If any of those blogs belong to our user
		if(parsedData['blog-blog_collection'][blog].ownerId == nursApp.userData.userId)
		{
			// Grab the entity reference and separate it so we can find the siteId.
			var bigString = parsedData['blog-blog_collection'][blog].location;
			var littleStrings = bigString.split('/');
			Ti.API.info('The bigString = ' + bigString);

			Ti.API.info('parsing the blogs entity reference, last item in split: ' + littleStrings[littleStrings.length-1]);
			// Go through the blogs we have saved and find the one that matches this blog
			for (var listItem in nursApp.userData.blogList)
			{
				Ti.API.info('Checking if ' + nursApp.userData.blogList[listItem] + ' is = ' + littleStrings[littleStrings.length-1]);
				// Save the blogId with its match in the blogList
				if(nursApp.userData.blogList[listItem] == littleStrings[littleStrings.length-1])
				{
					Ti.API.info('BlogList item and last item in split match. Storing id; ' + parsedData['blog-blog_collection'][blog].id)
					nursApp.userData.blogId[listItem] = parsedData['blog-blog_collection'][blog].id;
				}
			}
		}
	}
	decCount();
}


text:
/* this ALWAYS GENERATED file contains the definitions for the interfaces */

 /* File created by MIDL compiler version 8.xx.xxxx */
/* at a redacted point in time
 */
/* Compiler settings for ../../edge_embedded_browser/client/win/current/webview2interop.idl:
    Oicf, W1, Zp8, env=Win64 (32b run), target_arch=AMD64 8.xx.xxxx
    protocol : dce , ms_ext, c_ext, robust
    error checks: allocation ref bounds_check enum stub_data
    VC __declspec() decoration level:
         __declspec(uuid()), __declspec(selectany), __declspec(novtable)
         DECLSPEC_UUID(), MIDL_INTERFACE()
*/
/* @@MIDL_FILE_HEADING(  ) */

#pragma warning( disable: 4049 )  /* more than 64k source lines */

/* verify that the <rpcndr.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 475
#endif

#include "rpc.h"
#include "rpcndr.h"

#ifndef __RPCNDR_H_VERSION__
#error this stub requires an updated version of <rpcndr.h>
#endif /* __RPCNDR_H_VERSION__ */

#ifndef __webview2interop_h__
#define __webview2interop_h__

#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif

/* Forward Declarations */

#ifndef __ICoreWebView2Interop_FWD_DEFINED__
#define __ICoreWebView2Interop_FWD_DEFINED__
typedef interface ICoreWebView2Interop ICoreWebView2Interop;

#endif 	/* __ICoreWebView2Interop_FWD_DEFINED__ */

#ifndef __ICoreWebView2CompositionControllerInterop_FWD_DEFINED__
#define __ICoreWebView2CompositionControllerInterop_FWD_DEFINED__
typedef interface ICoreWebView2CompositionControllerInterop ICoreWebView2CompositionControllerInterop;

#endif 	/* __ICoreWebView2CompositionControllerInterop_FWD_DEFINED__ */

#ifndef __ICoreWebView2EnvironmentInterop_FWD_DEFINED__
#define __ICoreWebView2EnvironmentInterop_FWD_DEFINED__
typedef interface ICoreWebView2EnvironmentInterop ICoreWebView2EnvironmentInterop;

#endif 	/* __ICoreWebView2EnvironmentInterop_FWD_DEFINED__ */

/* header files for imported files */
#include "oaidl.h"

#ifdef __cplusplus
extern "C"{
#endif

#ifndef __WebView2Interop_LIBRARY_DEFINED__
#define __WebView2Interop_LIBRARY_DEFINED__

/* library WebView2Interop */
/* [version][uuid] */

EXTERN_C const IID LIBID_WebView2Interop;

#ifndef __ICoreWebView2Interop_INTERFACE_DEFINED__
#define __ICoreWebView2Interop_INTERFACE_DEFINED__

/* interface ICoreWebView2Interop */
/* [unique][object][uuid] */

EXTERN_C __declspec(selectany) const IID IID_ICoreWebView2Interop = {0x912b34a7,0xd10b,0x49c4,{0xaf,0x18,0x7c,0xb7,0xe6,0x04,0xe0,0x1a}};

#if defined(__cplusplus) && !defined(CINTERFACE)

    MIDL_INTERFACE("912b34a7-d10b-49c4-af18-7cb7e604e01a")
    ICoreWebView2Interop : public IUnknown
    {
    public:
        virtual HRESULT STDMETHODCALLTYPE AddHostObjectToScript(
            /* [in] */ LPCWSTR name,
            /* [in] */ VARIANT *object) = 0;

    };

#else 	/* C style interface */

    typedef struct ICoreWebView2InteropVtbl
    {
        BEGIN_INTERFACE

        HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
            ICoreWebView2Interop * This,
            /* [in] */ REFIID riid,
            /* [annotation][iid_is][out] */
            _COM_Outptr_  void **ppvObject);

        ULONG ( STDMETHODCALLTYPE *AddRef )(
            ICoreWebView2Interop * This);

        ULONG ( STDMETHODCALLTYPE *Release )(
            ICoreWebView2Interop * This);

        HRESULT ( STDMETHODCALLTYPE *AddHostObjectToScript )(
            ICoreWebView2Interop * This,
            /* [in] */ LPCWSTR name,
            /* [in] */ VARIANT *object);

        END_INTERFACE
    } ICoreWebView2InteropVtbl;

    interface ICoreWebView2Interop
    {
        CONST_VTBL struct ICoreWebView2InteropVtbl *lpVtbl;
    };

#ifdef COBJMACROS

#define ICoreWebView2Interop_QueryInterface(This,riid,ppvObject)	\
    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )

#define ICoreWebView2Interop_AddRef(This)	\
    ( (This)->lpVtbl -> AddRef(This) )

#define ICoreWebView2Interop_Release(This)	\
    ( (This)->lpVtbl -> Release(This) )

#define ICoreWebView2Interop_AddHostObjectToScript(This,name,object)	\
    ( (This)->lpVtbl -> AddHostObjectToScript(This,name,object) )

#endif /* COBJMACROS */

#endif 	/* C style interface */

#endif 	/* __ICoreWebView2Interop_INTERFACE_DEFINED__ */

#ifndef __ICoreWebView2CompositionControllerInterop_INTERFACE_DEFINED__
#define __ICoreWebView2CompositionControllerInterop_INTERFACE_DEFINED__

/* interface ICoreWebView2CompositionControllerInterop */
/* [unique][object][uuid] */

EXTERN_C __declspec(selectany) const IID IID_ICoreWebView2CompositionControllerInterop = {0x8e9922ce,0x9c80,0x42e6,{0xba,0xd7,0xfc,0xeb,0xf2,0x91,0xa4,0x95}};

#if defined(__cplusplus) && !defined(CINTERFACE)

    MIDL_INTERFACE("8e9922ce-9c80-42e6-bad7-fcebf291a495")
    ICoreWebView2CompositionControllerInterop : public IUnknown
    {
    public:
        virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_UIAProvider(
            /* [retval][out] */ IUnknown **provider) = 0;

        virtual /* [propget] */ HRESULT STDMETHODCALLTYPE get_RootVisualTarget(
            /* [retval][out] */ IUnknown **target) = 0;

        virtual /* [propput] */ HRESULT STDMETHODCALLTYPE put_RootVisualTarget(
            /* [in] */ IUnknown *target) = 0;

    };

#else 	/* C style interface */

    typedef struct ICoreWebView2CompositionControllerInteropVtbl
    {
        BEGIN_INTERFACE

        HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
            ICoreWebView2CompositionControllerInterop * This,
            /* [in] */ REFIID riid,
            /* [annotation][iid_is][out] */
            _COM_Outptr_  void **ppvObject);

        ULONG ( STDMETHODCALLTYPE *AddRef )(
            ICoreWebView2CompositionControllerInterop * This);

        ULONG ( STDMETHODCALLTYPE *Release )(
            ICoreWebView2CompositionControllerInterop * This);

        /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_UIAProvider )(
            ICoreWebView2CompositionControllerInterop * This,
            /* [retval][out] */ IUnknown **provider);

        /* [propget] */ HRESULT ( STDMETHODCALLTYPE *get_RootVisualTarget )(
            ICoreWebView2CompositionControllerInterop * This,
            /* [retval][out] */ IUnknown **target);

        /* [propput] */ HRESULT ( STDMETHODCALLTYPE *put_RootVisualTarget )(
            ICoreWebView2CompositionControllerInterop * This,
            /* [in] */ IUnknown *target);

        END_INTERFACE
    } ICoreWebView2CompositionControllerInteropVtbl;

    interface ICoreWebView2CompositionControllerInterop
    {
        CONST_VTBL struct ICoreWebView2CompositionControllerInteropVtbl *lpVtbl;
    };

#ifdef COBJMACROS

#define ICoreWebView2CompositionControllerInterop_QueryInterface(This,riid,ppvObject)	\
    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )

#define ICoreWebView2CompositionControllerInterop_AddRef(This)	\
    ( (This)->lpVtbl -> AddRef(This) )

#define ICoreWebView2CompositionControllerInterop_Release(This)	\
    ( (This)->lpVtbl -> Release(This) )

#define ICoreWebView2CompositionControllerInterop_get_UIAProvider(This,provider)	\
    ( (This)->lpVtbl -> get_UIAProvider(This,provider) )

#define ICoreWebView2CompositionControllerInterop_get_RootVisualTarget(This,target)	\
    ( (This)->lpVtbl -> get_RootVisualTarget(This,target) )

#define ICoreWebView2CompositionControllerInterop_put_RootVisualTarget(This,target)	\
    ( (This)->lpVtbl -> put_RootVisualTarget(This,target) )

#endif /* COBJMACROS */

#endif 	/* C style interface */

#endif 	/* __ICoreWebView2CompositionControllerInterop_INTERFACE_DEFINED__ */

#ifndef __ICoreWebView2EnvironmentInterop_INTERFACE_DEFINED__
#define __ICoreWebView2EnvironmentInterop_INTERFACE_DEFINED__

/* interface ICoreWebView2EnvironmentInterop */
/* [unique][object][uuid] */

EXTERN_C __declspec(selectany) const IID IID_ICoreWebView2EnvironmentInterop = {0xee503a63,0xc1e2,0x4fbf,{0x8a,0x4d,0x82,0x4e,0x95,0xf8,0xbb,0x13}};

#if defined(__cplusplus) && !defined(CINTERFACE)

    MIDL_INTERFACE("ee503a63-c1e2-4fbf-8a4d-824e95f8bb13")
    ICoreWebView2EnvironmentInterop : public IUnknown
    {
    public:
        virtual HRESULT STDMETHODCALLTYPE GetProviderForHwnd(
            /* [in] */ HWND hwnd,
            /* [retval][out] */ IUnknown **provider) = 0;

    };

#else 	/* C style interface */

    typedef struct ICoreWebView2EnvironmentInteropVtbl
    {
        BEGIN_INTERFACE

        HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
            ICoreWebView2EnvironmentInterop * This,
            /* [in] */ REFIID riid,
            /* [annotation][iid_is][out] */
            _COM_Outptr_  void **ppvObject);

        ULONG ( STDMETHODCALLTYPE *AddRef )(
            ICoreWebView2EnvironmentInterop * This);

        ULONG ( STDMETHODCALLTYPE *Release )(
            ICoreWebView2EnvironmentInterop * This);

        HRESULT ( STDMETHODCALLTYPE *GetProviderForHwnd )(
            ICoreWebView2EnvironmentInterop * This,
            /* [in] */ HWND hwnd,
            /* [retval][out] */ IUnknown **provider);

        END_INTERFACE
    } ICoreWebView2EnvironmentInteropVtbl;

    interface ICoreWebView2EnvironmentInterop
    {
        CONST_VTBL struct ICoreWebView2EnvironmentInteropVtbl *lpVtbl;
    };

#ifdef COBJMACROS

#define ICoreWebView2EnvironmentInterop_QueryInterface(This,riid,ppvObject)	\
    ( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )

#define ICoreWebView2EnvironmentInterop_AddRef(This)	\
    ( (This)->lpVtbl -> AddRef(This) )

#define ICoreWebView2EnvironmentInterop_Release(This)	\
    ( (This)->lpVtbl -> Release(This) )

#define ICoreWebView2EnvironmentInterop_GetProviderForHwnd(This,hwnd,provider)	\
    ( (This)->lpVtbl -> GetProviderForHwnd(This,hwnd,provider) )

#endif /* COBJMACROS */

#endif 	/* C style interface */

#endif 	/* __ICoreWebView2EnvironmentInterop_INTERFACE_DEFINED__ */

#endif /* __WebView2Interop_LIBRARY_DEFINED__ */

/* Additional Prototypes for ALL interfaces */

/* end of Additional Prototypes */

#ifdef __cplusplus
}
#endif

#endif

redpajama_set_name: RedPajamaGithub


text:
package loci.jar2lib;

import jace.proxy.AutoProxy;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * Generates a C++ project for C++ proxies corresponding
 * to a list of Java JAR files.
 *
 * @author Curtis Rueden
 */
public class Jar2Lib {

	// -- Constants --

	private static final String RESOURCE_PREFIX = "project-files/";

	// -- Fields --

	private String projectId;
	private String projectName;
	private List<String> libraryJars;
	private List<String> classpathJars;
	private String conflictsPath;
	private String headerPath;
	private String sourcePath;
	private String extrasPath;
	private String corePath;
	private String outputPath;

	private File[] sourceFiles;
	private File outputDir;
	private File outputIncludeDir, outputSourceDir;
	private File proxiesDir;
	private File proxiesIncludeDir, proxiesSourceDir;

	// -- Constructor --

	public Jar2Lib() {
		libraryJars = new ArrayList<String>();
		classpathJars = new ArrayList<String>();
	}

	// -- Jar2Lib methods --

	public String getProjectId() {
		return projectId;
	}
	public void setProjectId(String projectId) {
		this.projectId = projectId;
	}
	public String getProjectName() {
		return projectName;
	}
	public void setProjectName(String projectName) {
		this.projectName = projectName;
	}
	public List<String> getLibraryJars() {
		return libraryJars;
	}
	public void setLibraryJars(List<String> libraryJars) {
		this.libraryJars = libraryJars;
	}
	public List<String> getClasspathJars() {
		return classpathJars;
	}
	public void setClasspathJars(List<String> classpathJars) {
		this.classpathJars = classpathJars;
	}
	public String getConflictsPath() {
		return conflictsPath;
	}
	public void setConflictsPath(String conflictsPath) {
		this.conflictsPath = conflictsPath;
	}
	public String getHeaderPath() {
		return headerPath;
	}
	public void setHeaderPath(String headerPath) {
		this.headerPath = headerPath;
	}
	public String getSourcePath() {
		return sourcePath;
	}
	public void setSourcePath(String sourcePath) {
		this.sourcePath = sourcePath;
	}
	public String getOutputPath() {
		return outputPath;
	}
	public void setOutputPath(String outputPath) {
		this.outputPath = outputPath;
	}
	public String getExtrasPath() {
			return extrasPath;
	}
	public void setExtrasPath(String extrasPath) {
	this.extrasPath = extrasPath;
	}
	public String getCorePath() {
	return corePath;
	}
	public void setCorePath(String corePath) {
	this.corePath = corePath;
	}

	/** Parses the settings from the given command line arguments. */
	public void parseArgs(String[] args) {
		projectId = args.length >= 1 ? args[0] : null;
		projectName = args.length >= 2 ? args[1] : null;
		libraryJars = new ArrayList<String>();
		classpathJars = new ArrayList<String>();
		conflictsPath = null;
		headerPath = null;
		outputPath = null;
		for (int i = 2; i < args.length; i++) {
			final String arg = args[i];
			if (arg.equals("-conflicts")) {
				if (i == args.length - 1) die("Error: no conflicts file given.");
				conflictsPath = args[++i];
			}
			else if (arg.equals("-header")) {
				if (i == args.length - 1) die("Error: no header file given.");
				headerPath = args[++i];
			}
			else if (arg.equals("-source")) {
				if (i == args.length - 1) die("Error: no source path given.");
				sourcePath = args[++i];
			}
			else if (arg.equals("-output")) {
				if (i == args.length - 1) die("Error: no output path given.");
				outputPath = args[++i];
			}
			else if (arg.equals("-extras")) {
				if (i == args.length - 1) die("Error: no extras path given.");
				extrasPath = args[++i];
			}
			else if (arg.equals("-core")) {
				if (i == args.length - 1) die("Error: no core classes path given.");
				corePath = args[++i];
			}
			else if (arg.startsWith("-")) die("Unknown flag: " + arg);
			else libraryJars.add(arg);
		}
		if (projectId == null || projectName == null || libraryJars.size() == 0) {
			die("Usage: java " + getClass().getName() + " projectId projectName\n" +
				"\tlibrary.jar [library2.jar ...]\n" +
				"\t[-conflicts conflicts.txt] [-header header.txt]\n" +
				"\t[-extras cmake_extras.txt] [-output /path/to/output-project]\n +" +
				"\t[-core java_core_classes.txt");
		}
		if (outputPath == null) outputPath = projectId;
	}

	/** Generates a C++ wrapper project based on the current settings. */
	public void execute() throws IOException, VelocityException {
		validateInputs();
		generateSkeleton();
		copySourceFiles();
		fixLibraryPaths();
		generateHeaders();
		generateProxies();
		fixConflicts();

		// TODO - print instructions on how to proceed with CMake
		// TODO - copy "final product" files such as wrapped JARs to build dir

		log("--> Done");
	}

 /**
	* Converts "\\" to "/" in all library paths, making them platform safe for CMakeLists.txt files
	*/
	public void fixLibraryPaths() {
		List<String> tmpArray = new ArrayList<String>();

		for(String libPath : libraryJars) {
			tmpArray.add(libPath.replaceAll("\\\\", "/"));
		}
		setLibraryJars(tmpArray);
	}

	/**
	 * Checks that the current settings for project production are valid.
	 * Creates various needed output directories if needed.
	 *
	 * @throws IllegalStateException if the settings are invalid.
	 */
	public void validateInputs() {
		// check project ID
		if (projectId == null || !projectId.matches("^(\\w)([\\w\\-])*$")) {
			throw new IllegalStateException("Invalid project ID: " + projectId);
		}

		// check project name
		if (projectName == null) {
			throw new IllegalStateException("Invalid project name: " + projectName);
		}

		// check conflicts file
		if (conflictsPath != null && !new File(conflictsPath).exists()) {
			throw new IllegalStateException("Invalid conflicts file: " +
				conflictsPath);
		}

		// check header file
		if (headerPath != null && !new File(headerPath).exists()) {
			throw new IllegalStateException("Invalid header file: " + headerPath);
		}

		// generate list of source files
		sourceFiles = listSourceFiles(sourcePath);

		// create output directory
		outputDir = new File(outputPath);
		if (!outputDir.exists()) outputDir.mkdirs();
		if (!outputDir.isDirectory()) {
			throw new IllegalStateException("Not a valid directory: " + outputPath);
		}

		// create source and include directories
		outputIncludeDir = new File(outputDir, "include");
		if (!outputIncludeDir.exists()) outputIncludeDir.mkdirs();
		outputSourceDir = new File(outputDir, "source");
		if (!outputSourceDir.exists()) outputSourceDir.mkdirs();

		proxiesDir = new File(outputPath, "proxies");
		proxiesIncludeDir = new File(proxiesDir, "include");
		if (!proxiesIncludeDir.exists()) proxiesIncludeDir.mkdirs();
		proxiesSourceDir = new File(proxiesDir, "source");
		if (!proxiesSourceDir.exists()) proxiesSourceDir.mkdirs();

		// create java.h
		try {
			BufferedWriter fout = new BufferedWriter(new FileWriter(outputIncludeDir + File.separator + "java.h"));
			fout.write("//\n// java.h\n//\n\n");
			fout.write("// additional core java files to include\n\n");
			if(corePath != null)
			{
				BufferedReader fin = new BufferedReader(new FileReader(new File(corePath)));
				while(fin.ready())
				{
					fout.write("#include \"jace/proxy/" + fin.readLine().replace('.', '/') + ".h\"\n");
				}
				fin.close();
			}
			fout.flush();
			fout.close();
		}
		catch (IOException e)
		{
			System.out.println("Error creating java.h");
		}
	}

	/**
	 * Generates one header per input Java library.
	 * Also generates the CMake build file.
	 */
	public void generateHeaders() throws IOException, VelocityException {
		final VelocityAutogen generator = new VelocityAutogen(headerPath);
		for (String jarPath : libraryJars) {
			final File jarFile = new File(jarPath);
			log("--> Generating header for " + jarFile.getName());
			generator.createJaceHeader(jarPath, path(outputIncludeDir));
		}
		log("--> Generating CMake build file");
		generator.createCMakeLists(projectId, projectName,
			sourceFiles, path(outputDir), libraryJars);

		if (extrasPath != null) {
			String cmakePath = outputPath + "/CMakeLists.txt";

			OutputStream fout = new FileOutputStream(new File(cmakePath), true);
			InputStream fin = new FileInputStream(new File(extrasPath));

			byte[] buf = new byte[1];
			int len;

			while ((len = fin.read(buf)) >= 0) {
				if(len > 0) fout.write(buf, 0, len);
			}

			fout.flush();

			fin.close();
			fout.close();
		}
	}

	/**
	 * Copies static project resources into the project directory.
	 * In particular, copies the Jace C++ distribution and related files.
	 */
	public void generateSkeleton() throws IOException {
		log("--> Generating project skeleton");
		final List<String> projectResources = findResources(RESOURCE_PREFIX);
		for (String resource : projectResources) {
			final String outPath = resource.substring(RESOURCE_PREFIX.length());
			if (outPath.equals("")) continue; // skip base folder
			copyResource(resource, outPath);
		}
	}

	/** Copies any extra C++ source files into the project directory. */
	public void copySourceFiles() throws IOException {
		if (sourceFiles.length == 0) return; // no sources
		log("--> Copying sources");
		for (File sourceFile : sourceFiles) {
			copySourceFile(sourceFile);
		}
	}

	/** Generates the C++ proxy classes enumerated in the C++ headers. */
	public void generateProxies() throws UnsupportedEncodingException {
		final String osName = System.getProperty("os.name");
		final boolean isWindows = osName.indexOf("Windows") >= 0;
		final List<String> autoProxyArgs = new ArrayList<String>();
		autoProxyArgs.add(path(outputIncludeDir));
		autoProxyArgs.add(path(outputSourceDir));
		autoProxyArgs.add(path(proxiesIncludeDir));
		autoProxyArgs.add(path(proxiesSourceDir));
		List<String> allJars = new ArrayList<String>();
		allJars.addAll(libraryJars);
		allJars.addAll(classpathJars);
		autoProxyArgs.add(classpath(allJars));
		autoProxyArgs.add("-mindep");
		if (isWindows) autoProxyArgs.add("-exportsymbols");
		log("--> Generating proxies");
		AutoProxy.main(autoProxyArgs.toArray(new String[0]));
	}

	/**
	 * Post-processes the generated proxies to correct any
	 * conflicts identified in the specified conflicts file.
	 */
	public void fixConflicts() throws IOException {
		if (conflictsPath == null) return;
		log("--> Renaming conflicting constants");
		final FixProxies fixProxies = new FixProxies(conflictsPath);
		fixProxies.fixProxies(path(proxiesDir));
	}

	// -- Main method --

	public static void main(final String[] args) throws Exception {
		final Jar2Lib jar2Lib = new Jar2Lib();
		try {
			jar2Lib.parseArgs(args);
		}
		catch (IllegalArgumentException exc) {
			System.err.println(exc.getMessage());
			System.exit(1);
		}
		try {
			jar2Lib.execute();
		}
		catch (IllegalStateException exc) {
			System.err.println(exc.getMessage());
			System.exit(2);
		}
	}

	// -- Helper methods --

	protected void log(final String message) {
		System.out.println(message);
	}

	protected void die(final String message) {
		throw new IllegalArgumentException(message);
	}

	/** Gets a list of C++ source files in the given directory. */
	private File[] listSourceFiles(final String path) {
		if (path == null) return new File[0]; // no sources
		final File sourceDir = new File(path);

		if (!sourceDir.exists()) return new File[0]; // no sources
		return sourceDir.listFiles(new FileFilter() {
			@Override
			public boolean accept(final File pathname) {
				return pathname.getName().toLowerCase().endsWith(".cpp");
			}
		});
	}

	/** Scans the enclosing JAR file for all resources beneath the given path. */
	private List<String> findResources(final String resourceDir)
		throws IOException
	{
		final List<String> resources = new ArrayList<String>();
		final String jarPath = findEnclosingJar(Jar2Lib.class);
		final JarFile jarFile = new JarFile(jarPath);
		final Enumeration<JarEntry> jarEntries = jarFile.entries();
		if (jarEntries != null) {
			while (jarEntries.hasMoreElements()) {
				final JarEntry entry = jarEntries.nextElement();
				final String name = entry.getName();
				if (name == null) continue;
				if (name.startsWith(resourceDir)) resources.add(name);
			}
		}
		return resources;
	}

	/** Copies the given resource to the specified output directory. */
	private void copyResource(final String resource, final String outPath)
		throws IOException
	{
		log(outPath);
		final File outputFile = new File(outputDir, outPath);
		final File parentDir = outputFile.getParentFile();
		if (!parentDir.exists()) parentDir.mkdirs();
		if (resource.endsWith("/")) {
			// resource is a directory
			outputFile.mkdir();
		}
		else {
			// resource is a file
			final InputStream in = Jar2Lib.class.getResourceAsStream("/" + resource);
			writeStreamToFile(in, outputFile);
			in.close();
		}
	}

	/**
	 * Copies the given file to to the source folder
	 * of the specified output directory.
	 * @throws IOException
	 */
	private void copySourceFile(final File sourceFile) throws IOException {
		log(sourceFile.getPath());
		final File outputFile = new File(outputSourceDir, sourceFile.getName());
		final FileInputStream in = new FileInputStream(sourceFile);
		writeStreamToFile(in, outputFile);
		in.close();
	}

	// -- Static utility methods --

	/**
	 * Finds the JAR file (or file system path)
	 * from which the given class was loaded.
	 */
	public static String findEnclosingJar(final Class<?> c)
		throws UnsupportedEncodingException
	{
		String className = c.getName();
		int dot = className.lastIndexOf(".");
		if (dot >= 0) className = className.substring(dot + 1);
		String path = c.getResource(className + ".class").toString();
		path = path.replaceAll("^jar:", "");
		path = path.replaceAll("^file:", "");
		path = path.replaceAll("^/*/", "/");
		path = path.replaceAll("^/([A-Z]:)", "$1");
		path = path.replaceAll("!.*", "");
		path = URLDecoder.decode(path, "UTF-8");
		String slash = File.separator;
		if (slash.equals("\\")) slash = "\\\\";
		path = path.replaceAll("/", slash);
		return path;
	}

	/** Locates the JAR file containing this JVM's classes. */
	private static String findRuntime() throws UnsupportedEncodingException {
		return findEnclosingJar(Object.class);
	}

	/** Gets the absolute path to the given file, with forward slashes. */
	private static String path(final File file) {
		final String path = file.getAbsolutePath();
		// NB: Use forward slashes even on Windows.
		return path.replaceAll("\\\\", "/");
	}

	/** Builds a classpath corresponding to the given list of JAR files. */
	private static String classpath(final List<String> libraryJars)
		throws UnsupportedEncodingException
	{
		final StringBuilder sb = new StringBuilder();
		final String jrePath = findRuntime();
		sb.append(jrePath);
		for (String jarPath : libraryJars) {
			sb.append(File.pathSeparator);
			sb.append(jarPath);
		}
		final String classPath = System.getProperty("java.class.path");
		if (classPath != null && !classPath.equals("")) {
			sb.append(File.pathSeparator);
			sb.append(classPath);
		}
		final String bootClassPath = System.getProperty("sun.boot.class.path");
		if (bootClassPath != null && !bootClassPath.equals("")) {
			sb.append(File.pathSeparator);
			sb.append(bootClassPath);
		}
		return sb.toString();
	}

	/** Writes the contents of the given input stream to the specified file. */
	private static void writeStreamToFile(final InputStream in,
		final File outputFile) throws IOException
	{
		final OutputStream out = new FileOutputStream(outputFile);
		final byte[] buf = new byte[512 * 1024]; // 512K buffer
		while (true) {
			int r = in.read(buf);
			if (r <= 0) break; // EOF
			out.write(buf, 0, r);
		}
		out.close();
	}

}


text:
package io.github.privacystreams.commons.string;

/**
 * Get the substring of the string specified by a field in the item.
 */
final class StringElideOperator extends StringProcessor<String> {

    private final int start;
    private final int end;

    StringElideOperator(String stringField, int start, int end) {
        super(stringField);
        this.start = start;
        this.end = end;
        this.addParameters(start, end);
    }

    @Override
    protected String processString(String stringValue) {
        if (stringValue == null) return null;
        int start = this.start;
        int end = this.end;
        if (start > end) return stringValue;
        if (start < 0) start = 0;
        if (end > stringValue.length()) end = stringValue.length() - 1;
        int elideLen = end - start + 1;
        String elideStr = String.format("%0" + elideLen + "d", 0).replace("0", "*");
        return stringValue.substring(0, start) + elideStr + stringValue.substring(end + 1);
    }
}


text:
<?php

namespace AppBundle\EventListeners;

use AppBundle\SerializeJsonResponse;
use JMS\Serializer\Serializer;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;

class ResponseSerializerListener
{
    /**
     * JMS Serializer
     *
     * @var Serializer
     */
    private $serializer;

    /**
     * ResponseSerializerListener constructor.
     *
     * @param Serializer $serializer JMS Serializer
     */
    public function __construct(Serializer $serializer)
    {
        $this->serializer = $serializer;
    }

    /**
     * @param FilterResponseEvent $event
     */
    public function onKernelResponse(FilterResponseEvent $event)
    {
        $response = $event->getResponse();

        if ($response instanceof SerializeJsonResponse) {
            $response->setJson($this->serializer->serialize($response->getUnserialized(), 'json'));
        }
    }

}


text: google-site-verification: googlebf4c56384f8fc253.html


text:
"""
VOLDEMORT (VDM)

-h, --help: this help text
-v, --vista: name of VistA. Defaults to "CGVISTA", Caregraf's publicly hosted demo VistA
-f, --fmqlep: FMQL endpoint. For example, "http://vista.caregraf.org/fmqlEP". If set, then no need for --host, --port, --access, --verify
--host: host of VistA
--port: port of VistA
--access: access for FMQL RPC
--verify: verify for FMQL RPC
-r, --report: 'schema', 'builds', 'schemaBuilds'

Example using a full FMQL RESTful endpoint ...
$ python -m vdm -v CGVISTA -f http://vista.caregraf.org/fmqlEP -r schema
or to use the FMQL RPC directly ...
$ python -m vdm -v CGVISTA --host "xx.xx.xx" --port 9201 --access "XXX" --verify "YYY" -r schema

The first time VDM runs against a VistA, the majority of time taken is downloading meta data. Subsequent runs of VDM for that VistA will be much faster as they'll run off a cache.

Any VistA being reported on must have FMQL installed.

Note: you DO NOT have to install the full, RESTful FMQL endpoint. The RPC is enough.
"""

import os
import sys
import re
import getopt
import logging
from vdm.vistaSchema import VistaSchema
from vdm.vistaSchemaComparer import VistaSchemaComparer
from vdm.vistaBuilds import VistaBuilds
from vdm.vistaBuildsComparer import VistaBuildsComparer
from vdm.vistaOtherDiffer import VistaOtherDiffer
from vdm.copies.fmqlCacher import FMQLCacher
import pkg_resources
from shutil import copy
from zipfile import ZipFile

def _makeEnvir():
    """
    Create Caches and Reports directories and move GOLD into Caches

    TODO:
    - move into a vdmEnvir module. After setup, it can provide access
    to all files and vistaSchema and others can delegate to it.
    """
    if not os.path.exists("Reports"):
        os.mkdir("Reports")
    if not os.path.exists("Caches"):
        os.mkdir("Caches")
    if not os.path.exists("Caches/GOLD"):
        # must run inside the package itself so __name__ works
        goldZipFile = pkg_resources.resource_filename(__name__, "resources/GOLD.zip")
        copy(goldZipFile, "Caches")
        print "First time VDM is run - installing GOLD into %s" % (os.getcwd() + "/Caches")
        ZipFile(os.getcwd() + "/Caches/GOLD.zip").extractall(os.getcwd() + "/Caches")

def _runReport(reportType, goldCacher, otherCacher):
    if reportType == "schema":
        vsr = VistaSchemaComparer(VistaSchema("GOLD", goldCacher), VistaSchema(otherCacher.vistaLabel, otherCacher))
        reportLocation = vsr.compare()
        print "Schema Report written to %s" % os.path.abspath(reportLocation)
    elif reportType == "builds":
        vbr = VistaBuildsComparer(VistaBuilds("GOLD", goldCacher), VistaBuilds(otherCacher.vistaLabel, otherCacher))
        reportLocation = vbr.compare()
        print "Builds Report written to %s" % os.path.abspath(reportLocation)
    elif reportType == "schemaBuilds":
        vod = VistaOtherDiffer(VistaBuilds("GOLD", goldCacher), VistaBuilds(otherCacher.vistaLabel, otherCacher), VistaSchema("GOLD", goldCacher), VistaSchema(otherCacher.vistaLabel, otherCacher))
        reportLocation = vod.report()
        print "Schema Builds Report written to %s" % os.path.abspath(reportLocation)
    else:
        print "No valid report type %s specified - exiting" % reportType

def main():
    """
    Invoked with python -m vdm

    TODO:
    - packaging: use setuptools - make front from windows/linux etc explicitly and don't reply on python -m
      - merge directory handling with equivalents in vistaSchema etc. Want one environment manager.
      - http://parijatmishra.wordpress.com/2008/10/13/python-packaging-custom-scripts/
    - cmd based interaction with VDM ... http://www.doughellmann.com/PyMOTW/cmd/
    - play with pool size to see speed of Caching
    - crude: move to argparse and a VistA directory file
    - consider opening browser if html reports: http://www.afpy.org/doc/python/2.7/library/webbrowser.html
    """
    logging.basicConfig(level=logging.INFO, format="%(message)s")
    _makeEnvir()
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hv:f:r:", ["help", "vista=", "fmqlep=", "report=", "host=", "port=", "access=", "verify="])
    except getopt.GetoptError, err:
        print str(err)
        print __doc__
        sys.exit(2)
    # Default VistA to Caregraf Demo VistA
    vista = "CGVISTA"
    # Will match to CGVISTA's if no other VistA name is specified
    fmqlEP = ""
    host = ""
    port = -1
    access = ""
    verify = ""
    report = ""
    for o, a in opts:
        if o in ["-v", "--vista"]:
            vista = a
        elif o in ["-f", "--fmqlep"]:
            fmqlEP = a
        elif o in ["--host"]:
            host = a
        elif o in ["--port"]:
            port = a
        elif o in ["--access"]:
            access = a
        elif o in ["--verify"]:
            verify = a
        elif o in ["-r", "--report"]:
            report = a
        elif o in ["-h", "--help"]:
            print __doc__
            sys.exit()
    if not report:
        sys.exit()
    if vista == "CGVISTA":
        print "Defaulting to Caregraf's demo VistA, 'CGVISTA'"
        fmqlEP = "http://vista.caregraf.org/fmqlEP"
    print "VDM - comparing %s against GOLD" % vista
    goldCacher = FMQLCacher("Caches")
    goldCacher.setVista("GOLD")
    otherCacher = FMQLCacher("Caches")
    otherCacher.setVista(vista, fmqlEP=fmqlEP, host=host, port=int(port), access=access, verify=verify)
    _runReport(report, goldCacher, otherCacher)

if __name__ == "__main__":
    main()


text:
'use strict';

describe('Factory: FireObjects', function () {

  // load the service's module
  beforeEach(angular.mock.module("nashaLeptaApp"));
  beforeEach(angular.mock.module("nashaLeptaApp", function ($provide) {
    //Attempt to override the FirebaseLink value that gets passed to config
    $provide.constant("FirebaseLink", "https://vivid-fire-8580.firebaseio.com");
  }));
  // instantiate service
  var FireObjects, FirebaseLink, ModelCopier;
  beforeEach(inject(function (_FireObjects_, _FirebaseLink_, _ModelCopier_) {
    FireObjects = _FireObjects_;
    FirebaseLink = _FirebaseLink_;
    ModelCopier = _ModelCopier_;
  }));
  //var originalTimeout;
  //beforeEach(function() {
  //  originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
  //  jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
  //});
  //afterEach(function() {
  //  jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
  //});
  it('all dependencies are correctly injected', function () {
    expect(!!FireObjects).toBe(true);
    expect(!!FirebaseLink).toBe(true);
    expect(!!ModelCopier).toBe(true);
    expect(FirebaseLink).toEqual("https://vivid-fire-8580.firebaseio.com");

  });
  it('FireObjects methods are defined', function () {
    expect(FireObjects.all).toBeDefined();
    expect(FireObjects.find).toBeDefined();
    expect(FireObjects.update).toBeDefined();
    expect(FireObjects.create).toBeDefined();
  });
  //too long callback, moved to pending
  xit('article1 created successfully', function (done) {
    var article = {
      url : 'article1',
      body : 'article1 body'
    };
    var articlesFireObject = FireObjects.create("articles", "article1");
    ModelCopier(article, articlesFireObject);
    articlesFireObject.$save().then(function(ref) {
      expect(ref.key()).toEqual(articlesFireObject.$id);
      done();
    }, function(error) {
      expect(error).toBeUndefined();
      done();
    });
  });
  //too long callback, moved to pending
  xit('article2 created successfully', function (done) {
    var article = {
      url : 'article2',
      body : 'article2 body'
    };
    var articlesFireObject = FireObjects.create("articles", "article2");
    ModelCopier(article, articlesFireObject);
    articlesFireObject.$save().then(function(ref) {
      expect(ref.key()).toEqual(articlesFireObject.$id);
      done();
    }, function(error) {
      expect(error).toBeUndefined();
      done();
    });
  });
  //too long callback, moved to pending
  xit('article3 created successfully', function (done) {
    var article = {
      url : 'article3',
      body : 'article3 body'
    };
    var articlesFireObject = FireObjects.create("articles", "article3");
    ModelCopier(article, articlesFireObject);
    articlesFireObject.$save().then(function(ref) {
      expect(ref.key()).toEqual(articlesFireObject.$id);
      done();
    }, function(error) {
      expect(error).toBeUndefined();
      done();
    });
  });
  //too long callback, moved to pending
  xit('article1 is retrieved successfully', function (done) {
    var articlesFireObject = FireObjects.find("articles", "article1");
    articlesFireObject.$loaded(function(data) {
        console.log(data === obj); // true
        expect(data.url).toEqual('article1');
        expect(data.body).toEqual('article1 body');
      },
      function(error) {
        expect(error).toBeUndefined();
        console.error("Error:", error);
      })
  });
});


text:
<?php

namespace IMAG\LdapBundle\Authentication\Token;

use Symfony\Component\Security\Core\Authentication\Token\AbstractToken;

class LdapToken extends AbstractToken
{

    public function __construct($username, $password, $providerKey, array $roles= array())
    {
        parent::__construct($roles);

        $this->setuser($username);
        $this->credentials = $password;
        $this->providerKey = $providerKey;
    }

    public function getCredentials()
    {
        return $this->credentials;
    }

    public function getProviderKey()
    {
        return $this->providerKey;
    }

    public function eraseCredentials()
    {
        parent::eraseCredentials();

        $this->credentials = null;
    }

    public function serialize()
    {
        return serialize(array($this->credentials, $this->providerKey, parent::serialize()));
    }

    public function unserialize($str)
    {
        list($this->credentials, $this->providerKey, $parentStr) = unserialize($str);
        parent::unserialize($parentStr);
    }

}


text:
package com.github.bohnman.squiggly.context.provider;

public class ThreadLocalContextProvider extends AbstractSquigglyContextProvider {

    @Override
    protected String getFilter(Class beanClass) {
        return SquigglyFilterHolder.getFilter();
    }
}


text:
<?xml version="1.0"?>
<doc>
    <assembly>
        <name>Quartz.Serialization.Json</name>
    </assembly>
    <members>
        <member name="T:Quartz.Simpl.JsonObjectSerializer">
            <summary>
            Default object serialization strategy that uses <see cref="T:Newtonsoft.Json.JsonSerializer" />
            under the hood.
            </summary>
            <author>Marko Lahma</author>
        </member>
        <member name="M:Quartz.Simpl.JsonObjectSerializer.Serialize``1(``0)">
            <summary>
            Serializes given object as bytes
            that can be stored to permanent stores.
            </summary>
            <param name="obj">Object to serialize.</param>
        </member>
        <member name="M:Quartz.Simpl.JsonObjectSerializer.DeSerialize``1(System.Byte[])">
            <summary>
            Deserializes object from byte array presentation.
            </summary>
            <param name="obj">Data to deserialize object from.</param>
        </member>
        <member name="T:Quartz.Simpl.NameValueCollectionConverter">
            <summary>
            Custom converter for (de)serializing <see cref="T:System.Collections.Specialized.NameValueCollection" />.
            </summary>
        </member>
    </members>
</doc>


text:
using UnityEngine;
using System.Collections;

public class Blinking : MonoBehaviour
{
    private bool isBlinking = false;
    public float TimeOn = 1f;
    public float TimeOff = 0.5f;

    IEnumerator Start()
    {
        while(true)
        {
            if (isBlinking) renderer.enabled = false;
            yield return new WaitForSeconds(TimeOff);
            renderer.enabled = true;
            yield return new WaitForSeconds(TimeOn);
        }
    }

    public void StartBlinking()
    {
        isBlinking = true;
    }

    public void StopBlinking()
    {
        isBlinking = false;
    }
}


text:
package com.amazonaws.services.cloudsearchdomain.model.transform;

import java.util.Map;
import java.util.List;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.cloudsearchdomain.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * SearchStatusMarshaller
 */
public class SearchStatusJsonMarshaller {

    /**
     * Marshall the given parameter object, and output to a SdkJsonGenerator
     */
    public void marshall(SearchStatus searchStatus,
            StructuredJsonGenerator jsonGenerator) {

        if (searchStatus == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        try {
            jsonGenerator.writeStartObject();

            if (searchStatus.getTimems() != null) {
                jsonGenerator.writeFieldName("timems").writeValue(
                        searchStatus.getTimems());
            }
            if (searchStatus.getRid() != null) {
                jsonGenerator.writeFieldName("rid").writeValue(
                        searchStatus.getRid());
            }

            jsonGenerator.writeEndObject();
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }
    }

    private static SearchStatusJsonMarshaller instance;

    public static SearchStatusJsonMarshaller getInstance() {
        if (instance == null)
            instance = new SearchStatusJsonMarshaller();
        return instance;
    }

}


text:
from setuptools import setup
import sys, os
import codecs

here = os.path.abspath(os.path.dirname(__file__))

def readfile(fname):
    return codecs.open(os.path.join(here, fname), encoding='utf-8').read()

version = '0.7.0'

README = readfile('README.rst')
CHANGES = readfile('CHANGES.rst')
AUTHORS = readfile('AUTHORS.rst')

install_requires=[]

if sys.version_info < (3, 2):
    install_requires=["backports.functools_lru_cache >= 1.0"]

# hack, or test wont run on py2.7
try:
    import multiprocessing
    import logging
except:
    pass

setup(name='wsgicors',
      version=version,
      description="WSGI for Cross Origin Resource Sharing (CORS)",
      long_description=README + '\n\n' +  CHANGES + '\n\n' +  AUTHORS,
      classifiers = [
        "License :: OSI Approved :: Apache Software License",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 3",
        "Development Status :: 3 - Alpha",
        "Environment :: Web Environment",
        "Intended Audience :: Developers",
        "Topic :: Software Development :: Libraries :: Python Modules",
        "Topic :: Internet :: WWW/HTTP :: WSGI"
        ],
      keywords=["wsgi", "cors"],
      author='Norman Krämer',
      author_email='kraemer.norman@googlemail.com',
      url="https://github.com/may-day/wsgicors",
      license='Apache Software License 2.0',
      py_modules=["wsgicors"],
      install_requires = install_requires,
      tests_require = [
        'nose',
        'nose-testconfig',
        'webob'
        ],
      test_suite = 'nose.collector',
      entry_points = """
      [paste.filter_app_factory]
      middleware = wsgicors:make_middleware
      """
      )


text:
{{ names.render( 'tr' ) }}

	As an extension of {{ names.name( 'android' ) }}'s {{ command( 'R' ) }} class, the {{ names.name( 'sbt-plugin' ) }} introduces a the {{ command( names.abbr( 'tr' ) ) }} class. It generates type safe mappings from ids in {{ names.abbr( 'xml' ) }} views to their respective class. This is explained best by a simple example.

{{ code( 'page/typed-resources/view.xml', 'xml' ) }}


text:
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" packagerversion="1.9.0" version="2.0" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0
    http://pear.php.net/dtd/tasks-1.0.xsd
    http://pear.php.net/dtd/package-2.0
    http://pear.php.net/dtd/package-2.0.xsd">
	<name>acl</name>
	<channel>pear.roundcube.net</channel>
	<summary>Folders Access Control Lists</summary>
	<description>IMAP Folders Access Control Lists Management (RFC4314, RFC2086).</description>
	<lead>
		<name>Aleksander Machniak</name>
		<user>alec</user>
		<email>alec@alec.pl</email>
		<active>yes</active>
	</lead>
	<date>2013-03-01</date>
	<version>
		<release>1.2</release>
		<api>0.7</api>
	</version>
	<stability>
		<release>stable</release>
		<api>stable</api>
	</stability>
	<license uri="http://www.gnu.org/licenses/gpl.html">GNU GPLv3+</license>
	<notes>-</notes>
	<contents>
		<dir baseinstalldir="/" name="/">
			<file name="acl.php" role="php">
				<tasks:replace from="@name@" to="name" type="package-info"/>
				<tasks:replace from="@package_version@" to="version" type="package-info"/>
			</file>
			<file name="acl.js" role="data">
				<tasks:replace from="@name@" to="name" type="package-info"/>
				<tasks:replace from="@package_version@" to="version" type="package-info"/>
			</file>
			<file name="config.inc.php.dist" role="data"></file>
			<file name="localization/de_DE.inc" role="data"></file>
			<file name="localization/en_US.inc" role="data"></file>
			<file name="localization/pl_PL.inc" role="data"></file>
			<file name="skins/classic/acl.css" role="data"></file>
			<file name="skins/classic/images/enabled.png" role="data"></file>
			<file name="skins/classic/images/partial.png" role="data"></file>
			<file name="skins/classic/templates/table.html" role="data"></file>
			<file name="skins/larry/acl.css" role="data"></file>
			<file name="skins/larry/images/enabled.png" role="data"></file>
			<file name="skins/larry/images/partial.png" role="data"></file>
			<file name="skins/larry/templates/table.html" role="data"></file>
		</dir>
		<!-- / -->
	</contents>
	<dependencies>
		<required>
			<php>
				<min>5.2.1</min>
			</php>
			<pearinstaller>
				<min>1.7.0</min>
			</pearinstaller>
		</required>
	</dependencies>
	<phprelease/>
</package>


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/txt_shout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/input_shout"
        android:inputType="textMultiLine"
        android:layout_marginLeft="5dip"
        android:layout_marginRight="5dip">

        <requestFocus />
    </EditText>

    <CheckBox
        android:id="@+id/sw_share_with_friends"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/share_with_friends"
        android:layout_marginLeft="5dip"
        android:layout_marginRight="5dip" />

    <CheckBox
        android:id="@+id/sw_share_with_facebook"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/share_with_facebook"
        android:layout_marginLeft="5dip"
        android:layout_marginRight="5dip" />

    <CheckBox
        android:id="@+id/sw_share_with_twitter"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/share_with_twitter"
        android:layout_marginLeft="5dip"
        android:layout_marginRight="5dip" />

</LinearLayout>


text:
package edu.columbia.cs.psl.phosphor.control.graph;

import edu.columbia.cs.psl.phosphor.control.graph.FlowGraph.NaturalLoop;
import edu.columbia.cs.psl.phosphor.struct.harmony.util.*;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.ExternalResource;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class FlowGraphTest {

    // A graph that contains only a source and sink node and a single edge between them
    private static FlowGraph<Integer> emptyGraph;

    // A graph containing a lot of potential loops based on figure 9.38 in Compilers: Principles, Techniques, and Tools
    // (2nd Edition) by Alfred V. Aho, Monica S. Lam, Ravi Sethi, and Jeffrey D. Ullman in section 9.6.1
    private static FlowGraph<Integer> loopingGraph;

    @ClassRule
    public static ExternalResource resource = new ExternalResource() {
        @Override
        protected void before() {
            initializeGraphs();
        }
    };

    @Test
    public void testGetAllSuccessorsEmptyGraph() {
        Map<Integer, Set<Integer>> expected = new HashMap<>();
        expected.put(0, new HashSet<>(Arrays.asList(1)));
        expected.put(1, new HashSet<>());
        assertEquals(expected, emptyGraph.getSuccessors());
    }

    @Test
    public void testGetAllPredecessorsEmptyGraph() {
        Map<Integer, Set<Integer>> expected = new HashMap<>();
        expected.put(0, new HashSet<>());
        expected.put(1, new HashSet<>(Arrays.asList(0)));
        assertEquals(expected, emptyGraph.getPredecessors());
    }

    @Test
    public void testGetSuccessors() {
        assertEquals(new HashSet<>(Arrays.asList(1)), emptyGraph.getSuccessors(0));
        assertEquals(new HashSet<>(), emptyGraph.getSuccessors(1));
    }

    @Test
    public void testGetPredecessors() {
        assertEquals(new HashSet<>(), emptyGraph.getPredecessors(0));
        assertEquals(new HashSet<>(Arrays.asList(0)), emptyGraph.getPredecessors(1));
    }

    @Test(expected = IllegalArgumentException.class)
    public void testGetSuccessorsVertexNotInGraph() {
        emptyGraph.getSuccessors(2);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testGetPredecessorsVertexNotInGraph() {
        emptyGraph.getPredecessors(2);
    }

    @Test
    public void testGetVerticesEmptyGraph() {
        assertEquals(new HashSet<>(Arrays.asList(0, 1)), emptyGraph.getVertices());
    }

    @Test
    public void testGetTransverseGraphEmptyGraph() {
        FlowGraph<Integer> expected = new FlowGraphBuilder<Integer>()
                .addEntryPoint(1)
                .addExitPoint(0)
                .addEdge(1, 0)
                .build();
        assertEquals(expected, emptyGraph.getTransverseGraph());
    }

    @Test
    public void testGetImmediateDominatorsEmptyGraph() {
        Map<Integer, Integer> expected = new HashMap<>();
        expected.put(0, null);
        expected.put(1, 0);
        assertEquals(expected, emptyGraph.getImmediateDominators());
    }

    @Test
    public void testGetDominatorSetsEmptyGraph() {
        Map<Integer, Set<Integer>> expected = new HashMap<>();
        expected.put(0, new HashSet<>(Arrays.asList(0)));
        expected.put(1, new HashSet<>(Arrays.asList(0, 1)));
        assertEquals(expected, emptyGraph.getDominatorSets());
    }

    @Test
    public void testGetDominanceFrontiersEmptyGraph() {
        Map<Integer, Set<Integer>> expected = new HashMap<>();
        expected.put(0, new HashSet<>());
        expected.put(1, new HashSet<>());
        assertEquals(expected, emptyGraph.getDominanceFrontiers());
    }

    @Test
    public void testGetNaturalLoopsEmptyGraph() {
        assertTrue(emptyGraph.getNaturalLoops().isEmpty());
    }

    @Test
    public void testGetAllSuccessorsLoopingGraph() {
        Map<Integer, Set<Integer>> expected = new HashMap<>();
        expected.put(0, new HashSet<>(Arrays.asList(1)));
        expected.put(1, new HashSet<>(Arrays.asList(2, 3)));
        expected.put(2, new HashSet<>(Arrays.asList(3)));
        expected.put(3, new HashSet<>(Arrays.asList(4)));
        expected.put(4, new HashSet<>(Arrays.asList(3, 5, 6)));
        expected.put(5, new HashSet<>(Arrays.asList(7)));
        expected.put(6, new HashSet<>(Arrays.asList(7)));
        expected.put(7, new HashSet<>(Arrays.asList(4, 8)));
        expected.put(8, new HashSet<>(Arrays.asList(3, 9, 10)));
        expected.put(9, new HashSet<>(Arrays.asList(1)));
        expected.put(10, new HashSet<>(Arrays.asList(7, 11)));
        expected.put(11, new HashSet<>());
        assertEquals(expected, loopingGraph.getSuccessors());
    }

    @Test
    public void testGetAllPredecessorsLoopingGraph() {
        Map<Integer, Set<Integer>> expected = new HashMap<>();
        expected.put(0, new HashSet<>());
        expected.put(1, new HashSet<>(Arrays.asList(0, 9)));
        expected.put(2, new HashSet<>(Arrays.asList(1)));
        expected.put(3, new HashSet<>(Arrays.asList(1, 2, 4, 8)));
        expected.put(4, new HashSet<>(Arrays.asList(3, 7)));
        expected.put(5, new HashSet<>(Arrays.asList(4)));
        expected.put(6, new HashSet<>(Arrays.asList(4)));
        expected.put(7, new HashSet<>(Arrays.asList(5, 6, 10)));
        expected.put(8, new HashSet<>(Arrays.asList(7)));
        expected.put(9, new HashSet<>(Arrays.asList(8)));
        expected.put(10, new HashSet<>(Arrays.asList(8)));
        expected.put(11, new HashSet<>(Arrays.asList(10)));
        assertEquals(expected, loopingGraph.getPredecessors());
    }

    @Test
    public void testGetVerticesLoopingGraph() {
        Set<Integer> expected = new HashSet<>();
        for(int i = 0; i <= 11; i++) {
            expected.add(i);
        }
        assertEquals(expected, loopingGraph.getVertices());
    }

    @Test
    public void testGetTransverseGraphLoopingGraph() {
        FlowGraph<Integer> expected = new FlowGraphBuilder<Integer>()
                .addEntryPoint(11)
                .addExitPoint(0)
                .addEdge(1, 0)
                .addEdge(2, 1)
                .addEdge(3, 1)
                .addEdge(3, 2)
                .addEdge(4, 3)
                .addEdge(3, 4)
                .addEdge(5, 4)
                .addEdge(6, 4)
                .addEdge(7, 5)
                .addEdge(7, 6)
                .addEdge(4, 7)
                .addEdge(8, 7)
                .addEdge(3, 8)
                .addEdge(9, 8)
                .addEdge(10, 8)
                .addEdge(1, 9)
                .addEdge(7, 10)
                .addEdge(11, 10)
                .build();
        assertEquals(expected, loopingGraph.getTransverseGraph());
    }

    @Test
    public void testGetImmediateDominatorsLoopingGraph() {
        Map<Integer, Integer> expected = new HashMap<>();
        expected.put(0, null);
        expected.put(1, 0);
        expected.put(2, 1);
        expected.put(3, 1);
        expected.put(4, 3);
        expected.put(5, 4);
        expected.put(6, 4);
        expected.put(7, 4);
        expected.put(8, 7);
        expected.put(9, 8);
        expected.put(10, 8);
        expected.put(11, 10);
        assertEquals(expected, loopingGraph.getImmediateDominators());
    }

    @Test
    public void testGetDominatorSetsLoopingGraph() {
        Map<Integer, Set<Integer>> expected = new HashMap<>();
        expected.put(0, new HashSet<>(Arrays.asList(0)));
        expected.put(1, new HashSet<>(Arrays.asList(0, 1)));
        expected.put(2, new HashSet<>(Arrays.asList(0, 1, 2)));
        expected.put(3, new HashSet<>(Arrays.asList(0, 1, 3)));
        expected.put(4, new HashSet<>(Arrays.asList(0, 1, 3, 4)));
        expected.put(5, new HashSet<>(Arrays.asList(0, 1, 3, 4, 5)));
        expected.put(6, new HashSet<>(Arrays.asList(0, 1, 3, 4, 6)));
        expected.put(7, new HashSet<>(Arrays.asList(0, 1, 3, 4, 7)));
        expected.put(8, new HashSet<>(Arrays.asList(0, 1, 3, 4, 7, 8)));
        expected.put(9, new HashSet<>(Arrays.asList(0, 1, 3, 4, 7, 8, 9)));
        expected.put(10, new HashSet<>(Arrays.asList(0, 1, 3, 4, 7, 8, 10)));
        expected.put(11, new HashSet<>(Arrays.asList(0, 1, 3, 4, 7, 8, 10, 11)));
        assertEquals(expected, loopingGraph.getDominatorSets());
    }

    @Test
    public void testGetDominanceFrontiersLoopingGraph() {
        Map<Integer, Set<Integer>> expected = new HashMap<>();
        expected.put(0, new HashSet<>());
        expected.put(1, new HashSet<>(Arrays.asList(1)));
        expected.put(2, new HashSet<>(Arrays.asList(3)));
        expected.put(3, new HashSet<>(Arrays.asList(1, 3)));
        expected.put(4, new HashSet<>(Arrays.asList(1, 3, 4)));
        expected.put(5, new HashSet<>(Arrays.asList(7)));
        expected.put(6, new HashSet<>(Arrays.asList(7)));
        expected.put(7, new HashSet<>(Arrays.asList(1, 3, 4, 7)));
        expected.put(8, new HashSet<>(Arrays.asList(1, 3, 7)));
        expected.put(9, new HashSet<>(Arrays.asList(1)));
        expected.put(10, new HashSet<>(Arrays.asList(7)));
        expected.put(11, new HashSet<>());
        assertEquals(expected, loopingGraph.getDominanceFrontiers());
    }

    @Test
    public void testGetNaturalLoopsLoopingGraph() {
        Map<NaturalLoop<Integer>, Set<Integer>> expected = new HashMap<>();
        expected.put(new NaturalLoop<>(10, 7), new HashSet<>(Arrays.asList(7, 8, 10)));
        expected.put(new NaturalLoop<>(7, 4), new HashSet<>(Arrays.asList(4, 5, 6, 7, 8, 10)));
        expected.put(new NaturalLoop<>(new HashSet<>(Arrays.asList(4, 8)), 3), new HashSet<>(Arrays.asList(3, 4, 5, 6, 7, 8, 10)));
        expected.put(new NaturalLoop<>(9, 1), new HashSet<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)));
        Set<NaturalLoop<Integer>> loops = loopingGraph.getNaturalLoops();
        assertEquals(expected.keySet(), loops);
        for(NaturalLoop<Integer> loop : loops) {
            assertEquals(expected.get(loop), loop.getVertices());
        }
    }

    private static void initializeGraphs() {
        emptyGraph = new FlowGraphBuilder<Integer>()
                .addEntryPoint(0)
                .addExitPoint(1)
                .addEdge(0, 1)
                .build();
        loopingGraph = new FlowGraphBuilder<Integer>()
                .addEntryPoint(0)
                .addExitPoint(11)
                .addEdge(0, 1)
                .addEdge(1, 2)
                .addEdge(1, 3)
                .addEdge(2, 3)
                .addEdge(3, 4)
                .addEdge(4, 3)
                .addEdge(4, 5)
                .addEdge(4, 6)
                .addEdge(5, 7)
                .addEdge(6, 7)
                .addEdge(7, 4)
                .addEdge(7, 8)
                .addEdge(8, 3)
                .addEdge(8, 9)
                .addEdge(8, 10)
                .addEdge(9, 1)
                .addEdge(10, 7)
                .addEdge(10, 11)
                .build();
    }
}


text:
<?php

App::uses('CoPetitionsController', 'Controller');

class EnvSourceCoPetitionsController extends CoPetitionsController {
  // Class name, used by Cake
  public $name = "EnvSourceCoPetitions";

  public $uses = array("CoPetition",
                       "OrgIdentitySource",
                       "EnvSource.EnvSource",
                       "EnvSource.EnvSourceBackend");

  public $in_reauth = false;

  /**
   * Callback before other controller methods are invoked or views are rendered.
   * - postcondition: If invalid enrollment flow provided, session flash message set
   *
   * @since  COmanage Registry v3.1.0
   */

  function beforeFilter() {
    // We need some special authorization logic here, depending on the type of flow.
    // This is loosely based on parent::beforeFilter().
    $noAuth = false;

    // For self signup, we simply require a token (and for the token to match).
    $token = $this->CoPetition->field('petitioner_token', array('CoPetition.id' => $this->parseCoPetitionId()));
    $passedToken = $this->parseToken();

    if($token && $token != '' && $passedToken) {
      if($token == $passedToken) {
        // If we were passed a reauth flag, we require authentication even though
        // the token matched. This enables account linking.
        if(!isset($this->request->params['named']['reauth'])
           || $this->request->params['named']['reauth'] != 1) {
          $noAuth = true;
        } else {
          // Store a hint for isAuthorized that we matched the token and are reauthenticating,
          // so we can authorize the transaction.

          $this->in_reauth = true;
        }

        // Dump the token into a viewvar in case needed
        $this->set('vv_petition_token', $token);
      } else {
        $this->Flash->set(_txt('er.token'), array('key' => 'error'));
        $this->redirect("/");
      }
    }

    if($noAuth) {
      $this->Auth->allow($this->action);

      if(!$this->Session->check('Auth.User.name')) {
        // If authentication is not required, and we're not authenticated as
        // a valid user, hide the login/logout button to minimize confusion

        $this->set('noLoginLogout', true);
      }
    }

    // We want our grandparent's beforeFilter to run, but not our parent's,
    // as that will clobber the special authz logic we just implemented.
    StandardController::beforeFilter();
  }

  /**
   * Enrollment Flow collectIdentifierIdentify (identify mode)
   *
   * @since  COmanage Registry v3.1.0
   * @param  Integer $id CO Petition ID
   * @param  Array $oiscfg Array of configuration data for this plugin
   * @param  Array $onFinish URL, in Cake format
   * @param  Integer $actorCoPersonId CO Person ID of actor
   * @throws InvalidArgumentException
   * @throws RuntimeException
   */

  protected function execute_plugin_collectIdentifierIdentify($id, $oiscfg, $onFinish, $actorCoPersonId) {
    // We'll typically get here in an invitation flow. (Self signup and account
    // linking would get handled by selectOrgIdentityAuthenticate.) So we don't
    // need to run through a logout exercise. We simply try to create a new org
    // identity.

    // retrieve() will parse the env variables and create an org identity out
    // of it. However, we need to pass the SORID/$sourceKey to confirm to that
    // backend that we really are trying to create a record.

    // First pull our configuration.

    $args = array();
    $args['conditions']['EnvSource.org_identity_source_id'] = $oiscfg['OrgIdentitySource']['id'];
    $args['contain'] = false;

    $cfg = $this->EnvSource->find('first', $args);

    if(empty($cfg)) {
      throw new InvalidArgumentException(_txt('er.notfound',
                                              array(_txt('ct.env_sources.1'),
                                                    $oiscfg['OrgIdentitySource']['id'])));
    }

    if(empty($cfg['EnvSource']['env_identifier_sorid'])) {
      throw new RuntimeException(_txt('er.envsource.sorid.cfg'));
    }

    $sorid = getenv($cfg['EnvSource']['env_identifier_sorid']);

    if(!$sorid) {
      throw new RuntimeException(_txt('er.envsource.sorid', array($cfg['EnvSource']['env_identifier_sorid'])));
    }

    // Pull the target CO Person from the petition so the new Org Identity can be linked

    $coPersonId = $this->CoPetition->field('enrollee_co_person_id', array('CoPetition.id' => $id));

    $newOrgId = $this->OrgIdentitySource->createOrgIdentity($oiscfg['OrgIdentitySource']['id'],
                                                            $sorid,
                                                            $actorCoPersonId,
                                                            $this->cur_co['Co']['id'],
                                                            $coPersonId,
                                                            false,
                                                            $id);

    // The step is done

    $this->redirect($onFinish);
  }

  /**
   * Enrollment Flow selectOrgIdentity (authenticate mode)
   *
   * @since  COmanage Registry v3.1.0
   * @param  Integer $id CO Petition ID
   * @param  Array $oiscfg Array of configuration data for this plugin
   * @param  Array $onFinish URL, in Cake format
   * @param  Integer $actorCoPersonId CO Person ID of actor
   * @throws InvalidArgumentException
   * @throws RuntimeException
   */

  protected function execute_plugin_selectOrgIdentityAuthenticate($id, $oiscfg, $onFinish, $actorCoPersonId) {
    // See if there is a petitioner_token attached to the petition.
    // If not, the petitioner is logged in and we need to log them
    // out, but first we create a token for re-entry.

    $token = $this->CoPetition->field('petitioner_token', array('CoPetition.id' => $id));

    // We distinguish self-signup enrollment from account linking by the presence
    // of $token, which will be populated at the start of a self-signup enrollment
    // (since the user will not be registered) and but not at the start of account
    // linking (since the user is already registered).
    if(!$token) {
      // Generate a token and issue a reauthentication redirect

      $token = Security::generateAuthKey();

      $this->CoPetition->id = $id;
      $this->CoPetition->saveField('petitioner_token', $token);

      // This redirect will pass through logout (to terminate the current session)
      // then send us back here (following a re-authentication). While we embed a
      // token into the URL, CoPetitionsController::beforeFilter will ignore it
      // because the settings and step configuration won't permit it. ie: Authentication
      // will be triggered, the token will not be sufficient to bypass it.
      $redirect = array(
        'plugin'     => 'env_source',
        'controller' => 'env_source_co_petitions',
        'action'     => 'selectOrgIdentityAuthenticate',
        $id,
        'oisid'      => $oiscfg['OrgIdentitySource']['id'],
        'token'      => $token,
        // Hint that we're performing account linking
        'reauth'     => '1'
      );

      $this->Session->write('Logout.redirect', $redirect);

      $this->redirect('/auth/logout');
    }

    // Before passing through to a view, we need to clear a confusing Cake generated
    // error message. See UsersController::login() for more information.
    CakeSession::delete('Message.error');

    // We simply try to create a new org identity. retrieve() will parse the
    // env variables and create an org identity out of it. However, we need to
    // pass the SORID/$sourceKey to confirm to that backend that we really are
    // trying to create a record.

    // First pull our configuration.

    $args = array();
    $args['conditions']['EnvSource.org_identity_source_id'] = $oiscfg['OrgIdentitySource']['id'];
    $args['contain'] = false;

    $cfg = $this->EnvSource->find('first', $args);

    if(empty($cfg)) {
      throw new InvalidArgumentException(_txt('er.notfound',
                                              array(_txt('ct.env_sources.1'),
                                                    $oiscfg['OrgIdentitySource']['id'])));
    }

    if(empty($cfg['EnvSource']['env_identifier_sorid'])) {
      throw new RuntimeException(_txt('er.envsource.sorid.cfg'));
    }

    $sorid = getenv($cfg['EnvSource']['env_identifier_sorid']);

    if(!$sorid) {
      throw new RuntimeException(_txt('er.envsource.sorid', array($cfg['EnvSource']['env_identifier_sorid'])));
    }

    // selectEnrollee hasn't run yet so we can't pull the target CO Person from the
    // petition, but for OISAuthenticate, it's the current user (ie: $actorCoPersonId)
    // that we always want to link to. Actually, it isn't (CO-1619), but the enrollment
    // flow should later correctly link the identity.

    $newOrgId = $this->OrgIdentitySource->createOrgIdentity($oiscfg['OrgIdentitySource']['id'],
                                                            $sorid,
                                                            $actorCoPersonId,
                                                            $this->cur_co['Co']['id'],
                                                            null,
                                                            false,
                                                            $id);

    // The step is done

    $this->redirect($onFinish);
  }

  /**
   * Authorization for this Controller, called by Auth component
   * - precondition: Session.Auth holds data used for authz decisions
   * - postcondition: $permissions set with calculated permissions
   *
   * @since  COmanage Registry v3.1.0
   * @return Array Permissions
   */

  function isAuthorized() {
    $roles = $this->Role->calculateCMRoles();

    $petitionId = $this->parseCoPetitionId();
    $curToken = null;

    if($petitionId) {
      $curToken = $this->CoPetition->field('enrollee_token', array('CoPetition.id' => $petitionId));
    }

    // Construct the permission set for this user, which will also be passed to the view.
    $p = array();

    // Invitation based collection, we need the user in the petition.
    // Note we can't invalidate this token because for the duration of the enrollment
    // $REMOTE_USER may or may not match a valid login identifier (though probably it should).
    $p['collectIdentifierIdentify'] = ($curToken == $this->parseToken());

    // Probably an account linking being initiated, so we need a valid user
    $p['selectOrgIdentityAuthenticate'] = $roles['copersonid'] || $this->in_reauth;

    $this->set('permissions', $p);
    return $p[$this->action];
  }

  /**
   * Perform a redirect back to the controller's default view.
   * - postcondition: Redirect generated
   *
   * @since  COmanage Registry v3.1.0
   */

  function performRedirect() {
    // We don't want our parent's behavior, so always redirect to /.
    $this->redirect('/');
  }
}


text:
use std::{fmt, io, iter::once, mem, os::windows::ffi::OsStrExt, path::Path, ptr, sync::Arc};

use winapi::{
    ctypes::{c_int, wchar_t},
    shared::{
        minwindef::{BYTE, LPARAM, WORD, WPARAM},
        windef::{HICON, HWND},
    },
    um::libloaderapi,
    um::winuser,
};

use crate::dpi::PhysicalSize;
use crate::icon::*;

impl Pixel {
    fn to_bgra(&mut self) {
        mem::swap(&mut self.r, &mut self.b);
    }
}

impl RgbaIcon {
    fn into_windows_icon(self) -> Result<WinIcon, BadIcon> {
        let mut rgba = self.rgba;
        let pixel_count = rgba.len() / PIXEL_SIZE;
        let mut and_mask = Vec::with_capacity(pixel_count);
        let pixels =
            unsafe { std::slice::from_raw_parts_mut(rgba.as_mut_ptr() as *mut Pixel, pixel_count) };
        for pixel in pixels {
            and_mask.push(pixel.a.wrapping_sub(std::u8::MAX)); // invert alpha channel
            pixel.to_bgra();
        }
        assert_eq!(and_mask.len(), pixel_count);
        let handle = unsafe {
            winuser::CreateIcon(
                ptr::null_mut(),
                self.width as c_int,
                self.height as c_int,
                1,
                (PIXEL_SIZE * 8) as BYTE,
                and_mask.as_ptr() as *const BYTE,
                rgba.as_ptr() as *const BYTE,
            ) as HICON
        };
        if !handle.is_null() {
            Ok(WinIcon::from_handle(handle))
        } else {
            Err(BadIcon::OsError(io::Error::last_os_error()))
        }
    }
}

#[derive(Debug)]
pub enum IconType {
    Small = winuser::ICON_SMALL as isize,
    Big = winuser::ICON_BIG as isize,
}

#[derive(Debug)]
struct RaiiIcon {
    handle: HICON,
}

#[derive(Clone)]
pub struct WinIcon {
    inner: Arc<RaiiIcon>,
}

unsafe impl Send for WinIcon {}

impl WinIcon {
    pub fn as_raw_handle(&self) -> HICON {
        self.inner.handle
    }

    pub fn from_path<P: AsRef<Path>>(
        path: P,
        size: Option<PhysicalSize<u32>>,
    ) -> Result<Self, BadIcon> {
        let wide_path: Vec<u16> = path
            .as_ref()
            .as_os_str()
            .encode_wide()
            .chain(once(0))
            .collect();

        // width / height of 0 along with LR_DEFAULTSIZE tells windows to load the default icon size
        let (width, height) = size.map(Into::into).unwrap_or((0, 0));

        let handle = unsafe {
            winuser::LoadImageW(
                ptr::null_mut(),
                wide_path.as_ptr() as *const wchar_t,
                winuser::IMAGE_ICON,
                width as c_int,
                height as c_int,
                winuser::LR_DEFAULTSIZE | winuser::LR_LOADFROMFILE,
            ) as HICON
        };
        if !handle.is_null() {
            Ok(WinIcon::from_handle(handle))
        } else {
            Err(BadIcon::OsError(io::Error::last_os_error()))
        }
    }

    pub fn from_resource(
        resource_id: WORD,
        size: Option<PhysicalSize<u32>>,
    ) -> Result<Self, BadIcon> {
        // width / height of 0 along with LR_DEFAULTSIZE tells windows to load the default icon size
        let (width, height) = size.map(Into::into).unwrap_or((0, 0));
        let handle = unsafe {
            winuser::LoadImageW(
                libloaderapi::GetModuleHandleW(ptr::null_mut()),
                winuser::MAKEINTRESOURCEW(resource_id),
                winuser::IMAGE_ICON,
                width as c_int,
                height as c_int,
                winuser::LR_DEFAULTSIZE,
            ) as HICON
        };
        if !handle.is_null() {
            Ok(WinIcon::from_handle(handle))
        } else {
            Err(BadIcon::OsError(io::Error::last_os_error()))
        }
    }

    pub fn from_rgba(rgba: Vec<u8>, width: u32, height: u32) -> Result<Self, BadIcon> {
        let rgba_icon = RgbaIcon::from_rgba(rgba, width, height)?;
        rgba_icon.into_windows_icon()
    }

    pub fn set_for_window(&self, hwnd: HWND, icon_type: IconType) {
        unsafe {
            winuser::SendMessageW(
                hwnd,
                winuser::WM_SETICON,
                icon_type as WPARAM,
                self.as_raw_handle() as LPARAM,
            );
        }
    }

    fn from_handle(handle: HICON) -> Self {
        Self {
            inner: Arc::new(RaiiIcon { handle }),
        }
    }
}

impl Drop for RaiiIcon {
    fn drop(&mut self) {
        unsafe { winuser::DestroyIcon(self.handle) };
    }
}

impl fmt::Debug for WinIcon {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        (*self.inner).fmt(formatter)
    }
}

pub fn unset_for_window(hwnd: HWND, icon_type: IconType) {
    unsafe {
        winuser::SendMessageW(hwnd, winuser::WM_SETICON, icon_type as WPARAM, 0 as LPARAM);
    }
}


text:
package edu.cmu.cs.stage3.alice.scenegraph.renderer.nativerenderer;

public abstract class DirectionalLightProxy extends LightProxy {
}


text:
GS.Detector = {
	run: function(callback) {
		var canvas = document.createElement("canvas");
		if (canvas.getContext === undefined) {
			this.displayErrorMessage("HTML5 canvas");
			return;
		}

		var webGL = (function () {
			try {
				var canvas = document.createElement("canvas");
				return !!window.WebGLRenderingContext && (canvas.getContext("webgl") || canvas.getContext("experimental-webgl"));
			} catch (e) {
				return false;
			}
		})();
		if (!webGL) {
			this.displayErrorMessage("WebGL, or WebGL failed to initialize");
			return;
		}

		var webAudio = (typeof AudioContext !== "undefined") || (typeof webkitAudioContext !== "undefined");
		if (!webAudio) {
			this.displayErrorMessage("the Web Audio API");
			return;
		}

		var pointerLock = "pointerLockElement" in document || "mozPointerLockElement" in document || "webkitPointerLockElement" in document;
		if (!pointerLock) {
			this.displayErrorMessage("the Pointer Lock API");
			return;
		}

		var localStorage;
		try {
			localStorage = "localStorage" in window && window["localStorage"] !== null;
		} catch(e) {
			localStorage = false;
		}
		if (!localStorage) {
			this.displayErrorMessage("HTML5 local storage");
			return;
		}

		callback();
	},

	displayErrorMessage: function(html) {
		var div = document.createElement("div");

		div.style.width = "450px";
		div.style.height = "150px";
		div.style.marginLeft = "-225px";
		div.style.marginTop = "-75px";
		div.style.position = "absolute";
		div.style.top = "50%";
		div.style.left = "50%";
		div.style.backgroundColor = "#000";
		div.style.color = "#fff";
		div.style.fontSize = "20px";
		div.style.fontFamily = "Arial, Helvetica, sans-serif";
		div.style.fontWeight = "normal";
		div.style.textAlign = "center";
		div.style.border = "1px dashed #fff";

		var span = document.createElement("span");
		span.style.display = "block";
		span.style.marginTop = "50px";
		span.innerHTML = "Your browser does not support<br/>" + html + ".";

		div.appendChild(span);
		document.body.appendChild(div);
	}
};


text:
/**
 * @author Alexey A. Ivanov
 */
package javax.swing.text.html;

public class StyleSheet_ConvertAttr_BorderLeftTest
    extends StyleSheet_ConvertAttr_BorderPartTestCase {

    protected void setUp() throws Exception {
        super.setUp();
        cssKey = CSS.Attribute.BORDER_LEFT;
        cssWidthKey = CSS.Attribute.BORDER_LEFT_WIDTH;
        sideIndex = 3;
    }
}


text:
package DDG::Spice::Sports::NFL::Games;
# ABSTRACT: NFL Boxscores

use strict;
use DDG::Spice;

spice to => 'https://duckduckgo.com/sports.js?q=$1&callback={{callback}}';

triggers start => '///***never trigger***///';

handle remainder => sub {
    return $_;
#    return $_ if $_ && !exists $skip{lc $_};
    return;
};

1;


text:
package calzone;

import calzone.model.BuildInfo;
import calzone.model.ProjectInfo;
import calzone.model.ResultsPageFormModel;
import calzone.model.ValueWithLabel;
import jetbrains.buildServer.controllers.BaseController;
import jetbrains.buildServer.serverSide.SBuildServer;
import jetbrains.buildServer.serverSide.SBuildType;
import jetbrains.buildServer.serverSide.SProject;
import jetbrains.buildServer.web.openapi.PluginDescriptor;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

public class ResultsPageController extends BaseController {
    private static final String[] FAILURE_FONT_SIZES = new String[]{"18pt", "24pt", "30pt", "36pt", "42pt", "48pt", "60pt", "72pt", "84pt", "96pt", "112pt", "128pt", "144pt", "180pt", "216pt"};
    private static final int[] REFRESH_FREQUENCIES = new int[]{5, 10, 15, 20, 30, 60, 120, 300};
    private static final ValueWithLabel[] DISSOLVE_RATES = new ValueWithLabel[]{
            new ValueWithLabel("direct transition", 1.0),
            new ValueWithLabel("fast (.4s) dissolve", 0.25),
            new ValueWithLabel("medium (1s) dissolve", 0.1),
            new ValueWithLabel("slow (5s) dissolve", 0.02)
    };

    private final SBuildServer server;
    private final PluginDescriptor pluginDescriptor;
    private final BuildFormatter buildFormatter;

    public ResultsPageController(SBuildServer server, PluginDescriptor pluginDescriptor) {
        super(server);
        this.server = server;
        this.pluginDescriptor = pluginDescriptor;
        final TimeFormatter timeFormatter = new TimeFormatter();
        buildFormatter = new BuildFormatter(new FinishedBuildMaker(server, timeFormatter), new RunningBuildMaker(timeFormatter));
    }

    @Override
    protected ModelAndView doHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String[] buildsToDisplay = ServletRequestUtils.getStringParameters(request, "buildsToDisplay");
        HashSet<String> buildsToDisplaySet = asSet(buildsToDisplay);
        String[] projectsToDisplay = ServletRequestUtils.getStringParameters(request, "projectsToDisplay");
        HashSet<String> projectsToDisplaySet = asSet(projectsToDisplay);

        TreeSet<String> buildNames = new TreeSet<String>();
        ArrayList<String> projectNames = new ArrayList<String>();
        TreeSet<ProjectInfo> projects = new TreeSet<ProjectInfo>();

        for (SProject sProject : server.getProjectManager().getProjects()) {
            projectNames.add(sProject.getName());
            TreeSet<BuildInfo> builds = new TreeSet<BuildInfo>();
            for (SBuildType sBuildType : sProject.getBuildTypes()) {
                buildNames.add(sBuildType.getName());
                if (isBuildInWhichWeAreInterested(sBuildType, buildsToDisplaySet, projectsToDisplaySet)) {
                    builds.add(buildFormatter.format(sBuildType));
                }
            }
            if (!builds.isEmpty()) {
                projects.add(new ProjectInfo(sProject.getName(), builds));
            }
        }

        String failFontSize = ServletRequestUtils.getStringParameter(request, "failFontSize", "72pt");
        boolean runningInItalics = parameterAsBoolean(request, "runningInItalics");
        boolean dontShowGreenBuilds = parameterAsBoolean(request, "dontShowGreenBuilds");
        boolean runTogether = parameterAsBoolean(request, "runTogether");
        boolean blink = parameterAsBoolean(request, "blink");
        boolean showDividers = parameterAsBoolean(request, "showDividers");
        boolean showTimeRemaining = parameterAsBoolean(request, "showTimeRemaining");
        boolean showTimeSinceFirstFail = parameterAsBoolean(request, "showTimeSinceFirstFail");
        int frequency = ServletRequestUtils.getIntParameter(request, "frequency", 5);
        double dissolveRate = ServletRequestUtils.getDoubleParameter(request, "dissolveRate", 1);

        Map<String, Object> model = new HashMap<String, Object>();
        model.put("results", projects);
        model.put("buildNames", buildNames);
        model.put("projectNames", projectNames);
        model.put("dontShowGreenBuilds", dontShowGreenBuilds);
        model.put("runTogether", runTogether);
        model.put("blink", blink);
        model.put("showDividers", showDividers);
        model.put("now", new Date());
        model.put("failFontSize", failFontSize);
        model.put("failFontSizes", FAILURE_FONT_SIZES);
        model.put("showTimeRemaining", showTimeRemaining);
        model.put("showTimeSinceFirstFail", showTimeSinceFirstFail);
        model.put("runningInItalics", runningInItalics);
        model.put("frequency", frequency);
        model.put("frequencies", REFRESH_FREQUENCIES);
        model.put("dissolveRate", dissolveRate);
        model.put("dissolveRates", DISSOLVE_RATES);
        model.put("formModel", new ResultsPageFormModel(buildsToDisplay, projectsToDisplay, failFontSize, dontShowGreenBuilds, runTogether, blink, showDividers, showTimeRemaining, showTimeSinceFirstFail, runningInItalics, frequency, dissolveRate));

        boolean isFragment = parameterAsBoolean(request, "fragment");
        if (isFragment) {
            return new ModelAndView(pluginDescriptor.getPluginResourcesPath("results.jsp"), model);
        } else {
            return new ModelAndView(pluginDescriptor.getPluginResourcesPath("calzone.jsp"), model);
        }
    }

    private boolean parameterAsBoolean(HttpServletRequest request, String parameterName) throws ServletRequestBindingException {
        String paramString = ServletRequestUtils.getStringParameter(request, parameterName);
        return paramString != null && paramString.length() > 0;
    }

    private boolean isBuildInWhichWeAreInterested(SBuildType sBuildType, HashSet<String> buildsToDisplaySet, HashSet<String> projectsToDisplaySet) {
        return (buildsToDisplaySet.isEmpty() || buildsToDisplaySet.contains(sBuildType.getName().toLowerCase())) &&
                (projectsToDisplaySet.isEmpty() || projectsToDisplaySet.contains(sBuildType.getProjectName().toLowerCase()));
    }

    private HashSet<String> asSet(String[] buildsToDisplay) {
        HashSet<String> buildsToDisplaySet = new HashSet<String>();
        if (buildsToDisplay != null) {
            for (String s : buildsToDisplay) {
                buildsToDisplaySet.add(s.toLowerCase());
            }
        }
        return buildsToDisplaySet;
    }
}


text:
export interface AppItem {
  icon: string;
  title: string;
  description: string;
  downloadUrl?: string;
  expectedDownloadSize?: number,
  storeAs?: string;
  installCommand?: string;
  installedExecutable?: string;
}


text:
function loadJavaScript() {

	'use strict';

	var startTime	= Date.now();
	var container;
	var camera, scene, renderer;
	var cube;

	function init() {

		// if (! Detector.webgl ) Detector.addGetWebGLMessage();

		camera = new THREE.PerspectiveCamera(45, 400 / 400, 0.1, 10000);
		camera.position.y = 200;
		camera.position.z = 400;
		camera.position.x = 0;

		scene = new THREE.Scene();

		var cubeGeometry = new THREE.CubeGeometry(100, 100, 100);
		var cubeMaterial = new THREE.MeshLambertMaterial({ color: 0xFF530D });
		cube = new THREE.Mesh(cubeGeometry, cubeMaterial);

		cube.rotation.y = Math.PI * 45 / 180;
		cube.castShadow = true;

		scene.add(cube);

		camera.lookAt(cube.position);

		var planeGeometry = new THREE.PlaneGeometry(1000,1000, 64, 64);
		var planeMaterial = new THREE.MeshLambertMaterial({color: 0xffffff, transparent: true, opacity: 0.2});
		var plane = new THREE.Mesh(planeGeometry,planeMaterial);
		plane.receiveShadow = true;
		plane.position.z = -200;

		scene.add(plane);

		// Add lights

		var pointLight = new THREE.SpotLight(0xffffff);
		pointLight.position.y = 700;
		pointLight.position.z = 600;
		pointLight.position.x = 0;
		pointLight.lookAt(cube.position);
		pointLight.castShadow = true;

		pointLight.shadowCameraRight = 1000;
		pointLight.shadowCameraLeft = -1000;
		pointLight.shadowCameraTop =  1000;
		pointLight.shadowCameraBottom = -1000;

		scene.add(pointLight);

		container = document.getElementById('titlecanvas');

		renderer = new THREE.WebGLRenderer({alpha: true});
		renderer.setSize(400, 400);
		renderer.shadowMapEnabled = true;
		renderer.shadowMapSoft = true;

		container.appendChild(renderer.domElement);

	}

	function animate() {

		render();
		requestAnimationFrame(animate);
	}

	function render() {

		cube.rotation.x += 0.02;
		cube.rotation.y += 0.0225;
		cube.rotation.z += 0.0175;

		var dtime = Date.now() - startTime;
		cube.scale.x	= 1.0 + 0.3 * Math.sin(dtime / 300);
		cube.scale.y	= 1.0 + 0.3 * Math.sin(dtime / 300);
		cube.scale.z	= 1.0 + 0.3 * Math.sin(dtime / 300);

		renderer.render(scene, camera);

	}

	init();
	animate();
}


text:
<?php

$ROOT = $_SERVER["DOCUMENT_ROOT"];

include $ROOT . '/include/function.php';
require $ROOT . '/php/Impl/hr.class.php';
require $ROOT . '/include/Smarty/Smarty.class.php';

// 分配
switch ($ac) {
    // 页面容器
    case "doLayout":
        $tpl = new Smarty;
        $tpl->display($ROOT . "/php/View/admin/hr/layout.tpl");
        break;
    // 获取列表数据
    case "doGetList" :
        $hr = new Hr;
        $hr->title = $_REQUEST["title"];
        $hr->education = $_REQUEST["education"];
        $hr->description = $_REQUEST["description"];
        $hr->welfare = $_REQUEST["welfare"];
        $hr->display = $_REQUEST["display"];

        $hr->totalCount = $hr->selectCount();

        $hrList = $hr->select($hr->getLimit());
        jsonEncode($hr->totalCount, $hrList, $db->log, "dhtmlx");
        break;
    case "edit":
        $tpl = new Smarty;
        $id = isset($_REQUEST["id"]) && !empty($_REQUEST["id"]) ? $_REQUEST["id"] : "";
        if (!empty($id)) {
            $hr = new Hr;
            $hr->id = $id;
            $hrList = $hr->select();
            //$tpl->assign("hrList", $hrList);
        }
        $tpl->display($ROOT . "/php/View/admin/hr/edit.tpl");
        break;
    case "del":
        $tpl = new Smarty;
        $hr = new Hr;
        $hr->id = isset($_REQUEST["id"]) && !empty($_REQUEST["id"]) ? $_REQUEST["id"] : "";
        $hr->delete();
        $tpl->display($ROOT . "/php/View/result/succ.tpl");
        break;
    case "doCommit":
        $tpl = new Smarty;
        $hr = new Hr;

        $hr->id = isset($_REQUEST["id"]) && !empty($_REQUEST["id"]) ? $_REQUEST["id"] : "";
        $hr->title = isset($_REQUEST["title"]) && !empty($_REQUEST["title"]) ? $_REQUEST["title"] : "";
        $hr->education = isset($_REQUEST["education"]) && !empty($_REQUEST["education"]) ? $_REQUEST["education"] : "";
        $hr->description = isset($_REQUEST["description"]) && !empty($_REQUEST["description"]) ? $_REQUEST["description"] : "";
        $hr->welfare = isset($_REQUEST["welfare"]) && !empty($_REQUEST["welfare"]) ? $_REQUEST["welfare"] : "";
        $hr->display = isset($_REQUEST["display"]) && !empty($_REQUEST["display"]) ? $_REQUEST["display"] : "";
        $hr->time = date("Y-m-d H:i:s", time());

        try {
            if (empty($hr->id)) {
                $hr->insert();
            } else {
                $hr->update();
            }
            $tpl->display($ROOT . "/php/View/result/succ.tpl");
        } catch (Exception $exc) {
            $tpl->assign("actionError", $exc);
            $tpl->display($ROOT . "/php/View/result/error.tpl");
        }
        break;
    default :
        error("There is no Action mapped for action name [{$ac}]", "", "text");
        break;
}
?>


text:
package uk.gov.hmrc.ct.accounts.frs102.boxes

import org.joda.time.LocalDate
import org.mockito.Mockito.when
import uk.gov.hmrc.ct.{AbridgedFiling, CompaniesHouseFiling, FilingCompanyType, HMRCFiling}
import uk.gov.hmrc.ct.accounts._
import uk.gov.hmrc.ct.accounts.frs102.retriever.FullAccountsBoxRetriever
import uk.gov.hmrc.ct.box.CtValidation
import uk.gov.hmrc.ct.domain.CompanyTypes

class AC13Spec extends AccountsMoneyValidationFixture[FullAccountsBoxRetriever]
               with AccountsPreviousPeriodValidationFixture[FullAccountsBoxRetriever]
               with MockFullAccountsRetriever {

  testAccountsMoneyValidationWithMin("AC13", 0, AC13.apply, true, false)

  testAccountsPreviousPoAValidation("AC13", AC13.apply)

  "AC13" should {
    val testValues = Set(
      (Some(-1), "return an error if negative", true),
      (Some(0), "return no error if zero", false),
      (Some(1), "return no error if positive", false)
    )

    testValues.foreach { case (ac13Value: Option[Int], message: String, shouldError: Boolean) =>
      s"$message" in {
        val boxRetriever = mock[FullAccountsBoxRetriever]
        when(boxRetriever.ac205()).thenReturn(AC205(Some(new LocalDate("2015-01-01"))))
        val validationResult = AC13(ac13Value).validate(boxRetriever)
        if (shouldError)
          validationResult shouldBe Set(CtValidation(Some("AC13"), "error.AC13.mustBeZeroOrPositive"))
        else
          validationResult shouldBe empty
      }
    }
  }
}


text:
package org.apache.webbeans.spi;

import java.util.Properties;

import javax.enterprise.inject.spi.BeanManager;

/**
 *
JSR-299 Container lifecycle.

 *

 * Implement this interface to provide own container initialization logic.
 *

 *

 * From the application point of view this interface can be used to start
 * and stop OpenWebBeans.
 *

 *
 */
public interface ContainerLifecycle
{
    /**
     * Initialize lifecycle.
     *

     * Implementors can configure their
     * initialization specific actions here.
     *

     * @param properties any properties
     */
    void initApplication(Properties properties);

    /**
     * Starts container. It discovers all beans
     * in the deployed application classpath.
     *

     * For Java EE artifact deployment, it scans all classes
     * and libraries in all deployment archives in the classpath.
     * There are several types of deployment archives;
     *

     *
EAR archive

     *
EJB archive

     *
WAR archive

     *
RAR archive

     *
Application client archive. OPTIONAL

     *

     *

     *
     *

     * Container uses {@link ScannerService} SPI for scanning archives
     * and act accordingly. If there is an exception while starting,
     * it must abort the deployment and provides information to the
     * developer.
     *

     *
     * @param startupObject any startup object.
     */
    void startApplication(Object startupObject);

    /**
     *

     * Stopping the Application means that the container destroys all bean instances
     * it stores, cleans and removes all contexts and does other necessary
     * cleanup actions.
     *

     *

     * Attention: Accessing the BeanManager or any bean proxy after the shutdown
     * will result in non-portable behaviour!
     *

     * @param endObject any object provided by application implementor. This can be a ServletContext, etc
     */
    void stopApplication(Object endObject);

    /**
     * Get the underlying {@link BeanManager} instance for the current application.
     * There is 1-1 correspondence between a bean manager and a deployed (web-) application.
     * @return deployment {@link BeanManager} instance
     */
    BeanManager getBeanManager();

    /**
     * Gets container's context service implementation.
     * This allows to manually start and end specific contexts.
     *
     * @return container contexts service
     */
    ContextsService getContextService();
}