text:
package org.adligo.tests4j_v1_tests.gwt_refs.v2_6.lang;

import java.util.Set;

import org.adligo.gwt_refs.v2_6.GWT_2_6_Lang;
import org.adligo.tests4j.models.shared.results.I_SourceFileTrialResult;
import org.adligo.tests4j.shared.asserts.reference.I_ClassAttributes;
import org.adligo.tests4j.shared.asserts.reference.I_FieldSignature;
import org.adligo.tests4j.shared.asserts.reference.I_MethodSignature;
import org.adligo.tests4j.system.shared.trials.SourceFileScope;
import org.adligo.tests4j.system.shared.trials.SuppressOutput;
import org.adligo.tests4j.system.shared.trials.Test;
import org.adligo.tests4j_tests.base_trials.I_CountType;
import org.adligo.tests4j_tests.base_trials.SourceFileCountingTrial;

@SourceFileScope (sourceClass=AutoCloseable_2_6_MockUse.class)
@SuppressOutput
public class AutoCloseable_2_6_UseTrial extends SourceFileCountingTrial
  implements AutoCloseable {

	private int methodsCalled = 0;

	public void close() {
		methodsCalled++;
	}

	@Test
	public void testMethods() throws Exception {
		new AutoCloseable_2_6_MockUse(this);
		assertEquals(1, methodsCalled);
	}

	@Override
	public void afterTrialTests(I_SourceFileTrialResult p) {
		super.afterTrialTests(p);
		I_ClassAttributes refs = p.getSourceClassAttributes();
		if (refs == null) {
			return;
		}
		I_ClassAttributes example = GWT_2_6_Lang.getAutoCloseable();
		assertNotNull(refs);
		assertEquals(AutoCloseable_2_6_MockUse.class.getName(), refs.getName());

		refs = p.getReferences(AutoCloseable.class.getName());

		assertEquals(example.getName(), refs.getName());
		Set<I_FieldSignature> exampleFields = example.getFields();
		Set<I_FieldSignature> fields = refs.getFields();
		for (I_FieldSignature sig: exampleFields) {
			assertContains(fields, sig);
		}
		assertEquals(exampleFields.size(), fields.size());
		Set<I_MethodSignature> exampleMethods = example.getMethods();
		Set<I_MethodSignature> methods = refs.getMethods();
		for (I_MethodSignature method: exampleMethods) {
			assertContains(methods, method);
		}
		assertEquals(exampleMethods.size(), methods.size());
	}

	@Override
	public int getTests(I_CountType type) {
		return super.getTests(type, 1);
	}

	@Override
	public int getAsserts(I_CountType type) {
		int thisAsserts = 1;
		//code coverage and circular dependencies +
		//custom afterTrialTests
		//+ see above
		int thisAfterAsserts = 8;
		if (type.isFromMetaWithCoverage()) {
			return super.getAsserts(type, thisAsserts + thisAfterAsserts);
		} else {
			return super.getAsserts(type, thisAsserts);
		}
	}

	@Override
	public int getUniqueAsserts(I_CountType type) {
		int thisUniqueAsserts = 1;
		//code coverage and circular dependencies +
		//custom afterTrialTests
		//+ see above
		int thisAfterUniqueAsserts = 8;
		if (type.isFromMetaWithCoverage()) {
			//code coverage and circular dependencies +
			//custom afterTrialTests
			return super.getUniqueAsserts(type, thisUniqueAsserts + thisAfterUniqueAsserts);
		} else {
			return super.getUniqueAsserts(type, thisUniqueAsserts);
		}
	}
}


text: tinyMCE.addI18n('nn.advhr_dlg',{size:"Storleik",noshade:"Inga skugge",width:"Breidd"});

redpajama_set_name: RedPajamaGithub


text:
<ion-view view-title="Account">
  <ion-content overflow-scroll="false" has-bouncing="true">
    <ion-list>
    <ion-toggle  ng-model="settings.enableFriends">
        Enable Friends
    </ion-toggle>
    </ion-list>
  </ion-content>
</ion-view>


text:
package com.palantir.typescript.text;

import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.ltk.core.refactoring.Refactoring;
import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;

import com.google.common.base.CharMatcher;
import com.palantir.typescript.Resources;

/**
 * The refactoring wizard for renaming TypeScript elements.
 *
 * @author dcicerone
 */
public final class RenameRefactoringWizard extends RefactoringWizard {

    public RenameRefactoringWizard(Refactoring refactoring) {
        super(refactoring, SWT.NONE);

        this.setWindowTitle(Resources.BUNDLE.getString("wizard.refactoring.window.title"));
    }

    @Override
    protected void addUserInputPages() {
        TypeScriptRenameProcessor processor = (TypeScriptRenameProcessor) this.getRefactoring().getAdapter(TypeScriptRenameProcessor.class);
        MyUserInputWizardPage page = new MyUserInputWizardPage(processor);

        this.addPage(page);
    }

    private static final class MyUserInputWizardPage extends UserInputWizardPage {

        private Text nameField;

        private final TypeScriptRenameProcessor processor;

        MyUserInputWizardPage(TypeScriptRenameProcessor processor) {
            super(MyUserInputWizardPage.class.getSimpleName());

            this.processor = processor;
        }

        @Override
        public void createControl(Composite parent) {
            Composite composite = new Composite(parent, SWT.NONE);
            composite.setLayout(new GridLayout(2, false));
            composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
            composite.setFont(parent.getFont());

            Label label = new Label(composite, SWT.NONE);
            label.setLayoutData(new GridData());
            label.setText("New name:");

            this.nameField = new Text(composite, SWT.BORDER);
            this.nameField.setText(this.processor.getOldName());
            this.nameField.setFont(composite.getFont());
            this.nameField.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false));
            this.nameField.addModifyListener(new ModifyListener() {
                @Override
                public void modifyText(ModifyEvent e) {
                    // check that there is no whitespace in the new name
                    if (!CharMatcher.whitespace().matchesAnyOf(MyUserInputWizardPage.this.nameField.getText())) {
                        setPageComplete(true);
                    }
                }
            });
            this.nameField.selectAll();

            this.setPageComplete(false);

            this.setControl(composite);
        }

        @Override
        public IWizardPage getNextPage() {
            this.setNewName();

            return super.getNextPage();
        }

        @Override
        public void setVisible(boolean visible) {
            // put the focus in the name field when the page is first displayed
            if (visible) {
                this.nameField.setFocus();
            }

            super.setVisible(visible);
        }

        @Override
        protected boolean performFinish() {
            this.setNewName();

            return super.performFinish();
        }

        private void setNewName() {
            this.processor.setNewName(this.nameField.getText());
        }
    }
}


text:
package com.att.research.xacml.std.pip.engines;

import java.util.Properties;

import com.att.research.xacml.api.pip.PIPException;
import com.att.research.xacml.api.pip.PIPResponse;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

/**
 * StdConfigurableEngine implements the {@link com.att.research.xacml.std.pip.engines.ConfigurableEngine} interface to automatically
 * process the standard name, description, and issuer properties.
 *
 * @author car
 * @version $Revision$
 */
public abstract class StdConfigurableEngine implements ConfigurableEngine {
	public static final String PROP_NAME			= "name";
	public static final String PROP_DESCRIPTION		= "description";
	public static final String PROP_ISSUER			= "issuer";
	public static final String PROP_CACHESPEC		= "cacheSpec";

	private String name;
	private String description;
	private String issuer;
	private Cache<String,PIPResponse> cache;

	public StdConfigurableEngine() {
	}

	@Override
	public String getName() {
		return this.name;
	}

	public void setName(String nameIn) {
		this.name	= nameIn;
	}

	@Override
	public String getDescription() {
		return this.description;
	}

	public void setDescription(String descriptionIn) {
		this.description	= descriptionIn;
	}

	public String getIssuer() {
		return this.issuer;
	}

	public void setIssuer(String issuerIn) {
		this.issuer	= issuerIn;
	}

	public Cache<String, PIPResponse> getCache() {
		return cache;
	}

	public void setCache(Cache<String, PIPResponse> cache) {
		this.cache = cache;
	}

	@Override
	public void configure(String id, Properties properties) throws PIPException {
		this.setName(properties.getProperty(id + "." + PROP_NAME, id));
		this.setDescription(properties.getProperty(id + "." + PROP_DESCRIPTION));
		this.setIssuer(properties.getProperty(id + "." + PROP_ISSUER));
		/*
		 * Configure the cache IF it is defined
		 */
		if (properties.getProperty(id + "." + PROP_CACHESPEC) != null) {
			this.cache	= CacheBuilder.from(properties.getProperty(id + "." + PROP_CACHESPEC)).build();
		}
	}

}


text:
package com.sanath.movies.models;

import android.os.Parcel;
import android.os.Parcelable;

import com.google.gson.annotations.SerializedName;

/**
 * Created by sanathnandasiri on 7/14/16.
 */

public class Movie implements Parcelable {
    @SerializedName("id")
    public String id;
    @SerializedName("title")
    public String title;
    @SerializedName("original_title")
    public String originalTitle;
    @SerializedName("original_language")
    public String originalLanguage;
    @SerializedName("release_date")
    public String releaseDate;
    @SerializedName("overview")
    public String overview;
    @SerializedName("poster_path")
    public String posterPath;
    @SerializedName("backdrop_path")
    public String backdropPath;
    @SerializedName("popularity")
    public String popularity;
    @SerializedName("vote_count")
    public String voteCount;
    @SerializedName("vote_average")
    public String voteAverage;

    public boolean isFavorite;

    public Movie() {
    }

