text:
package com.groupon.promise;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import com.groupon.promise.exception.PromiseException;
import com.groupon.promise.function.EchoFunction;
import com.groupon.promise.function.FixedValueFunction;
import com.groupon.promise.function.PromiseFunctionResult;
import com.groupon.promise.function.PromiseListFunctionResult;

/**
 * Test the PromiseImpl.
 *
 * @author Stuart Siegrist (fsiegrist at groupon dot com)
 * @since 0.1
 */
public class PromiseImplTest {
    @Mock
    private PromiseHandler<PromiseFuture<Void>> handler;

    @Mock
    private PromiseHandler<PromiseFuture<Throwable>> errorHandler;

    @Mock
    private PromiseFunctionResult<String, Integer> onFulfilled;

    @Mock
    private PromiseFunctionResult<Integer, String> onFulfilledReversed;

    @Mock
    private PromiseListFunctionResult<String, Integer> onFulfilledMap;

    @Mock
    private PromiseListFunctionResult<Integer, String> onFulfilledMapReversed;

    @Mock
    private PromiseFunctionResult<Void, Void> onFulfilledAfter;

    @Mock
    private PromiseFunctionResult<Throwable, String> onRejectedString;

    @Mock
    private PromiseFunctionResult<Throwable, Integer> onRejectedInteger;

    @Mock
    private PromiseListFunctionResult<Throwable, String> onRejectedStringList;

    @Mock
    private PromiseListFunctionResult<Throwable, Integer> onRejectedIntegerList;

    @Mock
    private PromiseFunctionResult<Throwable, Void> onRejectedAfter;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testEmptyCreate() {
        PromiseImpl<String> future = new PromiseImpl<>();

        assertTrue(future.pending());
        assertFalse(future.fulfilled());
        assertFalse(future.rejected());
        assertFalse(future.optional());
        assertNull(future.value());
        assertNull(future.reason());
    }

