text:
using namespace seqan;
using namespace std;

// empty files & LOCAL_ALIGNMENT_MODE.
SEQAN_DEFINE_TEST(test_GCluster_systemTest_emptyFiles_LAMode)
{
	const char * inDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/unmutable/empty.fasta";
	const char * outClustDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/clusteredDatabase_empty_LocalAlignmentMode.fasta";
	const char * outClustDataBaseReferencePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/unmutable/clusteredDatabase_empty_reference.fasta";
	const char * outMasterPath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/master_empty_LocalAlignmentMode.fasta";
	const char * outMasterReferencePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/unmutable/master_empty_reference.fasta";
	string scoreMode = "LOCAL_ALIGNMENT_MODE";

	String<PerformanceSample> performance;
	DnaString sequenceFormatExample;
	int res = GCluster(performance, inDataBasePath, outClustDataBasePath, outMasterPath, sequenceFormatExample, 4, 0.5, scoreMode);

	SEQAN_ASSERT_EQ(res,0);

	FILE * pFile1;
	FILE * pFile2;
	pFile1 = fopen (outClustDataBasePath , "r");
	pFile2 = fopen (outClustDataBaseReferencePath , "r");
	SEQAN_ASSERT_EQ(compareFiles(pFile1,pFile2),0);

	pFile1 = fopen (outMasterPath , "r");
	pFile2 = fopen (outMasterReferencePath , "r");
	SEQAN_ASSERT_EQ(compareFiles(pFile1,pFile2),0);
}

// empty files & COMMON_QGRAM_MODE.
SEQAN_DEFINE_TEST(test_GCluster_systemTest_emptyFiles_CQMode)
{
	const char * inDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/unmutable/empty.fasta";
	const char * outClustDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/clusteredDatabase_empty.fasta";
	const char * outClustDataBaseReferencePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/unmutable/clusteredDatabase_empty_reference.fasta";
	const char * outMasterPath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/master_empty.fasta";
	const char * outMasterReferencePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/unmutable/master_empty_reference.fasta";
	string scoreMode = "COMMON_QGRAM_MODE";

	String<PerformanceSample> performance;
	DnaString sequenceFormatExample;
	int res = GCluster(performance, inDataBasePath, outClustDataBasePath, outMasterPath, sequenceFormatExample, 800, 0.5, scoreMode);

	SEQAN_ASSERT_EQ(res,0);

	FILE * pFile1;
	FILE * pFile2;
	pFile1 = fopen (outClustDataBasePath , "r");
	pFile2 = fopen (outClustDataBaseReferencePath , "r");
	SEQAN_ASSERT_EQ(compareFiles(pFile1,pFile2),0);

	pFile1 = fopen (outMasterPath , "r");
	pFile2 = fopen (outMasterReferencePath , "r");
	SEQAN_ASSERT_EQ(compareFiles(pFile1,pFile2),0);
}

// toy files & LOCAL_ALIGNMENT_MODE.
SEQAN_DEFINE_TEST(test_GCluster_systemTest_toyFiles_LAMode)
{

	const char * inDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/unmutable/toyDatabase.fasta";
	const char * outClustDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/clusteredDatabase_toy.fasta";
	const char * outMasterPath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/master_toy.fasta";
	string scoreMode = "LOCAL_ALIGNMENT_MODE";

	String<PerformanceSample> performance;
	DnaString sequenceFormatExample;
	int res = GCluster(performance, inDataBasePath, outClustDataBasePath, outMasterPath, sequenceFormatExample, 4, 0.5, scoreMode);
	SEQAN_ASSERT_EQ(res,0);
}

// toy files & COMMON_QGRAM_MODE.
SEQAN_DEFINE_TEST(test_GCluster_systemTest_toyFiles_CQMode)
{

	const char * inDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/unmutable/toyDatabase.fasta";
	const char * outClustDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/clusteredDatabase_toy.fasta";
	const char * outMasterPath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/master_toy.fasta";
	string scoreMode = "COMMON_QGRAM_MODE";

	String<PerformanceSample> performance;
	DnaString sequenceFormatExample;
	int res = GCluster(performance, inDataBasePath, outClustDataBasePath, outMasterPath, sequenceFormatExample, 200, 0.5, scoreMode);
	SEQAN_ASSERT_EQ(res,0);
}

// rfam_short files & LOCAL_ALIGNMENT_MODE.
SEQAN_DEFINE_TEST(test_GCluster_systemTest_rfamFiles_LAMode)
{
	const char * inDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/unmutable/rfam.10K.fasta";
	const char * outClustDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/clusteredDatabase_rfam.fasta";
	const char * outMasterPath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/master_rfam.fasta";
	string scoreMode = "LOCAL_ALIGNMENT_MODE";

	String<PerformanceSample> performance;
	Rna5String sequenceFormatExample;
	int res = GCluster(performance, inDataBasePath, outClustDataBasePath, outMasterPath, sequenceFormatExample, 40, 0.5, scoreMode);
	SEQAN_ASSERT_EQ(res,0);
}

// rfam_short files & GLOBAL_ALIGNMENT_MODE.
SEQAN_DEFINE_TEST(test_GCluster_systemTest_rfamFiles_GAMode)
{
	const char * inDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/unmutable/rfam.10K.fasta";
	const char * outClustDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/clusteredDatabase_rfam.fasta";
	const char * outMasterPath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/master_rfam.fasta";
	string scoreMode = "GLOBAL_ALIGNMENT_MODE";

	String<PerformanceSample> performance;
	Rna5String sequenceFormatExample;
	int res = GCluster(performance, inDataBasePath, outClustDataBasePath, outMasterPath, sequenceFormatExample, 40, 0.5, scoreMode);
	SEQAN_ASSERT_EQ(res,0);
}

// rfam_short files & COMMON_QGRAM_MODE.
SEQAN_DEFINE_TEST(test_GCluster_systemTest_rfamFiles_CQMode)
{
	const char * inDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/unmutable/rfam.10K.fasta";
	const char * outClustDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/clusteredDatabase_rfam.fasta";
	const char * outMasterPath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/master_rfam.fasta";
	string scoreMode = "COMMON_QGRAM_MODE";

	String<PerformanceSample> performance;
	Rna5String sequenceFormatExample;
	int res = GCluster(performance, inDataBasePath, outClustDataBasePath, outMasterPath, sequenceFormatExample, 100, 0.5, scoreMode);
	SEQAN_ASSERT_EQ(res,0);
}

// rfam_short files & LOCAL_ALIGNMENT_MODE.
SEQAN_DEFINE_TEST(test_GCluster_systemTest_pfamFiles_LAMode)
{
	const char * inDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/unmutable/pfam.10K.fasta";
	const char * outClustDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/clusteredDatabase_pfam.fasta";
	const char * outMasterPath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/master_pfam.fasta";
	string scoreMode = "LOCAL_ALIGNMENT_MODE";

	String<PerformanceSample> performance;
	Peptide sequenceFormatExample;
	int res = GCluster(performance, inDataBasePath, outClustDataBasePath, outMasterPath, sequenceFormatExample, 10, 0.5, scoreMode);
	SEQAN_ASSERT_EQ(res,0);
}

// rfam_short files & GLOBAL_ALIGNMENT_MODE.
SEQAN_DEFINE_TEST(test_GCluster_systemTest_pfamFiles_GAMode)
{
	const char * inDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/unmutable/pfam.10K.fasta";
	const char * outClustDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/clusteredDatabase_pfam.fasta";
	const char * outMasterPath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/master_pfam.fasta";
	string scoreMode = "GLOBAL_ALIGNMENT_MODE";

	String<PerformanceSample> performance;
	Peptide sequenceFormatExample;
	int res = GCluster(performance, inDataBasePath, outClustDataBasePath, outMasterPath, sequenceFormatExample, 10, 0.5, scoreMode);
	SEQAN_ASSERT_EQ(res,0);
}

// rfam_short files & COMMON_QGRAM_MODE.
SEQAN_DEFINE_TEST(test_GCluster_systemTest_pfamFiles_CQMode)
{
	const char * inDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/unmutable/pfam.10K.fasta";
	const char * outClustDataBasePath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/clusteredDatabase_pfam.fasta";
	const char * outMasterPath = "/home/development/seqan-trunk/sandbox/PMSB_group6/tests/autoTestData/mutable/master_pfam.fasta";
	string scoreMode = "COMMON_QGRAM_MODE";

	String<PerformanceSample> performance;
	Peptide sequenceFormatExample;
	int res = GCluster(performance, inDataBasePath, outClustDataBasePath, outMasterPath, sequenceFormatExample, 200, 0.5, scoreMode);
	SEQAN_ASSERT_EQ(res,0);
}

#endif  // SANDBOX_PMSB_GROUP6_TEST_CLUSTER_SYSTEMTEST_H_


text: hello template

redpajama_set_name: RedPajamaGithub


text:
package network

sealed trait Message
case class Join(name: String) extends Message
case class JoinResponse(uid: Uid) extends Message
case object YourTurn extends Message
case class GameCommand(cmd: Command[Any]) extends Message

trait Serial[A] {
  def read(is: DataInputStream): A
  def write(os: DataOutputStream, a: A)
}

