text:
package com.gs.fw.common.mithra.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gs.fw.common.mithra.*;
import com.gs.fw.common.mithra.finder.Operation;
import com.gs.fw.common.mithra.test.domain.*;
import com.gs.fw.common.mithra.util.MithraPerformanceData;
import com.gs.fw.common.mithra.util.DefaultInfinityTimestamp;

import javax.transaction.Synchronization;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.concurrent.Exchanger;

public class TestPureBitemporalTransactionalObject extends MithraTestAbstract
{
    static private Logger logger = LoggerFactory.getLogger(TestTransactionalObject.class.getName());

    private static SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private final Timestamp businessDate = new Timestamp(System.currentTimeMillis());

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

    public Class[] getRestrictedClassList()
    {
        return new Class[]
        {
            PureBitemporalOrder.class,
            PureBitemporalOrderItem.class,
        };
    }

    public void setNullAndBack()
    {
        PureBitemporalOrder order = PureBitemporalOrderFinder.findOne(PureBitemporalOrderFinder.orderId().eq(1));
        int oldUserId = order.getUserId();
        MithraTransaction tx = MithraManager.getInstance().startOrContinueTransaction();

        order.setUserIdNull();
        order.setUserId(oldUserId);
        tx.commit();
        assertEquals(oldUserId, order.getUserId());
    }

