text:
package io.reactivex.flowable;

import static org.junit.Assert.*;

import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;

import org.junit.*;
import org.reactivestreams.*;

import io.reactivex.*;
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.*;
import io.reactivex.functions.*;
import io.reactivex.internal.functions.Functions;
import io.reactivex.internal.subscribers.ForEachWhileSubscriber;
import io.reactivex.internal.subscriptions.BooleanSubscription;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.processors.PublishProcessor;
import io.reactivex.subscribers.*;

public class FlowableSubscriberTest {

    /**
     * Should request n for whatever the final Subscriber asks for.
     */
    @Test
    public void testRequestFromFinalSubscribeWithRequestValue() {
        TestSubscriber<String> s = new TestSubscriber<String>(0L);
        s.request(10);
        final AtomicLong r = new AtomicLong();
        s.onSubscribe(new Subscription() {

            @Override
            public void request(long n) {
                r.set(n);
            }

            @Override
            public void cancel() {

            }

        });
        assertEquals(10, r.get());
    }

    /**
     * Should request -1 for infinite.
     */
    @Test
    public void testRequestFromFinalSubscribeWithoutRequestValue() {
        TestSubscriber<String> s = new TestSubscriber<String>();
        final AtomicLong r = new AtomicLong();
        s.onSubscribe(new Subscription() {

            @Override
            public void request(long n) {
                r.set(n);
            }

            @Override
            public void cancel() {

            }

        });
        assertEquals(Long.MAX_VALUE, r.get());
    }

    @Test
    public void testRequestFromChainedOperator() throws Exception {
        TestSubscriber<String> s = new TestSubscriber<String>(10L);
        FlowableOperator<String, String> o = new FlowableOperator<String, String>() {
            @Override
            public Subscriber<? super String> apply(final Subscriber<? super String> s1) {
                return new FlowableSubscriber<String>() {

                    @Override
                    public void onSubscribe(Subscription a) {
                        s1.onSubscribe(a);
                    }

                    @Override
                    public void onComplete() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String t) {

                    }

                };
            }
        };
        Subscriber<? super String> ns = o.apply(s);