    @Override
    public String toString() {
        return "Movie{" +
                "id='" + id + '\'' +
                ", title='" + title + '\'' +
                ", originalTitle='" + originalTitle + '\'' +
                ", originalLanguage='" + originalLanguage + '\'' +
                ", releaseDate='" + releaseDate + '\'' +
                ", overview='" + overview + '\'' +
                ", posterPath='" + posterPath + '\'' +
                ", backdropPath='" + backdropPath + '\'' +
                ", popularity='" + popularity + '\'' +
                ", voteCount='" + voteCount + '\'' +
                ", voteAverage='" + voteAverage + '\'' +
                ", isFavorite=" + isFavorite +
                '}';
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.id);
        dest.writeString(this.title);
        dest.writeString(this.originalTitle);
        dest.writeString(this.originalLanguage);
        dest.writeString(this.releaseDate);
        dest.writeString(this.overview);
        dest.writeString(this.posterPath);
        dest.writeString(this.backdropPath);
        dest.writeString(this.popularity);
        dest.writeString(this.voteCount);
        dest.writeString(this.voteAverage);
        dest.writeByte(this.isFavorite ? (byte) 1 : (byte) 0);
    }

    protected Movie(Parcel in) {
        this.id = in.readString();
        this.title = in.readString();
        this.originalTitle = in.readString();
        this.originalLanguage = in.readString();
        this.releaseDate = in.readString();
        this.overview = in.readString();
        this.posterPath = in.readString();
        this.backdropPath = in.readString();
        this.popularity = in.readString();
        this.voteCount = in.readString();
        this.voteAverage = in.readString();
        this.isFavorite = in.readByte() != 0;
    }

    public static final Creator<Movie> CREATOR = new Creator<Movie>() {
        @Override
        public Movie createFromParcel(Parcel source) {
            return new Movie(source);
        }

        @Override
        public Movie[] newArray(int size) {
            return new Movie[size];
        }
    };
}


text:
package org.assertj.core.internal;

import static org.assertj.core.data.MapEntry.entry;
import static org.assertj.core.test.ExpectedException.none;
import static org.assertj.core.test.Maps.mapOf;
import static org.mockito.Mockito.spy;

import java.util.Map;

import org.assertj.core.data.MapEntry;
import org.assertj.core.test.ExpectedException;
import org.junit.Before;
import org.junit.Rule;

/**
 * Base class for {@link Maps} unit tests
 *

 * Is in org.assertj.core.internal package to be able to set {@link Maps} attributes appropriately.
 *
 * @author Joel Costigliola
 *
 */
public class MapsBaseTest {

  @Rule
  public ExpectedException thrown = none();
  protected Map<String, String> actual;
  protected Failures failures;
  protected Maps maps;

  @Before
  public void setUp() {
    actual = mapOf(entry("name", "Yoda"), entry("color", "green"));
    failures = spy(new Failures());
    maps = new Maps();
    maps.failures = failures;
  }

  @SuppressWarnings("rawtypes")
  protected static MapEntry[] emptyEntries() {
    return new MapEntry[0];
  }

  protected static String[] emptyKeys() {
    return new String[0];
  }
}


text:
.rotate {
  -webkit-transform: rotate(-90deg);
  -moz-transform: rotate(-90deg);
  -ms-transform: rotate(-90deg);
  -o-transform: rotate(-90deg);
  transform: rotate(-90deg);

  /* also accepts left, right, top, bottom coordinates; not required, but a good idea for styling */
  -webkit-transform-origin: 150% 100%;
  -moz-transform-origin: 150% 100%;
  -ms-transform-origin: 150% 100%;
  -o-transform-origin: 150% 100%;
  transform-origin: 150% 100%;

  /* Should be unset in IE9+ I think. */
  filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}


text:
/*****
 * functions for the expert script creation process.
 *
 ******/

function chgStage(chg, loc){
	if(chg==-1 && currentStage==1) return;
	if(chg>=1 && currentStage==maxStage){
		alert("last stage");
		return;
	}
	if(chg==1 || chg==-1){
		var oldStage = currentStage;
		currentStage += chg;
	}
	else if(chg>1) currentStage = chg;
	var winloc = window.location.href;

	if(winloc.indexOf("stage")<0) winloc = loc+"?stage="+currentStage;
	else {
		winloc = location.href.replace("stage="+oldStage, "stage="+currentStage);
	}
	window.location.href = winloc;
}
/**
** We either display the map at the current stage of the case or display the complete map (as if on last card)
 */
/*function toggleMapDisplay(){
	sendAjax(0, callBackReload, "toggleShowAll", "");
}*/

/**
 * we change the language of the map and reload the page to display the changed list items
 */
function chgMapLang(){
	var newLang = $("#scriptloc").val();
	listUrl="../jsonp_"+newLang+".json";
	listNursingUrl="../jsonp_n_"+newLang+".json";
	scriptlang = newLang;
	//alert(listUrl);
	if(isEmptyScript=="true"){ //trigger submit, script is empty
		sendAjax(newLang, callBackReload, "changeLangOfScript", "");
	}
	else{ //we have to ask user what he/she wants to do with the already created items
		var cont = confirm("Wollen Sie die Sprache ändern? Es wird versucht alle bereits eingegebenen Knoten in die neue Sprache zu übersetzen.")
		if(cont){
			sendAjax(newLang, callBackReload, "changeLangOfScript", "");
		}
	}
	//location.reload();
}

/*function chgBox2(){
	var newType = $("#chgbox2").val();
	sendAjax(newType, callBackReload, "changeBoxType2", "");
	//location.reload();
}

function chgBox3(){
	var newType = $("#chgbox3").val();
	sendAjax(newType, callBackReload, "changeBoxType3", "");
	//location.reload();
}

function chgBox4(){
	var newType = $("#chgbox4").val();
	sendAjax(newType, callBackReload, "changeBoxType4", "");
	//location.reload();
}

function chgBox6(){
	var newType = $("#chgbox6").val();
	sendAjax(newType, callBackReload, "changeBoxType6", "");
	//location.reload();
}*/

function toggleDisplayMode(){
	if(sessionStorage.displayMode==1) sessionStorage.displayMode = 0;
	else sessionStorage.displayMode = 1;
	/*if (displayMode==1) displayMode = 0;
	else displayMode = 1;*/
	toggleShowAll();
}
/**
 * the display of the individual map is either as a step-thru (0) or complete map display (1)
 * @param url
 * @returns
 */
function toggleShowAll(){

	var winloc = window.location.href;
	if(winloc.indexOf("repdm")<0) winloc = winloc+"&repdm=0";

	if (sessionStorage.displayMode==1){
		winloc = winloc.replace("repdm=1", "repdm=0");
	}
	else
		winloc = winloc.replace("repdm=0", "repdm=1");

	//alert ( winloc);
	window.location.href = winloc;
}

/*
 * expert has chosen a diagnosis to be a final one...
 */
function expFinalDiagnosis(id){
	sendAjax(id, expFinalDiagnosisCallback, "expSetFinalDiagnosis", "");
}

/*
 * expert has chosen a diagnosis to be a final one...
 */
function expNoFinalDiagnosis(id){
	sendAjax(id, expFinalDiagnosisCallback, "expSetNoFinalDiagnosis", "");
}

function expFinalDiagnosisCallback(){
	diagnosisCallBack();
}

/* expert changes the stage for a problem or ddx or ...*/
function chgStageItem(obj){
	var id = obj.id;
	var realId = id.substring(9);
	var newStage = $("#"+id).val();
	if(newStage<=0 || newStage>maxStage){ //check that the new card idx is within the case length!
		alert("Invalid card number");
		return;
	}
	else
		sendAjax(realId, chgStageCallback, "chgStateOfItem", newStage);
}

/* changes the stage when the final diagnosis is made */
function chgStageFinal(obj){
	var id = obj.id;
	var realId = id.substring(14);
	var newStage = $("#"+id).val();
	sendAjax(realId, chgStageCallback, "chgFinalState", newStage);
}

/**
* the stage at which the connection appears is changed
 */
function chgStageEdge(obj){
	var cnxId = $("#conn_id").html();	// form of "cnx_12345"
	//var cnx = getConnectionById(cnxId);
	var newStage = $("#conn_stage").val();
	sendAjax(cnxId, chgStageCallback, "chgStateOfEdge", newStage);
}
function chgSummStCrd(obj){
	var id = obj.id;
	var newStage = $("#"+id).val();
	sendAjax(newStage, chgStageCallback, "chgSummStCard", newStage);
}

/**
* we reload the changed box and the connections.
 */
function chgStageCallback(){
	location.reload();
}

/**
 * open the jdialog to display the editor to create a new script
 **/
function createNewScript(){
	$("#jdialog").dialog( "option", "width", ['350'] );
	$("#jdialog").dialog( "option", "height", ['250'] );
	$("#jdialog").dialog( "option", "title", "Create new script" );
	$("#jdialog").dialog( "option", "buttons", [ ] );
	$("#jdialog").dialog( "open" );
	$("#jdialog").dialog( "option", "position", [0,0] );
	$("#jdialog").html();
	$("#jdialog").show();
}

function toggleStageDisplay(){
    $(".stagedisplay").hide();
    $(".stagestepon").show();
    $(".stagestepoff").hide();
    if(displayMode==1){
    	$(".stagedisplay").show(); //display of stages
    	$(".stagestepon").hide(); //the navigation
    	$(".stagestepoff").show();
    }
}

function openSelBoxes(title){
	$("#boxesSel").dialog( "option", "width", ['300'] );
	$("#boxesSel").dialog( "option", "height", 'auto' );
	$("#boxesSel").dialog( "option", "maxHeight", '400' );
	$("#boxesSel").dialog( "option", "title", title?title:"");
	$("#boxesSel").dialog( "option", "buttons", [ ] );
	$("#boxesSel" ).dialog( "open" );
	$("#boxesSel").show();
}

/**
* we check whether the author has checked 4 or less boxes, if more we alert a warning.
 */
