text:
package com.carrotsearch.hppc;

import static com.carrotsearch.hppc.TestUtils.*;

import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;

import org.assertj.core.api.Assertions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.carrotsearch.hppc.cursors.KTypeCursor;
import com.carrotsearch.hppc.predicates.KTypePredicate;
import com.carrotsearch.hppc.procedures.KTypeProcedure;

/**
 * Unit tests for {@link KTypeArrayList}.
 */
/*! ${TemplateOptions.generatedAnnotation} !*/
public class KTypeArrayListTest<KType> extends AbstractKTypeTest<KType>
{
    /**
     * Per-test fresh initialized instance.
     */
    public KTypeArrayList<KType> list;

    /* */
    @Before
    public void initialize()
    {
        list = new KTypeArrayList<>();
    }

    @After
    public void checkTrailingSpaceUninitialized()
    {
        if (list != null)
        {
            for (int i = list.elementsCount; i < list.buffer.length; i++)
                assertTrue(Intrinsics.<KType> empty() == list.buffer[i]);
        }
    }

    /* */
    @Test
    public void testInitiallyEmpty()
    {
        assertEquals(0, list.size());
    }

    /* */
    @Test
    public void testAdd()
    {
        list.add(key1, key2);
        assertListEquals(list.toArray(), 1, 2);
    }

    /* */
    @Test
    public void testAddTwoArgs()
    {
        list.add(key1, key2);
        list.add(key3, key4);
        assertListEquals(list.toArray(), 1, 2, 3, 4);
    }

    /* */
    @Test
    public void testAddArray()
    {
        list.add(asArray(0, 1, 2, 3), 1, 2);
        assertListEquals(list.toArray(), 1, 2);
    }

    /* */
    @Test
    public void testAddVarArg()
    {
        list.add(asArray(0, 1, 2, 3));
        list.add(key4, key5, key6, key7);
        assertListEquals(list.toArray(), 0, 1, 2, 3, 4, 5, 6, 7);
    }

    /* */
    @Test
    public void testAddAll()
    {
        KTypeArrayList<KType> list2 = new KTypeArrayList<>();
        list2.add(asArray(0, 1, 2));

        list.addAll(list2);
        list.addAll(list2);

        assertListEquals(list.toArray(), 0, 1, 2, 0, 1, 2);
    }

    /* */
    @Test
    public void testInsert()
    {
        list.insert(0, k1);
        list.insert(0, k2);
        list.insert(2, k3);
        list.insert(1, k4);

        assertListEquals(list.toArray(), 2, 4, 1, 3);
    }

    /* */
    @Test
    public void testSet()
    {
        list.add(asArray(0, 1, 2));

        assertEquals2(0, list.set(0, k3));
        assertEquals2(1, list.set(1, k4));
        assertEquals2(2, list.set(2, k5));

        assertListEquals(list.toArray(), 3, 4, 5);
    }

    /* */
    @Test
    public void testRemove()
    {
        list.add(asArray(0, 1, 2, 3, 4));

        list.remove(0);
        list.remove(2);
        list.remove(1);

        assertListEquals(list.toArray(), 1, 4);
    }

    /* */
    @Test
    public void testRemoveRange()
    {
        list.add(asArray(0, 1, 2, 3, 4));

        list.removeRange(0, 2);
        assertListEquals(list.toArray(), 2, 3, 4);

        list.removeRange(2, 3);
        assertListEquals(list.toArray(), 2, 3);

        list.removeRange(1, 1);
        assertListEquals(list.toArray(), 2, 3);

        list.removeRange(0, 1);
        assertListEquals(list.toArray(), 3);
    }

    /* */
    @Test
    public void testRemoveFirstLast()
    {
        list.add(asArray(0, 1, 2, 1, 0));

        assertEquals(-1, list.removeFirst(k5));
        assertEquals(-1, list.removeLast(k5));
        assertListEquals(list.toArray(), 0, 1, 2, 1, 0);

        assertEquals(1, list.removeFirst(k1));
        assertListEquals(list.toArray(), 0, 2, 1, 0);
        assertEquals(3, list.removeLast(k0));
        assertListEquals(list.toArray(), 0, 2, 1);
        assertEquals(0, list.removeLast(k0));
        assertListEquals(list.toArray(), 2, 1);
        assertEquals(-1, list.removeLast(k0));

        /*! #if ($TemplateOptions.KTypeGeneric) !*/
        list.clear();
        list.add(newArray(k0, null, k2, null, k0));
        assertEquals(1, list.removeFirst(null));
        assertEquals(2, list.removeLast(null));
        assertListEquals(list.toArray(), 0, 2, 0);
        /*! #end !*/
    }

    /* */
    @Test
    public void testRemoveAll()
    {
        list.add(asArray(0, 1, 0, 1, 0));

        assertEquals(0, list.removeAll(k2));
        assertEquals(3, list.removeAll(k0));
        assertListEquals(list.toArray(), 1, 1);

        assertEquals(2, list.removeAll(k1));
        assertTrue(list.isEmpty());

        /*! #if ($TemplateOptions.KTypeGeneric) !*/
        list.clear();
        list.add(newArray(k0, null, k2, null, k0));
        assertEquals(2, list.removeAll((KType) null));
        assertEquals(0, list.removeAll((KType) null));
        assertListEquals(list.toArray(), 0, 2, 0);
        /*! #end !*/
    }

    /* */
    @Test
    public void testRemoveAllFromLookupContainer()
    {
        list.add(asArray(0, 1, 2, 1, 0));

        KTypeHashSet<KType> list2 = new KTypeHashSet<>();
        list2.addAll(asArray(0, 2));

        assertEquals(3, list.removeAll(list2));
        assertEquals(0, list.removeAll(list2));

        assertListEquals(list.toArray(), 1, 1);
    }