    public void testComplexQueryInsideTransaction()
    {
        Operation op = PureBitemporalOrderFinder.items().order().description().contains("order");
        op = op.and(PureBitemporalOrderFinder.businessDate().eq(businessDate));
        assertEquals(2, PureBitemporalOrderFinder.findMany(op).size());
        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand<Object>()
        {
            @Override
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                Operation op = PureBitemporalOrderFinder.items().order().description().contains("order");
                op = op.and(PureBitemporalOrderFinder.businessDate().eq(businessDate));
                assertEquals(2, PureBitemporalOrderFinder.findMany(op).size());
                return null;
            }
        });

    }

    public void testInnerTransactionRetriable()
    {
        final int[] count = new int[1];
        count[0] = 0;
        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand()
        {
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                PureBitemporalOrder order = new PureBitemporalOrder(businessDate);
                order.setNullablePrimitiveAttributesToNull();
                order.setOrderId(999);
                order.insert();
                try
                {
                    MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand()
                    {
                        public Object executeTransaction(MithraTransaction tx) throws Throwable
                        {
                            count[0]++;
                            if (count[0] == 1)
                            {
                                MithraBusinessException excp = new MithraBusinessException("for testing");
                                excp.setRetriable(true);
                                throw excp;
                            }
                            return null;
                        }
                    });
                }
                catch (Exception e)
                {
                    assertTrue(count[0] == 1);
                }
                return null;
            }
        });
        PureBitemporalOrderFinder.clearQueryCache();
        PureBitemporalOrder order2 = findOrderNow(PureBitemporalOrderFinder.orderId().eq(999));
        assertNotNull(order2);
    }

    private PureBitemporalOrder findOrderNow(Operation operation)
    {
        return PureBitemporalOrderFinder.findOne(operation.and(PureBitemporalOrderFinder.businessDate().eq(businessDate)));
    }

    public void testSetPrimitiveAttributesToNullToInMemoryObject()
    {
        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand()
        {
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                PureBitemporalOrder order = new PureBitemporalOrder(businessDate);
                order.setNullablePrimitiveAttributesToNull();
                order.setOrderId(999);
                order.insert();
                return null;
            }
        });
        PureBitemporalOrderFinder.clearQueryCache();
        PureBitemporalOrder order2 = findOrderNow(PureBitemporalOrderFinder.orderId().eq(999));
        assertNotNull(order2);
        assertTrue(order2.isUserIdNull());
    }

    public void testSetPrimitiveAttributesToNullToPersistedObjectWithReadOnlyAttribute()
    {
        try
        {
            MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand<Object>()
            {
                @Override
                public Object executeTransaction(MithraTransaction tx) throws Throwable
                {
                    Operation op = PureBitemporalOrderItemFinder.id().eq(1);
                    op = op.and(PureBitemporalOrderItemFinder.businessDate().eq(businessDate));
                    PureBitemporalOrderItem item = PureBitemporalOrderItemFinder.findOne(op);
                    assertNotNull(item);
                    item.setNullablePrimitiveAttributesToNull();
                    fail("Should not get here");
                    return null;
                }
            });
        }
        catch(MithraBusinessException e)
        {
            assertTrue(e.getMessage().contains("readonly"));
            getLogger().info("Expected Exception. OrderItem has a readOnly attribute and cannot be updated when is already persisted");
        }
    }

    public void testQueryInsideTransaction()
    {
        MithraPerformanceData data = PureBitemporalOrderFinder.getMithraObjectPortal().getPerformanceData();
        int cacheHits = data.getObjectCacheHits();
        MithraTransaction tx = MithraManager.getInstance().startOrContinueTransaction();
        PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
        tx.commit();
        assertNotNull(order);
        assertTrue(data.getObjectCacheHits() > cacheHits);
    }
    /* this is not a trivial test; just look at the implementation of get/setOrderId() */
    public void testSetter()
    {
        PureBitemporalOrder order = new PureBitemporalOrder(businessDate);
        order.setOrderId(17);
        assertEquals(order.getOrderId(), 17);
    }

    public void testMaxLengthWithTruncate()
    {
        String longDescription="0123456789A123456789B123456789C123456789D123456789E123456789F";
        String truncatedDescription="0123456789A123456789B123456789C123456789D123456789";
        PureBitemporalOrder order = new PureBitemporalOrder(businessDate);
        order.setDescription(longDescription);
        assertEquals(truncatedDescription, order.getDescription());
    }

    public void testTransactionalRetrieve()
    {
        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand()
        {
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
                assertNotNull(order);
                assertTrue(order.zIsParticipatingInTransaction(tx));
                return null;
            }
        });
    }

    public void testUpdateOneRow()
            throws SQLException
    {
        final PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
        assertNotNull(order);
        final int oldValue = order.getUserId();
        final PureBitemporalOrderList firstList = findForUserId(oldValue);
        int oldSize = firstList.size();
        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand()
        {
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                int newValue = oldValue+10000;
                order.setUserId(newValue);
                assertEquals(order.getUserId(), newValue);
                checkUserId(newValue, 1);
                return null;
            }
        });

        PureBitemporalOrderList list = findForUserId(oldValue);
        assertEquals(oldSize, list.size()+1);
    }

    private PureBitemporalOrderList findForUserId(int userId)
    {
        return new PureBitemporalOrderList(PureBitemporalOrderFinder.userId().eq(userId).and(PureBitemporalOrderFinder.businessDate().eq(businessDate)));
    }

    private void checkUserId(int newValue, int orderId)
            throws SQLException
    {
        PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId));
        assertNotNull(order);
        assertEquals(newValue, order.getUserId());
    }

    private void checkPureBitemporalOrderExists(int orderId)
            throws SQLException
    {
        assertNotNull(findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId)));
    }

    private void checkPureBitemporalOrderDoesNotExist(int orderId)
            throws SQLException
    {
        assertNull(findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId)));
    }

    public void testInsert() throws SQLException
    {
        final int orderId = 1017;
        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand()
        {
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                PureBitemporalOrder order = new PureBitemporalOrder(businessDate);
                order.setOrderId(orderId);
                Timestamp orderDate = new Timestamp(System.currentTimeMillis());
                order.setOrderDate(orderDate);
                String description = "new order description";
                order.setDescription(description);
                order.insert();
                int dbCount = getRetrievalCount();
                PureBitemporalOrder order2 = findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId));
                assertSame(order, order2);
                assertEquals(dbCount, getRetrievalCount());
                return null;
            }
        });
    }

    public void testInsertForRecovery() throws SQLException
    {
        final int orderId = 1017;
        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand()
        {
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                PureBitemporalOrder order = new PureBitemporalOrder(businessDate);
                order.setOrderId(orderId);
                Timestamp orderDate = new Timestamp(System.currentTimeMillis());
                order.setOrderDate(orderDate);
                order.setBusinessDateFrom(businessDate);
                order.setBusinessDateTo(DefaultInfinityTimestamp.getDefaultInfinity());
                order.setProcessingDateFrom(new Timestamp(System.currentTimeMillis()));
                order.setProcessingDateTo(DefaultInfinityTimestamp.getDefaultInfinity());
                String description = "new order description";
                order.setDescription(description);
                order.insertForRecovery();
                int dbCount = getRetrievalCount();
                PureBitemporalOrder order2 = findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId));
                assertSame(order, order2);
                assertEquals(dbCount, getRetrievalCount());
                return null;
            }
        });
    }

    public void testBatchInsertWithDatabaseRollback() throws SQLException
    {
        final int orderId = 1017;
        try
        {
            MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand()
                        {
                            public Object executeTransaction(MithraTransaction mithraTransaction) throws Throwable
                            {
                                PureBitemporalOrder order = new PureBitemporalOrder(businessDate);
                                order.setOrderId(orderId);
                                Timestamp orderDate = new Timestamp(System.currentTimeMillis());
                                order.setOrderDate(orderDate);
                                String description = "new order description";
                                order.setDescription(description);
                                order.insert();
                                PureBitemporalOrder order2 = new PureBitemporalOrder(businessDate);
                                order2.setOrderId(orderId);
                                order2.setOrderDate(orderDate);
                                order2.setDescription(description);
                                order2.insert();
                                return null;
                            }
                        });
            fail("should not get here.");
        }
        catch(MithraDatabaseException e)
        {
            // ok
        }
        checkPureBitemporalOrderDoesNotExist(orderId);
    }

    public void testTerminate()
            throws SQLException
    {
        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand()
        {
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
                assertNotNull(order);
                order.terminate();
                PureBitemporalOrder order2 = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
                assertNull(order2);
                return null;
            }
        });

        checkPureBitemporalOrderDoesNotExist(1);
    }

    public void testTerminateMultiple()
    {
        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand()
        {
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                PureBitemporalOrderList list = findForUserId(1);
                assertTrue(list.size() > 0);
                PureBitemporalOrder[] elements = list.elements();
                for(int i=0;i<elements.length;i++)
                {
                    elements[i].terminate();
                }
                return null;
            }
        });
        PureBitemporalOrderList list2 = findForUserId(1);
        assertEquals(0, list2.size());
    }

    public void testQueryExpiration()
    {
        final PureBitemporalOrderList firstList = findForUserId(1);
        firstList.setOrderBy(PureBitemporalOrderFinder.orderId().ascendingOrderBy());
        firstList.forceResolve();
        assertTrue(firstList.size() > 0);
        assertFalse(firstList.isStale());
        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand()
        {
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                PureBitemporalOrder order = firstList.getPureBitemporalOrderAt(0);
                order.setUserId(order.getUserId()+1000);
                assertTrue(firstList.isStale());
                return null;
            }
        });
        PureBitemporalOrderList secondList = findForUserId(1);
        secondList.forceResolve();
        assertTrue(secondList.size() < firstList.size());
    }

    public void testMultipleSet() throws SQLException
    {
        final int orderId = 1;
        final int newValue = 7;
        final String description = "new long description";
        PureBitemporalOrder order = (PureBitemporalOrder) MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand()
        {
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId));
                order.setUserId(newValue);
                order.setDescription(description);
                return order;
            }
        });

        assertEquals(order.getUserId(), newValue);
        assertEquals(order.getDescription(), description);
    }

    public void testMaximumStringLength() throws Exception
    {
        MithraTransaction tx = null;
        boolean setDescription = false;
        boolean rolledBack = false;
        try
        {
            tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
            int orderId = 1;
            PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId));

            String description = "123456789012345678901234567890123456789012345678901234567890112345678901234567890123456789011234567890123456789012345678901";
            order.setDescription(description); // should not fail, as it trims.
            setDescription = true;
            String state = "1234567890123456789012345678901";
            // this set will cause an exception due to state.length longer then maxLength defined.
            order.setState(state);
            tx.commit();
        }
        catch (MithraBusinessException e)
        {
            rolledBack = true;
            // expected
            if (tx != null)
            {
                tx.rollback();
            }
        }
        assertTrue(setDescription);
        assertTrue(rolledBack);
    }

    public void testSingleSet() throws SQLException
    {
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        int orderId = 1;
        int newValue = 7;
        PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId));
        order.setUserId(newValue);
        tx.commit();

        assertEquals(order.getUserId(), newValue);
    }

    public void testTransactionalMethod() throws SQLException
    {
        int orderId = 1;
        int newValue = 7;
        String description = "new long description";
        PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId));
        order.setUserIdAndDescription(newValue,description);

        assertEquals(newValue, order.getUserId());
        assertEquals(description, order.getDescription());
    }

    public void testTransactionalMethodWithException() throws SQLException
    {
        int orderId = 1;
        int newValue = 7;
        String description = "";
        PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId));
        assertTrue(order.getDescription().length() > 0);
        int oldUserId = order.getUserId();
        try
        {
            order.setUserIdAndDescription(newValue,description);
            fail("should've thrown an exception");
        }
        catch (IllegalArgumentException e)
        {
            // expected
        }

        this.checkUserId(oldUserId, orderId);
    }

    public void testTerminateAddSameFind()
    {
        MithraTransaction tx = null;
        try
        {
            int orderId = 1;
            tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
            PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId));
            order.terminate();
            assertNull(findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId)));
            PureBitemporalOrder order2 = new PureBitemporalOrder(businessDate);
            order2.setOrderId(orderId);
            order2.setState("test state");
            order2.setDescription("test description");
            order2.setUserId(2);
            order2.setOrderDate(new Timestamp(System.currentTimeMillis()));
            order2.insert();
            PureBitemporalOrder order3 = findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId));
            assertSame(order3, order2);
        }
        finally
        {
            if (tx != null)
            {
                tx.commit();
            }
        }
    }

    public void testRollbackInsertDelete() throws SQLException
    {
        int orderId = 11111;
        checkPureBitemporalOrderDoesNotExist(orderId);
        PureBitemporalOrder order = new PureBitemporalOrder(businessDate);
        order.setOrderId(orderId);
        order.setState("test state");
        order.setDescription("test description");
        order.setUserId(2);
        order.setOrderDate(new Timestamp(System.currentTimeMillis()));
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        order.insert();
        order.terminate();
        tx.rollback();
        assertTrue(order.isInMemoryAndNotInserted());
        checkPureBitemporalOrderDoesNotExist(orderId);
    }

    public void testRollbackUpdate() throws SQLException
    {
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        int orderId = 1;
        int newUserId = 7;
        String description = "new long description";
        PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId));
        int oldUserId = order.getUserId();
        String oldDescription = order.getDescription();
        order.setUserId(newUserId);
        order.setDescription(description);
        tx.rollback();
        assertEquals(oldUserId, order.getUserId());
        assertEquals(oldDescription, order.getDescription());
        checkUserId(oldUserId, orderId);
    }

    public void testRollbackDelete() throws SQLException
    {
        int orderId = 1;
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId));
        order.terminate();
        tx.rollback();
        PureBitemporalOrder order2 = findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId));
        order.getUserId(); // make sure it doesn't throw an exception here.
        assertSame(order2, order);

        checkPureBitemporalOrderExists(orderId);
    }

    public void testRollbackInsert() throws SQLException
    {
        int orderId = 11111;
        PureBitemporalOrder order = new PureBitemporalOrder(businessDate);
        order.setOrderId(orderId);
        order.setState("test state");
        order.setDescription("test description");
        order.setUserId(2);
        order.setOrderDate(new Timestamp(System.currentTimeMillis()));
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        order.insert();
        tx.rollback();
        assertTrue(order.isInMemoryAndNotInserted());

        checkPureBitemporalOrderDoesNotExist(orderId);
    }

    public void testCommitInsertTerminate() throws SQLException
    {
        int orderId = 11111;
        PureBitemporalOrder order = new PureBitemporalOrder(businessDate);
        order.setOrderId(orderId);
        order.setState("test state");
        order.setDescription("test description");
        order.setUserId(2);
        order.setOrderDate(new Timestamp(System.currentTimeMillis()));
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        order.insert();
        order.terminate();
        tx.commit();
        checkPureBitemporalOrderDoesNotExist(orderId);
    }

    public void testCommitTerminate() throws SQLException
    {
        int orderId = 1;
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(orderId));
        order.terminate();
        tx.commit();

        checkPureBitemporalOrderDoesNotExist(orderId);
    }

    public void testInsertAndUpdate() throws SQLException
    {
        PureBitemporalOrder order = new PureBitemporalOrder(businessDate);
        int orderId = 1017;
        order.setOrderId(orderId);
        Timestamp orderDate = new Timestamp(System.currentTimeMillis());
        order.setOrderDate(orderDate);
        String description = "new order description";
        order.setDescription(description);
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        order.insert();

        order.setUserId(17);
        tx.commit();
        checkUserId(17, orderId);
    }

    public void testInsertAndFindInTransaction() throws SQLException
    {
        int userId = 17111;
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        PureBitemporalOrder order = new PureBitemporalOrder(businessDate);
        int orderId = 1017;
        order.setOrderId(orderId);
        findOrderNow(PureBitemporalOrderFinder.userId().eq(userId)); // causes the tx to flush after we've enrolled this object
        Timestamp orderDate = new Timestamp(System.currentTimeMillis());
        order.setOrderDate(orderDate);
        String description = "new order description";
        order.setDescription(description);
        order.setUserId(userId);
        order.insert();

        order = findOrderNow(PureBitemporalOrderFinder.userId().eq(userId));

        tx.commit();
        assertNotNull(order);
        checkUserId(userId, orderId);
    }

    public void testInsertAndUpdateInTransaction() throws SQLException
    {
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        PureBitemporalOrder order = new PureBitemporalOrder(businessDate);
        int orderId = 1017;
        order.setOrderId(orderId);
        Timestamp orderDate = new Timestamp(System.currentTimeMillis());
        order.setOrderDate(orderDate);
        String description = "new order description";
        order.setDescription(description);
        order.insert();

        order.setUserId(17);
        tx.commit();
        checkUserId(17, orderId);
    }

    public void testInsertAndUpdateAndInsertInTransaction() throws SQLException
    {
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        PureBitemporalOrder order = new PureBitemporalOrder(businessDate);
        int orderId = 1017;
        order.setOrderId(orderId);
        Timestamp orderDate = new Timestamp(System.currentTimeMillis());
        order.setOrderDate(orderDate);
        String description = "new order description";
        order.setDescription(description);
        order.insert();

        order.setUserId(17);
        order = new PureBitemporalOrder(businessDate);
        order.setOrderId(orderId+1);
        order.setOrderDate(orderDate);
        order.insert();
        tx.commit();
        checkUserId(17, orderId);
    }

    public void testGlobalCounterOnInsert()
    {
        int startingUpdateCount = PureBitemporalOrderFinder.getMithraObjectPortal().getPerClassUpdateCountHolder().getUpdateCount();
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        PureBitemporalOrder order = constructNewPureBitemporalOrder();
        order.insert();
        tx.commit();
        int endingUpdateCount = PureBitemporalOrderFinder.getMithraObjectPortal().getPerClassUpdateCountHolder().getUpdateCount();
        assertEquals(endingUpdateCount - startingUpdateCount, 1);
    }

    public void testGlobalCounterOnUpdate()
    {
        int startingUpdateCount = PureBitemporalOrderFinder.getMithraObjectPortal().getPerClassUpdateCountHolder().getUpdateCount();
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
        order.setState("void");
        tx.commit();
        int endingUpdateCount = PureBitemporalOrderFinder.getMithraObjectPortal().getPerClassUpdateCountHolder().getUpdateCount();
        assertEquals(1, endingUpdateCount - startingUpdateCount);
    }

    public void testGlobalCounterOnTerminate()
    {
        int startingUpdateCount = PureBitemporalOrderFinder.getMithraObjectPortal().getPerClassUpdateCountHolder().getUpdateCount();
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
        order.terminate();
        tx.commit();
        int endingUpdateCount = PureBitemporalOrderFinder.getMithraObjectPortal().getPerClassUpdateCountHolder().getUpdateCount();
        assertEquals(endingUpdateCount - startingUpdateCount, 1);
    }

    private PureBitemporalOrder constructNewPureBitemporalOrder()
    {
        PureBitemporalOrder order = new PureBitemporalOrder(businessDate);
        order.setOrderId(1017);
        Timestamp orderDate = new Timestamp(System.currentTimeMillis());
        order.setOrderDate(orderDate);
        order.setDescription("testing");
        order.setUserId(17);
        return order;
    }

    public void testInMemoryTransactionalObject()
    {
        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        PureBitemporalOrder order = constructNewPureBitemporalOrder();
        tx.commit();
        assertNull("in memory object should not be in cache", findOrderNow(PureBitemporalOrderFinder.orderId().eq(1017)));
    }

    public void testInsertUpdateReordering()
    {
        final PureBitemporalOrder order1 = new PureBitemporalOrder(businessDate);
        final PureBitemporalOrder order2 = new PureBitemporalOrder(businessDate);

        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand()
        {
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                order1.setOrderId(2001);
                order1.insert();

                PureBitemporalOrderItem item = new PureBitemporalOrderItem(businessDate);
                item.setId(2500);
                item.setOrderId(1);
                item.insert();

                order1.setDescription("foo");

                order2.setOrderId(2005);
                order2.insert();
                return null;
            }
        });
    }

    public void testCommitFailure()
    {
        try
        {
            MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand() {
                public Object executeTransaction(MithraTransaction tx) throws Throwable
                {
                    PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
                    order.setOrderDate(new Timestamp(System.currentTimeMillis()));
                    tx.registerSynchronization(new Synchronization() {
                        public void afterCompletion(int i)
                        {
                        }

                        public void beforeCompletion()
                        {
                            throw new RuntimeException("for testing");
                        }
                    });
                    return null;
                }
            });
        }
        catch (MithraBusinessException e)
        {
            this.logger.info("Expected exception", e);
        }

        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand() {
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
                order.setOrderDate(new Timestamp(System.currentTimeMillis()));
                return null;
            }
        });
    }

    public void testCommitFailure2()
    {
        try
        {
            MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand() {
                public Object executeTransaction(MithraTransaction tx) throws Throwable
                {
                    tx.enlistResource(new ExceptionThrowingXaResource(true));
                    PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
                    order.setOrderDate(new Timestamp(System.currentTimeMillis()));
                    return null;
                }
            });
        }
        catch (MithraBusinessException e)
        {
            this.logger.info("Expected exception", e);
        }

        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand() {
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
                order.setOrderDate(new Timestamp(System.currentTimeMillis()));
                return null;
            }
        });
    }

    public void testCommitFailureSingleResource()
    {
        try
        {
            MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand() {
                public Object executeTransaction(MithraTransaction tx) throws Throwable
                {
                    tx.enlistResource(new ExceptionThrowingXaResource(true));
                    return null;
                }
            });
        }
        catch (MithraBusinessException e)
        {
            this.logger.info("Expected exception", e);
        }

        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand() {
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
                order.setOrderDate(new Timestamp(System.currentTimeMillis()));
                return null;
            }
        });
    }

    public void testGetNonPersistentCopyInTransaction()
    {
        MithraManagerProvider.getMithraManager().executeTransactionalCommand(
                new TransactionalCommand()
                {
                    public Object executeTransaction(MithraTransaction tran) throws Throwable
                    {
                        PureBitemporalOrder order = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
                        PureBitemporalOrder copy = order.getNonPersistentCopy();
                        assertEquals(order.getOrderId(), copy.getOrderId());
                        return null;
                    }
                });
    }

    public void testIsInMemory()
    {
        PureBitemporalOrder order1 = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
        assertFalse(order1.isInMemoryAndNotInserted());

        PureBitemporalOrder detachedPureBitemporalOrder = order1.getDetachedCopy();
        assertTrue(detachedPureBitemporalOrder.isInMemoryAndNotInserted());

        PureBitemporalOrder order2 = new PureBitemporalOrder(businessDate);
        order2.setOrderId(987);
        order2.setState("Created");
        order2.setUserId(123);
        order2.setOrderDate(new Timestamp(System.currentTimeMillis()));
        assertTrue(order2.isInMemoryAndNotInserted());

        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        order2.insert();
        tx.commit();
        assertFalse(order2.isInMemoryAndNotInserted());
    }

    public void testIsDeletedOrMarkForDeletion()
    {
        PureBitemporalOrder order1 = new PureBitemporalOrder(businessDate);
        order1.setOrderId(987);
        order1.setState("Created");
        order1.setUserId(123);
        order1.setOrderDate(new Timestamp(System.currentTimeMillis()));
        assertFalse(order1.isDeletedOrMarkForDeletion());

        MithraTransaction tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        order1.insert();
        tx.commit();
        assertFalse(order1.isDeletedOrMarkForDeletion());

        tx = MithraManagerProvider.getMithraManager().startOrContinueTransaction();
        order1.terminate();
        tx.commit();
        assertTrue(order1.isDeletedOrMarkForDeletion());

        PureBitemporalOrder order2 = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
        PureBitemporalOrder detachedPureBitemporalOrder = order2.getDetachedCopy();
        assertFalse(order2.isDeletedOrMarkForDeletion());

        detachedPureBitemporalOrder.terminate();
        assertFalse(order2.isDeletedOrMarkForDeletion());
        assertTrue(detachedPureBitemporalOrder.isDeletedOrMarkForDeletion());

        detachedPureBitemporalOrder.copyDetachedValuesToOriginalOrInsertIfNew();
        assertTrue(order2.isDeletedOrMarkForDeletion());
        assertTrue(detachedPureBitemporalOrder.isDeletedOrMarkForDeletion());
    }

    public void testIsTerminatedWithSeparateThreads()
    {
        final Exchanger rendezvous = new Exchanger();
        Runnable runnable1 = new Runnable()
        {
            public void run()
            {

                PureBitemporalOrder order1 = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
                assertFalse(order1.isDeletedOrMarkForDeletion());
                waitForOtherThread(rendezvous);
                waitForOtherThread(rendezvous);
                assertFalse(order1.isDeletedOrMarkForDeletion());
                waitForOtherThread(rendezvous);
                waitForOtherThread(rendezvous);
                assertTrue(order1.isDeletedOrMarkForDeletion());
            }

        };

        Runnable runnable2 = new Runnable()
        {
            public void run()
            {
                MithraManagerProvider.getMithraManager().executeTransactionalCommand(
                        new TransactionalCommand()
                        {

                            public Object executeTransaction(MithraTransaction tx) throws Throwable
                            {
                                PureBitemporalOrder order2 = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
                                assertFalse(order2.isDeletedOrMarkForDeletion());
                                waitForOtherThread(rendezvous);
                                order2.terminate();
                                waitForOtherThread(rendezvous);
                                assertTrue(order2.isDeletedOrMarkForDeletion());
                                waitForOtherThread(rendezvous);
                                return null;
                            }
                        });
                waitForOtherThread(rendezvous);
            }
        };

        assertTrue(runMultithreadedTest(runnable1, runnable2));
    }

    public void testDetachedIsTerminatedWithSeparateThreads()
    {
        final Exchanger rendezvous = new Exchanger();
        Runnable runnable1 = new Runnable()
        {
            public void run()
            {

                PureBitemporalOrder order1 = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));

                assertFalse(order1.isDeletedOrMarkForDeletion());

                waitForOtherThread(rendezvous);
                waitForOtherThread(rendezvous);
                assertFalse(order1.isDeletedOrMarkForDeletion());

                waitForOtherThread(rendezvous);
                waitForOtherThread(rendezvous);
                assertFalse(order1.isDeletedOrMarkForDeletion());

                waitForOtherThread(rendezvous);
                waitForOtherThread(rendezvous);
                assertTrue(order1.isDeletedOrMarkForDeletion());

            }

        };

        Runnable runnable2 = new Runnable()
        {
            public void run()
            {
                MithraManagerProvider.getMithraManager().executeTransactionalCommand(
                        new TransactionalCommand()
                        {

                            public Object executeTransaction(MithraTransaction tx) throws Throwable
                            {
                                PureBitemporalOrder order2 = findOrderNow(PureBitemporalOrderFinder.orderId().eq(1));
                                PureBitemporalOrder detachedPureBitemporalOrder2 = order2.getDetachedCopy();
                                assertFalse(order2.isDeletedOrMarkForDeletion());
                                assertFalse(detachedPureBitemporalOrder2.isDeletedOrMarkForDeletion());

                                waitForOtherThread(rendezvous);
                                detachedPureBitemporalOrder2.terminate();

                                waitForOtherThread(rendezvous);
                                assertFalse(order2.isDeletedOrMarkForDeletion());
                                assertTrue(detachedPureBitemporalOrder2.isDeletedOrMarkForDeletion());

                                waitForOtherThread(rendezvous);
                                detachedPureBitemporalOrder2.copyDetachedValuesToOriginalOrInsertIfNew();

                                waitForOtherThread(rendezvous);
                                assertTrue(order2.isDeletedOrMarkForDeletion());
                                assertTrue(detachedPureBitemporalOrder2.isDeletedOrMarkForDeletion());

                                waitForOtherThread(rendezvous);
                                return null;
                            }
                        });
                waitForOtherThread(rendezvous);
            }
        };

        assertTrue(runMultithreadedTest(runnable1, runnable2));
    }

    private static class ExceptionThrowingXaResource implements XAResource
    {
        private boolean throwExceptionOnCommit = false;

        public ExceptionThrowingXaResource(boolean throwExceptionOnCommit)
        {
            this.throwExceptionOnCommit = throwExceptionOnCommit;
        }

        public int getTransactionTimeout() throws XAException
        {
            return 0;
        }

        public boolean setTransactionTimeout(int i) throws XAException
        {
            return true;
        }

        public boolean isSameRM(XAResource xaResource) throws XAException
        {
            return xaResource == this;
        }

        public Xid[] recover(int i) throws XAException
        {
            return new Xid[0];
        }

        public int prepare(Xid xid) throws XAException
        {
            return 0;
        }

        public void forget(Xid xid) throws XAException
        {
        }

        public void rollback(Xid xid) throws XAException
        {
        }

        public void end(Xid xid, int i) throws XAException
        {
        }

        public void start(Xid xid, int i) throws XAException
        {
        }

        public void commit(Xid xid, boolean b) throws XAException
        {
            if (this.throwExceptionOnCommit)
            {
                throw new XAException("for testing.");
            }
        }
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">
<meta name="generator" content="joDoc">
<title>Apache Cordova API Documentation</title>
<link rel="stylesheet" type="text/css" href="index.css">
<link rel="stylesheet" type="text/css" href="mobile.css" media="only screen and (max-device-width: 1024px)">
<link rel="stylesheet" type="text/css" href="prettify/prettify.css">

Apache Cordova Documentation

                <select><optgroup label="English" value="en">
<option value="edge">edge</option>
<option value="2.9.0rc1">2.9.0rc1</option>
<option value="2.9.0">2.9.0</option>
<option value="2.8.0">2.8.0</option>
<option value="2.7.0rc1">2.7.0rc1</option>
<option value="2.7.0">2.7.0</option>
<option value="2.6.0rc1">2.6.0rc1</option>
<option value="2.6.0">2.6.0</option>
<option value="2.5.0rc1">2.5.0rc1</option>
<option value="2.5.0">2.5.0</option>
<option value="2.4.0rc1">2.4.0rc1</option>
<option value="2.4.0">2.4.0</option>
<option value="2.3.0rc2">2.3.0rc2</option>
<option value="2.3.0rc1">2.3.0rc1</option>
<option value="2.3.0">2.3.0</option>
<option value="2.2.0rc2">2.2.0rc2</option>
<option value="2.2.0rc1">2.2.0rc1</option>
<option value="2.2.0">2.2.0</option>
<option value="2.1.0rc2">2.1.0rc2</option>
<option value="2.1.0rc1">2.1.0rc1</option>
<option value="2.1.0">2.1.0</option>
<option value="2.0.0rc1">2.0.0rc1</option>
<option value="2.0.0">2.0.0</option>
<option value="1.9.0rc1">1.9.0rc1</option>
<option value="1.9.0">1.9.0</option>
<option value="1.8.1">1.8.1</option>
<option value="1.8.0rc1">1.8.0rc1</option>
<option value="1.8.0">1.8.0</option>
<option value="1.7.0rc1">1.7.0rc1</option>
<option value="1.7.0">1.7.0</option>
<option value="1.6.1">1.6.1</option>
<option value="1.6.0rc1">1.6.0rc1</option>
<option value="1.6.0">1.6.0</option>
<option value="1.5.0rc1">1.5.0rc1</option>
<option selected value="1.5.0">1.5.0</option>
</optgroup>
<optgroup label="Japanese" value="jp">
<option value="2.2.0">2.2.0</option>
<option value="2.1.0">2.1.0</option>
<option value="2.0.0">2.0.0</option>
<option value="1.9.0">1.9.0</option>
<option value="1.8.1">1.8.1</option>
<option value="1.7.0">1.7.0</option>
</optgroup>
<optgroup label="Korean" value="kr"><option value="2.0.0">2.0.0</option></optgroup></select>

Getting Started with iOS

            <select><option value="Getting%2520Started%2520with%2520iOS">Getting Started with iOS</option>
<option value="Getting%20Started%20with%20iOS_video_tutorials">      - Video Tutorials:</option>
<option value="Getting%20Started%20with%20iOS_1_requirements">      - 1. Requirements</option>
<option value="Getting%20Started%20with%20iOS_2_install_sdk_phonegap">      - 2. Install SDK + PhoneGap</option>
<option value="Getting%20Started%20with%20iOS_3_setup_new_project">      - 3. Setup New Project</option>
<option value="Getting%20Started%20with%20iOS_4_hello_world">      - 4. Hello World</option>
<option value="Getting%20Started%20with%20iOS_5a_deploy_to_simulator">      - 5A. Deploy to Simulator</option>
<option value="Getting%20Started%20with%20iOS_5b_deploy_to_device">      - 5B. Deploy to Device
</option>
<option value="Getting%20Started%20with%20iOS_done">      - Done!</option></select>

API Reference

Accelerometer

Camera

Capture

Compass

Connection

Contacts

Device

Events

File

Geolocation

Media

Notification

Storage

Guides

Getting Started Guides

Keyword Index

Getting Started with iOS

Video Tutorials:

PhoneGap Installer - Xcode 4 Template

1. Requirements

Intel-based computer with Mac OS X Snow Leopard (10.6)

Necessary for Installing on Device:

An Apple iOS device (iPhone, iPad, iPod Touch)

iOS developer certification

2. Install SDK + PhoneGap

Download and install Xcode from Apple Developer Portal (Membership required)

Download the latest copy of PhoneGap and extract its contents. We will be working with the Android directory.

3. Setup New Project

Launch Xcode, then under the File menu select New and then New Project...

Select PhoneGap-based Application from the list of templates

Select the Next button, Fill in the "Product Name" & "Company Identifier" for your app

Choose a directory to store your app

You should see your project in Xcode 4 now. Press the Run button in the top left corner. Your build should succeed and launch in the simulator

You should see a error in your simulator informing you index.html was not found

To fix this, we need to copy the www directory into the project. Right click on the project in the left navigation window and click show in finder

In Finder, you should see the www directory beside your project

Next step is IMPORTANT! Drag the www folder into Xcode 4. You can't just drag the www folder into your app's folder. It needs to be dragged into Xcode 4!! In my case I would drag it and drop it on HiWorld shown below.

After you drag, you should see a prompt with a few options. Make sure to select Create folder references for any added folders. Click Finish

4. Hello World

Open the folder named www and type <h1>Hello World</h1> after the <body> tag in index.html. You can also add any associated Javascript and CSS files there as well.

5A. Deploy to Simulator

Make sure to change the Active SDK in the top left menu to Simulator+version#.

Hit Run in your project window header.

5B. Deploy to Device

Open [AppName]-Info.plist and change BundleIdentifier to the identifier provided by Apple. If you have a developer license, you can access and run the Assistant at here and register your App.

Make sure to change the Active SDK in the top left menu to Device+version#.

Hit Run in your project window header.

Done!

You can also checkout more detailed version of this guide here.

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="Event invitation">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
    <title>Event Invitation</title>
    <link rel="stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" href="styles.css" />
    <link href="https://fonts.googleapis.com/css?family=Dancing+Script" rel="stylesheet">

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                Toggle navigation

            </button>

Home

Our Story(current)

The Wedding

RSVP

Our Story

Bella's Story

Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

Brown's Story

Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

        ×
            <form>

                    <input type="text" class="form-control" id="first" placeholder="First Name...">

                    <input type="text" class="form-control" id="last" placeholder="Last Name...">

                    <input type="email" class="form-control" id="email" placeholder="Email...">

                <button type="submit" class="btn btn-success">Yes, I'm coming</button>
            </form>

       © Design by Pankajashree. Background Photo by Scott Webb on Unsplash.


text:
package com.newsblur.util;

import android.content.Context;

import com.newsblur.R;

/**
 * Created by mark on 20/05/2014.
 */
public class ThemeUtils {

    private ThemeUtils() {} // util class - no instances

    // Resources.getColor(rid) was deprecated for a version that actually has a native
    // understanding of themes, but isn't available unless platform version > Build.M.
    // If we ever bump min platform version to M or higher, we could greatly simplify
    // or totally remove this whole utility class.
    @SuppressWarnings("deprecation")
    private static int getColor(Context context, int id) {
        return context.getResources().getColor(id);
    }

    public static int getProfileActivitiesLinkColor(Context context) {
        if (PrefsUtils.isLightThemeSelected(context)) {
            return getColor(context, R.color.linkblue);
        } else {
            return getColor(context, R.color.dark_linkblue);
        }
    }

    public static int getProfileActivitiesContentColor(Context context) {
        if (PrefsUtils.isLightThemeSelected(context)) {
            return getColor(context, R.color.text);
        } else {
            return getColor(context, R.color.white);
        }
    }

    public static int getProfileActivitiesQuoteColor(Context context) {
        if (PrefsUtils.isLightThemeSelected(context)) {
            return getColor(context, R.color.gray55);
        } else {
            return getColor(context, R.color.gray80);
        }
    }

    public static int getSelectorOverlayBackgroundText(Context context) {
        if (PrefsUtils.isLightThemeSelected(context)) {
            return R.drawable.selector_overlay_bg_text;
        } else {
            return R.drawable.selector_overlay_bg_dark_text;
        }
    }

    public static int getSelectorOverlayBackgroundStory(Context context) {
        if (PrefsUtils.isLightThemeSelected(context)) {
            return R.drawable.selector_overlay_bg_story;
        } else {
            return R.drawable.selector_overlay_bg_dark_story;
        }
    }

    public static int getSelectorOverlayBackgroundRight(Context context) {
        if (PrefsUtils.isLightThemeSelected(context)) {
            return R.drawable.selector_overlay_bg_right;
        } else {
            return R.drawable.selector_overlay_bg_dark_right;
        }
    }

    public static int getSelectorOverlayBackgroundRightDone(Context context) {
        if (PrefsUtils.isLightThemeSelected(context)) {
            return R.drawable.selector_overlay_bg_right_done;
        } else {
            return R.drawable.selector_overlay_bg_dark_right_done;
        }
    }
}


text:
import type { Action } from '../actions/types';
import { SET_USER } from '../actions/user';

export type State = {
    name: object
}

const initialState = {
  user: {},
};

export default function (state:State = initialState, action:Action): State {
  if (action.type === SET_USER) {
    return {
      ...state,
      user: action.payload,
    };
  }
  return state;
}


text:
This provides a polyfill for the `Ember.getOwner` feature added in Ember 2.3.

## Installation

```sh
ember install ember-getowner-polyfill
```

## Usage

```javascript
import Ember from 'ember';

export default Ember.Service.extend({
  someMethod() {
    let owner = Ember.getOwner(this);
    // do stuff with owner
  }
});
```

## Migration

### Applications

After you upgrade your application to Ember 2.3, you should remove `ember-getowner-polyfill` from
your `package.json`.

### Addons

Addons generally support many different Ember versions, so leaving `ember-getowner-polyfill` in
place for consumers of your addon is perfectly normal.  When the addon no longer supports Ember
versions older than 2.4, we recommend removing `ember-getowner-polyfill` from your `package.json`
and doing a major version bump.

## Documentation

The returned owner object should support all of the methods of the `ContainerProxyMixin` and `RegistryProxyMixin`.

* http://emberjs.com/api/classes/RegistryProxyMixin.html
* http://emberjs.com/api/classes/ContainerProxyMixin.html

## Compatibility

This addon is tested against quite a few past Ember versions. Check `config/ember-try.js` for the current list, but
the list of supported Ember versions at the time of authoring was:

* 1.10
* 1.11
* 1.12
* 1.13
* 2.0
* 2.1
* 2.2
* 2.3
* 2.4
* 2.8
* 2.12 (canary at the time)

## Addon Maintenance

### Installation

* `git clone` this repository
* `npm install`
* `bower install`

### Running

* `ember server`
* Visit your app at http://localhost:4200.

### Running Tests

* `npm test` (Runs `ember try:testall` to test your addon against multiple Ember versions)
* `ember test`
* `ember test --server`

### Building

* `ember build`

For more information on using ember-cli, visit [http://www.ember-cli.com/](http://www.ember-cli.com/).


text:
import React, { Component } from 'react'

// Material UI
import FlatButton from 'material-ui/FlatButton'

export default class LoginButton extends Component {
  static muiName = 'FlatButton'

  render() {
    return (
      <a href={$config.githubApi.authorizeUrl}>
        <FlatButton {...this.props} label="Login" />
      </a>
    )
  }
}


text:
package com.henryp.sparkfinance.config

import org.apache.spark.{SparkConf, SparkContext}

object Spark {

  val localMaster = "local[*]"

  def sparkContext(master: String = localMaster): SparkContext = {
    val conf = new SparkConf()
    conf.setMaster(master)
    conf.setAppName("ftse")
    SparkContext.getOrCreate(conf)
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace AspNetCoreAngular.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            var fileName = "home.html";
            var contentType = "text/html";
            return File(fileName, contentType);
        }
    }
}


text:
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.EventGrid.Models
{
    public partial class DynamicDeliveryAttributeMapping : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Name))
            {
                writer.WritePropertyName("name");
                writer.WriteStringValue(Name);
            }
            writer.WritePropertyName("type");
            writer.WriteStringValue(MappingType.ToString());
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Optional.IsDefined(SourceField))
            {
                writer.WritePropertyName("sourceField");
                writer.WriteStringValue(SourceField);
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static DynamicDeliveryAttributeMapping DeserializeDynamicDeliveryAttributeMapping(JsonElement element)
        {
            Optional<string> name = default;
            DeliveryAttributeMappingType type = default;
            Optional<string> sourceField = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    type = new DeliveryAttributeMappingType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("sourceField"))
                        {
                            sourceField = property0.Value.GetString();
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new DynamicDeliveryAttributeMapping(name.Value, type, sourceField.Value);
        }
    }
}