    @Test
    public void testDispatchWithNoHandler() {
        String result = "success";

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Void> dispatch = future.after();
        future.fulfill(result);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertFalse(future.optional());
        assertEquals(result, future.value());
        assertNull(future.reason());

        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.reason());
    }

    @Test
    public void testDispatchWithHandler() {
        String result = "success";

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Void> dispatch = future.after();
        dispatch.then(onFulfilledAfter);
        future.fulfill(result);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertFalse(future.optional());
        assertEquals(result, future.value());
        assertNull(future.reason());

        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.reason());

        verify(onFulfilledAfter, times(1)).handle(null);
    }

    @Test
    public void testDispatchFailureWithNoHandler() {
        RuntimeException exception = new RuntimeException();

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Void> dispatch = future.after();
        future.reject(exception);

        assertFalse(future.pending());
        assertFalse(future.fulfilled());
        assertTrue(future.rejected());
        assertFalse(future.optional());
        assertNull(future.value());
        assertEquals(exception, future.reason());

        assertFalse(dispatch.fulfilled());
        assertTrue(dispatch.rejected());
        assertEquals(exception, dispatch.reason().getSuppressed()[0]);
    }

    @Test
    public void testDispatchFailureWithNoHandlerAndOptional() {
        RuntimeException exception = new RuntimeException();

        Promise<String> future = new PromiseImpl<String>().optional(true);
        Promise<Void> dispatch = future.after();
        future.reject(exception);

        assertFalse(future.pending());
        assertFalse(future.fulfilled());
        assertTrue(future.rejected());
        assertTrue(future.optional());
        assertNull(future.value());
        assertEquals(exception, future.reason());

        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.reason());
    }

    @Test
    public void testDispatchFailureWithHandler() {
        RuntimeException exception = new RuntimeException();

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Void> dispatch = future.after();
        dispatch.then(onFulfilledAfter, onRejectedAfter);
        future.reject(exception);

        assertFalse(future.pending());
        assertFalse(future.fulfilled());
        assertTrue(future.rejected());
        assertNull(future.value());
        assertEquals(exception, future.reason());

        assertFalse(dispatch.fulfilled());
        assertTrue(dispatch.rejected());
        assertEquals(exception, dispatch.reason().getSuppressed()[0]);

        verify(onFulfilledAfter, never()).handle(null);
        verify(onRejectedAfter, times(1)).handle(any(PromiseException.class));
    }

    @Test
    public void testDispatchFailureWithHandlerAndOptional() {
        RuntimeException exception = new RuntimeException();

        Promise<String> future = new PromiseImpl<String>().optional(true);
        Promise<Void> dispatch = future.after();
        dispatch.then(onFulfilledAfter);
        future.reject(exception);

        assertFalse(future.pending());
        assertFalse(future.fulfilled());
        assertTrue(future.rejected());
        assertTrue(future.optional());
        assertNull(future.value());
        assertEquals(exception, future.reason());

        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.reason());

        verify(onFulfilledAfter, times(1)).handle(null);
    }

    @Test
    public void testThenSuccessWithPromise() {
        String result = "success";

        PromiseImpl<String> parent = new PromiseImpl<>();
        PromiseImpl<String> future = new PromiseImpl<>();
        parent.then(future);

        Promise<Void> dispatch = parent.after();
        parent.fulfill(result);

        assertFalse(parent.pending());
        assertTrue(parent.fulfilled());
        assertFalse(parent.rejected());
        assertFalse(parent.optional());
        assertEquals(result, parent.value());
        assertNull(parent.reason());

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertFalse(future.optional());
        assertEquals(result, future.value());
        assertNull(future.reason());

        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.reason());
    }

    @Test
    public void testThenFailureWithPromise() {
        Exception exception = new Exception("error");

        PromiseImpl<String> parent = new PromiseImpl<>();
        PromiseImpl<String> future = new PromiseImpl<>();
        parent.then(future);

        Promise<Void> dispatch = parent.after();
        parent.reject(exception);

        assertFalse(parent.pending());
        assertFalse(parent.fulfilled());
        assertTrue(parent.rejected());
        assertFalse(parent.optional());
        assertNull(parent.value());
        assertEquals(exception, parent.reason());

        assertFalse(future.pending());
        assertFalse(future.fulfilled());
        assertTrue(future.rejected());
        assertFalse(future.optional());
        assertNull(future.value());
        assertEquals(exception, future.reason());

        assertFalse(dispatch.fulfilled());
        assertTrue(dispatch.rejected());
        assertNull(dispatch.value());
    }

    @Test
    public void testThenCreation() {
        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> then = future.then(onFulfilled);

        assertNotNull(then);
        assertTrue(then.pending());
        assertFalse(then.fulfilled());
        assertFalse(then.rejected());
        assertNull(then.value());
        assertNull(then.reason());

        verify(onFulfilled, never()).handle(any(String.class));
    }

    @Test
    public void testMultipleThenCreation() {
        PromiseImpl<String> future = new PromiseImpl<>();

        List<Promise<Integer>> thenList = new ArrayList<>();
        thenList.add(future.then(onFulfilled));
        thenList.add(future.then(onFulfilled));

        for (Promise<Integer> then : thenList) {
            assertNotNull(then);
            assertTrue(then.pending());
            assertFalse(then.fulfilled());
            assertFalse(then.rejected());
            assertNull(then.value());
            assertNull(then.reason());
        }

        verify(onFulfilled, never()).handle(any(String.class));
    }

    @Test
    public void testDispatchThen() {
        String input = "result";
        Integer output = 1;

        when(onFulfilled.handle(input)).thenReturn(new DefaultPromiseFuture<>(output));

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> then = future.then(onFulfilled);

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(input, future.value());
        assertNull(future.reason());

        assertNotNull(then);
        assertFalse(then.pending());
        assertTrue(then.fulfilled());
        assertFalse(then.rejected());
        assertEquals(output, then.value());
        assertNull(then.reason());

        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.reason());

        verify(onFulfilled, times(1)).handle(input);
    }

    @Test
    public void testDispatchThenWithNullOnFulfilled() {
        PromiseImpl<String> future = new PromiseImpl<>();

        try {
            assertNull("Should have thrown an exception", future.then((AsyncPromiseFunction<String, String>) null));
        } catch (IllegalArgumentException iae) {
            assertNotNull(iae);
        }
    }

    @Test
    public void testDispatchMultipleThen() {
        String input = "result";
        Integer output = 1;

        when(onFulfilled.handle(input)).thenReturn(new DefaultPromiseFuture<>(output));
        when(onFulfilled.equivalent(onFulfilled)).thenReturn(true);

        PromiseImpl<String> future = new PromiseImpl<>();

        List<Promise<Integer>> thenList = new ArrayList<>();
        thenList.add(future.then(onFulfilled));
        thenList.add(future.then(onFulfilled));

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(input, future.value());
        assertNull(future.reason());

        for (Promise<Integer> then : thenList) {
            assertNotNull(then);
            assertFalse(then.pending());
            assertTrue(then.fulfilled());
            assertFalse(then.rejected());
            assertEquals(output, then.value());
            assertNull(then.reason());
        }

        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.reason());

        verify(onFulfilled, times(1)).handle(input);
    }

    @Test
    public void testDispatchMultipleThenWithDuplication() {
        String input = "result";
        Integer output = 1;

        when(onFulfilled.handle(input)).thenReturn(new DefaultPromiseFuture<>(output));

        PromiseImpl<String> future = new PromiseImpl<>();
        future.nonduplicating(false);

        List<Promise<Integer>> thenList = new ArrayList<>();
        thenList.add(future.then(onFulfilled));
        thenList.add(future.then(onFulfilled));

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(input, future.value());
        assertNull(future.reason());

        for (Promise<Integer> then : thenList) {
            assertNotNull(then);
            assertFalse(then.pending());
            assertTrue(then.fulfilled());
            assertFalse(then.rejected());
            assertEquals(output, then.value());
            assertNull(then.reason());
        }

        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.reason());

        verify(onFulfilled, times(2)).handle(input);
    }

    @Test
    public void testDispatchNestedThen() {
        String input = "success";
        Integer output = 1;

        when(onFulfilled.handle(input)).thenReturn(new DefaultPromiseFuture<>(output));
        when(onFulfilledReversed.handle(output)).thenReturn(new DefaultPromiseFuture<>(input));

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> then = future.then(onFulfilled);
        Promise<String> nestedThen = then.then(onFulfilledReversed);

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(input, future.value());
        assertNull(future.reason());

        assertNotNull(then);
        assertFalse(then.pending());
        assertTrue(then.fulfilled());
        assertFalse(then.rejected());
        assertEquals(output, then.value());
        assertNull(then.reason());

        assertNotNull(nestedThen);
        assertFalse(nestedThen.pending());
        assertTrue(nestedThen.fulfilled());
        assertFalse(nestedThen.rejected());
        assertEquals(input, nestedThen.value());
        assertNull(nestedThen.reason());

        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.reason());

        verify(onFulfilled, times(1)).handle(input);
        verify(onFulfilledReversed, times(1)).handle(output);
    }

    @Test
    public void testDispatchNestedThenAndOptional() {
        String input = "success";
        RuntimeException error = new RuntimeException("error");

        when(onFulfilled.handle(input)).thenReturn(new DefaultPromiseFuture<Integer>(error));

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> then = future.then(onFulfilled).optional(true);
        Promise<String> nestedThen = then.then(onFulfilledReversed);

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(input, future.value());
        assertNull(future.reason());

        assertNotNull(then);
        assertFalse(then.pending());
        assertFalse(then.fulfilled());
        assertTrue(then.rejected());
        assertNull(then.value());
        assertEquals(error, then.reason());

        assertNotNull(nestedThen);
        assertFalse(nestedThen.pending());
        assertFalse(nestedThen.fulfilled());
        assertTrue(nestedThen.rejected());
        assertNull(input, nestedThen.value());
        assertEquals(error, nestedThen.reason());

        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.reason());

        verify(onFulfilled, times(1)).handle(input);
        verifyNoMoreInteractions(onFulfilled);
        verifyNoMoreInteractions(onFulfilledReversed);
    }

    @Test
    public void testDispatchNestedThenWithError() {
        String input = "success";
        RuntimeException error = new RuntimeException("error");

        when(onFulfilled.handle(input)).thenReturn(new DefaultPromiseFuture<Integer>(error));

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> then = future.then(onFulfilled);
        Promise<String> nestedThen = then.then(onFulfilledReversed);

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(input, future.value());
        assertNull(future.reason());

        assertNotNull(then);
        assertFalse(then.pending());
        assertFalse(then.fulfilled());
        assertTrue(then.rejected());
        assertNull(then.value());
        assertEquals(error, then.reason());

        assertNotNull(nestedThen);
        assertFalse(nestedThen.pending());
        assertFalse(nestedThen.fulfilled());
        assertTrue(nestedThen.rejected());
        assertNull(nestedThen.value());
        assertEquals(error, nestedThen.reason());

        assertFalse(dispatch.fulfilled());
        assertTrue(dispatch.rejected());
        assertEquals(error, dispatch.reason().getSuppressed()[0]);

        verify(onFulfilled, times(1)).handle(input);
        verify(onFulfilledReversed, never()).handle(any(Integer.class));
    }

    @Test
    public void testOptionalWithAfter() {
        String input = "success";
        Exception error = new Exception("error");

        Promise<String> a = new PromiseImpl<>();
        Promise<String> b = a.then(new EchoFunction<>());
        Promise<String> c = b.then(new EchoFunction<>()).optional(true);
        Promise<Void> d = b.after();

        a.reject(error);

        assertTrue(a.rejected());
        assertTrue(b.rejected());
        assertTrue(c.rejected());
        assertTrue(d.rejected());
    }

    @Test
    public void testDedupeAfterMap() {
        final AtomicInteger counter = new AtomicInteger(0);
        CounterFunction countFunction = new CounterFunction(counter);

        Promise<Void> root = new PromiseImpl<>();
        root.then(new FixedValueFunction<Void, String>("a")).then(countFunction);
        root.then(new FixedValueFunction<Void, String>("b")).then(countFunction);
        root.then(new FixedValueFunction<Void, String>("c")).then(countFunction);

        root.thenList(new SyncPromiseListFunction<Void, String>() {
            public List<String> handle(Void data) {
                return Arrays.asList("a", "b", "c", "a", "b", "c");
            }
        }).map().then(countFunction);
        root.fulfill(null);

        assertEquals(3, counter.get());
    }

    @Test
    public void testDispatchNestedThenWithLeafError() {
        String input = "success";
        Integer output = 1;
        RuntimeException error = new RuntimeException("error");

        when(onFulfilled.handle(input)).thenReturn(new DefaultPromiseFuture<>(output));
        when(onFulfilledReversed.handle(output)).thenReturn(new DefaultPromiseFuture<String>(error));

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> then = future.then(onFulfilled);
        Promise<String> nestedThen = then.then(onFulfilledReversed);

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(input, future.value());
        assertNull(future.reason());

        assertNotNull(then);
        assertFalse(then.pending());
        assertTrue(then.fulfilled());
        assertFalse(then.rejected());
        assertEquals(output, then.value());
        assertNull(then.reason());

        assertNotNull(nestedThen);
        assertFalse(nestedThen.pending());
        assertFalse(nestedThen.fulfilled());
        assertTrue(nestedThen.rejected());
        assertNull(nestedThen.value());
        assertEquals(error, nestedThen.reason());

        assertFalse(dispatch.fulfilled());
        assertTrue(dispatch.rejected());
        assertEquals(error, dispatch.reason().getSuppressed()[0]);

        verify(onFulfilled, times(1)).handle(input);
        verify(onFulfilledReversed, times(1)).handle(output);
    }

    @Test
    public void testDispatchThrowableWithNestedThen() {
        RuntimeException error = new RuntimeException("failure");

        when(onRejectedInteger.handle(error)).thenReturn(new DefaultPromiseFuture<Integer>(error));
        when(onRejectedString.handle(error)).thenReturn(new DefaultPromiseFuture<String>(error));

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> then = future.then(onFulfilled, onRejectedInteger);
        Promise<String> nestedThen = then.then(onFulfilledReversed, onRejectedString);

        Promise<Void> dispatch = future.after();
        future.reject(error);

        assertFalse(future.pending());
        assertFalse(future.fulfilled());
        assertTrue(future.rejected());
        assertNull(future.value());
        assertEquals(error, future.reason());

        assertFalse(then.pending());
        assertFalse(then.fulfilled());
        assertTrue(then.rejected());
        assertNull(then.value());
        assertEquals(error, then.reason());

        assertFalse(nestedThen.pending());
        assertFalse(nestedThen.fulfilled());
        assertTrue(nestedThen.rejected());
        assertNull(nestedThen.value());
        assertEquals(error, nestedThen.reason());

        assertFalse(dispatch.fulfilled());
        assertTrue(dispatch.rejected());
        assertEquals(error, dispatch.reason().getSuppressed()[0]);

        verify(onFulfilled, never()).handle(any(String.class));
        verify(onFulfilledReversed, never()).handle(any(Integer.class));
        verify(onRejectedInteger, times(1)).handle(error);
        verify(onRejectedString, times(1)).handle(error);
    }

    @Test
    public void testDispatchThrowableWithOnRejectSuccessAndNestedThen() {
        RuntimeException error = new RuntimeException("failure");

        when(onRejectedInteger.handle(error)).thenReturn(new DefaultPromiseFuture<>(1));
        when(onFulfilledReversed.handle(1)).thenReturn(new DefaultPromiseFuture<>("success"));

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> then = future.then(onFulfilled, onRejectedInteger);
        Promise<String> nestedThen = then.then(onFulfilledReversed, onRejectedString);

        Promise<Void> dispatch = future.after();
        future.reject(error);

        assertFalse(future.pending());
        assertFalse(future.fulfilled());
        assertTrue(future.rejected());
        assertNull(future.value());
        assertEquals(error, future.reason());

        assertFalse(then.pending());
        assertTrue(then.fulfilled());
        assertFalse(then.rejected());
        assertEquals(Integer.valueOf(1), then.value());
        assertNull(then.reason());

        assertFalse(nestedThen.pending());
        assertTrue(nestedThen.fulfilled());
        assertFalse(nestedThen.rejected());
        assertEquals("success", nestedThen.value());
        assertNull(nestedThen.reason());

        assertFalse(dispatch.fulfilled());
        assertTrue(dispatch.rejected());
        assertNotNull(dispatch.reason());

        verify(onFulfilled, never()).handle(any(String.class));
        verify(onFulfilledReversed, times(1)).handle(any(Integer.class));
        verify(onRejectedInteger, times(1)).handle(error);
    }

    @Test
    public void testDispatchMultipleThenWithAfter() {
        String input = "result";
        Integer output = 1;

        when(onFulfilled.handle(input)).thenReturn(new DefaultPromiseFuture<>(output));
        when(onFulfilled.equivalent(onFulfilled)).thenReturn(true);

        PromiseImpl<String> future = new PromiseImpl<>();

        List<Promise<Integer>> thenList = new ArrayList<>();
        thenList.add(future.then(onFulfilled));
        thenList.add(future.then(onFulfilled));

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(input, future.value());
        assertNull(future.reason());

        for (Promise<Integer> then : thenList) {
            assertNotNull(then);
            assertFalse(then.pending());
            assertTrue(then.fulfilled());
            assertFalse(then.rejected());
            assertEquals(output, then.value());
            assertNull(then.reason());
        }

        assertFalse(dispatch.pending());
        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.value());
        assertNull(dispatch.reason());

        verify(onFulfilled, times(1)).handle(input);
    }

    @Test
    public void testDispatchMultipleThenWithAfterAndDuplicates() {
        String input = "result";
        Integer output = 1;

        when(onFulfilled.handle(input)).thenReturn(new DefaultPromiseFuture<>(output));

        PromiseImpl<String> future = new PromiseImpl<>();
        future.nonduplicating(false);

        List<Promise<Integer>> thenList = new ArrayList<>();
        thenList.add(future.then(onFulfilled));
        thenList.add(future.then(onFulfilled));

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(input, future.value());
        assertNull(future.reason());

        for (Promise<Integer> then : thenList) {
            assertNotNull(then);
            assertFalse(then.pending());
            assertTrue(then.fulfilled());
            assertFalse(then.rejected());
            assertEquals(output, then.value());
            assertNull(then.reason());
        }

        assertFalse(dispatch.pending());
        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.value());
        assertNull(dispatch.reason());

        verify(onFulfilled, times(2)).handle(input);
    }

    @Test
    public void testDispatchNestedThenWithAfter() {
        String input = "result";
        Integer output = 1;

        when(onFulfilled.handle(input)).thenReturn(new DefaultPromiseFuture<>(output));
        when(onFulfilledReversed.handle(output)).thenReturn(new DefaultPromiseFuture<>(input));

        PromiseImpl<String> future = new PromiseImpl<>();

        Promise<Integer> firstThen = future.then(onFulfilled);
        Promise<String> secondThen = firstThen.then(onFulfilledReversed);

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(input, future.value());
        assertNull(future.reason());

        assertNotNull(firstThen);
        assertFalse(firstThen.pending());
        assertTrue(firstThen.fulfilled());
        assertFalse(firstThen.rejected());
        assertEquals(output, firstThen.value());
        assertNull(firstThen.reason());

        assertNotNull(secondThen);
        assertFalse(secondThen.pending());
        assertTrue(secondThen.fulfilled());
        assertFalse(secondThen.rejected());
        assertEquals(input, secondThen.value());
        assertNull(secondThen.reason());

        assertFalse(dispatch.pending());
        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.value());
        assertNull(dispatch.reason());

        verify(onFulfilled, times(1)).handle(input);
        verify(onFulfilledReversed, times(1)).handle(output);
    }

    @Test
    public void testDispatchNestedThenUnfinishedWithAfter() {
        String input = "result";
        Integer output = 1;

        when(onFulfilled.handle(input)).thenReturn(new DefaultPromiseFuture<>(output));
        when(onFulfilledReversed.handle(output)).thenReturn(new DefaultPromiseFuture<String>());

        PromiseImpl<String> future = new PromiseImpl<>();

        Promise<Integer> firstThen = future.then(onFulfilled);
        Promise<String> secondThen = firstThen.then(onFulfilledReversed);

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(input, future.value());
        assertNull(future.reason());

        assertNotNull(firstThen);
        assertFalse(firstThen.pending());
        assertTrue(firstThen.fulfilled());
        assertFalse(firstThen.rejected());
        assertEquals(output, firstThen.value());
        assertNull(firstThen.reason());

        assertNotNull(secondThen);
        assertTrue(secondThen.pending());
        assertFalse(secondThen.fulfilled());
        assertFalse(secondThen.rejected());
        assertNull(secondThen.value());
        assertNull(secondThen.reason());

        assertTrue(dispatch.pending());
        assertFalse(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.value());
        assertNull(dispatch.reason());

        verify(onFulfilled, times(1)).handle(input);
        verify(onFulfilledReversed, times(1)).handle(output);
    }

    @Test
    public void testMapCreation() {
        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> map = future.thenList(onFulfilledMap).map();

        assertNotNull(map);
        assertTrue(map.pending());
        assertFalse(map.fulfilled());
        assertFalse(map.rejected());
        assertNull(map.value());
        assertNull(map.reason());

        verify(onFulfilledMap, never()).handle(any(String.class));
    }

    @Test
    public void testMultipleMapCreation() {
        PromiseImpl<String> future = new PromiseImpl<>();

        List<Promise<Integer>> mapList = new ArrayList<>();
        mapList.add(future.thenList(onFulfilledMap).map());
        mapList.add(future.thenList(onFulfilledMap).map());

        for (Promise<Integer> map : mapList) {
            assertNotNull(map);
            assertTrue(map.pending());
            assertFalse(map.fulfilled());
            assertFalse(map.rejected());
            assertNull(map.value());
            assertNull(map.reason());
        }

        verify(onFulfilled, never()).handle(any(String.class));
    }

    @Test
    public void testDispatchMap() {
        String input = "result";
        List<Integer> output = Arrays.asList(1, 2);

        when(onFulfilledMap.handle(input)).thenReturn(new DefaultPromiseFuture<>(output));

        PromiseImpl<String> future = new PromiseImpl<>();
        future.thenList(onFulfilledMap).map();

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(input, future.value());
        assertNull(future.reason());

        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.reason());

        verify(onFulfilledMap, times(1)).handle(input);
    }

    @Test
    public void testDispatchMapWithNullOnFulfilled() {
        PromiseImpl<String> future = new PromiseImpl<>();

        try {
            assertNull("Should have thrown an exception", future.thenList((PromiseListFunction<String, Void>) null).map());
        } catch (IllegalArgumentException iae) {
            assertNotNull(iae);
        }
    }

    @Test
    public void testEmptyList() {
        String result = "success";

        PromiseImpl<String> future = new PromiseImpl<>();
        future.thenList(new SyncPromiseListFunction<String, String>() {
            public List<String> handle(String data) {
                return Collections.emptyList();
            }
        }).map().then(new SyncPromiseFunction<String, Object>() {
            public Object handle(String data) {
                return data;
            }
        });

        Promise<Void> dispatch = future.after();
        future.fulfill(result);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(result, future.value());
        assertNull(future.reason());

        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.reason());
    }

    @Test
    public void testDispatchMultipleMap() {
        String input = "result";
        List<Integer> output = Arrays.asList(1, 2);

        when(onFulfilledMap.handle(input)).thenReturn(new DefaultPromiseFuture<>(output));
        when(onFulfilledMap.equivalent(onFulfilledMap)).thenReturn(true);

        PromiseImpl<String> future = new PromiseImpl<>();

        future.thenList(onFulfilledMap).map();
        future.thenList(onFulfilledMap).map();

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(input, future.value());
        assertNull(future.reason());

        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.reason());

        verify(onFulfilledMap, times(1)).handle(input);
    }

    @Test
    public void testDispatchMultipleMapWithDuplicates() {
        String input = "result";
        List<Integer> output = Arrays.asList(1, 2);

        when(onFulfilledMap.handle(input)).thenReturn(new DefaultPromiseFuture<>(output));

        PromiseImpl<String> future = new PromiseImpl<>();
        future.nonduplicating(false);

        future.thenList(onFulfilledMap).map();
        future.thenList(onFulfilledMap).map();

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(input, future.value());
        assertNull(future.reason());

        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.reason());

        verify(onFulfilledMap, times(2)).handle(input);
    }

    @Test
    public void testDispatchMapWithNestedThen() {
        String input = "result";
        List<Integer> output = Arrays.asList(1, 2);

        when(onFulfilledMap.handle(input)).thenReturn(new DefaultPromiseFuture<>(output));

        for (Integer intOut : output) {
            when(onFulfilledReversed.handle(intOut)).thenReturn(new DefaultPromiseFuture<>(input));
        }

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> map = future.thenList(onFulfilledMap).map();
        map.then(onFulfilledReversed);

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(future.pending());
        assertTrue(future.fulfilled());
        assertFalse(future.rejected());
        assertEquals(input, future.value());
        assertNull(future.reason());

        assertTrue(dispatch.fulfilled());
        assertFalse(dispatch.rejected());
        assertNull(dispatch.reason());

        verify(onFulfilledMap, times(1)).handle(input);
        verify(onFulfilledReversed, times(1)).handle(1);
        verify(onFulfilledReversed, times(1)).handle(2);
    }

    @Test
    public void testDispatchMapWithNestedMap() {
        String input = "result";
        RuntimeException error = new RuntimeException("error");

        when(onFulfilledMap.handle(input)).thenReturn(new DefaultPromiseFuture<Collection<Integer>>(error));

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> map = future.thenList(onFulfilledMap).map();
        map.thenList(onFulfilledMapReversed).map();

        Promise<Void> dispatch = future.after();
        future.fulfill(input);

        assertFalse(dispatch.fulfilled());
        assertTrue(dispatch.rejected());
        assertEquals(error, dispatch.reason().getSuppressed()[0]);

        verify(onFulfilledMap, times(1)).handle(input);
        verify(onFulfilledMapReversed, never()).handle(any(Integer.class));
    }

    @Test
    public void testDispatchMapWithNestedFailure() {
        RuntimeException error = new RuntimeException("1");

        when(onRejectedIntegerList.handle(error)).thenReturn(new DefaultPromiseFuture<Collection<Integer>>(error));
        when(onRejectedString.handle(error)).thenReturn(new DefaultPromiseFuture<>(error));

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> map = future.thenList(onFulfilledMap, onRejectedIntegerList).map();
        map.then(onFulfilledReversed, onRejectedString);

        Promise<Void> dispatch = future.after();
        future.reject(error);

        assertFalse(dispatch.fulfilled());
        assertTrue(dispatch.rejected());
        assertEquals(error, dispatch.reason().getSuppressed()[0]);

        verify(onFulfilledMap, never()).handle(any(String.class));
        verify(onFulfilledReversed, never()).handle(any(Integer.class));
        verify(onRejectedIntegerList, times(1)).handle(error);
        verify(onRejectedString, times(1)).handle(error);
    }

    @Test
    public void testDispatchMapFailureWithOnRejectSuccessOnNested() {
        String success = "success";
        RuntimeException error = new RuntimeException("1");

        when(onRejectedIntegerList.handle(error)).thenReturn(new DefaultPromiseFuture<>(Collections.singletonList(1)));
        when(onFulfilledReversed.handle(1)).thenReturn(new DefaultPromiseFuture<>(success));

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> map = future.thenList(onFulfilledMap, onRejectedIntegerList).map();
        map.then(onFulfilledReversed, onRejectedString);

        Promise<Void> dispatch = future.after();
        future.reject(error);

        assertFalse(dispatch.fulfilled());
        assertTrue(dispatch.rejected());
        assertNotNull(dispatch.reason());

        verify(onFulfilledMap, never()).handle(any(String.class));
        verify(onRejectedIntegerList, times(1)).handle(error);
        verify(onFulfilledReversed, times(1)).handle(any(Integer.class));
        verify(onRejectedString, never()).handle(any(Throwable.class));
    }

    @Test
    public void testDispatchMapWithNestedFailureAlt() {
        RuntimeException error = new RuntimeException("1");

        when(onRejectedIntegerList.handle(error)).thenReturn(new DefaultPromiseFuture<Collection<Integer>>(error));
        when(onRejectedString.handle(error)).thenReturn(new DefaultPromiseFuture<>(error));

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> map = future.thenList(onFulfilledMap, onRejectedIntegerList).map();
        map.then(onFulfilledReversed, onRejectedString);

        Promise<Void> dispatch = future.after();
        future.reject(error);

        assertFalse(dispatch.fulfilled());
        assertTrue(dispatch.rejected());
        assertEquals(error, dispatch.reason().getSuppressed()[0]);

        verify(onFulfilledMap, never()).handle(any(String.class));
        verify(onFulfilledReversed, never()).handle(any(Integer.class));
        verify(onRejectedIntegerList, times(1)).handle(error);
        verify(onRejectedString, times(1)).handle(error);
    }

    @Test
    public void testMultipleDispatchFails() {
        String input = "result";
        List<Integer> output = Arrays.asList(1, 2);

        when(onFulfilledMap.handle(input)).thenReturn(new DefaultPromiseFuture<>(output));

        for (Integer intOut : output) {
            when(onFulfilledReversed.handle(intOut)).thenReturn(new DefaultPromiseFuture<>(input));
        }

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> map = future.thenList(onFulfilledMap).map();
        map.then(onFulfilledReversed);

        future.fulfill(input);

        try {
            future.fulfill(input);
            assertFalse("Failed to throw error", true);
        } catch (IllegalStateException ise) {
            assertNotNull(ise);
        }
    }

    @Test
    public void testMultipleNestedDispatchFails() {
        String input = "result";
        List<Integer> output = Arrays.asList(1, 2);

        when(onFulfilledMap.handle(input)).thenReturn(new DefaultPromiseFuture<>(output));

        for (Integer intOut : output) {
            when(onFulfilledReversed.handle(intOut)).thenReturn(new DefaultPromiseFuture<>(input));
        }

        PromiseImpl<String> future = new PromiseImpl<>();
        Promise<Integer> map = future.thenList(onFulfilledMap).map();
        Promise<String> then = map.then(onFulfilledReversed);

        future.fulfill(input);

        try {
            then.fulfill(input);
            assertFalse("Failed to throw error", true);
        } catch (IllegalStateException ise) {
            assertNotNull(ise);
        }
    }

    @Test
    public void testDeferredAfter() {
        Map<String, PromiseFuture<String>> results = new HashMap<>();

        Promise<String> future = new PromiseImpl<>();
        future.then((AsyncPromiseFunction<String, String>) data -> {
            PromiseFuture<String> current = new DefaultPromiseFuture<>();
            results.put("one", current);
            return current;
        });
        future.then((AsyncPromiseFunction<String, String>) data -> {
            PromiseFuture<String> current = new DefaultPromiseFuture<>();
            results.put("two", current);
            return current;
        });
        future.then((AsyncPromiseFunction<String, String>) data -> {
            PromiseFuture<String> current = new DefaultPromiseFuture<>();
            results.put("three", current);
            return current;
        });

        Map<String, PromiseFuture<Void>> afterResults = new HashMap<>();

        Promise<Void> after = future.after();
        after.then((AsyncPromiseFunction<Void, Void>) data -> {
            PromiseFuture<Void> current = new DefaultPromiseFuture<>();
            afterResults.put("four", current);
            return current;
        }, (AsyncPromiseFunction<Throwable, Void>) data -> {
            PromiseFuture<Void> current = new DefaultPromiseFuture<>();
            afterResults.put("five", current);
            return current;

        });

        assertEquals(0, results.size());
        assertEquals(0, afterResults.size());
        assertTrue(after.pending());

        future.fulfill("result");

        assertEquals(3, results.size());
        assertEquals(0, afterResults.size());
        assertTrue(after.pending());

        results.get("one").setResult("success");
        results.get("two").setResult("success");

        assertEquals(3, results.size());
        assertEquals(0, afterResults.size());
        assertTrue(after.pending());

        results.get("three").setResult("success");

        assertEquals(3, results.size());
        assertEquals(1, afterResults.size());
        assertTrue(after.fulfilled());
    }

    @Test
    public void testThenWithLambdaSuccess() {
        String input = "result";

        List<String> results = new ArrayList<>();

        PromiseImpl<String> future = new PromiseImpl<>();
        future.thenSync(data -> {
            results.add(input);
            return input;
        });
        future.thenSync(new EchoFunction<>(), data -> {
            results.add(input);
            return input;
        });
        future.thenSync(data -> {
            results.add(input);
            return input;
        }, data -> {
            results.add(input);
            return input;
        });
        future.thenAsync(data -> {
            results.add(input);
            return new DefaultPromiseFuture<>(input);
        });
        future.thenAsync(data -> {
            results.add(input);
            return new DefaultPromiseFuture<>(input);
        }, onRejectedString);

        future.fulfill(input);

        assertEquals(4, results.size());
    }

    @Test
    public void testThenWithLambdaRejected() {
        Throwable error = new Exception("result");

        List<String> results = new ArrayList<>();

        PromiseImpl<String> future = new PromiseImpl<>();
        future.thenSync(data -> {
            results.add("result");
            return "result";
        }, data -> {
            results.add("result");
            return "result";
        });
        future.thenSync(new EchoFunction<>(), data -> {
            results.add("result");
            return "result";
        });
        future.thenSync(data -> {
            results.add("result");
            return "result";
        }, data -> {
            results.add("result");
            return "result";
        });
        future.thenAsync(data -> {
            results.add("result");
            return new DefaultPromiseFuture<>("result");
        });
        future.thenAsync(data -> {
            results.add("result");
            return new DefaultPromiseFuture<>("result");
        }, data -> {
            results.add("result");
            return new DefaultPromiseFuture<>("result");
        });

        future.reject(error);

        assertEquals(4, results.size());
    }

    private class CounterFunction implements SyncPromiseFunction<String, Integer>, ComparablePromiseFunction {
        private AtomicInteger counter;

        CounterFunction(AtomicInteger counter) {
            this.counter = counter;
        }

        public Integer handle(String value) {
            return counter.incrementAndGet();
        }

        @Override
        public boolean equivalent(Object o) {
            return this == o || (o != null && CounterFunction.class.equals(o.getClass()));
        }
    }
}