    /* */
    @Test
    public void testRemoveAllWithPredicate()
    {
        list.add(newArray(k0, k1, k2, k1, k4));

        assertEquals(3, list.removeAll(new KTypePredicate<KType>()
        {
            public boolean apply(KType v)
            {
                return v == key1 || v == key2;
            };
        }));

        assertListEquals(list.toArray(), 0, 4);
    }

    /* */
    @Test
    public void testRetainAllWithPredicate()
    {
        list.add(newArray(k0, k1, k2, k1, k0));

        assertEquals(2, list.retainAll(new KTypePredicate<KType>()
        {
            public boolean apply(KType v)
            {
                return v == key1 || v == key2;
            };
        }));

        assertListEquals(list.toArray(), 1, 2, 1);
    }

    /* */
    @Test
    public void testRemoveAllWithPredicateInterrupted()
    {
        list.add(newArray(k0, k1, k2, k1, k4));

        final RuntimeException t = new RuntimeException();
        try
        {
            assertEquals(3, list.removeAll(new KTypePredicate<KType>()
            {
                public boolean apply(KType v)
                {
                    if (v == key2) throw t;
                    return v == key1;
                };
            }));
            fail();
        }
        catch (RuntimeException e)
        {
            // Make sure it's really our exception...
            if (e != t) throw e;
        }

        // And check if the list is in consistent state.
        assertListEquals(list.toArray(), 0, key2, key1, 4);
        assertEquals(4, list.size());
    }

    /* */
    @Test
    public void testIndexOf()
    {
        list.add(asArray(0, 1, 2, 1, 0));

        /*! #if ($TemplateOptions.KTypeGeneric) !*/
        list.add((KType) null);
        assertEquals(5, list.indexOf(null));
        /*! #end !*/

        assertEquals(0, list.indexOf(k0));
        assertEquals(-1, list.indexOf(k3));
        assertEquals(2, list.indexOf(k2));
    }

    /* */
    @Test
    public void testLastIndexOf()
    {
        list.add(asArray(0, 1, 2, 1, 0));

        /*! #if ($TemplateOptions.KTypeGeneric) !*/
        list.add((KType) null);
        assertEquals(5, list.lastIndexOf(null));
        /*! #end !*/

        assertEquals2(4, list.lastIndexOf(k0));
        assertEquals2(-1, list.lastIndexOf(k3));
        assertEquals2(2, list.lastIndexOf(k2));
    }

    /* */
    @Test
    public void testEnsureCapacity()
    {
        TightRandomResizingStrategy resizer = new TightRandomResizingStrategy(0);
        KTypeArrayList<KType> list = new KTypeArrayList<>(0, resizer);

        // Add some elements.
        final int max = rarely() ? 0 : randomIntBetween(0, 1000);
        for (int i = 0; i < max; i++) {
          list.add(cast(i));
        }

        final int additions = randomIntBetween(1, 5000);
        list.ensureCapacity(additions + list.size());
        final int before = resizer.growCalls;
        for (int i = 0; i < additions; i++) {
          list.add(cast(i));
        }
        assertEquals(before, resizer.growCalls);
    }

    @Test
    public void testResizeAndCleanBuffer()
    {
        list.ensureCapacity(20);
        Arrays.fill(list.buffer, k1);

        list.resize(10);
        assertEquals(10, list.size());
        for (int i = 0; i < list.size(); i++) {
            assertEquals2(Intrinsics.<KType> empty(), list.get(i));
        }

        Arrays.fill(list.buffer, Intrinsics.<KType> empty());
        for (int i = 5; i < list.size(); i++) {
            list.set(i, k1);
        }
        list.resize(5);
        assertEquals(5, list.size());
        for (int i = list.size(); i < list.buffer.length; i++) {
            assertEquals2(Intrinsics.<KType> empty(), list.buffer[i]);
        }
    }

    /* */
    @Test
    public void testTrimToSize()
    {
        list.add(asArray(1, 2));
        list.trimToSize();
        assertEquals(2, list.buffer.length);
    }

    /* */
    @Test
    public void testRelease()
    {
        list.add(asArray(1, 2));
        list.release();
        assertEquals(0, list.size());
        list.add(asArray(1, 2));
        assertEquals(2, list.size());
    }

    /* */
    @Test
    public void testGrowth()
    {
        final int maxGrowth = 10;
        final int count = 500;

        list = new KTypeArrayList<KType>(0,
            new BoundedProportionalArraySizingStrategy(5, maxGrowth, 2));

        for (int i = 0; i < count; i++)
            list.add(cast(i));

        assertEquals(count, list.size());

        for (int i = 0; i < count; i++)
            assertEquals2(cast(i), list.get(i));

        assertTrue("Buffer size: 510 <= " + list.buffer.length,
            list.buffer.length <= count + maxGrowth);
    }

    /* */
    @Test
    public void testIterable()
    {
        list.add(asArray( 0, 1, 2, 3));
        int count = 0;
        for (KTypeCursor<KType> cursor : list)
        {
            count++;
            assertEquals2(list.get(cursor.index), cursor.value);
            assertEquals2(list.buffer[cursor.index], cursor.value);
        }
        assertEquals(count, list.size());

        count = 0;
        list.resize(0);
        for (@SuppressWarnings("unused") KTypeCursor<KType> cursor : list)
        {
            count++;
        }
        assertEquals(0, count);
    }