text:
<?php

class Ess_M2ePro_Model_Walmart_Template_Description_Source
{
    const GALLERY_IMAGES_COUNT_MAX = 8;

    /**
     * @var $_magentoProduct Ess_M2ePro_Model_Magento_Product
     */
    protected $_magentoProduct = null;

    /**
     * @var $_descriptionTemplateModel Ess_M2ePro_Model_Template_Description
     */
    protected $_descriptionTemplateModel = null;

    //########################################

    /**
     * @param Ess_M2ePro_Model_Magento_Product $magentoProduct
     * @return $this
     */
    public function setMagentoProduct(Ess_M2ePro_Model_Magento_Product $magentoProduct)
    {
        $this->_magentoProduct = $magentoProduct;
        return $this;
    }

    /**
     * @return Ess_M2ePro_Model_Magento_Product
     */
    public function getMagentoProduct()
    {
        return $this->_magentoProduct;
    }

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

    /**
     * @param Ess_M2ePro_Model_Template_Description $instance
     * @return $this
     */
    public function setDescriptionTemplate(Ess_M2ePro_Model_Template_Description $instance)
    {
        $this->_descriptionTemplateModel = $instance;
        return $this;
    }

    /**
     * @return Ess_M2ePro_Model_Template_Description
     */
    public function getDescriptionTemplate()
    {
        return $this->_descriptionTemplateModel;
    }

