text:
package net.sourceforge.easyml;

import net.sourceforge.easyml.marshalling.java.io.SerializableStrategy;
import net.sourceforge.easyml.marshalling.java.lang.CharsStrategy;
import net.sourceforge.easyml.marshalling.java.util.*;
import org.junit.After;
import org.junit.Test;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

import static org.junit.Assert.*;

/**
 * @author Victor Cordis ( cordis.victor at gmail.com)
 */
public class ArraysCollectionsTest {

    private final ByteArrayOutputStream out = new ByteArrayOutputStream(256);

    @After
    public void tearDown() {
        this.out.reset();
    }

    @Test
    public void testEnumMapStrategy() {
        final EnumMap expected = new EnumMap(EasyML.Style.class);
        expected.put(EasyML.Style.PRETTY, 1);
        expected.put(EasyML.Style.DETAILED, 2);

        final XMLWriter xos = new XMLWriter(this.out);
        xos.alias(EasyML.Style.class, "emlStype");
        xos.getCompositeStrategies().add(EnumMapStrategy.INSTANCE);
        xos.write(expected);
        xos.close();

        System.out.println(this.out);

        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        xis.alias(EasyML.Style.class, "emlStype");
        xis.getCompositeStrategies().put(EnumMapStrategy.INSTANCE.name(), EnumMapStrategy.INSTANCE);
        assertEquals(expected, xis.read());
        xis.close();
    }

    @Test
    public void testEnumSetStrategy() {
        final EnumSet expected = EnumSet.allOf(EasyML.Style.class);

        final XMLWriter xos = new XMLWriter(this.out);
        xos.alias(EasyML.Style.class, "emlStype");
        xos.getCompositeStrategies().add(EnumSetStrategy.INSTANCE);
        xos.write(expected);
        xos.close();

        System.out.println(this.out);

        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        xis.alias(EasyML.Style.class, "emlStype");
        xis.getCompositeStrategies().put(EnumSetStrategy.INSTANCE.name(), EnumSetStrategy.INSTANCE);
        assertEquals(expected, xis.read());
        xis.close();
    }

    @Test
    public void testBitSetStrategy() {
        final BitSet expected = new BitSet();
        expected.set(1);
        expected.set(3);
        expected.set(64);

        final XMLWriter xos = new XMLWriter(this.out);
        xos.getCompositeStrategies().add(BitSetStrategy.INSTANCE);
        xos.write(expected);
        xos.close();

        System.out.println(this.out);

        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        xis.getCompositeStrategies().put(BitSetStrategy.INSTANCE.name(), BitSetStrategy.INSTANCE);
        assertEquals(expected, xis.read());
        xis.close();
    }

    @Test
    public void testGenericStringStringArray() {
        final String[][] expected = new String[][]{{"unu", "doi"}, {"eee", "nuu"}};

        final XMLWriter xos = new XMLWriter(this.out);
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        final String[][] actual = (String[][]) xis.readArray(String[].class);
        xis.close();

        assertArrayEquals(expected[0], actual[0]);
        assertArrayEquals(expected[1], actual[1]);
    }

    @Test
    public void testSingletonSet() {
        final Set<String> expected = Collections.singleton("single");
        final XMLWriter xos = new XMLWriter(this.out);
        xos.getCompositeStrategies().add(SingletonSetStrategy.INSTANCE);
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        xis.getCompositeStrategies().put(SingletonSetStrategy.INSTANCE.name(), SingletonSetStrategy.INSTANCE);
        assertEquals(expected, xis.read());
        xis.close();
    }

    @Test
    public void testSingletonList() {
        final List<String> expected = Collections.singletonList("single");
        final XMLWriter xos = new XMLWriter(this.out);
        xos.getCompositeStrategies().add(SingletonListStrategy.INSTANCE);
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        xis.getCompositeStrategies().put(SingletonListStrategy.INSTANCE.name(), SingletonListStrategy.INSTANCE);
        assertEquals(expected, xis.read());
        xis.close();
    }

    @Test
    public void testSingletonMap() {
        final Map<Integer, String> expected = Collections.singletonMap(1, "one");
        final XMLWriter xos = new XMLWriter(this.out);
        xos.getCompositeStrategies().add(SingletonMapStrategy.INSTANCE);
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        xis.getCompositeStrategies().put(SingletonMapStrategy.INSTANCE.name(), SingletonMapStrategy.INSTANCE);
        assertEquals(expected, xis.read());
        xis.close();
    }

    @Test
    public void testStack() {
        final Stack<String> expected = new Stack();
        expected.push("call1");
        expected.push("call2");
        expected.push("call3");
        final XMLWriter xos = new XMLWriter(this.out);
        xos.getCompositeStrategies().add(new SerializableStrategy());
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        xis.getCompositeStrategies().put(SerializableStrategy.NAME, new SerializableStrategy());
        assertEquals(expected, xis.read());
        xis.close();
    }

    @Test
    public void testCharArray() {
        final char[] expected = new char[]{'a', '&', 'c'};
        final XMLWriter xos = new XMLWriter(this.out);
        xos.getSimpleStrategies().add(CharsStrategy.INSTANCE);
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        xis.getSimpleStrategies().put(CharsStrategy.INSTANCE.name(), CharsStrategy.INSTANCE);
        assertArrayEquals(expected, (char[]) xis.read());
        xis.close();
    }

    @Test
    public void testArrayListArray() throws Exception {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document dom = dBuilder.newDocument();

        final List l0 = new ArrayList(20);
        l0.add(1);
        l0.add(2);
        final List l1 = new LinkedList();
        l1.add("one");
        l1.add("two");
        final List[] lists = new List[]{l0, l1};
        final XMLWriter xos = new XMLWriter(dom);
        EasyML.defaultConfiguration(xos);
        xos.write(lists);
        xos.close();
        System.out.println(dom);
        final XMLReader xis = new XMLReader(dom);
        EasyML.defaultConfiguration(xis);
        assertArrayEquals(lists, (Object[]) xis.read());
        xis.close();
    }

    @Test
    public void testListListArray() throws Exception {
        final List expected = new ArrayList();
        expected.add(1);
        List l2 = new LinkedList();
        l2.add(2);
        l2.add(3);
        l2.add(4);
        expected.add(l2);

        final XMLWriter xos = new XMLWriter(this.out);
        EasyML.defaultConfiguration(xos);
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        EasyML.defaultConfiguration(xis);
        assertEquals(expected, xis.read());
        xis.close();
    }

    @Test(expected = IllegalClassException.class)
    public void testListListArrayInject1() throws Exception {
        final List expected = new ArrayList();
        expected.add(1);
        List l2 = new LinkedList();
        l2.add(2);
        l2.add(3);
        l2.add(4);
        expected.add(l2);

        final XMLWriter xos = new XMLWriter(this.out);
        EasyML.defaultConfiguration(xos);
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        EasyML.defaultConfiguration(xis);
        xis.getSecurityPolicy().add(Integer.class);
        xis.read();
    }

    @Test
    public void testLinkedListCollection() {
        final Collection expected = new ArrayList(20);
        final List l = new LinkedList();
        l.add("one");
        l.add("two");
        expected.add(l);
        final XMLWriter xos = new XMLWriter(this.out);
        EasyML.defaultConfiguration(xos);
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        EasyML.defaultConfiguration(xis);
        assertEquals(expected, xis.read());
        xis.close();
    }

    @Test
    public void testTreeSet() {
        final Set<Integer> expected = new TreeSet<>(new IntegerComparator());
        expected.add(1);
        expected.add(2);

        final XMLWriter xos = new XMLWriter(this.out);
        EasyML.defaultConfiguration(xos);
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        EasyML.defaultConfiguration(xis);
        assertEquals(expected, xis.read());
        xis.close();
    }

    private static final class IntegerComparator implements Comparator<Integer> {
        @Override
        public int compare(Integer i1, Integer i2) {
            return i1 - i2;
        }

        @Override
        public int hashCode() {
            return 1;
        }

        @Override
        public boolean equals(Object o) {
            return this.getClass() == o.getClass();
        }
    }

    @Test
    public void testMap() {
        final Map expected = new HashMap();
        expected.put(1, "unu");
        expected.put(2, "doi");
        final XMLWriter xos = new XMLWriter(this.out);
        EasyML.defaultConfiguration(xos);
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        EasyML.defaultConfiguration(xis);
        assertEquals(expected, xis.read());
        xis.close();
    }

    @Test
    public void testConcurrentMap() {
        final Map expected = new ConcurrentHashMap(2);
        expected.put(1, "unu");
        expected.put(2, "doi");
        final XMLWriter xos = new XMLWriter(this.out);
        EasyML.defaultConfiguration(xos);
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        EasyML.defaultConfiguration(xis);
        assertEquals(expected, xis.read());
        xis.close();
    }

    @Test
    public void testIdentityHashMapMap() {
        final Map expected = new IdentityHashMap();
        final Map m = new HashMap();
        m.put(1, "unu");
        m.put(2, "doi");
        expected.put(m, m);
        final XMLWriter xos = new XMLWriter(this.out);
        EasyML.defaultConfiguration(xos);
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        EasyML.defaultConfiguration(xis);
        assertEquals(expected.values().iterator().next(), ((Map) xis.read()).values().iterator().next());
        xis.close();
    }

    @Test
    public void testCollectionsEmptyMap() {
        final Map expected = Collections.EMPTY_MAP;
        final XMLWriter xos = new XMLWriter(this.out);
        EasyML.defaultConfiguration(xos);
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        EasyML.defaultConfiguration(xis);
        assertTrue(expected == xis.read());
        xis.close();
    }

    @Test
    public void testCollectionsSingletonMap() {
        final Map expected = Collections.singletonMap(3, "trei");
        final XMLWriter xos = new XMLWriter(this.out);
        EasyML.defaultConfiguration(xos);
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        EasyML.defaultConfiguration(xis);
        assertEquals(expected.toString(), xis.read().toString());
        xis.close();
    }

    @Test(expected = IllegalClassException.class)
    public void testCollectionsSingletonMapInjection1() {
        final Map expected = Collections.singletonMap(3, "trei");
        final XMLWriter xos = new XMLWriter(this.out);
        EasyML.defaultConfiguration(xos);
        xos.write(expected);
        xos.close();
        System.out.println(this.out);
        final XMLReader xis = new XMLReader(new ByteArrayInputStream(this.out.toByteArray()));
        EasyML.defaultConfiguration(xis);
        xis.getSecurityPolicy().addHierarchy(Map.class);
        xis.read();
    }
}