        final AtomicLong r = new AtomicLong();
        // set set the producer at the top of the chain (ns) and it should flow through the operator to the (s) subscriber
        // and then it should request up with the value set on the final Subscriber (s)
        ns.onSubscribe(new Subscription() {

            @Override
            public void request(long n) {
                r.set(n);
            }

            @Override
            public void cancel() {

            }

        });
        assertEquals(10, r.get());
    }

    @Test
    public void testRequestFromDecoupledOperator() throws Exception {
        TestSubscriber<String> s = new TestSubscriber<String>(0L);
        FlowableOperator<String, String> o = new FlowableOperator<String, String>() {
            @Override
            public Subscriber<? super String> apply(final Subscriber<? super String> s1) {
                return new FlowableSubscriber<String>() {

                    @Override
                    public void onSubscribe(Subscription a) {
                        s1.onSubscribe(a);
                    }

                    @Override
                    public void onComplete() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String t) {

                    }

                };
            }
        };
        s.request(10);
        Subscriber<? super String> ns = o.apply(s);

        final AtomicLong r = new AtomicLong();
        // set set the producer at the top of the chain (ns) and it should flow through the operator to the (s) subscriber
        // and then it should request up with the value set on the final Subscriber (s)
        ns.onSubscribe(new Subscription() {

            @Override
            public void request(long n) {
                r.set(n);
            }

            @Override
            public void cancel() {

            }

        });
        assertEquals(10, r.get());
    }

    @Test
    public void testRequestFromDecoupledOperatorThatRequestsN() throws Exception {
        TestSubscriber<String> s = new TestSubscriber<String>(10L);
        final AtomicLong innerR = new AtomicLong();
        FlowableOperator<String, String> o = new FlowableOperator<String, String>() {
            @Override
            public Subscriber<? super String> apply(Subscriber<? super String> child) {
                // we want to decouple the chain so set our own Producer on the child instead of it coming from the parent
                child.onSubscribe(new Subscription() {

                    @Override
                    public void request(long n) {
                        innerR.set(n);
                    }

                    @Override
                    public void cancel() {

                    }

                });

                ResourceSubscriber<String> as = new ResourceSubscriber<String>() {

                    @Override
                    protected void onStart() {
                        // we request 99 up to the parent
                        request(99);
                    }

                    @Override
                    public void onComplete() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(String t) {

                    }
                };

                return as;
            }
        };
        Subscriber<? super String> ns = o.apply(s);

        final AtomicLong r = new AtomicLong();
        // set set the producer at the top of the chain (ns) and it should flow through the operator to the (s) subscriber
        // and then it should request up with the value set on the final Subscriber (s)
        ns.onSubscribe(new Subscription() {

            @Override
            public void request(long n) {
                r.set(n);
            }

            @Override
            public void cancel() {

            }

        });
        assertEquals(99, r.get());
        assertEquals(10, innerR.get());
    }

    @Test
    public void testRequestToFlowable() {
        TestSubscriber<Integer> ts = new TestSubscriber<Integer>(3L);
        final AtomicLong requested = new AtomicLong();
        Flowable.<Integer>unsafeCreate(new Publisher<Integer>() {
            @Override
            public void subscribe(Subscriber<? super Integer> s) {
                s.onSubscribe(new Subscription() {

                    @Override
                    public void request(long n) {
                        requested.set(n);
                    }

                    @Override
                    public void cancel() {

                    }
                });
            }
        }).subscribe(ts);
        assertEquals(3, requested.get());
    }

    @Test
    public void testRequestThroughMap() {
        TestSubscriber<Integer> ts = new TestSubscriber<Integer>(0L);
        ts.request(3);
        final AtomicLong requested = new AtomicLong();
        Flowable.<Integer>unsafeCreate(new Publisher<Integer>() {
            @Override
            public void subscribe(Subscriber<? super Integer> s) {
                s.onSubscribe(new Subscription() {

                    @Override
                    public void request(long n) {
                        requested.set(n);
                    }

                    @Override
                    public void cancel() {

                    }
                });
            }
        }).map(Functions.<Integer>identity()).subscribe(ts);
        assertEquals(3, requested.get());
    }

    @Test
    public void testRequestThroughTakeThatReducesRequest() {
        TestSubscriber<Integer> ts = new TestSubscriber<Integer>(0L);
        ts.request(3);
        final AtomicLong requested = new AtomicLong();
        Flowable.<Integer>unsafeCreate(new Publisher<Integer>() {
            @Override
            public void subscribe(Subscriber<? super Integer> s) {
                s.onSubscribe(new Subscription() {

                    @Override
                    public void request(long n) {
                        requested.set(n);
                    }

                    @Override
                    public void cancel() {

                    }

                });
            }
        }).take(2).subscribe(ts);

        // FIXME the take now requests Long.MAX_PATH if downstream requests at least the limit
        assertEquals(Long.MAX_VALUE, requested.get());
    }

    @Test
    public void testRequestThroughTakeWhereRequestIsSmallerThanTake() {
        TestSubscriber<Integer> ts = new TestSubscriber<Integer>(0L);
        ts.request(3);
        final AtomicLong requested = new AtomicLong();
        Flowable.<Integer>unsafeCreate(new Publisher<Integer>() {
            @Override
            public void subscribe(Subscriber<? super Integer> s) {
                s.onSubscribe(new Subscription() {

                    @Override
                    public void request(long n) {
                        requested.set(n);
                    }

                    @Override
                    public void cancel() {

                    }

                });
            }
        }).take(10).subscribe(ts);
        assertEquals(3, requested.get());
    }

    @Test
    public void testOnStartCalledOnceViaSubscribe() {
        final AtomicInteger c = new AtomicInteger();
        Flowable.just(1, 2, 3, 4).take(2).subscribe(new DefaultSubscriber<Integer>() {

            @Override
            public void onStart() {
                c.incrementAndGet();
                request(1);
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Integer t) {
                request(1);
            }

        });

        assertEquals(1, c.get());
    }

    @Test
    public void testOnStartCalledOnceViaUnsafeSubscribe() {
        final AtomicInteger c = new AtomicInteger();
        Flowable.just(1, 2, 3, 4).take(2).subscribe(new DefaultSubscriber<Integer>() {

            @Override
            public void onStart() {
                c.incrementAndGet();
                request(1);
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Integer t) {
                request(1);
            }

        });

        assertEquals(1, c.get());
    }

    @Test
    public void testOnStartCalledOnceViaLift() {
        final AtomicInteger c = new AtomicInteger();
        Flowable.just(1, 2, 3, 4).lift(new FlowableOperator<Integer, Integer>() {

            @Override
            public Subscriber<? super Integer> apply(final Subscriber<? super Integer> child) {
                return new DefaultSubscriber<Integer>() {

                    @Override
                    public void onStart() {
                        c.incrementAndGet();
                        request(1);
                    }

                    @Override
                    public void onComplete() {
                        child.onComplete();
                    }

                    @Override
                    public void onError(Throwable e) {
                        child.onError(e);
                    }

                    @Override
                    public void onNext(Integer t) {
                        child.onNext(t);
                        request(1);
                    }

                };
            }

        }).subscribe();

        assertEquals(1, c.get());
    }

    @Ignore("Non-positive requests are relayed to the plugin and is a no-op otherwise")
    @Test
    public void testNegativeRequestThrowsIllegalArgumentException() throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(1);
        final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
        Flowable.just(1, 2, 3, 4).subscribe(new DefaultSubscriber<Integer>() {

            @Override
            public void onStart() {
                request(1);
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onError(Throwable e) {
               exception.set(e);
               latch.countDown();
            }

            @Override
            public void onNext(Integer t) {
                request(-1);
                request(1);
            }});

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
        Assert.assertTrue(exception.get() instanceof IllegalArgumentException);
    }

    @Test
    public void testOnStartRequestsAreAdditive() {
        final List<Integer> list = new ArrayList<Integer>();
        Flowable.just(1, 2, 3, 4, 5)
        .subscribe(new DefaultSubscriber<Integer>() {
            @Override
            public void onStart() {
                request(3);
                request(2);
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Integer t) {
                list.add(t);
            }});
        assertEquals(Arrays.asList(1, 2, 3, 4, 5), list);
    }

    @Test
    public void testOnStartRequestsAreAdditiveAndOverflowBecomesMaxValue() {
        final List<Integer> list = new ArrayList<Integer>();
        Flowable.just(1, 2, 3, 4, 5).subscribe(new DefaultSubscriber<Integer>() {
            @Override
            public void onStart() {
                request(2);
                request(Long.MAX_VALUE - 1);
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Integer t) {
                list.add(t);
            }});
        assertEquals(Arrays.asList(1, 2, 3, 4, 5), list);
    }

    @Test
    public void forEachWhile() {
        PublishProcessor<Integer> pp = PublishProcessor.create();

        final List<Integer> list = new ArrayList<Integer>();

        Disposable d = pp.forEachWhile(new Predicate<Integer>() {
            @Override
            public boolean test(Integer v) throws Exception {
                list.add(v);
                return v < 3;
            }
        });

        assertFalse(d.isDisposed());

        pp.onNext(1);
        pp.onNext(2);
        pp.onNext(3);

        assertFalse(pp.hasSubscribers());

        assertEquals(Arrays.asList(1, 2, 3), list);
    }

    @Test
    public void doubleSubscribe() {
        ForEachWhileSubscriber<Integer> s = new ForEachWhileSubscriber<Integer>(new Predicate<Integer>() {
            @Override
            public boolean test(Integer v) throws Exception {
                return true;
            }
        }, Functions.<Throwable>emptyConsumer(), Functions.EMPTY_ACTION);

        List<Throwable> list = TestHelper.trackPluginErrors();

        try {
            s.onSubscribe(new BooleanSubscription());

            BooleanSubscription bs = new BooleanSubscription();
            s.onSubscribe(bs);

            assertTrue(bs.isCancelled());

            TestHelper.assertError(list, 0, IllegalStateException.class, "Subscription already set!");
        } finally {
            RxJavaPlugins.reset();
        }
    }

    @Test
    public void suppressAfterCompleteEvents() {
        List<Throwable> errors = TestHelper.trackPluginErrors();
        try {
            final TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
            ts.onSubscribe(new BooleanSubscription());

            ForEachWhileSubscriber<Integer> s = new ForEachWhileSubscriber<Integer>(new Predicate<Integer>() {
                @Override
                public boolean test(Integer v) throws Exception {
                    ts.onNext(v);
                    return true;
                }
            }, new Consumer<Throwable>() {
                @Override
                public void accept(Throwable e) throws Exception {
                    ts.onError(e);
                }
            }, new Action() {
                @Override
                public void run() throws Exception {
                    ts.onComplete();
                }
            });

            s.onComplete();
            s.onNext(1);
            s.onError(new TestException());
            s.onComplete();

            ts.assertResult();

            TestHelper.assertUndeliverable(errors, 0, TestException.class);
        } finally {
            RxJavaPlugins.reset();
        }
    }

    @Test
    public void onNextCrashes() {
        final TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
        ts.onSubscribe(new BooleanSubscription());

        ForEachWhileSubscriber<Integer> s = new ForEachWhileSubscriber<Integer>(new Predicate<Integer>() {
            @Override
            public boolean test(Integer v) throws Exception {
                throw new TestException();
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable e) throws Exception {
                ts.onError(e);
            }
        }, new Action() {
            @Override
            public void run() throws Exception {
                ts.onComplete();
            }
        });

        BooleanSubscription b = new BooleanSubscription();

        s.onSubscribe(b);
        s.onNext(1);

        assertTrue(b.isCancelled());
        ts.assertFailure(TestException.class);
    }

    @Test
    public void onErrorThrows() {
        ForEachWhileSubscriber<Integer> s = new ForEachWhileSubscriber<Integer>(new Predicate<Integer>() {
            @Override
            public boolean test(Integer v) throws Exception {
                return true;
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable e) throws Exception {
                throw new TestException("Inner");
            }
        }, new Action() {
            @Override
            public void run() throws Exception {

            }
        });

        List<Throwable> list = TestHelper.trackPluginErrors();

        try {
            s.onSubscribe(new BooleanSubscription());

            s.onError(new TestException("Outer"));

            TestHelper.assertError(list, 0, CompositeException.class);
            List<Throwable> cel = TestHelper.compositeList(list.get(0));
            TestHelper.assertError(cel, 0, TestException.class, "Outer");
            TestHelper.assertError(cel, 1, TestException.class, "Inner");
        } finally {
            RxJavaPlugins.reset();
        }
    }

    @Test
    public void onCompleteThrows() {
        ForEachWhileSubscriber<Integer> s = new ForEachWhileSubscriber<Integer>(new Predicate<Integer>() {
            @Override
            public boolean test(Integer v) throws Exception {
                return true;
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable e) throws Exception {
            }
        }, new Action() {
            @Override
            public void run() throws Exception {
                throw new TestException("Inner");
            }
        });

        List<Throwable> list = TestHelper.trackPluginErrors();

        try {
            s.onSubscribe(new BooleanSubscription());

            s.onComplete();

            TestHelper.assertUndeliverable(list, 0, TestException.class, "Inner");
        } finally {
            RxJavaPlugins.reset();
        }
    }

    @Test
    public void subscribeConsumerConsumerWithError() {
        final List<Integer> list = new ArrayList<Integer>();

        Flowable.<Integer>error(new TestException()).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer v) throws Exception {
                list.add(v);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable e) throws Exception {
                list.add(100);
            }
        });

        assertEquals(Arrays.asList(100), list);
    }

    @Test
    public void methodTestCancelled() {
        PublishProcessor<Integer> pp = PublishProcessor.create();

        pp.test(Long.MAX_VALUE, true);

        assertFalse(pp.hasSubscribers());
    }

    @Test
    public void safeSubscriberAlreadySafe() {
        TestSubscriber<Integer> ts = new TestSubscriber<Integer>();
        Flowable.just(1).safeSubscribe(new SafeSubscriber<Integer>(ts));

        ts.assertResult(1);
    }

    @Test
    public void methodTestNoCancel() {
        PublishProcessor<Integer> pp = PublishProcessor.create();

        pp.test(Long.MAX_VALUE, false);

        assertTrue(pp.hasSubscribers());
    }

    @Test
    public void subscribeConsumerConsumer() {
        final List<Integer> list = new ArrayList<Integer>();

        Flowable.just(1).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer v) throws Exception {
                list.add(v);
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable e) throws Exception {
                list.add(100);
            }
        });

        assertEquals(Arrays.asList(1), list);
    }

    @SuppressWarnings("rawtypes")
    @Test
    public void pluginNull() {
        RxJavaPlugins.setOnFlowableSubscribe(new BiFunction<Flowable, Subscriber, Subscriber>() {
            @Override
            public Subscriber apply(Flowable a, Subscriber b) throws Exception {
                return null;
            }
        });

        try {
            try {

                Flowable.just(1).test();
                fail("Should have thrown");
            } catch (NullPointerException ex) {
                assertEquals("The RxJavaPlugins.onSubscribe hook returned a null FlowableSubscriber. Please check the handler provided to RxJavaPlugins.setOnFlowableSubscribe for invalid null returns. Further reading: https://github.com/ReactiveX/RxJava/wiki/Plugins", ex.getMessage());
            }
        } finally {
            RxJavaPlugins.reset();
        }
    }

    static final class BadFlowable extends Flowable<Integer> {
        @Override
        protected void subscribeActual(Subscriber<? super Integer> s) {
            throw new IllegalArgumentException();
        }
    }

    @Test
    public void subscribeActualThrows() {
        List<Throwable> list = TestHelper.trackPluginErrors();
        try {
            try {
                new BadFlowable().test();
                fail("Should have thrown!");
            } catch (NullPointerException ex) {
                if (!(ex.getCause() instanceof IllegalArgumentException)) {
                    fail(ex.toString() + ": Should be NPE(IAE)");
                }
            }

            TestHelper.assertError(list, 0, IllegalArgumentException.class);
        } finally {
            RxJavaPlugins.reset();
        }
    }
}


text:
package fr.mncc.gwttoolbox.authenticate.shared;

import com.google.gwtjsonrpc.common.AsyncCallback;

public interface SecureAsyncCallback<T> extends AsyncCallback<T> {

}

redpajama_set_name: RedPajamaGithub


text:
import { Component } from '@angular/core';

@Component({
  selector: 'nav',
  styleUrls: [ 'navbar.scss' ],
  templateUrl: 'navbar.html'
})
export class NavbarComponent {}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GearsAnimationScript : MonoBehaviour {
    public GameObject Gear1;
    public GameObject Gear2;
    public GameObject Gear3;
    public GameObject GearX;

    private Vector3 Gear1_Angle;
    private Vector3 Gear2_Angle;
    private Vector3 Gear3_Angle;
    private Vector3 OldGearXAngle;

    //public GameObject Lens1;
    //public GameObject Lens2;
    public GameObject Particle1;
    public GameObject Particle2;
    public GameObject Particle3;

    private bool flag = false;
    private bool step = false;
    private bool refresh = false;
    private int step_number = 1;
	// Use this for initialization
	void Start () {
        Particle1.SetActive(false);
        Particle2.SetActive(false);
        Particle3.SetActive(false);
    }