    /* */
    @Test
    public void testIterator()
    {
        list.add(asArray( 0, 1, 2, 3));
        Iterator<KTypeCursor<KType>> iterator = list.iterator();
        int count = 0;
        while (iterator.hasNext())
        {
            iterator.hasNext();
            iterator.hasNext();
            iterator.hasNext();
            iterator.next();
            count++;
        }
        assertEquals(count, list.size());

        list.resize(0);
        assertFalse(list.iterator().hasNext());
    }

    /* */
    @Test
    public void testForEachWithProcedure()
    {
        list.add(asArray( 1, 2, 3));
        final AtomicInteger holder = new AtomicInteger();
        list.forEach(new KTypeProcedure<KType>() {
            int index = 0;
            public void apply(KType v)
            {
                assertEquals2(v, list.get(index++));
                holder.set(index);
            }
        });
        assertEquals(holder.get(), list.size());
    }

    /* */
    @Test
    public void testForEachReturnValueFromAnonymousClass()
    {
        list.add(asArray( 1, 2, 3));
        int result = list.forEach(new KTypeProcedure<KType>() {
            int index = 0;
            public void apply(KType v)
            {
                assertEquals2(v, list.get(index++));
            }
        }).index;
        assertEquals(result, list.size());
    }

    /* */
    @Test
    public void testClear()
    {
        list.add(asArray( 1, 2, 3));
        list.clear();
        checkTrailingSpaceUninitialized();
    }

    /* */
    @Test
    public void testFrom()
    {
        KTypeArrayList<KType> variable = KTypeArrayList.from(k1, k2, k3);
        assertEquals(3, variable.size());
        assertListEquals(variable.toArray(), 1, 2, 3);
    }

    /* */
    @Test
    public void testHashCodeEquals()
    {
        KTypeArrayList<KType> l0 = KTypeArrayList.from();
        assertEquals(1, l0.hashCode());
        assertEquals(l0, KTypeArrayList.from());

        KTypeArrayList<KType> l1 = KTypeArrayList.from(k1, k2, k3);
        KTypeArrayList<KType> l2 = KTypeArrayList.from(k1, k2);
        l2.add(k3);

        assertEquals(l1.hashCode(), l2.hashCode());
        assertEquals(l1, l2);
    }

    /* */
    @Test
    public void testEqualElements()
    {
        KTypeStack<KType> l1 = KTypeStack.from(k1, k2, k3);
        KTypeArrayList<KType> l2 = KTypeArrayList.from(k1, k2);
        l2.add(k3);

        assertEquals(l1.hashCode(), l2.hashCode());
        assertTrue(l2.equalElements(l1));
    }

    /*! #if ($TemplateOptions.KTypeGeneric) !*/
    @Test
    public void testHashCodeWithNulls()
    {
        KTypeArrayList<KType> l1 = KTypeArrayList.from(k1, null, k3);
        KTypeArrayList<KType> l2 = KTypeArrayList.from(k1, null, k3);

        assertEquals(l1.hashCode(), l2.hashCode());
        assertEquals(l1, l2);
    }
    /*! #end !*/

    /*! #if ($TemplateOptions.KTypeGeneric) !*/
    @Test
    public void testAddAll_subclass()
    {
        class A {
        }

        class B extends A {
        }

        KTypeArrayList<B> list2 = new KTypeArrayList<B>();
        list2.add(new B());

        KTypeArrayList<A> list3 = new KTypeArrayList<A>();
        list3.add(new B());
        list3.add(new A());
        list3.addAll(list2);
        assertEquals(3, list3.size());
    }
    /*! #end !*/

    /*! #if ($TemplateOptions.KTypeGeneric) !*/
    @Test
    public void testToArrayWithClass()
    {
        KTypeArrayList<Integer> l1 = KTypeArrayList.from(1, 2, 3);
        Integer[] result = l1.toArray(Integer.class);
        assertArrayEquals(new Integer [] {1, 2, 3}, result); // dummy
    }
    /*! #end !*/

    /*! #if ($TemplateOptions.KTypeGeneric) !*/
    @Test
    public void testToArray()
    {
        KTypeArrayList<KType> l1 = KTypeArrayList.from(k1, k2, k3);
        Object[] result = l1.toArray();
        assertArrayEquals(new Object [] {k1, k2, k3}, result);
    }
    /*! #end !*/

    /* */
    @Test
    public void testClone()
    {
        list.add(k1, k2, k3);

        KTypeArrayList<KType> cloned = list.clone();
        cloned.removeAll(key1);

        assertSortedListEquals(list.toArray(), key1, key2, key3);
        assertSortedListEquals(cloned.toArray(), key2, key3);
    }

    /* */
    @Test
    public void testToString()
    {
        assertEquals("["
            + key1 + ", "
            + key2 + ", "
            + key3 + "]", KTypeArrayList.from(k1, k2, k3).toString());
    }

    /* */
    @Test
    public void testEqualsSameClass()
    {
        KTypeArrayList<KType> l1 = KTypeArrayList.from(k1, k2, k3);
        KTypeArrayList<KType> l2 = KTypeArrayList.from(k1, k2, k3);
        KTypeArrayList<KType> l3 = KTypeArrayList.from(k1, k3, k2);

        Assertions.assertThat(l1).isEqualTo(l2);
        Assertions.assertThat(l1.hashCode()).isEqualTo(l2.hashCode());
        Assertions.assertThat(l1).isNotEqualTo(l3);
    }

    /* */
    @Test
    public void testEqualsSubClass()
    {
        class Sub extends KTypeArrayList<KType> {
        };

        KTypeArrayList<KType> l1 = KTypeArrayList.from(k1, k2, k3);
        KTypeArrayList<KType> l2 = new Sub();
        KTypeArrayList<KType> l3 = new Sub();
        l2.addAll(l1);
        l3.addAll(l1);

        Assertions.assertThat(l2).isEqualTo(l3);
        Assertions.assertThat(l1).isNotEqualTo(l2);
    }
}


