text:
package org.neo4j.kernel.impl.nioneo.xa;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.xa.XAException;

import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.kernel.impl.core.LockReleaser;
import org.neo4j.kernel.impl.core.PropertyIndex;
import org.neo4j.kernel.impl.nioneo.store.DynamicRecord;
import org.neo4j.kernel.impl.nioneo.store.InvalidRecordException;
import org.neo4j.kernel.impl.nioneo.store.NeoStore;
import org.neo4j.kernel.impl.nioneo.store.NodeRecord;
import org.neo4j.kernel.impl.nioneo.store.NodeStore;
import org.neo4j.kernel.impl.nioneo.store.PropertyData;
import org.neo4j.kernel.impl.nioneo.store.PropertyIndexData;
import org.neo4j.kernel.impl.nioneo.store.PropertyIndexRecord;
import org.neo4j.kernel.impl.nioneo.store.PropertyIndexStore;
import org.neo4j.kernel.impl.nioneo.store.PropertyRecord;
import org.neo4j.kernel.impl.nioneo.store.PropertyStore;
import org.neo4j.kernel.impl.nioneo.store.PropertyType;
import org.neo4j.kernel.impl.nioneo.store.Record;
import org.neo4j.kernel.impl.nioneo.store.RelationshipChainPosition;
import org.neo4j.kernel.impl.nioneo.store.RelationshipData;
import org.neo4j.kernel.impl.nioneo.store.RelationshipRecord;
import org.neo4j.kernel.impl.nioneo.store.RelationshipStore;
import org.neo4j.kernel.impl.nioneo.store.RelationshipTypeData;
import org.neo4j.kernel.impl.nioneo.store.RelationshipTypeRecord;
import org.neo4j.kernel.impl.nioneo.store.RelationshipTypeStore;
import org.neo4j.kernel.impl.nioneo.xa.Command.PropertyCommand;
import org.neo4j.kernel.impl.transaction.LockManager;
import org.neo4j.kernel.impl.transaction.LockType;
import org.neo4j.kernel.impl.transaction.xaframework.XaCommand;
import org.neo4j.kernel.impl.transaction.xaframework.XaLogicalLog;
import org.neo4j.kernel.impl.transaction.xaframework.XaTransaction;
import org.neo4j.kernel.impl.util.ArrayMap;

/**
 * Transaction containing {@link Command commands} reflecting the operations
 * performed in the transaction.
 */
class NeoTransaction extends XaTransaction
{
    private final Map<Integer,NodeRecord> nodeRecords =
        new HashMap<Integer,NodeRecord>();
    private final Map<Integer,PropertyRecord> propertyRecords =
        new HashMap<Integer,PropertyRecord>();
    private final Map<Integer,RelationshipRecord> relRecords =
        new HashMap<Integer,RelationshipRecord>();
    private final Map<Integer,RelationshipTypeRecord> relTypeRecords =
        new HashMap<Integer,RelationshipTypeRecord>();
    private final Map<Integer,PropertyIndexRecord> propIndexRecords =
        new HashMap<Integer,PropertyIndexRecord>();

    private final ArrayList<Command.NodeCommand> nodeCommands =
        new ArrayList<Command.NodeCommand>();
    private final ArrayList<Command.PropertyCommand> propCommands =
        new ArrayList<Command.PropertyCommand>();
    private final ArrayList<Command.PropertyIndexCommand> propIndexCommands =
        new ArrayList<Command.PropertyIndexCommand>();
    private final ArrayList<Command.RelationshipCommand> relCommands =
        new ArrayList<Command.RelationshipCommand>();
    private final ArrayList<Command.RelationshipTypeCommand> relTypeCommands =
        new ArrayList<Command.RelationshipTypeCommand>();

    private final NeoStore neoStore;
    private boolean committed = false;
    private boolean prepared = false;

    private final LockReleaser lockReleaser;
    private final LockManager lockManager;

    NeoTransaction( int identifier, XaLogicalLog log, NeoStore neoStore,
        LockReleaser lockReleaser, LockManager lockManager )
    {
        super( identifier, log );
        this.neoStore = neoStore;
        this.lockReleaser = lockReleaser;
        this.lockManager = lockManager;
    }

    public boolean isReadOnly()
    {
        if ( isRecovered() )
        {
            if ( nodeCommands.size() == 0 && propCommands.size() == 0 &&
                relCommands.size() == 0 && relTypeCommands.size() == 0 &&
                propIndexCommands.size() == 0 )
            {
                return true;
            }
            return false;
        }
        if ( nodeRecords.size() == 0 && relRecords.size() == 0 &&
            relTypeRecords.size() == 0 && propertyRecords.size() == 0 &&
            propIndexRecords.size() == 0 )
        {
            return true;
        }
        return false;
    }

    public void doAddCommand( XaCommand command )
    {
        // override
    }

    @Override
    protected void doPrepare() throws XAException
    {
        if ( committed )
        {
            throw new XAException( "Cannot prepare committed transaction["
                + getIdentifier() + "]" );
        }
        if ( prepared )
        {
            throw new XAException( "Cannot prepare prepared transaction["
                + getIdentifier() + "]" );
        }
        // generate records then write to logical log via addCommand method
        prepared = true;
        for ( RelationshipTypeRecord record : relTypeRecords.values() )
        {
            Command.RelationshipTypeCommand command =
                new Command.RelationshipTypeCommand(
                    neoStore.getRelationshipTypeStore(), record );
            relTypeCommands.add( command );
            addCommand( command );
        }
        for ( NodeRecord record : nodeRecords.values() )
        {
            if ( !record.inUse() && record.getNextRel() !=
                Record.NO_NEXT_RELATIONSHIP.intValue() )
            {
                throw new InvalidRecordException( "Node record " + record
                    + " still has relationships" );
            }
            Command.NodeCommand command = new Command.NodeCommand(
                neoStore.getNodeStore(), record );
            nodeCommands.add( command );
            if ( !record.inUse() )
            {
                removeNodeFromCache( record.getId() );
            }
            addCommand( command );
        }
        for ( RelationshipRecord record : relRecords.values() )
        {
            Command.RelationshipCommand command =
                new Command.RelationshipCommand(
                    neoStore.getRelationshipStore(), record );
            relCommands.add( command );
            if ( !record.inUse() )
            {
                removeRelationshipFromCache( record.getId() );
            }
            addCommand( command );
        }
        for ( PropertyIndexRecord record : propIndexRecords.values() )
        {
            Command.PropertyIndexCommand command =
                new Command.PropertyIndexCommand(
                    neoStore.getPropertyStore().getIndexStore(), record );
            propIndexCommands.add( command );
            addCommand( command );
        }
        for ( PropertyRecord record : propertyRecords.values() )
        {
            Command.PropertyCommand command = new Command.PropertyCommand(
                neoStore.getPropertyStore(), record );
            propCommands.add( command );
            addCommand( command );
        }
    }

    @Override
    protected void injectCommand( XaCommand xaCommand )
    {
        if ( xaCommand instanceof Command.NodeCommand )
        {
            nodeCommands.add( (Command.NodeCommand) xaCommand );
        }
        else if ( xaCommand instanceof Command.RelationshipCommand )
        {
            relCommands.add( (Command.RelationshipCommand) xaCommand );
        }
        else if ( xaCommand instanceof Command.PropertyCommand )
        {
            propCommands.add( (Command.PropertyCommand) xaCommand );
        }
        else if ( xaCommand instanceof Command.PropertyIndexCommand )
        {
            propIndexCommands.add( (Command.PropertyIndexCommand) xaCommand );
        }
        else if ( xaCommand instanceof Command.RelationshipTypeCommand )
        {
            relTypeCommands.add( (Command.RelationshipTypeCommand) xaCommand );
        }
        else
        {
            throw new IllegalArgumentException( "Unknown command " + xaCommand );
        }
    }

    public void doRollback() throws XAException
    {
        if ( committed )
        {
            throw new XAException( "Cannot rollback partialy commited "
                + "transaction[" + getIdentifier() + "]. Recover and "
                + "commit" );
        }
        try
        {
            for ( RelationshipTypeRecord record : relTypeRecords.values() )
            {
                if ( record.isCreated() )
                {
                    getRelationshipTypeStore().freeId( record.getId() );
                    for ( DynamicRecord dynamicRecord : record.getTypeRecords() )
                    {
                        if ( dynamicRecord.isCreated() )
                        {
                            getRelationshipTypeStore().freeBlockId(
                                dynamicRecord.getId() );
                        }
                    }
                }
                removeRelationshipTypeFromCache( record.getId() );
            }
            for ( NodeRecord record : nodeRecords.values() )
            {
                if ( record.isCreated() )
                {
                    getNodeStore().freeId( record.getId() );
                }
                removeNodeFromCache( record.getId() );
            }
            for ( RelationshipRecord record : relRecords.values() )
            {
                if ( record.isCreated() )
                {
                    getRelationshipStore().freeId( record.getId() );
                }
                removeRelationshipFromCache( record.getId() );
            }
            for ( PropertyIndexRecord record : propIndexRecords.values() )
            {
                if ( record.isCreated() )
                {
                    getPropertyStore().getIndexStore().freeId( record.getId() );
                    for ( DynamicRecord dynamicRecord : record.getKeyRecords() )
                    {
                        if ( dynamicRecord.isCreated() )
                        {
                            getPropertyStore().getIndexStore().freeBlockId(
                                dynamicRecord.getId() );
                        }
                    }
                }
            }
            for ( PropertyRecord record : propertyRecords.values() )
            {
                if ( record.getNodeId() != -1 )
                {
                    removeNodeFromCache( record.getNodeId() );
                }
                else if ( record.getRelId() != -1 )
                {
                    removeRelationshipFromCache( record.getRelId() );
                }
                if ( record.isCreated() )
                {
                    getPropertyStore().freeId( record.getId() );
                    for ( DynamicRecord dynamicRecord : record
                        .getValueRecords() )
                    {
                        if ( dynamicRecord.isCreated() )
                        {
                            if ( dynamicRecord.getType() ==
                                PropertyType.STRING.intValue() )
                            {
                                getPropertyStore().freeStringBlockId(
                                    dynamicRecord.getId() );
                            }
                            else if ( dynamicRecord.getType() ==
                                PropertyType.ARRAY.intValue() )
                            {
                                getPropertyStore().freeArrayBlockId(
                                    dynamicRecord.getId() );
                            }
                            else
                            {
                                throw new InvalidRecordException(
                                    "Unknown type on " + dynamicRecord );
                            }
                        }
                    }
                }
            }
        }
        finally
        {
            nodeRecords.clear();
            propertyRecords.clear();
            relRecords.clear();
            relTypeRecords.clear();
            propIndexRecords.clear();

            nodeCommands.clear();
            propCommands.clear();
            propIndexCommands.clear();
            relCommands.clear();
            relTypeCommands.clear();
            if ( !isRecovered() )
            {
                lockReleaser.rollback();
            }
        }
    }