function checkBoxNum(){
	var boxesNum = ($('.boxeschk :checked').size());
	if(boxesNum>4) alert("Please only select 4 Boxes.");
}

function saveBoxesSel(){
	if(($('.boxeschk :checked').size())>4){
		alert("Please only select max. 4 Boxes.");
	}
	else{
		var arr = [];
		$(".boxeschk").each(function(){
	   		if($(this).is(":checked")){
		 		arr.push($(this).val());
	   		}
			else{
		 		arr.push(0);
	   		}
		})
	var vals = arr.join(",");
	//alert(vals);
		sendAjax(vals, callBackReload, "changeBoxType", "");
	}
}

function initBoxesSel(){
	   for(var i=1; i<=20;i++){
		//var val = box1type;
		if(box1Type==i || box2Type==i || box3Type==i || box4Type==i)
			$("#boxtypes"+i).prop("checked", true);
	}

}

/*function chgBox(boxNo){
	var newType = $("#chgbox"+boxNo).val();
	sendAjax(newType, callBackReload, "changeBoxType"+boxNo, "");
	//location.reload();
}*/


text:
<?php

namespace Kendoctor\Bundle\DocumentorBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * ContentRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ContentRepository extends EntityRepository
{
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.15"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>reVision: Class Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

reVision
    5.0.0

Video game engine project.

Here is a list of all documented class members with links to the class documentation for each member:

- t -

Technique_Category
: Graphics_Technique

TextInput()
: TextInput

Texture()
: Texture

tick()
: CameraController
, Editor_Interface
, Engine
, EntityInspector
, Hotkeys
, ImGUI_Element
, MissingFileDialogue
, OpenDialogue
, Prefabs
, RecoverDialogue
, RotationIndicator
, SaveDialogue
, SceneInspector
, Settings
, TitleBar
, UnsavedChangesDialogue

tickThreaded()
: Engine

TitleBar()
: TitleBar

to_buffer()
: ecsBaseComponent
, ecsComponent< C, chars >

Toggle()
: Toggle

toggleAddToSelection()
: LevelEditor_Module

Transform()
: Transform

Transform_System()
: Transform_System

Translation_Gizmo()
: Translation_Gizmo

tryPrompt()
: UnsavedChangesDialogue

<address class="footer">
Generated by

 1.8.15
</address>


text:
package org.apache.olingo.odata2.core.debug;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.olingo.odata2.api.commons.HttpContentType;
import org.apache.olingo.odata2.api.commons.HttpHeaders;
import org.apache.olingo.odata2.api.commons.HttpStatusCodes;
import org.apache.olingo.odata2.api.commons.ODataHttpMethod;
import org.apache.olingo.odata2.api.edm.EdmNavigationProperty;
import org.apache.olingo.odata2.api.edm.EdmProperty;
import org.apache.olingo.odata2.api.exception.ODataException;
import org.apache.olingo.odata2.api.exception.ODataMessageException;
import org.apache.olingo.odata2.api.processor.ODataContext;
import org.apache.olingo.odata2.api.processor.ODataContext.RuntimeMeasurement;
import org.apache.olingo.odata2.api.processor.ODataResponse;
import org.apache.olingo.odata2.api.uri.NavigationPropertySegment;
import org.apache.olingo.odata2.api.uri.PathInfo;
import org.apache.olingo.odata2.api.uri.SelectItem;
import org.apache.olingo.odata2.api.uri.UriInfo;
import org.apache.olingo.odata2.api.uri.UriParser;
import org.apache.olingo.odata2.api.uri.expression.CommonExpression;
import org.apache.olingo.odata2.api.uri.expression.ExpressionParserException;
import org.apache.olingo.odata2.api.uri.expression.FilterExpression;
import org.apache.olingo.odata2.api.uri.expression.OrderByExpression;
import org.apache.olingo.odata2.testutil.fit.BaseTest;
import org.apache.olingo.odata2.testutil.helper.StringHelper;
import org.junit.Test;

/**
 * Tests for the debug information output.
 */
public class ODataDebugResponseWrapperTest extends BaseTest {

  private static final String EXPECTED = "{"
      + "\"request\":{\"method\":\"GET\",\"uri\":\"http://test/entity\",\"protocol\":null},"
      + "\"response\":{\"status\":{\"code\":200,\"info\":\"OK\"}},"
      + "\"server\":{\"version\":null}}";

  private ODataContext mockContext(final ODataHttpMethod method) throws ODataException {
    ODataContext context = mock(ODataContext.class);
    when(context.getHttpMethod()).thenReturn(method.name());
    PathInfo pathInfo = mock(PathInfo.class);
    when(pathInfo.getRequestUri()).thenReturn(URI.create("http://test/entity"));
    when(pathInfo.getServiceRoot()).thenReturn(URI.create("http://test/"));
    when(context.getPathInfo()).thenReturn(pathInfo);
    when(context.getRuntimeMeasurements()).thenReturn(null);
    return context;
  }

  private ODataResponse mockResponse(final HttpStatusCodes status, final String body, final String contentType) {
    ODataResponse response = mock(ODataResponse.class);
    when(response.getStatus()).thenReturn(status);
    when(response.getEntity()).thenReturn(body);
    if (contentType != null) {
      when(response.getHeaderNames()).thenReturn(new HashSet<String>(Arrays.asList(HttpHeaders.CONTENT_TYPE)));
      when(response.getHeader(HttpHeaders.CONTENT_TYPE)).thenReturn(contentType);
      when(response.getContentHeader()).thenReturn(contentType);
    }
    return response;
  }

  private RuntimeMeasurement mockRuntimeMeasurement(final String method, final long startTime, final long stopTime) {
    RuntimeMeasurement measurement = mock(RuntimeMeasurement.class);
    when(measurement.getClassName()).thenReturn("class");
    when(measurement.getMethodName()).thenReturn(method);
    when(measurement.getTimeStarted()).thenReturn(startTime);
    when(measurement.getTimeStopped()).thenReturn(stopTime);
    return measurement;
  }

  @Test
  public void minimal() throws Exception {
    final ODataContext context = mockContext(ODataHttpMethod.PUT);
    final ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.NO_CONTENT, null, null);

    ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
        ODataDebugResponseWrapper.ODATA_DEBUG_JSON).wrapResponse();
    final String actualJson = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertEquals(EXPECTED.replace(ODataHttpMethod.GET.name(), ODataHttpMethod.PUT.name())
        .replace(Integer.toString(HttpStatusCodes.OK.getStatusCode()),
            Integer.toString(HttpStatusCodes.NO_CONTENT.getStatusCode()))
        .replace(HttpStatusCodes.OK.getInfo(), HttpStatusCodes.NO_CONTENT.getInfo()),
        actualJson);