text:
import { UpdateTopicParentTopicsInput } from '__generated__/updateTopicParentTopicsMutation.graphql';
export declare type Input = UpdateTopicParentTopicsInput;
declare const _default: (...args: any) => import("react-relay").Disposable;
export default _default;

redpajama_set_name: RedPajamaGithub


text:
.. _simplest_approach:

Getting started
===============

This approach requires fewest input of code to complete the orbit
correction optimization task, which also means you only has very few
options to adjust to the optimization model. Hopefully, this approach
could be used as an ordinary template to fulfill most of the orbit
correction tasks. Below is the demo code:

.. literalinclude:: ../../snippets/demo1.py
    :language: python

The lattice file used here could be found from
:download:`here <../../snippets/test_392.lat>`, or from `https://github.com/archman/genopt/blob/master/lattice/test_392.lat <https://github.com/archman/genopt/blob/master/lattice/test_392.lat>`_.

For this approach, the following default configuration is applied:

1. Selected all BPMs and correctors (both horizontal and vertical types);
2. Set the reference orbit with all BPMs' readings of ``x=0`` and ``y=0``;
3. Set the objective function with the sum of all the square of orbit deviations w.r.t. reference orbit.

By default, ``conmin_frcg`` optimization method is used, possible options
for ``simple_run()`` could be:

* common options:
    1. ``mpi``: if True, run in parallel mode; if False, run in serial mode;
    2. ``np``: number of cores to use if ``mpi`` is True;
    3. ``echo``: if False, will not generate output when optimizing, the same for :func:`run()`;
* gradient descent, i.e. ``method=cg``:
    1. ``iternum``: max iteration number, 20 by default;
    2. ``step``: forward gradient step size, 1e-6 by default;
* pattern search, i.e. ``method=ps``:
    1. ``iternum``: max iteration number, 20 by default;
    2. ``evalnum``: max function evaulation number, 1000 by default;

There are two options for ``DakotaOC`` maybe useful sometimes:

1. ``workdir``: root directory for dakota input and output files
2. ``keep``: if keep working files, True or False

After run this script, beam orbit data could be saved into file, e.g.
:download:`orbit.dat <../../snippets/orbit.dat>`:

which could be used to generate figures, the following figure is a typical
one could be generated from the optimized results:

.. image:: ../../images/oc_x0y0.png
    :width: 500px
    :align: center


text:
/**********************************************************************
   Copyright [2014] [Cisco Systems, Inc.]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
**********************************************************************/

/**************************************************************************

    module: cosa_userinterface_internal.c

        For COSA Data Model Library Development

    -------------------------------------------------------------------

    description:

        This file implementes back-end apis for the COSA Data Model Library

        *  CosaUserinterfaceCreate
        *  CosaUserinterfaceInitialize
        *  CosaUserinterfaceRemove
    -------------------------------------------------------------------

    environment:

        platform independent

    -------------------------------------------------------------------

    author:

        COSA XML TOOL CODE GENERATOR 1.0

    -------------------------------------------------------------------

    revision:

        01/11/2011    initial revision.

**************************************************************************/

#include "cosa_userinterface_internal.h"
#include "safec_lib_common.h"

extern void* g_pDslhDmlAgent;

/**********************************************************************

    caller:     owner of the object

    prototype:

        ANSC_HANDLE
        CosaUserinterfaceCreate
            (
            );

    description:

        This function constructs cosa Userinterface object and return handle.

    argument:

    return:     newly created Userinterface object.

**********************************************************************/

ANSC_HANDLE
CosaUserinterfaceCreate
    (
        VOID
    )
{
    PCOSA_DATAMODEL_USERINTERFACE   pMyObject    = (PCOSA_DATAMODEL_USERINTERFACE)NULL;

    /*
     * We create object by first allocating memory for holding the variables and member functions.
     */
    pMyObject = (PCOSA_DATAMODEL_USERINTERFACE)AnscAllocateMemory(sizeof(COSA_DATAMODEL_USERINTERFACE));

    if ( !pMyObject )
    {
        return  (ANSC_HANDLE)NULL;
    }

    /*
     * Initialize the common variables and functions for a container object.
     */
    pMyObject->Oid               = COSA_DATAMODEL_USERINTERFACE_OID;
    pMyObject->Create            = CosaUserinterfaceCreate;
    pMyObject->Remove            = CosaUserinterfaceRemove;
    pMyObject->Initialize        = CosaUserinterfaceInitialize;

    pMyObject->Initialize   ((ANSC_HANDLE)pMyObject);

    return  (ANSC_HANDLE)pMyObject;
}

/**********************************************************************

    caller:     self

    prototype:

        ANSC_STATUS
        CosaUserinterfaceInitialize
            (
                ANSC_HANDLE                 hThisObject
            );

    description:

        This function initiate  cosa Userinterface object and return handle.

    argument:   ANSC_HANDLE                 hThisObject
            This handle is actually the pointer of this object
            itself.

    return:     operation status.

**********************************************************************/

ANSC_STATUS
CosaUserinterfaceInitialize
    (
        ANSC_HANDLE                 hThisObject
    )
{
    ANSC_STATUS                         returnStatus = ANSC_STATUS_SUCCESS;
    PCOSA_DATAMODEL_USERINTERFACE       pMyObject    = (PCOSA_DATAMODEL_USERINTERFACE)hThisObject;
    PPOAM_IREP_FOLDER_OBJECT        pPoamIrepFoCOSA        = (PPOAM_IREP_FOLDER_OBJECT)NULL;
    PPOAM_IREP_FOLDER_OBJECT        hIrepFolderUIIPRange   = (PPOAM_IREP_FOLDER_OBJECT)NULL;
    PSLAP_VARIABLE                  pSlapVariable          = (PSLAP_VARIABLE          )NULL;
    PCOSA_CONTEXT_LINK_OBJECT       pCosaContext           = (PCOSA_CONTEXT_LINK_OBJECT)NULL;
    PCOSA_DML_UI_IPRANGE_ENTRY      pEntry                 = (PCOSA_DML_UI_IPRANGE_ENTRY)NULL;
    ULONG                           ulEntryCount           = 0;
    ULONG                           ulIndex                = 0;
    errno_t                         rc                     = -1;

    /* Initiation all functions */
    _ansc_memset(&pMyObject->RaCfg, 0, sizeof(COSA_DML_RA_CFG));
    _ansc_memset(&pMyObject->UserInterfaceCfg, 0, sizeof(COSA_DML_USERINTERFACE_CFG));

    CosaDmlRaInit(NULL, NULL);

    CosaDmlRaGetCfg(NULL, &pMyObject->RaCfg);
    CosaDmlUserInterfaceGetCfg(NULL, &pMyObject->UserInterfaceCfg);

    pMyObject->hIrepFolderCOSA = g_GetRegistryRootFolder(g_pDslhDmlAgent);

    /* Initiation Device.UserInterface.X_CISCO_COM_RemoteAccess.iprange.{i}. */

    AnscSListInitializeHeader(&pMyObject->iprangeList);

    pMyObject->uliprangeNextInsNum = 1;

    pPoamIrepFoCOSA = (PPOAM_IREP_FOLDER_OBJECT)pMyObject->hIrepFolderCOSA;
    if ( !pPoamIrepFoCOSA )
    {
        return ANSC_STATUS_FAILURE;
    }

    hIrepFolderUIIPRange =
        (PPOAM_IREP_FOLDER_OBJECT)pPoamIrepFoCOSA->GetFolder
            (
                (ANSC_HANDLE)pPoamIrepFoCOSA,
                COSA_IREP_FOLDER_NAME_UserInterface_IPRange
            );

    if ( !hIrepFolderUIIPRange )
    {
        hIrepFolderUIIPRange =
            pPoamIrepFoCOSA->AddFolder
                (
                    (ANSC_HANDLE)pPoamIrepFoCOSA,
                    COSA_IREP_FOLDER_NAME_UserInterface_IPRange,
                    0
                );
    }

    if ( !hIrepFolderUIIPRange )
    {
        return ANSC_STATUS_FAILURE;
    }
    else
    {
        pMyObject->hIrepFolderUIIPRange = (ANSC_HANDLE)hIrepFolderUIIPRange;
    }

    /* Retrieve Next Instance Number */

    if ( TRUE )
    {
        pSlapVariable =
            (PSLAP_VARIABLE)hIrepFolderUIIPRange->GetRecord
                (
                    (ANSC_HANDLE)hIrepFolderUIIPRange,
                    COSA_DML_RR_NAME_UserInterface_IPRangeNextInsNunmber,
                    NULL
                );

        if ( pSlapVariable )
        {
            pMyObject->uliprangeNextInsNum = pSlapVariable->Variant.varUint32;

            SlapFreeVariable(pSlapVariable);
        }
    }

    /* Initialize middle layer */

    ulEntryCount = CosaDmlUIIPRangeGetNumberOfEntries(NULL);

    for ( ulIndex = 0; ulIndex < ulEntryCount; ulIndex++ )
    {
        pEntry = (PCOSA_DML_UI_IPRANGE_ENTRY)AnscAllocateMemory(sizeof(COSA_DML_UI_IPRANGE_ENTRY));

        if ( !pEntry )
        {
            return ANSC_STATUS_RESOURCES;
        }

        CosaDmlUIIPRangeGetEntry(NULL, ulIndex, pEntry);

        if ( TRUE )
        {
            pCosaContext = (PCOSA_CONTEXT_LINK_OBJECT)AnscAllocateMemory(sizeof(COSA_CONTEXT_LINK_OBJECT));

            if ( !pCosaContext )
            {
                AnscFreeMemory(pEntry);

                return ANSC_STATUS_RESOURCES;
            }

            if ( pEntry->InstanceNumber != 0 )
            {
                pCosaContext->InstanceNumber = pEntry->InstanceNumber;

                if ( pMyObject->uliprangeNextInsNum <= pEntry->InstanceNumber )
                {
                    pMyObject->uliprangeNextInsNum = pEntry->InstanceNumber + 1;

                    if ( pMyObject->uliprangeNextInsNum == 0 )
                    {
                        pMyObject->uliprangeNextInsNum = 1;
                    }
                }
            }
            else
            {
                pEntry->InstanceNumber = pCosaContext->InstanceNumber = pMyObject->uliprangeNextInsNum;

                pMyObject->uliprangeNextInsNum++;

                if ( pMyObject->uliprangeNextInsNum == 0 )
                {
                    pMyObject->uliprangeNextInsNum = 1;
                }

                /* Generate Alias */
                rc = sprintf_s(pEntry->Alias, sizeof(pEntry->Alias),"iprange%d", (int)pCosaContext->InstanceNumber);
                if(rc < EOK)
                {
                  ERR_CHK(rc);
                  AnscFreeMemory(pEntry);
                  AnscFreeMemory(pCosaContext);
                  return ANSC_STATUS_FAILURE;
                }

                CosaDmlUIIPRangeSetValues
                (
                    NULL,
                    ulIndex,
                    pCosaContext->InstanceNumber,
                    pEntry->Alias
                );
            }

            pCosaContext->hContext      = (ANSC_HANDLE)pEntry;
            pCosaContext->hParentTable  = NULL;
            pCosaContext->bNew          = FALSE;
            pCosaContext->hPoamIrepUpperFo = NULL;
            pCosaContext->hPoamIrepFo      = NULL;

            CosaSListPushEntryByInsNum(&pMyObject->iprangeList, pCosaContext);
        }
    }

    return returnStatus;
}