    private void removeRelationshipTypeFromCache( int id )
    {
        lockReleaser.removeRelationshipTypeFromCache( id );
    }

    private void removeRelationshipFromCache( int id )
    {
        lockReleaser.removeRelationshipFromCache( id );
    }

    private void removeNodeFromCache( int id )
    {
        lockReleaser.removeNodeFromCache( id );
    }

    private void addRelationshipType( int id )
    {
        setRecovered();
        RelationshipTypeData type;
        if ( isRecovered() )
        {
            type = neoStore.getRelationshipTypeStore().getRelationshipType(
                id, true );
        }
        else
        {
            type = neoStore.getRelationshipTypeStore().getRelationshipType(
                id );
        }
        lockReleaser.addRelationshipType( type );
    }

    private void addPropertyIndexCommand( int id )
    {
        PropertyIndexData index;
        if ( isRecovered() )
        {
            index =
                neoStore.getPropertyStore().getIndexStore().getPropertyIndex(
                    id, true );
        }
        else
        {
            index =
                neoStore.getPropertyStore().getIndexStore().getPropertyIndex(
                    id );
        }
        lockReleaser.addPropertyIndex( index );
    }

    public void doCommit() throws XAException
    {
        if ( !isRecovered() && !prepared )
        {
            throw new XAException( "Cannot commit non prepared transaction["
                + getIdentifier() + "]" );
        }
        if ( isRecovered() )
        {
            commitRecovered();
            return;
        }
        try
        {
            committed = true;
            CommandSorter sorter = new CommandSorter();
            // reltypes
            java.util.Collections.sort( relTypeCommands, sorter );
            for ( Command.RelationshipTypeCommand command : relTypeCommands )
            {
                command.execute();
            }
            // nodes
            java.util.Collections.sort( nodeCommands, sorter );
            for ( Command.NodeCommand command : nodeCommands )
            {
                command.execute();
            }
            // relationships
            java.util.Collections.sort( relCommands, sorter );
            for ( Command.RelationshipCommand command : relCommands )
            {
                command.execute();
            }
            java.util.Collections.sort( propIndexCommands, sorter );
            for ( Command.PropertyIndexCommand command : propIndexCommands )
            {
                command.execute();
            }
            // properties
            java.util.Collections.sort( propCommands, sorter );
            for ( Command.PropertyCommand command : propCommands )
            {
                command.execute();
            }
            if ( !isRecovered() )
            {
                lockReleaser.commit();
            }
        }
        finally
        {
            nodeRecords.clear();
            propertyRecords.clear();
            relRecords.clear();
            relTypeRecords.clear();
            propIndexRecords.clear();

            nodeCommands.clear();
            propCommands.clear();
            propIndexCommands.clear();
            relCommands.clear();
            relTypeCommands.clear();
        }
    }

    private void commitRecovered()
    {
        try
        {
            committed = true;
            CommandSorter sorter = new CommandSorter();
            // reltypes
            java.util.Collections.sort( relTypeCommands, sorter );
            for ( Command.RelationshipTypeCommand command : relTypeCommands )
            {
                command.execute();
                addRelationshipType( command.getKey() );
            }
            // nodes
            java.util.Collections.sort( nodeCommands, sorter );
            for ( Command.NodeCommand command : nodeCommands )
            {
                command.execute();
                removeNodeFromCache( command.getKey() );
            }
            // relationships
            java.util.Collections.sort( relCommands, sorter );
            for ( Command.RelationshipCommand command : relCommands )
            {
                command.execute();
                removeRelationshipFromCache( command.getKey() );
            }
            java.util.Collections.sort( propIndexCommands, sorter );
            for ( Command.PropertyIndexCommand command : propIndexCommands )
            {
                command.execute();
                addPropertyIndexCommand( command.getKey() );
            }
            // properties
            java.util.Collections.sort( propCommands, sorter );
            for ( Command.PropertyCommand command : propCommands )
            {
                command.execute();
                removePropertyFromCache( command );
            }
            neoStore.updateIdGenerators();
            if ( !isRecovered() )
            {
                lockReleaser.commit();
            }
        }
        finally
        {
            nodeRecords.clear();
            propertyRecords.clear();
            relRecords.clear();
            relTypeRecords.clear();
            propIndexRecords.clear();

            nodeCommands.clear();
            propCommands.clear();
            propIndexCommands.clear();
            relCommands.clear();
            relTypeCommands.clear();
        }
    }

    private void removePropertyFromCache( PropertyCommand command )
    {
        lockReleaser.clearCache();
    }

    private RelationshipTypeStore getRelationshipTypeStore()
    {
        return neoStore.getRelationshipTypeStore();
    }

    private int getRelGrabSize()
    {
        return neoStore.getRelationshipGrabSize();
    }

    private NodeStore getNodeStore()
    {
        return neoStore.getNodeStore();
    }

    private RelationshipStore getRelationshipStore()
    {
        return neoStore.getRelationshipStore();
    }

    private PropertyStore getPropertyStore()
    {
        return neoStore.getPropertyStore();
    }

    public boolean nodeLoadLight( int nodeId )
    {
        NodeRecord nodeRecord = getNodeRecord( nodeId );
        if ( nodeRecord != null )
        {
            return nodeRecord.inUse();
        }
        return getNodeStore().loadLightNode( nodeId );
    }

    public RelationshipData relationshipLoad( int id )
    {
        RelationshipRecord relRecord = getRelationshipRecord( id );
        if ( relRecord != null )
        {
            if ( !relRecord.inUse() )
            {
                return null;
            }
            return new RelationshipData( id, relRecord.getFirstNode(),
                relRecord.getSecondNode(), relRecord.getType() );
        }
        relRecord = getRelationshipStore().getLightRel( id );
        if ( relRecord != null )
        {
            return new RelationshipData( id, relRecord.getFirstNode(),
                relRecord.getSecondNode(), relRecord.getType() );
        }
        return null;
    }

    void nodeDelete( int nodeId )
    {
        NodeRecord nodeRecord = getNodeRecord( nodeId );
        if ( nodeRecord == null )
        {
            nodeRecord = getNodeStore().getRecord( nodeId );
            addNodeRecord( nodeRecord );
        }
        if ( !nodeRecord.inUse() )
        {
            throw new IllegalStateException( "Unable to delete Node[" + nodeId +
            "] since it has already been deleted." );
        }
        nodeRecord.setInUse( false );
        int nextProp = nodeRecord.getNextProp();
        while ( nextProp != Record.NO_NEXT_PROPERTY.intValue() )
        {
            PropertyRecord propRecord = getPropertyRecord( nextProp );
            if ( propRecord == null )
            {
                propRecord = getPropertyStore().getRecord( nextProp );
                addPropertyRecord( propRecord );
            }
            if ( propRecord.isLight() )
            {
                getPropertyStore().makeHeavy( propRecord );
            }

            nextProp = propRecord.getNextProp();
            propRecord.setInUse( false );
            // TODO: update count on property index record
            for ( DynamicRecord valueRecord : propRecord.getValueRecords() )
            {
                valueRecord.setInUse( false );
            }
        }
    }

    void relDelete( int id )
    {
        RelationshipRecord record = getRelationshipRecord( id );
        if ( record == null )
        {
            record = getRelationshipStore().getRecord( id );
            addRelationshipRecord( record );
        }
        if ( !record.inUse() )
        {
            throw new IllegalStateException( "Unable to delete relationship[" +
                id + "] since it is already deleted." );
        }
        int nextProp = record.getNextProp();
        while ( nextProp != Record.NO_NEXT_PROPERTY.intValue() )
        {
            PropertyRecord propRecord = getPropertyRecord( nextProp );
            if ( propRecord == null )
            {
                propRecord = getPropertyStore().getRecord( nextProp );
                addPropertyRecord( propRecord );
            }
            if ( propRecord.isLight() )
            {
                getPropertyStore().makeHeavy( propRecord );
            }
            nextProp = propRecord.getNextProp();
            propRecord.setInUse( false );
            // TODO: update count on property index record
            for ( DynamicRecord valueRecord : propRecord.getValueRecords() )
            {
                valueRecord.setInUse( false );
            }
        }
        disconnectRelationship( record );
        updateNodes( record );
        record.setInUse( false );
    }

    private void disconnectRelationship( RelationshipRecord rel )
    {
        // update first node prev
        if ( rel.getFirstPrevRel() != Record.NO_NEXT_RELATIONSHIP.intValue() )
        {
            Relationship lockableRel = new LockableRelationship(
                rel.getFirstPrevRel() );
            getWriteLock( lockableRel );
            RelationshipRecord prevRel = getRelationshipRecord(
                rel.getFirstPrevRel() );
            if ( prevRel == null )
            {
                prevRel = getRelationshipStore().getRecord(
                    rel.getFirstPrevRel() );
                addRelationshipRecord( prevRel );
            }
            if ( prevRel.getFirstNode() == rel.getFirstNode() )
            {
                prevRel.setFirstNextRel( rel.getFirstNextRel() );
            }
            else if ( prevRel.getSecondNode() == rel.getFirstNode() )
            {
                prevRel.setSecondNextRel( rel.getFirstNextRel() );
            }
            else
            {
                throw new InvalidRecordException(
                    prevRel + " don't match " + rel );
            }
        }
        // update first node next
        if ( rel.getFirstNextRel() != Record.NO_NEXT_RELATIONSHIP.intValue() )
        {
            Relationship lockableRel = new LockableRelationship(
                rel.getFirstNextRel() );
            getWriteLock( lockableRel );
            RelationshipRecord nextRel = getRelationshipRecord(
                rel.getFirstNextRel() );
            if ( nextRel == null )
            {
                nextRel = getRelationshipStore().getRecord(
                    rel.getFirstNextRel() );
                addRelationshipRecord( nextRel );
            }
            if ( nextRel.getFirstNode() == rel.getFirstNode() )
            {
                nextRel.setFirstPrevRel( rel.getFirstPrevRel() );
            }
            else if ( nextRel.getSecondNode() == rel.getFirstNode() )
            {
                nextRel.setSecondPrevRel( rel.getFirstPrevRel() );
            }
            else
            {
                throw new InvalidRecordException( nextRel + " don't match "
                    + rel );
            }
        }
        // update second node prev
        if ( rel.getSecondPrevRel() != Record.NO_NEXT_RELATIONSHIP.intValue() )
        {
            Relationship lockableRel = new LockableRelationship(
                rel.getSecondPrevRel() );
            getWriteLock( lockableRel );
            RelationshipRecord prevRel = getRelationshipRecord(
                rel.getSecondPrevRel() );
            if ( prevRel == null )
            {
                prevRel = getRelationshipStore().getRecord(
                    rel.getSecondPrevRel() );
                addRelationshipRecord( prevRel );
            }
            if ( prevRel.getFirstNode() == rel.getSecondNode() )
            {
                prevRel.setFirstNextRel( rel.getSecondNextRel() );
            }
            else if ( prevRel.getSecondNode() == rel.getSecondNode() )
            {
                prevRel.setSecondNextRel( rel.getSecondNextRel() );
            }
            else
            {
                throw new InvalidRecordException( prevRel + " don't match " +
                    rel );
            }
        }
        // update second node next
        if ( rel.getSecondNextRel() != Record.NO_NEXT_RELATIONSHIP.intValue() )
        {
            Relationship lockableRel = new LockableRelationship(
                rel.getSecondNextRel() );
            getWriteLock( lockableRel );
            RelationshipRecord nextRel = getRelationshipRecord(
                rel.getSecondNextRel() );
            if ( nextRel == null )
            {
                nextRel = getRelationshipStore().getRecord(
                    rel.getSecondNextRel() );
                addRelationshipRecord( nextRel );
            }
            if ( nextRel.getFirstNode() == rel.getSecondNode() )
            {
                nextRel.setFirstPrevRel( rel.getSecondPrevRel() );
            }
            else if ( nextRel.getSecondNode() == rel.getSecondNode() )
            {
                nextRel.setSecondPrevRel( rel.getSecondPrevRel() );
            }
            else
            {
                throw new InvalidRecordException( nextRel + " don't match " +
                    rel );
            }
        }
    }