object Serial {
  implicit val serialCommand = new Serial[Command[Any]] {
    def read(is: DataInputStream): Command[Any] = {
      val ev = implicitly[Serial[Dir]]
      is.readByte() match {
        case 1 => Spawn(is.readInt(), is.readInt())
        case 2 => Move(ev.read(is))
        case 3 => Quit(is.readInt())
      }
    }
    def write(os: DataOutputStream, cmd: Command[Any])(implicit ev: Serial[Dir]) {
      val ev = implicitly[Serial[Dir]]
      cmd match {
        case Spawn(x, y) =>
          os.writeByte(1)
          os.writeInt(x)
          os.writeInt(y)
        case Move(dir) =>
          os.writeByte(2)
          ev.write(os, dir)
        case Quit(uid) =>
          os.writeByte(3)
          os.writeInt(uid)
      }
    }
  }
  implicit val serialDir = new Serial[Dir] {
    def read(os: DataInputStream) =
      os.readByte() match {
        case 1 => Up
        case 2 => Down
        case 3 => Left
        case 4 => Right
      }
    def write(os: DataOutputStream, dir: Dir) {
      os.writeByte(dir match {
        case Up => 1
        case Down => 2
        case Left => 3
        case Right => 4
      })
    }
  }
}


text:
package noop.grammar;

import org.scalatest.matchers.ShouldMatchers;
import org.scalatest.Spec;

/**
 * @author alexeagle@google.com (Alex Eagle)
 * @author tocman@gmail.com (Jeremie Lenfant-Engelmann)
 */
class PropertiesSpec extends Spec with ShouldMatchers {

  val parser = new Parser();

  describe("parser") {

    it("should parse a single property declaration") {
      val source = """
        class Foo() {
          Int a = 4;
          Int i;
        }
      """;

      parser.parseFile(source).toStringTree() should equal ("(CLASS Foo (VAR Int (= a 4)) (VAR Int i))");
    }
  }
}


text:
package cz.geek.util;

import java.util.Arrays;
import java.util.List;

public abstract class ListUtils {

	/**
	 * Delete items from given list at given indexes
	 * @param list list
	 * @param indexes indexes to remove (may be null)
     * @throws UnsupportedOperationException if the <tt>remove</tt> method is not supported by this list.
	 * @throws IndexOutOfBoundsException if one of indexes is out of range < 0 || index >= size()).
	 */
	public static void delete(List<?> list, Integer[] indexes) throws IndexOutOfBoundsException, UnsupportedOperationException {
		if (indexes == null)
			return;
		if (indexes.length > 1)
			Arrays.sort(indexes);
		for (int i=0; i<indexes.length; i++)
			list.remove(indexes[i]-i);
	}
}


text:
import { SafeString } from "handlebars/runtime";
import { values } from "../utils/statuses";

export default function(statistic) {
  const fill = values
    .map((status) => {
      const count = !statistic || typeof statistic[status] === "undefined" ? 0 : statistic[status];
      return count === 0 ? "" : `<span class="label label_status_${status}">${count}</span> `;
    })
    .join("");
  return new SafeString(`${fill}`);
}


text:
package ru.job4j.iterator;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class MatrixIterator implements Iterator {

    private final int[][] values;
    private int index = 0;
    private int outer = 0;
    private int inner = 0;

    public MatrixIterator(final int[][] values) {
        this.values = values;
    }

    public boolean hasNext() {
        return outer < values.length;
    }

    public Object next() throws NoSuchElementException {
        if (!hasNext()) {
            throw new NoSuchElementException();
        } else {
            int item = values[outer][inner];
            inner++;
            if (inner == values[outer].length) {
                inner = 0;
                outer++;
            }
            index++;
            return item;
        }
    }
}


text:
FROM jekyll/jekyll:pages

COPY Gemfile* /srv/jekyll/

WORKDIR /srv/jekyll

RUN apk update && \
	apk add ruby-dev ruby-bundler nodejs gcc make curl build-base libc-dev libffi-dev zlib-dev libxml2-dev libgcrypt-dev libxslt-dev python

# RUN bundle clean
# RUN bundle config build.nokogiri --use-system-libraries
# RUN bundle install
# RUN bundle exec jekyll liveserve
# RUN bundle exec jekyll serve

EXPOSE 4000


text:
using System;
using AuthorizeNet.Api.Contracts.V1;
using AuthorizeNet.Api.Controllers;
using AuthorizeNet.Api.Controllers.Bases;

namespace AuthorizeNET.CustomerProfiles
{
    class CreateCustomerPaymentProfile
    {
        public static void Run(string apiLoginId, string apiTransactionKey)
        {
            Console.WriteLine("CreateCustomerPaymentProfile Sample");
            ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = AuthorizeNet.Environment.SANDBOX;
            ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
            {
                name            = apiLoginId,
                ItemElementName = ItemChoiceType.transactionKey,
                Item            = apiTransactionKey,
            };

            var bankAccount = new bankAccountType
            {
                accountNumber = "01245524321",
                routingNumber = "000000204",
                accountType = bankAccountTypeEnum.checking,
                echeckType = echeckTypeEnum.WEB,
                nameOnAccount = "test",
                bankName = "Bank Of America"
            };

            paymentType echeck = new paymentType {Item = bankAccount};

            customerPaymentProfileType echeckPaymentProfile = new customerPaymentProfileType();
            echeckPaymentProfile.payment = echeck;

            var request = new createCustomerPaymentProfileRequest
            {
                customerProfileId = "10000",
                paymentProfile = echeckPaymentProfile,
                validationMode = validationModeEnum.none
            };

            //Prepare Request
            var controller = new createCustomerPaymentProfileController(request);
            controller.Execute();

             //Send Request to EndPoint
            createCustomerPaymentProfileResponse response = controller.GetApiResponse();
            if (response != null && response.messages.resultCode == messageTypeEnum.Ok)
            {
                if (response.messages.message != null)
                {
                    Console.WriteLine("Success, createCustomerPaymentProfileID : " + response.customerPaymentProfileId);
                }
            }
            else
            {
                if (response != null)
                    Console.WriteLine("Error: " + response.messages.message[0].code + "  " + response.messages.message[0].text);
            }

        }
    }
}


text:
package com.commonsware.android.abf.uiautomator;

import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiScrollable;
import android.support.test.uiautomator.UiSelector;
import junit.framework.Assert;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(AndroidJUnit4.class)
public class ListTests {
  private static final String[] items= { "lorem", "ipsum", "dolor",
      "sit", "amet", "consectetuer", "adipiscing", "elit", "morbi",
      "vel", "ligula", "vitae", "arcu", "aliquet", "mollis", "etiam",
      "vel", "erat", "placerat", "ante", "porttitor", "sodales",
      "pellentesque", "augue", "purus" };
  private UiDevice device;

  @Before
  public void setUp() throws UiObjectNotFoundException {
    device=UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
    openActivity();
  }

  @After
  public void tearDown() {
    device.pressBack();
    device.pressBack();
  }

  @Test
  public void testContents() throws UiObjectNotFoundException {
    UiScrollable words=
        new UiScrollable(
                         new UiSelector().className("android.widget.ListView"));

    words.setAsVerticalList();

    for (String s : items) {
      Assert.assertNotNull("Could not find " + s,
          words.getChildByText(new UiSelector().className("android.widget.TextView"),
              s));
    }
  }

  @Test
  public void testAdd() throws UiObjectNotFoundException {
    UiObject add=device.findObject(new UiSelector().text("Word"));

    add.setText("snicklefritz");
    device.pressEnter();

    UiScrollable words=
        new UiScrollable(
                         new UiSelector().className("android.widget.ListView"));

    words.setAsVerticalList();

    Assert.assertNotNull("Could not find snicklefritz",
        words.getChildByText(new UiSelector().className("android.widget.TextView"),
            "snicklefritz"));
  }

  private void openActivity() throws UiObjectNotFoundException {
    device.pressHome();

    UiObject allAppsButton=
        device.findObject(new UiSelector().description("Apps"));

    allAppsButton.clickAndWaitForNewWindow();

    UiObject appsTab=device.findObject(new UiSelector().text("Apps"));

    appsTab.click();

    UiScrollable appViews=
        new UiScrollable(new UiSelector().scrollable(true));

    appViews.setAsHorizontalList();

    UiObject ourApp=
        appViews.getChildByText(new UiSelector().className("android.widget.TextView"),
                                "Action Bar Fragment Demo");

    ourApp.clickAndWaitForNewWindow();

    UiObject appValidation=
        device.findObject(new UiSelector().packageName("com.commonsware.android.abf"));

    Assert.assertTrue("Could not open test app", appValidation.exists());
  }
}