/**********************************************************************

    caller:     self

    prototype:

        ANSC_STATUS
        CosaUserinterfaceRemove
            (
                ANSC_HANDLE                 hThisObject
            );

    description:

        This function initiate  cosa Userinterface object and return handle.

    argument:   ANSC_HANDLE                 hThisObject
            This handle is actually the pointer of this object
            itself.

    return:     operation status.

**********************************************************************/

ANSC_STATUS
CosaUserinterfaceRemove
    (
        ANSC_HANDLE                 hThisObject
    )
{
    ANSC_STATUS                         returnStatus = ANSC_STATUS_SUCCESS;
    PCOSA_DATAMODEL_USERINTERFACE       pMyObject    = (PCOSA_DATAMODEL_USERINTERFACE)hThisObject;

    /* Remove necessary resounce */

    /* Remove self */
    AnscFreeMemory((ANSC_HANDLE)pMyObject);

    return returnStatus;
}


text:
var React = require('react');
var styles = require('./MessageItem.scss');

var cn = require('classnames');

var MessageItem = React.createClass({
  render: function () {
    var rs = this.props.rs;
    var content = this.props.content;
    var avatar = this.props.avatar;
    var name = this.props.name

    return (

        {name}

{content}

    );
  }
});

module.exports = MessageItem;


text:
. "$(dirname "$0")/testlib.sh"

contents="a"
contents_oid=$(calc_oid "$contents")
b="b"
b_oid=$(calc_oid "$b")
reponame="$(basename "$0" ".sh")"

begin_test "init for fetch tests"
(
  set -e

  setup_remote_repo "$reponame"

  clone_repo "$reponame" repo

  git lfs track "*.dat" 2>&1 | tee track.log
  grep "Tracking \"\*.dat\"" track.log

  printf "%s" "$contents" > a.dat
  git add a.dat
  git add .gitattributes
  git commit -m "add a.dat" 2>&1 | tee commit.log
  grep "main (root-commit)" commit.log
  grep "2 files changed" commit.log
  grep "create mode 100644 a.dat" commit.log
  grep "create mode 100644 .gitattributes" commit.log

  [ "a" = "$(cat a.dat)" ]

  assert_local_object "$contents_oid" 1

  refute_server_object "$reponame" "$contents_oid"

  git push origin main 2>&1 | tee push.log
  grep "Uploading LFS objects: 100% (1/1), 1 B" push.log
  grep "main -> main" push.log

  assert_server_object "$reponame" "$contents_oid"

  # Add a file in a different branch
  git checkout -b newbranch
  printf "%s" "$b" > b.dat
  git add b.dat
  git commit -m "add b.dat"
  assert_local_object "$b_oid" 1

  git push origin newbranch
  assert_server_object "$reponame" "$b_oid"

  # These clones are used for subsequent tests
  clone_repo "$reponame" clone
  git clone --shared "$TRASHDIR/clone" "$TRASHDIR/shared"
)
end_test

begin_test "fetch"
(
  set -e
  cd clone
  rm -rf .git/lfs/objects

  git lfs fetch
  assert_local_object "$contents_oid" 1

  git lfs fsck 2>&1 | tee fsck.log
  grep "Git LFS fsck OK" fsck.log
)
end_test

begin_test "fetch (shared repository)"
(
  set -e
  cd shared
  rm -rf .git/lfs/objects

  git lfs fetch 2>&1 | tee fetch.log
  ! grep "Could not scan" fetch.log
  assert_local_object "$contents_oid" 1

  git lfs fsck 2>&1 | tee fsck.log
  grep "Git LFS fsck OK" fsck.log
)
end_test

begin_test "fetch with remote"
(
  set -e
  cd clone
  rm -rf .git/lfs/objects

  git lfs fetch origin
  assert_local_object "$contents_oid" 1
  refute_local_object "$b_oid" 1

  git lfs fsck 2>&1 | tee fsck.log
  grep "Git LFS fsck OK" fsck.log
)
end_test

begin_test "fetch with remote and branches"
(
  set -e
  cd clone

  git checkout newbranch
  git checkout main

  rm -rf .git/lfs/objects

  git lfs fetch origin main newbranch
  assert_local_object "$contents_oid" 1
  assert_local_object "$b_oid" 1

  git lfs fsck 2>&1 | tee fsck.log
  grep "Git LFS fsck OK" fsck.log
)
end_test

begin_test "fetch with main commit sha1"
(
  set -e
  cd clone
  rm -rf .git/lfs/objects

  main_sha1=$(git rev-parse main)
  git lfs fetch origin "$main_sha1"
  assert_local_object "$contents_oid" 1
  refute_local_object "$b_oid" 1

  git lfs fsck 2>&1 | tee fsck.log
  grep "Git LFS fsck OK" fsck.log
)
end_test

begin_test "fetch with newbranch commit sha1"
(
  set -e
  cd clone
  rm -rf .git/lfs/objects

  newbranch_sha1=$(git rev-parse newbranch)
  git lfs fetch origin "$newbranch_sha1"
  assert_local_object "$contents_oid" 1
  assert_local_object "$b_oid" 1

  git lfs fsck 2>&1 | tee fsck.log
  grep "Git LFS fsck OK" fsck.log
)
end_test

begin_test "fetch with include filters in gitconfig"
(
  set -e
  cd clone
  rm -rf .git/lfs/objects

  git config "lfs.fetchinclude" "a*"
  git lfs fetch origin main newbranch
  assert_local_object "$contents_oid" 1
  refute_local_object "$b_oid"

  git lfs fsck 2>&1 | tee fsck.log
  grep "Git LFS fsck OK" fsck.log
)
end_test

begin_test "fetch with exclude filters in gitconfig"
(
  set -e

  cd clone
  git config --unset "lfs.fetchinclude"
  rm -rf .git/lfs/objects

  git config "lfs.fetchexclude" "a*"
  git lfs fetch origin main newbranch
  refute_local_object "$contents_oid"
  assert_local_object "$b_oid" 1

  git lfs fsck 2>&1 | tee fsck.log
  grep "Git LFS fsck OK" fsck.log
)
end_test

begin_test "fetch with include/exclude filters in gitconfig"
(
  set -e
  cd clone
  rm -rf .git/lfs/objects
  git config --unset "lfs.fetchexclude"

  git config "lfs.fetchinclude" "a*,b*"
  git config "lfs.fetchexclude" "c*,d*"
  git lfs fetch origin main newbranch
  assert_local_object "$contents_oid" 1
  assert_local_object "$b_oid" 1

  rm -rf .git/lfs/objects
  git config "lfs.fetchinclude" "c*,d*"
  git config "lfs.fetchexclude" "a*,b*"
  git lfs fetch origin main newbranch
  refute_local_object "$contents_oid"
  refute_local_object "$b_oid"
)
end_test

begin_test "fetch with include filter in cli"
(
  set -e
  cd clone
  git config --unset "lfs.fetchinclude"
  git config --unset "lfs.fetchexclude"
  rm -rf .git/lfs/objects

  git lfs fetch --include="a*" origin main newbranch
  assert_local_object "$contents_oid" 1
  refute_local_object "$b_oid"
)
end_test

begin_test "fetch with exclude filter in cli"
(
  set -e
  cd clone
  rm -rf .git/lfs/objects
  git lfs fetch --exclude="a*" origin main newbranch
  refute_local_object "$contents_oid"
  assert_local_object "$b_oid" 1
)
end_test

begin_test "fetch with include/exclude filters in cli"
(
  set -e
  cd clone
  rm -rf .git/lfs/objects
  git lfs fetch -I "a*,b*" -X "c*,d*" origin main newbranch
  assert_local_object "$contents_oid" 1
  assert_local_object "$b_oid" 1

  rm -rf .git/lfs/objects
  git lfs fetch --include="c*,d*" --exclude="a*,b*" origin main newbranch
  refute_local_object "$contents_oid"
  refute_local_object "$b_oid"
)
end_test

begin_test "fetch with include filter overriding exclude filter"
(
  set -e
  cd clone
  rm -rf .git/lfs/objects
  git config lfs.fetchexclude "b*"
  git lfs fetch -I "b.dat" -X "" origin main newbranch
  assert_local_object "$b_oid" "1"
)
end_test

begin_test "fetch with missing object"
(
  set -e
  cd clone
  git config --unset lfs.fetchexclude
  rm -rf .git/lfs/objects

  delete_server_object "$reponame" "$b_oid"
  refute_server_object "$reponame" "$b_oid"

  # should return non-zero, but should also download all the other valid files too
  set +e
  git lfs fetch origin main newbranch
  fetch_exit=$?
  set -e
  [ "$fetch_exit" != "0" ]
  assert_local_object "$contents_oid" 1
  refute_local_object "$b_oid"
)
end_test