    private void getWriteLock( Relationship lockableRel )
    {
        lockManager.getWriteLock( lockableRel );
        lockReleaser.addLockToTransaction( lockableRel, LockType.WRITE );
    }

    public RelationshipChainPosition getRelationshipChainPosition( int nodeId )
    {
        NodeRecord nodeRecord = getNodeRecord( nodeId );
        if ( nodeRecord == null )
        {
            nodeRecord = getNodeStore().getRecord( nodeId );
        }
        else if ( !nodeRecord.inUse() )
        {
            return new RelationshipChainPosition(
                Record.NO_NEXT_RELATIONSHIP.intValue() );
        }
        int nextRel = nodeRecord.getNextRel();
        return new RelationshipChainPosition( nextRel );
    }

    public Iterable<RelationshipData> getMoreRelationships( int nodeId,
        RelationshipChainPosition position )
    {
        int nextRel = position.getNextRecord();
        List<RelationshipData> rels = new ArrayList<RelationshipData>();
        for ( int i = 0; i < getRelGrabSize() &&
            nextRel != Record.NO_NEXT_RELATIONSHIP.intValue(); i++ )
        {
            RelationshipRecord relRecord = getRelationshipRecord( nextRel );
            if ( relRecord == null )
            {
                relRecord = getRelationshipStore().getChainRecord( nextRel );
            }
            if ( relRecord == null )
            {
                // return what we got so far
                position.setNextRecord( Record.NO_NEXT_RELATIONSHIP.intValue() );
                return rels;
            }
            int firstNode = relRecord.getFirstNode();
            int secondNode = relRecord.getSecondNode();
            if ( relRecord.inUse() && !relRecord.isCreated() )
            {
                rels.add( new RelationshipData( relRecord.getId(), firstNode,
                    secondNode, relRecord.getType() ) );
            }
            else
            {
                i--;
            }
            if ( firstNode == nodeId )
            {
                nextRel = relRecord.getFirstNextRel();
            }
            else if ( secondNode == nodeId )
            {
                nextRel = relRecord.getSecondNextRel();
            }
            else
            {
                throw new InvalidRecordException( "Node[" + nodeId +
                    "] not part of firstNode[" + firstNode +
                    "] or secondNode[" + secondNode + "]" );
            }
        }
        position.setNextRecord( nextRel );
        return rels;
    }

    private void updateNodes( RelationshipRecord rel )
    {
        if ( rel.getFirstPrevRel() == Record.NO_PREV_RELATIONSHIP.intValue() )
        {
            NodeRecord firstNode = getNodeRecord( rel.getFirstNode() );
            if ( firstNode == null )
            {
                firstNode = getNodeStore().getRecord( rel.getFirstNode() );
                addNodeRecord( firstNode );
            }
            firstNode.setNextRel( rel.getFirstNextRel() );
        }
        if ( rel.getSecondPrevRel() == Record.NO_PREV_RELATIONSHIP.intValue() )
        {
            NodeRecord secondNode = getNodeRecord( rel.getSecondNode() );
            if ( secondNode == null )
            {
                secondNode = getNodeStore().getRecord( rel.getSecondNode() );
                addNodeRecord( secondNode );
            }
            secondNode.setNextRel( rel.getSecondNextRel() );
        }
    }

    void relRemoveProperty( int relId, int propertyId )
    {
        RelationshipRecord relRecord = getRelationshipRecord( relId );
        if ( relRecord == null )
        {
            relRecord = getRelationshipStore().getRecord( relId );
        }
        if ( !relRecord.inUse() )
        {
            throw new IllegalStateException( "Property remove on relationship[" +
                relId + "] illegal since it has been deleted." );
        }
        PropertyRecord propRecord = getPropertyRecord( propertyId );
        if ( propRecord == null )
        {
            propRecord = getPropertyStore().getRecord( propertyId );
            addPropertyRecord( propRecord );
        }
        if ( !propRecord.inUse() )
        {
            throw new IllegalStateException( "Unable to delete property[" +
                propertyId + "] since it is already deleted." );
        }
        propRecord.setRelId( relId );
        if ( propRecord.isLight() )
        {
            getPropertyStore().makeHeavy( propRecord );
        }

        propRecord.setInUse( false );
        // TODO: update count on property index record
        for ( DynamicRecord valueRecord : propRecord.getValueRecords() )
        {
            if ( valueRecord.inUse() )
            {
                valueRecord.setInUse( false, propRecord.getType().intValue() );
            }
        }
        int prevProp = propRecord.getPrevProp();
        int nextProp = propRecord.getNextProp();
        if ( relRecord.getNextProp() == propertyId )
        {
            relRecord.setNextProp( nextProp );
            // re-adding not a problem
            addRelationshipRecord( relRecord );
        }
        if ( prevProp != Record.NO_PREVIOUS_PROPERTY.intValue() )
        {
            PropertyRecord prevPropRecord = getPropertyRecord( prevProp );
            if ( prevPropRecord == null )
            {
                prevPropRecord = getPropertyStore().getLightRecord( prevProp );
                addPropertyRecord( prevPropRecord );
            }
            assert prevPropRecord.inUse();
            prevPropRecord.setNextProp( nextProp );
        }
        if ( nextProp != Record.NO_NEXT_PROPERTY.intValue() )
        {
            PropertyRecord nextPropRecord = getPropertyRecord( nextProp );
            if ( nextPropRecord == null )
            {
                nextPropRecord = getPropertyStore().getLightRecord( nextProp );
                addPropertyRecord( nextPropRecord );
            }
            assert nextPropRecord.inUse();
            nextPropRecord.setPrevProp( prevProp );
        }
    }

    public ArrayMap<Integer,PropertyData> relGetProperties( int relId )
    {
        RelationshipRecord relRecord = getRelationshipRecord( relId );
        if ( relRecord == null )
        {
            relRecord = getRelationshipStore().getRecord( relId );
        }
        if ( !relRecord.inUse() )
        {
            throw new InvalidRecordException( "Relationship[" + relId +
                "] not in use" );
        }
        int nextProp = relRecord.getNextProp();
        ArrayMap<Integer,PropertyData> propertyMap =
            new ArrayMap<Integer,PropertyData>( 9, false, true );
        while ( nextProp != Record.NO_NEXT_PROPERTY.intValue() )
        {
            PropertyRecord propRecord = getPropertyRecord( nextProp );
            if ( propRecord == null )
            {
                propRecord = getPropertyStore().getLightRecord( nextProp );
            }
            if ( !propRecord.isCreated() )
            {
                propertyMap.put( propRecord.getKeyIndexId(),
                    new PropertyData( propRecord.getId(),
                        propertyGetValueOrNull( propRecord ) ) );
            }
            nextProp = propRecord.getNextProp();
        }
        return propertyMap;
    }

    ArrayMap<Integer,PropertyData> nodeGetProperties( int nodeId )
    {
        NodeRecord nodeRecord = getNodeRecord( nodeId );
        if ( nodeRecord == null )
        {
            nodeRecord = getNodeStore().getRecord( nodeId );
        }
        else if ( !nodeRecord.inUse() )
        {
            throw new InvalidRecordException( "Node[" + nodeId +
                "] not in use" );
        }

        int nextProp = nodeRecord.getNextProp();
        ArrayMap<Integer,PropertyData> propertyMap =
            new ArrayMap<Integer,PropertyData>( 9, false, true );
        while ( nextProp != Record.NO_NEXT_PROPERTY.intValue() )
        {
            PropertyRecord propRecord = getPropertyRecord( nextProp );
            if ( propRecord == null )
            {
                propRecord = getPropertyStore().getLightRecord( nextProp );
            }
            if ( !propRecord.isCreated() )
            {
                propertyMap.put( propRecord.getKeyIndexId(),
                    new PropertyData( propRecord.getId(),
                        propertyGetValueOrNull( propRecord ) ) );
            }
            nextProp = propRecord.getNextProp();
        }
        return propertyMap;
    }

    public Object propertyGetValueOrNull( PropertyRecord propertyRecord )
    {
        PropertyType type = propertyRecord.getType();
        if ( type == PropertyType.INT )
        {
            return (int) propertyRecord.getPropBlock();
        }
        if ( type == PropertyType.STRING )
        {
            return null;
        }
        if ( type == PropertyType.BOOL )
        {
            if ( propertyRecord.getPropBlock() == 1 )
            {
                return Boolean.valueOf( true );
            }
            return Boolean.valueOf( false );
        }
        if ( type == PropertyType.DOUBLE )
        {
            return new Double( Double.longBitsToDouble(
                propertyRecord.getPropBlock() ) );
        }
        if ( type == PropertyType.FLOAT )
        {
            return new Float( Float.intBitsToFloat(
                (int) propertyRecord.getPropBlock() ) );
        }
        if ( type == PropertyType.LONG )
        {
            return propertyRecord.getPropBlock();
        }
        if ( type == PropertyType.BYTE )
        {
            return (byte) propertyRecord.getPropBlock();
        }
        if ( type == PropertyType.CHAR )
        {
            return (char) propertyRecord.getPropBlock();
        }
        if ( type == PropertyType.ARRAY )
        {
            return null;
        }
        if ( type == PropertyType.SHORT )
        {
            return (short) propertyRecord.getPropBlock();
        }
        throw new InvalidRecordException( "Unknown type: " + type +
            " on " + propertyRecord );
    }