    /**
     * @return Ess_M2ePro_Model_Walmart_Template_Description
     */
    public function getWalmartDescriptionTemplate()
    {
        return $this->_descriptionTemplateModel->getChildObject();
    }

    //########################################

    /**
     * @return string
     */
    public function getTitle()
    {
        $src = $this->getWalmartDescriptionTemplate()->getTitleSource();

        switch ($src['mode']) {
            case Ess_M2ePro_Model_Walmart_Template_Description::TITLE_MODE_PRODUCT:
                $title = $this->getMagentoProduct()->getName();
                break;

            case Ess_M2ePro_Model_Walmart_Template_Description::TITLE_MODE_CUSTOM:
                $title = Mage::helper('M2ePro/Module_Renderer_Description')->parseTemplate(
                    $src['template'], $this->getMagentoProduct()
                );
                break;

            default:
                $title = $this->getMagentoProduct()->getName();
                break;
        }

        return $title;
    }

    /**
     * @return null|string
     */
    public function getBrand()
    {
        $src = $this->getWalmartDescriptionTemplate()->getBrandSource();

        if ($this->getWalmartDescriptionTemplate()->isBrandModeCustomValue()) {
            return trim($src['custom_value']);
        }

        return trim($this->getMagentoProduct()->getAttributeValue($src['custom_attribute']));
    }