    response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
        ODataDebugResponseWrapper.ODATA_DEBUG_HTML).wrapResponse();
    final String html = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertTrue(html.contains(HttpStatusCodes.NO_CONTENT.getInfo()));
  }

  @Test
  public void body() throws Exception {
    final ODataContext context = mockContext(ODataHttpMethod.GET);
    ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.OK, "\"test\"", HttpContentType.APPLICATION_JSON);

    ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
        ODataDebugResponseWrapper.ODATA_DEBUG_JSON).wrapResponse();
    String entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertEquals(EXPECTED.replace("}},\"server",
        "},\"headers\":{\"" + HttpHeaders.CONTENT_TYPE + "\":\"" + HttpContentType.APPLICATION_JSON + "\"},"
            + "\"body\":\"test\"},\"server"),
        entity);

    wrappedResponse = mockResponse(HttpStatusCodes.OK, "test", HttpContentType.TEXT_PLAIN);
    response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
        ODataDebugResponseWrapper.ODATA_DEBUG_JSON).wrapResponse();
    entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertEquals(EXPECTED.replace("}},\"server",
        "},\"headers\":{\"" + HttpHeaders.CONTENT_TYPE + "\":\"" + HttpContentType.TEXT_PLAIN + "\"},"
            + "\"body\":\"test\"},\"server"),
        entity);

    wrappedResponse = mockResponse(HttpStatusCodes.OK, null, "image/png");
    when(wrappedResponse.getEntity()).thenReturn(new ByteArrayInputStream("test".getBytes()));
    response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
        ODataDebugResponseWrapper.ODATA_DEBUG_JSON).wrapResponse();
    entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertEquals(EXPECTED.replace("}},\"server",
        "},\"headers\":{\"" + HttpHeaders.CONTENT_TYPE + "\":\"image/png\"},"
            + "\"body\":\"dGVzdA==\"},\"server"),
        entity);

    when(wrappedResponse.getEntity()).thenReturn(new ByteArrayInputStream("test".getBytes()));
    response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
        ODataDebugResponseWrapper.ODATA_DEBUG_HTML).wrapResponse();
    entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertTrue(entity.contains(""));
  }

  @Test
  public void headers() throws Exception {
    ODataContext context = mockContext(ODataHttpMethod.GET);
    Map<String, List<String>> headers = new HashMap<String, List<String>>();
    headers.put(HttpHeaders.CONTENT_TYPE, Arrays.asList(HttpContentType.APPLICATION_JSON));
    when(context.getRequestHeaders()).thenReturn(headers);

    final ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.OK, null, HttpContentType.APPLICATION_JSON);

    ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
        ODataDebugResponseWrapper.ODATA_DEBUG_JSON).wrapResponse();
    String entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertEquals(EXPECTED.replace("},\"response",
        ",\"headers\":{\"" + HttpHeaders.CONTENT_TYPE + "\":\"" + HttpContentType.APPLICATION_JSON + "\"}},\"response")
        .replace("}},\"server",
            "},\"headers\":{\"" + HttpHeaders.CONTENT_TYPE + "\":\"" + HttpContentType.APPLICATION_JSON
                + "\"}},\"server"),
        entity);

    response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
        ODataDebugResponseWrapper.ODATA_DEBUG_HTML).wrapResponse();
    entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertTrue(entity.contains("Content-Type	application/json	"));
  }

  @Test
  public void server() throws Exception {
    ODataContext context = mockContext(ODataHttpMethod.GET);
    HttpServletRequest servletRequest = mock(HttpServletRequest.class);
    when(servletRequest.getServerPort()).thenReturn(12345);
    when(context.getParameter(ODataContext.HTTP_SERVLET_REQUEST_OBJECT)).thenReturn(servletRequest);

    final ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.OK, null, null);
    ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
        ODataDebugResponseWrapper.ODATA_DEBUG_JSON).wrapResponse();
    String entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertEquals(EXPECTED.replace("null}}", "null,\"environment\":{\"serverPort\":\"12345\"}}}"),
        entity);

    response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
        ODataDebugResponseWrapper.ODATA_DEBUG_HTML).wrapResponse();
    entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertTrue(entity.contains("serverPort	12345	"));
  }

  @Test
  public void uri() throws Exception {
    final ODataContext context = mockContext(ODataHttpMethod.GET);
    final ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.OK, null, null);

    UriInfo uriInfo = mock(UriInfo.class);
    final FilterExpression filter = UriParser.parseFilter(null, null, "true");
    when(uriInfo.getFilter()).thenReturn(filter);
    final OrderByExpression orderBy = UriParser.parseOrderBy(null, null, "true");
    when(uriInfo.getOrderBy()).thenReturn(orderBy);
    List<ArrayList<NavigationPropertySegment>> expand = new ArrayList<ArrayList<NavigationPropertySegment>>();
    NavigationPropertySegment segment = mock(NavigationPropertySegment.class);
    EdmNavigationProperty navigationProperty = mock(EdmNavigationProperty.class);
    when(navigationProperty.getName()).thenReturn("nav");
    when(segment.getNavigationProperty()).thenReturn(navigationProperty);
    ArrayList<NavigationPropertySegment> segments = new ArrayList<NavigationPropertySegment>();
    segments.add(segment);
    expand.add(segments);
    when(uriInfo.getExpand()).thenReturn(expand);
    SelectItem select1 = mock(SelectItem.class);
    SelectItem select2 = mock(SelectItem.class);
    EdmProperty property = mock(EdmProperty.class);
    when(property.getName()).thenReturn("property");
    when(select1.getProperty()).thenReturn(property);
    when(select2.getProperty()).thenReturn(property);
    when(select2.getNavigationPropertySegments()).thenReturn(segments);
    when(uriInfo.getSelect()).thenReturn(Arrays.asList(select1, select2));

    ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, uriInfo, null,
        ODataDebugResponseWrapper.ODATA_DEBUG_JSON).wrapResponse();
    String entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertEquals(EXPECTED.replace("null}}", "null,"
        + "\"uri\":{\"filter\":{\"nodeType\":\"LITERAL\",\"type\":\"Edm.Boolean\",\"value\":\"true\"},"
        + "\"orderby\":{\"nodeType\":\"order collection\","
        + "\"orders\":[{\"nodeType\":\"ORDER\",\"sortorder\":\"asc\","
        + "\"expression\":{\"nodeType\":\"LITERAL\",\"type\":\"Edm.Boolean\",\"value\":\"true\"}}]},"
        + "\"expandSelect\":{\"all\":false,\"properties\":[\"property\"],"
        + "\"links\":[{\"nav\":{\"all\":false,\"properties\":[\"property\"],\"links\":[]}}]}}}}"),
        entity);

    response = new ODataDebugResponseWrapper(context, wrappedResponse, uriInfo, null,
        ODataDebugResponseWrapper.ODATA_DEBUG_HTML).wrapResponse();
    entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertTrue(entity.contains("Edm.Boolean"));
    assertTrue(entity.contains("asc"));
  }

  @Test
  public void uriWithException() throws Exception {
    final ODataContext context = mockContext(ODataHttpMethod.GET);
    final ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.OK, null, null);

    ExpressionParserException exception = mock(ExpressionParserException.class);
    when(exception.getMessageReference()).thenReturn(ExpressionParserException.COMMON_ERROR);
    when(exception.getStackTrace()).thenReturn(new StackTraceElement[] {
        new StackTraceElement("class", "method", "file", 42) });
    CommonExpression filterTree = mock(CommonExpression.class);
    when(filterTree.getUriLiteral()).thenReturn("wrong");
    when(exception.getFilterTree()).thenReturn(filterTree);

    ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), exception,
        ODataDebugResponseWrapper.ODATA_DEBUG_JSON).wrapResponse();
    String entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertEquals(EXPECTED.replace("null}}", "null,"
        + "\"uri\":{\"error\":{\"expression\":\"wrong\"}},"
        + "\"stacktrace\":{\"exceptions\":[{\"class\":\"" + exception.getClass().getName() + "\","
        + "\"message\":\"Error while parsing a ODATA expression.\","
        + "\"invocation\":{\"class\":\"class\",\"method\":\"method\",\"line\":42}}],"
        + "\"stacktrace\":[{\"class\":\"class\",\"method\":\"method\",\"line\":42}]}}}"),
        entity);

    response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), exception,
        ODataDebugResponseWrapper.ODATA_DEBUG_HTML).wrapResponse();
    entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertTrue(entity.contains("wrong"));
    assertTrue(entity.contains(exception.getClass().getName()));
    assertTrue(entity.contains("42"));
  }

  @Test
  public void runtime() throws Exception {
    ODataContext context = mockContext(ODataHttpMethod.GET);
    List<RuntimeMeasurement> runtimeMeasurements = new ArrayList<RuntimeMeasurement>();
    runtimeMeasurements.add(mockRuntimeMeasurement("method", 1000, 42000));
    runtimeMeasurements.add(mockRuntimeMeasurement("inner", 2000, 5000));
    runtimeMeasurements.add(mockRuntimeMeasurement("inner", 7000, 12000));
    runtimeMeasurements.add(mockRuntimeMeasurement("inner", 13000, 16000));
    runtimeMeasurements.add(mockRuntimeMeasurement("inner2", 14000, 15000));
    runtimeMeasurements.add(mockRuntimeMeasurement("child", 17000, 21000));
    runtimeMeasurements.add(mockRuntimeMeasurement("second", 45000, 99000));
    when(context.getRuntimeMeasurements()).thenReturn(runtimeMeasurements);

    final ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.OK, null, null);

    ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
        ODataDebugResponseWrapper.ODATA_DEBUG_JSON).wrapResponse();
    String entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertEquals(EXPECTED.replace("null}}", "null,"
        + "\"runtime\":[{\"class\":\"class\",\"method\":\"method\",\"duration\":{\"value\":41,\"unit\":\"µs\"},"
        + "\"children\":[{\"class\":\"class\",\"method\":\"inner\",\"duration\":{\"value\":8,\"unit\":\"µs\"}},"
        + "{\"class\":\"class\",\"method\":\"inner\",\"duration\":{\"value\":3,\"unit\":\"µs\"},\"children\":["
        + "{\"class\":\"class\",\"method\":\"inner2\",\"duration\":{\"value\":1,\"unit\":\"µs\"}}]},"
        + "{\"class\":\"class\",\"method\":\"child\",\"duration\":{\"value\":4,\"unit\":\"µs\"}}]},"
        + "{\"class\":\"class\",\"method\":\"second\",\"duration\":{\"value\":54,\"unit\":\"µs\"}}]}}"),
        entity);

    response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), null,
        ODataDebugResponseWrapper.ODATA_DEBUG_HTML).wrapResponse();
    entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertTrue(entity.contains("54 µs"));
  }

  @Test
  public void exception() throws Exception {
    final ODataContext context = mockContext(ODataHttpMethod.GET);
    final ODataResponse wrappedResponse = mockResponse(HttpStatusCodes.BAD_REQUEST, null, null);

    ODataMessageException exception = mock(ODataMessageException.class);
    when(exception.getMessageReference()).thenReturn(ODataMessageException.COMMON);
    RuntimeException innerException = mock(RuntimeException.class);
    when(innerException.getLocalizedMessage()).thenReturn("error");
    final StackTraceElement[] stackTrace = new StackTraceElement[] {
        new StackTraceElement("innerClass", "innerMethod", "innerFile", 99),
        new StackTraceElement("class", "method", "file", 42),
        new StackTraceElement("outerClass", "outerMethod", "outerFile", 11) };
    when(innerException.getStackTrace()).thenReturn(stackTrace);
    when(exception.getCause()).thenReturn(innerException);
    when(exception.getStackTrace()).thenReturn(Arrays.copyOfRange(stackTrace, 1, 3));

    ODataResponse response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), exception,
        ODataDebugResponseWrapper.ODATA_DEBUG_JSON).wrapResponse();
    String entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertEquals(EXPECTED
        .replace(Integer.toString(HttpStatusCodes.OK.getStatusCode()),
            Integer.toString(HttpStatusCodes.BAD_REQUEST.getStatusCode()))
        .replace(HttpStatusCodes.OK.getInfo(), HttpStatusCodes.BAD_REQUEST.getInfo())
        .replace("null}}", "null,"
            + "\"stacktrace\":{\"exceptions\":[{\"class\":\"" + exception.getClass().getName() + "\","
            + "\"message\":\"Common exception\","
            + "\"invocation\":{\"class\":\"class\",\"method\":\"method\",\"line\":42}},"
            + "{\"class\":\"" + innerException.getClass().getName() + "\",\"message\":\"error\","
            + "\"invocation\":{\"class\":\"innerClass\",\"method\":\"innerMethod\",\"line\":99}}],"
            + "\"stacktrace\":[{\"class\":\"class\",\"method\":\"method\",\"line\":42},"
            + "{\"class\":\"outerClass\",\"method\":\"outerMethod\",\"line\":11}]}}}"),
        entity);

    response = new ODataDebugResponseWrapper(context, wrappedResponse, mock(UriInfo.class), exception,
        ODataDebugResponseWrapper.ODATA_DEBUG_HTML).wrapResponse();
    entity = StringHelper.inputStreamToString((InputStream) response.getEntity());
    assertTrue(entity.contains("Common exception"));
    assertTrue(entity.contains("42"));
    assertTrue(entity.contains("innerMethod"));
    assertTrue(entity.contains("outerMethod"));
  }
}