    public Object propertyGetValue( int id )
    {
        PropertyRecord propertyRecord = getPropertyRecord( id );
        if ( propertyRecord == null )
        {
            propertyRecord = getPropertyStore().getRecord( id );
        }
        if ( propertyRecord.isLight() )
        {
            getPropertyStore().makeHeavy( propertyRecord );
        }
        PropertyType type = propertyRecord.getType();
        if ( type == PropertyType.INT )
        {
            return (int) propertyRecord.getPropBlock();
        }
        if ( type == PropertyType.STRING )
        {
            return getPropertyStore().getStringFor( propertyRecord );
        }
        if ( type == PropertyType.BOOL )
        {
            if ( propertyRecord.getPropBlock() == 1 )
            {
                return Boolean.valueOf( true );
            }
            return Boolean.valueOf( false );
        }
        if ( type == PropertyType.DOUBLE )
        {
            return new Double( Double.longBitsToDouble(
                propertyRecord.getPropBlock() ) );
        }
        if ( type == PropertyType.FLOAT )
        {
            return new Float( Float.intBitsToFloat(
                (int) propertyRecord.getPropBlock() ) );
        }
        if ( type == PropertyType.LONG )
        {
            return propertyRecord.getPropBlock();
        }
        if ( type == PropertyType.BYTE )
        {
            return (byte) propertyRecord.getPropBlock();
        }
        if ( type == PropertyType.CHAR )
        {
            return (char) propertyRecord.getPropBlock();
        }
        if ( type == PropertyType.ARRAY )
        {
            return getPropertyStore().getArrayFor( propertyRecord );
        }
        if ( type == PropertyType.SHORT )
        {
            return (short) propertyRecord.getPropBlock();
        }
        throw new InvalidRecordException( "Unknown type: " + type +
            " on " + propertyRecord );
    }

    void nodeRemoveProperty( int nodeId, int propertyId )
    {
        NodeRecord nodeRecord = getNodeRecord( nodeId );
        if ( nodeRecord == null )
        {
            nodeRecord = getNodeStore().getRecord( nodeId );
        }
        if ( !nodeRecord.inUse() )
        {
            throw new IllegalStateException( "Property remove on node[" +
                nodeId + "] illegal since it has been deleted." );
        }
        PropertyRecord propRecord = getPropertyRecord( propertyId );
        if ( propRecord == null )
        {
            propRecord = getPropertyStore().getRecord( propertyId );
            addPropertyRecord( propRecord );
        }
        if ( !propRecord.inUse() )
        {
            throw new IllegalStateException( "Unable to delete property[" +
                propertyId + "] since it is already deleted." );
        }
        propRecord.setNodeId( nodeId );
        if ( propRecord.isLight() )
        {
            getPropertyStore().makeHeavy( propRecord );
        }

        propRecord.setInUse( false );
        // TODO: update count on property index record
        for ( DynamicRecord valueRecord : propRecord.getValueRecords() )
        {
            if ( valueRecord.inUse() )
            {
                valueRecord.setInUse( false, propRecord.getType().intValue() );
            }
        }
        int prevProp = propRecord.getPrevProp();
        int nextProp = propRecord.getNextProp();
        if ( nodeRecord.getNextProp() == propertyId )
        {
            nodeRecord.setNextProp( nextProp );
            // re-adding not a problem
            addNodeRecord( nodeRecord );
        }
        if ( prevProp != Record.NO_PREVIOUS_PROPERTY.intValue() )
        {
            PropertyRecord prevPropRecord = getPropertyRecord( prevProp );
            if ( prevPropRecord == null )
            {
                prevPropRecord = getPropertyStore().getLightRecord( prevProp );
                addPropertyRecord( prevPropRecord );
            }
            assert prevPropRecord.inUse();
            prevPropRecord.setNextProp( nextProp );
        }
        if ( nextProp != Record.NO_NEXT_PROPERTY.intValue() )
        {
            PropertyRecord nextPropRecord = getPropertyRecord( nextProp );
            if ( nextPropRecord == null )
            {
                nextPropRecord = getPropertyStore().getLightRecord( nextProp );
                addPropertyRecord( nextPropRecord );
            }
            assert nextPropRecord.inUse();
            nextPropRecord.setPrevProp( prevProp );
        }
    }

    void relChangeProperty( int relId, int propertyId, Object value )
    {
        RelationshipRecord relRecord = getRelationshipRecord( relId );
        if ( relRecord == null )
        {
            relRecord = getRelationshipStore().getRecord( relId );
        }
        if ( !relRecord.inUse() )
        {
            throw new IllegalStateException( "Property change on relationship[" +
                relId + "] illegal since it has been deleted." );
        }
        PropertyRecord propertyRecord = getPropertyRecord( propertyId );
        if ( propertyRecord == null )
        {
            propertyRecord = getPropertyStore().getRecord( propertyId );
            addPropertyRecord( propertyRecord );
        }
        if ( !propertyRecord.inUse() )
        {
            throw new IllegalStateException( "Unable to change property[" +
                propertyId + "] since it is deleted." );
        }
        propertyRecord.setRelId( relId );
        if ( propertyRecord.isLight() )
        {
            getPropertyStore().makeHeavy( propertyRecord );
        }
        if ( propertyRecord.getType() == PropertyType.STRING )
        {
            for ( DynamicRecord record : propertyRecord.getValueRecords() )
            {
                if ( record.inUse() )
                {
                    record.setInUse( false, PropertyType.STRING.intValue() );
                }
            }
        }
        else if ( propertyRecord.getType() == PropertyType.ARRAY )
        {
            for ( DynamicRecord record : propertyRecord.getValueRecords() )
            {
                if ( record.inUse() )
                {
                    record.setInUse( false, PropertyType.ARRAY.intValue() );
                }
            }
        }
        getPropertyStore().encodeValue( propertyRecord, value );
        addPropertyRecord( propertyRecord );
    }

    void nodeChangeProperty( int nodeId, int propertyId, Object value )
    {
        NodeRecord nodeRecord = getNodeRecord( nodeId );
        if ( nodeRecord == null )
        {
            nodeRecord = getNodeStore().getRecord( nodeId );
        }
        if ( !nodeRecord.inUse() )
        {
            throw new IllegalStateException( "Property change on node[" +
                nodeId + "] illegal since it has been deleted." );
        }
        PropertyRecord propertyRecord = getPropertyRecord( propertyId );
        if ( propertyRecord == null )
        {
            propertyRecord = getPropertyStore().getRecord( propertyId );
            addPropertyRecord( propertyRecord );
        }
        if ( !propertyRecord.inUse() )
        {
            throw new IllegalStateException( "Unable to change property[" +
                propertyId + "] since it is deleted." );
        }
        propertyRecord.setNodeId( nodeId );
        if ( propertyRecord.isLight() )
        {
            getPropertyStore().makeHeavy( propertyRecord );
        }
        if ( propertyRecord.getType() == PropertyType.STRING )
        {
            for ( DynamicRecord record : propertyRecord.getValueRecords() )
            {
                if ( record.inUse() )
                {
                    record.setInUse( false, PropertyType.STRING.intValue() );
                }
            }
        }
        else if ( propertyRecord.getType() == PropertyType.ARRAY )
        {
            for ( DynamicRecord record : propertyRecord.getValueRecords() )
            {
                if ( record.inUse() )
                {
                    record.setInUse( false, PropertyType.ARRAY.intValue() );
                }
            }
        }
        getPropertyStore().encodeValue( propertyRecord, value );
        addPropertyRecord( propertyRecord );
    }

    void relAddProperty( int relId, int propertyId, PropertyIndex index,
        Object value )
    {
        RelationshipRecord relRecord = getRelationshipRecord( relId );
        if ( relRecord == null )
        {
            relRecord = getRelationshipStore().getRecord( relId );
            addRelationshipRecord( relRecord );
        }
        if ( !relRecord.inUse() )
        {
            throw new IllegalStateException( "Property add on relationship[" +
                relId + "] illegal since it has been deleted." );
        }
        PropertyRecord propertyRecord = new PropertyRecord( propertyId );
        propertyRecord.setInUse( true );
        propertyRecord.setCreated();
        if ( relRecord.getNextProp() != Record.NO_NEXT_RELATIONSHIP.intValue() )
        {
            PropertyRecord prevProp = getPropertyRecord(
                relRecord.getNextProp() );
            if ( prevProp == null )
            {
                prevProp = getPropertyStore().getLightRecord(
                    relRecord.getNextProp() );
                addPropertyRecord( prevProp );
            }
            assert prevProp.getPrevProp() ==
                Record.NO_PREVIOUS_PROPERTY.intValue();
            prevProp.setPrevProp( propertyId );
            propertyRecord.setNextProp( prevProp.getId() );
        }
        int keyIndexId = index.getKeyId();
        propertyRecord.setKeyIndexId( keyIndexId );
        getPropertyStore().encodeValue( propertyRecord, value );
        relRecord.setNextProp( propertyId );
        addPropertyRecord( propertyRecord );
    }

    void nodeAddProperty( int nodeId, int propertyId, PropertyIndex index,
        Object value )
    {
        NodeRecord nodeRecord = getNodeRecord( nodeId );
        if ( nodeRecord == null )
        {
            nodeRecord = getNodeStore().getRecord( nodeId );
            addNodeRecord( nodeRecord );
        }
        if ( !nodeRecord.inUse() )
        {
            throw new IllegalStateException( "Property add on node[" +
                nodeId + "] illegal since it has been deleted." );
        }

        PropertyRecord propertyRecord = new PropertyRecord( propertyId );
        propertyRecord.setInUse( true );
        propertyRecord.setCreated();
        // encoding has to be set here before anything is change
        // (exception is thrown in encodeValue now and tx not marked
        // rollback only
        getPropertyStore().encodeValue( propertyRecord, value );
        if ( nodeRecord.getNextProp() != Record.NO_NEXT_PROPERTY.intValue() )
        {
            PropertyRecord prevProp = getPropertyRecord(
                nodeRecord.getNextProp() );
            if ( prevProp == null )
            {
                prevProp = getPropertyStore().getLightRecord(
                    nodeRecord.getNextProp() );
                addPropertyRecord( prevProp );
            }
            assert prevProp.getPrevProp() ==
                Record.NO_PREVIOUS_PROPERTY.intValue();
            prevProp.setPrevProp( propertyId );
            propertyRecord.setNextProp( prevProp.getId() );
        }
        int keyIndexId = index.getKeyId();
        propertyRecord.setKeyIndexId( keyIndexId );
        nodeRecord.setNextProp( propertyId );
        addPropertyRecord( propertyRecord );
    }