    /**
     * @return int|null|string
     */
    public function getCountPerPack()
    {
        $result = '';
        $src = $this->getWalmartDescriptionTemplate()->getCountPerPackSource();

        if ($this->getWalmartDescriptionTemplate()->isCountPerPackModeNone()) {
            $result = NULL;
        }

        if ($this->getWalmartDescriptionTemplate()->isCountPerPackModeCustomValue()) {
            $result = (int)$src['value'];
        }

        if ($this->getWalmartDescriptionTemplate()->isCountPerPackModeCustomAttribute()) {
            $result = (int)$this->getMagentoProduct()->getAttributeValue($src['attribute']);
        }

        return $result;
    }

    /**
     * @return int|null|string
     */
    public function getMultipackQuantity()
    {
        $result = '';
        $src = $this->getWalmartDescriptionTemplate()->getMultipackQuantitySource();

        if ($this->getWalmartDescriptionTemplate()->isMultipackQuantityModeNone()) {
            $result = NULL;
        }

        if ($this->getWalmartDescriptionTemplate()->isMultipackQuantityModeCustomValue()) {
            $result = (int)$src['value'];
        }

        if ($this->getWalmartDescriptionTemplate()->isMultipackQuantityModeCustomAttribute()) {
            $result = (int)$this->getMagentoProduct()->getAttributeValue($src['attribute']);
        }

        return $result;
    }

    /**
     * @return int|null|string
     */
    public function getTotalCount()
    {
        $result = 0;
        $src = $this->getWalmartDescriptionTemplate()->getTotalCountSource();

        if ($this->getWalmartDescriptionTemplate()->isTotalCountModeNone()) {
            $result = NULL;
        }

        if ($this->getWalmartDescriptionTemplate()->isTotalCountModeCustomValue()) {
            $result = (int)$src['custom_value'];
        }

        if ($this->getWalmartDescriptionTemplate()->isTotalCountModeCustomAttribute()) {
            $result = (int)$this->getMagentoProduct()->getAttributeValue($src['custom_attribute']);
        }

        return $result;
    }

    /**
     * @return int|null|string
     */
    public function getModelNumber()
    {
        $result = '';
        $src = $this->getWalmartDescriptionTemplate()->getModelNumberSource();

        if ($this->getWalmartDescriptionTemplate()->isModelNumberModeNone()) {
            $result = NULL;
        }

        if ($this->getWalmartDescriptionTemplate()->isModelNumberModeCustomValue()) {
            $result = (int)$src['custom_value'];
        }

        if ($this->getWalmartDescriptionTemplate()->isModelNumberModeCustomAttribute()) {
            $result = (int)$this->getMagentoProduct()->getAttributeValue($src['custom_attribute']);
        }

        return $result;
    }

    /**
     * @return float|null
     */
    public function getMsrpRrp($storeForConvertingAttributeTypePrice = NULL)
    {
        $result = '';

        if ($this->getWalmartDescriptionTemplate()->isMsrpRrpModeNone()) {
            return NULL;
        }

        if ($this->getWalmartDescriptionTemplate()->isMsrpRrpModeCustomAttribute()) {
            $src = $this->getWalmartDescriptionTemplate()->getMsrpRrpSource();
            $result = $this->getMagentoProductAttributeValue(
                $src['custom_attribute'],
                $storeForConvertingAttributeTypePrice
            );
        }

        is_string($result) && $result = str_replace(',', '.', $result);

        return round((float)$result, 2);
    }