text:
var searchData=
[
  ['scenemanager',['SceneManager',['../class_lumengine_1_1_scene_manager.html',1,'Lumengine']]],
  ['scenenode',['SceneNode',['../class_lumengine_1_1_scene_node.html',1,'Lumengine']]],
  ['scenenodevisitor',['SceneNodeVisitor',['../class_lumengine_1_1_scene_node_visitor.html',1,'Lumengine']]],
  ['shader',['Shader',['../class_shader.html',1,'']]],
  ['shape',['Shape',['../class_lumengine_1_1_shape.html',1,'Lumengine']]],
  ['signal',['Signal',['../class_lumengine_1_1_signal.html',1,'Lumengine']]]
];


text:
(function (root, factory)
{
    'use strict';

    if (typeof exports === 'object') {
        // CommonJS module
        factory(require('jquery'), require('../pikaday'));
    } else if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery', 'pikaday'], factory);
    } else {
        // Browser globals
        factory(root.jQuery, root.Pikaday);
    }
}(this, function ($, Pikaday)
{
    'use strict';

    $.fn.pikaday = function()
    {
        var args = arguments;

        if (!args || !args.length) {
            args = [{ }];
        }

        return this.each(function()
        {
            var self   = $(this),
                plugin = self.data('pikaday');

            if (!(plugin instanceof Pikaday)) {
                if (typeof args[0] === 'object') {
                    var options = $.extend({}, args[0]);
                    options.field = self[0];
                    self.data('pikaday', new Pikaday(options));
                }
            } else {
                if (typeof args[0] === 'string' && typeof plugin[args[0]] === 'function') {
                    plugin[args[0]].apply(plugin, Array.prototype.slice.call(args,1));
                }
            }
        });
    };

}));


text:
package io.elegie.luchess.pgn.impl.tokens;

import io.elegie.luchess.pgn.api.ParserVisitor;

/**
 * Intended for super classes to let their child classes decide which visitor
 * method to call.
 */
public interface DelegateVisitor {

    /**
     * @param visitor
     *            The visitor to be notified. Child class should select the
     *            appropriate visitor method.
     * @param value
     *            The value to pass to the visitor method.
     */
    void visitToken(ParserVisitor visitor, String value);

}


text:
package com.boztalay.codejam.qualification.problem1;

import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;

public class QualificationProblem1 {

    public static void main(String[] args) {
        String input;
        PrintWriter writer;

        try {
            String inFilePath = args[0];
            byte[] encodedFile = Files.readAllBytes(Paths.get(inFilePath));
            input = new String(encodedFile);
            writer = new PrintWriter(inFilePath.replace(".in", ".out"));
        } catch(Exception e) {
            System.out.println("Whoops, couldn't open the input file!");
            return;
        }

        QualificationProblem1 prob1 = new QualificationProblem1();
        prob1.solve(input, writer);
        writer.close();
    }

    private void solve(String input, PrintWriter writer) {
        TestCase[] testCases = readCases(input);

        for(int i = 0; i < testCases.length; i++) {
            TestCase testCase = testCases[i];

            StringBuilder builder = new StringBuilder();
            builder.append("Case #").append((i + 1)).append(": ");

            int[] firstRow = testCase.firstCardGrid[testCase.firstAnswer];
            int[] secondRow = testCase.secondCardGrid[testCase.secondAnswer];

            int candidateCard = -1;
            outerLoop:
            for(int j = 0; j < firstRow.length; j++) {
                for(int k = 0; k < secondRow.length; k++) {
                    if(firstRow[j] == secondRow[k]) {
                        if(candidateCard > 0) {
                            candidateCard = -2;
                            break outerLoop;
                        }
                        candidateCard = firstRow[j];
                    }
                }
            }

            if(candidateCard == -1) {
                builder.append("Volunteer cheated!");
            } else if(candidateCard == -2) {
                builder.append("Bad magician!");
            } else {
                builder.append(candidateCard);
            }

            writer.println(builder.toString());
        }
    }

    private TestCase[] readCases(String input) {
        String[] inputLines = input.split("\\r?\\n");
        int numCases = Integer.valueOf(inputLines[0]);

        TestCase[] testCases = new TestCase[numCases];

        int fileIndex = 1;
        for(int i = 0; i < numCases; i++) {
            testCases[i] = new TestCase();
            fileIndex = readCaseAndAdvanceIndex(inputLines, testCases[i], fileIndex);
        }

        return testCases;
    }

    private int readCaseAndAdvanceIndex(String[] inputLines, TestCase testCase, int i) {
        testCase.firstAnswer = Integer.valueOf(inputLines[i++]) - 1; //Accommodating for 1-indexed answers

        for(int j = 0; j < 4; j++) {
            String[] cardStrings = inputLines[i++].split(" ");

            for(int k = 0; k < 4; k++) {
                testCase.firstCardGrid[j][k] = Integer.valueOf(cardStrings[k]);
            }
        }

        testCase.secondAnswer = Integer.valueOf(inputLines[i++]) - 1; //Accommodating for 1-indexed answers

        for(int j = 0; j < 4; j++) {
            String[] cardStrings = inputLines[i++].split(" ");

            for(int k = 0; k < 4; k++) {
                testCase.secondCardGrid[j][k] = Integer.valueOf(cardStrings[k]);
            }
        }

        return i;
    }

    private class TestCase {
        public int firstAnswer;
        public int[][] firstCardGrid;
        public int secondAnswer;
        public int[][] secondCardGrid;

        public TestCase() {
            firstCardGrid = new int[4][4];
            secondCardGrid = new int[4][4];
        }

        @Override
        public String toString() {
            String thisString = firstAnswer + "\n";
            for(int[] thing : firstCardGrid) {
                for(int thingy : thing) {
                    thisString += thingy + " ";
                }
                thisString += "\n";
            }

            thisString += secondAnswer + "\n";
            for(int[] thing : secondCardGrid) {
                for(int thingy : thing) {
                    thisString += thingy + " ";
                }
                thisString += "\n";
            }
            return thisString;
        }
    }
}


text:
<?php

namespace SeerUK\RestBundle\Validator\Exception;

use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Validator\ConstraintViolationList;

/**
 * Validation Exception Interface
 */
class ConstraintViolationException extends HttpException
{
    /**
     * @var ConstraintViolationList
     */
    private $constraintViolations;

    /**
     * Prepare error message
     *
     * @param ConstraintViolationList $constraintViolations
     */
    public function __construct(ConstraintViolationList $constraintViolations, \Exception $previous = null)
    {
        parent::__construct(400, sprintf('Constraint violation, %d error(s).', count($constraintViolations)), $previous, array());

        $this->constraintViolations = $constraintViolations;
    }

    /**
     * Get all associated constraint violations
     *
     * @return ConstraintViolationList
     */
    public function getConstraintViolationList()
    {
        return $this->constraintViolations;
    }
}


text:
set(NOSTDINC "")

foreach(file_name include include-fixed)
  execute_process(
    COMMAND ${CMAKE_C_COMPILER} --print-file-name=${file_name}
    OUTPUT_VARIABLE _OUTPUT
    )
  string(REGEX REPLACE "\n" "" _OUTPUT ${_OUTPUT})

  list(APPEND NOSTDINC ${_OUTPUT})
endforeach()

foreach(isystem_include_dir ${NOSTDINC})
  list(APPEND isystem_include_flags -isystem ${isystem_include_dir})
endforeach()

set(CMAKE_REQUIRED_FLAGS -nostartfiles -nostdlib ${isystem_include_flags} -Wl,--unresolved-symbols=ignore-in-object-files)
string(REPLACE ";" " " CMAKE_REQUIRED_FLAGS "${CMAKE_REQUIRED_FLAGS}")


text:
package net.hydromatic.foodmart.data.hsqldb;

/** Foodmart data set in hsqldb format. */
public class FoodmartHsqldb {
  /** URI of the hsqldb database. */
  public static final String URI = "jdbc:hsqldb:res:foodmart";
  public static final String USER = "FOODMART";
  public static final String PASSWORD = "FOODMART";
}

// End FoodmartHsqldb.java


text:
gcontacts
=========

Retrieve a list of users from google contacts


text:
#include "rtllib.h"
#include <linux/etherdevice.h>
#include "rtl819x_TS.h"

static void TsSetupTimeOut(unsigned long data)
{
}

static void TsInactTimeout(unsigned long data)
{
}