    void relationshipCreate( int id, int firstNodeId, int secondNodeId,
        int type )
    {
        NodeRecord firstNode = getNodeRecord( firstNodeId );
        if ( firstNode == null )
        {
            firstNode = getNodeStore().getRecord( firstNodeId );
            addNodeRecord( firstNode );
        }
        if ( !firstNode.inUse() )
        {
            throw new IllegalStateException( "First node[" + firstNodeId +
                "] is deleted and cannot be used to create a relationship" );
        }
        NodeRecord secondNode = getNodeRecord( secondNodeId );
        if ( secondNode == null )
        {
            secondNode = getNodeStore().getRecord( secondNodeId );
            addNodeRecord( secondNode );
        }
        if ( !secondNode.inUse() )
        {
            throw new IllegalStateException( "Second node[" + secondNodeId +
                "] is deleted and cannot be used to create a relationship" );
        }
        RelationshipRecord record = new RelationshipRecord( id, firstNodeId,
            secondNodeId, type );
        record.setInUse( true );
        record.setCreated();
        addRelationshipRecord( record );
        connectRelationship( firstNode, secondNode, record );
    }

    private void connectRelationship( NodeRecord firstNode,
        NodeRecord secondNode, RelationshipRecord rel )
    {
        assert firstNode.getNextRel() != rel.getId();
        assert secondNode.getNextRel() != rel.getId();
        rel.setFirstNextRel( firstNode.getNextRel() );
        rel.setSecondNextRel( secondNode.getNextRel() );
        if ( firstNode.getNextRel() != Record.NO_NEXT_RELATIONSHIP.intValue() )
        {
            Relationship lockableRel = new LockableRelationship(
                firstNode.getNextRel() );
            getWriteLock( lockableRel );
            RelationshipRecord nextRel = getRelationshipRecord(
                firstNode.getNextRel() );
            if ( nextRel == null )
            {
                nextRel = getRelationshipStore().getRecord(
                    firstNode.getNextRel() );
                addRelationshipRecord( nextRel );
            }
            if ( nextRel.getFirstNode() == firstNode.getId() )
            {
                nextRel.setFirstPrevRel( rel.getId() );
            }
            else if ( nextRel.getSecondNode() == firstNode.getId() )
            {
                nextRel.setSecondPrevRel( rel.getId() );
            }
            else
            {
                throw new InvalidRecordException( firstNode + " dont match "
                    + nextRel );
            }
        }
        if ( secondNode.getNextRel() != Record.NO_NEXT_RELATIONSHIP.intValue() )
        {
            Relationship lockableRel = new LockableRelationship(
                secondNode.getNextRel() );
            getWriteLock( lockableRel );
            RelationshipRecord nextRel = getRelationshipRecord(
                secondNode.getNextRel() );
            if ( nextRel == null )
            {
                nextRel = getRelationshipStore().getRecord(
                    secondNode.getNextRel() );
                addRelationshipRecord( nextRel );
            }
            if ( nextRel.getFirstNode() == secondNode.getId() )
            {
                nextRel.setFirstPrevRel( rel.getId() );
            }
            else if ( nextRel.getSecondNode() == secondNode.getId() )
            {
                nextRel.setSecondPrevRel( rel.getId() );
            }
            else
            {
                throw new InvalidRecordException( secondNode + " dont match "
                    + nextRel );
            }
        }
        firstNode.setNextRel( rel.getId() );
        secondNode.setNextRel( rel.getId() );
    }

    void nodeCreate( int nodeId )
    {
        NodeRecord nodeRecord = new NodeRecord( nodeId );
        nodeRecord.setInUse( true );
        nodeRecord.setCreated();
        addNodeRecord( nodeRecord );
    }

    String getPropertyIndex( int id )
    {
        PropertyIndexStore indexStore = getPropertyStore().getIndexStore();
        PropertyIndexRecord index = getPropertyIndexRecord( id );
        if ( index == null )
        {
            index = indexStore.getRecord( id );
        }
        if ( index.isLight() )
        {
            indexStore.makeHeavy( index );
        }
        return indexStore.getStringFor( index );
    }

    PropertyIndexData[] getPropertyIndexes( int count )
    {
        PropertyIndexStore indexStore = getPropertyStore().getIndexStore();
        return indexStore.getPropertyIndexes( count );
    }

    void createPropertyIndex( int id, String key )
    {
        PropertyIndexRecord record = new PropertyIndexRecord( id );
        record.setInUse( true );
        record.setCreated();
        PropertyIndexStore propIndexStore = getPropertyStore().getIndexStore();
        int keyBlockId = propIndexStore.nextKeyBlockId();
        record.setKeyBlockId( keyBlockId );
        int length = key.length();
        char[] chars = new char[length];
        key.getChars( 0, length, chars, 0 );
        Collection<DynamicRecord> keyRecords =
            propIndexStore.allocateKeyRecords( keyBlockId, chars );
        for ( DynamicRecord keyRecord : keyRecords )
        {
            record.addKeyRecord( keyRecord );
        }
        addPropertyIndexRecord( record );
    }

    void relationshipTypeAdd( int id, String name )
    {
        RelationshipTypeRecord record = new RelationshipTypeRecord( id );
        record.setInUse( true );
        record.setCreated();
        int blockId = getRelationshipTypeStore().nextBlockId();
        record.setTypeBlock( blockId );
        int length = name.length();
        char[] chars = new char[length];
        name.getChars( 0, length, chars, 0 );
        Collection<DynamicRecord> typeNameRecords =
            getRelationshipTypeStore().allocateTypeNameRecords( blockId, chars );
        for ( DynamicRecord typeRecord : typeNameRecords )
        {
            record.addTypeRecord( typeRecord );
        }
        addRelationshipTypeRecord( record );
    }

    static class CommandSorter implements Comparator<Command>, Serializable
    {
        public int compare( Command o1, Command o2 )
        {
            int id1 = o1.getKey();
            int id2 = o2.getKey();
            return id1 - id2;
        }

        public boolean equals( Object o )
        {
            if ( o instanceof CommandSorter )
            {
                return true;
            }
            return false;
        }

        public int hashCode()
        {
            return 3217;
        }
    }

    void addNodeRecord( NodeRecord record )
    {
        nodeRecords.put( record.getId(), record );
    }

    NodeRecord getNodeRecord( int nodeId )
    {
        return nodeRecords.get( nodeId );
    }

    void addRelationshipRecord( RelationshipRecord record )
    {
        relRecords.put( record.getId(), record );
    }

    RelationshipRecord getRelationshipRecord( int relId )
    {
        return relRecords.get( relId );
    }

    void addPropertyRecord( PropertyRecord record )
    {
        propertyRecords.put( record.getId(), record );
    }

    PropertyRecord getPropertyRecord( int propertyId )
    {
        return propertyRecords.get( propertyId );
    }

    void addRelationshipTypeRecord( RelationshipTypeRecord record )
    {
        relTypeRecords.put( record.getId(), record );
    }

    void addPropertyIndexRecord( PropertyIndexRecord record )
    {
        propIndexRecords.put( record.getId(), record );
    }

    PropertyIndexRecord getPropertyIndexRecord( int id )
    {
        return propIndexRecords.get( id );
    }

    private static class LockableRelationship implements Relationship
    {
        private final int id;

        LockableRelationship( int id )
        {
            this.id = id;
        }

        public void delete()
        {
            throw new UnsupportedOperationException( "Lockable rel" );
        }

        public Node getEndNode()
        {
            throw new UnsupportedOperationException( "Lockable rel" );
        }

        public long getId()
        {
            return this.id;
        }

        public Node[] getNodes()
        {
            throw new UnsupportedOperationException( "Lockable rel" );
        }

        public Node getOtherNode( Node node )
        {
            throw new UnsupportedOperationException( "Lockable rel" );
        }

        public Object getProperty( String key )
        {
            throw new UnsupportedOperationException( "Lockable rel" );
        }

        public Object getProperty( String key, Object defaultValue )
        {
            throw new UnsupportedOperationException( "Lockable rel" );
        }

        public Iterable<String> getPropertyKeys()
        {
            throw new UnsupportedOperationException( "Lockable rel" );
        }

        public Iterable<Object> getPropertyValues()
        {
            throw new UnsupportedOperationException( "Lockable rel" );
        }

        public Node getStartNode()
        {
            throw new UnsupportedOperationException( "Lockable rel" );
        }

        public RelationshipType getType()
        {
            throw new UnsupportedOperationException( "Lockable rel" );
        }

        public boolean isType( RelationshipType type )
        {
            throw new UnsupportedOperationException( "Lockable rel" );
        }

        public boolean hasProperty( String key )
        {
            throw new UnsupportedOperationException( "Lockable rel" );
        }

        public Object removeProperty( String key )
        {
            throw new UnsupportedOperationException( "Lockable rel" );
        }

        public void setProperty( String key, Object value )
        {
            throw new UnsupportedOperationException( "Lockable rel" );
        }

        public boolean equals( Object o )
        {
            if ( !(o instanceof Relationship) )
            {
                return false;
            }
            return this.getId() == ((Relationship) o).getId();
        }

        public int hashCode()
        {
            return id;
        }

        public String toString()
        {
            return "Lockable relationship #" + this.getId();
        }
    }
}


text:
package orm

import (
	"sync"
)

const (
	odCascade             = "cascade"
	odSetNULL             = "set_null"
	odSetDefault          = "set_default"
	odDoNothing           = "do_nothing"
	defaultStructTagName  = "orm"
	defaultStructTagDelim = ";"
)

var (
	modelCache = &_modelCache{
		cache:           make(map[string]*modelInfo),
		cacheByFullName: make(map[string]*modelInfo),
	}
)

// model info collection
type _modelCache struct {
	sync.RWMutex    // only used outsite for bootStrap
	orders          []string
	cache           map[string]*modelInfo
	cacheByFullName map[string]*modelInfo
	done            bool
}

// get all model info
func (mc *_modelCache) all() map[string]*modelInfo {
	m := make(map[string]*modelInfo, len(mc.cache))
	for k, v := range mc.cache {
		m[k] = v
	}
	return m
}

// get orderd model info
func (mc *_modelCache) allOrdered() []*modelInfo {
	m := make([]*modelInfo, 0, len(mc.orders))
	for _, table := range mc.orders {
		m = append(m, mc.cache[table])
	}
	return m
}

// get model info by table name
func (mc *_modelCache) get(table string) (mi *modelInfo, ok bool) {
	mi, ok = mc.cache[table]
	return
}

// get model info by full name
func (mc *_modelCache) getByFullName(name string) (mi *modelInfo, ok bool) {
	mi, ok = mc.cacheByFullName[name]
	return
}