	// Update is called once per frame
	void Update () {

        Particle1.SetActive(flag);
        Particle2.SetActive(flag);
        Particle3.SetActive(step);

        if (Input.GetKeyUp("e"))
        {
            if (!refresh)
            {
                StartCoroutine(Count());
                refresh = true;
            }

        }
        if (flag)
        {

            //            Gear1_Angle = new Vector3(
            //    Mathf.LerpAngle(0, 0, Time.deltaTime),
            //    Mathf.LerpAngle(0, 0, Time.deltaTime),
            //    Mathf.LerpAngle(1 * Time.deltaTime * 250, 1 * Time.deltaTime * 250, 1));

            //            Gear2_Angle = new Vector3(
            //Mathf.LerpAngle(0, 0, Time.deltaTime),
            //Mathf.LerpAngle(0, 0, Time.deltaTime),
            //Mathf.LerpAngle(-1 * Time.deltaTime * 400, -1 * Time.deltaTime * 400, 1));

            //            Gear3_Angle = new Vector3(
            //Mathf.LerpAngle(0, 0, Time.deltaTime),
            //Mathf.LerpAngle(-1 * Time.deltaTime * 500, -1 * Time.deltaTime * 500, Time.deltaTime),
            //Mathf.LerpAngle(0, 0, 1));

            //Gear1.transform.eulerAngles = Gear1_Angle;
            //Gear2.transform.eulerAngles = Gear2_Angle;
            //Gear3.transform.eulerAngles = Gear3_Angle;

            Gear1.transform.Rotate(0, 0, 1 * Time.deltaTime * 250);
            Gear2.transform.Rotate(0, 0, -1 * Time.deltaTime * 400);
            Gear3.transform.Rotate(0, 0, -1 * Time.deltaTime * 500);

            //Gear1.transform.rotation = new Quaternion(Gear1.transform.rotation.x, Gear1.transform.rotation.y, 0, 0);
            //Gear2.transform.rotation = new Quaternion(Gear2.transform.rotation.x, Gear2.transform.rotation.y, 0, 0);
            //Gear3.transform.rotation = new Quaternion(Gear3.transform.rotation.x, Gear3.transform.rotation.y, 0, 0);

        }
        if (step)
        {

            GearX.transform.Rotate(0, 0, 1 * Time.deltaTime * 1000);
        }
        //StartCoroutine(RotateGears());
        //Debug.Log(flag);
    }

    IEnumerator PerformStep()
    {

        yield return new WaitForSeconds(0.7f);
        step = true;
        if (step_number == 3)
        {
            step_number = 0;
        }
        else
        {
            step_number += 1;
        }

        //finishedStep = true;
    }