text: <app-fullpage-message>Under Maintenance</app-fullpage-message>

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

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

    <title>HSBC's Revolution Programme</title>
    <meta name="description" content="" />
    <link href="//fonts.googleapis.com/css?family=Noto+Sans:300,400,700" rel="stylesheet" type="text/css">
    <link href="//fonts.googleapis.com/css?family=Noto+Serif:400,700,400italic" rel="stylesheet" type="text/css">
    <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
    <link href="//www.agency-showcase.com/themes/mirum/assets/css/style.css?v=1.0.0" rel="stylesheet" type="text/css">
    <link href="//www.agency-showcase.com/themes/mirum/assets/css/animate.min.css?v=1.0.0" rel="stylesheet" type="text/css">
    <link href="//www.agency-showcase.com/themes/mirum/favicon.ico" rel="shortcut icon">
    <link rel="canonical" href="http://www.agency-showcase.com/2015/09/18/HSBCs-Revolution-Programme.html" />

    <meta property="og:site_name" content="Mirum Singapore Agency Showcase" />
    <meta property="og:type" content="article" />
    <meta property="og:title" content="HSBC's Revolution Programme" />
    <meta property="og:description" content="Client: HSBC Singapore Project: HSBC&#8217;s Revolution programme campaign How does a bank reach out to today's group of young adults, professionals and executives who don't really have the time or inclination to learn about a new..." />
    <meta property="og:url" content="http://www.agency-showcase.com/2015/09/18/HSBCs-Revolution-Programme.html" />
    <meta property="og:image" content="https://cloud.githubusercontent.com/assets/1509874/9987241/7046631c-6078-11e5-83bc-3e7b8a8f1281.jpg" />
    <meta property="article:published_time" content="2015-09-17T16:00:00.000Z" />
    <meta property="article:modified_time" content="2015-10-21T04:29:23.427Z" />
    <meta property="article:tag" content="HSBC" />
    <meta property="article:tag" content="campaign" />

    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="HSBC's Revolution Programme" />
    <meta name="twitter:description" content="Client: HSBC Singapore Project: HSBC&#8217;s Revolution programme campaign How does a bank reach out to today's group of young adults, professionals and executives who don't really have the time or inclination to learn about a new..." />
    <meta name="twitter:url" content="http://www.agency-showcase.com/2015/09/18/HSBCs-Revolution-Programme.html" />
    <meta name="twitter:image:src" content="https://cloud.githubusercontent.com/assets/1509874/9987241/7046631c-6078-11e5-83bc-3e7b8a8f1281.jpg" />

    <meta name="generator" content="Ghost ?" />
    <link rel="alternate" type="application/rss+xml" title="Mirum Singapore Agency Showcase" href="http://www.agency-showcase.com/rss" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">

        Mirum Singapore Agency Showcase

HSBC's Revolution Programme

         <time class="timesince date" data-timesince="1442505600" datetime="2015-09-18T00:00" title="18 September 2015">2015-09-18 00:00:00<ago class="ago"></time>
             HSBC, campaign
             Mirum Singapore

Client: HSBC Singapore

Project: HSBC’s Revolution programme campaign

How does a bank reach out to today's group of young adults, professionals and executives who don't really have the time or inclination to learn about a new banking programme? You grab their attention by letting them create a world which revolves around them. And then show them how HSBC's Revolution programme can enrich their world and lifestyle.

Campaign Results

The online advertising created:

- The number of sign-ups was more than 8 times the daily average.

- A 4-fold increase in the number of visitors.

- More than triple the number of worlds created.

          Privacy | Terms | A WPP Company

Copyright © 2015 Mirum Singapore


text:
package de.muspellheim.flowdesign;

/**
 * Marks an functional unit need a dependency.
 *
 * @param <T> the dependencies type.
 * @author Falko Schumann
 * @since 3.0
 */
public interface DependsOn<T> {

    /**
     * Inject the dependency in the functional unit.
     *
     * @param dependency the dependency.
     */
    void inject(T dependency);

}


text:
webgl-codes
===========

WebGL tutorials are based on https://github.com/gpjt/webgl-lessons

Go to http://html5.iii.org.tw/webgl/ <- this website has some datails.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"

  	android:gravity="center"
  >
   <EditText
        android:id="@+id/careerstack_searchBar_editin_keywords"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/careerstack_input_hint_keywords"
        android:maxLines="1"
        android:singleLine="true"
        android:ellipsize="end"
        android:layout_weight="1.0"
        android:layout_marginBottom="3dp"
        android:nextFocusForward="@+id/careerstack_searchBar_editin_location"
        android:nextFocusDown="@+id/careerstack_searchBar_editin_location"
        android:inputType="textCapSentences|textAutoCorrect"
         />

    <EditText
        android:id="@+id/careerstack_searchBar_editin_location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/careerstack_input_hint_location"
        android:maxLines="1"
        android:singleLine="true"
        android:ellipsize="end"
        android:layout_weight="1.0"
        android:layout_marginBottom="3dp"
        android:inputType="textCapSentences|textAutoCorrect"
         />
 </LinearLayout>


text:
package org.gradle.messaging.remote.internal.hub.protocol;

public class ChannelIdentifier {
    private final String name;

    public ChannelIdentifier(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj == null || obj.getClass() != getClass()) {
            return false;
        }
        ChannelIdentifier other = (ChannelIdentifier) obj;
        return name.equals(other.name);
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }

    @Override
    public String toString() {
        return name;
    }
}


text:
/*

License
-------

All source code in this directory is licensed under the MIT license unless
otherwise noted in the source file itself.

See MIT-LICENSE in this directory for details.

*/