// set model info to collection
func (mc *_modelCache) set(table string, mi *modelInfo) *modelInfo {
	mii := mc.cache[table]
	mc.cache[table] = mi
	mc.cacheByFullName[mi.fullName] = mi
	if mii == nil {
		mc.orders = append(mc.orders, table)
	}
	return mii
}

// clean all model info.
func (mc *_modelCache) clean() {
	mc.orders = make([]string, 0)
	mc.cache = make(map[string]*modelInfo)
	mc.cacheByFullName = make(map[string]*modelInfo)
	mc.done = false
}

// ResetModelCache Clean model cache. Then you can re-RegisterModel.
// Common use this api for test case.
func ResetModelCache() {
	modelCache.clean()
}

redpajama_set_name: RedPajamaGithub


text:
<?php

require_once(dirname(__FILE__) . '/../db/data/models.php');

class CActiveDataProviderTest extends CTestCase
{

    /**
     * @var CDbConnection
     */
    private $db;

    public function setUp()
    {

        if (!extension_loaded('pdo') || !extension_loaded('pdo_sqlite')) {
            $this->markTestSkipped('PDO and SQLite extensions are required.');
        }

        $this->db         = new CDbConnection('sqlite::memory:');
        $this->db->active = true;
        $this->db->pdoInstance->exec(file_get_contents(dirname(__FILE__) . '/../db/data/sqlite.sql'));
        CActiveRecord::$db = $this->db;
    }

    public function tearDown()
    {

        $this->db->active = false;
    }

    public function testCountCriteria()
    {

        // 1
        $dataProvider = new CActiveDataProvider('Post', array(
            'criteria'   => array(
                'condition' => 'content LIKE "%content%"',
                'order'     => 'create_time DESC',
                'with'      => array('author'),
            ),
            'pagination' => array(
                'pageSize' => 5,
            ),
        ));
        $this->assertSame($dataProvider->countCriteria, $dataProvider->criteria);
        $this->assertEquals(5, $dataProvider->getTotalItemCount(true));

        // 2
        $dataProvider->setCountCriteria(
            array(
                'condition' => 'content LIKE "%content 1%"',
            )
        );
        $this->assertNotSame($dataProvider->countCriteria, $dataProvider->criteria);
        $this->assertEquals(1, $dataProvider->getTotalItemCount(true));

        // 3
        $dataProvider->setCountCriteria(
            array(
                'condition' => 'content LIKE "%content%"',
            )
        );
        $this->assertNotSame($dataProvider->countCriteria, $dataProvider->criteria);
        $this->assertEquals(5, $dataProvider->getTotalItemCount(true));
    }
}


text:
			<?php get_sidebar('core'); ?>

Text Inputs

Easily create nicely looking forms with different styles and layouts.

					<?php

						require_once __DIR__ . '/objects/usage.php';
						require_once __DIR__ . '/objects/validation-mods.php';
						require_once __DIR__ . '/objects/size-mods.php';

						require_once __DIR__ . '/objects/help-text.php';
						get_microdata('author');

					?>


text:
require 'net/http'
require 'uri'
require 'json'

module LessonsHelper
end


text:
package com.alibaba.druid.support.http.stat;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;

import java.util.Map;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;

import static com.alibaba.druid.util.JdbcSqlStatUtils.get;

public class WebSessionStat {

    private final static Log                               LOG                                               = LogFactory.getLog(WebSessionStat.class);

    private final String                                   sessionId;