text:
class TroveConnector

  include HTTParty

  base_uri 'api.trove.nla.gov.au'
  format :json

  QUERY_DEFAULT_OPTIONS = {encoding: 'json', zone: 'newspaper'}
  RECORD_DEFAULT_OPTIONS = {encoding: 'json', reclevel: 'full', include: 'all'}

  def initialize(api_key)
    QUERY_DEFAULT_OPTIONS[:key] = api_key
    RECORD_DEFAULT_OPTIONS[:key] = api_key
  end

  def query_articles(term, options={})
    response = query_records(term, options)
    response['response']['zone'][0]['records']['article']
  end

  def query_records(term, options={})
    parameters = QUERY_DEFAULT_OPTIONS.merge options
    parameters[:q] = term
    response = self.class.get('/result', query: parameters)
    response.parsed_response
  end

  def get_article(record_url, options={})
    response = get_record(record_url, options)
    response['article']
  end

  def get_record(record_url, options={})
    parameters = RECORD_DEFAULT_OPTIONS.merge options
    response = self.class.get(record_url, query: parameters)
    response.parsed_response
  end

end


text:
package com.workshop.wilqor.testing.matchers.examples;

import com.workshop.wilqor.testing.Point;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;

import java.util.Collections;
import java.util.Map;

/**
 * Example demonstrating usage of Hamcrest matchers.
 *
 * @author wilqor
 */
public class MatchersExampleTest {
    @Test
    public void assertTruth_twoPlusTwoIsFour() {
        // there is no negative alternative
        MatcherAssert.assertThat("2 plus 2 should be equal to 4", 2 + 2 == 4);
    }

    @Test
    public void assertEquality_integers() {
        // psst, see what happens when you add static imports!
        MatcherAssert.assertThat("2 plus 2 should be equal to 4", 2 + 2, Matchers.is(Matchers.equalTo(4)));
    }

    @Test
    public void assertEquality_strings() {
        // by the way, the "equalTo" part is optional, but looks better with static imports
        MatcherAssert.assertThat("concatenated string parts should be equal to the concatenation",
                "a" + "bc", Matchers.is(Matchers.equalTo("abc")));
    }

    @Test
    public void assertEquality_doublePrecisionFloatingPoints() {
        // note: only double precision floating point is supported
        MatcherAssert.assertThat(1.0d + 0.009, Matchers.is(Matchers.closeTo(1.01d, 0.01d)));
    }

    @Test
    public void assertEquality_objects() {
        Point point = new Point(10, 20);
        Point pointWithSameCoordinates = new Point(15 - 5, 15 + 5);
        MatcherAssert.assertThat(pointWithSameCoordinates, Matchers.is(Matchers.equalTo(point)));
    }

    @Test
    public void assertNullValue_noValueForEmptyMap() {
        // empty map has no entries, so for each key we expect null
        Map<Integer, String> map = Collections.emptyMap();
        MatcherAssert.assertThat(map.get(10), Matchers.is(Matchers.nullValue()));
    }

    @Test
    public void assertAnyOf_integerOutsideExclusiveRange() {
        // at least one condition has to be true
        MatcherAssert.assertThat(150, Matchers.anyOf(
                Matchers.lessThan(50),
                Matchers.greaterThan(100)
        ));
    }

    @Test
    public void testAllOf_integerInsideRangeInclusive() {
        // each condition has to be true
        MatcherAssert.assertThat(150, Matchers.allOf(
                Matchers.greaterThanOrEqualTo(100),
                Matchers.lessThanOrEqualTo(150)
        ));
    }
}


text:
$(document).ready(function() {
	//right side stuff
    //Selecting all the divs with the "shown" class
	var $shown = $('.shown');
    //and grabbing all of the divs that follow a "shown" div
	var $hid = $('.shown + div');
//This makes the $shown and $hid objects into basically an accordion, but I wasn't very familiar with the jQuery UI when I wrote this, so I made my own.
	$shown.click(function(){
         //Pretty straight-forward, this checks to see if the div after the one that is clicked on already has the class "open"
		if ($(this).next().hasClass("open")){
            //If it does, then the class is removed and the div slid up out of sight
			$(this).next().removeClass("open").slideUp(350);
		}
		else {
             //Otherwise, the div that *does* have the "open" class has the class removed and is slid up,
			$(".open").removeClass("open").slideUp(350);
            // While the div that we're working with is given the "open" class and is slid down into view
			$(this).next().addClass("open").slideDown(350);
		}
	});
	//left side stuff
    //An array of the inputs from the Gauge Finding side of the program
	var inputs = [$("#sts"), $("#wid"), $("#row"), $("#len")];
	//When the 'Calculate' button is clicked, this function comes in to play
	$("#cal").click(function(){
        //This checks to see which of the radio buttons is checked; 'Inches' or 'Centimeters'
		var $op = ($("input[name=opt]:checked").val());
        //This is the primary function of the program, it does the arithmetic of finding your gauge by finding how many stitches and rows you are using per unit of knitting
		var perInch = function perInch(stitches, width, rows, length) {
            //The number of stitches per unit is equal to the number of stitches divided by the width, then `.toFixed(2)` to keep it down to two decimal points
			var stsPerIn = (parseFloat(stitches)/parseFloat(width)).toFixed(2);
            //Rows per unit is the same basic thing, except it is rows divided by length
			var rowsPerIn = (parseFloat(rows)/parseFloat(length)).toFixed(2);
            //This is where the radio button value comes in; I tack on either "inches" or "centimeters" to the end of this sentence using `$op`
			var ans = "Your gauge is " + stsPerIn + " stitches, " + rowsPerIn + " rows per square " + $op;
			return ans;
		};

		for(i = 0; i < 4; i++){
			if (inputs[i].val().length === 0){
				if($("#hid").hasClass("hide")){
					$(".hide").removeClass("hide").addClass("showWrong").text("Please fill in all the Swatch Info fields");
					return;
				}
				else if($("#hid").hasClass("showRight")){
					$(".showRight").removeClass("showRight").addClass("showWrong").text("Please fill in all the Swatch Info fields");
					return;
				}
				else if($("#hid").hasClass("showWrong")){
					$(".showWrong").text("Please fill in all the Swatch Info fields");
					return;
				}
			}
			else if (isNaN(inputs[i].val()) === true){
				$("#hid").removeClass().addClass("showWrong").text("All the inputted values should be numeric");
				return;
			}
			else if (i === 3){
				$("#hid").removeClass().addClass("showRight").text(perInch($("#sts").val(), $("#wid").val(), $("#row").val(), $("#len").val()));
			}
		}
	});
});


text:
// @flow

import React, { Component } from 'react';
import withRouter from '@cajacko/lib/components/HOCs/withRouter';
import Profile from './Profile.render';

type Props = {};
type State = {};

/**
 * Business logic for the profile component
 */
class ProfileComponent extends Component<Props, State> {
  /**
   * Initialise the class, set the initial state and bind the methods
   */
  constructor(props: Props) {
    super(props);

    this.state = {
      name: props.name,
      error: null,
    };
  }

  getError = () => {
    if (!this.state.name) return 'Profile.Errors.NoName';

    const minLength = 3;
    const { length } = this.state.name;

    if (length >= minLength) return;

    return { key: 'Profile.Errors.TooShort', length: minLength };
  };

  save = () => {
    const error = this.getError();

    if (error) {
      this.setState({ error });
      return;
    }

    this.props.save(this.state.name);
    this.props.history.push('/');
  };

  onChange = (text) => {
    this.setState({ name: text, error: null });
  };

  back = () => {
    this.props.history.push('/');
  };

  /**
   * Render the component
   */
  render() {
    return (
      <Profile
        back={this.props.name && this.back}
        save={this.save}
        name={this.state.name}
        onChange={this.onChange}
        error={this.state.error}
      />
    );
  }
}

export default withRouter(ProfileComponent);


text:
ACCEPTED

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

#### Published in
null

#### Original name
Aitchisonia rosea Hemsl. ex Aitch.

### Remarks
null


text:
<?php

namespace hflan\LanBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class EventType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', 'text', array(
                'label' => 'Nom'
            ))
            ->add('price', 'number', array(
                'label' => 'Prix'
            ))
            ->add('beginAt', 'datepicker', array(
                'label' => 'Début'
            ))
            ->add('endAt', 'datepicker', array(
                'label' => 'Fin'
            ))
            ->add('datesVisible', 'toggle', array(
                'label' => 'Visibilité',
                'icons' => array(
                    'active' => 'eye-open',
                    'inactive' => 'eye-close',
                ),
                'labels' => array(
                    'inactive' => 'Caché',
                    'active' => 'Public',
                ),
                'required' => false,
            ))
            ->add('registrationOpenAt', 'datepicker', array(
                'label' => 'Ouverture'
            ))
            ->add('registrationCloseAt', 'datepicker', array(
                'label' => 'Fermeture'
            ))
            ->add('registrationVisible', 'toggle', array(
                'label' => 'Visibilité',
                'icons' => array(
                    'active' => 'eye-open',
                    'inactive' => 'eye-close',
                ),
                'labels' => array(
                    'inactive' => 'Caché',
                    'active' => 'Public',
                ),
                'required' => false,
            ))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'hflan\LanBundle\Entity\Event'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'hflan_lanbundle_event';
    }
}


text:
<?php

namespace kvetinac97;

/*
 * This plugin was written by © kvetinac97 2016
 * You can use it on modify it without any restricitions
 * (You must write that it was originally developped by kvetinac97
 * Read full LICENSE in file LICENSE
 */