/*jslint
onevar: true,
undef: true,
nomen: true,
eqeqeq: true,
plusplus: true,
bitwise: true,
regexp: true,
immed: true,
strict: true,
laxbreak: true
*/

/*global
Components: false
*/

"use strict";

var EXPORTED_SYMBOLS = ['exports', 'load']

  , Cc = Components.classes
  , Ci = Components.interfaces
  , Cu = Components.utils

  , exports = {}

  , require = Cu.import('resource://fireworks/lib/require.js', null).require

  , util = require('util')
  , events = require('events')
  , logging = require('logging')
  , dcube = require('dcube')
  , modeler = require('modeler')

  , Promise = events.Promise
  , has = util.has
  , confirmArray = util.confirmArray
  , confirmObject = util.confirmObject
  , isArray = util.isArray
  , isObject = util.isObject

  , DBError = require('errors')
                .ErrorConstructor('DBError', 'db')
  , log = logging.get('DB')
  , user_sessions = {}
  , open_connections = {}
  , entity_util
  , blocking
  ;

function connection_id(username, dbname) {
  return username +'-'+ dbname;
}

function repr_connections() {
  var rv = '', id;
  for (id in open_connections) {
    if(has(open_connections, id)) {
      rv += (id +', ');
    }
  }
  return rv.slice(0, rv.length -2);
}

function ChangeSet(connection_id) {
  if (!(this instanceof ChangeSet)) {
    return new ChangeSet(connection_id);
  }
  this.connection = connection_id;
  this.originals = {};
  this.updates = {};
  this.set = {};
  this.length = 0;
}

ChangeSet.prototype = {};

ChangeSet.prototype.originals = {};
ChangeSet.prototype.set = {};
ChangeSet.prototype.staging = {};
ChangeSet.prototype.length = 0;

// A JSON string is expected as the value.
ChangeSet.prototype.register = function (k, v, idx) {
  this.originals[k] = [v, idx];
};

// A JSON string is expected as the value.
ChangeSet.prototype.update = function (k, v, idx) {
  var first;

  // This equality check between JSON strings works only because the modeling
  // system keeps the JSON representation of entities consistent.
  if (this.originals[k][0] !== v) {
    first = !this.set[k];
    this.set[k] = [v, idx];
    if (first && (this.length += 1) === 1) {
      events.trigger('db.state',
          {id: this.connection, state: 'mutated'}, true);
    }
  }
  else if (this.set[k]) {
    delete this.set[k];
    if ((this.length -= 1) === 0) {
      events.trigger('db.state',
          {id: this.connection, state: 'clean'}, true);
    }
  }
};

ChangeSet.prototype.stage = function () {
  var k, keys = [];
  for (k in this.set) {
    if (has(this.set, k)) {
      this.staging[k] = this.originals[k];
      this.originals[k] = this.set[k];
      keys.push(k);
    }
  }
  this.set = {};
  this.length = 0;
  events.trigger('db.committing', {id: this.connection, keys: keys});
};

ChangeSet.prototype.revert = function (k) {
  // This equality check between JSON strings works only because the modeling
  // system keeps the JSON representation of entities consistent.
  var set = this.originals[k]
    , changed = (this.set[k] && set[0] !== this.set[k][0]);

  this.originals[k] = this.staging[k];

  // The entity was changed back to its original state while the commit was
  // going over the network.
  if (changed && this.originals[k][0] === this.set[k][0]) {
    delete this.set[k];
    this.length -= 1;
    return;
  }

  // The entity was not changed during network transmission of the commit, but
  // it needs to go back to a 'mutated' state.
  if (!changed) {
    this.set[k] = set;
    this.length += 1;
  }
};

ChangeSet.prototype.commit = function (keys) {
  this.staging = {};
  if (this.length === 0) {
    events.trigger('db.committed'
        , {id: this.connection, keys: keys, state: 'clean'}, true);
    return;
  }
  events.trigger('db.committed'
      , {id: this.connection, keys: keys, state: 'mutated'}, true);
};

function Query(connection) {
  var self = {}
    , query = dcube.Query()
    , callbacks = []
    , sent = false
    , $F = function () {}
    ;

  self.start = function () {
    if (sent) {
      throw 'This query has already been committed.';
    }
    var q = query.query(query)
      , override_append = q.append
      ;

    q.append = function (fn) {
      callbacks.push((typeof fn === 'function') ? fn : $F);
      override_append.call(q);
      return self;
    };
    return q;
  };

  self.send = function () {
    if (sent) {
      throw 'This query has already been committed.';
    }
    events.enqueue(function () {
      connection.request(query.resolve(), callbacks);
    }, 0);
    sent = true;
  };

  return self;
}

entity_util = {
  update_array: function (a, b) {
    a = confirmArray(a);
    var i = 0, len = b.length;
    for (; i < len; i += 1) {
      a[i] = this.update(a[i], b[i]);
    }
    return a;
  },

  update_object: function (a, b) {
    a = confirmObject(a);
    var p;
    for (p in b) {
      if (has(b, p)) {
        a[p] = this.update(a[p], b[p]);
      }
    }
    return a;
  },

  update: function (a, b) {
    if (isArray(b)) {
      return this.update_array(a, b);
    }
    if (isObject(b)) {
      return this.update_object(a, b);
    }
    return (a = b);
  }
};