text:
using System;
//
//Module : AASIDEREAL.CPP
//Purpose: Implementation for the algorithms which obtain sidereal time
//Created: PJN / 29-12-2003
//         PJN / 26-01-2007 1. Update to fit in with new layout of CAADate class
//         PJN / 28-01-2007 1. Minor updates to fit in with new layout of CAADate class
//
//Copyright (c) 2003 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com)
//
//All rights reserved.
//
//Copyright / Usage Details:
//
//You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise)
//when your product is released in binary form. You are allowed to modify the source code in any way you want
//except you cannot modify the copyright details at the top of each module. If you want to distribute source
//code with your application, then you are only allowed to distribute versions released by the author. This is
//to maintain a single distribution point for the source code.
//
//

/////////////////////////////// Includes //////////////////////////////////////

/////////////////////// Classes ///////////////////////////////////////////////

public class  CAASidereal
{
//Static methods

	/////////////////////////////// Implementation ////////////////////////////////

	public static double MeanGreenwichSiderealTime(double JD)
	{
	  //Get the Julian day for the same day at midnight

	  DT date = new DT();
	  date.SetJD(JD, DT.AfterPapalReformJD(JD));
	  double[] D = date.Get();

	  int Year = (int)D[0];
      int Month = (int)D[1];
      int Day = (int)D[2];
      int Hour = (int)D[3];
      int Minute = (int)D[4];
      double Second = D[5];

	  date.Set(Year, Month, Day, 0, 0, 0, date.InGregorianCalendar());
	  double JDMidnight = date.Julian();

	  //Calculate the sidereal time at midnight
	  double T = (JDMidnight - 2451545) / 36525;
	  double TSquared = T *T;
	  double TCubed = TSquared *T;
	  double Value = 100.46061837 + (36000.770053608 *T) + (0.000387933 *TSquared) - (TCubed/38710000);

	  //Adjust by the time of day
	  Value += (((Hour * 15) + (Minute * 0.25) + (Second * 0.0041666666666666666666666666666667)) * 1.00273790935);

	  Value = CT.D2H(Value);

	  return CT.M24(Value);
	}

  public static double ApparentGreenwichSiderealTime(double JD)
  {
	double MeanObliquity = CAANutation.MeanObliquityOfEcliptic(JD);
	double TrueObliquity = MeanObliquity + CAANutation.NutationInObliquity(JD) / 3600;
	double NutationInLongitude = CAANutation.NutationInLongitude(JD);

	double Value = MeanGreenwichSiderealTime(JD) + (NutationInLongitude * Math.Cos(CT.D2R(TrueObliquity)) / 54000);
	return CT.M24(Value);
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/geo-political/north-america-and-caribbean/united-states-of-america/utah/american-fork-utah-utah-usa" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/geo-political/north-america-and-caribbean/united-states-of-america/utah/american-fork-utah-utah-usa</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">American Fork (Utah, Utah, USA)</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/geo-political/north-america-and-caribbean/united-states-of-america/utah/american-fork-utah-utah-usa</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/geo-political/north-america-and-caribbean/united-states-of-america/utah/american-fork-utah-utah-usa</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.schema.org/Place</sem:object>
  </sem:triple>
</sem:triples>


text:
@implementation TemplateNormalSubModel

+ (NSDictionary *)mj_objectClassInArray
{
    return @{
             @"picList" : @"TemplatePicModel"
             };
}

- (NSString *)floorIdentifier
{
    return @"TemplateNormalCell";
}

- (BOOL)isValid
{
    if (self.pattern.integerValue == TemplateNormalStyle001 && self.picList.count >= 1) {
        return YES;
    }
    else if (self.pattern.integerValue == TemplateNormalStyle002 && self.picList.count >= 1) {
        return YES;
    }
    else if (self.pattern.integerValue == TemplateNormalStyle003 && self.picList.count >= 2) {
        return YES;
    }
    else if (self.pattern.integerValue == TemplateNormalStyle004 && self.picList.count >= 2) {
        return YES;
    }
    else if (self.pattern.integerValue == TemplateNormalStyle005 && self.picList.count >= 3) {
        return YES;
    }
    else if (self.pattern.integerValue == TemplateNormalStyle006 && self.picList.count >= 3) {
        return YES;
    }
    else if (self.pattern.integerValue == TemplateNormalStyle007 && self.picList.count >= 3) {
        return YES;
    }
    else if (self.pattern.integerValue == TemplateNormalStyle008 && self.picList.count >= 4) {
        return YES;
    }
    else if (self.pattern.integerValue == TemplateNormalStyle009 && self.picList.count >= 4) {
        return YES;
    }
    else {
        return NO;
    }
}

- (TemplateAction *)jumpFloorModelAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger position = [indexPath indexAtPosition:0];
    if (position < self.picList.count) {
        TemplatePicModel *picModel = self.picList[position];
        TemplateJumpAction *action = [[TemplateJumpAction alloc] init];
        action.jumpToType = TemplateJumpToActivityM;
        action.jumpToUrl = picModel.jump.url;
        action.eventId = @"GeneralChannel_BannerPic";
        return action;
    }
    return nil;
}
@end


text:
using FluentAssertions;
using Xunit;

namespace Meziantou.Framework.CodeDom.Tests;

public class TypeReferenceTests
{
    [Theory]
    [InlineData(typeof(int), "System.Int32")]
    [InlineData(typeof(int[]), "System.Int32[]")]
    [InlineData(typeof(int[,]), "System.Int32[,]")]
    [InlineData(typeof(IList<int[,]>), "System.Collections.Generic.IList<System.Int32[,]>")]
    [InlineData(typeof(int?), "System.Nullable<System.Int32>")]
    [InlineData(typeof(Uri), "System.Uri")]
    [InlineData(typeof(TestNested), "Meziantou.Framework.CodeDom.Tests.TypeReferenceTests+TestNested")]
    [InlineData(typeof(TestNested.TestNested2), "Meziantou.Framework.CodeDom.Tests.TypeReferenceTests+TestNested+TestNested2")]
    public void TypeReference_FromType(Type type, string expectedClrFullTypeName)
    {
        var typeReference = new TypeReference(type);

        // Assert
        typeReference.ClrFullTypeName.Should().Be(expectedClrFullTypeName);

        if (type.IsArray)
        {
            typeReference.ArrayRank.Should().Be(type.GetArrayRank());
        }
        else
        {
            typeReference.ArrayRank.Should().Be(0);
        }
    }

    [Fact]
    public void TypeReference_FromGenericType()
    {
        // Act
        var typeReference = new TypeReference(typeof(Nullable<>)).MakeGeneric(typeof(int));

        // Assert
        typeReference.ClrFullTypeName.Should().Be("System.Nullable<System.Int32>");
        typeReference.Parameters.Select(p => p.ClrFullTypeName).ToList().Should().BeEquivalentTo(new[] { typeof(int).FullName });
    }

    private sealed class TestNested
    {
        public sealed class TestNested2
        {
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="text_grey_color">#ff818181</color>
    <color name="transparent">#0000</color>
</resources>


text:
import notifications from "../../../utilities/notifications";
import log from "../../../utilities/logging/log";
import date from "../../../utilities/date";
import fp from "lodash/fp";

/**
 * Methods for mapping between request responses and the application's state
 */

export default class collectionMapper {
    static mapTeams(collection, allGroups) {
        if (collection.teamsDetails) {
            return collection.teamsDetails.map(team => ({
                id: team.id.toString(),
                name: team.name,
            }));
        } else {
            if (allGroups) {
                const groups = fp.get("teams", collection);
                return fp.filter(g => {
                    return fp.includes(g.id)(groups);
                })(allGroups);
            }
            return [];
        }
    }

    static collectionResponseToState(collection, allGroups = []) {
        try {
            const publishStates = this.publishState(collection);
            return {
                id: collection.id,
                name: collection.name,
                publishDate: collection.publishDate,
                approvalStatus: collection.approvalStatus,
                status: {
                    neutral: publishStates.inProgress,
                    warning: publishStates.thrownError,
                    success: publishStates.completed,
                    message: publishStates.message,
                },
                type: collection.type,
                isForcedManualType: this.isForcedManualType(collection), // the collection has been made 'manual' programatically because 'scheduled' wasn't possible
                release: collection.releaseUri,
                selectableBox: {
                    firstColumn: collection.name,
                    secondColumn: this.publishDate(collection),
                },
                canBeApproved: false,
                canBeDeleted: false,
                inProgress: collection.inProgress,
                complete: collection.complete,
                reviewed: collection.reviewed,
                datasets: collection.datasets,
                interactives: collection.interactives,
                datasetVersions: collection.datasetVersions,
                teams: collectionMapper.mapTeams(collection, allGroups),
                deletes: collection.pendingDeletes,
            };
        } catch (error) {
            const notification = {
                type: "warning",
                message: "Error whilst mapping list of collections to screen",
                isDismissable: true,
                autoDismiss: 3000,
            };
            notifications.add(notification);
            console.error("Error mapping collections to component state: ", error);
            log.event("Error mapping collections to component state", log.error(error));
            return false;
        }
    }

    static pagesToCollectionState(collection) {
        try {
            const canBeApproved = this.collectionCanBeApproved(collection);
            const canBeDeleted = this.collectionCanBeDeleted(collection);
            const mapPageToState = pagesArray => {
                if (!pagesArray) {
                    log.event("Collections pages array (e.g. inProgress) wasn't set, had to hardcode a default value of null", log.warn());
                    return null;
                }
                return pagesArray.map(page => {
                    let lastEdited = null;
                    if (page.events && page.events.length > 0) {
                        lastEdited = page.events.filter(e => e.type === "EDITED").pop();

                        if (!lastEdited) {
                            lastEdited = page.events.pop();
                        } // fallback to newest date if not edited
                    }
                    let updatedPage = {};
                    try {
                        updatedPage = {
                            lastEdit: {
                                email: lastEdited ? lastEdited.email : "",
                                date: lastEdited ? lastEdited.date : "",
                            },
                            title: page.description.title,
                            edition: page.description.edition || "",
                            uri: page.uri,
                            type: page.type,
                        };
                    } catch (error) {
                        log.event("Error mapping a page to Florence's state", log.error(error));
                        console.error("Error mapping a page to Florence's state", error);
                    }
                    return updatedPage;
                });
            };
            const collectionWithPages = {
                ...collection,
                canBeApproved,
                canBeDeleted,
                inProgress: mapPageToState(collection.inProgress),
                complete: mapPageToState(collection.complete),
                reviewed: mapPageToState(collection.reviewed),
            };
            const collectionWithDatasetsAndPages = this.datasetsToCollectionState(collectionWithPages);
            const collectionWithInteractivesAndDatasetsAndPages = this.interactivesToCollectionState(collectionWithDatasetsAndPages);
            return {
                ...collectionWithInteractivesAndDatasetsAndPages,
                canBeDeleted: this.collectionCanBeDeleted(collectionWithInteractivesAndDatasetsAndPages),
                canBeApproved: this.collectionCanBeApproved(collectionWithInteractivesAndDatasetsAndPages),
            };
        } catch (error) {
            log.event("Error mapping collection GET response to Florence's state", log.error(error));
            console.error("Error mapping collection GET response to Florence's state", error);
            return null;
        }
    }