    private volatile int                                   runningCount;
    private volatile int                                   concurrentMax;
    final static AtomicIntegerFieldUpdater<WebSessionStat> runningCountUpdater                               = AtomicIntegerFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "runningCount");
    final static AtomicIntegerFieldUpdater<WebSessionStat> concurrentMaxUpdater                              = AtomicIntegerFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "concurrentMax");

    private volatile long                                  requestCount;
    private volatile long                                  requestErrorCount;
    private volatile long                                  requestTimeNano;

    final static AtomicLongFieldUpdater<WebSessionStat>    requestCountUpdater                               = AtomicLongFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "requestCount");
    final static AtomicLongFieldUpdater<WebSessionStat>    requestErrorCountUpdater                          = AtomicLongFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "requestErrorCount");
    final static AtomicLongFieldUpdater<WebSessionStat>    requestTimeNanoUpdater                            = AtomicLongFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "requestTimeNano");

    private volatile long                                  jdbcFetchRowCount;
    private volatile long                                  jdbcUpdateCount;
    private volatile long                                  jdbcExecuteCount;
    private volatile long                                  jdbcExecuteTimeNano;
    final static AtomicLongFieldUpdater<WebSessionStat>    jdbcFetchRowCountUpdater                          = AtomicLongFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "jdbcFetchRowCount");
    final static AtomicLongFieldUpdater<WebSessionStat>    jdbcUpdateCountUpdater                            = AtomicLongFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "jdbcUpdateCount");
    final static AtomicLongFieldUpdater<WebSessionStat>    jdbcExecuteCountUpdater                           = AtomicLongFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "jdbcExecuteCount");
    final static AtomicLongFieldUpdater<WebSessionStat>    jdbcExecuteTimeNanoUpdater                        = AtomicLongFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "jdbcExecuteTimeNano");

    private volatile long                                  jdbcCommitCount;
    private volatile long                                  jdbcRollbackCount;
    final static AtomicLongFieldUpdater<WebSessionStat>    jdbcCommitCountUpdater                            = AtomicLongFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "jdbcCommitCount");
    final static AtomicLongFieldUpdater<WebSessionStat>    jdbcRollbackCountUpdater                          = AtomicLongFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "jdbcRollbackCount");

    private long                                           createTimeMillis                                  = -1L;
    private volatile long                                  lastAccessTimeMillis                              = -1L;

    private String                                         remoteAddresses;

    private String                                         principal                                         = null;

    private String                                         userAgent;

    private volatile int                                   requestIntervalHistogram_0_1;
    private volatile int                                   requestIntervalHistogram_1_10;
    private volatile int                                   requestIntervalHistogram_10_100;
    private volatile int                                   requestIntervalHistogram_100_1000;
    private volatile int                                   requestIntervalHistogram_1000_10000;
    private volatile int                                   requestIntervalHistogram_10000_100000;
    private volatile int                                   requestIntervalHistogram_100000_1000000;
    private volatile int                                   requestIntervalHistogram_1000000_10000000;
    private volatile int                                   requestIntervalHistogram_10000000_more;

    final static AtomicIntegerFieldUpdater<WebSessionStat> requestIntervalHistogram_0_1_Updater              = AtomicIntegerFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "requestIntervalHistogram_0_1");
    final static AtomicIntegerFieldUpdater<WebSessionStat> requestIntervalHistogram_1_10_Updater             = AtomicIntegerFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "requestIntervalHistogram_1_10");
    final static AtomicIntegerFieldUpdater<WebSessionStat> requestIntervalHistogram_10_100_Updater           = AtomicIntegerFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "requestIntervalHistogram_10_100");
    final static AtomicIntegerFieldUpdater<WebSessionStat> requestIntervalHistogram_100_1000_Updater         = AtomicIntegerFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "requestIntervalHistogram_100_1000");
    final static AtomicIntegerFieldUpdater<WebSessionStat> requestIntervalHistogram_1000_10000_Updater       = AtomicIntegerFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "requestIntervalHistogram_1000_10000");
    final static AtomicIntegerFieldUpdater<WebSessionStat> requestIntervalHistogram_10000_100000_Updater     = AtomicIntegerFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "requestIntervalHistogram_10000_100000");
    final static AtomicIntegerFieldUpdater<WebSessionStat> requestIntervalHistogram_100000_1000000_Updater   = AtomicIntegerFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "requestIntervalHistogram_100000_1000000");
    final static AtomicIntegerFieldUpdater<WebSessionStat> requestIntervalHistogram_1000000_10000000_Updater = AtomicIntegerFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "requestIntervalHistogram_1000000_10000000");
    final static AtomicIntegerFieldUpdater<WebSessionStat> requestIntervalHistogram_10000000_more_Updater    = AtomicIntegerFieldUpdater.newUpdater(WebSessionStat.class,
                                                                                "requestIntervalHistogram_10000000_more");

    public WebSessionStat(String sessionId){
        super();
        this.sessionId = sessionId;
    }

    public void reset() {
        concurrentMaxUpdater.set(this, 0);
        requestCountUpdater.set(this, 0);
        requestErrorCountUpdater.set(this, 0);
        requestTimeNanoUpdater.set(this, 0);

        jdbcFetchRowCountUpdater.set(this, 0);
        jdbcUpdateCountUpdater.set(this, 0);
        jdbcExecuteCountUpdater.set(this, 0);
        jdbcExecuteTimeNanoUpdater.set(this, 0);
        jdbcCommitCountUpdater.set(this, 0);
        jdbcRollbackCountUpdater.set(this, 0);

        remoteAddresses = null;
        principal = null;

        requestIntervalHistogram_0_1_Updater.set(this, 0);
        requestIntervalHistogram_1_10_Updater.set(this, 0);
        requestIntervalHistogram_10_100_Updater.set(this, 0);
        requestIntervalHistogram_100_1000_Updater.set(this, 0);
        requestIntervalHistogram_1000_10000_Updater.set(this, 0);
        requestIntervalHistogram_10000_100000_Updater.set(this, 0);
        requestIntervalHistogram_100000_1000000_Updater.set(this, 0);
        requestIntervalHistogram_1000000_10000000_Updater.set(this, 0);
        requestIntervalHistogram_10000000_more_Updater.set(this, 0);
    }

    public String getUserAgent() {
        return userAgent;
    }

    public void setUserAgent(String userAgent) {
        this.userAgent = userAgent;
    }

    public String getSessionId() {
        return sessionId;
    }

    public long getCreateTimeMillis() {
        return createTimeMillis;
    }

    public String getPrincipal() {
        return principal;
    }

    public void setPrincipal(String principal) {
        this.principal = principal;
    }

    public void setCreateTimeMillis(long createTimeMillis) {
        this.createTimeMillis = createTimeMillis;
    }

    public long getLastAccessTimeMillis() {
        return lastAccessTimeMillis;
    }

    public String getRemoteAddress() {
        return remoteAddresses;
    }

    public void setLastAccessTimeMillis(long lastAccessTimeMillis) {
        if (this.lastAccessTimeMillis > 0) {
            long interval = lastAccessTimeMillis - this.lastAccessTimeMillis;
            requestIntervalHistogramRecord(interval);
        }
        this.lastAccessTimeMillis = lastAccessTimeMillis;
    }

    private void requestIntervalHistogramRecord(long nanoSpan) {
        long millis = nanoSpan / 1000 / 1000;

        if (millis < 1) {
            requestIntervalHistogram_0_1_Updater.incrementAndGet(this);
        } else if (millis < 10) {
            requestIntervalHistogram_1_10_Updater.incrementAndGet(this);
        } else if (millis < 100) {
            requestIntervalHistogram_10_100_Updater.incrementAndGet(this);
        } else if (millis < 1000) {
            requestIntervalHistogram_100_1000_Updater.incrementAndGet(this);
        } else if (millis < 10000) {
            requestIntervalHistogram_1000_10000_Updater.incrementAndGet(this);
        } else if (millis < 100000) {
            requestIntervalHistogram_10000_100000_Updater.incrementAndGet(this);
        } else if (millis < 1000000) {
            requestIntervalHistogram_100000_1000000_Updater.incrementAndGet(this);
        } else if (millis < 10000000) {
            requestIntervalHistogram_1000000_10000000_Updater.incrementAndGet(this);
        } else {
            requestIntervalHistogram_10000000_more_Updater.incrementAndGet(this);
        }
    }

    public void beforeInvoke() {
        int running = runningCountUpdater.incrementAndGet(this);

        for (;;) {
            int max = concurrentMaxUpdater.get(this);
            if (running > max) {
                if (concurrentMaxUpdater.compareAndSet(this, max, running)) {
                    break;
                }
            } else {
                break;
            }
        }

        incrementRequestCount();

        WebRequestStat requestStat = WebRequestStat.current();
        if (requestStat != null) {
            this.setLastAccessTimeMillis(requestStat.getStartMillis());
        }
    }

    public void incrementRequestCount() {
        requestCountUpdater.incrementAndGet(this);
    }

    public void afterInvoke(Throwable error, long nanos) {
        runningCountUpdater.decrementAndGet(this);
        reacord(nanos);
    }

    public void reacord(long nanos) {
        requestTimeNanoUpdater.addAndGet(this, nanos);

        WebRequestStat requestStat = WebRequestStat.current();
        if (requestStat != null) {
            this.addJdbcExecuteCount(requestStat.getJdbcExecuteCount());
            this.addJdbcFetchRowCount(requestStat.getJdbcFetchRowCount());
            this.addJdbcUpdateCount(requestStat.getJdbcUpdateCount());
            this.addJdbcCommitCount(requestStat.getJdbcCommitCount());
            this.addJdbcRollbackCount(requestStat.getJdbcRollbackCount());
            this.addJdbcExecuteTimeNano(requestStat.getJdbcExecuteTimeNano());
        }
    }

    public void addRemoteAddress(String ip) {
        if (remoteAddresses == null) {
            this.remoteAddresses = ip;
            return;
        }

        if (remoteAddresses.contains(ip)) {
            return;
        }

        if (remoteAddresses.length() > 256) {
            LOG.error("session ip change too many");
            return;
        }

        remoteAddresses += ';' + ip;
    }

    public int getRunningCount() {
        return this.runningCount;
    }

    public long getConcurrentMax() {
        return concurrentMax;
    }

    public long getRequestCount() {
        return requestCount;
    }

    public long getRequestErrorCount() {
        return requestErrorCount;
    }

    public long getRequestTimeNano() {
        return requestTimeNano;
    }

    public void addJdbcFetchRowCount(long delta) {
        jdbcFetchRowCountUpdater.addAndGet(this, delta);
    }

    public long getJdbcFetchRowCount() {
        return jdbcFetchRowCount;
    }

    public void addJdbcUpdateCount(long updateCount) {
        jdbcUpdateCountUpdater.addAndGet(this, updateCount);
    }

    public long getJdbcUpdateCount() {
        return jdbcUpdateCount;
    }

    public void incrementJdbcExecuteCount() {
        jdbcExecuteCountUpdater.incrementAndGet(this);
    }

    public void addJdbcExecuteCount(long executeCount) {
        jdbcExecuteCountUpdater.addAndGet(this, executeCount);
    }

    public long getJdbcExecuteCount() {
        return jdbcExecuteCount;
    }

    public long getJdbcExecuteTimeNano() {
        return jdbcExecuteTimeNano;
    }

    public void addJdbcExecuteTimeNano(long nano) {
        jdbcExecuteTimeNanoUpdater.addAndGet(this, nano);
    }

    public void incrementJdbcCommitCount() {
        jdbcCommitCountUpdater.incrementAndGet(this);
    }

    public long getJdbcCommitCount() {
        return jdbcCommitCount;
    }

    public void addJdbcCommitCount(long commitCount) {
        jdbcCommitCountUpdater.addAndGet(this, commitCount);
    }

    public void incrementJdbcRollbackCount() {
        jdbcRollbackCountUpdater.incrementAndGet(this);
    }

    public long getJdbcRollbackCount() {
        return jdbcRollbackCount;
    }

    public void addJdbcRollbackCount(long rollbackCount) {
        jdbcRollbackCountUpdater.addAndGet(this, rollbackCount);
    }

    public long[] getRequestInterval() {
        return new long[] {
                //
                requestIntervalHistogram_0_1, //
                requestIntervalHistogram_1_10, //
                requestIntervalHistogram_10_100, //
                requestIntervalHistogram_100_1000, //
                requestIntervalHistogram_1000_10000, //
                requestIntervalHistogram_10000_100000, //
                requestIntervalHistogram_100000_1000000, //
                requestIntervalHistogram_1000000_10000000, //
                requestIntervalHistogram_10000000_more //
        };
    }

    public Map<String, Object> getStatData() {
        return getValue(false).getStatData();
    }

    public WebSessionStatValue getValue(boolean reset) {
        WebSessionStatValue val = new WebSessionStatValue();

        val.sessionId = sessionId;
        val.runningCount = this.getRunningCount();
        val.concurrentMax = get(this, concurrentMaxUpdater, reset);
        val.requestCount = get(this, requestCountUpdater, reset);
        val.requestErrorCount = get(this, requestErrorCountUpdater, reset);
        val.requestTimeNano = get(this, requestTimeNanoUpdater, reset);
        val.jdbcFetchRowCount = get(this, jdbcFetchRowCountUpdater, reset);
        val.jdbcUpdateCount = get(this, jdbcUpdateCountUpdater, reset);
        val.jdbcExecuteCount = get(this, jdbcExecuteCountUpdater, reset);
        val.jdbcExecuteTimeNano = get(this, jdbcExecuteTimeNanoUpdater, reset);
        val.jdbcCommitCount = get(this, jdbcCommitCountUpdater, reset);
        val.jdbcRollbackCount = get(this, jdbcRollbackCountUpdater, reset);
        val.createTimeMillis = createTimeMillis;
        val.lastAccessTimeMillis = lastAccessTimeMillis;
        val.remoteAddress = remoteAddresses;
        val.principal = principal;
        val.userAgent = userAgent;

        val.requestIntervalHistogram_0_1 = get(this, requestIntervalHistogram_0_1_Updater, reset);
        val.requestIntervalHistogram_1_10 = get(this, requestIntervalHistogram_1_10_Updater, reset);
        val.requestIntervalHistogram_10_100 = get(this, requestIntervalHistogram_10_100_Updater, reset);
        val.requestIntervalHistogram_100_1000 = get(this, requestIntervalHistogram_100_1000_Updater, reset);
        val.requestIntervalHistogram_1000_10000 = get(this, requestIntervalHistogram_1000_10000_Updater, reset);
        val.requestIntervalHistogram_10000_100000 = get(this, requestIntervalHistogram_10000_100000_Updater, reset);
        val.requestIntervalHistogram_100000_1000000 = get(this, requestIntervalHistogram_100000_1000000_Updater, reset);
        val.requestIntervalHistogram_1000000_10000000 = get(this, requestIntervalHistogram_1000000_10000000_Updater,
                                                            reset);
        val.requestIntervalHistogram_10000000_more = get(this, requestIntervalHistogram_10000000_more_Updater, reset);

        return val;
    }
}


text:
// NOTE: this function must be self-contained, i.e. contain no references to variables
// defined outside the function, so that it can be passed into a WebView.

/* eslint-env browser */

const webviewEventCallbackSetup = options => {
  const { window } = options;
  window.eventCallback = (type, detail) => {
    window.postMessage(
      JSON.stringify({
        detail,
        isTngMessage: true,
        type
      })
    );
  };
  window.addEventListener("error", ev => {
    const file = (ev.filename || "").substring(0, 100);
    window.eventCallback(
      "error",
      `msg=${ev.message || ""}, file=${file}, line=${ev.lineno ||
        ""}, col=${ev.colno || ""}`
    );
  });
  // eslint-disable-next-line no-console
  window.console.error = (...args) => {
    window.eventCallback("error", args.join("\n"));
  };
};

export default webviewEventCallbackSetup;


text:
class LoginPage implements ILoginPage {

    //The locators for each page element should only be defined once.
    private usernameLocator = "#Username";
    private passwordLocator = "#Password";
    private submitButtonLocator = "form input[type='submit']";

    startOnLoginPage = () => {
        //casper.echo("base url is : " + casper.cli.options.baseUrl);
        casper.start(casper.cli.options.baseUrl + '/account');
    };

    //There are differences of opinion on whether page objects should include assertions
    //  themselves, or just provide data for test scripts to do the assertions.
    //I prefer this way as it seems to be easier to maintain and easier to read
    //  what the test pages are doing.
    checkWeAreOnTheLoginPage = () => {
        casper.waitForSelector(this.usernameLocator, function () {
            casper.test.assertUrlMatch('account', 'then check we are currently on the login page');
            casper.test.assertExists('form', 'then check that the login page form has been found');
        });
    };

    fillInThePassword = (password : string) => {
        casper.waitForSelector(this.passwordLocator, () => {
            var params = {};
            params[this.passwordLocator] = password;

            casper.fillSelectors('form', params, false);
            casper.test.assertExists(this.passwordLocator, "then fill in the password with " + password);
        });
    };

    fillInTheUsername = (username : string) => {
        casper.waitForSelector(this.usernameLocator,  () => {
            var params = {};
            params[this.usernameLocator] = username;

            casper.fillSelectors('form', params, false);
            casper.test.assertExists(this.usernameLocator, "then fill in the username with " + username);
        });
    };

    submitForm = () => {
        casper.then(() => {
            casper.test.assertExists(this.submitButtonLocator, "then submit the login form");
            casper.click(this.submitButtonLocator);
        });
    };

    checkUsernameValidationIsShown = () => {
        casper.waitForSelector(this.usernameLocator, () => {
            casper.test.assertTextExists("The Username field is required", "then check the username required message is shown");
        });
    }

    checkPasswordValidationIsShown = () => {
        casper.waitForSelector(this.usernameLocator, () => {
            casper.test.assertTextExists("The Password field is required", "then check the password required message is shown");
        });
    }