static void RxPktPendingTimeout(unsigned long data)
{
	struct rx_ts_record *pRxTs = (struct rx_ts_record *)data;
	struct rtllib_device *ieee = container_of(pRxTs, struct rtllib_device,
						  RxTsRecord[pRxTs->num]);

	struct rx_reorder_entry *pReorderEntry = NULL;

	unsigned long flags = 0;
	u8 index = 0;
	bool bPktInBuf = false;

	spin_lock_irqsave(&(ieee->reorder_spinlock), flags);
	if (pRxTs->RxTimeoutIndicateSeq != 0xffff) {
		while (!list_empty(&pRxTs->RxPendingPktList)) {
			pReorderEntry = (struct rx_reorder_entry *)
					list_entry(pRxTs->RxPendingPktList.prev,
					struct rx_reorder_entry, List);
			if (index == 0)
				pRxTs->RxIndicateSeq = pReorderEntry->SeqNum;

			if (SN_LESS(pReorderEntry->SeqNum, pRxTs->RxIndicateSeq) ||
				SN_EQUAL(pReorderEntry->SeqNum, pRxTs->RxIndicateSeq)) {
				list_del_init(&pReorderEntry->List);

				if (SN_EQUAL(pReorderEntry->SeqNum,
				    pRxTs->RxIndicateSeq))
					pRxTs->RxIndicateSeq =
					      (pRxTs->RxIndicateSeq + 1) % 4096;

				RTLLIB_DEBUG(RTLLIB_DL_REORDER, "%s(): Indicate"
					     " SeqNum: %d\n", __func__,
					     pReorderEntry->SeqNum);
				ieee->stats_IndicateArray[index] =
							 pReorderEntry->prxb;
				index++;

				list_add_tail(&pReorderEntry->List,
					      &ieee->RxReorder_Unused_List);
			} else {
				bPktInBuf = true;
				break;
			}
		}
	}

	if (index > 0) {
		pRxTs->RxTimeoutIndicateSeq = 0xffff;

		if (index > REORDER_WIN_SIZE) {
			RTLLIB_DEBUG(RTLLIB_DL_ERR, "RxReorderIndicatePacket():"
				     " Rx Reorer struct buffer full!!\n");
			spin_unlock_irqrestore(&(ieee->reorder_spinlock),
					       flags);
			return;
		}
		rtllib_indicate_packets(ieee, ieee->stats_IndicateArray, index);
		bPktInBuf = false;
	}

	if (bPktInBuf && (pRxTs->RxTimeoutIndicateSeq == 0xffff)) {
		pRxTs->RxTimeoutIndicateSeq = pRxTs->RxIndicateSeq;
		mod_timer(&pRxTs->RxPktPendingTimer,  jiffies +
			  MSECS(ieee->pHTInfo->RxReorderPendingTime));
	}
	spin_unlock_irqrestore(&(ieee->reorder_spinlock), flags);
}

static void TsAddBaProcess(unsigned long data)
{
	struct tx_ts_record *pTxTs = (struct tx_ts_record *)data;
	u8 num = pTxTs->num;
	struct rtllib_device *ieee = container_of(pTxTs, struct rtllib_device,
				     TxTsRecord[num]);

	TsInitAddBA(ieee, pTxTs, BA_POLICY_IMMEDIATE, false);
	RTLLIB_DEBUG(RTLLIB_DL_BA, "TsAddBaProcess(): ADDBA Req is "
		     "started!!\n");
}

static void ResetTsCommonInfo(struct ts_common_info *pTsCommonInfo)
{
	memset(pTsCommonInfo->Addr, 0, 6);
	memset(&pTsCommonInfo->TSpec, 0, sizeof(union tspec_body));
	memset(&pTsCommonInfo->TClass, 0, sizeof(union qos_tclas)*TCLAS_NUM);
	pTsCommonInfo->TClasProc = 0;
	pTsCommonInfo->TClasNum = 0;
}

static void ResetTxTsEntry(struct tx_ts_record *pTS)
{
	ResetTsCommonInfo(&pTS->TsCommonInfo);
	pTS->TxCurSeq = 0;
	pTS->bAddBaReqInProgress = false;
	pTS->bAddBaReqDelayed = false;
	pTS->bUsingBa = false;
	pTS->bDisable_AddBa = false;
	ResetBaEntry(&pTS->TxAdmittedBARecord);
	ResetBaEntry(&pTS->TxPendingBARecord);
}

static void ResetRxTsEntry(struct rx_ts_record *pTS)
{
	ResetTsCommonInfo(&pTS->TsCommonInfo);
	pTS->RxIndicateSeq = 0xffff;
	pTS->RxTimeoutIndicateSeq = 0xffff;
	ResetBaEntry(&pTS->RxAdmittedBARecord);
}

void TSInitialize(struct rtllib_device *ieee)
{
	struct tx_ts_record *pTxTS  = ieee->TxTsRecord;
	struct rx_ts_record *pRxTS  = ieee->RxTsRecord;
	struct rx_reorder_entry *pRxReorderEntry = ieee->RxReorderEntry;
	u8				count = 0;
	RTLLIB_DEBUG(RTLLIB_DL_TS, "==========>%s()\n", __func__);
	INIT_LIST_HEAD(&ieee->Tx_TS_Admit_List);
	INIT_LIST_HEAD(&ieee->Tx_TS_Pending_List);
	INIT_LIST_HEAD(&ieee->Tx_TS_Unused_List);

	for (count = 0; count < TOTAL_TS_NUM; count++) {
		pTxTS->num = count;
		_setup_timer(&pTxTS->TsCommonInfo.SetupTimer,
			    TsSetupTimeOut,
			    (unsigned long) pTxTS);

		_setup_timer(&pTxTS->TsCommonInfo.InactTimer,
			    TsInactTimeout,
			    (unsigned long) pTxTS);

		_setup_timer(&pTxTS->TsAddBaTimer,
			    TsAddBaProcess,
			    (unsigned long) pTxTS);

		_setup_timer(&pTxTS->TxPendingBARecord.Timer,
			    BaSetupTimeOut,
			    (unsigned long) pTxTS);
		_setup_timer(&pTxTS->TxAdmittedBARecord.Timer,
			    TxBaInactTimeout,
			    (unsigned long) pTxTS);

		ResetTxTsEntry(pTxTS);
		list_add_tail(&pTxTS->TsCommonInfo.List,
				&ieee->Tx_TS_Unused_List);
		pTxTS++;
	}

	INIT_LIST_HEAD(&ieee->Rx_TS_Admit_List);
	INIT_LIST_HEAD(&ieee->Rx_TS_Pending_List);
	INIT_LIST_HEAD(&ieee->Rx_TS_Unused_List);
	for (count = 0; count < TOTAL_TS_NUM; count++) {
		pRxTS->num = count;
		INIT_LIST_HEAD(&pRxTS->RxPendingPktList);

		_setup_timer(&pRxTS->TsCommonInfo.SetupTimer,
			    TsSetupTimeOut,
			    (unsigned long) pRxTS);

		_setup_timer(&pRxTS->TsCommonInfo.InactTimer,
			    TsInactTimeout,
			    (unsigned long) pRxTS);

		_setup_timer(&pRxTS->RxAdmittedBARecord.Timer,
			    RxBaInactTimeout,
			    (unsigned long) pRxTS);

		_setup_timer(&pRxTS->RxPktPendingTimer,
			    RxPktPendingTimeout,
			    (unsigned long) pRxTS);

		ResetRxTsEntry(pRxTS);
		list_add_tail(&pRxTS->TsCommonInfo.List,
			      &ieee->Rx_TS_Unused_List);
		pRxTS++;
	}
	INIT_LIST_HEAD(&ieee->RxReorder_Unused_List);
	for (count = 0; count < REORDER_ENTRY_NUM; count++) {
		list_add_tail(&pRxReorderEntry->List,
			      &ieee->RxReorder_Unused_List);
		if (count == (REORDER_ENTRY_NUM-1))
			break;
		pRxReorderEntry = &ieee->RxReorderEntry[count+1];
	}

}

static void AdmitTS(struct rtllib_device *ieee,
		    struct ts_common_info *pTsCommonInfo, u32 InactTime)
{
	del_timer_sync(&pTsCommonInfo->SetupTimer);
	del_timer_sync(&pTsCommonInfo->InactTimer);

	if (InactTime != 0)
		mod_timer(&pTsCommonInfo->InactTimer, jiffies +
			  MSECS(InactTime));
}

static struct ts_common_info *SearchAdmitTRStream(struct rtllib_device *ieee,
						  u8 *Addr, u8 TID,
						  enum tr_select TxRxSelect)
{
	u8	dir;
	bool	search_dir[4] = {0};
	struct list_head *psearch_list;
	struct ts_common_info *pRet = NULL;
	if (ieee->iw_mode == IW_MODE_MASTER) {
		if (TxRxSelect == TX_DIR) {
			search_dir[DIR_DOWN] = true;
			search_dir[DIR_BI_DIR] = true;
		} else {
			search_dir[DIR_UP] = true;
			search_dir[DIR_BI_DIR] = true;
		}
	} else if (ieee->iw_mode == IW_MODE_ADHOC) {
		if (TxRxSelect == TX_DIR)
			search_dir[DIR_UP] = true;
		else
			search_dir[DIR_DOWN] = true;
	} else {
		if (TxRxSelect == TX_DIR) {
			search_dir[DIR_UP] = true;
			search_dir[DIR_BI_DIR] = true;
			search_dir[DIR_DIRECT] = true;
		} else {
			search_dir[DIR_DOWN] = true;
			search_dir[DIR_BI_DIR] = true;
			search_dir[DIR_DIRECT] = true;
		}
	}

	if (TxRxSelect == TX_DIR)
		psearch_list = &ieee->Tx_TS_Admit_List;
	else
		psearch_list = &ieee->Rx_TS_Admit_List;

	for (dir = 0; dir <= DIR_BI_DIR; dir++) {
		if (search_dir[dir] == false)
			continue;
		list_for_each_entry(pRet, psearch_list, List) {
			if (memcmp(pRet->Addr, Addr, 6) == 0)
				if (pRet->TSpec.f.TSInfo.field.ucTSID == TID)
					if (pRet->TSpec.f.TSInfo.field.ucDirection == dir)
						break;

		}
		if (&pRet->List  != psearch_list)
			break;
	}

	if (pRet && &pRet->List  != psearch_list)
		return pRet ;
	else
		return NULL;
}