// Entity function object constructor.
//
// ### Params
//   * `spec` {object}
//     * `spec.key` {string} Key of the entity.
//     * `spec.data` {object} The entity representation as a JS object.
//     * `spec.indexes` {object} The JS object representation of the index
//         entries this entity is indexed under.
//     * `spec.mapper` {function} A function that mutates data structures to
//         meet the schema of this entity.
//   * `original` {string} JSON string representation of the original data.
//   * `connections` {InitConnection object}
function Entity(spec, original, connection) {
  var key = spec.key
    , data = JSON.parse(original)
    , indexes = JSON.parse(JSON.stringify(spec.indexes))
    , mapper = spec.mapper
    , rv
    ;

  log.trace('Creating Entity for '+ key);
  connection.changeset.register(key, original, JSON.stringify(indexes));

  return function (method) {
    switch (method) {

    case 'key':
      return key;

    case 'original':
      return connection.changeset.originals[key][0];

    case 'entity':
      // Return a cheap copy.
      return JSON.parse(JSON.stringify(data));

    case 'indexes':
      // Return a cheap copy.
      return JSON.parse(JSON.stringify(indexes));

    case 'update':
      mapper(entity_util.update(data, arguments[1]), indexes);
      rv = JSON.stringify(data);
      connection.changeset.update(key, rv, JSON.stringify(indexes));
      break;

    case 'delete':
      data = indexes = null;
      connection.changeset.update(key, null);
      break;

    default:
      throw new Error('"'+ method +'" is an invalid entity operation.');
    }
  };
}

// Create a private connection object.
//
// #### Params
// * `opt` {object}
//   * `opt.id` {string} Connection ID.
//   * `opt.dbname` {string} Name of database.
//   * `opt.session` {function} The DCube user session function object.
//   * `opt.models` {object} Dict of entity modeling constructor functions.
//       One for each model kind.
function InitConnection(opt) {
  if (!(this instanceof InitConnection)) {
    return new InitConnection(opt);
  }
  log.trace('InitConnection() -> '+ opt.id);
  this.id = opt.id;
  this.dbname = opt.dbname;
  this.passkey = opt.passkey;
  this.session = opt.session;
  this.models = opt.models;
  this.changeset = ChangeSet(opt.id);
}

InitConnection.prototype = {};

InitConnection.prototype.multi_model = function (items) {
  var rv = [], i = 0, len = items.length, item;

  for (; i < len; i += 1) {
    item = items[i];
    rv.push(this.model(items.kind, items.key, items.entity, items.index));
  }
  return rv;
};

InitConnection.prototype.model = function (kind, key, ent, index) {
  if (!has(this.models, kind)) {
    throw DBError(new Error('InitConnection.model("'+
            kind +'") is not a valid kind name.'));
  }

  var data;
  try {
    data = JSON.parse(ent);
  }
  catch (e) {
    log.debug(e);
    log.error('Unable to parse JSON for entity: '+ key);
    return null;
  }

  return Entity(this.models[kind](key, data, index), ent, this);
};

InitConnection.prototype.remote_result = function (callbacks) {
  var self = this;
  return function (result, i) {
    var n, p, item, multi_rv, indexes
      , cb = callbacks[i]
      ;

    if (result.status === 400) {
      log.error('Got a 400 query response status.');
      events.enqueue(function () {
        cb(false, DBError('invalid query'));
      }, 0);
      return;
    }
    if (result.status === 404) {
      events.enqueue(function () { cb(null); }, 0);
      return;
    }

    switch (result.action) {
    case 'get':
      events.enqueue(function () {
        cb(self.model(
            result.indexes.kind
          , result.key
          , result.entity
          , result.indexes
          )
        );
      }, 0);
      break;

    case 'put':
      events.enqueue(function () { cb(true); }, 0);
      break;

    case 'delete':
      events.enqueue(function () { cb(true); }, 0);
      break;

    case 'query':
      multi_rv = [];
      indexes = {};
      for (n = 0; n < result.results.length; n += 1) {
        item = result.results[n];
        for (p in item) {
          if (has(item, p) && p !== 'key' && p !== 'entity') {
            indexes[p] = item[p];
          }
        }
        multi_rv.push(self.model(
            indexes.kind
          , item.key
          , item.entity
          , indexes
          )
        );
      }
      events.enqueue(function () { cb(multi_rv); }, 0);
      break;
    }
  };
};

// All requests come through here.
// ! Do not call this method from the UI thread.
InitConnection.prototype.request = function (queries, callbacks) {
  var promise = this.session('query', this.passkey, this.dbname, queries)
    , self = this
    ;

  log.info('Making connection request for '+ this.id);
  promise(
    function (results) {
      log.trace('Got connection response for '+ self.id);
      results.forEach(self.remote_result(callbacks));
    }
  , function (err) {
      log.trace('Got connection response for '+ self.id);
      log.debug('Request error.');
      log.debug(logging.formatError(err));
      callbacks.forEach(function (cb) { cb(false, DBError('request error')); });
    }
  );
};

InitConnection.prototype.get = function (keys) {
  var self = this;
  return Promise(function (fulfill, except, progress) {
    keys = isArray(keys) ? keys : [keys];
    var i = 0, len = keys.length
      , queries = []
      , callbacks = []
      , results = []
      , exception
      ;

    log.trace('Making "get" request for '+ self.id);

    function combiner(ent, err) {
      log.trace('Connection.get()::combiner('+
          typeof ent +', '+ typeof err +') called.');
      if (!ent) {
        len -= 1;
        log.debug(logging.formatError(err));
        if (err && err.message === 'request error') {
          if (!exception) {
            exception = err;
          }
          return;
        }
        log.error('Unexpected error on get.');
        return;
      }

      results.push(ent);
      if (results.length === len) {
        if (!exception) {
          fulfill(results);
        }
        else {
          except(exception);
        }
      }
    }

    for (; i < len; i += 1) {
      queries.push({action: 'get', statements: [['key', '=', keys[i]]]});
      callbacks.push(combiner);
    }

    self.request(queries, callbacks);
  });
};