    /**
     * @return mixed|string
     * @throws Ess_M2ePro_Model_Exception
     */
    public function getDescription()
    {
        $src = $this->getWalmartDescriptionTemplate()->getDescriptionSource();

        /** @var $templateProcessor Mage_Core_Model_Email_Template_Filter */
        $templateProcessor = Mage::getModel('Core/Email_Template_Filter');

        switch ($src['mode']) {
            case Ess_M2ePro_Model_Walmart_Template_Description::DESCRIPTION_MODE_PRODUCT:
                $description = $this->getMagentoProduct()->getProduct()->getDescription();
                $description = $templateProcessor->filter($description);
                break;

            case Ess_M2ePro_Model_Walmart_Template_Description::DESCRIPTION_MODE_SHORT:
                $description = $this->getMagentoProduct()->getProduct()->getShortDescription();
                $description = $templateProcessor->filter($description);
                break;

            case Ess_M2ePro_Model_Walmart_Template_Description::DESCRIPTION_MODE_CUSTOM:
                $description = Mage::helper('M2ePro/Module_Renderer_Description')->parseTemplate(
                    $src['template'], $this->getMagentoProduct()
                );
                break;

            default:
                $description = '';
                break;
        }

        $allowedTags = array('<p>', '<br>', '<ul>', '<li>', '<b>');

        $description = str_replace(array('<![CDATA[', ']]>'), '', $description);
        $description = strip_tags($description, implode($allowedTags));

        return $description;
    }

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

    /**
     * @return array
     */
    public function getKeyFeatures()
    {
        if ($this->getWalmartDescriptionTemplate()->isKeyFeaturesModeNone()) {
            return array();
        }

        $result = array();
        $src = $this->getWalmartDescriptionTemplate()->getKeyFeaturesSource();

        foreach ($src['template'] as $value) {
            $parsedValue = Mage::helper('M2ePro/Module_Renderer_Description')->parseTemplate(
                $value, $this->getMagentoProduct()
            );

            if (empty($parsedValue)) {
                continue;
            }

            $result[] = $parsedValue;
        }

        return $result;
    }

    /**
     * @return array
     */
    public function getOtherFeatures()
    {
        if ($this->getWalmartDescriptionTemplate()->isOtherFeaturesModeNone()) {
            return array();
        }

        $result = array();
        $src = $this->getWalmartDescriptionTemplate()->getOtherFeaturesSource();

        foreach ($src['template'] as $value) {
            $parsedValue = Mage::helper('M2ePro/Module_Renderer_Description')->parseTemplate(
                $value, $this->getMagentoProduct()
            );

            if (empty($parsedValue)) {
                continue;
            }

            $result[] = $parsedValue;
        }

        return $result;
    }

    /**
     * @return array
     */
    public function getAttributes()
    {
        if ($this->getWalmartDescriptionTemplate()->isAttributesModeNone()) {
            return array();
        }

        $result = array();
        $src = $this->getWalmartDescriptionTemplate()->getAttributesSource();

        foreach ($src['template'] as $value) {
            if (empty($value)) {
                continue;
            }

            $result[$value['name']] = Mage::helper('M2ePro/Module_Renderer_Description')->parseTemplate(
                $value['value'], $this->getMagentoProduct()
            );
        }

        return $result;
    }

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

    /**
     * @return null|string
     */
    public function getKeywords()
    {
        if ($this->getWalmartDescriptionTemplate()->isKeywordsModeNone()) {
            return NULL;
        }

        $src = $this->getWalmartDescriptionTemplate()->getKeywordsSource();

        if ($this->getWalmartDescriptionTemplate()->isKeywordsModeCustomValue()) {
            return trim($src['custom_value']);
        }

        return trim($this->getMagentoProduct()->getAttributeValue($src['custom_attribute']));
    }

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

    /**
     * @return null|string
     */
    public function getManufacturer()
    {
        $src = $this->getWalmartDescriptionTemplate()->getManufacturerSource();

        if ($this->getWalmartDescriptionTemplate()->isManufacturerModeNone()) {
            return NULL;
        }

        if ($this->getWalmartDescriptionTemplate()->isManufacturerModeCustomValue()) {
            return trim($src['custom_value']);
        }

        return trim($this->getMagentoProduct()->getAttributeValue($src['custom_attribute']));
    }

    /**
     * @return null|string
     */
    public function getManufacturerPartNumber()
    {
        if ($this->getWalmartDescriptionTemplate()->isManufacturerPartNumberModeNone()) {
            return NULL;
        }

        $src = $this->getWalmartDescriptionTemplate()->getManufacturerPartNumberSource();

        if ($this->getWalmartDescriptionTemplate()->isManufacturerPartNumberModeCustomValue()) {
            return trim($src['custom_value']);
        }

        return trim($this->getMagentoProduct()->getAttributeValue($src['custom_attribute']));
    }

    //########################################

    /**
     * @return Ess_M2ePro_Model_Magento_Product_Image|null
     */
    public function getMainImage()
    {
        $image = null;

        if ($this->getWalmartDescriptionTemplate()->isImageMainModeProduct()) {
            $image = $this->getMagentoProduct()->getImage('image');
        }

        if ($this->getWalmartDescriptionTemplate()->isImageMainModeAttribute()) {
            $src = $this->getWalmartDescriptionTemplate()->getImageMainSource();
            $image = $this->getMagentoProduct()->getImage($src['attribute']);
        }

        return $image;
    }

    /**
     * @return Ess_M2ePro_Model_Magento_Product_Image[]
     */
    public function getGalleryImages()
    {
        if ($this->getWalmartDescriptionTemplate()->isImageMainModeNone()) {
            return array();
        }

        if (!$mainImage = $this->getMainImage()) {
            return array();
        }

        if ($this->getWalmartDescriptionTemplate()->isGalleryImagesModeNone()) {
            return array();
        }

        $galleryImages = array();
        $gallerySource = $this->getWalmartDescriptionTemplate()->getGalleryImagesSource();
        $limitGalleryImages = self::GALLERY_IMAGES_COUNT_MAX;

        if ($this->getWalmartDescriptionTemplate()->isGalleryImagesModeProduct()) {
            $limitGalleryImages = (int)$gallerySource['limit'];
            $galleryImagesTemp = $this->getMagentoProduct()->getGalleryImages($limitGalleryImages + 1);

            foreach ($galleryImagesTemp as $image) {
                if (array_key_exists($image->getHash(), $galleryImages)) {
                    continue;
                }

                $galleryImages[$image->getHash()] = $image;
            }
        }

        if ($this->getWalmartDescriptionTemplate()->isGalleryImagesModeAttribute()) {
            $limitGalleryImages = self::GALLERY_IMAGES_COUNT_MAX;

            $galleryImagesTemp = $this->getMagentoProduct()->getAttributeValue($gallerySource['attribute']);
            $galleryImagesTemp = (array)explode(',', $galleryImagesTemp);

            foreach ($galleryImagesTemp as $tempImageLink) {
                $tempImageLink = trim($tempImageLink);
                if (empty($tempImageLink)) {
                    continue;
                }

                $image = new Ess_M2ePro_Model_Magento_Product_Image($tempImageLink);
                $image->setStoreId($this->getMagentoProduct()->getStoreId());

                if (array_key_exists($image->getHash(), $galleryImages)) {
                    continue;
                }

                $galleryImages[$image->getHash()] = $image;
            }
        }

        unset($galleryImages[$mainImage->getHash()]);

        if (empty($galleryImages)) {
            return array($mainImage);
        }

        $galleryImages = array_slice($galleryImages, 0, $limitGalleryImages);
        array_unshift($galleryImages, $mainImage);

        return $galleryImages;
    }

    /**
     * @return Ess_M2ePro_Model_Magento_Product_Image
     */
    public function getVariationDifferenceImage()
    {
        if ($this->getWalmartDescriptionTemplate()->isImageVariationDifferenceModeNone()) {
            return NULL;
        }

        $image = null;

        if ($this->getWalmartDescriptionTemplate()->isImageVariationDifferenceModeProduct()) {
            $image = $this->getMagentoProduct()->getImage('image');
        }

        if ($this->getWalmartDescriptionTemplate()->isImageVariationDifferenceModeAttribute()) {
            $src = $this->getWalmartDescriptionTemplate()->getImageVariationDifferenceSource();
            $image = $this->getMagentoProduct()->getImage($src['attribute']);
        }

        if (!$image) {
            return NULL;
        }

        return $image;
    }

    protected function getMagentoProductAttributeValue($attributeCode, $store)
    {
        return $this->getMagentoProduct()->getAttributeValue($attributeCode); // todo
    }

    //########################################
}


text:
package poussecafe.attribute.entity;

import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;
import poussecafe.domain.Entity;
import poussecafe.domain.EntityAttributes;

public class OptionalEntityAttributeBuilder<D extends EntityAttributes<?>, E extends Entity<?, D>, F extends D> {

    OptionalEntityAttributeBuilder() {

    }

    Class<E> entityClass;

    Class<F> dataClass;

    public ReadOnlyAttribute read(Supplier<F> getter) {
        Objects.requireNonNull(getter);
        this.getter = getter;
        return new ReadOnlyAttribute();
    }

    private Supplier<F> getter;

    public class ReadOnlyAttribute {

        private ReadOnlyAttribute() {

        }

        public ReadWriteAttribute write(Consumer<F> setter) {
            Objects.requireNonNull(setter);
            OptionalEntityAttributeBuilder.this.setter = setter;
            return new ReadWriteAttribute();
        }
    }

    private Consumer<F> setter;

    public class ReadWriteAttribute {

        private ReadWriteAttribute() {

        }