static void MakeTSEntry(struct ts_common_info *pTsCommonInfo, u8 *Addr,
			union tspec_body *pTSPEC, union qos_tclas *pTCLAS,
			u8 TCLAS_Num, u8 TCLAS_Proc)
{
	u8	count;

	if (pTsCommonInfo == NULL)
		return;

	memcpy(pTsCommonInfo->Addr, Addr, 6);

	if (pTSPEC != NULL)
		memcpy((u8 *)(&(pTsCommonInfo->TSpec)), (u8 *)pTSPEC,
			sizeof(union tspec_body));

	for (count = 0; count < TCLAS_Num; count++)
		memcpy((u8 *)(&(pTsCommonInfo->TClass[count])),
		       (u8 *)pTCLAS, sizeof(union qos_tclas));

	pTsCommonInfo->TClasProc = TCLAS_Proc;
	pTsCommonInfo->TClasNum = TCLAS_Num;
}

bool GetTs(struct rtllib_device *ieee, struct ts_common_info **ppTS,
	   u8 *Addr, u8 TID, enum tr_select TxRxSelect, bool bAddNewTs)
{
	u8	UP = 0;
	if (is_broadcast_ether_addr(Addr) || is_multicast_ether_addr(Addr)) {
		RTLLIB_DEBUG(RTLLIB_DL_ERR, "ERR! get TS for Broadcast or "
			     "Multicast\n");
		return false;
	}
	if (ieee->current_network.qos_data.supported == 0) {
		UP = 0;
	} else {
		if (!IsACValid(TID)) {
			RTLLIB_DEBUG(RTLLIB_DL_ERR, "ERR! in %s(), TID(%d) is "
				     "not valid\n", __func__, TID);
			return false;
		}

		switch (TID) {
		case 0:
		case 3:
			UP = 0;
			break;
		case 1:
		case 2:
			UP = 2;
			break;
		case 4:
		case 5:
			UP = 5;
			break;
		case 6:
		case 7:
			UP = 7;
			break;
		}
	}

	*ppTS = SearchAdmitTRStream(ieee, Addr, UP, TxRxSelect);
	if (*ppTS != NULL) {
		return true;
	} else {
		if (bAddNewTs == false) {
			RTLLIB_DEBUG(RTLLIB_DL_TS, "add new TS failed"
				     "(tid:%d)\n", UP);
			return false;
		} else {
			union tspec_body TSpec;
			union qos_tsinfo *pTSInfo = &TSpec.f.TSInfo;
			struct list_head *pUnusedList =
				(TxRxSelect == TX_DIR) ?
				(&ieee->Tx_TS_Unused_List) :
				(&ieee->Rx_TS_Unused_List);

			struct list_head *pAddmitList =
				(TxRxSelect == TX_DIR) ?
				(&ieee->Tx_TS_Admit_List) :
				(&ieee->Rx_TS_Admit_List);

			enum direction_value Dir =
				 (ieee->iw_mode == IW_MODE_MASTER) ?
				 ((TxRxSelect == TX_DIR) ? DIR_DOWN : DIR_UP) :
				 ((TxRxSelect == TX_DIR) ? DIR_UP : DIR_DOWN);
			RTLLIB_DEBUG(RTLLIB_DL_TS, "to add Ts\n");
			if (!list_empty(pUnusedList)) {
				(*ppTS) = list_entry(pUnusedList->next,
					  struct ts_common_info, List);
				list_del_init(&(*ppTS)->List);
				if (TxRxSelect == TX_DIR) {
					struct tx_ts_record *tmp =
						container_of(*ppTS,
						struct tx_ts_record,
						TsCommonInfo);
					ResetTxTsEntry(tmp);
				} else {
					struct rx_ts_record *tmp =
						 container_of(*ppTS,
						 struct rx_ts_record,
						 TsCommonInfo);
					ResetRxTsEntry(tmp);
				}

				RTLLIB_DEBUG(RTLLIB_DL_TS, "to init current TS"
					     ", UP:%d, Dir:%d, addr: %pM"
					     " ppTs=%p\n", UP, Dir,
					      Addr, *ppTS);
				pTSInfo->field.ucTrafficType = 0;
				pTSInfo->field.ucTSID = UP;
				pTSInfo->field.ucDirection = Dir;
				pTSInfo->field.ucAccessPolicy = 1;
				pTSInfo->field.ucAggregation = 0;
				pTSInfo->field.ucPSB = 0;
				pTSInfo->field.ucUP = UP;
				pTSInfo->field.ucTSInfoAckPolicy = 0;
				pTSInfo->field.ucSchedule = 0;

				MakeTSEntry(*ppTS, Addr, &TSpec, NULL, 0, 0);
				AdmitTS(ieee, *ppTS, 0);
				list_add_tail(&((*ppTS)->List), pAddmitList);

				return true;
			} else {
				RTLLIB_DEBUG(RTLLIB_DL_ERR, "ERR!!in function "
					     "%s() There is not enough dir=%d"
					     "(0=up down=1) TS record to be "
					     "used!!", __func__, Dir);
				return false;
			}
		}
	}
}

static void RemoveTsEntry(struct rtllib_device *ieee, struct ts_common_info *pTs,
			  enum tr_select TxRxSelect)
{
	del_timer_sync(&pTs->SetupTimer);
	del_timer_sync(&pTs->InactTimer);
	TsInitDelBA(ieee, pTs, TxRxSelect);

	if (TxRxSelect == RX_DIR) {
		struct rx_reorder_entry *pRxReorderEntry;
		struct rx_ts_record *pRxTS = (struct rx_ts_record *)pTs;

		if (timer_pending(&pRxTS->RxPktPendingTimer))
			del_timer_sync(&pRxTS->RxPktPendingTimer);

		while (!list_empty(&pRxTS->RxPendingPktList)) {
			pRxReorderEntry = (struct rx_reorder_entry *)
					list_entry(pRxTS->RxPendingPktList.prev,
					struct rx_reorder_entry, List);
			RTLLIB_DEBUG(RTLLIB_DL_REORDER, "%s(): Delete SeqNum "
				     "%d!\n", __func__,
				     pRxReorderEntry->SeqNum);
			list_del_init(&pRxReorderEntry->List);
			{
				int i = 0;
				struct rtllib_rxb *prxb = pRxReorderEntry->prxb;
				if (unlikely(!prxb))
					return;
				for (i = 0; i < prxb->nr_subframes; i++)
					dev_kfree_skb(prxb->subframes[i]);
				kfree(prxb);
				prxb = NULL;
			}
			list_add_tail(&pRxReorderEntry->List,
				      &ieee->RxReorder_Unused_List);
		}
	} else {
		struct tx_ts_record *pTxTS = (struct tx_ts_record *)pTs;
		del_timer_sync(&pTxTS->TsAddBaTimer);
	}
}

void RemovePeerTS(struct rtllib_device *ieee, u8 *Addr)
{
	struct ts_common_info *pTS, *pTmpTS;
	printk(KERN_INFO "===========>RemovePeerTS, %pM\n", Addr);

	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Tx_TS_Pending_List, List) {
		if (memcmp(pTS->Addr, Addr, 6) == 0) {
			RemoveTsEntry(ieee, pTS, TX_DIR);
			list_del_init(&pTS->List);
			list_add_tail(&pTS->List, &ieee->Tx_TS_Unused_List);
		}
	}

	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Tx_TS_Admit_List, List) {
		if (memcmp(pTS->Addr, Addr, 6) == 0) {
			printk(KERN_INFO "====>remove Tx_TS_admin_list\n");
			RemoveTsEntry(ieee, pTS, TX_DIR);
			list_del_init(&pTS->List);
			list_add_tail(&pTS->List, &ieee->Tx_TS_Unused_List);
		}
	}

	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Rx_TS_Pending_List, List) {
		if (memcmp(pTS->Addr, Addr, 6) == 0) {
			RemoveTsEntry(ieee, pTS, RX_DIR);
			list_del_init(&pTS->List);
			list_add_tail(&pTS->List, &ieee->Rx_TS_Unused_List);
		}
	}

	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Rx_TS_Admit_List, List) {
		if (memcmp(pTS->Addr, Addr, 6) == 0) {
			RemoveTsEntry(ieee, pTS, RX_DIR);
			list_del_init(&pTS->List);
			list_add_tail(&pTS->List, &ieee->Rx_TS_Unused_List);
		}
	}
}
EXPORT_SYMBOL(RemovePeerTS);

void RemoveAllTS(struct rtllib_device *ieee)
{
	struct ts_common_info *pTS, *pTmpTS;

	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Tx_TS_Pending_List, List) {
		RemoveTsEntry(ieee, pTS, TX_DIR);
		list_del_init(&pTS->List);
		list_add_tail(&pTS->List, &ieee->Tx_TS_Unused_List);
	}

	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Tx_TS_Admit_List, List) {
		RemoveTsEntry(ieee, pTS, TX_DIR);
		list_del_init(&pTS->List);
		list_add_tail(&pTS->List, &ieee->Tx_TS_Unused_List);
	}

	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Rx_TS_Pending_List, List) {
		RemoveTsEntry(ieee, pTS, RX_DIR);
		list_del_init(&pTS->List);
		list_add_tail(&pTS->List, &ieee->Rx_TS_Unused_List);
	}

	list_for_each_entry_safe(pTS, pTmpTS, &ieee->Rx_TS_Admit_List, List) {
		RemoveTsEntry(ieee, pTS, RX_DIR);
		list_del_init(&pTS->List);
		list_add_tail(&pTS->List, &ieee->Rx_TS_Unused_List);
	}
}