InitConnection.prototype.query = function () {
  return Query(this);
};

InitConnection.prototype.commit = function (report) {
  var self = this;
  return Promise(function (fulfill, except, progress) {
    var set = self.changeset.set, k
      , keys = []
      , query = dcube.Query()
      , callbacks = []
      , exception
      , results = 0
      ;

    log.trace('.commit() called called on '+ self.id);

    function combiner(committed, err) {
      results += 1;

      if (!committed) {
        log.debug(logging.formatError(err));
        self.changeset.revert(keys[results -1]);
        if (err && err.message === 'request error') {
          if (!exception) {
            exception = err;
          }
          return;
        }
        log.error('Unexpected error on commit.');
        return;
      }

      if (results === keys.length) {
        self.changeset.commit(keys);
        if (!exception) {
          fulfill(results);
        }
        else {
          except(exception);
        }
      }
    }

    for (k in set) {
      if (has(set, k)) {
        keys.push(k);
        query.put(k, set[k][0], JSON.parse(set[k][1]));
        callbacks.push(combiner);
      }
    }

    if (!keys.length) {
      fulfill(0);
    }
    else if (!report) {
      log.debug('change set -> '+ util.prettify(set));
      self.changeset.stage();
      self.request(query.resolve(), callbacks);
    }
    else {
      log.debug('change set -> '+ util.prettify(set));
      fulfill(query.resolve());
    }
  });
};

function Connection(spec) {
  log.trace('Connection() -> '+ spec.id);
  var dbname = spec.dbname
    , username = spec.username
    , id = spec.id
    , models = modeler.register(username, spec.models)
    , opt = {
        dbname: dbname
      , models: models
      , passkey: spec.passkey
      , session: spec.session
      , id: id
    }
    , cxn = InitConnection(opt)

    , callback, model, ent
    ;

  return function (op) {
    switch (op) {

    case 'username':
      return username;

    case 'dbname':
      return dbname;

    case 'id':
      return id;

    // !Note: If the user creates a new entity, but does not make any changes
    // to the default values, it will not be saved on commit.
    case 'create':
      // arguments[1]: kind
      model = models[arguments[1]];
      if (typeof model !== 'function') {
        throw 'Kind "'+ arguments[1] +'" is not valid.';
      }
      ent = model();
      return Entity(ent, JSON.stringify(ent.data), cxn);

    case 'get':
      // arguments[1]: key(s)
      // arguments[2]: callback
      callback = arguments[2];
      cxn.get(arguments[1])(callback, function (ex) {
        callback(false, ex);
      });
      break;

    case 'query':
      return cxn.query();

    case 'commit':
      // arguments[1]: report flag
      return cxn.commit(arguments[1]);

    default:
      throw '"'+ op +'" is an invalid connection operation.';
    }
  };
}

blocking = {
    stack: []
  , locked: false

  , done: function () {
      events.enqueue(function () {
        blocking.locked = false;
        blocking.next();
      }, 0);
    }

  , next: function (cc, args, binding) {
      var cont;

      if (typeof cc === 'function') {
        args = args || [];
        args.unshift(blocking.done);
        blocking.stack.push({cc: cc, args: args, binding: binding});
      }

      if (blocking.stack.length && !blocking.locked) {
        blocking.locked = true;
        cont = blocking.stack.shift();
        cont.cc.apply(cont.binding, cont.args);
      }
    }
};

exports.connections = function (callback) {
  blocking.next(function (done) {
    var id, rv = [], cxn;
    for (id in open_connections) {
      if (has(open_connections, id)) {
        cxn = open_connections[id];
        rv.push({
            id: cxn('id')
          , username: cxn('username')
          , dbname: cxn('dbname')
          }
        );
      }
    }
    done();
    callback(rv);
  });
};

exports.getConnection = function (dbname, username, callback) {
  blocking.next(function (done) {
    done();
    if (typeof username === 'function') {
      callback = username;
      callback(open_connections[dbname] || null);
    }
    else {
      callback(open_connections[connection_id(username, dbname)] || null);
    }
  });
};

exports.Query = dcube.Query;

// Open a connection to a database with the given username and passkey.
//
// #### Params
//   * `dbname` {string} The name of the database to connect to.
//   * `models` {object} Dictionary object of
//     data models to use for this connection.
//   * `username` {string} The username of the user to connect.
//   * `passkey` {string} The passkey of the user.
//   * `query` {object} A DCube.Query object or array.
//
// #### Returns a `Promise` function object.
//   * The value passed to fulfill callbacks will be a `Connection` object.
//   * Possible exception messages passed to the exception callbacks include:
//     * 'Request error.' HTTP request error.
//     * 'User does not exist.' The named user could not be found.
//     * 'Authentication denied.' Invalid passkey.
//     * 'Database could not be found.' The db does not exist.
//     * 'Database is restricted.' The user does not have access to the db.
exports.connect = function (dbname, models, username, passkey, query) {
  log.trace('DB.connect('+
        [dbname, 'models', username, 'passkey', 'query'] +')');

  return Promise(function (fulfill, except, progress) {
    blocking.next(function (done) {
      var id = connection_id(username, dbname)
        , spec = {
              dbname: dbname
            , models: models
            , username: username
            , passkey: passkey
            , id: id
          }
        ;

      if (query.constructor === exports.Query) {
        query = query.resolve();
      }
      else if (isArray(query)) {
        query = query;
      }
      else {
        query = [];
      }

      function has_session(session) {
        spec.session = session;
        session('query', passkey, dbname, query)(
          function (results) {
            log.debug('Connection query results -> '+ util.prettify(results));
            user_sessions[username] = session;
            open_connections[id] = Connection(spec);
            log.debug('Update open_connections -> '+ repr_connections());
            done();
            fulfill(open_connections[id]);
          }
        , function (ex) {
            log.debug('Connection error -- '+ ex);
            done();
            except(ex);
          }
        );
      }

      log.debug('open_connections -> '+ repr_connections());

      if (!has(open_connections, id)) {
        log.trace('Creating new connection function.');
        if (!has(user_sessions, username)) {
          log.trace('Creating a new user session.');
          dcube.User(username, has_session);
        }
        else {
          log.trace('Using existing user session.');
          has_session(user_sessions[username]);
        }
        return;
      }
      log.trace('Returning existing connection function.');
      done();
      fulfill(open_connections[id]);
    });
  });
};