        public OptionalEntityAttribute<E> build() {
            return new OptionalEntityAttributeData<>(entityClass) {
                @Override
                protected D getData() {
                    return getter.get();
                }

                @SuppressWarnings("unchecked")
                @Override
                protected void setData(D data) {
                    setter.accept((F) data);
                }
            };
        }
    }
}


text:
package com.inepex.ineForm.client.form.formunits;

import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.IsWidget;

public class UIMandatory extends HTML implements IsWidget {
    UIMandatory(boolean mandatory) {
        if (mandatory)
            setHTML("*");

        setStyleName("mandatorySign");
    }
}


text:
require 'spec_helper'

describe API::API do
  include ApiHelpers

  # Create test objects
  let(:user1) { create(:user) }
  let(:user2) { create(:user) }
  let(:admin) { create(:admin) }
  let!(:group1) { create(:group, owner: user1) }
  let!(:group2) { create(:group, owner: user2) }
  let(:user_team1) { create(:user_team, owner: user1) }
  let(:user_team2) { create(:user_team, owner: user2) }
  let!(:project1) { create(:project, creator_id: admin.id) }
  let!(:project2) { create(:project, creator_id: admin.id) }

  before {
    # Add members to teams
    user_team1.add_member(user1, UsersProject::MASTER, false)
    user_team2.add_member(user2, UsersProject::MASTER, false)

    # Add projects to teams
    user_team1.assign_to_projects([project1.id], UsersProject::MASTER)
    user_team2.assign_to_projects([project2.id], UsersProject::MASTER)

  }

  describe "GET /user_teams" do
    context "when unauthenticated" do
      it "should return authentication error" do
        get api("/user_teams")
        response.status.should == 401
      end
    end

    context "when authenticated as user" do
      it "normal user: should return an array of user_teams of user1" do
        get api("/user_teams", user1)
        response.status.should == 200
        json_response.should be_an Array
        json_response.length.should == 1
        json_response.first['name'].should == user_team1.name
      end
    end

    context "when authenticated as admin" do
      it "admin: should return an array of all user_teams" do
        get api("/user_teams", admin)
        response.status.should == 200
        json_response.should be_an Array
        json_response.length.should == 2
      end
    end
  end

  describe "GET /user_teams/:id" do
    context "when authenticated as user" do
      it "should return one of user1's user_teams" do
        get api("/user_teams/#{user_team1.id}", user1)
        response.status.should == 200
        json_response['name'] == user_team1.name
      end

      it "should not return a non existing team" do
        get api("/user_teams/1328", user1)
        response.status.should == 404
      end

      it "should not return a user_team not attached to user1" do
        get api("/user_teams/#{user_team2.id}", user1)
        response.status.should == 404
      end
    end

    context "when authenticated as admin" do
      it "should return any existing user_team" do
        get api("/user_teams/#{user_team2.id}", admin)
        response.status.should == 200
        json_response['name'].should == user_team2.name
      end

      it "should not return a non existing user_team" do
        get api("/user_teams/1328", admin)
        response.status.should == 404
      end
    end
  end

  describe "POST /user_teams" do
    context "when authenticated as user" do
      it "should not create user_team" do
        count_before=UserTeam.count
        post api("/user_teams", user1), attributes_for(:user_team)
        response.status.should == 403
        UserTeam.count.should == count_before
      end
    end

    context "when authenticated as admin" do
      it "should create user_team" do
        count_before=UserTeam.count
        post api("/user_teams", admin), attributes_for(:user_team)
        response.status.should == 201
        UserTeam.count.should == count_before + 1
      end

      it "should not create user_team, duplicate" do
        post api("/user_teams", admin), {:name => "Duplicate Test", :path => user_team2.path}
        response.status.should == 404
      end

      it "should return 400 bad request error if name not given" do
        post api("/user_teams", admin), {:path => user_team2.path}
        response.status.should == 400
      end

      it "should return 400 bad request error if path not given" do
        post api("/user_teams", admin), {:name => 'test'}
        response.status.should == 400
      end
    end
  end

  # Members

  describe "GET /user_teams/:id/members" do
    context "when authenticated as user" do
      it "should return user1 as member of user1's user_teams" do
        get api("/user_teams/#{user_team1.id}/members", user1)
        response.status.should == 200
        json_response.first['name'].should == user1.name
        json_response.first['access_level'].should == UsersProject::MASTER
      end
    end

    context "when authenticated as admin" do
      it "should return member of any existing user_team" do
        get api("/user_teams/#{user_team2.id}/members", admin)
        response.status.should == 200
        json_response.first['name'].should == user2.name
        json_response.first['access_level'].should == UsersProject::MASTER
      end
    end
  end

  describe "POST /user_teams/:id/members" do
    context "when authenticated as user" do
      it "should not add user2 as member of user_team1" do
        post api("/user_teams/#{user_team1.id}/members", user1), user_id: user2.id, access_level: UsersProject::MASTER
        response.status.should == 403
      end
    end

    context "when authenticated as admin" do
      it "should return ok and add new member" do
        count_before=user_team1.user_team_user_relationships.count
        post api("/user_teams/#{user_team1.id}/members", admin), user_id: user2.id, access_level: UsersProject::MASTER
        response.status.should == 201
        json_response['name'].should == user2.name
        json_response['access_level'].should == UsersProject::MASTER
        user_team1.user_team_user_relationships.count.should == count_before + 1
      end
      it "should return ok if member already exists" do
        post api("/user_teams/#{user_team2.id}/members", admin), user_id: user2.id, access_level: UsersProject::MASTER
        response.status.should == 409
      end
      it "should return a 400 error when user id is not given" do
        post api("/user_teams/#{user_team2.id}/members", admin), access_level: UsersProject::MASTER
        response.status.should == 400
      end
      it "should return a 400 error when access level is not given" do
        post api("/user_teams/#{user_team2.id}/members", admin), user_id: user2.id
        response.status.should == 400
      end

      it "should return a 422 error when access level is not known" do
        post api("/user_teams/#{user_team2.id}/members", admin), user_id: user1.id, access_level: 1234
        response.status.should == 422
      end

    end
  end

  # Get single member
  describe "GET /user_teams/:id/members/:user_id" do
    context "when authenticated as member" do
      it "should show user1's membership of user_team1" do
        get api("/user_teams/#{user_team1.id}/members/#{user1.id}", user1)
        response.status.should == 200
        json_response['name'].should == user1.name
        json_response['access_level'].should == UsersProject::MASTER
      end
      it "should show that user2 is not member of user_team1" do
        get api("/user_teams/#{user_team1.id}/members/#{user2.id}", user1)
        response.status.should == 404
      end
    end

    context "when authenticated as non-member" do
      it "should not show user1's membership of user_team1" do
        get api("/user_teams/#{user_team1.id}/members/#{user1.id}", user2)
        response.status.should == 404
      end
    end

    context "when authenticated as admin" do
      it "should show user1's membership of user_team1" do
        get api("/user_teams/#{user_team1.id}/members/#{user1.id}", admin)
        response.status.should == 200
        json_response['name'].should == user1.name
        json_response['access_level'].should == UsersProject::MASTER
      end
      it "should return a 404 error when user id is not known" do
        get api("/user_teams/#{user_team2.id}/members/1328", admin)
        response.status.should == 404
      end
    end
  end

  describe "DELETE /user_teams/:id/members/:user_id" do
    context "when authenticated as user" do
      it "should not delete user1's membership of user_team1" do
        delete api("/user_teams/#{user_team1.id}/members/#{user1.id}", user1)
        response.status.should == 403
      end
    end

    context "when authenticated as admin" do
      it "should delete user1's membership of user_team1" do
        count_before=user_team1.user_team_user_relationships.count
        delete api("/user_teams/#{user_team1.id}/members/#{user1.id}", admin)
        response.status.should == 200
        user_team1.user_team_user_relationships.count.should == count_before - 1
      end
      it "should return a 404 error when user id is not known" do
        delete api("/user_teams/#{user_team2.id}/members/1328", admin)
        response.status.should == 404
      end
    end
  end

  # Projects

  describe "GET /user_teams/:id/projects" do
    context "when authenticated as user" do
      it "should return project1 as assigned to user_team1 as member user1" do
        get api("/user_teams/#{user_team1.id}/projects", user1)
        response.status.should == 200
        json_response.first['name'].should == project1.name
        json_response.length.should == user_team1.user_team_project_relationships.count
      end
    end

    context "when authenticated as admin" do
      it "should return project2 as assigned to user_team2 as non-member, but admin" do
        get api("/user_teams/#{user_team2.id}/projects", admin)
        response.status.should == 200
        json_response.first['name'].should == project2.name
        json_response.first['greatest_access_level'].should == UsersProject::MASTER
      end
    end
  end

  describe "POST /user_teams/:id/projects" do
    context "when authenticated as admin" do
      it "should return ok and add new project" do
        count_before=user_team1.user_team_project_relationships.count
        post api("/user_teams/#{user_team1.id}/projects", admin),
             project_id: project2.id,
             greatest_access_level: UsersProject::MASTER
        response.status.should == 201
        json_response['name'].should == project2.name
        json_response['greatest_access_level'].should == UsersProject::MASTER
        user_team1.user_team_project_relationships.count.should == count_before + 1
      end
      it "should return ok if project already exists" do
        post api("/user_teams/#{user_team2.id}/projects", admin),
             project_id: project2.id,
             greatest_access_level: UsersProject::MASTER
        response.status.should == 409
      end
      it "should return a 400 error when project id is not given" do
        post api("/user_teams/#{user_team2.id}/projects", admin), greatest_access_level: UsersProject::MASTER
        response.status.should == 400
      end
      it "should return a 400 error when access level is not given" do
        post api("/user_teams/#{user_team2.id}/projects", admin), project_id: project2.id
        response.status.should == 400
      end

      it "should return a 422 error when access level is not known" do
        post api("/user_teams/#{user_team2.id}/projects", admin),
             project_id: project2.id,
             greatest_access_level: 1234
        response.status.should == 422
      end

    end
  end

  describe "GET /user_teams/:id/projects/:project_id" do
    context "when authenticated as member" do
      it "should show project1's assignment to user_team1" do
        get api("/user_teams/#{user_team1.id}/projects/#{project1.id}", user1)
        response.status.should == 200
        json_response['name'].should == project1.name
        json_response['greatest_access_level'].should == UsersProject::MASTER
      end
      it "should show project2's is not assigned to user_team1" do
        get api("/user_teams/#{user_team1.id}/projects/#{project2.id}", user1)
        response.status.should == 404
      end
    end

    context "when authenticated as non-member" do
      it "should not show project1's assignment to user_team1" do
        get api("/user_teams/#{user_team1.id}/projects/#{project1.id}", user2)
        response.status.should == 404
      end
    end

    context "when authenticated as admin" do
      it "should show project1's assignment to user_team1" do
        get api("/user_teams/#{user_team1.id}/projects/#{project1.id}", admin)
        response.status.should == 200
        json_response['name'].should == project1.name
        json_response['greatest_access_level'].should == UsersProject::MASTER
      end
      it "should return a 404 error when project id is not known" do
        get api("/user_teams/#{user_team2.id}/projects/1328", admin)
        response.status.should == 404
      end
    end
  end

  describe "DELETE /user_teams/:id/projects/:project_id" do
    context "when authenticated as user" do
      it "should not delete project1's assignment to user_team2" do
        delete api("/user_teams/#{user_team2.id}/projects/#{project1.id}", user1)
        response.status.should == 403
      end
    end

    context "when authenticated as admin" do
      it "should delete project1's assignment to user_team1" do
        count_before=user_team1.user_team_project_relationships.count
        delete api("/user_teams/#{user_team1.id}/projects/#{project1.id}", admin)
        response.status.should == 200
        user_team1.user_team_project_relationships.count.should == count_before - 1
      end
      it "should return a 404 error when project id is not known" do
        delete api("/user_teams/#{user_team2.id}/projects/1328", admin)
        response.status.should == 404
      end
    end
  end