void TsStartAddBaProcess(struct rtllib_device *ieee, struct tx_ts_record *pTxTS)
{
	if (pTxTS->bAddBaReqInProgress == false) {
		pTxTS->bAddBaReqInProgress = true;

		if (pTxTS->bAddBaReqDelayed) {
			RTLLIB_DEBUG(RTLLIB_DL_BA, "TsStartAddBaProcess(): "
				     "Delayed Start ADDBA after 60 sec!!\n");
			mod_timer(&pTxTS->TsAddBaTimer, jiffies +
				  MSECS(TS_ADDBA_DELAY));
		} else {
			RTLLIB_DEBUG(RTLLIB_DL_BA, "TsStartAddBaProcess(): "
				     "Immediately Start ADDBA now!!\n");
			mod_timer(&pTxTS->TsAddBaTimer, jiffies+10);
		}
	} else
		RTLLIB_DEBUG(RTLLIB_DL_BA, "%s()==>BA timer is already added\n",
			     __func__);
}


text:
import supertest from 'supertest';
import {expect} from 'chai';
import _ from 'lodash';

import App from '../src/app';

describe('Movies Api pagination', () => {
  let server;

  before ((done) => {
    server = App.listen('3001', (err, result) => {
      done(err);
    });
  });

  after(() => {
    server.close();
  });

  it('Should return 10 results on query', (done) => {
    supertest(App)
      .get('/api/movies')
      .expect('Content-Type', /json/)
      .expect(200, (err, res) => {
        expect(res.body.movies.length).to.equal(10);

        done();
      });
  });

  it('Should have a metea attribute with pagination data', (done) => {
    supertest(App)
      .get('/api/movies')
      .expect('Content-Type', /json/)
      .expect(200, (err, res) => {
        expect(res.body.meta).to.exist;
        expect(res.body.meta).to.be.an('object');

        done();
      });
  });

  it('Should use defaults if no query params were provided', (done) => {
    supertest(App)
      .get('/api/movies')
      .expect('Content-Type', /json/)
      .expect(200, (err, res) => {
        expect(res.body.meta.page).to.equal(1);
        expect(res.body.meta.limit).to.equal(10);

        done();
      });
  });

  it('Should be able to limit queries with limit param', (done) => {
    supertest(App)
      .get('/api/movies?limit=2')
      .expect('Content-Type', /json/)
      .expect(200, (err, res) => {
        expect(res.body.movies.length).to.equal(2);

        done();
      });
  });

  it('Should be able to specify an offset for pagination', (done) => {
    supertest(App)
      .get('/api/movies')
      .query({ limit: 2 })
      .expect('Content-Type', /json/)
      .expect(200, (err, res) => {
        expect(res.body.movies.length).to.equal(2);

        done();
      });
  });

  it('Should be able to paginate with offset', (done) => {
    supertest(App)
      .get('/api/movies')
      .query({ limit: 2, page: 2 })
      .expect('Content-Type', /json/)
      .expect(200, (err, res) => {
        expect(res.body.meta.page).to.equal(2);
        expect(res.body.movies.length).to.equal(2);

        done();
      });
  });

});


text:
ufront
======

[![Build Status](https://travis-ci.org/ufront/ufront.svg?branch=master)](https://travis-ci.org/ufront/ufront) [![Join the chat at https://gitter.im/ufront/ufront](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/ufront/ufront?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Ufront is a client/server MVC web framework for Haxe.
It allows you to share models, views and controllers between both server-side and client-side code.
Client side, your app will run as a fast single-page-app.
But everything can still work server-side - which makes for fast first page loads, great SEO, and a good fallback for old browsers.

Platform Support
----------------

* __Neko__ (Server side)
* __PHP__ (Server side)
* __NodeJS__ (Server side, experimental)
* __JS__ (Client side)

It would be possible to also support Python, Java, C# and C++ with a little work.

Installing
----------

Installing from haxelib:

```bash
haxelib install ufront-mvc
haxelib install ufront-tool
sudo haxelib run ufront-tool --setup
```

Using the latest git version:

```bash
haxelib git ufront-mvc https://github.com/ufront/ufront-mvc
# Similar for other libs
```

To update that git repository to a newer version:

```bash
haxelib update ufront-mvc
```

Getting started
---------------

A "hello world" can be found in the [ufront/hello](https://github.com/ufront/hello) repo to give you an example of how to get started.
This example includes builds for Neko, PHP and NodeJS in `server.hxml`, and for Client JS in `client.hxml`.

You can also visit the [ufront-nodejs-guide](https://github.com/kevinresol/ufront-nodejs-guide) for a more comprensive guide.

Repos
-----

Core:

 - [ufront](https://github.com/ufront/ufront) - This is not a library itself but just to hold some codes for generating the documentations
 - [ufront-mvc](https://github.com/ufront/ufront-mvc) - The MVC framework. Provides routing, controllers, views, APIs, remoting, dependency injection and more.

Plugins and other optional libraries:

 - [ufront-tool](https://github.com/ufront/ufront-tool) - The helper tool for ufront.
 - [ufront-orm](https://github.com/ufront/ufront-orm) - An ORM that makes it easy to have models with validation, serialization, automatic relationships and more.
 - [ufront-easyauth](https://github.com/ufront/ufront-easyauth) - An auth system that gives you users, groups and permissions. Fairly simplistic but flexible. Easy to replace if you have different needs.
 - [ufront-ufadmin](https://github.com/ufront/ufront-ufadmin) - An admin area for your web-app.
 - [ufront-uftasks](https://github.com/ufront/ufront-uftasks) - Easy command line tasks that integrate with your models and APIs.
 - [ufront-mail](https://github.com/ufront/ufront-mail) - Easily send emails with Ufront.

Feel free to contribute!


text:
package org.fiteagle.interactors.sfa.renewSlice;

import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.TimeZone;

import javax.xml.bind.JAXBException;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import org.fiteagle.core.ResourceAdapterManager;
import org.fiteagle.core.aaa.KeyStoreManagement;
import org.fiteagle.core.groupmanagement.GroupDBManager;
import org.fiteagle.core.util.URN;
import org.fiteagle.interactors.sfa.common.AMResult;
import org.fiteagle.interactors.sfa.common.ListCredentials;
import org.fiteagle.interactors.sfa.common.SFAv3RequestProcessor;
import org.fiteagle.interactors.sfa.getSelfCredential.jaxbClasses.Credential;
import org.fiteagle.interactors.sfa.getSelfCredential.jaxbClasses.SignedCredential;
import org.fiteagle.interactors.sfa.register.RegisterRequestProcessor;
import org.fiteagle.interactors.sfa.util.CredentialFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RenewSliceRequestProcessor extends SFAv3RequestProcessor {
	Logger log = LoggerFactory.getLogger(getClass());

	private KeyStoreManagement keyStoreManagement;
	private GroupDBManager groupDBManager;

	public RenewSliceRequestProcessor(KeyStoreManagement keystoreInstance,
			GroupDBManager groupDBInstance) {
		setKeyStoreManagement(keystoreInstance);
		setGroupDBManager(groupDBInstance);

	}

	@Override
	public AMResult processRequest(ListCredentials credentials,
			Object... specificArgs) {
		// TODO Auto-generated method stub
		return null;
	}

	public HashMap<String, Object> renew(HashMap<String, Object> parameters) {
		String dateTimeString = (String) parameters.get("expiration");
		Date dateTime = getDateFromString(dateTimeString);

		String credentialsString = (String) parameters.get("credential");

		RegisterRequestProcessor registerReqProcessor = new RegisterRequestProcessor(getKeyStoreManagement(), getGroupDBManager());

		SignedCredential credentials = null;
		try {
			credentials = registerReqProcessor.buildCredential(credentialsString);
		} catch (JAXBException e) {
			log.error(e.getMessage(),e);
		}
		System.out.println(credentials);
		System.out.println(dateTime);

		String sliceUrnStr = credentials.getCredential().getTargetURN();

		URN sliceUrn = new URN(sliceUrnStr);

//		---------------------------------------------------------
		X509Certificate userCert = getUserCertificate();
		URN target = new URN(sliceUrnStr);
		Credential credential = null;
		try{
			CredentialFactory.setGroupDBManager(GroupDBManager.getInstance());
			CredentialFactory.setKeystoreManagement(KeyStoreManagement.getInstance());
			 credential = CredentialFactory.newCredential(userCert,	target);
		}catch(RuntimeException e){
			return null;
		}

//		TimeZone utc = TimeZone.getTimeZone("Etc/UTC");
		GregorianCalendar c = new GregorianCalendar();
		c.setTimeInMillis(dateTime.getTime());
//		c.setTime(dateTime);
		XMLGregorianCalendar valueGreg=null;

		try {
			valueGreg = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
		} catch (DatatypeConfigurationException e) {
			e.printStackTrace();
		}

		credential.setExpires(valueGreg);
		String signedCredential = CredentialFactory.signCredential(credential);

//		----------------------------------------------------------

		HashMap<String, Object> returnMap =  new HashMap<String, Object>();
    	returnMap.put("code", new Integer(0));
    	returnMap.put("value", signedCredential);
//    	returnMap.put("value", "");
    	returnMap.put("output", "");
    	return returnMap;

	}

	public Date getDateFromString(String dateTimeString) {
//		SimpleDateFormat rfc3339 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
		SimpleDateFormat rfc3339 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
		rfc3339.setTimeZone(TimeZone.getTimeZone("UTC"));
		try {
			return  rfc3339.parse(dateTimeString);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public KeyStoreManagement getKeyStoreManagement() {
		return keyStoreManagement;
	}

	public void setKeyStoreManagement(KeyStoreManagement keyStoreManagement) {
		this.keyStoreManagement = keyStoreManagement;
	}

	public GroupDBManager getGroupDBManager() {
		return groupDBManager;
	}

	public void setGroupDBManager(GroupDBManager groupDBManager) {
		this.groupDBManager = groupDBManager;
	}

}