function load(cb) {
  require.ensure(['logging', 'dcube'], function (require) {
    cb('db', exports);
  });
}


text:
package org.xins.client;

import org.xins.common.MandatoryArgumentChecker;
import org.xins.common.collections.PropertyReader;
import org.xins.common.service.TargetDescriptor;
import org.xins.common.spec.ErrorCodeSpec;
import org.xins.common.xml.Element;

/**
 * Exception that indicates that a result code was returned by the API call.
 *
 * @version $Revision$ $Date$
 * @author Ernst de Haan
 *
 * @since XINS 1.0.0
 */
public class UnsuccessfulXINSCallException
extends XINSCallException
implements XINSCallResultData {

   /**
    * The result data. The value of this field cannot be null.
    */
   private final XINSCallResultData _result;

   /**
    * The type of the error.
    */
   private ErrorCodeSpec.Type _type;

   /**
    * Constructs a new UnsuccessfulXINSCallException based on a
    * XINSCallResultData instance.
    *
    * @param request
    *    the original request, cannot be null.
    *
    * @param target
    *    descriptor for the target that was attempted to be called, cannot be
    *    null.
    *
    * @param duration
    *    the call duration in milliseconds, must be >= 0.
    *
    * @param resultData
    *    the result data, cannot be null.
    *
    * @param detail
    *    detail message, or null.
    *
    * @throws IllegalArgumentException
    *    if request     == null
    *          || target      == null
    *          || duration  < 0
    *          || resultData  == null
    *          || resultData.{@link XINSCallResult#getErrorCode() getErrorCode()} == null.
    */
   UnsuccessfulXINSCallException(XINSCallRequest    request,
                                 TargetDescriptor   target,
                                 long               duration,
                                 XINSCallResultData resultData,
                                 String             detail)
   throws IllegalArgumentException {

      super("Unsuccessful XINS call result", request, target, duration,
            determineDetail(resultData, detail), null);

      // Check additional precondition
      MandatoryArgumentChecker.check("resultData", resultData);

      // Result object must be unsuccessful
      String errorCode = resultData.getErrorCode();
      if (errorCode == null) {
         throw new IllegalArgumentException("resultData.getErrorCode() == null");
      }

      // Store details
      _result = resultData;
   }

   /**
    * Delegate for the constructor that determines the detail message based on
    * a XINSCallResultData object and an optional detailed
    * description.
    *
    * @param result
    *    the {@link XINSCallResultData} instance, should not be
    *    null.
    *
    * @param detail
    *    detailed description to include, or null if unavailable.
    *
    * @return
    *    the detail message for the constructor to use, never
    *    null.
    *
    * @throws IllegalArgumentException
    *    if result == null
    *          || result.{@link XINSCallResultData#getErrorCode() getErrorCode()} == null.
    */
   private static final String determineDetail(XINSCallResultData result,
                                               String             detail)
   throws IllegalArgumentException {

      // Argument cannot be null
      MandatoryArgumentChecker.check("result", result);

      // Result must be unsuccessful
      String errorCode = result.getErrorCode();
      if (errorCode == null) {
         throw new IllegalArgumentException("result.getErrorCode() == null");
      }

      if (detail == null || detail.length() < 1) {
         return "Error code \"" + errorCode + "\".";
      } else {
         return "Error code \"" + errorCode + "\": " + detail;
      }
   }

   /**
    * Returns the error code.
    *
    * @return
    *    the error code, never null.
    */
   public final String getErrorCode() {
      return _result.getErrorCode();
   }

   /**
    * Gets all returned parameters.
    *
    * @return
    *    a {@link PropertyReader} containing all parameters, or
    *    null if there are none.
    */
   public final PropertyReader getParameters() {
      return _result.getParameters();
   }

   /**
    * Gets the value of the specified returned parameter.
    *
    * @param name
    *    the parameter name, not null.
    *
    * @return
    *    the value of the parameter, or null if there is no values.
    *
    * @throws IllegalArgumentException
    *    if name == null.
    */
   public final String getParameter(String name)
   throws IllegalArgumentException {
      PropertyReader p = getParameters();
      if (p == null) {
         return null;
      } else {
         return p.get(name);
      }
   }

   /**
    * Returns the optional extra data.
    *
    * @return
    *    the extra data as an {@link Element}, can be null;
    */
   public final Element getDataElement() {
      return _result.getDataElement();
   }

   /**
    * Sets the type of the error code.
    *
    * @param type
    *    the type of the error (functionnal or technical).
    */
   void setType(ErrorCodeSpec.Type type) {
      _type = type;
   }

   /**
    * Returns the type of the error code.
    *
    * @return
    *    the type as a {@link ErrorCodeSpec ErrorCodeSpec.Type}, can be null if it's unknown.
    *
    * @since XINS 1.4.0
    */
   public final ErrorCodeSpec.Type getType() {
      return _type;
   }
}