    static datasetsToCollectionState(collection) {
        try {
            const mapVersion = version => ({
                title: version.title,
                edition: version.edition,
                version: version.version,
                datasetID: version.id,
                id: `${version.id}/editions/${version.edition}/versions/${version.version}`,
                type: "dataset_version",
                uri: `/datasets/${version.id}/editions/${version.edition}/versions/${version.version}`,
                lastEditedBy: version.lastEditedBy,
            });

            const mapDataset = dataset => ({
                title: dataset.title,
                type: "dataset_details",
                id: dataset.id,
                uri: `/datasets/${dataset.id}`,
                lastEditedBy: dataset.lastEditedBy,
            });

            const mapDatasets = () => {
                let inProgress = collection.inProgress || [];
                let complete = collection.complete || [];
                let reviewed = collection.reviewed || [];

                if (collection.datasetVersions) {
                    collection.datasetVersions.forEach(version => {
                        if (version.state === "InProgress") {
                            inProgress.push(mapVersion(version));
                        }
                        if (version.state === "Complete") {
                            complete.push(mapVersion(version));
                        }
                        if (version.state === "Reviewed") {
                            reviewed.push(mapVersion(version));
                        }
                    });
                }

                if (collection.datasets) {
                    collection.datasets.forEach(dataset => {
                        if (dataset.state === "InProgress") {
                            inProgress.push(mapDataset(dataset));
                        }
                        if (dataset.state === "Complete") {
                            complete.push(mapDataset(dataset));
                        }
                        if (dataset.state === "Reviewed") {
                            reviewed.push(mapDataset(dataset));
                        }
                    });
                }

                return { inProgress, complete, reviewed };
            };

            return { ...collection, ...mapDatasets() };
        } catch (error) {
            log.event("Error mapping collection datasets response to Florence's state", log.error(error));
            console.error("Error mapping collection datasets response to Florence's state", error);
            return null;
        }
    }

    static interactivesToCollectionState(collection) {
        try {
            const mapInteractive = interactive => ({
                title: interactive.title,
                type: "interactive",
                id: interactive.id,
                uri: `/interactive/${interactive.id}`,
                lastEditedBy: interactive.lastEditedBy,
                lastEditedAt: interactive.lastEditedAt,
            });

            const mapInteractives = () => {
                let inProgress = collection.inProgress || [];
                let complete = collection.complete || [];
                let reviewed = collection.reviewed || [];

                if (collection.interactives) {
                    collection.interactives.forEach(interactive => {
                        if (interactive.state === "InProgress") {
                            inProgress.push(mapInteractive(interactive));
                        }
                        if (interactive.state === "Complete") {
                            complete.push(mapInteractive(interactive));
                        }
                        if (interactive.state === "Reviewed") {
                            reviewed.push(mapInteractive(interactive));
                        }
                    });
                }

                return { inProgress, complete, reviewed };
            };

            return { ...collection, ...mapInteractives() };
        } catch (error) {
            log.event("Error mapping collection interactives response to Florence's state", log.error(error));
            console.error("Error mapping collection interactives response to Florence's state", error);
            return null;
        }
    }

    static isForcedManualType(collection) {
        if (collection.publishDate && collection.type === "manual") {
            return true;
        }
        return false;
    }

    static publishState(collection) {
        const publishStates = {
            inProgress: false,
            thrownError: false,
            completed: false,
            notStarted: false,
            message: "",
        };
        try {
            switch (collection.approvalStatus) {
                case undefined: {
                    break;
                }
                case "NOT_STARTED": {
                    publishStates.notStarted = true;
                    break;
                }
                case "IN_PROGRESS": {
                    publishStates.inProgress = true;
                    publishStates.message = "preparing publish";
                    break;
                }
                case "COMPLETE": {
                    publishStates.completed = true;
                    break;
                }
                case "ERROR": {
                    publishStates.thrownError = true;
                    publishStates.message = "error whilst preparing publish";
                    break;
                }
            }
            return publishStates;
        } catch (error) {
            console.error(error);
            return null;
        }
    }

    static publishDate(collection) {
        if (collection.publishDate && collection.type === "manual") {
            return date.format(collection.publishDate, "ddd, dd/mm/yyyy h:MMTT") + " [rolled back]";
        }

        if (collection.publishDate) {
            return date.format(collection.publishDate, "ddd, dd/mm/yyyy h:MMTT");
        }

        if (!collection.publishDate) {
            return "[manual collection]";
        }
    }

    static collectionCanBeApproved(collection) {
        // One of the lists doesn't have a value, so we can't verify whether it can be
        // deleted or not. Therefore it's safer to not allow approval
        if (!collection.inProgress || !collection.complete || !collection.reviewed || !collection.deletes) {
            return false;
        }

        if (collection.reviewed.length >= 1 && collection.inProgress.length === 0 && collection.complete.length === 0) {
            return true;
        }

        if (collection.deletes.length >= 1 && collection.inProgress.length === 0 && collection.complete.length === 0) {
            return true;
        }

        // We shouldn't get to this return but we'll return false by default because it's safer to disallow
        // approval rather than approve something in a unexpected state
        return false;
    }

    static collectionCanBeDeleted(collection) {
        // One of the lists doesn't have a value, so we can't verify whether it can be
        // deleted or not. Therefore it's safer to not allow approval
        if (!collection.inProgress || !collection.complete || !collection.reviewed || !collection.deletes) {
            return false;
        }

        if (
            collection.reviewed.length === 0 &&
            collection.inProgress.length === 0 &&
            collection.complete.length === 0 &&
            collection.deletes.length === 0
        ) {
            return true;
        }

        // We shouldn't get to this return but we'll return false by default because it's safer to disallow
        // approval rather than approve something in a unexpected state
        return false;
    }

    // Used for getting all pages in a collection minus the pages that user has requested to be deleted
    // from a collection (but haven't actually been sent to the API yet because allow an 'undo' ability)
    static pagesExcludingPendingDeletedPages(pages, pendingDeletesPages) {
        if (!pages) {
            return;
        }

        if (!pendingDeletesPages || pendingDeletesPages.length === 0) {
            return pages;
        }

        return pages.filter(page => {
            return !pendingDeletesPages.includes(page.uri);
        });
    }
}


text:
<?php

namespace SignatureModule\Pad\Marshal;

use EMRCore\Zend\ServiceManager\AnnotationAwareInterface;
use SignatureModule\Pad\Marshal\JsonToImage as JsonToImageMarshaller;

interface JsonToImageAwareInterface extends AnnotationAwareInterface
{
    /**
     * @param JsonToImageMarshaller $marshaller
     * @return self
     * @setter
     */
    public function setJsonToImageMarshaller(JsonToImageMarshaller $marshaller);

    /**
     * @return JsonToImageMarshaller
     */
    public function getJsonToImageMarshaller();
}


text:
namespace SchoolSystemTest
{
    using System;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using SchoolSystem;

    [TestClass]
    public class TestCourse
    {
        private const string VALID_COURSE_NAME = "CSharp";

        [TestMethod]
        public void TestCourseCreationWithValidName()
        {
            try
            {
                var course = new Course(VALID_COURSE_NAME);
            }
            catch (Exception)
            {

                Assert.Fail("Expected no exception");
            }
        }