    fullLogin = (username : string, password : string) => {
        this.startOnLoginPage();
        this.checkWeAreOnTheLoginPage();
        this.fillInTheUsername(username);
        this.fillInThePassword(password);
        this.submitForm();
    };

}

interface ILoginPage {
    startOnLoginPage:Function;
    fullLogin:Function;
    checkWeAreOnTheLoginPage:Function;
    fillInTheUsername:Function;
    fillInThePassword:Function;
    submitForm:Function;
    checkUsernameValidationIsShown:Function;
    checkPasswordValidationIsShown:Function;
}


text:
<?php

namespace g5\MovieBundle\DataFixtrues\MongoDB;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

use g5\MovieBundle\Document\Label;

class LoadLabelData extends AbstractFixture implements ContainerAwareInterface, OrderedFixtureInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * {@inheritDoc}
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        $user = $this->getReference('test-user');

        $labelData = array(
            array('name' => 'Horror'),
            array('name' => 'Action'),
            array('name' => 'Top-Hits'),
        );

        foreach ($labelData as $data) {
            $label = new Label();
            $label->setName($data['name']);
            $label->setUser($user);

            $manager->persist($label);
            $this->addReference('label-'.$label->getName(), $label);
        }

        $manager->flush();
    }

    /**
     * {@inheritDoc}
     */
    public function getOrder()
    {
        return 2;
    }
}


text:
package com.mechjack.dispatch;

import com.mechjack.BadRequestException;

@SuppressWarnings("serial")
public final class UnsupportedMediaTypeException
    extends BadRequestException {

  public UnsupportedMediaTypeException(final String message) {
    super(message);
  }

}


text:
import textStyle from '../stateManagement/textStyle.js';
import { draw, fillTextLines, fillBox } from './drawing.js';

/**
 * Compute the width of the box required to display the given `text` with a given `padding`.
 *
 * @param {CanvasRenderingContext2D} context
 * @param {String} text - The text to find the width of.
 * @param {Number} padding - The padding to apply on either end of the text.
 */
export function textBoxWidth (context, text, padding) {
  const font = textStyle.getFont();
  const origFont = context.font;

  if (font && font !== origFont) {
    context.font = font;
  }
  const width = context.measureText(text).width;

  if (font && font !== origFont) {
    context.font = origFont;
  }

  return width + 2 * padding;
}

export default function (context, textLines, x, y, color, options) {
  if (Object.prototype.toString.call(textLines) !== '[object Array]') {
    textLines = [textLines];
  }

  const padding = 5;
  const fontSize = textStyle.getFontSize();
  const backgroundColor = textStyle.getBackgroundColor();

  // Find the longest text width in the array of text data
  let maxWidth = 0;

  textLines.forEach(function (text) {
    // Get the text width in the current font
    const width = textBoxWidth(context, text, padding);

    // Find the maximum with for all the text rows;
    maxWidth = Math.max(maxWidth, width);
  });

  // Calculate the bounding box for this text box
  const boundingBox = {
    width: maxWidth,
    height: padding + textLines.length * (fontSize + padding)
  };

  draw(context, (context) => {
    context.strokeStyle = color;

    // Draw the background box with padding
    if (options && options.centering && options.centering.x === true) {
      x -= boundingBox.width / 2;
    }

    if (options && options.centering && options.centering.y === true) {
      y -= boundingBox.height / 2;
    }

    boundingBox.left = x;
    boundingBox.top = y;

    const fillStyle = (options && options.debug === true) ? '#FF0000' : backgroundColor;

    fillBox(context, boundingBox, fillStyle);

    // Draw each of the text lines on top of the background box
    fillTextLines(context, boundingBox, textLines, color, padding);
  });

  // Return the bounding box so it can be used for pointNearHandle
  return boundingBox;
}


text:
package mappers

import (
	"fmt"
	"net/http"
)

func String(hashName string, request *http.Request, strict bool) (interface{}, error) {

	if _, found := request.PostForm[hashName]; !found && strict {

		return nil, fmt.Errorf("key '%s' not found", hashName)
	}

	return request.PostForm.Get(hashName), nil
}


text:
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.common.data;

import com.google.gerrit.reviewdb.client.Change;

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

/** Contains a set of ApprovalSummary objects, keyed by the change id
 * from which they were derived.
 */
public class ApprovalSummarySet {
  protected AccountInfoCache accounts;

  protected Map<Change.Id, ApprovalSummary> summaries;

  protected ApprovalSummarySet() {
  }

  public ApprovalSummarySet(final AccountInfoCache accts,
      final Map<Change.Id, ApprovalSummary> map) {
    accounts = accts;

    summaries = new HashMap<Change.Id, ApprovalSummary>();
    summaries.putAll(map);
  }

  public AccountInfoCache getAccountInfoCache() {
    return accounts;
  }

  public Map<Change.Id, ApprovalSummary> getSummaryMap() {
    return Collections.unmodifiableMap(summaries);
  }
}


text:
package passwordless

import (
	log "github.com/Sirupsen/logrus"
	"github.com/gorilla/context"
	"github.com/gorilla/securecookie"
	"github.com/gorilla/sessions"
	"net/http"
	"os"
)

const (
	contextUser string = "User"
	sessionUser string = "_user_id"
)

var store *sessions.CookieStore
var secretKey []byte

// GetSession returns the session for the site.
func GetSession(r *http.Request) *sessions.Session {
	session, err := store.Get(r, "site")
	if err != nil {
		log.Error("problem decoding session ... ", err)
	}
	return session
}

// GetContextUser returns the User for the given request context or nil.
func GetContextUser(r *http.Request) *User {
	log.Debug("context contents are...", context.GetAll(r))
	if user, ok := context.GetOk(r, contextUser); ok {
		return user.(*User)
	}
	log.Debug("in GetContextUser...no user!")
	return nil
}

// SetContextUser stores the given user in the request context.
func SetContextUser(user *User, r *http.Request) {
	log.Debug("setting context!")
	context.Set(r, contextUser, user)
}

// Login adds the User's id to the session.
func Login(u *User, w http.ResponseWriter, r *http.Request) {
	log.Debug("in login...", u.Id)
	s := GetSession(r)
	s.Values[sessionUser] = u.Id
	err := s.Save(r, w)
	if err != nil {
		log.Debug("...something went wrong saving!!!...", err)
	}
	log.Debug("in login after session save...", s.Values)
	//SetContextUser(u, r)
}

// Logout removes the User from their session.
func Logout(w http.ResponseWriter, r *http.Request) {
	s := GetSession(r)
	delete(s.Values, sessionUser)
	s.Save(r, w)
}

// IsLoggedIn is a convenience function for checking if a User exists in the request context.
func IsLoggedIn(r *http.Request) bool {
	return GetContextUser(r) != nil
}

func init() {
	//log.Debug("****calling init in auth...")
	authKey := os.Getenv("AUTH_KEY")
	if authKey == "" {
		log.Panic("Missing required environment variable 'AUTH_KEY'.")
	}

	encryptKey := os.Getenv("ENCRYPT_KEY")
	if encryptKey == "" {
		log.Panic("Missing required environment variable 'ENCRYPT_KEY' (16, 24, 32 bytes in length).")
	}

	store = sessions.NewCookieStore(securecookie.GenerateRandomKey(32), securecookie.GenerateRandomKey(32)) //[]byte(authKey), []byte(encryptKey))

	//	store.Options = &sessions.Options{
	//		Domain:   "localhost",
	//		Path:     "/",
	//		MaxAge:   3600 * 8, // 8 hours
	//		HttpOnly: true,
	//	}

}


text:
package org.elasticsearch.index.query;

import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.support.QueryInnerHitBuilder;

import java.io.IOException;

public class NestedFilterBuilder extends BaseFilterBuilder {

    private final QueryBuilder queryBuilder;
    private final FilterBuilder filterBuilder;

    private final String path;
    private Boolean join;

    private String filterName;

    private QueryInnerHitBuilder innerHit = null;

    public NestedFilterBuilder(String path, QueryBuilder queryBuilder) {
        this.path = path;
        this.queryBuilder = queryBuilder;
        this.filterBuilder = null;
    }

    public NestedFilterBuilder(String path, FilterBuilder filterBuilder) {
        this.path = path;
        this.queryBuilder = null;
        this.filterBuilder = filterBuilder;
    }

    public NestedFilterBuilder join(boolean join) {
        this.join = join;
        return this;
    }

    /**
     * Sets the filter name for the filter that can be used when searching for matched_filters per hit.
     */
    public NestedFilterBuilder filterName(String filterName) {
        this.filterName = filterName;
        return this;
    }

    /**
     * Sets inner hit definition in the scope of this nested filter and reusing the defined path and query.
     */
    public NestedFilterBuilder innerHit(QueryInnerHitBuilder innerHit) {
        this.innerHit = innerHit;
        return this;
    }

    @Override
    protected void doXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject(NestedFilterParser.NAME);
        if (queryBuilder != null) {
            builder.field("query");
            queryBuilder.toXContent(builder, params);
        } else {
            builder.field("filter");
            filterBuilder.toXContent(builder, params);
        }
        if (join != null) {
            builder.field("join", join);
        }
        builder.field("path", path);
        if (filterName != null) {
            builder.field("_name", filterName);
        }
        if (innerHit != null) {
            builder.startObject("inner_hits");
            builder.value(innerHit);
            builder.endObject();
        }
        builder.endObject();
    }
}


text:
CREATE TABLE event (
    id bigint NOT NULL PRIMARY KEY,
    is_weighted boolean,
    name character varying(255)
);

CREATE SEQUENCE event_id_sequence
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


text:
* [FEATURE] Handle Problems in Validation errors https://github.com/penseo/webflow-ruby/pull/14 https://github.com/penseo/webflow-ruby/pull/16 😍 @vfonic @sega

## 1.2.0
* [FEATURE] Add patch support for updating items https://github.com/penseo/webflow-ruby/issues/10 😍 @ukd1

## 1.1.0

* [FEATURE] Allow passing a block to `items` that yields the results by page https://github.com/penseo/webflow-ruby/issues/9 😍 @emilesilvis
* [FEATURE] Handle Webflow live feature https://github.com/penseo/webflow-ruby/pull/8 😍 @emilesilvis

## 1.0.0

* [BREAKING] Raise errors when status > 200, see also https://github.com/penseo/webflow-ruby/pull/7 😍 @sega

## 0.7.0

* [FEATURE] Configuration class to store api token https://github.com/penseo/webflow-ruby/pull/6 😍 @mateuscruz

## 0.6.0

* [CHANGE] Use pure ruby dependencies

## 0.5.0

* [FEATURE] Pagination https://github.com/penseo/webflow-ruby/pull/2 😍 @cohesiveneal