end


text:
require 'spec_helper'

describe Job, type: :model do
  skip "Add some examples to (or delete) #{__FILE__}"
end


text:
package fr.openwide.core.wicket.more.link.descriptor.builder.state.validator;

import org.apache.wicket.model.IModel;
import org.bindgen.BindingRoot;

import fr.openwide.core.wicket.more.condition.Condition;
import fr.openwide.core.wicket.more.link.descriptor.builder.state.main.common.IMappableParameterDeclarationState;
import fr.openwide.core.wicket.more.link.descriptor.builder.state.parameter.chosen.common.IChosenParameterState;
import fr.openwide.core.wicket.more.link.descriptor.builder.state.parameter.chosen.common.IOneChosenParameterState;
import fr.openwide.core.wicket.more.link.descriptor.generator.ILinkGenerator;
import fr.openwide.core.wicket.more.link.descriptor.mapper.ILinkDescriptorMapper;
import fr.openwide.core.wicket.more.link.descriptor.parameter.extractor.ILinkParametersExtractor;
import fr.openwide.core.wicket.more.link.descriptor.parameter.validator.ConditionLinkParameterValidator;
import fr.openwide.core.wicket.more.link.descriptor.parameter.validator.ILinkParameterValidator;

/**
 * A state where one may add validation to the link.
 *
"Validation" here means any type of condition, which among others may be parameter-based (check that a parameter
 * is in a certain state), session-based (check that the user has required roles, or both (check that the user has
 * a certain permission on a parameter).
 *
Note: if you're planning on adding parameter-based validation, please consider declaring your
 * model parameters using {@link IMappableParameterDeclarationState#model(Class)}, mapping those declared parameters
 * using one of the methods defined in {@link IChosenParameterState} or {@link IOneChosenParameterState} and adding
 * validation using the same interfaces. This will allow you to build a
 * {@link ILinkDescriptorMapper link descriptor mapper}, suitable for use in declarative builders such
 * as {@link fr.openwide.core.wicket.more.markup.repeater.table.builder.DataTableBuilder}.
 */
public interface IValidatorState<TSelf extends IValidatorState<TSelf>> {

	/**
	 * Add the given validator to the resulting link descriptor.
	 *
The validator will be executed each time a link will get {@link ILinkGenerator generated} or link parameters
	 * will get {@link ILinkParametersExtractor extracted}.
	 *
Note: if your validator depends on one of the parameters, and you're building a
	 * {@link ILinkDescriptorMapper link descriptor mapper}, please consider calling
	 * {@link IChosenParameterState#validator(fr.openwide.core.wicket.more.markup.html.factory.IDetachableFactory)}
	 * instead.
	 * @param validator
	 * @return The same builder for chaining calls.
	 * @see ILinkParameterValidator
	 */
	TSelf validator(ILinkParameterValidator validator);

	/**
	 * {@link #validator(ILinkParameterValidator) Add a validator to the resulting link descriptor} that will pass
	 * validation if and only if the given condition is true, and raise an error otherwise.
	 *
Note: if your condition depends on one of the parameters, and you're building a
	 * {@link ILinkDescriptorMapper link descriptor mapper}, please consider calling
	 * {@link IChosenParameterState#validator(fr.openwide.core.wicket.more.markup.html.factory.IDetachableFactory)}
	 * instead.
	 * @param condition The condition on which the validation should pass.
	 * @return The same builder for chaining calls.
	 * @see ConditionLinkParameterValidator
	 */
	TSelf validator(Condition condition);

	/**
	 * {@link #validator(ILinkParameterValidator) Add a validator to the resulting link descriptor} that will pass
	 * validation if and only if the authenticated user has the given permission on the object contained in the
	 * given model, and raise an error otherwise.
	 *
Note: if the given model is one of the link parameters, and you're building a
	 * {@link ILinkDescriptorMapper link descriptor mapper}, please consider calling
	 * {@link IOneChosenParameterState#permission(String)} instead.
	 * @param model The object on which the permission should be granted.
	 * @param permissionName The name of the permission that should be granted.
	 * @return The same builder for chaining calls.
	 * @see Condition#permission(IModel, String)
	 */
	TSelf permission(IModel<?> model, String permissionName);

	/**
	 * {@link #validator(ILinkParameterValidator) Add a validator to the resulting link descriptor} that will pass
	 * validation if and only if the authenticated user has any of the given permissions on the object
	 * contained in the given model, and raise an error otherwise.
	 *
Note: if the given model is one of the link parameters, and you're building a
	 * {@link ILinkDescriptorMapper link descriptor mapper}, please consider calling
	 * {@link IOneChosenParameterState#permission(String, String...)} instead.
	 * @param model The object on which one of the permissions should be granted.
	 * @param firstPermissionName The name of a permission that is sufficient to pass validation.
	 * @param otherPermissionNames The name of other permissions that are each sufficient to pass validation.
	 * @return The same builder for chaining calls.
	 * @see Condition#anyPermission(IModel, String, String...)
	 */
	TSelf permission(IModel<?> model, String firstPermissionName, String ... otherPermissionNames);

	/**
	 * Shorthand for
	 * permission(BindingModel.of(model, binding), firstPermissionName, otherPermissionNames)
	 * @see #permission(IModel, String, String...)
	 */
	<R, T> TSelf permission(IModel<R> model, BindingRoot<R, T> binding, String firstPermissionName,
					String ... otherPermissionNames);

}


text:
package main

import (
	"log"
	"net"
	"net/http"
	"os"

	"github.com/anacrolix/tagflag"
)

func setIfGetHeader(w http.ResponseWriter, r *http.Request, set, get string) {
	h := r.Header.Get(get)
	if h == "" {
		return
	}
	w.Header().Set(set, h)
}

func allowCORS(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if origin := r.Header.Get("Origin"); origin != "" {
			w.Header().Set("Access-Control-Allow-Origin", origin)
			w.Header().Set("Access-Control-Allow-Credentials", "true")
			setIfGetHeader(w, r, "Access-Control-Allow-Methods", "Access-Control-Request-Method")
			setIfGetHeader(w, r, "Access-Control-Allow-Headers", "Access-Control-Request-Headers")
			w.Header().Set("Access-Control-Expose-Headers", "Content-Type")
		}
		h.ServeHTTP(w, r)
	})
}

func main() {
	var flags = struct {
		Addr string
	}{
		Addr: "localhost:8080",
	}
	tagflag.Parse(&flags)
	dir, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}
	l, err := net.Listen("tcp", flags.Addr)
	if err != nil {
		log.Fatal(err)
	}
	defer l.Close()
	addr := l.Addr()
	log.Printf("serving %q at %s", dir, addr)
	log.Fatal(http.Serve(l, allowCORS(http.FileServer(http.Dir(dir)))))
}


text:
package gumble

// Channels is a map of server channels.
//
// When accessed through Client.Channels, it contains all channels on the
// server. When accessed through a specific channel
// (e.g. client.Channels[0].Children), it contains only the children of the
// channel.
type Channels map[uint32]*Channel

// create adds a new channel with the given id to the collection. If a channel
// with the given id already exists, it is overwritten.
func (c Channels) create(id uint32) *Channel {
	channel := &Channel{
		ID:       id,
		Children: Channels{},
		Users:    Users{},
	}
	c[id] = channel
	return channel
}

// Find returns a channel whose path (by channel name) from the server root
// channel is equal to the arguments passed. If the root channel does not
// exist, nil is returned.
func (c Channels) Find(names ...string) *Channel {
	root := c[0]
	if names == nil || root == nil {
		return root
	}
	return root.Find(names...)
}


text:
repo_dir=$( cd "$( dirname "$0" )" && pwd )

echo -n 'Linking mydefault.sty...'
ln -s $repo_dir/latex/mydefault $HOME/.program_files/texmf/tex/latex/
echo 'Done'