        [TestMethod]
        public void TestCourseIfReturnsRightName()
        {
            var course = new Course(VALID_COURSE_NAME);

            Assert.AreEqual(VALID_COURSE_NAME, course.Name);

        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void TestCourseCreationWithNameNull()
        {
            var course = new Course(null);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void TestCourseCreationWithNameEmptyString()
        {
            var course = new Course(string.Empty);
        }

        [TestMethod]
        public void TestAddingStudent()
        {
            var course = new Course(VALID_COURSE_NAME);

            course.AddStudent(new Student("John", 55555));
            var students = course.Students;
            int count = students.Count;

            Assert.AreEqual(1, count, "Course contains different count of students than expected.");
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void TestAddingNullStudent()
        {
            var course = new Course(VALID_COURSE_NAME);

            course.AddStudent(null);
        }

        [TestMethod]
        [ExpectedException(typeof(InvalidOperationException))]
        public void TestOverflowStudentsList()
        {
            var course = new Course(VALID_COURSE_NAME);

            for (int i = 0; i < 30; i++)
            {
                course.AddStudent(new Student(
                    string.Format("Student {0}", i + 1),
                    (10000 + i)));
            }

            course.AddStudent(new Student("John", 55555));
        }

        [TestMethod]
        public void TestRemovingStudent()
        {
            var course = new Course(VALID_COURSE_NAME);
            var student = new Student("John", 55551);

            course.AddStudent(student);
            course.RemoveStudent(student);

            var students = course.Students;
            int count = students.Count;

            Assert.AreEqual(0, count, "Student is not removed from list.");
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void TestRemovingNullStudent()
        {
            var course = new Course(VALID_COURSE_NAME);

            course.AddStudent(new Student("John", 55555));
            course.RemoveStudent(null);
        }

        [TestMethod]
        [ExpectedException(typeof(InvalidOperationException))]
        public void TestRemovingStudentFromEmptyList()
        {
            var course = new Course(VALID_COURSE_NAME);

            course.RemoveStudent(new Student("John", 55555));
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void TestRemovingNonExistingStudent()
        {
            var course = new Course(VALID_COURSE_NAME);

            course.AddStudent(new Student("John", 55551));
            course.AddStudent(new Student("John", 55552));

            course.RemoveStudent(new Student("John", 55555));
        }
    }
}


text:
#pragma once

#include <crtdbg.h>
#include <vector>
#include "Basic/UtilTime.h"
#include "Basic/ModelStat.h"
#include "ModelBase/IndividualBase.h"
#include "WSBEquations.h"

namespace WBSF
{

	enum TWSBStat {
		S_EGG, S_L2o, S_L2, S_L3, S_L4, S_L5, S_L6, S_PUPAE, S_ADULT, S_DEAD_ADULT, S_OVIPOSITING_ADULT, S_BROOD, S_EGG2, S_L2o2, S_L22, S_L32,
		E_EGG, E_L2o, E_L2, E_L3, E_L4, E_L5, E_L6, E_PUPAE, E_ADULT, E_DEAD_ADULT, E_BROOD, E_TOTAL_BROOD, E_TOTAL_FEMALE, E_EGG2, E_L2o2, E_L22, E_L32,
		S_DEAD_ATTRITION, S_DEAD_FROZEN_EGG, S_DEAD_FROZEN_LARVA, S_DEAD_FROZEN_ADULT, S_DEAD_CLEANUP, S_DEAD_MISSING_ENERGY, S_DEAD_SYNCH, S_DEAD_WINDOW, S_DEAD,
		S_AVERAGE_INSTAR, S_DD_BUD, S_DD_SHOOT,
		NB_WSB_STAT
	};

	class CWSBTree;
	class CWSBStand;
	class CWSpruceBudworm : public CIndividual
	{
	public:

		enum TDeathWSB { FROZEN_EGG = NB_DEATHS, FROZEN_LARVA, FROZEN_ADULT, CLEANUP, NB_DEATHS_WSB };

		CWSpruceBudworm(CHost* pHost = NULL, CTRef creationDay = CTRef(), double age = EGG, TSex sex = RANDOM_SEX, bool bFertil = true, size_t generation = 0, double scaleFactor = 1);
		~CWSpruceBudworm(void);

		virtual void Live(const CWeatherDay& weather);
		virtual void Brood(const CWeatherDay& weather);
		virtual void Die(const CWeatherDay& weather);
		virtual void GetStat(CTRef d, CModelStat& stat);
		virtual size_t GetNbStages(void) const { return NB_STAGES; }
		virtual double GetInstar(bool includeLast)const;
		virtual CIndividualPtr CreateCopy()const { return std::make_shared<CWSpruceBudworm>(*this); }
		virtual bool NeedOverheating()const { return GetStage() != L2o && GetStage() != ADULT; }

		inline CWSBTree* GetTree();
		inline const CWSBTree* GetTree()const;
		inline CWSBStand* GetStand();
		inline const CWSBStand* GetStand()const;
		inline CWSBTableLookup& Equations();

	protected:

		bool IsDeadByAttrition(double T, double r)const;
		bool IsDeadByOverwintering(double T, double dt);
		bool IsDeadByAsynchrony();
		bool IsDeadByWindow();
		bool ChangeStage(double RR) { return short(m_age + RR) != GetStage(); }

		//member
		double m_relativeDevRate[NB_STAGES]; //Individual's relative development rates in 9 stages
		CTRef m_OWDate; //When individual pass from Egg to OW, they must stop development until next spring
		double m_potentialFecundity;
		bool m_bKillByAttrition;
		bool m_bKillByOverwintering;

		//survival
		double m_eggAge;
		double m_energy;
		double m_overwinterLuck;		//for overwinter survival
		double m_synchLuck;	//for synchrony survival
		double m_windowLuck;//for shoot development survival
		double m_onBole; //for overwintering survival (buffering of temperature)
		static const double EGG_FREEZING_POINT;
		static const double ADULT_FREEZING_POINT;
	};

	class CWSBTree : public CHost
	{
	public:

		CWSBTree(CStand* pStand = NULL);
		void clear();

		virtual void Live(const CWeatherDay& weather);
		virtual void GetStat(CTRef d, CModelStat& stat, size_t generation = -1);
		virtual void HappyNewYear();

		double GetDDbud()const { return m_DDbud; }//DD for bug test
		double GetDDshoot()const { return m_DDshoot; } //DD for window test
		double GetProbBudMineable()const { return m_probBudMineable; } //Proportion of buds that can be mined by a budworm

	protected:

		void ComputeMineable(const CWeatherDay& weather);
		void ComputeShootDevel(const CWeatherDay& weather);
		//Tree variables
		double m_DDbud; //Accumulated degree days for bud devlopmnent
		double m_DDshoot; //Accumulated degree days for shoot development
		double m_probBudMineable; //Proportion of buds that can be mined by a budworm
	};

	//*******************************************************************************************************
	//*******************************************************************************************************
	// CWSBStand
	class CWSBStand : public CStand
	{
	public:

		//global variables of all bugs
		bool m_bApplyAttrition;
		bool m_bApplyWinterMortality;
		bool m_bApplyAsynchronyMortality;
		bool m_bApplyWindowMortality;
		bool m_bFertilEgg;
		double m_survivalRate;
		double m_defoliation;

		CWSBStand(CBioSIMModelBase* pModel) :
			CStand(pModel),
			m_equations(pModel->RandomGenerator())
		{
			m_bApplyAttrition = true;
			m_bApplyWinterMortality = true;
			m_bApplyAsynchronyMortality = true;
			m_bApplyWindowMortality = true;
			m_bFertilEgg = false;
			m_survivalRate = 0.1;
			m_defoliation = 0.5;

		}

		CWSBTableLookup m_equations;

	protected:

	};

	//WARNING: cast must be defined here to avoid bug in cast
	inline CWSBTree* CWSpruceBudworm::GetTree() { return static_cast<CWSBTree*>(m_pHost); }
	inline const CWSBTree* CWSpruceBudworm::GetTree()const { return static_cast<const CWSBTree*>(m_pHost); }
	inline CWSBStand* CWSpruceBudworm::GetStand() { ASSERT(m_pHost); return static_cast<CWSBStand*>(GetTree()->GetStand()); }
	inline const CWSBStand* CWSpruceBudworm::GetStand()const { ASSERT(m_pHost); return static_cast<const CWSBStand*>(GetTree()->GetStand()); }
	inline CWSBTableLookup& CWSpruceBudworm::Equations() { return GetStand()->m_equations; }

}


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

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:clickable="true"
        android:onClick="onClickNearbyBtn"
        android:id="@+id/ll_nearby_btnwtxt"
        android:background="#FFEDEDED">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/imageButton"
            android:layout_marginBottom="0dp"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="0dp"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:layout_weight="1"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/game_picker_locationarrow_2x"
            android:background="#FFEDEDED"
            android:textAlignment="center"
            android:layout_gravity="center_horizontal"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="Nearby"
            android:id="@+id/textView2"
            android:layout_gravity="center_horizontal"
            android:background="#FFEDEDED"/>
    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
        android:id="@+id/ll_popular_btnwtxt"
        android:onClick="onClickPopularBtn"
        android:clickable="true"
        android:background="#FFEDEDED">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/imageButton2"
            android:layout_marginBottom="0dp"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="0dp"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:layout_weight="1"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/game_picker_star_2x"
            android:background="#FFEDEDED"
            android:onClick="onClickPopularBtn"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:layout_gravity="center_horizontal"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="Popular"
            android:id="@+id/textView3"
            android:layout_gravity="center_horizontal"
            android:focusable="false"
            android:focusableInTouchMode="false"
            android:background="#FFEDEDED"/>
    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
        android:clickable="true"
        android:id="@+id/ll_recent_btnwtxt"
        android:onClick="onClickRecentBtn"
        android:background="#FFEDEDED">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/imageButton3"
            android:layout_marginBottom="0dp"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="0dp"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:layout_weight="1"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/game_picker_clock_2x"
            android:background="#FFEDEDED"
            android:layout_gravity="center_horizontal"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="Recent"
            android:id="@+id/textView4"
            android:layout_gravity="center_horizontal"
            android:background="#FFEDEDED"/>
    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
        android:clickable="true"
        android:id="@+id/ll_search_btnwtxt"
        android:onClick="onClickSearchBtn"
        android:background="#FFEDEDED">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/imageButton4"
            android:layout_marginBottom="0dp"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="0dp"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:layout_weight="1"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/game_picker_search_2x"
            android:background="#FFEDEDED"
            android:layout_gravity="center_horizontal"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="Search"
            android:id="@+id/textView5"
            android:layout_gravity="center_horizontal"
            android:background="#FFEDEDED"/>
    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_gravity="center_horizontal"
        android:clickable="true"
        android:id="@+id/ll_mine_btnwtxt"
        android:onClick="onClickMineBtn"
        android:background="#FFEDEDED">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:id="@+id/imageButton5"
            android:layout_marginBottom="0dp"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="5dp"
            android:layout_marginTop="0dp"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:layout_weight="1"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:adjustViewBounds="true"
            android:scaleType="fitCenter"
            android:src="@drawable/game_picker_clock_2x"
            android:background="#FFEDEDED"
            android:layout_gravity="center_horizontal"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="Mine"
            android:id="@+id/textView6"
            android:layout_gravity="center_horizontal"
            android:background="#FFEDEDED"/>
    </LinearLayout>

</LinearLayout>


text:
package org.apache.gearpump.akkastream.task

import java.time.Instant

import org.apache.gearpump.Message
import org.apache.gearpump.cluster.UserConfig
import org.apache.gearpump.streaming.task.TaskContext

class FoldTask[In, Out](context: TaskContext, userConf : UserConfig)
  extends GraphTask(context, userConf) {

  val zero = userConf.getValue[Out](FoldTask.ZERO)
  val aggregator = userConf.getValue[(Out, In) => Out](FoldTask.AGGREGATOR)
  var aggregated: Out = _
  implicit val ec = context.system.dispatcher

  override def onStart(instant: Instant): Unit = {
    zero.foreach(value => {
      aggregated = value
    })
  }

  override def onNext(msg: Message) : Unit = {
    val data = msg.value.asInstanceOf[In]
    val time = msg.timestamp
    aggregator.foreach(func => {
      aggregated = func(aggregated, data)
      LOG.info(s"aggregated = $aggregated")
      val msg = Message(aggregated, time)
      context.output(msg)
    })
  }
}

object FoldTask {
  val ZERO = "ZERO"
  val AGGREGATOR = "AGGREGATOR"
}


text:
class RemoveEventStatuses < ActiveRecord::Migration[5.2]
  def change
    drop_table(:event_statuses, if_exists: true)
  end
end


text:
using System;

namespace FreeAmp.Core
{
    public class TrackListLadedEventArgs :EventArgs

    {
        private readonly TrackList _trackList;

        public TrackList TrackList => _trackList;

        public TrackListLadedEventArgs(TrackList trackList)
        {
            _trackList = trackList;
        }
    }
}


text:
<?php
include_once 'trafficlight.php';

$tl = new VoidTrafficLight();
for($i=0; $i<40; $i++){
    echo "$i) " . $tl->UpdateController();
}
$tl->change_sensor();
for($i=0; $i<60; $i++){
    echo "$i) " . $tl->UpdateController();
}
 $tl->change_sensor();
 for($i=0; $i<24; $i++){
    echo "$i) " . $tl->UpdateController();
}
 $tl->change_sensor();
 for($i=0; $i<17; $i++){
    echo "$i) " . $tl->UpdateController();
}
 $tl->change_sensor();
 for($i=0; $i<34; $i++){
    echo "$i) " . $tl->UpdateController();
}
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


text:
int _glfwCreateContextTLS(void)
{
    _glfw.win32_tls.context = TlsAlloc();
    if (_glfw.win32_tls.context == TLS_OUT_OF_INDEXES)
    {
        _glfwInputError(GLFW_PLATFORM_ERROR,
                        "Win32: Failed to allocate TLS index");
        return GLFW_FALSE;
    }

    _glfw.win32_tls.allocated = GLFW_TRUE;
    return GLFW_TRUE;
}

void _glfwDestroyContextTLS(void)
{
    if (_glfw.win32_tls.allocated)
        TlsFree(_glfw.win32_tls.context);
}

void _glfwSetContextTLS(_GLFWwindow* context)
{
    TlsSetValue(_glfw.win32_tls.context, context);
}

//////////////////////////////////////////////////////////////////////////
//////                       GLFW platform API                      //////
//////////////////////////////////////////////////////////////////////////

_GLFWwindow* _glfwPlatformGetCurrentContext(void)
{
    return TlsGetValue(_glfw.win32_tls.context);
}


text:
API server for next freemap webapp.

## Requirements

- Node 10+
- MariaDB Database Server
- exiftran (for uploaded images processing)
- gdal_translate (for geotiff to HGT conversion)

## Running in development mode

Please provide settings in environment variables or put them to `.env` file in project root directory.

```bash
npm i
npm run watch | npx bunyan
```

## Running in production mode

Please provide settings in environment variables. Then:

```bash
npm i
npm run build
npm start | npx bunyan
```

We strongly recommend to use `forever` command (installed with `npm i -g forever`).

## Running tests

```bash
npm i
npx mocha test/
```

Running single test:

```bash
./node_modules/.bin/mochamocha test -g "POST /tracklogs should return uid"
```

## Environment variables

- `EARTHEXPLORER_PASSWORD` - TODO
- `EARTHEXPLORER_USERNAME` - TODO
- `ELEVATION_DATA_DIRECTORY` - TODO
- `FACEBOOK_APP_SECRET` - TODO
- `GOOGLE_CLIENT_ID` - TODO
- `GOOGLE_CLIENT_SECRET` - TODO
- `HTTP_PORT` - TODO
- `HTTP_SSL_CERT` - TODO
- `HTTP_SSL_ENABLE` - TODO
- `HTTP_SSL_KEY` - TODO
- `MAILGIN_API_KEY` - TODO
- `MAILGIN_DOMAIN` - TODO
- `MAILGIN_ENABLE` - TODO
- `MARIADB_DATABASE` - TODO
- `MARIADB_HOST` - TODO
- `MARIADB_PASSWORD` - TODO
- `MARIADB_PORT` - TODO
- `MARIADB_USER` - TODO
- `NODE_ENV` - TODO
- `OAUTH_CONSUMER_KEY` - TODO
- `OAUTH_CONSUMER_SECRET` - TODO
- `PICTURES_DIRECTORY` - TODO
- `TRACKING_SOCKET_PORT` - TODO
- `TRACKLOGS_DIRECTORY` - TODO
- `WEB_BASE_URL` - TODO


text:
package org.apache.asterix.optimizer.rules;

import java.util.ArrayList;
import java.util.List;

import org.apache.asterix.lang.common.util.FunctionUtil;
import org.apache.asterix.metadata.declared.DataSource;
import org.apache.asterix.metadata.declared.IMutationDataSource;
import org.apache.asterix.om.constants.AsterixConstantValue;
import org.apache.asterix.om.functions.BuiltinFunctions;
import org.apache.asterix.om.types.IAType;
import org.apache.commons.lang3.mutable.Mutable;
import org.apache.commons.lang3.mutable.MutableObject;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalOperator;
import org.apache.hyracks.algebricks.core.algebra.base.IOptimizationContext;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalExpressionTag;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalOperatorTag;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable;
import org.apache.hyracks.algebricks.core.algebra.expressions.AbstractFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.ConstantExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.ScalarFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.VariableReferenceExpression;
import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
import org.apache.hyracks.algebricks.core.algebra.functions.IFunctionInfo;
import org.apache.hyracks.algebricks.core.algebra.operators.logical.DataSourceScanOperator;
import org.apache.hyracks.algebricks.core.algebra.visitors.ILogicalExpressionReferenceTransform;
import org.apache.hyracks.algebricks.core.rewriter.base.IAlgebraicRewriteRule;

/**
 * This rule rewrites all meta() function calls in a query plan
 * to proper variable references.
 */
public class MetaFunctionToMetaVariableRule implements IAlgebraicRewriteRule {
    // The rule can only apply once.
    private boolean hasApplied = false;
    private boolean rewritten = false;

    @Override
    public boolean rewritePre(Mutable<ILogicalOperator> opRef, IOptimizationContext context)
            throws AlgebricksException {
        if (hasApplied) {
            return false;
        }
        hasApplied = true;
        visit(opRef);
        return rewritten;
    }

    private ILogicalExpressionReferenceTransformWithCondition visit(Mutable<ILogicalOperator> opRef)
            throws AlgebricksException {
        ILogicalOperator op = opRef.getValue();

        // Reaches NTS or ETS.
        if (op.getInputs().size() == 0) {
            return NoOpExpressionReferenceTransform.INSTANCE;
        }
        // Datascan returns an useful transform if the meta part presents in the dataset.
        if (op.getOperatorTag() == LogicalOperatorTag.DATASOURCESCAN) {
            DataSourceScanOperator scanOp = (DataSourceScanOperator) op;
            ILogicalExpressionReferenceTransformWithCondition inputTransfomer = visit(op.getInputs().get(0));
            DataSource dataSource = (DataSource) scanOp.getDataSource();
            List<ILogicalExpressionReferenceTransformWithCondition> transformers = null;
            List<LogicalVariable> allVars = scanOp.getVariables();
            LogicalVariable dataVar = dataSource.getDataRecordVariable(allVars);
            LogicalVariable metaVar = dataSource.getMetaVariable(allVars);
            LogicalExpressionReferenceTransform currentTransformer = null;
            // https://issues.apache.org/jira/browse/ASTERIXDB-1618
            if (dataSource.getDatasourceType() != DataSource.Type.EXTERNAL_DATASET
                    && dataSource.getDatasourceType() != DataSource.Type.INTERNAL_DATASET
                    && dataSource.getDatasourceType() != DataSource.Type.LOADABLE) {
                IMutationDataSource mds = (IMutationDataSource) dataSource;
                if (mds.isChange()) {
                    transformers = new ArrayList<>();
                    transformers.add(new MetaKeyExpressionReferenceTransform(mds.getPkVars(allVars),
                            mds.getKeyAccessExpression()));
                } else if (metaVar != null) {
                    transformers = new ArrayList<>();
                    transformers.add(new MetaKeyToFieldAccessTransform(metaVar));
                }
            }
            if (!dataSource.hasMeta() && transformers == null) {
                return inputTransfomer;
            }
            if (metaVar != null) {
                currentTransformer = new LogicalExpressionReferenceTransform(dataVar, metaVar);
            }
            if (inputTransfomer.equals(NoOpExpressionReferenceTransform.INSTANCE) && transformers == null) {
                return currentTransformer;
            } else if (inputTransfomer.equals(NoOpExpressionReferenceTransform.INSTANCE)
                    && currentTransformer == null) {
                return transformers.get(0);
            } else {
                // Requires an argument variable to resolve ambiguity.
                if (transformers == null) {
                    transformers = new ArrayList<>();
                }
                if (!inputTransfomer.equals(NoOpExpressionReferenceTransform.INSTANCE)) {
                    inputTransfomer.setVariableRequired();
                    transformers.add(inputTransfomer);
                }
                currentTransformer.setVariableRequired();
                transformers.add(currentTransformer);
                return new CompositeExpressionReferenceTransform(transformers);
            }
        }

        // Visits children in the depth-first order.
        List<ILogicalExpressionReferenceTransformWithCondition> transformers = new ArrayList<>();
        for (Mutable<ILogicalOperator> childRef : op.getInputs()) {
            ILogicalExpressionReferenceTransformWithCondition transformer = visit(childRef);
            if (!transformer.equals(NoOpExpressionReferenceTransform.INSTANCE)) {
                transformers.add(transformer);
            }
        }
        ILogicalExpressionReferenceTransformWithCondition currentTransformer = null;
        if (transformers.size() == 0) {
            currentTransformer = NoOpExpressionReferenceTransform.INSTANCE;
        } else if (transformers.size() == 1) {
            currentTransformer = transformers.get(0);
        } else {
            // Transformers in a CompositeTransformer should require argument variable check.
            for (ILogicalExpressionReferenceTransformWithCondition transformer : transformers) {
                transformer.setVariableRequired();
            }
            currentTransformer = new CompositeExpressionReferenceTransform(transformers);
        }
        rewritten |= op.acceptExpressionTransform(currentTransformer);
        return currentTransformer;
    }
}

interface ILogicalExpressionReferenceTransformWithCondition extends ILogicalExpressionReferenceTransform {
    default void setVariableRequired() {

    }
}

class NoOpExpressionReferenceTransform implements ILogicalExpressionReferenceTransformWithCondition {
    static final NoOpExpressionReferenceTransform INSTANCE = new NoOpExpressionReferenceTransform();

    private NoOpExpressionReferenceTransform() {

    }

    @Override
    public boolean transform(Mutable<ILogicalExpression> expression) throws AlgebricksException {
        return false;
    }

}

class LogicalExpressionReferenceTransform implements ILogicalExpressionReferenceTransformWithCondition {
    private final LogicalVariable dataVar;
    private final LogicalVariable metaVar;
    private boolean variableRequired = false;

    LogicalExpressionReferenceTransform(LogicalVariable dataVar, LogicalVariable metaVar) {
        this.dataVar = dataVar;
        this.metaVar = metaVar;
    }

    @Override
    public void setVariableRequired() {
        this.variableRequired = true;
    }

    @Override
    public boolean transform(Mutable<ILogicalExpression> exprRef) throws AlgebricksException {
        ILogicalExpression expr = exprRef.getValue();
        if (expr.getExpressionTag() != LogicalExpressionTag.FUNCTION_CALL) {
            return false;
        }
        AbstractFunctionCallExpression funcExpr = (AbstractFunctionCallExpression) expr;
        List<Mutable<ILogicalExpression>> argRefs = funcExpr.getArguments();

        // Recursively transform argument expressions.
        for (Mutable<ILogicalExpression> argRef : argRefs) {
            transform(argRef);
        }

        if (!funcExpr.getFunctionIdentifier().equals(BuiltinFunctions.META)) {
            return false;
        }
        // The user query provides more than one parameter for the meta function.
        if (argRefs.size() > 1) {
            throw new AlgebricksException("The meta function can at most have one argument!");
        }

        // The user query provides exact one parameter for the meta function.
        if (argRefs.size() == 1) {
            ILogicalExpression argExpr = argRefs.get(0).getValue();
            if (argExpr.getExpressionTag() != LogicalExpressionTag.VARIABLE) {
                return false;
            }
            VariableReferenceExpression argVarExpr = (VariableReferenceExpression) argExpr;
            LogicalVariable argVar = argVarExpr.getVariableReference();
            if (!dataVar.equals(argVar)) {
                return false;
            }
            exprRef.setValue(new VariableReferenceExpression(metaVar));
            return true;
        }

        // The user query provides zero parameter for the meta function.
        if (variableRequired) {
            throw new AlgebricksException("Cannot resolve to ambiguity on the meta function call --"
                    + " there are more than one dataset choices!");
        }
        exprRef.setValue(new VariableReferenceExpression(metaVar));
        return true;
    }
}

class CompositeExpressionReferenceTransform implements ILogicalExpressionReferenceTransformWithCondition {
    private final List<ILogicalExpressionReferenceTransformWithCondition> transformers;

    public CompositeExpressionReferenceTransform(List<ILogicalExpressionReferenceTransformWithCondition> transforms) {
        this.transformers = transforms;
    }

    @Override
    public boolean transform(Mutable<ILogicalExpression> expression) throws AlgebricksException {
        // Tries transfomations one by one.
        for (ILogicalExpressionReferenceTransform transformer : transformers) {
            if (transformer.transform(expression)) {
                return true;
            }
        }
        return false;
    }
}

class MetaKeyToFieldAccessTransform implements ILogicalExpressionReferenceTransformWithCondition {
    private final LogicalVariable metaVar;

    MetaKeyToFieldAccessTransform(LogicalVariable recordVar) {
        this.metaVar = recordVar;
    }

    @Override
    public boolean transform(Mutable<ILogicalExpression> exprRef) throws AlgebricksException {
        ILogicalExpression expr = exprRef.getValue();
        if (expr.getExpressionTag() != LogicalExpressionTag.FUNCTION_CALL) {
            return false;
        }
        AbstractFunctionCallExpression funcExpr = (AbstractFunctionCallExpression) expr;
        if (!funcExpr.getFunctionIdentifier().equals(BuiltinFunctions.META_KEY)) {
            return false;
        }
        // Get arguments
        // first argument : Resource key
        // second argument: field
        List<Mutable<ILogicalExpression>> args = funcExpr.getArguments();
        ConstantExpression fieldNameExpression = (ConstantExpression) args.get(1).getValue();
        AsterixConstantValue fieldNameValue = (AsterixConstantValue) fieldNameExpression.getValue();
        IAType fieldNameType = fieldNameValue.getObject().getType();
        FunctionIdentifier functionIdentifier;
        switch (fieldNameType.getTypeTag()) {
            case ORDEREDLIST:
                // Field access nested
                functionIdentifier = BuiltinFunctions.FIELD_ACCESS_NESTED;
                break;
            case STRING:
                // field access by name
                functionIdentifier = BuiltinFunctions.FIELD_ACCESS_BY_NAME;
                break;
            default:
                throw new AlgebricksException("Unsupported field name type " + fieldNameType.getTypeTag());
        }
        IFunctionInfo finfoAccess = FunctionUtil.getFunctionInfo(functionIdentifier);
        ArrayList<Mutable<ILogicalExpression>> argExprs = new ArrayList<>(2);
        argExprs.add(new MutableObject<>(new VariableReferenceExpression(metaVar)));
        argExprs.add(new MutableObject<>(fieldNameExpression));
        exprRef.setValue(new ScalarFunctionCallExpression(finfoAccess, argExprs));
        return true;
    }
}

class MetaKeyExpressionReferenceTransform implements ILogicalExpressionReferenceTransformWithCondition {
    private final List<LogicalVariable> keyVars;
    private final List<ScalarFunctionCallExpression> metaKeyAccessExpressions;

    MetaKeyExpressionReferenceTransform(List<LogicalVariable> keyVars,
            List<ScalarFunctionCallExpression> metaKeyAccessExpressions) {
        this.keyVars = keyVars;
        this.metaKeyAccessExpressions = metaKeyAccessExpressions;
    }

    @Override
    public boolean transform(Mutable<ILogicalExpression> exprRef) throws AlgebricksException {
        ILogicalExpression expr = exprRef.getValue();
        if (expr.getExpressionTag() != LogicalExpressionTag.FUNCTION_CALL) {
            return false;
        }
        AbstractFunctionCallExpression funcExpr = (AbstractFunctionCallExpression) expr;
        if (!funcExpr.getFunctionIdentifier().equals(BuiltinFunctions.META_KEY)) {
            return false;
        }

        // Function is meta key access
        for (int i = 0; i < metaKeyAccessExpressions.size(); i++) {
            if (metaKeyAccessExpressions.get(i).equals(funcExpr)) {
                exprRef.setValue(new VariableReferenceExpression(keyVars.get(i)));
                return true;
            }
        }
        return false;
    }
}


text:
module ActionStore
  class Engine < ::Rails::Engine
    isolate_namespace ActionStore

    initializer "action_store.init_action", after: :load_config_initializers do
      # Ensure eager_load Action model to init methods
      require "action"
    end
  end
end


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CloneExtensions.UnitTests.Helpers;
using System.Collections.Generic;

namespace CloneExtensions.UnitTests
{
    [TestClass]
    public class TupleTests
    {
        private class MyClass
        {
        }

        [TestMethod]
        public void GetClone_TupleOfInt_InstanceIsCloned()
        {
            AssertHelpers.GetCloneAndAssert(() => new Tuple<int>(10));
        }

        [TestMethod]
        public void GetClone_Tuple_Null()
        {
            var source = (Tuple<int>)null;
            var target = CloneFactory.GetClone(source);
            Assert.IsNull(target);
        }

        [TestMethod]
        public void GetClone_Tuple_DuplicateReuse()
        {
            Tuple<int> helper = new Tuple<int>(1);
            List<Tuple<int>> source = new List<Tuple<int>>()
            {
                helper,
                helper
            };

            var target = CloneFactory.GetClone(source);

            Assert.AreNotSame(source, target);
            Assert.AreEqual(source.Count, target.Count);
            Assert.AreNotSame(source[0], target[0]);
            Assert.AreNotSame(source[1], target[1]);

            Assert.AreSame(target[0], target[1]);
        }

        [TestMethod]
        public void GetClone_TupleT1CloneTest_RefTypeValue_ValuesAreNotTheSame()
        {
            var source = new Tuple<MyClass>(new MyClass());
            var target = CloneFactory.GetClone(source);
            Assert.AreNotSame(source.Item1, target.Item1);
            Assert.AreNotSame(source, target);
        }

        [TestMethod]
        public void GetClone_TupleT5CloneTest_InstanceIsCloned()
        {
            var source = Tuple.Create(1, 2, 3, 4, 5);
            var target = CloneFactory.GetClone(source);
            Assert.AreEqual(source, target);
            Assert.AreNotSame(source, target);
        }

        [TestMethod]
        public void GetClone_TupleT8CloneTest_InstanceIsCloned()
        {
            var source = new Tuple<int, int, int, int, int, int, int, Tuple<int, int, int>>(1, 2, 3, 4, 5, 6, 7, new Tuple<int, int, int>(8, 9, 10));
            var target = CloneFactory.GetClone(source);
            Assert.AreEqual(source, target);
            Assert.AreNotSame(source, target);
        }
    }
}


text:
package com.thoughtworks.go.server.messaging.scheduling;

import com.thoughtworks.go.domain.AgentRuntimeStatus;
import com.thoughtworks.go.helper.AgentMother;
import com.thoughtworks.go.remote.AgentIdentifier;
import com.thoughtworks.go.remote.work.NoWork;
import com.thoughtworks.go.server.perf.WorkAssignmentPerformanceLogger;
import com.thoughtworks.go.server.service.AgentRuntimeInfo;
import com.thoughtworks.go.server.service.BuildAssignmentService;
import com.thoughtworks.go.util.ClassMockery;
import com.thoughtworks.go.work.FakeWork;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static com.thoughtworks.go.util.SystemUtil.currentWorkingDirectory;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.*;

@RunWith(JMock.class)
public class WorkFinderTest {
    private Mockery context;
    private BuildAssignmentService workAssigner;
    private static final AgentIdentifier AGENT_1 = new AgentIdentifier("localhost", "127.0.0.1", "uuid");
    private static final FakeWork SOME_WORK = new FakeWork();
    private static final NoWork NO_WORK = new NoWork();
    private WorkAssignedTopic assignedWorkTopic;
    private WorkFinder finder;
    private IdleAgentTopic idleAgentTopic;
    private WorkAssignmentPerformanceLogger workAssignmentPerformanceLogger;

    @Before
    public void before() {
        context = new ClassMockery();
        workAssigner = context.mock(BuildAssignmentService.class);
        assignedWorkTopic = context.mock(WorkAssignedTopic.class, "assignedWork");
        idleAgentTopic = context.mock(IdleAgentTopic.class, "idleAgent");
        workAssignmentPerformanceLogger = mock(WorkAssignmentPerformanceLogger.class);

        context.checking(new Expectations() {{
            one(idleAgentTopic).addListener(with(any(WorkFinder.class)));
        }});
        finder = new WorkFinder(workAssigner, idleAgentTopic, assignedWorkTopic, workAssignmentPerformanceLogger);
    }

    @Test
    public void shouldDoNothingIfNoWorkIsAvailable() {
        context.checking(new Expectations() {{
            one(workAssigner).assignWorkToAgent(AGENT_1);
            will(returnValue(NO_WORK));
            one(assignedWorkTopic).post(new WorkAssignedMessage(AGENT_1, NO_WORK));
        }});
        finder.onMessage(new IdleAgentMessage(new AgentRuntimeInfo(AGENT_1, AgentRuntimeStatus.Idle, currentWorkingDirectory(), "cookie", null)));
    }

    @Test
    public void shouldAssignWorkIfItIsAvailable() {
        context.checking(new Expectations() {{
            one(workAssigner).assignWorkToAgent(AGENT_1);
            will(returnValue(SOME_WORK));
            one(assignedWorkTopic).post(new WorkAssignedMessage(AGENT_1, SOME_WORK));
        }});
        finder.onMessage(new IdleAgentMessage(new AgentRuntimeInfo(AGENT_1, AgentRuntimeStatus.Idle, currentWorkingDirectory(), "cookie", null)));
    }

    @Test
    public void shouldPostNoWorkOnException() {
        final RuntimeException exception = new RuntimeException("foo");
        context.checking(new Expectations() {{
            one(workAssigner).assignWorkToAgent(AGENT_1);
            will(throwException(exception));
            one(assignedWorkTopic).post(new WorkAssignedMessage(AGENT_1, NO_WORK));
        }});

        try {
            finder.onMessage(new IdleAgentMessage(new AgentRuntimeInfo(AGENT_1, AgentRuntimeStatus.Idle, currentWorkingDirectory(), "cookie", null)));
        } catch (Exception e) {
            assertSame(exception, e);
        }
    }

    @Test
    public void shouldReturnNoWorkInCaseOfAnErrorIsThrown() {
        BuildAssignmentService assigner = mock(BuildAssignmentService.class);
        IdleAgentTopic idleTopic = mock(IdleAgentTopic.class);
        WorkAssignedTopic assignedTopic = mock(WorkAssignedTopic.class);
        WorkFinder finder = new WorkFinder(assigner, idleTopic, assignedTopic, workAssignmentPerformanceLogger);
        AgentRuntimeInfo runtimeInfo = AgentRuntimeInfo.initialState(AgentMother.approvedAgent());
        when(assigner.assignWorkToAgent(runtimeInfo.getIdentifier())).thenThrow(new OutOfMemoryError("test error for martians"));
        try {
            finder.onMessage(new IdleAgentMessage(runtimeInfo));
            fail("should have propagated error");
        } catch (OutOfMemoryError e) {
            String message = e.getMessage();
            if (message != null && message.equals("test error for martians")) {
                //expected
            } else {
                throw e;
            }
        }
        verify(assignedTopic).post(new WorkAssignedMessage(runtimeInfo.getIdentifier(), new NoWork()));
    }
}


text:
#ifndef __PACKETFUNCTIONS_H
#define __PACKETFUNCTIONS_H

/**
\addtogroup cross-layers
\{
\addtogroup PacketFunctions
\{
*/

#include "openwsn.h"

//=========================== define ==========================================

//=========================== typedef =========================================

//=========================== variables =======================================

//=========================== prototypes ======================================

// address translation
void     packetfunctions_ip128bToMac64b(open_addr_t* ip128b,open_addr_t* prefix64btoWrite,open_addr_t* mac64btoWrite);
void     packetfunctions_mac64bToIp128b(open_addr_t* prefix64b,open_addr_t* mac64b,open_addr_t* ip128bToWrite);
void     packetfunctions_mac64bToMac16b(open_addr_t* mac64b, open_addr_t* mac16btoWrite);
void     packetfunctions_mac16bToMac64b(open_addr_t* mac16b, open_addr_t* mac64btoWrite);

// address recognition
bool     packetfunctions_isBroadcastMulticast(open_addr_t* address);
bool     packetfunctions_isAllRoutersMulticast(open_addr_t* address);
bool     packetfunctions_isAllHostsMulticast(open_addr_t* address);
bool     packetfunctions_sameAddress(open_addr_t* address_1, open_addr_t* address_2);

// read/write addresses to/from packets
void     packetfunctions_readAddress(uint8_t* payload, uint8_t type, open_addr_t* writeToAddress, bool littleEndian);
void     packetfunctions_writeAddress(OpenQueueEntry_t* msg, open_addr_t* address, bool littleEndian);

// reserving/tossing headers and footers
void     packetfunctions_reserveHeaderSize(OpenQueueEntry_t* pkt, uint8_t header_length);
void     packetfunctions_tossHeader(OpenQueueEntry_t* pkt, uint8_t header_length);
void     packetfunctions_reserveFooterSize(OpenQueueEntry_t* pkt, uint8_t header_length);
void     packetfunctions_tossFooter(OpenQueueEntry_t* pkt, uint8_t header_length);

// calculate CRC
void     packetfunctions_calculateCRC(OpenQueueEntry_t* msg);
bool     packetfunctions_checkCRC(OpenQueueEntry_t* msg);

// calculate checksum
void     packetfunctions_calculateChecksum(OpenQueueEntry_t* msg, uint8_t* checksum_ptr);

// endianness
void     packetfunctions_htons( uint16_t val, uint8_t* dest );
uint16_t packetfunctions_ntohs( uint8_t* src );
void     packetfunctions_htonl( uint32_t val, uint8_t* dest );
uint32_t packetfunctions_ntohl( uint8_t* src );

/**
\}
\}
*/

#endif


text:
class ContextCreatorTest:
  public testing::Test
{};

struct EvictionContext {};

class Creator:
  public ContextCreator<EvictionContext, int>
{
};

class VoidCreator:
  public ContextCreator<EvictionContext>
{
public:
  size_t m_totalDestroyed = 0;

  void NotifyContextDestroyed(t_callbackHandle q, CoreContext* pContext) override {
    m_totalDestroyed++;
    ContextCreator<EvictionContext>::NotifyContextDestroyed(q, pContext);
  }
};

class GlobalSignal {
public:
private:
  std::mutex m_lock;
  bool m_shouldContinue = false;
  std::condition_variable s_continueCond;

public:
  void Signal(void) {
    (std::lock_guard<std::mutex>)m_lock,
    (m_shouldContinue = true),
    s_continueCond.notify_all();
  }

  void Delay(void) {
    std::unique_lock<std::mutex> lk(m_lock);
    s_continueCond.wait(lk, [this] () {return m_shouldContinue;});
  }
};

class WaitMember:
  public CoreThread
{
public:
  Autowired<GlobalSignal> m_signal;

  void Run(void) override {
    // Wait for our event to be signalled, then leave
    m_signal->Delay();
  }
};

TEST_F(ContextCreatorTest, ValidateSimpleEviction) {
  // Create a context and verify it gets evicted from the context creator:
  AutoRequired<Creator> creator;
  std::weak_ptr<CoreContext> ctxtWeak;

  {
    std::shared_ptr<CoreContext> ctxt;

    // Make a context:
    ctxt = creator->CreateContext(1).first;

    // Obtain a weak pointer, in order to ensure proper teardown:
    ctxtWeak = ctxt;
  }

  // Context must be destroyed as a precondition of the subsequent assertion
  ASSERT_TRUE(ctxtWeak.expired()) << "Expected the context to be destroyed";

  // Verify that our creator is now empty:
  ASSERT_EQ(0UL, creator->GetSize()) << "Context creator is non-empty after all created contexts were destroyed";
}

TEST_F(ContextCreatorTest, ValidateMultipleEviction) {
  AutoCurrentContext()->Initiate();

  // Number of dependent contexts to be created
  const size_t count = 100;

  // Teardown lock, counter, and condition:
  std::mutex lock;
  std::condition_variable cond;
  int counter = count;

  // Obtain creator pointer:
  AutoRequired<Creator> creator;

  // Set up a signal manager at global context scope:
  AutoRequired<GlobalSignal> signal;
  {
    // Array of objects to test destruction on, and corresponding collection of contexts:
    std::shared_ptr<WaitMember> members[count];

    // Create a few contexts:
    for(int i = count; i--;) {
      AutoCreateContext ctxt;
      CurrentContextPusher pshr(ctxt);

      // Trivial validation that the newly created context is an empty context:
      ASSERT_EQ(static_cast<size_t>(0), ctxt->GetMemberCount()) << "A created context was not empty";

      // Add in an object to test asynchronous destruction:
      AutoRequired<WaitMember> obj;
      members[i] = obj;
      ASSERT_EQ(signal.get(), obj->m_signal.get()) << "Dependent context wiring did not correctly match to the enclosing scope";

      // Add a notifier to signal a continue condition when we have everything we need:
      ctxt->AddTeardownListener([&lock, &cond, &counter] {
        (std::lock_guard<std::mutex>)lock,
        counter--,
        cond.notify_all();
      });

      // Kick off the context:
      ctxt->Initiate();
    }

    // Signal all members and then release everything:
    signal->Signal();
  }

  // Wait for all contexts to be destroyed
  std::unique_lock<std::mutex> lk(lock);
  bool wait_status = cond.wait_for(lk, std::chrono::seconds(1), [&counter] {return counter == 0;});
  ASSERT_TRUE(wait_status) << "All teardown listeners didn't trigger, counter still at " << counter;

  // Validate that everything expires:
  ASSERT_EQ(static_cast<size_t>(0), creator->GetSize()) << "Not all contexts were evicted as expected";
}

TEST_F(ContextCreatorTest, ClearAndTeardown) {
  // Create a context and verify it gets evicted from the context creator:

  std::weak_ptr<CoreContext> ctxtWeak;

  {
    AutoCreateContext mainContext;
    CurrentContextPusher pusher(mainContext);

    AutoRequired<Creator> creator;
    std::shared_ptr<CoreContext> ctxt;

    // Make a sub-context
    ctxt = creator->CreateContext(0).first;

    // Obtain a weak pointer, in order to ensure proper teardown:
    ctxtWeak = ctxt;

    //Call clear on the creator.
    creator->Clear(true);

    //Make another one!
    ctxt = creator->CreateContext(1).first;
    //Let the creator go out of scope
  }

  // Context must be destroyed as a precondition of the subsequent assertion
  ASSERT_TRUE(ctxtWeak.expired()) << "Expected the context to be destroyed";

  // Verify that our creator is now empty:
 // ASSERT_EQ(0UL, creator->GetSize()) << "Context creator is non-empty after all created contexts were destroyed";
}

TEST_F(ContextCreatorTest, VoidKeyType) {
  AutoRequired<VoidCreator> vc;

  {
    std::shared_ptr<CoreContext> ctxt = vc->CreateContext();
    ASSERT_EQ(1UL, vc->GetSize()) << "Requested that a context be created, but the void creator did not have any members";

    ASSERT_EQ(1UL, vc->GetSize()) << "A created context was apparently destroyed after firing bolts";
    ASSERT_EQ(0UL, vc->m_totalDestroyed) << "The void creator received a NotifyContextDestroyed call unexpectedly early";

    vc->Clear(true);

    //Make another one to check about collisions
    std::shared_ptr<CoreContext> ctxt2 = vc->CreateContext();
    ASSERT_EQ(1UL, vc->GetSize()) << "Second void context creation failed!";
  }

  ASSERT_EQ(0UL, vc->GetSize()) << "A void context creator was not correctly updated when its dependent context went out of scope";
  ASSERT_EQ(2UL, vc->m_totalDestroyed) << "The void creator did not receive the expected number of NotifyContextDestroyed calls";
}

TEST_F(ContextCreatorTest, ExplicitCallTo_CoreContext_Create) {
  struct FancySigil { };
  struct DullSigil { };

  std::shared_ptr<GlobalCoreContext> gc = GlobalCoreContext::Get();

  std::shared_ptr<CoreContextT<FancySigil>> ctxt1 = gc->Create<FancySigil>();
  std::shared_ptr<CoreContext> ctxt2 = gc->Create<FancySigil>();
  std::shared_ptr<CoreContext> ctxt3 = gc->Create<DullSigil>();

  size_t FancySigilCount = 0;
  for (auto m : ContextEnumeratorT<FancySigil>(gc)) {
    ++FancySigilCount;
  }

  size_t DullSigilCount = 0;
  for (auto m : ContextEnumeratorT<DullSigil>(gc)) {
    ++DullSigilCount;
  }

  ASSERT_EQ(2, FancySigilCount);
  ASSERT_EQ(1, DullSigilCount);
}

struct mySigil {};

class Runnable:
  public CoreRunnable
{
public:
  bool OnStart(void) override { return true;  }
};

TEST_F(ContextCreatorTest, TeardownListenerTest) {
  // Create a context and verify teardown happens as expected
  AutoCreateContext mainContext;
  CurrentContextPusher pusher(mainContext);

  AutoRequired<ContextCreator<mySigil, int>> creator;
  {
    auto subctxt = creator->CreateContext(0).first;
    auto brc = subctxt->Inject<Runnable>();
    subctxt->Initiate();
  }
  creator->Clear(true);
  ASSERT_TRUE(true) << "Really all this test has to do is not crash by this point.";
}


text:
define(["elaiJS/configuration", "elaiJS/widget", "elaiJS/helper"],
          function(config, widgetManager, helper) {
	'use strict';
  var self = {};

  self.beforeTest = function(callback) {
    config.elaiJS.defaultPlugins = undefined;
    config.elaiJS.ressources.widgets = "elaiJSTest/TestModules/TestWidgets";
    config.elaiJS.ressources.widgetCSS = "elaiJSTest/TestModules/TestWidgets/{{name}}.css";
    callback();
  };

  self.createWidget = function(test) {
    widgetManager.create("widget1", "w1").then(function(widget) {
      if(widget) {
        test.assertEq("w1", widget.id);
        test.done();
        return;
      }

      test.failed("Widget not created.");
    });
  };

  self.alreadyExists = function(test) {
    widgetManager.create("widget1", "w1").then(function(widget) {
      test.fail();
    }, function () {
	    widgetManager.create("widget1", "w1-2").then(function(widget) {
	      widgetManager.create("widget2", "w2").then(function(widget) {
	        test.done();
	      });
	    });
    });
  };

  self.get = function(test) {
    this.assertDefined(widgetManager.get("w1"));
    this.assertEq("w1", widgetManager.get("w1").id);
    this.assertDefined(widgetManager.get("w1-2"));
    this.assertDefined(widgetManager.get("w2"));

    var w2s = widgetManager.getWidgetsByName("widget2");
    this.assertEq(1, w2s.length);
    var w2 = w2s[0];
    var w2Copy = widgetManager.get("w2");
    this.assertEq(w2, w2Copy);

    var w1s = widgetManager.getWidgetsByName("widget1");
    this.assertEq(2, w1s.length);

    this.done();
  };

  self.remove = function(test) {
    this.assertDefined(widgetManager.get("w1"));
    this.assertEq("w1", widgetManager.get("w1").id);

    var w1 = widgetManager.get("w1");
    widgetManager.remove(w1);
    this.assertUndefined(widgetManager.get("w1"));

    widgetManager.create("widget1", "w1").then(function(widget) {
      test.assertEq("w1", widget.id);
      test.assertDefined(widgetManager.get("w1"));
      test.done();
    });
  };

  self.removeByID = function(test) {
    this.assertDefined(widgetManager.get("w1"));
    this.assertEq("w1", widgetManager.get("w1").id);

    widgetManager.removeByID("w1");
    this.assertUndefined(widgetManager.get("w1"));

    widgetManager.create("widget1", "w1").then(function(widget) {
      test.assertEq("w1", widget.id);
      test.assertDefined(widgetManager.get("w1"));
      test.done();
    });
  };

	return self;
});


text:
[Aligner](https://github.com/adrianlee44/atom-aligner) add-on to support Python.

## Supported operators
`:`:
```python
colors = {
    "red":    "ff0000",
    "blue":   "0000ff",
    "yellow": "ffff00"
}
```
`=`: assignment
```python
someArray = [0, 1]
zero      = 0

```

## Installation
Aligner must be installed along with this package. For more information, please check out [Aligner](https://github.com/adrianlee44/atom-aligner)

## Changelog
- 2018-08-19   v1.2.0   Add support for MagicPython
- 2017-05-21   v1.1.0   Add support for `=` and embedded python
- 2017-05-13   v1.0.2   Update documentation
- 2015-09-13   v1.0.1   Fix invalid copy in config
- 2015-09-09   v1.0.0   Initial release


text:
<?php

class IndexController extends BonesFw\Controller
{
	public $single_segment = false;

	public function __construct()
	{
		parent::__construct();
		BonesFw\I18N::load('index');
	}

	public function index($args=array(), $etc=array())
	{
		$data = array(
			'test_variable' => 'Bones Framework',
			'page_class' => array('page', 'index'),
		);
		if (!defined('TWIG')) {
		    /* The user hasn't installed Twig. Tell them where to get it. */
		    die('Bones Framework hasn\'t been completely installed yet. You still have to pull in the Twig submodule. See the website for details: https://github.com/msikma/bonesphp/');
		}
		$this->load_twig_view('pages/index', $data);
	}
}


text:
@import UIKit;
@import Foundation;
@import CoreBluetooth;

#import "BluetoothRobot.h"
#import "BluetoothRobotPrivate.h"
#import "RobosapienRobot.h"

@interface RobosapienRobot()

#pragma mark Private Api Calls
-(void) setRobosapienProductActivated;
@end

@protocol RobosapienRobotPrivateDelegate <RobosapienRobotDelegate>
@optional
#pragma mark - Lower level bluetooth chip delegate calls
// If didReceiveRawCommandBytes is implemented then higher level MIP commands are not passed, this takes priority
-(void) RobosapienRobotBluetooth:(RobosapienRobot *)mip didReceiveRobotCommand:(RobotCommand *)command;
-(void) RobosapienRobotBluetooth:(RobosapienRobot *)mip didReceiveRawCommandData:(NSData *)data;

@end


text:
:notebook:

Scenario:
I only need to `git add` a few modifications in the file instead of all modifications
due to make the clear commit for projects.

Solution:
Use `git add -i` to enter interactive mode and enter `5` which means *patch* command to do the work. Like this,
```diff
$ git add -i
           staged     unstaged path
  1:    unchanged        +1/-0 README.md

*** Commands ***
  1: status       2: update       3: revert       4: add untracked
  5: patch        6: diff         7: quit         8: help
What now> 5
           staged     unstaged path
  1:    unchanged        +1/-0 README.md
Patch update>> 1
           staged     unstaged path
* 1:    unchanged        +1/-0 README.md
Patch update>>
diff --git a/README.md b/README.md
index 2e4f550..bb3ef8f 100644
--- a/README.md
+++ b/README.md
@@ -22,3 +22,4 @@ In order to keep myself learning and better, I write notes which I learn day by
 ### Git
 - [Undo rebase or reset incorrectly](git/undo-rebase-or-reset-incorrectly.md)
 - [Search git log](git/search-git-log.md)
+- [Staging partial modification in files](git/staging-partial-modification-in-files.md)
Stage this hunk [y,n,q,a,d,/,e,?]?
```
When you see the line `Stage this hunk [y,n,q,a,d,/,e,?]?` , you could enter `help` to list more information.

```diff
Stage this hunk [y,n,q,a,d,/,e,?]? help
y - stage this hunk
n - do not stage this hunk
q - quit; do not stage this hunk or any of the remaining ones
a - stage this hunk and all later hunks in the file
d - do not stage this hunk or any of the later hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help
```
I often use `y`/`n` option to stage or not to stage the hunk. Sometimes, I also need the `s` to split the hunk to make it to be line-based to stage and use `e` to manually edit hunk.

NOTE: use `e` option to modify content of staging is more flexible.


text:
@implementation UIView (keylime)
  - (NSString*)stringIdentifier
  {
    return [NSString stringWithFormat: @"%@_%p",
            NSStringFromClass([self class]), self];
  }
@end