    IEnumerator Count()
    {
        flag = true;

        StartCoroutine(PerformStep());

        yield return new WaitForSeconds(0.878f);

        flag = false;
        step = false;

        //OldGearXAngle = GearX.

        //Gear1.transform.rotation = Quaternion.identity;
        Gear2.transform.rotation = Quaternion.identity;
        GearX.transform.rotation = Quaternion.identity;
        //Gear3.transform.rotation = Quaternion.identity;

        //Gear1.transform.Rotate(new Vector3(0, 180, 0));
        Gear2.transform.Rotate(new Vector3(0, 180, 90));
        GearX.transform.Rotate(new Vector3(0, 180, (90 * step_number) - 45));

        refresh = false;
        //Gear3.transform.Rotate(new Vector3(0, 180, 0));
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">

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

    <title>Introduction to Embedded Systems- Interrupts </title>

    <link href="../../css/bootstrap.min.css" rel="stylesheet">

    <link href="../../css/simple-sidebar.css" rel="stylesheet">
	<link href="../../css/textBodyStyles.css" rel="stylesheet">

 Interrupts

  There are two ways software can check
  for events or input. They are
   Polling Driven Code
  and
   Interrupt Driven Code.

 Polling Driven Code

  Polling code is code that regularly reads the
  status of whatever event it is waiting for,
  usually within an endless loop.

  While this is fine for simple applications,
  it begins to become insufficient when multiple
  inputs need to be handled at the same time.

  The other major downside is the limited
  speed of response polling can provide.
  If a button is pressed, the software will not
  notice the event until the button read
  portion of the loop comes around again.
  In a complex program, this could be hundreds
  of cycles later, which could generate a
  noticeable delay.

 Interrupt Driven Code

  Interrupts are special events that trigger
  the processor to stop running whatever
  code it is currently running, and to
  briefly run a special function called
  an
   Interrupt Service Routine
  (or ISR), instead.
  When the ISR is finished, the processor
  resumes running the code it was running
  before.

  Interrupt triggers can be set up to
  be tied to various kinds of events.
  Change of logic levels on an input pin,
  Timer overflow, completion of a serial
  transmission, and many more.

						&copy 2017


text:
<?xml version="1.0" encoding="utf-8"?>

<!--
   Copyright AllSeen Alliance. All rights reserved.

      Permission to use, copy, modify, and/or distribute this software for any
      purpose with or without fee is hereby granted, provided that the above
      copyright notice and this permission notice appear in all copies.

      THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
      ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
      ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
      OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.^M
 -->

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/about_config_layout"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true"
    >

    <Button
        android:id="@+id/AllJoynConnect"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:text="@string/AllJoynConnect" />

    <include
        android:id="@+id/devices_current_network"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        layout="@layout/current_network_layout"
        android:layout_below="@id/AllJoynConnect" />

    <ListView
        android:id="@+id/device_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/devices_current_network"
        android:layout_marginTop="14dp"
        android:background="@color/background_focused"
        android:cacheColorHint="@color/background_focused"
        android:visibility="visible">
    </ListView>

</RelativeLayout>


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;

//Test for Partial Compaction
//Goals: create fragmentation in Gen2
//Allocation should not be too intense
//For testing the concurrent phase of partial compaction: update references between objects
//What the test does:
// 1.Allocating phase:
//-Allocate n regions
//-When objects get in Gen2 release the objects used to create spaces
//-Create refs from objects in these regions to ephemeral objects
// 2.Steady state
//- randomly change references between objects
//- release some of the existing objects (to create fragmentation in the existing regions)
// Repeat from 1.
namespace PartialCompactionTest
{
    public class PartialCompactionTest
    {

        //Define the size buckets:
        public struct SizeBucket
        {
            public int minsize;
            public int maxsize;
            //public float percentage;  //percentage of objects that fall into this bucket
            public SizeBucket(int min, int max)
            {
                //
                minsize = min;
                maxsize = max;
            }

        }

        //Buckets are defined as following:
        //Bucket1: 17 bytes to 200 bytes
        //Bucket2: 200bytes to 1000 bytes
        //Bucket3: 1000 bytes to 10000 bytes
        //Bucket4: 10000 bytes to 80000 bytes
        //The rest is over 85000 bytes (Large Object Heap)
        private const int SIZEBUCKET_COUNT = 4;
        private const int BUCKET1_MIN = 50;
        private const int BUCKET2_MIN = 200;
        private const int BUCKET3_MIN = 1000;
        private const int BUCKET4_MIN = 10000;
        private const int BUCKETS_MAX = 80000;
        //////

        public const int DEFAULT_ITERATIONS = 100;
        public static int countIters = DEFAULT_ITERATIONS;
        public static long timeout = 600; //seconds
        public static SizeBucket[] sizeBuckets = new SizeBucket[SIZEBUCKET_COUNT];
        public static int randomSeed;

        public static int pointerSize = 4;  //bytes
        [ThreadStatic]
        public static Random Rand;

        public static int threadCount = 1;
        public static bool timeBased = true;
        public static int maxDepth = 10;
        public static int maxHeapMB = 100;  //max heap in MB
        public static long maxAllocation; //bytes
        public static int regionSizeMB = 4; //MB
        public static double EstimatedHeapSize = 0; //bytes
        public static double EstimatedObjectCount = 0; //estimate how many objects we have
        public static double AvgObjectSize = 0; //bytes

        [ThreadStatic]
        public static List<ObjectWrapper> staticArr = new List<ObjectWrapper>(2500);
        [ThreadStatic]
        public static List<Region> regionList = new List<Region>(2500);
        public static int staticIndex = 0;
        public static ObjectWrapper staticObject;

        public static int Main(string[] args)
        {
            if (!ParseArgs(args))
                return 101;

            maxAllocation = maxHeapMB * 1024 * 1024;
            Rand = new Random(randomSeed);
            List<ObjectWrapper> Arr = new List<ObjectWrapper>(2500);

                pointerSize = IntPtr.Size;

            RunTest(Arr);
            GC.KeepAlive(Arr);
            return 100;

        }

        public static void AllocatingPhase(List<ObjectWrapper> Arr, int maxRegions)
        {
            int regionSize = regionSizeMB * 1024 * 1024;
            //decide how many regions to allocate
            long size = maxAllocation - (long)EstimatedHeapSize;
            long regionsToAllocate = size / (long)(regionSize);

            if (regionsToAllocate <= 0)
            {
                System.Threading.Thread.Sleep(1000);
                return;
            }
            if (regionsToAllocate > maxRegions)
                regionsToAllocate = maxRegions;
            Console.WriteLine("Allocating {0} regions", regionsToAllocate);
            for (long i = 0; i < regionsToAllocate; i++)
            {
                int spaceBucket = Rand.Next(0, sizeBuckets.Length);
                int objectBucket = Rand.Next(0, sizeBuckets.Length);
                int pinnedPercentage = 0;
                if (i % 5 == 0)
                    pinnedPercentage = Rand.Next(0, 10);
                Region r = new Region(pinnedPercentage, sizeBuckets[spaceBucket].minsize, sizeBuckets[spaceBucket].maxsize, sizeBuckets[objectBucket].minsize, sizeBuckets[objectBucket].maxsize);
                r.Initialize(Arr);
                regionList.Add(r);
                if (i % 3 == 0 && i > 0)
                    DeleteSpaces();
            }
            DeleteSpaces();
        }

        //want to create fragmentation in Gen2; when objects in the "spaces" list get in gen2, clear the list.
        public static void DeleteSpaces()
        {
            if (regionList.Count == 0)
                return;
            for (int i = regionList.Count - 1; i >= 0; i--)
            {
                if (regionList[i].ClearSpaces())
                {
                    regionList.RemoveAt(i);
                }
            }
        }

        public static void SteadyState(List<ObjectWrapper> Arr)
        {
            Console.WriteLine("Heap size=" + GC.GetTotalMemory(false));
            Console.WriteLine("Estimated Heap size=" + EstimatedHeapSize);
            EstimatedObjectCount = CountTotalObjects(Arr);
            ClearVisitedFlag(Arr);
            Console.WriteLine("Before shuffle:EstimatedObjectCount " + EstimatedObjectCount);
            Console.WriteLine("Heap size=" + GC.GetTotalMemory(false));
            int iterCount = (int)(EstimatedObjectCount / 30);
            Console.WriteLine("Shuffle {0} times", iterCount);
            for (int iter2 = 0; iter2 < iterCount; iter2++)
            {
         //       Console.WriteLine("Shuffle iter " + iter2);
                ShuffleReferences(Arr);
            }
            EstimatedObjectCount = CountTotalObjects(Arr);
            ClearVisitedFlag(Arr);
            Console.WriteLine("After shuffle:EstimatedObjectCount " + EstimatedObjectCount);
            Console.WriteLine("Heap size=" + GC.GetTotalMemory(false));
            EstimatedHeapSize = EstimatedObjectCount * AvgObjectSize;
            Console.WriteLine("Estimated Heap size=" + EstimatedHeapSize);
            //randomly remove some objects

            if (EstimatedObjectCount >100)
                RemoveObjects(Arr);

        }

        public static void ShuffleReferences(List<ObjectWrapper> Arr)
        {
            ClearVisitedFlag(Arr);
            //Console.WriteLine("Shuffle");
            EstimatedObjectCount = CountTotalObjects(Arr);
        //    Console.WriteLine("EstimatedObjectCount " + EstimatedObjectCount);
            int randNumber = Rand.Next(0, (int)EstimatedObjectCount); //Console.WriteLine(randNumber);
            int randNumber2 = Rand.Next(0, (int)EstimatedObjectCount); //Console.WriteLine(randNumber2);
            PickObject(Arr, randNumber);

            ObjectWrapper Object1 = staticObject;
            for (int i = 0; i < Object1.m_data.Length; i++)
            {
                Object1.m_data[i] = (byte)(Object1.m_data[i] + randNumber);
            }
            PickObject(Arr, randNumber2);
            for (int i = 0; i < staticObject.m_data.Length; i++)
            {
                staticObject.m_data[i] = (byte)(staticObject.m_data[i] + randNumber2);
            }

            if (Object1 != null)
            {
                Object1.ref1 = staticObject;
            //    Console.Write("Set ref from {0}", Object1.m_dataSize);
           //     if (staticObject != null)
            //        Console.WriteLine("to " + staticObject.m_dataSize);
            }

        }

        public static void PickObject(List<ObjectWrapper> Arr, int index)
        {
            ClearVisitedFlag(Arr);
            staticObject=null;
            staticIndex = 0;
            for (int i = 0; i < Arr.Count; i++)
            {
                //Console.WriteLine("in Arr, pos=" + i);
                if (staticObject != null)
                    return;
               // Console.WriteLine("now pick object in Arr, pos=" + i);
                 PickObject(Arr[i], index);
            }

            for (int i = 0; i < staticArr.Count; i++)
            {
               // Console.WriteLine("in staticArr, pos=" + i);
                if (staticObject != null)
                    return;
               // Console.WriteLine("now pick object in static Arr, pos=" + i);
                 PickObject(staticArr[i], index);
            }
        }

        public static void PickObject(ObjectWrapper o, int index)
        {
            if (o.visited)
            {
                return;
            }
            o.visited = true;
       //    Console.WriteLine("Try Pick object" + staticIndex);

            if(staticObject != null)
                return;
            if (staticIndex == index)
            {
             //   Console.WriteLine("Object {0}; found for index {1}", o.m_dataSize, staticIndex);
                staticObject = o;
                return;
            }

            staticIndex++;

            if (o.ref1 != null && staticObject == null)
                PickObject(o.ref1, index);
            if (o.ref2 != null && staticObject == null)
                PickObject(o.ref2, index);
            if (o.ref3 != null && staticObject == null)
                PickObject(o.ref3, index);
            if (o.arrayRefs != null && staticObject == null)
            {
                for (int i = 0; i < o.arrayRefs.Length; i++)
                {
                    if (o.arrayRefs[i] != null && staticObject == null)
                        PickObject(o.arrayRefs[i], index);
                }
            }
        }
        public static void RemoveObjects(List<ObjectWrapper> Arr)
        {
            /*
            int CountPinned = CountPinnedObjects(Arr);
            Console.WriteLine("pinned objects, before removing= " + CountPinned);
            int Count = CountTotalObjects(Arr);
            Console.WriteLine("total objects, before removing= " + Count);
            Console.WriteLine("percentage pinned " + (float)CountPinned * 100.0f / (float)Count);
            */
            Console.WriteLine("Removing Objects");
            //Console.WriteLine("before: Arr.Count " + Arr.Count);
            for (int i = Arr.Count - 1; i >= 0; i--)
            {
                if (i % 4 == 0)
                {
                    if (GC.GetGeneration(Arr[i]) == 2)
                    {
                        Arr.RemoveAt(i);
                    }
                }
            }
            //Console.WriteLine("after: Arr.Count" + Arr.Count);
            //Console.WriteLine("before: staticArr.Count " + staticArr.Count);
            for (int j = staticArr.Count - 1; j >= 0; j--)
            {
                if (j % 4 == 0)
                {
                    if (GC.GetGeneration(staticArr[j]) == 2)
                        staticArr.RemoveAt(j);
                }
            }
            //Console.WriteLine("after: staticArr.Count " + staticArr.Count);
            // Console.WriteLine("before: gcHandleArr.Count " + gcHandleArr.Count);

            //Console.WriteLine("before: gcHandleArr.Count " + gcHandleArr.Count);
            //remove weak handles for dead objects

            EstimatedObjectCount = CountTotalObjects(Arr);
            EstimatedHeapSize = EstimatedObjectCount * AvgObjectSize;
            //Console.WriteLine("After removing objects: Estimated Heap size= " + EstimatedHeapSize);
        }

        //estimate the total number of objects in the reference graph
        public static int CountTotalObjects(List<ObjectWrapper> Arr)
        {
            ClearVisitedFlag(Arr);
           // Console.WriteLine("Counting Objects..");
            //use the "visited" table
            int runningCount = 0;

            for (int i = 0; i < Arr.Count; i++)
            {
                runningCount += CountReferences(Arr[i]);
            }

            for (int i = 0; i < staticArr.Count; i++)
            {
                runningCount += CountReferences(staticArr[i]);
            }
           // Console.WriteLine("Counted {0} objects", runningCount);
            return runningCount;
        }

        public static int CountPinnedObjects(List<ObjectWrapper> Arr)
        {
            ClearVisitedFlag(Arr);
            Console.WriteLine("Counting Objects..");
            //use the "visited" table
            int runningCount = 0;

            for (int i = 0; i < Arr.Count; i++)
            {
                runningCount += CountPinnedReferences(Arr[i]);
            }

            for (int i = 0; i < staticArr.Count; i++)
            {
                runningCount += CountPinnedReferences(staticArr[i]);
            }
            Console.WriteLine("Counted {0} objects", runningCount);
            return runningCount;
        }

        public static void ClearVisitedFlag(List<ObjectWrapper> Arr)
        {
           // Console.WriteLine("Clearing flag..");

            for (int i = 0; i < Arr.Count; i++)
            {
                ClearVisitedFlag(Arr[i]);
            }

            for (int i = 0; i < staticArr.Count; i++)
            {
                ClearVisitedFlag(staticArr[i]);
            }
        }

        //counts the refernces of this objects
        public static int CountReferences(ObjectWrapper o)
        {
            if (o.visited)
            {
                return 0;
            }
            else
                o.visited = true; ;
            int count = 1;

            if (o.ref1 != null)
                count+= CountReferences(o.ref1);
            if (o.ref2 != null)
                 count+= CountReferences(o.ref2);
            if (o.ref3 != null)
                count+= CountReferences(o.ref3);
            if (o.arrayRefs != null)
            {
                for (int i = 0; i < o.arrayRefs.Length; i++)
                {
                    if (o.arrayRefs[i] != null)
                    {
                        count += CountReferences(o.arrayRefs[i]);
                    }
                }
            }
            return count;
        }

        public static void ClearVisitedFlag(ObjectWrapper o)
        {
            if (!o.visited)
            {
                return;
            }
            else
                o.visited = false;

            if (o.ref1 != null)
                ClearVisitedFlag(o.ref1);
            if (o.ref2 != null)
                ClearVisitedFlag(o.ref2);
            if (o.ref3 != null)
                ClearVisitedFlag(o.ref3);
            if (o.arrayRefs != null)
            {
                for (int i = 0; i < o.arrayRefs.Length; i++)
                {
                    if (o.arrayRefs[i] != null)
                    {
                        ClearVisitedFlag(o.arrayRefs[i]);
                    }
                }
            }

        }
        //counts the pinned refernces of this objects
        public static int CountPinnedReferences(ObjectWrapper o)
        {
            if (o.visited)
            {
                return 0;
            }
            else
                o.visited=true;
            int count = 0;
            if (o.m_pinned)
                count = 1;

            if (o.ref1 != null)
                count += CountPinnedReferences(o.ref1);
            if (o.ref2 != null)
                count += CountPinnedReferences(o.ref2);
            if (o.ref3 != null)
                count += CountPinnedReferences(o.ref3);
            if (o.arrayRefs != null)
            {
                for (int i = 0; i < o.arrayRefs.Length; i++)
                {
                    if (o.arrayRefs[i] != null)
                    {
                        count += CountPinnedReferences(o.arrayRefs[i]);
                    }
                }
            }
            return count;
        }

        public static void UpdateAvg()
        {
            AvgObjectSize = (double)EstimatedHeapSize / (double)EstimatedObjectCount;
            //Console.WriteLine("Avg object size " + AvgObjectSize);

        }

        public static void AddRef(Object from, Object to)
        {
            Object[] arrFrom = from as Object[];
            for (int i = 0; i < arrFrom.Length; i++)
            {
                if (arrFrom[i] == null)
                {
                    arrFrom[i] = to;
                    break;
                }
            }

        }

        public static void RunTest(List<ObjectWrapper> Arr)
        {
            System.Diagnostics.Stopwatch threadStopwatch = new System.Diagnostics.Stopwatch();
            threadStopwatch.Start();

            int iter = 0;
            while (true)
            {
                Console.WriteLine("Allocating phase. Start at {0}", DateTime.Now);
                AllocatingPhase(Arr, 20);

                Console.WriteLine("starting steady state. Time is {0}", DateTime.Now);
                SteadyState(Arr);
                Console.WriteLine("End steady state. Time is {0}", DateTime.Now);
                iter++;

                if (timeBased)
                {
                    if (threadStopwatch.ElapsedMilliseconds / 1000 > timeout)
                        break;
                }
                else //not timebased
                {
                    if (iter >= countIters)
                        break;
                }
            }

        }

        public static void InitializeSizeBuckets()
        {
            sizeBuckets[0] = new SizeBucket(BUCKET1_MIN, BUCKET2_MIN);
            sizeBuckets[1] = new SizeBucket(BUCKET2_MIN, BUCKET3_MIN);
            sizeBuckets[2] = new SizeBucket(BUCKET3_MIN, BUCKET4_MIN);
            sizeBuckets[3] = new SizeBucket(BUCKET4_MIN, BUCKETS_MAX);
        }
        /// Parse the arguments and also initialize values that are not set by args
        public static bool ParseArgs(string[] args)
        {
            randomSeed = (int)DateTime.Now.Ticks;

            try
            {
                for (int i = 0; i < args.Length; ++i)
                {
                    string currentArg = args[i]; //Console.WriteLine(currentArg);
                    string currentArgValue;
                    if (currentArg.StartsWith("-") || currentArg.StartsWith("/"))
                    {
                        currentArg = currentArg.Substring(1);
                    }
                    else
                    {
                        Console.WriteLine("Error! Unexpected argument {0}", currentArg);
                        return false;
                    }

                    if (currentArg.StartsWith("?"))
                    {
                        Usage();
                        return false;
                    }
                    else if (String.Compare(currentArg.ToLower(), "iter") == 0) // number of iterations
                    {
                        currentArgValue = args[++i];
                        countIters = Int32.Parse(currentArgValue);
                        timeBased = false;
                    }
                    else if (String.Compare(currentArg.ToLower(), "maxheapmb") == 0)
                    {
                        currentArgValue = args[++i];
                        maxHeapMB = Int32.Parse(currentArgValue);
                    }
                    else if (String.Compare(currentArg.ToLower(), "regionsizemb") == 0)
                    {
                        currentArgValue = args[++i];
                        regionSizeMB = Int32.Parse(currentArgValue);
                    }
                    else if (String.Compare(currentArg.ToLower(), "timeout") == 0) //seconds; if 0 run forever
                    {
                        currentArgValue = args[++i];
                        timeout = Int64.Parse(currentArgValue);
                        if (timeout == -1)
                        {
                            timeout = Int64.MaxValue;
                        }
                    }
                    else if (String.Compare(currentArg.ToLower(), "randomseed") == 0) // number of iterations
                    {
                        currentArgValue = args[++i];
                        randomSeed = Int32.Parse(currentArgValue);
                    }
                    else if (String.Compare(currentArg.ToLower(), "depth") == 0) // number of iterations
                    {
                        currentArgValue = args[++i];
                        maxDepth = Int32.Parse(currentArgValue);
                    }
                    else
                    {
                        Console.WriteLine("Error! Unexpected argument {0}", currentArg);
                        return false;
                    }

                }
            }
            catch (System.Exception e)
            {
                Console.WriteLine("Incorrect arguments");
                Console.WriteLine(e.ToString());
                return false;
            }

            //do some basic checking of the arguments
            if (countIters < 1)
            {
                Console.WriteLine("Incorrect values for arguments");
                return false;
            }
            InitializeSizeBuckets();

            Console.WriteLine("Repro with: ");
            Console.WriteLine("==============================");
            if (timeBased)
                Console.WriteLine("-timeout " + timeout);
            else
                Console.WriteLine("-iter " + countIters);
            Console.WriteLine("-maxHeapMB " + maxHeapMB);
            Console.WriteLine("-regionSizeMB " + regionSizeMB);
            Console.WriteLine("-randomseed " + randomSeed);
            Console.WriteLine("-depth " + maxDepth);
            Console.WriteLine("==============================");
            return true;
        }

        public static void Usage()
        {
            Console.WriteLine("ECO1 [options]");
            Console.WriteLine("\nOptions");
            Console.WriteLine("-? Display the usage and exit");
            Console.WriteLine("-iter <num iterations> : specify number of iterations for the test, default is " + countIters);
            Console.WriteLine("If using time based instead of iterations:");
            Console.WriteLine("-timeout <seconds> : when to stop the test, default is " + timeout);
            Console.WriteLine("-maxHeapMB <MB> : max heap size in MB to allocate, default is " + maxHeapMB);
            Console.WriteLine("-regionSizeMB <MB> : regionSize, default is " + regionSizeMB);
            Console.WriteLine("-depth <depth of refernce tree>, default is " + maxDepth);

            Console.WriteLine("-randomseed <seed> : random seed(for repro)");
        }

        public class Region
        {
            public  List<Object> Spaces = new List<Object>(2500);

            public int depth;
            public int size = 0; //bytes
            public float pinnedPercentage;
            public int pinnedCount = 0;
            public int objectCount = 0;
            public int minObjectSize;
            public int maxObjectsize;
            public int minSpaceSize;
            public int maxSpaceSize;

            //create an empty region
            public Region(float pinnedPercentage, int minSpace, int maxSpace, int minObject, int maxObject)
            {
                this.pinnedPercentage = pinnedPercentage;
                minSpaceSize = minSpace;
                maxSpaceSize = maxSpace;
                minObjectSize = minObject;
                maxObjectsize = maxObject;

            }

            //add objects to region
            public void Initialize(List<ObjectWrapper> Arr)
            {
                while (size < regionSizeMB*1024*1024)
                {
                    //create an object with the characteristics(size, pinned) of this region. The object is added either o the static array or to Arr
                    bool useStatic = Rand.Next(0, 2) == 0 ? true : false;

                    if (useStatic)
                        staticArr.Add(ObjectWrapper.AddObject(this, 0, null));
                    else
                        Arr.Add(ObjectWrapper.AddObject(this, 0, null));

                }

                UpdateAvg();
            }

            public bool ClearSpaces()
            {
                if (Spaces.Count <= 0)
                {
                    Console.WriteLine("Spaces.Count <= 0");
                    return false;
                }
                if (GC.GetGeneration(Spaces[Spaces.Count - 1]) == 2)
                {
                    Spaces.Clear();
                    return true;
                }
                return false;
            }

        }

        public class ObjectWrapper
        {
            public bool visited = false;
            public ObjectWrapper parent = null;
            public GCHandle m_pinnedHandle;
            public bool m_pinned = false;
            public ObjectWrapper ref1;
            public ObjectWrapper ref2;
            public ObjectWrapper ref3;
            public byte[] m_data;
            public ObjectWrapper[] arrayRefs = null;
            public int m_dataSize;
            public int depth = 0;

            public static ObjectWrapper AddObject(Region r, int depth, ObjectWrapper Parent)
            {

                if (r.size >= regionSizeMB * 1024 * 1024 || depth>maxDepth)
                    return null;
                byte[] Temp = new byte[Rand.Next(50, 200)];
                int size = Rand.Next(r.minObjectSize, r.maxObjectsize);

                bool pinned = false;
                if ((r.pinnedCount * 100.0 / (double)r.objectCount) < r.pinnedPercentage)
                {
                    pinned = true;
                    r.pinnedCount++;
                }
                int randNumber = Rand.Next(0, 20);
                bool arrayrefs = false;
                if (randNumber == 1)
                    arrayrefs = true;
                int references = Rand.Next(0, 3);
                int arrayrefCount = 0;
                if (arrayrefs)
                {
                    arrayrefCount = Rand.Next(10, 100);
                    references = Rand.Next(3, arrayrefCount);
                }

                ObjectWrapper ow = new ObjectWrapper(size, pinned, references, arrayrefs, arrayrefCount, depth);
                if (randNumber == 7)
                    ow.parent = Parent;

                if (!arrayrefs) //object has up to 3 references to other objects
                {
                    if (references > 0)
                    {
                        ow.ref1 = AddObject(r, ow.depth+1, ow);
                    }
                    if (references > 1)
                    {
                        ow.ref2 = AddObject(r, ow.depth + 1, ow);
                    }
                    if (references > 2)
                    {
                        ow.ref3 = AddObject(r, ow.depth + 1, ow);
                    }
                }
                else  //object has an array of references
                {
                    for (int i = 0; i < arrayrefCount; i++)
                    {
                        ow.arrayRefs[i] = AddObject(r, depth+1, ow);
                    }
                }
                r.size += size;

                int spaceSize = Rand.Next(r.minSpaceSize, r.maxSpaceSize);
                r.Spaces.Add(new byte[spaceSize]);

                r.size += spaceSize;
                r.objectCount++;
                EstimatedObjectCount++;
                EstimatedHeapSize += size;
                return ow;
            }
            public ObjectWrapper(int datasize, bool pinned, int references, bool arrayrefs, int arrayRefCount, int depth)
            {
                this.depth = depth;
                //we want m_data to have an approximate size of dataSize
                m_dataSize = datasize;
                m_pinned = pinned;

                m_data = new byte[datasize];
                for (int i = 0; i < datasize; i++)
                {
                    m_data[i] = (byte)(references - i);
                }
                if(pinned)
                    m_pinnedHandle = GCHandle.Alloc(m_data, GCHandleType.Pinned);

                if (arrayrefs)
                {
                    arrayRefs = new ObjectWrapper[arrayRefCount];
                }

            }
            public void CleanUp()
            {
                if (m_pinned)
                {
                    if (m_pinnedHandle.IsAllocated)
                    {
                        m_pinnedHandle.Free();
                    }
                }
                GC.SuppressFinalize(this);
            }
            ~ObjectWrapper()
            {
                CleanUp();
            }

        }

    }
}


text:
/**
 * Legacy browser implementation of proxy window object to post message to target window
 *
 * @private
 * @constructor
 * @param {string} proxyIFrameUrl - Fully qualified url to proxy iframe, or null to create a receiver only window
 * @param {string} targetWindowName - Name of the proxy iframe window
 */
define( 'WindowProxyLegacy', function ( require ) {
	'use strict';

	var WindowProxyBase = require( 'WindowProxyBase' );
	var Log             = require( 'Log' );
	var WindowProxy     = require( 'WindowProxy' );

	var WindowProxyLegacy = WindowProxyBase.extend({
        init: function(proxyIFrameUrl, targetWindowName) {
            this._super(targetWindowName);

            if (proxyIFrameUrl !== null) {
                this.proxyIFrameName = this.targetWindowName + 'ProxyIFrame';
                this.proxyIFrameLocation = proxyIFrameUrl;

                // Create the proxy iFrame and add to dom
                this.proxyIFrameElement = this.createIFrameProxy();
            } else {
                // Won't be able to send messages
                this.proxyIFrameElement = null;
                Log.trace("proxyIFrameUrl is null, window will be a receiver only");
                this.post = function(){ throw new Error("Receiver only window");};
                //throw  new Error("proxyIFrameUrl can't be null");
            }
        },

        /**
         * Create an iframe and load the proxy
         *
         * @private
         * @returns iframe
         */
        createIFrameProxy: function() {
            var iframe = document.createElement('iframe');

            iframe.setAttribute('id', this.proxyIFrameName);
            iframe.setAttribute('name', this.proxyIFrameName);
            iframe.setAttribute('src', this.proxyIFrameLocation);
            // IE needs this otherwise resize event is not fired
            iframe.setAttribute('frameBorder', '1');
            iframe.setAttribute('scrolling', 'auto');
            // Need a certain size otherwise IE7 does not fire resize event
            iframe.setAttribute('width', 30);
            iframe.setAttribute('height', 30);
            iframe.setAttribute('style', 'position: absolute; left: -100px; top:0px;');
            // IE needs this because setting style attribute is broken. No really.
            if (iframe.style.setAttribute) {
                iframe.style.setAttribute('cssText', 'position: absolute; left: -100px; top:0px;');
            }
            document.body.appendChild(iframe);
            return iframe;
        },

        dispatchMessage: function(message) {
            var encode = window.encodeURIComponent;

            if (this.proxyIFrameElement) {
                var src = this.proxyIFrameLocation + '#' + encode(WindowProxy.serialize(message));
                this.proxyIFrameElement.setAttribute('src', src);
                this.proxyIFrameElement.height = this.proxyIFrameElement.height > 50 ? 50 : 100;
            }
        }
    });

	return WindowProxyLegacy;
} );


text:
package com.skcraft.plume.asm.util;

import net.minecraft.launchwrapper.Launch;

import java.util.HashMap;
import java.util.Map;

public final class ObfMappings {

    private static final Map<String, String> mappings = new HashMap<>();
    private static final boolean devEnvironment = (Boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment");

    public static String get(String key) {
        return devEnvironment ? key : mappings.get(key);
    }

    static {
        mappings.put("net/minecraft/server/network/NetHandlerLoginServer", "nn");
        mappings.put("net/minecraft/server/network/NetHandlerLoginServer$1", "no");
        mappings.put("net/minecraft/network/NetHandlerPlayServer", "nh");
        mappings.put("uncheckedTryHarvestBlock", "a");
    }
}


text:
/**
 * Created by jonas on 25/10/16.
 */

import {Injectable} from "@angular/core";

@Injectable()
export class ProductService {
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Var</title>

If there are <var>n</var> pipes leading to the ice
    cream factory then I expect at least <var>n</var>
    flavors of ice cream to be available for purchase!


text:
function [Psi, Stats, RhoTerms] = sampleUniqueFeats( Psi, data, algParams, doZMove, objIDs )
% Sample *unique* features for each time series,
%   using reversible jump moves that propose adding/deleting unique feat.
%   from each sequence.
% The proposal distribution for reversible jump is defined in "algParams'
%   can be any of:
%      'prior'  : emit param thetaStar drawn from prior
%      'data-driven' : emit param thetaStar draw from data posterior
%OUTPUT
%  Psi : resulting model config
%  Stats : struct that summarizes reversible jump performance
%           counts # birth (ADD) and death (DEL) attempts and acceptances

if ~exist( 'objIDs', 'var')
    objIDs = 1:data.N;
end

Stats.ADD.nAccept = 0;
Stats.ADD.nTotal = 0;
Stats.DEL.nAccept = 0;
Stats.DEL.nTotal = 0;

for ii = objIDs
    if doZMove
        [Psi, RhoTerms] = sampleSingleFeat_UniqueRJStateSeq( ii, Psi, data, algParams );
    else
        [Psi, RhoTerms] = sampleSingleFeatEntry_UniqueRJ( ii, Psi, data, algParams );
    end

    if RhoTerms.doBirth
        Stats.ADD.nTotal = Stats.ADD.nTotal+1;
        if RhoTerms.doAccept;
            Stats.ADD.nAccept = Stats.ADD.nAccept+1;
        end

    else
        Stats.DEL.nTotal = Stats.DEL.nTotal+1;
        if RhoTerms.doAccept;
            Stats.DEL.nAccept = Stats.DEL.nAccept+1;
        end
    end
end


text:
HAT:this file will have a extends dependency on the
ext.ends(abra.cad.abra.Hat, abra.cad.abra.open.sesame.Genie)

and will

force.load("something.else.Entirely")

include(something.else.Entirely)


text:
package org.hl7.v3;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="POCD_MT000040.Criterion", propOrder={"realmCode", "typeId", "templateId", "code", "text", "value"})
public class POCDMT000040Criterion
{
  protected List<CS> realmCode;
  protected POCDMT000040InfrastructureRootTypeId typeId;
  protected List<II> templateId;
  protected CD code;
  protected ED text;
  protected ANY value;

  @XmlAttribute(name="nullFlavor")
  protected List<String> nullFlavor;

  @XmlAttribute(name="classCode")
  protected List<String> classCode;

  @XmlAttribute(name="moodCode")
  protected List<String> moodCode;

  public List<CS> getRealmCode()
  {
    if (this.realmCode == null) {
      this.realmCode = new ArrayList();
    }
    return this.realmCode;
  }

  public POCDMT000040InfrastructureRootTypeId getTypeId()
  {
    return this.typeId;
  }

  public void setTypeId(POCDMT000040InfrastructureRootTypeId value)
  {
    this.typeId = value;
  }

  public List<II> getTemplateId()
  {
    if (this.templateId == null) {
      this.templateId = new ArrayList();
    }
    return this.templateId;
  }

  public CD getCode()
  {
    return this.code;
  }

  public void setCode(CD value)
  {
    this.code = value;
  }

  public ED getText()
  {
    return this.text;
  }

  public void setText(ED value)
  {
    this.text = value;
  }

  public ANY getValue()
  {
    return this.value;
  }

  public void setValue(ANY value)
  {
    this.value = value;
  }

  public List<String> getNullFlavor()
  {
    if (this.nullFlavor == null) {
      this.nullFlavor = new ArrayList();
    }
    return this.nullFlavor;
  }

  public List<String> getClassCode()
  {
    if (this.classCode == null) {
      this.classCode = new ArrayList();
    }
    return this.classCode;
  }

  public List<String> getMoodCode()
  {
    if (this.moodCode == null) {
      this.moodCode = new ArrayList();
    }
    return this.moodCode;
  }
}


text:
package org.wso2.esb.integration.services.jaxrs.musicsample;

import org.springframework.stereotype.Service;
import org.wso2.esb.integration.services.jaxrs.musicsample.bean.Music;
import org.wso2.esb.integration.services.jaxrs.musicsample.bean.Singer;

import java.util.concurrent.ConcurrentHashMap;

@Service
public class MusicService {

    private final ConcurrentHashMap< String, Music> musicCollection = new ConcurrentHashMap< String, Music>();
    private final ConcurrentHashMap< String,Singer> singerCollection = new ConcurrentHashMap< String, Singer >();

    public MusicService() {
        init();
    }

    final void init() {
        System.out.println("Welcome To The World Of Music .... ");

        Music music = new Music();
        music.setAlbum("Gold");
        music.setSinger("Elton John");
        musicCollection.put(music.getAlbum(), music);

        Music music2 = new Music();
        music2.setAlbum("THE ENDLESS RIVER");
        music2.setSinger("UB40");
        musicCollection.put(music2.getAlbum(), music2);

        Singer singer = new Singer();
        singer.setName("Eric Clapton");
        singer.setAge(45);
        singerCollection.put(singer.getName(),singer);
    }

    public Music getByAlbum( final String albumName ) {

        return musicCollection.get(albumName);
    }

    public void setMusic(Music music ) {

        musicCollection.put(music.getAlbum(),music);
    }

    public Singer getBySinger( final String singer ) {

        return singerCollection.get(singer);
    }

    public void setSinger(Singer singer ) {

        singerCollection.put(singer.getName(),singer);
    }
}


text:
from sdk.utils import load_class
from sdk.reply import REPLY_CATEGORY, REPLY_PASSIVE_TYPE, REPLY_SERVICE_TYPE

class WXMPReplyFactory(object):
    def __init__(self, recv, category, type):
        self.recv = recv
        self.category = category
        self.type = type

    def get_class(self):
        module_path = "sdk.reply.{0}.{1}".format(self.category, self.type)
        class_name = "WXMP{0}Reply{1}".format(self.category.title(), self.type.title())
        try:
            cls = load_class(module_path, class_name)
        except Exception,e:
            raise Exception("Failed to load class:%s from:%s" % (class_name, module_path))

        return cls

    def create(self, **kwargs):
        klass = self.get_class()
        instance = klass(self.recv)
        if not instance.validate(kwargs):
            return ""

        instance.assembly(kwargs)
        return instance

class WXMPReplyShortcut(object):
    def __init__(self, recv):
        self.recv = recv

    def get_factory(self, category, type):
        return WXMPReplyFactory(self.recv, category, type)

    def createPassiveText(self, content):
        kwargs = {'content': content}
        return self.get_factory(REPLY_CATEGORY.PASSIVE, REPLY_PASSIVE_TYPE.TEXT).create(**kwargs)

    def createPassiveImage(self, media_id):
        kwargs = {'media_id': media_id}
        return self.get_factory(REPLY_CATEGORY.PASSIVE, REPLY_PASSIVE_TYPE.IMAGE).create(**kwargs)

    def createPassiveMusic(self, media_id, title='', description='', music_url='#', hq_music_url=''):
        kwargs = {'media_id': media_id, 'title':title, 'description': description,
                  'music_url': music_url, 'hq_music_url': hq_music_url}
        return self.get_factory(REPLY_CATEGORY.PASSIVE, REPLY_PASSIVE_TYPE.MUSIC).create(**kwargs)

    def createPassiveVideo(self, media_id, title='', description=''):
        kwargs = {'media_id': media_id, 'title':title, 'description': description}
        return self.get_factory(REPLY_CATEGORY.PASSIVE, REPLY_PASSIVE_TYPE.VIDEO).create(**kwargs)

    def createPassiveVoice(self, media_id):
        kwargs = {'media_id': media_id}
        return self.get_factory(REPLY_CATEGORY.PASSIVE, REPLY_PASSIVE_TYPE.VOICE).create(**kwargs)

    def createPassiveNews(self, articles):
        kwargs = {'articles': articles}
        return self.get_factory(REPLY_CATEGORY.PASSIVE, REPLY_PASSIVE_TYPE.NEWS).create(**kwargs)

    def createServiceText(self, content):
        kwargs = {'content': content}
        return self.get_factory(REPLY_CATEGORY.SERVICE, REPLY_SERVICE_TYPE.TEXT).create(**kwargs)


text:
import { Component } from '@angular/core';
import {
  IonicPage,
  NavParams,
  ViewController
} from 'ionic-angular';

/**
* About page.
*
*/

@IonicPage()
@Component({
  selector: 'page-about',
  templateUrl: 'about.html'
})
export class AboutPage {
  private bgService: any;

  constructor(private viewCtrl: ViewController, private navParams: NavParams) {
    this.bgService = this.navParams.get('bgService');
  }

  ionViewDidLoad() {
    this.bgService.playSound("FLOURISH");

    console.log('ionViewDidLoad AboutPage');
  }

  onClickClose() {
    this.bgService.playSound("CLOSE");
    this.viewCtrl.dismiss();
  }
}


text:
package io.hosuaby.restful.controllers;

import io.hosuaby.restful.PortHolder;
import io.hosuaby.restful.domain.Teapot;
import io.hosuaby.restful.services.TeapotCrudService;
import io.hosuaby.restful.services.TeapotCommandService;
import io.hosuaby.restful.services.exceptions.teapots.TeapotNotConnectedException;
import io.hosuaby.restful.services.exceptions.teapots.TeapotNotExistsException;
import io.hosuaby.restful.simulators.TeapotSimulator;

import java.io.IOException;
import java.net.URISyntaxException;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.DeploymentException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

/**
 * API to send commands to teapots.
 */
// TODO: develop this controller
@RestController
@RequestMapping("/actions/teapots")
public class TeapotCommandController {

    /** Teapot CRUD service */
    @Autowired
    private TeapotCrudService crud;

    /** Teapot command service */
    @Autowired
    private TeapotCommandService commandService;

    /** Port holder */
    @Autowired
    private PortHolder portHolder;

    @RequestMapping(
            value = "/{id}/startup",
            method = RequestMethod.POST)
    public void startup(@PathVariable String id)
            throws TeapotNotExistsException, URISyntaxException,
                DeploymentException, IOException {

        /* Get teapot */
        Teapot teapot = crud.find(id);

        /* Start teapot simulator */
        TeapotSimulator simulator = new TeapotSimulator(
                teapot, portHolder.getPort());
    }

    @RequestMapping(
            value = "/{id}/shutdown",
            method = RequestMethod.POST)
    public void shutdown(@PathVariable String id)
            throws IOException, TeapotNotConnectedException {
        commandService.shutdown(id);
    }

    @RequestMapping(
            value = "/{teapotId}/cli",
            method = RequestMethod.POST)
    public DeferredResult<String> executeCommand(
            @PathVariable String teapotId,
            @RequestParam(required = true) String cmd,
            HttpServletRequest req) throws IOException {
        return commandService.sendMessage(req, teapotId, cmd);
    }

}


text:
// Copyright (c) 2016 Schneider-Electric
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SchneiderElectric.UnityComments
{
    public interface IUnityApplicationComments
    {
        #region properties
        /// <summary>
        /// Gets the comments.
        /// </summary>
        /// <value>
        /// The comments.
        /// </value>
        List<Comment> Comments { get; }
        /// <summary>
        /// Gets the source.
        /// </summary>
        /// <value>
        /// The source.
        /// </value>
        string Source { get; }
        #endregion

        #region method
        /// <summary>
        /// Writes the target.
        /// </summary>
        /// <param name="targetPath">The target path.</param>
        /// <returns></returns>
        bool WriteTarget(string targetPath);
        /// <summary>
        /// Reads the source.
        /// </summary>
        /// <param name="sourcePath">The source path.</param>
        /// <returns></returns>
        bool ReadSource(string sourcePath );
        /// <summary>
        /// Saves the XML.
        /// </summary>
        /// <param name="path">The path.</param>
        void SaveXml(string path);
        #endregion

        #region automatic translation
        /// <summary>
        /// Detects the language.
        /// </summary>
        /// <returns></returns>
        string DetectLanguage();
        /// <summary>
        /// Translates the comments.
        /// </summary>
        /// <param name="destlang">The destlang.</param>
        /// <param name="sourceLang">The source language.</param>
        /// <param name="eraseExisting">if set to <c>true</c> [erase existing].</param>
        /// <returns></returns>
        Task TranslateComments(string destlang = "fr", string sourceLang = "en", bool eraseExisting = false);
        #endregion
    }

}


text:
'use strict';var CASE_CHANGE_COST=1;var INSERTION_COST=10;var DELETION_COST=10;var SWAP_COST=10;var SUBSTITUTION_COST=20;var MAX_EDIT_DISTANCE=40;var distance=exports.distance=function(wordi,wordj){var wordiLen=wordi.length;var wordjLen=wordj.length;var row0=new Array(wordiLen+1);var row1=new Array(wordiLen+1);var row2=new Array(wordiLen+1);var tmp;var i,j;
for(i=0;i<=wordiLen;i++){row1[i]=i*INSERTION_COST;}
for(j=1;j<=wordjLen;j++){
row0[0]=j*INSERTION_COST;for(i=1;i<=wordiLen;i++){

var dc=row0[i-1]+DELETION_COST;var ic=row1[i]+INSERTION_COST;var sc0;if(wordi[i-1]===wordj[j-1]){sc0=0;}
else{if(wordi[i-1].toLowerCase()===wordj[j-1].toLowerCase()){sc0=CASE_CHANGE_COST;}
else{sc0=SUBSTITUTION_COST;}}
var sc=row1[i-1]+sc0;row0[i]=Math.min(dc,ic,sc);
if(i>1&&j>1&&wordi[i-1]===wordj[j-2]&&wordj[j-1]===wordi[i-2]){row0[i]=Math.min(row0[i],row2[i-2]+SWAP_COST);}}
tmp=row2;row2=row1;row1=row0;row0=tmp;}
return row1[wordiLen];};var distancePrefix=exports.distancePrefix=function(word,name){var dist=0;for(var i=0;i<word.length;i++){if(name[i]!==word[i]){if(name[i].toLowerCase()===word[i].toLowerCase()){dist++;}
else{
 return exports.distance(word,name);}}}
return dist;};exports.correct=function(word,names){if(names.length===0){return undefined;}
var distances={};var sortedCandidates;names.forEach(function(candidate){distances[candidate]=exports.distance(word,candidate);});sortedCandidates=names.sort(function(worda,wordb){if(distances[worda]!==distances[wordb]){return distances[worda]-distances[wordb];}
else{
 return worda<wordb;}});if(distances[sortedCandidates[0]]<=MAX_EDIT_DISTANCE){return sortedCandidates[0];}
else{return undefined;}};exports.rank=function(word,names,options){options=options||{};var reply=names.map(function(name){
 var algo=options.prefixZero?distancePrefix:distance;return{name:name,dist:algo(word,name)};});if(!options.noSort){reply=reply.sort(function(d1,d2){return d1.dist-d2.dist;});}
return reply;};


text:
package org.mifos.application.master.persistence;

import java.util.List;

import junit.framework.Assert;

import org.mifos.application.master.business.CustomValueList;
import org.mifos.application.master.business.CustomValueListElement;
import org.mifos.application.master.business.LookUpValueLocaleEntity;
import org.mifos.application.master.business.MasterDataEntity;
import org.mifos.application.master.business.ValueListElement;
import org.mifos.application.master.util.helpers.MasterConstants;
import org.mifos.application.util.helpers.EntityType;
import org.mifos.config.LocalizedTextLookup;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.exceptions.ApplicationException;
import org.mifos.framework.exceptions.PersistenceException;
import org.mifos.framework.exceptions.SystemException;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.framework.security.activity.DynamicLookUpValueCreationTypes;
import org.mifos.framework.util.helpers.TestObjectFactory;

public class MasterPersistenceIntegrationTest extends MifosIntegrationTestCase {
    public MasterPersistenceIntegrationTest() throws SystemException, ApplicationException {
        super();
    }

    final private static short DEFAULT_LOCALE = (short) 1;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
    }

    @Override
    public void tearDown() throws Exception {
        StaticHibernateUtil.closeSession();
        super.tearDown();
    }

    public void testEntityMasterRetrieval() throws Exception {
        MasterPersistence masterPersistence = new MasterPersistence();
        CustomValueList paymentTypes = masterPersistence.getCustomValueList(MasterConstants.ATTENDENCETYPES,
                "org.mifos.application.master.business.CustomerAttendanceType", "attendanceId");
        List<CustomValueListElement> paymentValues = paymentTypes.getCustomValueListElements();
       Assert.assertEquals(4, paymentValues.size());

    }

    public void testEntityMasterRetrievalForInvalidConnection() throws Exception {
        MasterPersistence masterPersistence = new MasterPersistence();
        TestObjectFactory.simulateInvalidConnection();
        try {
            masterPersistence.getCustomValueList(MasterConstants.ATTENDENCETYPES,
                    "org.mifos.application.master.business.CustomerAttendanceType", "attendanceId");
            Assert.fail();
        } catch (Exception e) {
           Assert.assertTrue(true);
        } finally {
            StaticHibernateUtil.closeSession();
        }
    }

    public void testGetLookUpEntity() throws Exception {
        MasterPersistence masterPersistence = new MasterPersistence();
        CustomValueList gender = masterPersistence.getLookUpEntity(MasterConstants.GENDER, Short.valueOf("1"));
        List<CustomValueListElement> genderValues = gender.getCustomValueListElements();
       Assert.assertEquals(2, genderValues.size());

    }

    public void testRetrieveMasterEntities() throws NumberFormatException, PersistenceException {
        MasterPersistence masterPersistence = new MasterPersistence();
        List<ValueListElement> masterEntity = masterPersistence.retrieveMasterEntities(MasterConstants.LOAN_PURPOSES,
                Short.valueOf("1"));
        // 131 if includes the empty lookup_name for lookup id 259, 263
       Assert.assertEquals(131, masterEntity.size());
    }

    public void testRetrieveMasterEntitiesForInvalidConnection() throws Exception {
        MasterPersistence masterPersistence = new MasterPersistence();
        TestObjectFactory.simulateInvalidConnection();
        try {
            masterPersistence.retrieveMasterEntities(MasterConstants.LOAN_PURPOSES, Short.valueOf("1"));
            Assert.fail();
        } catch (Exception e) {
           Assert.assertTrue(true);
        } finally {
            StaticHibernateUtil.closeSession();
        }
    }

    public void retrieveCustomFieldsDefinitionForInvalidConnection() throws Exception {
        MasterPersistence masterPersistence = new MasterPersistence();
        TestObjectFactory.simulateInvalidConnection();
        try {
            masterPersistence.retrieveCustomFieldsDefinition(EntityType.CLIENT);
            Assert.fail();
        } catch (Exception e) {
           Assert.assertTrue(true);
        } finally {
            StaticHibernateUtil.closeSession();
        }
    }

    public void testGetMasterEntityName() throws NumberFormatException, PersistenceException {
        MasterPersistence masterPersistence = new MasterPersistence();
       Assert.assertEquals("Partial Application", masterPersistence.retrieveMasterEntities(1, Short.valueOf("1")));
    }

    public void testRetrieveMasterDataEntity() throws Exception {
        MasterPersistence masterPersistence = new MasterPersistence();
        List<MasterDataEntity> masterDataList = masterPersistence
                .retrieveMasterDataEntity("org.mifos.application.accounts.business.AccountStateEntity");
       Assert.assertEquals(18, masterDataList.size());
        for (MasterDataEntity masterDataEntity : masterDataList) {
            for (LookUpValueLocaleEntity lookUpValueLocaleEntity : masterDataEntity.getLookUpValue()
                    .getLookUpValueLocales()) {
               Assert.assertEquals(Short.valueOf("1"), lookUpValueLocaleEntity.getLocaleId());
            }
        }
    }

    public void testRetrieveMasterDataEntityForInvalidConnection() throws Exception {
        MasterPersistence masterPersistence = new MasterPersistence();
        TestObjectFactory.simulateInvalidConnection();
        try {
            masterPersistence.retrieveMasterDataEntity("org.mifos.application.accounts.business.AccountStateEntity");
            Assert.fail();
        } catch (Exception e) {
           Assert.assertTrue(true);
        } finally {
            StaticHibernateUtil.closeSession();
        }
    }

    private boolean foundStringInCustomValueList(final MasterPersistence masterPersistence, final String CustomValueListName,
            final String searchString, final short localId) throws PersistenceException {
        List<ValueListElement> salutations = masterPersistence.retrieveMasterEntities(CustomValueListName, localId);
        boolean foundString = false;
        for (ValueListElement entity : salutations) {
            if (entity.getName().compareTo(searchString) == 0) {
                foundString = true;
            }
        }
        return foundString;
    }

    private Integer findValueListElementId(final MasterPersistence masterPersistence, final String CustomValueListName,
            final String searchString, final short localId) throws PersistenceException {
        List<ValueListElement> salutations = masterPersistence.retrieveMasterEntities(CustomValueListName, localId);
        Integer elementId = null;
        for (ValueListElement entity : salutations) {
            if (entity.getName().compareTo(searchString) == 0) {
                elementId = entity.getId();
            }
        }
        return elementId;
    }

    public void testAddAndDeleteValueListElement() throws Exception {
        // get the CustomValueList that we want to add to
        MasterPersistence masterPersistence = new MasterPersistence();
        CustomValueList salutationValueList = masterPersistence.getLookUpEntity(MasterConstants.SALUTATION,
                DEFAULT_LOCALE);

        // add a CustomValueListElement to the list
        final String NEW_SALUTATION_STRING = "Sir";
        LocalizedTextLookup lookupValueEntity = masterPersistence.addValueListElementForLocale(
                DynamicLookUpValueCreationTypes.LookUpOption, salutationValueList.getEntityId(), NEW_SALUTATION_STRING);
        StaticHibernateUtil.commitTransaction();
        StaticHibernateUtil.flushAndCloseSession();

        // verify that the new salutation was created
        Integer newSalutationId = findValueListElementId(masterPersistence, MasterConstants.SALUTATION,
                NEW_SALUTATION_STRING, DEFAULT_LOCALE);
       Assert.assertTrue(newSalutationId != null);

        // remove the new salutation
        masterPersistence.deleteValueListElement(newSalutationId);
        StaticHibernateUtil.commitTransaction();
        StaticHibernateUtil.flushAndCloseSession();

        // verify that the new salutation was deleted
        Assert.assertFalse(foundStringInCustomValueList(masterPersistence, MasterConstants.SALUTATION, NEW_SALUTATION_STRING,
                DEFAULT_LOCALE));
    }

    public void testUpdateValueListElement() throws Exception {
        // get a CustomValueListElement (as a BusinessActivityEntity)
        MasterPersistence masterPersistence = new MasterPersistence();
        List<ValueListElement> salutations = masterPersistence.retrieveMasterEntities(MasterConstants.SALUTATION,
                DEFAULT_LOCALE);
        ValueListElement first = salutations.get(0);
        Integer id = first.getId();
        String originalName = first.getName();

        // update it
        final String UPDATED_NAME = "Mister";
        first.setName(UPDATED_NAME);

        // save it
        masterPersistence.updateValueListElementForLocale(id, UPDATED_NAME);
        StaticHibernateUtil.commitTransaction();

        // get the element back
        // and verify that it has the new value
        salutations.clear();
        salutations = masterPersistence.retrieveMasterEntities(MasterConstants.SALUTATION, DEFAULT_LOCALE);
        for (ValueListElement entity : salutations) {
            if (entity.getId() == id) {
               Assert.assertEquals(entity.getName(), UPDATED_NAME);
            }
        }
        // restore it
        masterPersistence.updateValueListElementForLocale(id, originalName);
        StaticHibernateUtil.commitTransaction();

    }

}