use pocketmine\plugin\PluginBase;
use pocketmine\utils\TextFormat as TF;

class Main extends PluginBase {

    const VERSION = 3;

    /** @var String $drops */
    public $drops;

    /** @var String $config */
    public $config;

    /** @var EventListener $listener */
    public $listener;

    /*
     * Loading, Enabling, Disabling... START
     */

    public function onLoad(){
        $this->getLogger()->notice(TF::YELLOW."Loading InstantBreak version ".TF::AQUA.self::VERSION.".0.0...");
    }

    public function onEnable(){
        $this->getLogger()->info(TF::GREEN."InstantBreak enabled!");
        if(!file_exists($cfg = $this->getDataFolder()."config.yml") or !file_exists($drops = $this->getDataFolder()."drops.yml")){
            $this->saveResource("config.yml", false);
            $this->saveResource("drops.yml", false);
        }
        $this->config = \yaml_parse_file($cfg);
        $this->drops = \yaml_parse_file($drops);
        $this->getServer()->getPluginManager()->registerEvents($this->listener = new EventListener($this), $this);
        $this->getLogger()->info(TF::GREEN."All files have been successfully iniated!");
    }

    public function onDisable(){
        $this->getLogger()->info(TF::DARK_RED."InstantBreak disabled!");
    }

    /*
     * Loading, Enabling, Disabling END
     */

    /*
     * Commands /ib, /ib-on, /ib-off START
     */

}


text:
extern NSString *BEKErrorDomain;
extern NSString *BEKReasonKey;

typedef enum {
    BEKErrorEmailAlreadyRegistered = 100,
    BEKErrorEmailOrPasswordInvalid = 101,
    BEKErrorEmailValidationRequired = 102,
    BEKErrorEmailLoginFailedBecauseEmailNotVerified = 103,
    BEKErrorEmailValidationFailed = 104,
    BEKErrorAuthenticationFailed = 403,
    BEKErrorValidationTokenInvalid = 405,
    BEKErrorResetPasswordTokenInvalid = 405,
    BEKErrorForgotPasswordTokenInvalid = 406,
    BEKErrorResetPasswordLinkTokenInvalid = 407,
    BEKErrorRequestThrottled = 429,
    BEKErrorInternalRegistrationFailed = 501,
    BEKErrorInternalDatabaseError = 502,
    BEKErrorInternalUnableToSendMail = 503,
} BEKErrorCode;

@interface BEKErrorDefines : NSObject

@end


text:
Array.prototype.getIndexByValue = function(value){
  var index = -1;
  for(var i=0; i<this.length;i++){
    if(this[i]===value){
      index = i;
      break;
    }
  }
  return index;
};
Array.prototype.getObjectIndexByKeyValue = function (key, value) {
  var index = -1;
  for(var i=0; i<this.length;i++){
    var current = this[i];
    if(typeof current === "object") {
      if(current[key]===value){
        index = i;
        break;
      }
    }
  }
  return index;
};
Array.prototype.returnObjectByKeyValue = function (key, value) {
  var index = this.getObjectIndexByKeyValue(key, value);
  if(index>=0){
    return this[index];
  }
};
Array.prototype.extractItemByValue = function(value) {
  var index = this.getIndexByValue(value);
  if(index>=0){
    var result = this[index];
    this.splice(index, 1);
    return result;
  }
};
Array.prototype.extractObjectByKeyValue = function(key, value){
  var index = this.getObjectIndexByKeyValue(key, value);
  if(index>=0){
    var result = this[index];
    this.splice(index, 1);
    return result;
  }
};
Array.prototype.pushOnce = function (item) {
  var index;
  if(typeof item === 'object'){
    for(var i=0;i<this.length;i++){
      var current = this[i];
      if(typeof current==='object'){
        if(JSON.stringify(item) === JSON.stringify(current)){
          index = i;
          break;
        }
      }
    }
  }else{
    index = this.getIndexByValue(item);
  }
  if(index===-1){
    this.push(item);
  }
};

var gameSettings = {
  money: 30000,
  // если делать это ссылкой на объект, то все игроки будут ссылаться на этот объект. Нужно сделать функцией.
  startPosition: {
    path:0,
    tile:0
  }
};

var game = {
  players: [],
  activePlayer: null,
  isRunning: false,
  turn: {
    id: 0,
    canRoll: true,
    done:false,
    playerIndex: 0
  },
  roll: {
    id: 0,
    result: null
  },
  doRoll: function () {
    this.roll.id++;
    this.roll.result = getRoll();
  },
  settings: gameSettings,
  init: function () {
    if(this.players.length){
      if(this.activePlayer===null){
        this.activePlayer = this.players[0];
      }
      this.turn.id = 1;
      for(var i = 0; i< this.players.length;i++){
        this.players[i].money = gameSettings.money;
        this.players[i].position.path = gameSettings.startPosition.path;
        this.players[i].position.tile = gameSettings.startPosition.tile;
      }
      gameMap.clearAllPlayers();
      gameMap.updatePlayersPosition(game.players);
      updatePlayersState(this.players);
      return this;
    }else{
      //TODO: сделать модальный диалог
      alert('Алё, а где игроки?')
    }
  },
  passTurn: function() {
    if(this.turn.playerIndex==(this.players.length-1)){
      this.turn.playerIndex = 0;
    }else{
      this.turn.playerIndex++;
    }
    this.activePlayer = this.players[this.turn.playerIndex];
    this.turn.id++;
    this.turn.canRoll = true;
    this.turn.done = false;
    this.doTurn();
  },
  doTurn: function () {
    var activePlayer = this.activePlayer,
        players = this.players,
        skip = false;
    if(activePlayer.freeze.duration>0){
      skip = true;
      activePlayer.freeze.duration--;
    }
    if(!activePlayer.inGame){
      skip = true;
    }
    updatePlayersState(players);
    if(!skip){

    }else{
      this.passTurn();
    }
  },
  makeMovement: function () {
    this.turn.canRoll = false;
    this.doRoll();
    gameMap.movePlayer(this.activePlayer, this.roll.result);
    this.turn.done = true;
  }

};

var log = {
  messages: [],
  addMessage: function(text, player){
    var newMessage = {
      turn: game.turn.id,
      text: text
    };
    if(player){
      newMessage.color = player.color;
      newMessage.name = player.name;
    }
    this.messages.push(newMessage);
  }
};

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getRoll() {
  return getRandomInt(1, 6);
}
function updatePlayersState(array){
  for(var i = 0; i<array.length;i++){
    array[i].getState();
  }
}


text:
# :warning: Deprecated :warning:

**This gem does not work with Turbolinks 5+, and is not compatible with many jQuery plugins. We do not recommend using it.** Instead, please consider writing your JavaScript in a way that makes it compatible with Turbolinks. These resources can help:

- [RSJS](https://ricostacruz.com/rsjs) - A reasonable structure for JS, a document outlining how to write JavaScript as "behaviors" that will be compatible with Turbolinks.

- [onmount](https://www.npmjs.com/package/onmount) - 1kb library to run something when a DOM element appears and when it exits.

Rationale: making jQuery plugins compatible with Turbolinks requires more than simply dropping in a library. It should be able to setup and teardown its changes as needed, which is something you can't automate. jQuery Turbolinks's approach worked well enough for many libraries back in 2013, but today this is no longer the case. Given its utility is very limited, we've decided to no longer maintain this library.

----

# jQuery Turbolinks

[![Build Status](https://secure.travis-ci.org/kossnocorp/jquery.turbolinks.png?branch=master)](http://travis-ci.org/kossnocorp/jquery.turbolinks)

Do you like [Turbolinks](https://github.com/rails/turbolinks)? It's easy and fast way to improve user experience of surfing on your website.

But if you have a large codebase with lots of `$(el).bind(...)` Turbolinks will surprise you. Most part of your JavaScripts will stop working in usual way. It's because the nodes on which you bind events no longer exist.

I wrote jquery.turbolinks to solve this problem in [my project](http://amplifr.com). It's easy to use: just require it *immediately after* `jquery.js`. Your other scripts should be loaded after `jquery.turbolinks.js`, and `turbolinks.js` should be after your other scripts.

Initially sponsored by [Evil Martians](http://evilmartians.com/).

This project is a member of the [OSS Manifesto](http://ossmanifesto.org/).

## Important

This readme points to the latest version (v2.x) of jQuery Turbolinks, which
features new 2.0 API. For older versions, see [v1.0.0rc2 README][oldreadme].

## Usage

Gemfile:

``` js
gem 'jquery-turbolinks'
```

Add it to your JavaScript manifest file, in this order:

``` js
//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//
// ... your other scripts here ...
//
//= require turbolinks
```

And it just works!

**Checkout "[Faster page loads with Turbolinks](https://coderwall.com/p/ypzfdw)" for deeper explanation how to use jQuery Turbolink in real world**.

## API and Customization

### $.turbo.use

By default, jQuery.Turbolinks is bound to [page:load] and [page:fetch]. To use
different events (say, if you're not using Turbolinks), use:

``` js
$.turbo.use('pjax:start', 'pjax:end');
```

## $.turbo.isReady

You can check if the page is ready by checking `$.turbo.isReady`, which will be
either `true` or `false` depending on whether the page is loading.

## Troubleshooting

### Events firing twice or more

If you find that some events are being fired multiple times after using jQuery Turbolinks, you may have been binding your `document` events inside a `$(function())` block. For instance, this example below can be a common occurrence and should be avoided:

``` javascript
/* BAD: don't bind 'document' events while inside $()! */
$(function() {
  $(document).on('click', 'button', function() { ... })
});
```

You should be binding your events outside a `$(function())` block. This will ensure that your events will only ever be bound once.

``` javascript
/* Good: events are bound outside a $() wrapper. */
$(document).on('click', 'button', function() { ... })
```

### Not working with `$(document).on('ready')`

jQuery Turbolinks doesn't support ready events bound via `$(document).on('ready', function)`. Instead, use `$(document).ready(function)` or `$(function)`.

``` javascript
// BAD: this will not work.
$(document).on('ready', function () { /* ... */ });

// OK: these two are guaranteed to work.
$(document).ready(function () { /* ... */ });
$(function () { /* ... */ });
```

## Changelog

This project uses [Semantic Versioning](http://semver.org/) for release numbering.

For changelog notes, checkout [releases page](https://github.com/kossnocorp/jquery.turbolinks/releases).

## Contributors

Initial idea and code by [@kossnocorp](http://koss.nocorp.me/), with special thanks to [@rstacruz](https://github.com/rstacruz) and other the project's [contributors](https://github.com/kossnocorp/jquery.turbolinks/graphs/contributors).

## License

[The MIT License](https://github.com/kossnocorp/jquery.turbolinks/blob/master/LICENSE.md)

[page:load]: https://github.com/rails/turbolinks/#events
[page:fetch]: https://github.com/rails/turbolinks/#events
[oldreadme]: https://github.com/kossnocorp/jquery.turbolinks/blob/v1.0.0.rc2/README.md

[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/kossnocorp/jquery.turbolinks/trend.png)](https://bitdeli.com/free "Bitdeli Badge")


text:
from __future__ import absolute_import, division, print_function, unicode_literals

from botocore.exceptions import ClientError

from c7n.filters import CrossAccountAccessFilter
from c7n.manager import resources
from c7n.query import QueryResourceManager
from c7n.utils import local_session

@resources.register('ecr')
class ECR(QueryResourceManager):

    class resource_type(object):
        service = 'ecr'
        enum_spec = ('describe_repositories', 'repositories', None)
        name = "repositoryName"
        id = "repositoryArn"
        dimension = None

@ECR.filter_registry.register('cross-account')
class ECRCrossAccountAccessFilter(CrossAccountAccessFilter):
    """Filters all EC2 Container Registries (ECR) with cross-account access

    :example:

        .. code-block: yaml

            policies:
              - name: ecr-cross-account
                resource: ecr
                filters:
                  - type: cross-account
                    whitelist_from:
                      expr: "accounts.*.accountNumber"
                      url: *accounts_url
    """
    permissions = ('ecr:GetRepositoryPolicy',)

    def process(self, resources, event=None):

        def _augment(r):
            client = local_session(self.manager.session_factory).client('ecr')
            try:
                r['Policy'] = client.get_repository_policy(
                    repositoryName=r['repositoryName'])['policyText']
            except ClientError as e:
                if e.response['Error']['Code'] == 'RepositoryPolicyNotFoundException':
                    return None
                raise
            return r

        self.log.debug("fetching policy for %d repos" % len(resources))
        with self.executor_factory(max_workers=3) as w:
            resources = list(filter(None, w.map(_augment, resources)))

        return super(ECRCrossAccountAccessFilter, self).process(resources, event)


text:
package org.sagebionetworks.repo.model;

import org.sagebionetworks.repo.model.Entity;

/**
 * Allows methods to return an entity with its annotations.
 *
 * This object is deprecated. Please use the EntityBundle instead.
 * @author John
 *
 * @param <T>
 */
@Deprecated
public class EntityWithAnnotations <T extends Entity>{

	private T entity;
	private Annotations annotations;
	public T getEntity() {
		return entity;
	}
	public void setEntity(T entity) {
		this.entity = entity;
	}
	public Annotations getAnnotations() {
		return annotations;
	}
	public void setAnnotations(Annotations annotations) {
		this.annotations = annotations;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result
				+ ((annotations == null) ? 0 : annotations.hashCode());
		result = prime * result + ((entity == null) ? 0 : entity.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		@SuppressWarnings("rawtypes")
		EntityWithAnnotations other = (EntityWithAnnotations) obj;
		if (annotations == null) {
			if (other.annotations != null)
				return false;
		} else if (!annotations.equals(other.annotations))
			return false;
		if (entity == null) {
			if (other.entity != null)
				return false;
		} else if (!entity.equals(other.entity))
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "EntityWithAnnotations [entity=" + entity + ", annotations="
				+ annotations + "]";
	}

}


text: ansible compute_nodes -a "virsh list --all" -bK


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>c4</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />

c4 - Connect Four

      <canvas class="section-canvas"></canvas>

c4 - Connect Four

          Welcome to connect four game!
Please refer to
          Wikipedia article on Connect Four
          for how to play.

Mode chooser

        <input
            class="mode-chooser-input"
            type="radio"
            name="mode"
            value="offline-ai"
            checked
          />
          Offline: Human player vs AI player

        <input
            class="mode-chooser-input"
            type="radio"
            name="mode"
            value="offline-human"
          />
          Offline: Human player vs human player
<input
            class="mode-chooser-input"
            type="radio"
            name="mode"
            value="online-human"
          />
          Online: Human player vs human player

        <button class="mode-chooser-submit">Start game</button>

...

...

...

        <button class="message-body-dismiss">OK</button>

      By Kenrick95. Fork this project at
      GitHub.


text:
<?php

namespace AppBundle\Controller;

use AppBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

class UserController extends Controller
{
    /**
     * @Route("/user", name="usermanagement")
     */
    public function userListAction()
    {
        $em = $this->getDoctrine()->getManager();
        $users = $em->getRepository('AppBundle:User')->findAllUsersOrderedByName();

        return $this->render('user/usermanagement.html.twig', [
            'users' => $users,
        ]);
    }

    /**
     * @param $userid
     * @return \Symfony\Component\HttpFoundation\Response
     * @Route("/user/{userid}", name="showProfile")
     */
    public function showUserAction($userid) {
        $usermanager = $this->get('fos_user.user_manager');
        $user = $usermanager->findUserBy(array('id'=>$userid));
        $em = $this->getDoctrine()->getManager();

        $tickets = $em->getRepository('AppBundle:Tickets')->findBy(array(
            'uid' => $userid
        ), array(
            'tid' => 'DESC'
        ));

        return $this->render("user/userprofile.html.twig", array(
            'user' => $user,
            'tickets' => $tickets
        ));
    }

    /**
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     * @Route("/user/edit", name="usereditself")
     */
    public function editUserSelf(Request $request)
    {
        $user = $this->getUser();
        $user2 = $this->getUser();

        $form = $this->createFormBuilder($user)
            ->add('id', HiddenType::class, array(
                'mapped' => false
            ))
            ->add('vorname', TextType::class, array(
                'required' => true,
                'label' => 'Vorname'
            ))
            ->add('nachname', TextType::class, array(
                'required' => true,
                'label' => 'Nachname'
            ))
            ->add('email', TextType::class, array(
                'required' => true,
                'label' => 'E-Mail Adresse'
            ))

            ->add('save', SubmitType::class, array('label' => 'Daten ändern'))
            ->getForm();

        $form->handleRequest($request);
        //

        if($form->isSubmitted() && $form->isValid()) {

            $user = $form->getData();

            $em = $this->getDoctrine()->getManager();
            if ($em->getRepository('AppBundle:User')->isUsernameUnique($user->getEmail()) || $user->getEmail() == $user2->getUsername()) {

                $user->setUsername($user->getEmail());
                // UserObjekt in Datenbank speichern
                $em->persist($user);
                $em->flush();

                $this->addFlash('success', 'User aktuelisiert');
                return $this->redirectToRoute('usermanagement');
            }

            $this->addFlash('danger', 'Adresse existiert bereits');

        }

        return $this->render('user/edituser.html.twig', array(
            'form' => $form->createView(),
        ));
    }

    /**
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     * @Route("/user/changepassword", name="changePasswordSelf")
     */
    public function changePasswordSelfAction(Request $request) {
        $user = $this->getUser();

        $form = $this->createFormBuilder($user)
            ->add('id', HiddenType::class, array(
                'mapped' => false
            ))
            ->add('plainPassword', RepeatedType::class, array(
                'type' => PasswordType::class,
                'invalid_message' => 'Die Passwörter müssen übereinstimmen',
                'required' => true,
                'first_options'  => array('label' => 'Password'),
                'second_options' => array('label' => 'Password wiederholen')
            ))

            ->add('save', SubmitType::class, array('label' => 'Passwort ändern'))
            ->getForm();

        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid()) {
            $usermanager = $this->get('fos_user.user_manager');
            $user = $form->getData();

            $em = $this->getDoctrine()->getManager();
            $usermanager->updatePassword($user);
            $em->persist($user);
            $em->flush();

            $this->addFlash('success', 'Passwort geändert');
            return $this->redirectToRoute('usermanagement');
        }
        return $this->render('user/edituser.html.twig', array(
            'form' => $form->createView(),
        ));
    }
}


text:
#include "XnLinkInputStreamsMgr.h"
#include "XnLinkProtoUtils.h"
#include "XnLinkStatusCodes.h"
#include "XnLinkFrameInputStream.h"
#include "XnLinkProtoLibDefs.h"
#include "XnLinkContInputStream.h"
#include "XnLinkControlEndpoint.h"
#include <XnLog.h>
#include <XnProfiling.h>

namespace xn
{

/* FRAG_FLAGS_ALLOWED_CHANGES[y][x] is 1 if a change from fragmentation flag y to x is allowed, 0 otherwise. */
const XnUInt32 LinkInputStreamsMgr::FRAG_FLAGS_ALLOWED_CHANGES[4][4] = {
/*                                        M, B, E, S */
/* Allowed state changes from MIDDLE: */ {1, 0, 1, 0},
/* Allowed state changes from BEGIN:  */ {1, 0, 1, 0},
/* Allowed state changes from END:    */ {0, 1, 0, 1},
/* Allowed state changes from SINGLE: */ {0, 1, 0, 1},
};
const XnUInt16 LinkInputStreamsMgr::INITIAL_PACKET_ID = 1;

LinkInputStreamsMgr::LinkInputStreamsMgr()
{
	xnOSMemSet(&m_streamInfos, 0, sizeof(m_streamInfos));
}

LinkInputStreamsMgr::~LinkInputStreamsMgr()
{
	Shutdown();
}

XnStatus LinkInputStreamsMgr::Init()
{
	return XN_STATUS_OK;
}

void LinkInputStreamsMgr::Shutdown()
{
	for (XnUInt16 nStreamID = 0; nStreamID < XN_LINK_MAX_STREAMS; nStreamID++)
	{
		ShutdownInputStream(nStreamID);
	}
}

void LinkInputStreamsMgr::RegisterStreamOfType(XnStreamType streamType, const XnChar* strCreationInfo, XnUInt16 nStreamID)
{
	if (m_streamInfos[nStreamID].pInputStream == NULL ||
		(m_streamInfos[nStreamID].refCount > 0 && nStreamID != FindStreamByType(streamType,strCreationInfo)))
	{
		xnLogWarning(XN_MASK_LINK, "Trying to register a non existing Input stream %u", nStreamID);
		XN_ASSERT(false);
		return;
	}

	if (m_streamInfos[nStreamID].refCount == 0)
	{
		m_streamInfos[nStreamID].streamType      = streamType;
		m_streamInfos[nStreamID].strCreationInfo = strCreationInfo;
	}
	//increase refcounter
	++m_streamInfos[nStreamID].refCount;
	xnLogVerbose(XN_MASK_LINK, "Input stream %u incref. refcount is %d", nStreamID, m_streamInfos[nStreamID].refCount);
}

XnBool LinkInputStreamsMgr::UnregisterStream(XnUInt16 nStreamID)
{
	XnBool wasLast = false;

	if (m_streamInfos[nStreamID].pInputStream == NULL || m_streamInfos[nStreamID].refCount <= 0)
	{
		xnLogWarning(XN_MASK_LINK, "Trying to unregister a non existing Input stream %u", nStreamID);
		XN_ASSERT(false);
		return false;
	}

	//decrease refcounter
	if (--m_streamInfos[nStreamID].refCount == 0)
	{
		wasLast = true;
	}
	xnLogVerbose(XN_MASK_LINK, "Input stream %u decref. refcount is %d", nStreamID, m_streamInfos[nStreamID].refCount);

	return wasLast;
}

XnBool LinkInputStreamsMgr::HasStreamOfType(XnStreamType streamType, const XnChar* strCreationInfo,	XnUInt16& nStreamID)
{
	int i;
	if ((i = FindStreamByType(streamType, strCreationInfo)) >= 0)
	{
		nStreamID = (XnUInt16)i;
		return true;
	}
	return false;
}

int LinkInputStreamsMgr::FindStreamByType(XnStreamType streamType, const XnChar* strCreationInfo)
{
	for (int i = 0; i < XN_LINK_MAX_STREAMS; ++i)
	{
		if (m_streamInfos[i].refCount > 0 &&
			streamType == m_streamInfos[i].streamType &&
			((m_streamInfos[i].strCreationInfo == NULL && strCreationInfo == NULL) || xnOSStrCmp(strCreationInfo, m_streamInfos[i].strCreationInfo) == 0))
		{
			return i;
		}
	}
	return -1;
}

XnStatus LinkInputStreamsMgr::InitInputStream(LinkControlEndpoint* pLinkControlEndpoint,
                                              XnStreamType streamType,
                                              XnUInt16 nStreamID,
                                              IConnection* pConnection)
{
	XnStatus nRetVal = XN_STATUS_OK;
    XnStreamFragLevel streamFragLevel = XN_LINK_STREAM_FRAG_LEVEL_NONE;
	if (nStreamID > XN_LINK_MAX_STREAMS)
	{
		xnLogError(XN_MASK_LINK, "Cannot initialize stream of id %u - max stream id is %u",
			nStreamID, XN_LINK_MAX_STREAMS-1);
		XN_ASSERT(FALSE);
		return XN_STATUS_LINK_BAD_STREAM_ID;
	}

    nRetVal = pLinkControlEndpoint->GetStreamFragLevel(nStreamID, streamFragLevel);
    XN_IS_STATUS_OK_LOG_ERROR("Get stream frag level", nRetVal);

	if (m_streamInfos[nStreamID].pInputStream == NULL)
	{
		//Need to create the input stream for the first time
		switch (streamFragLevel)
		{
			case XN_LINK_STREAM_FRAG_LEVEL_FRAMES:
				m_streamInfos[nStreamID].pInputStream = XN_NEW(LinkFrameInputStream);
				break;
			case XN_LINK_STREAM_FRAG_LEVEL_CONTINUOUS:
				m_streamInfos[nStreamID].pInputStream = XN_NEW(LinkContInputStream);
				break;

			default:
				xnLogError(XN_MASK_LINK, "Bad stream type %u", streamFragLevel);
				XN_ASSERT(FALSE);
				return XN_STATUS_ERROR;
		}
	}

	XN_VALIDATE_ALLOC_PTR(m_streamInfos[nStreamID].pInputStream);

	StreamInfo& streamInfo = m_streamInfos[nStreamID];
	if (m_streamInfos[nStreamID].pInputStream->IsInitialized() && (streamInfo.streamFragLevel != streamFragLevel))
	{
		XN_DELETE(m_streamInfos[nStreamID].pInputStream);
		m_streamInfos[nStreamID].pInputStream = NULL;
		xnLogError(XN_MASK_LINK,
			"Stream %u was already initialized with stream type %u, but now tried to initialize it with stream type %u :(",
			nStreamID, streamInfo.streamFragLevel, streamFragLevel);
		/*Streams may only be re-initialized with the same stream type. This means a frame stream must always
		  remain a frame stream and a continuous stream must always remain a continuous stream. */
		XN_ASSERT(FALSE);
		return XN_STATUS_ERROR;
	}

	nRetVal = m_streamInfos[nStreamID].pInputStream->Init(pLinkControlEndpoint, streamType, nStreamID, pConnection);
	if (nRetVal != XN_STATUS_OK)
	{
		XN_DELETE(m_streamInfos[nStreamID].pInputStream);
		m_streamInfos[nStreamID].pInputStream = NULL;
		xnLogError(XN_MASK_LINK, "Failed to Initialize link input stream: %s", xnGetStatusString(nRetVal));
		XN_ASSERT(FALSE);
		return nRetVal;
	}

	streamInfo.nMsgType = 0;
	streamInfo.nNextPacketID = INITIAL_PACKET_ID;
	streamInfo.streamFragLevel = streamFragLevel;
	streamInfo.prevFragmentation = XN_LINK_FRAG_END; // this means we now expect BEGIN
	streamInfo.packetLoss = FALSE;
	return XN_STATUS_OK;
}

void LinkInputStreamsMgr::ShutdownInputStream(XnUInt16 nStreamID)
{
    LinkInputStream* pLinkInputStream = GetInputStream(nStreamID);
	if (pLinkInputStream != NULL)
	{
		pLinkInputStream->Shutdown();
		XN_DELETE(pLinkInputStream);
		m_streamInfos[nStreamID].pInputStream = NULL;
	}
}

void LinkInputStreamsMgr::HandlePacket(const LinkPacketHeader* pLinkPacketHeader)
{
	//Validate Stream ID
	XnUInt16 nStreamID = pLinkPacketHeader->GetStreamID();
	if (nStreamID >= XN_LINK_MAX_STREAMS)
	{
		xnLogWarning(XN_MASK_LINK, "Got bad Stream ID: %u, max StreamID is %u", nStreamID, XN_LINK_MAX_STREAMS-1);
		XN_ASSERT(FALSE);
		return;
	}

	StreamInfo* pStreamInfo = &m_streamInfos[nStreamID];

	//Validate packet ID
	XnUInt16 nPacketID = pLinkPacketHeader->GetPacketID();
	if (nPacketID != pStreamInfo->nNextPacketID)
	{
		xnLogWarning(XN_MASK_LINK, "Expected packet id of %u but got %u on stream %u.",
			pStreamInfo->nNextPacketID, nPacketID, nStreamID);
		pStreamInfo->packetLoss = TRUE;
	}

	//We now expect the packet ID to be right after the one we got (even if we lost some packets on the way).
	pStreamInfo->nNextPacketID = (nPacketID + 1);

	XnUInt16 nMsgType = pLinkPacketHeader->GetMsgType();
	XnLinkFragmentation fragmentation = pLinkPacketHeader->GetFragmentationFlags();

	if (!pStreamInfo->packetLoss && !FRAG_FLAGS_ALLOWED_CHANGES[pStreamInfo->prevFragmentation][fragmentation])
	{
		//The transition between the previous fragmentation flags and the current fragmentation flags is not allowed
		xnLogWarning(XN_MASK_LINK, "Packet %u in stream %u has fragmentation flags of %s, but previous packet in this stream was %s",
			nPacketID, nStreamID,
			xnFragmentationFlagsToStr(fragmentation),
			xnFragmentationFlagsToStr(pStreamInfo->prevFragmentation));
		pStreamInfo->packetLoss = TRUE;
	}

	pStreamInfo->prevFragmentation = fragmentation;

	if (fragmentation & XN_LINK_FRAG_BEGIN)
	{
		//Set message type for new frame
		pStreamInfo->nMsgType = nMsgType;
	}
	else
	{
		//Validate that message type is consistent with first packet in frame.
		if (!pStreamInfo->packetLoss && nMsgType != pStreamInfo->nMsgType)
		{
			xnLogWarning(XN_MASK_LINK, "Inconsistent msg type for stream %u - expected 0x%04X but got 0x%04X",
				nStreamID, pStreamInfo->nMsgType, nMsgType);
			pStreamInfo->packetLoss = TRUE;
			return;
		}
	}

	if (!pStreamInfo->pInputStream->IsStreaming())
	{
		xnLogWarning(XN_MASK_LINK, "Stream %u got packets but it is not streaming", nStreamID);
		XN_ASSERT(FALSE);
		return;
	}

	// the data is immediately after the header
	const XnUInt8* pPacketData = reinterpret_cast<const XnUInt8*>(pLinkPacketHeader + 1);
	XnStatus nRetVal = pStreamInfo->pInputStream->HandlePacket(*pLinkPacketHeader, pPacketData, pStreamInfo->packetLoss);
	if (nRetVal != XN_STATUS_OK)
	{
		xnLogWarning(XN_MASK_LINK, "Failed to handle packet of %u bytes in stream %u: %s",
			pLinkPacketHeader->GetDataSize(), nStreamID, xnGetStatusString(nRetVal));
		return;
	}
}

XnStatus LinkInputStreamsMgr::HandleData(const void* pData, XnUInt32 nSize)
{
	XnStatus nRetVal = XN_STATUS_OK;
	XnUInt32 nBytesToRead = nSize;

	XN_PROFILING_START_SECTION("LinkInputStreamsMgr::HandleData()");

	const XnUInt8* pRawLinkPacket = reinterpret_cast<const XnUInt8*>(pData);

	while (nBytesToRead > 0)
	{
		const LinkPacketHeader* pLinkPacketHeader = reinterpret_cast<const LinkPacketHeader*>(pRawLinkPacket);

		//Validate basic info in packet header
		nRetVal = pLinkPacketHeader->Validate(nBytesToRead);
		XN_IS_STATUS_OK_LOG_ERROR("Validate packet", nRetVal);

		pRawLinkPacket += pLinkPacketHeader->GetSize();
		nBytesToRead -= pLinkPacketHeader->GetSize();

		HandlePacket(pLinkPacketHeader);
	}

	XN_PROFILING_END_SECTION;

	return XN_STATUS_OK;
}

LinkInputStream* LinkInputStreamsMgr::GetInputStream(XnUInt16 nStreamID)
{
	if (nStreamID >= XN_LINK_MAX_STREAMS)
	{
		XN_ASSERT(FALSE);
		return NULL;
	}

	return m_streamInfos[nStreamID].pInputStream;
}

const LinkInputStream* LinkInputStreamsMgr::GetInputStream(XnUInt16 nStreamID) const
{
	if (nStreamID >= XN_LINK_MAX_STREAMS)
	{
		XN_ASSERT(FALSE);
		return NULL;
	}

	return m_streamInfos[nStreamID].pInputStream;
}

XnBool LinkInputStreamsMgr::HasStreams() const
{
	for (int i = 0; i < XN_LINK_MAX_STREAMS; ++i)
	{
		if (m_streamInfos[i].pInputStream != NULL)
		{
			return TRUE;
		}
	}

	return FALSE;
}

} //namespace xn


text:
<?php

class LaravelRoutesTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testLandingResponseCode()
    {
        $response = $this->call('GET', '/');

        $this->assertEquals(200, $response->status());
    }

    // public function testServeAngular()
    // {
    //     $this->visit('/')
    //          ->see('ng-app');
    // }

    public function testUnsupportedBrowserPage()
    {
        $this->visit('/unsupported-browser')
             ->see('update your browser')
             ->see('Internet Explorer');
    }
    public function testStyleResponse(){
      //$this->get('/api/index/epi/structure')
        //->seeJsonContains(['style_id' => 0])
        //->seeJsonContains(['style' => null]);
    }
}


text:
@interface PodsDummy_Pods_SilentRunnerEngine : NSObject
@end
@implementation PodsDummy_Pods_SilentRunnerEngine
@end


text:
{{method|upper}} {{api_prefix}}{{endpoint}}

  {% block description %}{% endblock %}

Parameters:

  {% block parameters %}

None

  {% endblock parameters %}

Response:

{% block response %}{% endblock %}

Example:

{% block example_jquery %}
  $.ajax({
    url: '{{api_prefix}}{{endpoint}}',
    method: '{{method}}',
    data: {
      {% block example_data %}{% endblock %}api_account_id: '{{api_account_id}}',
      api_access_key: '{{api_access_key}}'
    },
    success: function (data, status, xhr) {
      var pretty = JSON.stringify(JSON.parse(data), null, 2);
      $('#api-example-output').html(pretty);
      showSuccess(pretty);
    },
    error: function (xhr, status, error) {
      var errorContent = status + ': ' + error;
      showError(errorContent);
      $('#api-example-output').html(errorContent);
    }
  });{% endblock example_jquery %}


text:
package org.slc.sli.api.security.saml;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.opensaml.Configuration;
import org.opensaml.saml2.core.Assertion;
import org.opensaml.saml2.core.EncryptedAssertion;
import org.opensaml.saml2.core.Issuer;
import org.opensaml.saml2.core.Response;
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.io.Unmarshaller;
import org.opensaml.xml.signature.Signature;
import org.slc.sli.api.resources.security.KeyStoreAccessor;
import org.slc.sli.api.security.context.APIAccessDeniedException;
import org.slc.sli.api.security.context.resolver.RealmHelper;
import org.slc.sli.domain.Entity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ablum
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/applicationContext-test.xml" })
public class SamlHelperTest {
    @InjectMocks
    @Autowired
    SamlHelper samlHelper;

    @Mock
    RealmHelper realmHelper;

    @Autowired
    private KeyStoreAccessor apiKeyStoreAccessor;

    private Entity realm = Mockito.mock(Entity.class);

    private static final String REALM_ID = "REALM_ID";
    private static final String ARTIFACT = "AAQAAjh3bwgbBZ+LiIx3/RVwDGy0aRUu+xxuNtTZVbFofgZZVCKJQwQNQ7Q=";
    private static final String ARTIFACT_RESOLUTION_ENDPOINT = "https://example/artifactResolution";

    private static final String VALID_SOURCEID = "38776f081b059f8b888c77fd15700c6cb469152e";
    private static final String INCORRECT_SOURCEID = "59886f081b059f8b888c77fd15700c6cb469152e";
    private static final String NOT_HEX_SOURCEID = "49887f091b059f8b888c77fd15700c6vf469152f";

    @Value("${sli.api.encryption.certificate.keyAlias}")
    String encryptionCertKeyStoreAlias;

    @Value("#{encryptor.decrypt('${sli.encryption.ldapKeyAlias}', '${sli.encryption.ldapKeyPass}', '${sli.api.encryption.certificate.keyPass}')}")
    String encryptionCertKeyStoreEntryPassword;

    KeyStore.PrivateKeyEntry encryptPKEntry;

    @SuppressWarnings("unchecked")
    @Before
    public void init() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
        MockitoAnnotations.initMocks(this);
        Mockito.when(realmHelper.findRealmById(Mockito.anyString())).thenReturn(realm);
        Mockito.when(realm.getEntityId()).thenReturn(REALM_ID);

        try {
            encryptPKEntry = apiKeyStoreAccessor.getPrivateKeyEntry(encryptionCertKeyStoreAlias, encryptionCertKeyStoreEntryPassword);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Test
    public void testGetArtifactUrl() {
        setRealm(VALID_SOURCEID);

        String result = samlHelper.getArtifactUrl(REALM_ID, ARTIFACT);
        Assert.assertEquals(ARTIFACT_RESOLUTION_ENDPOINT, result);

    }

    @Test(expected = APIAccessDeniedException.class)
    public void testGetArtifactUrlIncorrectSourceId() {
        setRealm(INCORRECT_SOURCEID);

        String result = samlHelper.getArtifactUrl(REALM_ID, ARTIFACT);
        Assert.assertEquals(ARTIFACT_RESOLUTION_ENDPOINT, result);

    }

    @Test(expected = IllegalArgumentException.class)
    public void testGetArtifactUrlInvalidSourceIdFormat() {
        setRealm(NOT_HEX_SOURCEID);

        String result = samlHelper.getArtifactUrl(REALM_ID, ARTIFACT);
        Assert.assertEquals(ARTIFACT_RESOLUTION_ENDPOINT, result);

    }

    @Test
    public void testInlineDecryption() {
        Resource inlineAssertionResource = new ClassPathResource("saml/inlineEncryptedAssertion.xml");
        EncryptedAssertion encAssertion = createAssertion(inlineAssertionResource);

        Assertion assertion = samlHelper.decryptAssertion(encAssertion, encryptPKEntry);
        verifyAssertion(assertion);
    }

    private void verifyAssertion(Assertion assertion) {
        Assert.assertNotNull(assertion);
        Assert.assertNotNull(assertion.getSubject());
        Assert.assertEquals("http://local.slidev.org:8080/api/rest/saml/sso/artifact", assertion.getSubject().getSubjectConfirmations().get(0).getSubjectConfirmationData().getRecipient());
        Assert.assertNotNull(assertion.getConditions());
        Assert.assertNotNull(assertion.getSignature());

        LinkedMultiValueMap<String, String> attributes = samlHelper.extractAttributesFromResponse(assertion);
        Assert.assertEquals(3, attributes.size());
    }

    @Test
    public void testPeerDecryption() {
        Resource peerAssertionResource = new ClassPathResource("saml/peerEncryptedAssertion.xml");
        EncryptedAssertion encAssertion = createAssertion(peerAssertionResource);

        Assertion assertion = samlHelper.decryptAssertion(encAssertion, encryptPKEntry);
        verifyAssertion(assertion);
    }

    @Test
    public void testIsAssertionEncrypted() {
        Response samlResponse = Mockito.mock(Response.class);
        Mockito.when(samlResponse.getEncryptedAssertions()).thenReturn(null);

        boolean result = samlHelper.isAssertionEncrypted(samlResponse);
        Assert.assertFalse(result);

        Mockito.when(samlResponse.getEncryptedAssertions()).thenReturn(new ArrayList<EncryptedAssertion>());
        result = samlHelper.isAssertionEncrypted(samlResponse);
        Assert.assertFalse(result);

        EncryptedAssertion encryptedAssertion = Mockito.mock(EncryptedAssertion.class);
        List<EncryptedAssertion> assertionList = new ArrayList<EncryptedAssertion>();
        assertionList.add(encryptedAssertion);

        Mockito.when(samlResponse.getEncryptedAssertions()).thenReturn(assertionList);
        result = samlHelper.isAssertionEncrypted(samlResponse);
        Assert.assertTrue(result);
    }

    @Test (expected = APIAccessDeniedException.class)
    public void testValidSignature() {
        Response samlResponse = Mockito.mock(Response.class);
        Assertion assertion = Mockito.mock(Assertion.class);
        Signature responseSignature = Mockito.mock(Signature.class);
        Signature assertionSignature = Mockito.mock(Signature.class);
        Element element = Mockito.mock(Element.class);

        Issuer issuer = Mockito.mock(Issuer.class);
        String issuerValue = "http://testidp.com";
        Mockito.when(issuer.getValue()).thenReturn(issuerValue);

        Mockito.when(samlResponse.getIssuer()).thenReturn(issuer);
        Mockito.when(samlResponse.getSignature()).thenReturn(responseSignature);
        Mockito.when(samlResponse.getDOM()).thenReturn(element);
        Mockito.when(assertion.getSignature()).thenReturn(null);
        Mockito.when(assertion.getDOM()).thenReturn(element);

        SamlHelper spyObject = Mockito.spy(samlHelper);

        Mockito.doNothing().when(spyObject).validateFormatAndCertificate(Mockito.any(Signature.class), Mockito.any(Element.class), Mockito.anyString());

        spyObject.validateSignature(samlResponse, assertion);

        Mockito.verify(spyObject, Mockito.times(1)).validateFormatAndCertificate(responseSignature, element, issuerValue);
        Mockito.verify(spyObject, Mockito.times(0)).validateFormatAndCertificate(assertionSignature, element, issuerValue);

        Mockito.when(assertion.getSignature()).thenReturn(assertionSignature);

        spyObject = Mockito.spy(samlHelper);
        Mockito.doNothing().when(spyObject).validateFormatAndCertificate(Mockito.any(Signature.class), Mockito.any(Element.class), Mockito.anyString());
        spyObject.validateSignature(samlResponse, assertion);

        Mockito.verify(spyObject, Mockito.times(1)).validateFormatAndCertificate(responseSignature, element, issuerValue);
        Mockito.verify(spyObject, Mockito.times(1)).validateFormatAndCertificate(assertionSignature, element, issuerValue);

        Mockito.when(samlResponse.getSignature()).thenReturn(null);

        spyObject = Mockito.spy(samlHelper);
        Mockito.doNothing().when(spyObject).validateFormatAndCertificate(Mockito.any(Signature.class), Mockito.any(Element.class), Mockito.anyString());
        spyObject.validateSignature(samlResponse, assertion);

        Mockito.verify(spyObject, Mockito.times(0)).validateFormatAndCertificate(responseSignature, element, issuerValue);
        Mockito.verify(spyObject, Mockito.times(1)).validateFormatAndCertificate(assertionSignature, element, issuerValue);

        Mockito.when(samlResponse.getSignature()).thenReturn(null);
        Mockito.when(assertion.getSignature()).thenReturn(null);

        spyObject = Mockito.spy(samlHelper);
        Mockito.doNothing().when(spyObject).validateFormatAndCertificate(Mockito.any(Signature.class), Mockito.any(Element.class), Mockito.anyString());
        spyObject.validateSignature(samlResponse, assertion);

        Mockito.verify(spyObject, Mockito.times(0)).validateFormatAndCertificate(responseSignature, element, issuerValue);
        Mockito.verify(spyObject, Mockito.times(0)).validateFormatAndCertificate(assertionSignature, element, issuerValue);
    }

    @Test (expected = APIAccessDeniedException.class)
    public void testNonSamlXml() {
        String postData = "<test><child>text</child></test>";
        Document doc = samlHelper.parseToDoc(postData);

        Response samlResponse = samlHelper.convertToSAMLResponse(doc.getDocumentElement());
        Assert.assertNull(samlResponse);
    }

    @Test (expected = APIAccessDeniedException.class)
    public void testNonSamlResponseXml() {
        String postData = "<saml2:AttributeService xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:metadata\"></saml2:AttributeService>";
        Document doc = samlHelper.parseToDoc(postData);

        Response samlResponse = samlHelper.convertToSAMLResponse(doc.getDocumentElement());

        Assert.assertNull(samlResponse);
    }

    private void setRealm(String sourceId) {
        Map<String, Object> realmBody = new HashMap<String, Object>();
        realmBody.put("edOrg", "My School");
        Map<String, List<Map<String, String>>> saml = new HashMap<String, List<Map<String, String>>>();
        saml.put("field", new ArrayList<Map<String, String>>());
        realmBody.put("saml", saml);
        realmBody.put("tenantId", "My Tenant");
        realmBody.put("admin", true);
        realmBody.put("developer", Boolean.FALSE);
        Map<String, Object> idp = new HashMap<String, Object>();
        idp.put("artifactResolutionEndpoint", ARTIFACT_RESOLUTION_ENDPOINT);
        idp.put("sourceId", sourceId);
        realmBody.put("idp", idp);
        Mockito.when(realm.getBody()).thenReturn(realmBody);
    }

    private EncryptedAssertion createAssertion(Resource encAssertionResource) {
        EncryptedAssertion encryptedAssertion = null;

        try {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            dbFactory.setNamespaceAware(true);
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(encAssertionResource.getInputStream());
            Unmarshaller unm = Configuration.getUnmarshallerFactory().getUnmarshaller(EncryptedAssertion.DEFAULT_ELEMENT_NAME);
            XMLObject obj = unm.unmarshall(doc.getDocumentElement());
            encryptedAssertion = (EncryptedAssertion) obj;
            encryptedAssertion = (EncryptedAssertion) Configuration.getUnmarshallerFactory().getUnmarshaller(EncryptedAssertion.DEFAULT_ELEMENT_NAME).unmarshall(doc.getDocumentElement());
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return encryptedAssertion;
    }

}