begin_test "fetch-all"
(
  set -e

  reponame="fetch-all"
  setup_remote_repo "$reponame"

  clone_repo "$reponame" "$reponame"

  git lfs track "*.dat" 2>&1 | tee track.log
  grep "Tracking \"\*.dat\"" track.log

  NUMFILES=12
  # generate content we'll use
  for ((a=0; a < NUMFILES ; a++))
  do
    content[$a]="filecontent$a"
    oid[$a]=$(calc_oid "${content[$a]}")
  done

  echo "[
  {
    \"CommitDate\":\"$(get_date -180d)\",
    \"Files\":[
      {\"Filename\":\"file1.dat\",\"Size\":${#content[0]}, \"Data\":\"${content[0]}\"},
      {\"Filename\":\"file2.dat\",\"Size\":${#content[1]}, \"Data\":\"${content[1]}\"}]
  },
  {
    \"NewBranch\":\"branch1\",
    \"CommitDate\":\"$(get_date -140d)\",
    \"Files\":[
      {\"Filename\":\"file3.dat\",\"Size\":${#content[2]}, \"Data\":\"${content[2]}\"}]
  },
  {
    \"ParentBranches\":[\"main\"],
    \"CommitDate\":\"$(get_date -100d)\",
    \"Files\":[
      {\"Filename\":\"file1.dat\",\"Size\":${#content[3]}, \"Data\":\"${content[3]}\"}]
  },
  {
    \"NewBranch\":\"remote_branch_only\",
    \"CommitDate\":\"$(get_date -80d)\",
    \"Files\":[
      {\"Filename\":\"file2.dat\",\"Size\":${#content[4]}, \"Data\":\"${content[4]}\"}]
  },
  {
    \"ParentBranches\":[\"main\"],
    \"CommitDate\":\"$(get_date -75d)\",
    \"Files\":[
      {\"Filename\":\"file4.dat\",\"Size\":${#content[5]}, \"Data\":\"${content[5]}\"}]
  },
  {
    \"NewBranch\":\"tag_only\",
    \"Tags\":[\"tag1\"],
    \"CommitDate\":\"$(get_date -70d)\",
    \"Files\":[
      {\"Filename\":\"file4.dat\",\"Size\":${#content[6]}, \"Data\":\"${content[6]}\"}]
  },
  {
    \"ParentBranches\":[\"main\"],
    \"CommitDate\":\"$(get_date -60d)\",
    \"Files\":[
      {\"Filename\":\"file1.dat\",\"Size\":${#content[7]}, \"Data\":\"${content[7]}\"}]
  },
  {
    \"NewBranch\":\"branch3\",
    \"CommitDate\":\"$(get_date -50d)\",
    \"Files\":[
      {\"Filename\":\"file4.dat\",\"Size\":${#content[8]}, \"Data\":\"${content[8]}\"}]
  },
  {
    \"CommitDate\":\"$(get_date -40d)\",
    \"ParentBranches\":[\"main\"],
    \"Files\":[
      {\"Filename\":\"file1.dat\",\"Size\":${#content[9]}, \"Data\":\"${content[9]}\"},
      {\"Filename\":\"file2.dat\",\"Size\":${#content[10]}, \"Data\":\"${content[10]}\"}]
  },
  {
    \"ParentBranches\":[\"main\"],
    \"CommitDate\":\"$(get_date -30d)\",
    \"Files\":[
      {\"Filename\":\"file4.dat\",\"Size\":${#content[11]}, \"Data\":\"${content[11]}\"}]
  }
  ]" | lfstest-testutils addcommits

  git push origin main
  git push origin branch1
  git push origin branch3
  git push origin remote_branch_only
  git push origin tag_only
  git push origin tag1
  for ((a=0; a < NUMFILES ; a++))
  do
    assert_server_object "$reponame" "${oid[$a]}"
  done

  # delete remote_branch_only and make sure that objects are downloaded even
  # though not checked out to a local branch (full backup always)
  git branch -D remote_branch_only

  # delete tag_only to make sure objects are downloaded when only reachable from tag
  git branch -D tag_only

  rm -rf .git/lfs/objects

  git lfs fetch --all origin
  for ((a=0; a < NUMFILES ; a++))
  do
    assert_local_object "${oid[$a]}" "${#content[$a]}"
  done

  rm -rf .git/lfs/objects

  # fetch all objects reachable from the main branch only
  git lfs fetch --all origin main
  for a in 0 1 3 5 7 9 10 11
  do
    assert_local_object "${oid[$a]}" "${#content[$a]}"
  done
  for a in 2 4 6 8
  do
    refute_local_object "${oid[$a]}"
  done

  rm -rf .git/lfs/objects

  # fetch all objects reachable from branch1 and tag1 only
  git lfs fetch --all origin branch1 tag1
  for a in 0 1 2 3 5 6
  do
    assert_local_object "${oid[$a]}" "${#content[$a]}"
  done
  for a in 4 7 8 9 10 11
  do
    refute_local_object "${oid[$a]}"
  done

  # Make a bare clone of the repository
  cd ..
  git clone --bare "$GITSERVER/$reponame" "$reponame-bare"
  cd "$reponame-bare"

  # Preform the same assertion as above, on the same data
  git lfs fetch --all origin
  for ((a=0; a < NUMFILES ; a++))
  do
    assert_local_object "${oid[$a]}" "${#content[$a]}"
  done

  rm -rf lfs/objects

  # fetch all objects reachable from the main branch only
  git lfs fetch --all origin main
  for a in 0 1 3 5 7 9 10 11
  do
    assert_local_object "${oid[$a]}" "${#content[$a]}"
  done
  for a in 2 4 6 8
  do
    refute_local_object "${oid[$a]}"
  done

  rm -rf lfs/objects

  # fetch all objects reachable from branch1 and tag1 only
  git lfs fetch --all origin branch1 tag1
  for a in 0 1 2 3 5 6
  do
    assert_local_object "${oid[$a]}" "${#content[$a]}"
  done
  for a in 4 7 8 9 10 11
  do
    refute_local_object "${oid[$a]}"
  done
)
end_test

begin_test "fetch: outside git repository"
(
  set +e
  git lfs fetch 2>&1 > fetch.log
  res=$?

  set -e
  if [ "$res" = "0" ]; then
    echo "Passes because $GIT_LFS_TEST_DIR is unset."
    exit 0
  fi
  [ "$res" = "128" ]
  grep "Not in a git repository" fetch.log
)
end_test

begin_test "fetch with no origin remote"
(
  set -e

  reponame="fetch-no-remote"
  setup_remote_repo "$reponame"

  clone_repo "$reponame" no-remote-clone

  clone_repo "$reponame" no-remote-repo

  git lfs track "*.dat" 2>&1 | tee track.log
  grep "Tracking \"\*.dat\"" track.log

  contents="a"
  contents_oid=$(calc_oid "$contents")

  printf "%s" "$contents" > a.dat
  git add a.dat
  git add .gitattributes
  git commit -m "add a.dat" 2>&1 | tee commit.log
  grep "main (root-commit)" commit.log
  grep "2 files changed" commit.log
  grep "create mode 100644 a.dat" commit.log
  grep "create mode 100644 .gitattributes" commit.log

  [ "a" = "$(cat a.dat)" ]

  assert_local_object "$contents_oid" 1

  refute_server_object "$reponame" "$contents_oid"

  git push origin main 2>&1 | tee push.log
  grep "Uploading LFS objects: 100% (1/1), 1 B" push.log
  grep "main -> main" push.log

  # change to the clone's working directory
  cd ../no-remote-clone

  # pull commits & lfs
  git pull origin main 2>&1
  assert_local_object "$contents_oid" 1

  # now checkout detached HEAD so we're not tracking anything on remote
  git checkout --detach

  # delete lfs
  rm -rf .git/lfs

  # rename remote from 'origin' to 'something'
  git remote rename origin something

  # fetch should still pick this remote as in the case of no tracked remote,
  # and no origin, but only 1 remote, should pick the only one as default
  git lfs fetch
  assert_local_object "$contents_oid" 1
)
end_test

begin_test "fetch --prune"
(
  set -e

  reponame="fetch_prune"
  setup_remote_repo "remote_$reponame"

  clone_repo "remote_$reponame" "clone_$reponame"

  git lfs track "*.dat" 2>&1 | tee track.log
  grep "Tracking \"\*.dat\"" track.log

  content_head="HEAD content"
  content_commit2="Content for commit 2 (prune)"
  content_commit1="Content for commit 1 (prune)"
  oid_head=$(calc_oid "$content_head")
  oid_commit2=$(calc_oid "$content_commit2")
  oid_commit1=$(calc_oid "$content_commit1")

  echo "[
  {
    \"CommitDate\":\"$(get_date -50d)\",
    \"Files\":[
      {\"Filename\":\"file.dat\",\"Size\":${#content_commit1}, \"Data\":\"$content_commit1\"}]
  },
  {
    \"CommitDate\":\"$(get_date -35d)\",
    \"Files\":[
      {\"Filename\":\"file.dat\",\"Size\":${#content_commit2}, \"Data\":\"$content_commit2\"}]
  },
  {
    \"CommitDate\":\"$(get_date -25d)\",
    \"Files\":[
      {\"Filename\":\"file.dat\",\"Size\":${#content_head}, \"Data\":\"$content_head\"}]
  }
  ]" | lfstest-testutils addcommits

  # push all so no unpushed reason to not prune
  git push origin main

  # set no recents so max ability to prune
  git config lfs.fetchrecentrefsdays 0
  git config lfs.fetchrecentcommitsdays 0

  # delete HEAD object to prove that we still download something
  # also prune at the same time which will remove anything other than HEAD
  delete_local_object "$oid_head"
  git lfs fetch --prune
  assert_local_object "$oid_head" "${#content_head}"
  refute_local_object "$oid_commit1"
  refute_local_object "$oid_commit2"
)
end_test

begin_test "fetch raw remote url"
(
  set -e
  mkdir raw
  cd raw
  git init
  git lfs install --local --skip-smudge

  git remote add origin "$GITSERVER/$reponame"
  git pull origin main

  # LFS object not downloaded, pointer in working directory
  refute_local_object "$contents_oid"
  grep "$content_oid" a.dat

  git lfs fetch "$GITSERVER/$reponame"

  # LFS object downloaded, pointer still in working directory
  assert_local_object "$contents_oid" 1
  grep "$content_oid" a.dat
)
end_test

begin_test "fetch with invalid remote"
(
  set -e
  cd repo
  git lfs fetch not-a-remote 2>&1 | tee fetch.log
  grep "Invalid remote name" fetch.log
)
end_test

begin_test "fetch fails when LFS directory has wrong permissions"
(
  set -e

  # Windows lacks POSIX permissions.
  [ "$IS_WINDOWS" -eq 1 ] && exit 0

  # Root is exempt from permissions.
  [ "$(id -u)" -eq 0 ] && exit 0

  cd shared
  rm -rf .git/lfs/objects
  mkdir .git/lfs/objects
  chmod 400 .git/lfs/objects

  git lfs fetch 2>&1 | tee fetch.log
  grep "error trying to create local storage directory" fetch.log
)
end_test


text:
namespace turbodbc {

field_parameter_set::field_parameter_set(bound_parameter_set & parameters) :
	parameters_(parameters),
	current_parameter_set_(0)
{
}

field_parameter_set::~field_parameter_set() = default;

void field_parameter_set::flush()
{
	// bound result set handles empty parameter sets
	parameters_.execute_batch(current_parameter_set_);
	current_parameter_set_ = 0;
}

void field_parameter_set::add_parameter_set(std::vector<nullable_field> const & parameter_set)
{
	check_parameter_set(parameter_set);

	if (current_parameter_set_ == parameters_.buffered_sets()) {
		flush();
	}

	for (unsigned int p = 0; p != parameter_set.size(); ++p) {
		add_parameter(p, parameter_set[p]);
	}

	++current_parameter_set_;
}

void field_parameter_set::check_parameter_set(std::vector<nullable_field> const & parameter_set) const
{
	auto const expected_size = parameters_.number_of_parameters();
	if (parameter_set.size() != expected_size) {
		std::ostringstream message;
		message << "Invalid number of parameters (expected " << expected_size
				<< ", got " << parameter_set.size() << ")";
		throw cpp_odbc::error(message.str());
	}
}

void field_parameter_set::add_parameter(std::size_t index, nullable_field const & value)
{
	if (value) {
		if (parameter_is_suitable_for(*(parameters_.get_parameters()[index]), *value)) {
			auto & parameter = *(parameters_.get_parameters()[index]);
			auto element = parameter.get_buffer()[current_parameter_set_];
			set_field(*value, element);
		} else {
			auto const last_active_set = current_parameter_set_;
			flush();
			recover_unwritten_parameters_below(index, last_active_set);
			rebind_parameter_to_hold_value(index, *value);
			auto & parameter = *(parameters_.get_parameters()[index]);
			auto element = parameter.get_buffer()[0];
			set_field(*value, element);
		}
	} else {
		auto & parameter = *(parameters_.get_parameters()[index]);
		auto element = parameter.get_buffer()[current_parameter_set_];
		set_null(element);
	}
}

void field_parameter_set::recover_unwritten_parameters_below(std::size_t parameter_index, std::size_t last_active_row)
{
	for (std::size_t i = 0; i != parameter_index; ++i) {
		auto & parameter = *(parameters_.get_parameters()[i]);
		move_to_top(parameter, last_active_row);
	}
}

void field_parameter_set::rebind_parameter_to_hold_value(std::size_t index, field const & value)
{
	auto description = make_description(value);
	parameters_.rebind(index, std::move(description));
}

}


text:
@interface QBNotFoundIdsSerialisation : QBJSONResponseSerialiser
@end


text:
"""
    seaside.manage
    ~~~~~~~~~~~~~~~~~

    Starts web app

    :three terminals are needed: 1 for redis-server, 1 for celery, and the last for web app

"""
import os
import sys
from app import create_app, db, make_celery
from app.models import User, Role, Post, Follow, Comment, Like, TagTree, Tag, Notify, UserNotify, Subscribe
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand

# Append parent dir to path
sys.path.append('..')

app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
celery = make_celery(app)

def make_shell_context():
    """
        this function works as: >>>from *** import app, db, User, Role
    """
    return dict(app=app, db=db, User=User, Role=Role, Post=Post, Follow=Follow, Comment=Comment,
                Like=Like, TagTree=TagTree, Tag=Tag, Notify=Notify, UserNotify=UserNotify, Subscribe=Subscribe)

manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)

COV = None
if os.environ.get('FLASK_COVERAGE'):
    import coverage
    COV = coverage.coverage(branch=True, include='app/*')
    COV.start()

@manager.command
def test(coverage=False):
    """Run the unit tests."""
    if coverage and not os.environ.get('FLASK_COVERAGE'):
        import sys
        os.environ['FLASK_COVERAGE'] = '1'
        os.execvp(sys.executable, [sys.executable] + sys.argv)
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
    if COV:
        COV.stop()
        COV.save()
        print('Coverage Summary:')
        COV.report()
        basedir = os.path.abspath(os.path.dirname(__file__))
        covdir = os.path.join(basedir, 'temp/coverage')
        COV.html_report(directory=covdir)
        print('HTML version: file://%s/index.html' % covdir)
        COV.erase()

@manager.command
def profile(length=25, profile_dir=None):
    """ start the application under the code profiler. """
    from werkzeug.contrib.profiler import ProfilerMiddleware
    app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length], profile_dir=profile_dir)
    app.run()

@manager.command
def deploy():
    """Run deployment tasks"""
    from flask.ext.migrate import upgrade
    from app.models import Role, User
    # migrate data base to newest edtion
    upgrade()
    # create user roles
    Role.insert_roles()
    User.add_self_follows()

if __name__ == '__main__':
    manager.run()


text:
from django.conf.urls.defaults import *
from django.conf import settings
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
                       #
                       (r'^facebook/', include('django_facebook.urls')),

                       #what to do with these?
                       (r'^accounts/', include('django_facebook.auth_urls')),

                       # Example:
                       # (r'^django_facebook_test/', include('django_facebook_test.foo.urls')),

                       # Uncomment the admin/doc line below to enable admin documentation:
                       # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

                       # Uncomment the next line to enable the admin:
                       # (r'^admin/', include(admin.site.urls)),
                       )

if settings.MODE == 'userena':
    urlpatterns += patterns('',
                            (r'^accounts/', include('userena.urls')),
                            )
elif settings.MODE == 'django_registration':
    urlpatterns += patterns('',
                            (r'^accounts/', include(
                                'registration.backends.default.urls')),
                            )

if settings.DEBUG:
    urlpatterns += patterns('',
                            url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
                                'document_root': settings.MEDIA_ROOT,
                                }),
                            )


text:
$(document).ready(function() {
  var sidebar = $("#documenter > .docs-sidebar");
  var sidebar_button = $("#documenter-sidebar-button")
  sidebar_button.click(function(ev) {
    ev.preventDefault();
    sidebar.toggleClass('visible');
    if (sidebar.hasClass('visible')) {
      // Makes sure that the current menu item is visible in the sidebar.
      $("#documenter .docs-menu a.is-active").focus();
    }
  });
  $("#documenter > .docs-main").bind('click', function(ev) {
    if ($(ev.target).is(sidebar_button)) {
      return;
    }
    if (sidebar.hasClass('visible')) {
      sidebar.removeClass('visible');
    }
  });
})

// Resizes the package name / sitename in the sidebar if it is too wide.
// Inspired by: https://github.com/davatron5000/FitText.js
$(document).ready(function() {
  e = $("#documenter .docs-autofit");
  function resize() {
    var L = parseInt(e.css('max-width'), 10);
    var L0 = e.width();
    if(L0 > L) {
      var h0 = parseInt(e.css('font-size'), 10);
      e.css('font-size', L * h0 / L0);
      // TODO: make sure it survives resizes?
    }
  }
  // call once and then register events
  resize();
  $(window).resize(resize);
  $(window).on('orientationchange', resize);
});

// Scroll the navigation bar to the currently selected menu item
$(document).ready(function() {
  var sidebar = $("#documenter .docs-menu").get(0);
  var active = $("#documenter .docs-menu .is-active").get(0);
  if(typeof active !== 'undefined') {
    sidebar.scrollTop = active.offsetTop - sidebar.offsetTop - 15;
  }
})


text:
import React from 'react';
import { render } from 'react-dom';
import { Router, browserHistory} from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { Provider } from 'react-redux';
// import injectTapEventPlugin from 'react-tap-event-plugin';
import { MuiThemeProvider } from 'material-ui';
import routes from './routes.js';
import './styles/normalize.css';
import './styles/app.less';
import store from './store/index.js';
const history = syncHistoryWithStore(browserHistory, store);

// injectTapEventPlugin();

const RouterTree = () => (
  <Provider store={store}>
    <MuiThemeProvider>
      <Router history={history} routes={routes}/>
    </MuiThemeProvider>
  </Provider>
);

render(
  <RouterTree />,
  document.querySelector('#root')
);


text:
require 'slack-notifier'

module Taperole
  module Notifiers
    class Slack
      def initialize(webhook_url, deploy_info)
        @notifier = ::Slack::Notifier.new webhook_url
        @notifier.username = 'Tape'
        @deploy_info = deploy_info
      end

      def update(status)
        @status = status
        @notifier.ping(
          "",
          # TODO: Fill in real icon url
          icon_url: 'https://image.freepik.com/free-icon/adhesive-tape_318-42276.png',
          attachments: attachments
        )
      end

      private

      def attachments
        a = {}
        a[:text] = message
        a[:color] = color
        a[:fields] = fields unless @status == :start
        [a]
      end

      def fields
        [
          {
            title: "Project",
            value: project_link,
            short: true
          },
          {
            title: "Hosts/Env",
            value: @deploy_info[:hosts],
            short: true
          },
          {
            title: "Author",
            value: @deploy_info[:user],
            short: true
          }
        ]
      end

      def color
        case @status
        when :start   then "#a9a9a9"
        when :success then "good"
        when :fail    then "danger"
        end
      end

      def gh_link_base
        @deploy_info[:repo].sub(/^git@github.com:/, 'http://github.com/').sub(/.git$/, '')
      end

      def project_link
        "<#{gh_link_base}|#{@deploy_info[:app_name]}>"
      end

      def message
        case @status
        when :start
          user  = @deploy_info[:user]
          app   = @deploy_info[:app_name]
          hosts = @deploy_info[:hosts]
          "#{user} started deploying #{app} to #{hosts}"
        when :success
          "The deploy was successful!"
        when :fail
          "The deploy failed!"
        end
      end
    end
  end
end


text:
SET DEFINE OFF;
ALTER TABLE AFW_12_GROUP_STAT ADD (
  CONSTRAINT AFW_12_GROUP_STAT_FK2
  FOREIGN KEY (REF_DOMN)
  REFERENCES AFW_12_DOMN (SEQNC)
  ON DELETE CASCADE
  ENABLE VALIDATE)
/


text:
from nose import *
import proxmox

def setup_func():
    """function level setup function"""

def teardown_func():
    """function level teardown function"""

@with_setup(setup_func)
def testAuth():
    PROXMOX_HOST = "proxmox-7"
    PROXMOX_PORT = 8006
    USER = "apiuser@pam"
    PASSWD = "strawberries"

    connection = proxmox.Connector(PROXMOX_HOST, PROXMOX_PORT)
    assert connection.fetch_auth_token(USER, PASSWD)


text:
package com.dataagg.util;

import org.junit.Before;

public class TextUtilTest {

	@Before
	public void setUp() throws Exception {
	}
}


text:
#include "tensorflow/core/kernels/data/experimental/sql/driver_manager.h"
#include "tensorflow/core/kernels/data/experimental/sql/sqlite_query_connection.h"

namespace tensorflow {
namespace data {
namespace experimental {
namespace sql {

std::unique_ptr<QueryConnection> DriverManager::CreateQueryConnection(
    const string& driver_name) {
  if (driver_name == "sqlite") {
    return std::unique_ptr<SqliteQueryConnection>(new SqliteQueryConnection());
  } else {  // TODO(b/64276826, b/64276995) Add support for other db types.
            // Change to registry pattern.
    return nullptr;
  }
}

}  // namespace sql
}  // namespace experimental
}  // namespace data
}  // namespace tensorflow


text:
template<ncs::sim::DeviceType::Type MType, InputType IType>
bool LinearSimulator<MType, IType>::
BatchStartsLater::operator()(const Batch* a, const Batch* b) const {
  return a->start_time > b->start_time;
}

template<ncs::sim::DeviceType::Type MType, InputType IType>
bool LinearSimulator<MType, IType>::
addInputs(const std::vector<ncs::sim::Input*>& inputs,
          void* instantiator,
          float start_time,
          float end_time) {
  Instantiator* i = (Instantiator*)instantiator;
  auto starting_amplitude_generator = i->starting_amplitude;
  auto ending_amplitude_generator = i->ending_amplitude;
  std::vector<float> starting_amplitudes;
  std::vector<float> slopes;
  std::vector<unsigned int> device_neuron_ids;
  float duration = end_time - start_time;
  float one_over_duration = 1.0f / duration;
  for (auto input : inputs) {
    device_neuron_ids.push_back(input->neuron_device_id);
    ncs::spec::RNG rng(input->seed);
    float starting_amplitude =
      starting_amplitude_generator->generateDouble(&rng);
    starting_amplitudes.push_back(starting_amplitude);
    float ending_amplitude =
      ending_amplitude_generator->generateDouble(&rng);
    float slope = (ending_amplitude - starting_amplitude) * one_over_duration;
    slopes.push_back(slope);
  }
  Batch* batch = new Batch();
  batch->count = starting_amplitudes.size();
  batch->start_time = start_time;
  batch->end_time = end_time;
  bool result = true;
  result &= ncs::sim::mem::clone<MType>(batch->starting_amplitude,
                                        starting_amplitudes);
  result &= ncs::sim::mem::clone<MType>(batch->slope,
                                        slopes);
  result &= ncs::sim::mem::clone<MType>(batch->device_neuron_id,
                                        device_neuron_ids);
  if (!result) {
    delete batch;
    std::cerr << "Failed to allocate memory for input." << std::endl;
    return false;
  }
  future_batches_.push(batch);
  return true;
}

template<ncs::sim::DeviceType::Type MType, InputType IType>
bool LinearSimulator<MType, IType>::
initialize(const ncs::spec::SimulationParameters* simulation_parameters) {
  return true;
}

template<ncs::sim::DeviceType::Type MType, InputType IType>
bool LinearSimulator<MType, IType>::
update(ncs::sim::InputUpdateParameters* parameters) {
  const auto simulation_time = parameters->simulation_time;
  auto BatchIsDone = [simulation_time](Batch* b) {
    return b->end_time < simulation_time;
  };
  for (auto batch : active_batches_) {
    if (BatchIsDone(batch)) {
      delete batch;
    }
  }
  active_batches_.remove_if(BatchIsDone);

  while (!future_batches_.empty() &&
         future_batches_.top()->start_time <= simulation_time) {
    Batch* batch = future_batches_.top();
    future_batches_.pop();
    active_batches_.push_back(batch);
  }

  return update_(parameters);
}

template<ncs::sim::DeviceType::Type MType, InputType IType>
LinearSimulator<MType, IType>::Batch::~Batch() {
  if (starting_amplitude) {
    ncs::sim::Memory<MType>::free(starting_amplitude);
  }
  if (slope) {
    ncs::sim::Memory<MType>::free(slope);
  }
  if (device_neuron_id) {
    ncs::sim::Memory<MType>::free(device_neuron_id);
  }
}


text:
package org.wso2.carbon.siddhi.editor.core.util;

import org.wso2.carbon.siddhi.editor.core.commons.metadata.MetaData;

/**
 * Used for holding the meta data of the processors available in the siddhi engine.
 */
public class MetaDataHolder {

    private static MetaData inBuiltProcessorMetaData = SourceEditorUtils.getInBuiltProcessorMetaData();

    private MetaDataHolder() {

    }

    /**
     * Returns the in built processor meta data.
     *
     * @return In-built processor meta data
     */
    public static MetaData getInBuiltProcessorMetaData() {

        return inBuiltProcessorMetaData;
    }
}


text:
<? require_once('FCD-helpers.php'); ?>

<? if (userIsLoggedIn()) { ?>
logout
<? } else { ?>
login
<? } ?>

Sponsored by Coquina Press and
NESCent.
 •
All data is released under a
CC0 waiver. To the
extent possible under law, the authors have waived all copyright and related or
neighboring rights to the data in the Fossil Calibrations database.
 •
Full source code for this
website (© 2013-2014, National Evolutionary Synthesis Center) is available
under the BSD
(2-clause) license.


text:
layout: default
description: This chapter describes the REST interface for the multi-collection graph module
---
General Graphs
==============

This chapter describes the REST interface for the [multi-collection graph module](../graphs.html).
It allows you to define a graph that is spread across several edge and document collections.
There is no need to include the referenced collections within the query, this module will handle it for you.


text:
require 'test_helper'

module Tilia
  module Dav
    module Locks
      module Backend
        class FileTest < Minitest::Test
          include AbstractTest

          def backend
            @temp_dir = Dir.mktmpdir

            backend = File.new("#{@temp_dir}/lockdb")
            backend
          end

          def teardown
            FileUtils.remove_entry @temp_dir
          end
        end
      end
    end
  end
end


text:
package com.pCloudy.testNg;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.io.FileHandler;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.*;

public class Runner {

	WebDriver driver;
	DesiredCapabilities capabilities ;
	String folder_name;
	DateFormat df;

	@BeforeTest
	public void setUpSuite() throws Exception {

	}

	@Parameters({"os","osVersion","browserName","browserVersions"})
	@BeforeMethod
	public void prepareTest(String os,String osVersion,String browserName,String browserVersions) throws IOException, InterruptedException {

		if (browserName.contains("chrome")) {
			capabilities =  DesiredCapabilities.chrome();
		} else if (browserName.contains("ie")) {
			capabilities =  DesiredCapabilities.internetExplorer();
		} else if (browserName.contains("firefox")) {
			capabilities =  DesiredCapabilities.firefox();
		} else if (browserName.contains("edge")) {
			capabilities =  DesiredCapabilities.edge();
		}

		capabilities.setCapability("os", os);
		capabilities.setCapability("osVersion", osVersion);
		capabilities.setCapability("browserVersion",browserVersions);
		capabilities.setCapability("clientName", "Your Email adress");
		capabilities.setCapability("apiKey", "Your api key");
		capabilities.setCapability("email", "Your Email adress");
		driver = new RemoteWebDriver(new URL("https://prod-browsercloud-in.pcloudy.com/seleniumcloud/wd/hub"), capabilities);
	}

	@Test
	public void Test() throws Exception {

		WebDriverWait wait=new WebDriverWait(driver, 20);
		driver.manage().window().maximize();
		driver.get("http://sstsinc.com/");

		WebElement contacts = wait.until(ExpectedConditions.visibilityOfElementLocated(
				By.xpath("//div[@class='navbar-collapse collapse floated']//a[contains(text(),'Contacts')]")));
		contacts.click();
		captureScreenShots();

		WebElement careers = wait.until(ExpectedConditions.visibilityOfElementLocated(
				By.xpath("//a[contains(text(),'Careers')]")));
		careers.click();
		captureScreenShots();

		WebElement yourName = wait.until(ExpectedConditions.visibilityOfElementLocated(
				By.xpath("//input[@id='name2']")));
		yourName.sendKeys("pCloudy");
		captureScreenShots();

		WebElement phone = wait.until(ExpectedConditions.visibilityOfElementLocated(
				By.xpath("//input[@id='Phone']")));
		phone.sendKeys("1234567");
		captureScreenShots();

		WebElement email = wait.until(ExpectedConditions.visibilityOfElementLocated(
				By.xpath("//input[@id='email2']")));
		email.sendKeys("pCloudy@sstsinc.com");
		captureScreenShots();

	}

	@AfterMethod
	public void afterMethod() throws InterruptedException{

		driver.quit();

	}

	public void captureScreenShots() throws Exception{

		folder_name="screenshot";
		TakesScreenshot scrShot =((TakesScreenshot)driver);
		File f=scrShot.getScreenshotAs(OutputType.FILE);
		df=new  SimpleDateFormat("dd-MMM-yyyy__hh_mm_ssaa");
		//create dir with given folder name
		new File(folder_name).mkdir();
		//Setting file name
		String file_name=df.format(new Date())+".png";
		//copy screenshot file into screenshot folder.
		FileHandler.copy(f, new File(folder_name + "/" + file_name));

	}
}


text:
<!DOCTYPE html>

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

    <meta name="description" content=""/>
    <meta name="author" content=""/>

    <title>Spring Boot Web Application</title>

    <link th:href="@{/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css}" rel="stylesheet"/>

    <link th:href="@{/static/stylesheets/application.css}" rel="stylesheet"/>

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

                    </button>
                    TODO board

Home

Help

Login

Dash

Projects

Tasks

Users

                            Welcome, Guest

                            <form th:action="@{/logout}" method="post" style="margin: 8px 0px;">
                                <button class="btn btn-danger" type="submit">Sign Out</button>
                            </form>

Sticky footer with fixed navbar

Pin a fixed-height footer to the bottom of the viewport in desktop browsers with this custom HTML and CSS. A fixed navbar has been added with padding-top: 60px; on the body > .container.

Back to the default sticky footer minus the navbar.

© Spring boot todo, 2017


text:
package cmpp

import "encoding/binary"

// Packet length const for cmpp terminate request and response packets.
const (
	CmppTerminateReqPktLen uint32 = 12 //12d, 0xc
	CmppTerminateRspPktLen uint32 = 12 //12d, 0xc
)

type CmppTerminateReqPkt struct {
	// session info
	SeqId uint32
}
type CmppTerminateRspPkt struct {
	// session info
	SeqId uint32
}

// Pack packs the CmppTerminateReqPkt to bytes stream for client side.
func (p *CmppTerminateReqPkt) Pack(seqId uint32) ([]byte, error) {
	var pktLen = CmppTerminateReqPktLen

	var w = newPacketWriter(pktLen)

	// Pack header
	w.WriteInt(binary.BigEndian, pktLen)
	w.WriteInt(binary.BigEndian, CMPP_TERMINATE)
	w.WriteInt(binary.BigEndian, seqId)
	p.SeqId = seqId

	return w.Bytes()
}

// Unpack unpack the binary byte stream to a CmppTerminateReqPkt variable.
// After unpack, you will get all value of fields in
// CmppTerminateReqPkt struct.
func (p *CmppTerminateReqPkt) Unpack(data []byte) error {
	var r = newPacketReader(data)

	// Sequence Id
	r.ReadInt(binary.BigEndian, &p.SeqId)
	return r.Error()
}

// Pack packs the CmppTerminateRspPkt to bytes stream for client side.
func (p *CmppTerminateRspPkt) Pack(seqId uint32) ([]byte, error) {
	var pktLen = CmppTerminateRspPktLen

	var w = newPacketWriter(pktLen)

	// Pack header
	w.WriteInt(binary.BigEndian, pktLen)
	w.WriteInt(binary.BigEndian, CMPP_TERMINATE_RESP)
	w.WriteInt(binary.BigEndian, seqId)
	p.SeqId = seqId

	return w.Bytes()
}

// Unpack unpack the binary byte stream to a CmppTerminateRspPkt variable.
// After unpack, you will get all value of fields in
// CmppTerminateRspPkt struct.
func (p *CmppTerminateRspPkt) Unpack(data []byte) error {
	var r = newPacketReader(data)

	// Sequence Id
	r.ReadInt(binary.BigEndian, &p.SeqId)
	return r.Error()
}


text:
function res = length(this);

    tmp = struct(this);
    %if any(cellfun(@length, { tmp.EEG }) > 1)
    %    error('EEG structure in object with more than 1 element')
    %end;
    try
        res = length(tmp.EEG);
    catch
        res = length(tmp);
        return;
    end;
    if res > 1, error('EEG structure in object with more than 1 element'); end;
    res = length(tmp);