text:
This is an [Ant](http://ant.apache.org) build script that automates the steps of the [Advanced Installation](http://docs.brightspot.com/cms/developers-guide/installation/advanced.html) of Brightspot. Brightspot requires a specific configuration of Tomcat; see the [brightspot-server](https://github.com/OttoHagg/brightspot-server) repository for the build configuration.

## Features
* Interactive - zero configuration. The script asks you what to name your database and server directory.
* Creates a project-specific database (if MySQL is running).
* Creates a Brightspot-specific version of Tomcat.
* Configures proper permissions and ownership of the server directory.
* Makes the Tomcat shell scripts executable.

## Limitations
* It does not install MySQL. See Prerequisites below, and be sure your MySQL server is running when you execute this script.

## Prerequisites
* Java 8 - Download and install the latest release of [Java 8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html). Also tested with [Amazon Corretto 8](https://docs.aws.amazon.com/corretto/latest/corretto-8-ug/downloads-list.html).
* Ant - Download and install [Ant 1.9.7 or higher](http://ant.apache.org/bindownload.cgi). Make sure `ant` is on your PATH.
* MySQL - Download and install [MySQL 5.7.x GA](https://dev.mysql.com/downloads/mysql/5.7.html).

## Installation
[Download](https://github.com/OttoHagg/brightspot-server-install/archive/master.zip) the latest version and extract contents to some directory where you want to host your server(s). For example, `~/dev/servers`.

You may delete the `LICENSE` and `README.md` files, leaving only the `build.xml` file.

```
~/dev/servers/build.xml
```
## Usage

```
$ cd ~/dev/servers
$ ant
```

This script will create new server directories here. So, for example, if you name your server "myapp" you'll have a new directory named myapp.

```
~/dev/servers/build.xml
~/dev/servers/myapp
```

## Great! Now What?
Start your new server as you would with any Tomcat.

```
cd ~/dev/server/myapp/bin
$ ./startup.sh
```

Stopping your server is just as familiar.

```
cd ~/dev/server/myapp/bin
$ ./shutdown.sh
```

And, lastly, if you're here, you're probably doing some Brightspot development.

### Build your Brightspot Project
The artifact of building your project is a war file, typically at ```target/myapp-1.0.0-SNAPSHOT.war```. You can copy this file to your server's ```webapps``` directory and rename the file to ```ROOT.war```. Tomcat will hot-deploy this as the default application.

### Link your War File
Better yet, link your target's artifact to ROOT.war in your server's ```webapps``` directory. For example:

```
$ cd ~/dev/server/myapp/webapps
$ ln -sf ~/dev/workspace/myapp/target/myapp-1.0.0-SNAPSHOT.war ./ROOT.war
```


text:
package gr.geomike.ted.api.db.entity;

import gr.geomike.ted.Views;
import com.fasterxml.jackson.annotation.JsonView;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;

@Entity
@Table(name = "USER")
@XmlRootElement
@NamedQueries({
        @NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
        @NamedQuery(name = "User.findByUsername", query = "SELECT u FROM User u WHERE u.username = :username"),
        @NamedQuery(name = "User.findByFirstName", query = "SELECT u FROM User u WHERE u.firstName = :firstName"),
        @NamedQuery(name = "User.findByLastName", query = "SELECT u FROM User u WHERE u.lastName = :lastName"),
        @NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User u WHERE u.password = :password"),
        @NamedQuery(name = "User.findByUsernameAndPassword",
                query = "SELECT u FROM User u WHERE u.username = :username and u.password = :password" )})
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    private String username;

    private String password;
    private String role;
    private String accountStatus;
    private String firstName;
    private String lastName;
    private String email;
    private String socialSecurityNumber;
    private String address;
    private String phoneNumber;
    private String country;

    private Bidder bidder;
    private Seller seller;

    public User(){
    }
    public User(String username) {
        this.username = username;
    }
    public User(String username, String password,String role, String firstName, String lastName,  String email,
                String socialSecurityNumber, String address, String phoneNumber, Bidder bidder, Seller seller) {
        this.username = username;
        this.password = password;
        this.role = role;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.socialSecurityNumber = socialSecurityNumber;
        this.address = address;
        this.phoneNumber = phoneNumber;
        this.bidder = bidder;
        this.seller = seller;
    }

    @Id
    @Column(name = "USERNAME")
    @JsonView(Views.Basic.class)
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }

    @Basic
    @Column(name = "PASSWORD")
    @JsonView(Views.Basic.class)
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

    @Basic
    @Column(name = "ROLE")
    @JsonView(Views.Basic.class)
    public String getRole() {
        return role;
    }
    public void setRole(String role) {
        this.role = role;
    }

    @Basic
    @Column(name = "ACCOUNT_STATUS")
    @JsonView(Views.Basic.class)
    public String getAccountStatus() {
        return accountStatus;
    }
    public void setAccountStatus(String accountStatus) {
        this.accountStatus = accountStatus;
    }

    @Basic
    @Column(name = "FIRST_NAME")
    @JsonView(Views.Basic.class)
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @Basic
    @Column(name = "LAST_NAME")
    @JsonView(Views.Basic.class)
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Basic
    @Column(name = "EMAIL")
    @JsonView(Views.Basic.class)
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }

    @Basic
    @Column(name = "SOCIAL_SECURITY_NUMBER")
    @JsonView(Views.Basic.class)
    public String getSocialSecurityNumber() {
        return socialSecurityNumber;
    }
    public void setSocialSecurityNumber(String socialSecurityNumber) {
        this.socialSecurityNumber = socialSecurityNumber;
    }

    @Basic
    @Column(name = "COUNTRY")
    @JsonView(Views.Basic.class)
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }

    @Basic
    @Column(name = "ADDRESS")
    @JsonView(Views.Basic.class)
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }

    @Basic
    @Column(name = "PHONE_NUMBER")
    @JsonView(Views.Basic.class)
    public String getPhoneNumber() {
        return phoneNumber;
    }
    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

   /* @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof User)) return false;

        User user = (User) o;

        if (!username.equals(user.username)) return false;
        if (!password.equals(user.password)) return false;
        if (!role.equals(user.role)) return false;
        if (firstName != null ? !firstName.equals(user.firstName) : user.firstName != null) return false;
        if (lastName != null ? !lastName.equals(user.lastName) : user.lastName != null) return false;
        if (email != null ? !email.equals(user.email) : user.email != null) return false;
        if (socialSecurityNumber != null ? !socialSecurityNumber.equals(user.socialSecurityNumber) : user.socialSecurityNumber != null)
            return false;
        if (address != null ? !address.equals(user.address) : user.address != null) return false;
        if (phoneNumber != null ? !phoneNumber.equals(user.phoneNumber) : user.phoneNumber != null) return false;
        if (country != null ? !country.equals(user.country) : user.country != null) return false;
        if (!bidder.equals(user.bidder)) return false;
        return seller.equals(user.seller);

    }

    @Override
    public int hashCode() {
        int result = username.hashCode();
        result = 31 * result + password.hashCode();
        result = 31 * result + role.hashCode();
        result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
        result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
        result = 31 * result + (email != null ? email.hashCode() : 0);
        result = 31 * result + (socialSecurityNumber != null ? socialSecurityNumber.hashCode() : 0);
        result = 31 * result + (address != null ? address.hashCode() : 0);
        result = 31 * result + (phoneNumber != null ? phoneNumber.hashCode() : 0);
        result = 31 * result + (country != null ? country.hashCode() : 0);
        result = 31 * result + bidder.hashCode();
        result = 31 * result + seller.hashCode();
        return result;
    }*/

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
    @JsonView(Views.User.class)
    public Bidder getBidder() {
        return bidder;
    }
    public void setBidder(Bidder bidder) {
        this.bidder = bidder;
    }

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
    @JsonView(Views.User.class)
    public Seller getSeller() {
        return seller;
    }
    public void setSeller(Seller seller) {
        this.seller = seller;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
 */

package org.ligoj.app.plugin.prov.quote.container;

import java.util.List;

import javax.transaction.Transactional;
import javax.ws.rs.BeanParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;

import org.ligoj.app.plugin.prov.AbstractProvQuoteInstanceOsResource;
import org.ligoj.app.plugin.prov.ProvResource;
import org.ligoj.app.plugin.prov.UpdatedCost;
import org.ligoj.app.plugin.prov.dao.Optimizer;
import org.ligoj.app.plugin.prov.dao.ProvContainerPriceRepository;
import org.ligoj.app.plugin.prov.dao.ProvContainerTypeRepository;
import org.ligoj.app.plugin.prov.dao.ProvQuoteContainerRepository;
import org.ligoj.app.plugin.prov.model.ProvContainerPrice;
import org.ligoj.app.plugin.prov.model.ProvContainerType;
import org.ligoj.app.plugin.prov.model.ProvInstancePriceTerm;
import org.ligoj.app.plugin.prov.model.ProvQuote;
import org.ligoj.app.plugin.prov.model.ProvQuoteContainer;
import org.ligoj.app.plugin.prov.model.QuoteContainer;
import org.ligoj.app.plugin.prov.model.ResourceType;
import org.ligoj.app.plugin.prov.model.VmOs;
import org.ligoj.bootstrap.core.json.TableItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import lombok.Getter;

/**
 * The container part of the provisioning.
 */
@Service
@Path(ProvResource.SERVICE_URL)
@Produces(MediaType.APPLICATION_JSON)
@Transactional
public class ProvQuoteContainerResource extends
		AbstractProvQuoteInstanceOsResource<ProvContainerType, ProvContainerPrice, ProvQuoteContainer, QuoteContainerEditionVo, QuoteContainerLookup, QuoteContainer> {

	@Getter
	@Autowired
	private ProvContainerPriceRepository ipRepository;

	@Getter
	@Autowired
	private ProvQuoteContainerRepository qiRepository;

	@Getter
	@Autowired
	private ProvContainerTypeRepository itRepository;

	@Override
	protected ResourceType getType() {
		return ResourceType.CONTAINER;
	}

	@Override
	@POST
	@Path("container")
	@Consumes(MediaType.APPLICATION_JSON)
	public UpdatedCost create(final QuoteContainerEditionVo vo) {
		return saveOrUpdate(new ProvQuoteContainer(), vo);
	}

	@Override
	@PUT
	@Path("container")
	@Consumes(MediaType.APPLICATION_JSON)
	public UpdatedCost update(final QuoteContainerEditionVo vo) {
		return super.update(vo);
	}

	@Override
	@DELETE
	@Path("{subscription:\\d+}/container")
	@Consumes(MediaType.APPLICATION_JSON)
	public UpdatedCost deleteAll(@PathParam("subscription") final int subscription) {
		return super.deleteAll(subscription);
	}

	@Override
	@DELETE
	@Path("container/{id:\\d+}")
	@Consumes(MediaType.APPLICATION_JSON)
	public UpdatedCost delete(@PathParam("id") final int id) {
		return super.delete(id);
	}

	/**
	 * Return the container prices matching to the criteria.
	 *
	 * @param subscription The subscription identifier.
	 * @param query        The criteria.
	 * @return The best container price matching to the criteria.
	 */
	@GET
	@Path("{subscription:\\d+}/container-lookup")
	@Consumes(MediaType.APPLICATION_JSON)
	public QuoteContainerLookup lookup(@PathParam("subscription") final int subscription,
			@BeanParam final QuoteContainerQuery query) {
		return lookupInternal(subscription, query);
	}

	@Override
	protected List<Object[]> findLowestPrice(final ProvQuote configuration, final QuoteContainer query,
			final List<Integer> types, final List<Integer> terms, final int location, final double rate,
			final double duration, final double initialCost, final Optimizer optimizer) {
		final var service = getService(configuration);
		// Resolve the right OS
		final var os = service.getCatalogOs(query.getOs());
		// Resolve the right license model
		final var licenseR = normalize(getLicense(configuration, query.getLicense(), os, this::canByol));
		if (optimizer == Optimizer.CO2) {
			return ipRepository.findLowestCo2(types, terms, os, location, rate, duration, licenseR, initialCost,
					PageRequest.of(0, 1));
		}
		return ipRepository.findLowestCost(types, terms, os, location, rate, duration, licenseR, initialCost,
				PageRequest.of(0, 1));
	}

	@Override
	protected List<Object[]> findLowestDynamicPrice(final ProvQuote configuration, final QuoteContainer query,
			final List<Integer> types, final List<Integer> terms, final double cpu, final double gpu, final double ram,
			final int location, final double rate, final int duration, final double initialCost,
			final Optimizer optimizer) {
		final var service = getService(configuration);
		// Resolve the right OS
		final var os = service.getCatalogOs(query.getOs());
		// Resolve the right license model
		final var licenseR = normalize(getLicense(configuration, query.getLicense(), os, this::canByol));
		if (optimizer == Optimizer.CO2) {
			return ipRepository.findLowestDynamicCo2(types, terms, Math.ceil(Math.max(1, cpu)), gpu,
					Math.ceil(round(ram / 1024)), os, location, rate, round(rate * duration), duration, licenseR,
					initialCost, PageRequest.of(0, 1));
		}
		return ipRepository.findLowestDynamicCost(types, terms, Math.ceil(Math.max(1, cpu)), gpu,
				Math.ceil(round(ram / 1024)), os, location, rate, round(rate * duration), duration, licenseR,
				initialCost, PageRequest.of(0, 1));
	}

	@Override
	@GET
	@Path("{subscription:\\d+}/container-price-term")
	@Consumes(MediaType.APPLICATION_JSON)
	public TableItem<ProvInstancePriceTerm> findPriceTerms(@PathParam("subscription") final int subscription,
			@Context final UriInfo uriInfo) {
		return super.findPriceTerms(subscription, uriInfo);
	}

	@Override
	@GET
	@Path("{subscription:\\d+}/container-license/{os}")
	public List<String> findLicenses(@PathParam("subscription") final int subscription,
			@PathParam("os") final VmOs os) {
		return super.findLicenses(subscription, os);
	}

	@Override
	@GET
	@Path("{subscription:\\d+}/container-os")
	public List<String> findOs(@PathParam("subscription") final int subscription) {
		return super.findOs(subscription);
	}

	@Override
	@GET
	@Path("{subscription:\\d+}/container-type")
	@Consumes(MediaType.APPLICATION_JSON)
	public TableItem<ProvContainerType> findAllTypes(@PathParam("subscription") final int subscription,
			@Context final UriInfo uriInfo) {
		return super.findAllTypes(subscription, uriInfo);
	}

	@Override
	protected QuoteContainerLookup newPrice(final Object[] rs) {
		final var result = new QuoteContainerLookup();
		result.setPrice((ProvContainerPrice) rs[0]);
		result.setCost(round((double) rs[2]));
		result.setCo2(round((double) rs[4]));
		return result;
	}

}


text:
package org.rioproject.impl.watch;

import org.rioproject.watch.Calculable;
import org.rioproject.watch.ThresholdType;
import org.rioproject.watch.ThresholdValues;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The BoundedThresholdManager provides support for threshold handling as
 * follows: A ThresholdNotify.notify method is invoked when the high threshold
 * is breached, and again invoked when the Calculable drops below the high
 * threshold. Low threshold processing occurs in the same manner
 */
public class BoundedThresholdManager extends ThresholdManager {
    private boolean thresholdCrossed = false;
    private static final int CLEARED = 0;
    private static final int BREACHED_LOWER = 1;
    private static final int BREACHED_UPPER = 2;
    private int direction = 0;
    private final String id;
    static Logger logger = LoggerFactory.getLogger("org.rioproject.watch");

    public BoundedThresholdManager(String id) {
        this.id = id;
    }

    public boolean getThresholdCrossed() {
        return (thresholdCrossed);
    }

    @Override
    protected String getID() {
        return id;
    }

    public void checkThreshold(Calculable calculable) {
        ThresholdValues thresholdValues = getThresholdValues();
        double value = calculable.getValue();
        if(thresholdCrossed) {
            if(direction == BREACHED_UPPER) {
                if(value < thresholdValues.getHighThreshold()) {
                    thresholdCrossed = false;
                    direction = CLEARED;
                    /* the next 2 lines produce a cleared event*/
                    thresholdValues.incThresholdClearedCount();
                    notifyListeners(calculable, ThresholdType.CLEARED);
                    checkLowThresholdBreach(calculable);
                } else {
                    checkHighThresholdBreach(calculable);
                }
            } else if(direction == BREACHED_LOWER) {
                if(value > thresholdValues.getLowThreshold()) {
                    thresholdCrossed = false;
                    direction = CLEARED;
                    thresholdValues.incThresholdClearedCount();
                    notifyListeners(calculable, ThresholdType.CLEARED);
                    checkHighThresholdBreach(calculable);
                } else {
                    checkLowThresholdBreach(calculable);
                }
            }
        } else {
            checkHighThresholdBreach(calculable);
            checkLowThresholdBreach(calculable);
        }
    }

    /**
     * Check if the Calculable has crossed the high threshold
     *
     * @param calculable The Calculable value to check
     */
    private void checkHighThresholdBreach(Calculable calculable) {
        double value = calculable.getValue();
        if(value > thresholdValues.getHighThreshold()) {
            boolean notify;
            if(thresholdValues.getStep()>0 && thresholdCrossed) {
                double diff = value - thresholdValues.getCurrentHighThreshold();
                notify = diff >= thresholdValues.getStep();
            } else {
                notify = true;
            }
            if(notify) {
                thresholdCrossed = true;
                direction = BREACHED_UPPER;
                thresholdValues.incThresholdBreachedCount();
                thresholdValues.setCurrentHighThreshold(value);
                notifyListeners(calculable, ThresholdType.BREACHED);
            }
        }
    }

    /**
     * Check if the Calculable has crossed the low threshold
     *
     * @param calculable The Calculable value to check
     */
    private void checkLowThresholdBreach(Calculable calculable) {
        double value = calculable.getValue();
        if(value < thresholdValues.getLowThreshold()) {
            boolean notify;
            if(thresholdValues.getStep()>0 && thresholdCrossed) {
                double diff = Math.abs(thresholdValues.getCurrentLowThreshold()-value);
                notify = diff >= thresholdValues.getStep();
            } else {
                notify = true;
            }
            if(notify) {
                thresholdCrossed = true;
                direction = BREACHED_LOWER;
                thresholdValues.incThresholdBreachedCount();
                thresholdValues.setCurrentLowThreshold(value);
                notifyListeners(calculable, ThresholdType.BREACHED);
            }
        }
    }
}


text:
namespace mms {

class ConfigDialog : public QDialog {

    Q_OBJECT

public:

    ConfigDialog(
        QString name,
        QString directory,
        QString buildCommand,
        QString runCommand);

    QString getName();
    QString getDirectory();
    QString getBuildCommand();
    QString getRunCommand();
    bool removeButtonPressed();

private:

    QLineEdit* m_name;
    QLineEdit* m_directory;
    QLineEdit* m_buildCommand;
    QLineEdit* m_runCommand;
    bool m_removeButtonPressed;
    QDialogButtonBox* m_buttons;

    void onBrowseButtonPressed();
    void onRemoveButtonPressed();
    void validate(QString name);

    void appendRow(
        QGridLayout* layout,
        QString label,
        QLineEdit* lineEdit);
};

}


text:
package org.hisp.dhis.android.sdk.controllers.tracker;

import android.content.Context;
import android.util.Log;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;

import org.hisp.dhis.android.sdk.R;
import org.hisp.dhis.android.sdk.controllers.ApiEndpointContainer;
import org.hisp.dhis.android.sdk.controllers.DhisController;
import org.hisp.dhis.android.sdk.controllers.LoadingController;
import org.hisp.dhis.android.sdk.controllers.ResourceController;
import org.hisp.dhis.android.sdk.controllers.metadata.MetaDataController;
import org.hisp.dhis.android.sdk.controllers.wrappers.EventsWrapper;
import org.hisp.dhis.android.sdk.network.APIException;
import org.hisp.dhis.android.sdk.network.DhisApi;
import org.hisp.dhis.android.sdk.persistence.models.Enrollment;
import org.hisp.dhis.android.sdk.persistence.models.Event;
import org.hisp.dhis.android.sdk.persistence.models.OrganisationUnit;
import org.hisp.dhis.android.sdk.persistence.models.Program;
import org.hisp.dhis.android.sdk.persistence.models.Relationship;
import org.hisp.dhis.android.sdk.persistence.models.SystemInfo;
import org.hisp.dhis.android.sdk.persistence.models.TrackedEntityAttributeValue;
import org.hisp.dhis.android.sdk.persistence.models.TrackedEntityInstance;
import org.hisp.dhis.android.sdk.persistence.models.meta.DbOperation;
import org.hisp.dhis.android.sdk.persistence.preferences.DateTimeManager;
import org.hisp.dhis.android.sdk.persistence.preferences.ResourceType;
import org.hisp.dhis.android.sdk.utils.DbUtils;
import org.hisp.dhis.android.sdk.utils.UiUtils;
import org.hisp.dhis.android.sdk.utils.Utils;
import org.hisp.dhis.android.sdk.utils.api.ProgramType;
import org.joda.time.DateTime;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import static org.hisp.dhis.android.sdk.utils.NetworkUtils.unwrapResponse;

/**
 * @author Simen Skogly Russnes on 24.08.15.
 */
final class TrackerDataLoader extends ResourceController {

    public static final String CLASS_TAG = TrackerDataLoader.class.getSimpleName();

    private TrackerDataLoader() {}

    /**
     * Loads datavalue items that is scheduled to be loaded but has not yet been.
     */
    static void updateDataValueDataItems(Context context, DhisApi dhisApi) throws APIException {
        SystemInfo serverSystemInfo = dhisApi.getSystemInfo();
        DateTime serverDateTime = serverSystemInfo.getServerDate();
        List<OrganisationUnit> assignedOrganisationUnits = MetaDataController.getAssignedOrganisationUnits();
        Hashtable<String, List<Program>> programsForOrganisationUnits = new Hashtable<>();

        if (LoadingController.isLoadFlagEnabled(context, ResourceType.EVENTS)) {
            for (OrganisationUnit organisationUnit : assignedOrganisationUnits) {
                if (organisationUnit.getId() == null || organisationUnit.getId().length() == Utils.randomUUID.length()) {
                    continue;
                }

                List<Program> programsForOrgUnit = new ArrayList<>();
                List<Program> programsForOrgUnitSEWoR = MetaDataController.getProgramsForOrganisationUnit
                        (organisationUnit.getId(),
                                ProgramType.WITHOUT_REGISTRATION);
                if (programsForOrgUnitSEWoR != null) {
                    programsForOrgUnit.addAll(programsForOrgUnitSEWoR);
                }

                programsForOrganisationUnits.put(organisationUnit.getId(), programsForOrgUnit);
            }

            for (final OrganisationUnit organisationUnit : assignedOrganisationUnits) {
                if (organisationUnit.getId() == null || organisationUnit.getId().length() == Utils.randomUUID.length())
                    continue;

                for (final Program program : programsForOrganisationUnits.get(organisationUnit.getId())) {
                    if (program.getUid() == null || program.getUid().length() == Utils.randomUUID.length())
                        continue;

                    if (shouldLoad(dhisApi, ResourceType.EVENTS, organisationUnit.getId() + program.getUid())) {
                        UiUtils.postProgressMessage(context.getString(R.string.loading_events) + ": "
                                + organisationUnit.getLabel() + ": " + program.getName());
                        try {
                        getEventsDataFromServer(dhisApi, organisationUnit.getId(), program.getUid(), serverDateTime);
                        } catch (APIException e) {
                        e.printStackTrace();
                        //todo: could probably do something prettier here. This catch is done to prevent
                        // stopping loading of the following program/orgUnit as throwing and exception would exit the loop..
                        }
                    }
                }
            }
        }
    }

    static void getEventsDataFromServer(DhisApi dhisApi, String organisationUnitUid, String programUid, DateTime serverDateTime) throws APIException {
        Log.d(CLASS_TAG, "getEventsDataFromServer");
        DateTime lastUpdated = DateTimeManager.getInstance()
                .getLastUpdated(ResourceType.EVENTS,organisationUnitUid+programUid);
        final Map<String, String> map = new HashMap<>();
        map.put("fields", "[:all]");
        if (lastUpdated != null) {
            map.put("lastUpdated", lastUpdated.toString());
        }
        JsonNode response = dhisApi.getEvents(programUid, organisationUnitUid, 200,
                map);
        List<Event> events = EventsWrapper.getEvents(response);
        saveResourceDataFromServer(ResourceType.EVENTS,organisationUnitUid+programUid, dhisApi, events, null, serverDateTime);
    }

    static List<TrackedEntityInstance> queryTrackedEntityInstancesDataFromServer(DhisApi dhisApi,
                                                                                String organisationUnitUid,
                                                                                String programUid,
                                                                                String queryString,
                                                                                TrackedEntityAttributeValue... params) throws APIException {
        final Map<String, String> QUERY_MAP_FULL = new HashMap<>();
        if(programUid != null) {
            QUERY_MAP_FULL.put("program", programUid);
        }
        List<TrackedEntityAttributeValue> valueParams = new LinkedList<>();
        if( params != null ) {
            for(TrackedEntityAttributeValue teav: params ) {
                if( teav != null && teav.getValue() != null ) {
                    if( !teav.getValue().isEmpty() ) {
                        valueParams.add( teav );
                        QUERY_MAP_FULL.put("filter",teav.getTrackedEntityAttributeId()+":LIKE:"+teav.getValue());
                    }
                }
            }
        }

        //doesnt work with both attribute filter and query
        if(queryString!=null && !queryString.isEmpty() && valueParams.isEmpty() ) {
            QUERY_MAP_FULL.put("query","LIKE:"+queryString);//todo: make a map where we can use more than one of each key
        }
        List<TrackedEntityInstance> trackedEntityInstances = unwrapResponse(dhisApi
                .getTrackedEntityInstances(organisationUnitUid,
                        QUERY_MAP_FULL), ApiEndpointContainer.TRACKED_ENTITY_INSTANCES);
        return trackedEntityInstances;
    }

    static void getTrackedEntityInstancesDataFromServer(DhisApi dhisApi, List<TrackedEntityInstance> trackedEntityInstances, boolean getEnrollments) {
        if(trackedEntityInstances == null) {
            return;
        }
        for(TrackedEntityInstance trackedEntityInstance: trackedEntityInstances) {
            try {
                getTrackedEntityInstanceDataFromServer(dhisApi, trackedEntityInstance.getTrackedEntityInstance(), getEnrollments);
            } catch (APIException e) { //can't throw this further up because we want to continue loading all the TEIs..
                e.printStackTrace();
            }
        }
    }

    static void getTrackedEntityInstanceDataFromServer(DhisApi dhisApi, String uid, boolean getEnrollments) throws APIException {
        DateTime lastUpdated = DateTimeManager.getInstance()
                .getLastUpdated(ResourceType.TRACKEDENTITYINSTANCE, uid);
        DateTime serverDateTime = dhisApi.getSystemInfo()
                .getServerDate();

        Log.d(CLASS_TAG, "get tei " + uid);
        TrackedEntityInstance trackedEntityInstance = updateTrackedEntityInstance(dhisApi, uid, lastUpdated);
        Log.d(CLASS_TAG, "get tei1 " + uid);

        //need to save the TEI first to get a auto-increment id
        DbOperation.save(trackedEntityInstance).getModel().save();

        List<DbOperation> operations = new ArrayList<>();
        if (trackedEntityInstance.getAttributes() != null) {
            for (TrackedEntityAttributeValue value : trackedEntityInstance.getAttributes()) {
                if (value != null) {
                    value.setTrackedEntityInstanceId(trackedEntityInstance.getTrackedEntityInstance());
                    value.setLocalTrackedEntityInstanceId(trackedEntityInstance.getLocalId());
                    operations.add(DbOperation.save(value));
                }
            }
        }
        if (trackedEntityInstance.getRelationships() != null) {
            for (Relationship relationship : trackedEntityInstance.getRelationships()) {
                if (relationship != null) {
                    relationship.async().save();
                    operations.add(DbOperation.save(relationship));
                }
            }
        }
        DbUtils.applyBatch(operations);
        DateTimeManager.getInstance()
                .setLastUpdated(ResourceType.TRACKEDENTITYINSTANCE, uid, serverDateTime);
        if(getEnrollments) {
            getEnrollmentsDataFromServer(dhisApi, trackedEntityInstance);
        }
    }

    private static TrackedEntityInstance updateTrackedEntityInstance(DhisApi dhisApi, String uid, DateTime lastUpdated) throws APIException {
        final Map<String, String> QUERY_MAP_FULL = new HashMap<>();
        TrackedEntityInstance updatedTrackedEntityInstance = dhisApi.getTrackedEntityInstance(uid, QUERY_MAP_FULL);
        return updatedTrackedEntityInstance;
    }

    static void getEnrollmentsDataFromServer(DhisApi dhisApi, TrackedEntityInstance trackedEntityInstance) throws APIException {
        if(trackedEntityInstance == null) {
            return;
        }
        DateTime lastUpdated = DateTimeManager.getInstance()
                .getLastUpdated(ResourceType.ENROLLMENTS, trackedEntityInstance.getTrackedEntityInstance());
        DateTime serverDateTime = dhisApi.getSystemInfo()
                .getServerDate();
        List<Enrollment> enrollments = unwrapResponse(dhisApi
                .getEnrollments(trackedEntityInstance.getTrackedEntityInstance(),
                        getBasicQueryMap(lastUpdated)), ApiEndpointContainer.ENROLLMENTS);
        for(Enrollment enrollment: enrollments) {
            enrollment.setLocalTrackedEntityInstanceId(trackedEntityInstance.getLocalId());
        }

        saveResourceDataFromServer(ResourceType.ENROLLMENTS,
                trackedEntityInstance.getTrackedEntityInstance(), dhisApi,
                enrollments, TrackerController.getEnrollments(trackedEntityInstance), serverDateTime);
        enrollments = TrackerController.getEnrollments(trackedEntityInstance);
        if(enrollments != null) {
            for(Enrollment enrollment: enrollments) {
                try {
                    getEventsDataFromServer(dhisApi, enrollment);
                } catch (APIException e) {//can't throw this exception up because we want to continue loading enrollments.. todo: let the user know?
                    e.printStackTrace();
                }
            }
        }
    }

    static void getEnrollmentDataFromServer(DhisApi dhisApi, String uid, boolean getEvents) throws APIException {
        DateTime lastUpdated = DateTimeManager.getInstance()
                .getLastUpdated(ResourceType.ENROLLMENT, uid);
        DateTime serverDateTime = dhisApi.getSystemInfo()
                .getServerDate();

        Enrollment enrollment = updateEnrollment(dhisApi, uid, lastUpdated);

        DbOperation.save(enrollment).getModel().save();
        DateTimeManager.getInstance()
                .setLastUpdated(ResourceType.ENROLLMENT, uid, serverDateTime);
        if(getEvents) {
            getEventsDataFromServer(dhisApi, enrollment);
        }
    }

    private static Enrollment updateEnrollment(DhisApi dhisApi, String uid, DateTime lastUpdated) throws APIException {
        final Map<String, String> QUERY_MAP_FULL = new HashMap<>();
        Enrollment updatedEnrollment = dhisApi.getEnrollment(uid, QUERY_MAP_FULL);
        return updatedEnrollment;
    }

    static void getEventsDataFromServer(DhisApi dhisApi, Enrollment enrollment) {
        if(enrollment == null) {
            return;
        }
        DateTime lastUpdated = DateTimeManager.getInstance()
                .getLastUpdated(ResourceType.EVENTS, enrollment.getEnrollment());
        DateTime serverDateTime = dhisApi.getSystemInfo()
                .getServerDate();
        JsonNode response = dhisApi
                .getEventsForEnrollment(enrollment.getProgram().getUid(), enrollment.getStatus(),
                        enrollment.getTrackedEntityInstance(),
                        getBasicQueryMap(lastUpdated));
        List<Event> events = EventsWrapper.getEvents(response);
        for(Event event: events) {
            event.setLocalEnrollmentId(enrollment.getLocalId());
        }

        saveResourceDataFromServer(ResourceType.EVENTS, enrollment.getUid(), dhisApi, events, TrackerController.getEventsByEnrollment(enrollment.getLocalId()), serverDateTime);
    }

    static void getEventDataFromServer(DhisApi dhisApi, String uid) throws APIException {
        DateTime lastUpdated = DateTimeManager.getInstance()
                .getLastUpdated(ResourceType.EVENTS, uid);
        DateTime serverDateTime = dhisApi.getSystemInfo()
                .getServerDate();

        Event event = updateEvent(dhisApi, uid, lastUpdated);

        DbOperation.save(event).getModel().save();
        DateTimeManager.getInstance()
                .setLastUpdated(ResourceType.EVENT, uid, serverDateTime);
    }

    private static Event updateEvent(DhisApi dhisApi, String uid, DateTime lastUpdated) throws APIException {
        final Map<String, String> QUERY_MAP_FULL = new HashMap<>();

        Event updatedEvent = dhisApi.getEvent(uid, QUERY_MAP_FULL);
        return updatedEvent;
    }
}


text:
var dimagisphere = (function() {
    var self = {};

    self.formData = {
        totalFormsByCountry: {},  // keeps track of totals per country
        recentFormsByCountry: {},  // keeps track of "active" per country - from the last second
        maxFormsByCountry: 0, // most forms that any single country has submitted
        totalFormsByDomain: {}, // keeps track of totals per domain
        domainToCountry: {}
    };

    self.addData = function (dataItem) {
        /**
         * Adds data to self.formData. Returns whether anything was done.
         */
        dimagisphere.formData.domainToCountry[dataItem.domain] = dataItem.country;
        var currentDomainCount = dimagisphere.formData.totalFormsByDomain[dataItem.domain] || 0;
        currentDomainCount += 1;
        dimagisphere.formData.totalFormsByDomain[dataItem.domain] = currentDomainCount;
        if (dataItem.country) {
            // update totals
            var currentCount = self.formData.totalFormsByCountry[dataItem.country] || 0;
            currentCount += 1;
            self.formData.totalFormsByCountry[dataItem.country] = currentCount;
            if (currentCount > self.formData.maxFormsByCountry) {
                self.formData.maxFormsByCountry = currentCount;
            }
            // update active
            var activeCount = self.formData.recentFormsByCountry[dataItem.country] || 0;
            self.formData.recentFormsByCountry[dataItem.country] = activeCount + 1;
            return true;
        }
        return false;
    };

    var FAKE_DOMAINS = {
        'dimagi': 'United States of America',
        'unicef': 'Nigeria',
        'mvp': 'Ethiopia',
        'dsi': 'India',
        'icds': 'India',
        'tula': 'Guatemala'
    };

    self.generateRandomItem = function () {
        // just return a random item from FAKE_DOMAINS
        // http://stackoverflow.com/questions/2532218/pick-random-property-from-a-javascript-object
        var domains = Object.keys(FAKE_DOMAINS);
        var randomDomain = domains[domains.length * Math.random() << 0];
        return {
            domain: randomDomain,
            country: FAKE_DOMAINS[randomDomain]
        };
    };
    return self;
})();


text:
import os

from django.test.html import parse_html
from crispy_forms_foundation.layout import (
    Layout, Row, Column, ButtonHolder, Submit
)

from tests.forms import BasicInputForm, BasicInputFormLayoutIncluded, AdvancedForm
# from tests.utils import write_output

def test_basic(output_test_path, render_output, rendered_template, helper, client):
    form = BasicInputForm()
    pack = helper.template_pack

    rendered = rendered_template(form, helper=helper)

    attempted = render_output(os.path.join(output_test_path, pack,
                                           "test_basic.html"))
    # write_output(output_test_path, pack, "test_basic.html", rendered)

    assert parse_html(attempted) == parse_html(rendered)

def test_layout(output_test_path, render_output, rendered_template, helper, client):
    form = BasicInputFormLayoutIncluded(helper=helper)
    pack = helper.template_pack

    rendered = rendered_template(form)

    attempted = render_output(os.path.join(output_test_path, pack,
                                           "test_layout.html"))
    # write_output(output_test_path, pack, "test_layout.html", rendered)

    assert parse_html(attempted) == parse_html(rendered)

def test_advanced(output_test_path, render_output, rendered_template, helper, client):
    form = AdvancedForm()
    pack = helper.template_pack

    helper.layout = Layout(
        Row(
            Column(
                'simple',
                css_class='six'
            ),
            Column(
                'opt_in',
                css_class='six'
            ),
        ),
        Row(
            Column(
                'longtext'
            ),
        ),
        Row(
            Column(
                ButtonHolder(Submit('submit', 'Submit')),
            ),
            css_class="large"
        ),
    )

    rendered = rendered_template(form, helper=helper)

    attempted = render_output(os.path.join(output_test_path, pack,
                                           "test_advanced.html"))
    # write_output(output_test_path, pack, "test_advanced.html", rendered)

    assert parse_html(attempted) == parse_html(rendered)


text:
The following objects will be created automatically by Tutum when deploying a node on AWS:

* An SSH keypair named `tutum-<uuid>`
* An EBS volume of type `gp2` with the size specified on the **Create new node cluster** wizard
* A security group named `tutum-default` with all ports open by default

By default, Tutum will try to deploy instances on EC2 using "EC2-Classic" or "EC2-VPC" using the default VPC for your account in the selected region. If there's no default VPC, Tutum will create the following additional objects:

* A VPC named `tutum-vpc` with the CIDR range `172.77.0.0/16`
* An internet gateway named `tutum-gateway` attached to `tutum-vpc`
* A subnet named `tutum-subnet` with the CIDR range `172.77.0.0/16` in `tutum-vpc`
* A route table named `tutum-route-table` in `tutum-vpc` associated with `tutum-gateway` and `tutum-subnet`
* A VPC security group named `tutum-vpc-default` with all ports open by default

In order for Tutum to detect these objects after they are created, it's important that **their names don't change**. Otherwise, Tutum will try to recreate them and fail due to conflicts.

## Can I modify the tutum-default security group?

You can change the ports opened in the `tutum-default` or `tutum-vpc-default` security groups as long as **ports 22/tcp (ssh), 2375/tcp (docker) and 48001/tcp (metrics)** are open. This is a temporary limitation that will be solved in the future.

## What happens if I restart a node in the AWS console?

After the node boots up, Tutum Agent will try contact our API and register itself with the new IP. We will update the DNS of the node and the containers on it to use the new IP automatically. The node should change its state from `Unreachable` to `Deployed`.

## Can I use an elastic IP for my nodes?

Yes, you can, but you will need to restart the Tutum Agent (or the host) for the changes to take effect in Tutum.

## Can I terminate a node from the AWS console?

If you created the node using Tutum and you terminate it in the AWS console, all data in that node will be destroyed, as the volume attached to it is set to destroy on node termination. If you haven't revoked your Tutum IAM user, we will detect the termination and will mark the node as `Terminated` on Tutum.

If you created the host yourself, added it to Tutum as a "Bring Your Own Node" and then terminated it, the node will stay in `Unreachable` state until you manually remove it.


text:
function LessonsModel() {
   var that = {};
   var currentLesson;

   that.getNumUnits = function() {
      return LessonsModel.unitNames.length;
   }

   that.getNumLessons = function(unit) {
      var lesson = 0;
      while (true) {
         var lessonName = 'Unit' + unit + 'Lesson' + (lesson + 1);
         var fn = window[lessonName];
         if(typeof fn != 'function') {
            break;
         }
         lesson += 1;
      }
      return lesson;
   }

   that.createLesson = function(progressModel, finishedCallback) {

      if (progressModel.isAtHomescreen()) return HomeScreen(progressModel, finishedCallback);

      var unitIndex = progressModel.getUnitIndex();
      var lessonIndex = progressModel.getLessonIndex();

      var lessonName = 'Unit' + unitIndex + 'Lesson' + lessonIndex;

      currentLesson = window[lessonName](finishedCallback);
      return currentLesson;
   }

   return that;
}

LessonsModel.milestoneUnits = [5, 9, 13];
LessonsModel.unitNames = [
   'Meet Karel',
   'Commands',
   'Programs',
   'Functions',
   'Newspaper',
   'Repeat',
   'Conditionals',
   'While',
   'If',
   'Color',
   'Random',
   'Midpoint',
]

function AddEqualCheck(ide1, ide2, action, callback) {
   return function() {
      action();
      var model1 = ide1.getModel();
      var model2 = ide2.getModel();
      if (model1.equals(model2)) {
         callback();
      }
   }
}

function BasicIdeLesson(world, starterCode, unitTests, goalImages, finishedCallback) {
   var that = {};
   that.elements = [];

   var IDE_WIDTH = 0.95;
   var IDE_LEFT = (1- IDE_WIDTH) / 2;
   var IDE_TOP = 0.05;
   var IDE_HEIGHT = 0.76;
   var GOAL_TOP = 0.83;
   var GOAL_HEIGHT = 0.15;
   var GOAL_WIDTH = GOAL_HEIGHT / Const.LEARN_ASPECT_RATIO;
   var GOAL_SPACING = GOAL_HEIGHT / 5;
   var GOAL_TEXT_WIDTH = 0.16;
   var GOAL_TEXT_HEIGHT = 0.08;
   var GOAL_TEXT_TOP = GOAL_TOP + (GOAL_HEIGHT - GOAL_TEXT_HEIGHT)/2;
   var RUN_WIDTH = 0.2;
   var RUN_HEIGHT = 0.1;
   var ITERS_SPACING = 0.03;

   var numGoal = Object.keys(goalImages).length
   var goalIconsWidth = GOAL_TEXT_WIDTH + numGoal * GOAL_WIDTH + (numGoal - 1) * GOAL_SPACING;
   var intersWidth = goalIconsWidth + RUN_WIDTH + ITERS_SPACING;
   var intersLeft = (1 - intersWidth) / 2;
   var goalLeft = intersLeft + RUN_WIDTH + ITERS_SPACING
   var dim = {
      left:IDE_LEFT,
      top:IDE_TOP,
      width:IDE_WIDTH,
      height:IDE_HEIGHT
   };

   var runDim = {
      left:intersLeft,
      top:GOAL_TOP + (GOAL_HEIGHT - RUN_HEIGHT)/2,
      width:RUN_WIDTH,
      height:RUN_HEIGHT
   };

   var ideSettings = {};
   ideSettings.buttonBar = false;
   ideSettings.world = world;
   ideSettings.readOnly = true;
   that.ide = KarelIdeElement(dim, 'centerAreaDiv', ideSettings);
   var runButton = TextButton(runDim, 'Run', 'centerAreaDiv', function() {
      that.ide.getIde().playButton(runUnitTests);
   });
   runButton.setHeightFraction(0.60);
   runButton.setDisabled();
   that.elements.push(that.ide);
   that.elements.push(runButton);

   var i = 0;

   var goalTextDim = {
      left:goalLeft,
      top:GOAL_TEXT_TOP,
      height:GOAL_TEXT_HEIGHT,
      width:GOAL_TEXT_WIDTH
   }
   var goalText = TextElement(goalTextDim, 'Goal: ', 'centerAreaDiv');
   that.elements.push(goalText);
   that.goalElements = [];
   for (input in goalImages) {
      var left = goalLeft;
      left += i * (GOAL_WIDTH + GOAL_SPACING) + GOAL_TEXT_WIDTH;
      var goalDim = {
         left:left,
         top:GOAL_TOP,
         width:GOAL_WIDTH,
         height:GOAL_HEIGHT
      };
      var start = input;
      var goal = goalImages[input];
      var goal = UnitTestElement(goalDim, start, goal, 'centerAreaDiv');
      that.elements.push(goal);
      that.goalElements.push(goal);
      i++;
   }

   function runUnitTests() {
      var initialList = [];
      for (test in unitTests) {
         initialList.push(test);
      }
      var index = 0;

      function runUnitTest(index, failed) {
         if (index == initialList.length) {
            if (!failed)finishedCallback();
            for (var i =0; i < that.goalElements.length; i++) {
               that.goalElements[i].clearTestResult();
            }
         } else {

            var startWorld = initialList[index];
            var endWorld = unitTests[startWorld];

            var unitTestCallback = function(passedCurrent) {
               var timeoutFn = function() {
                  runUnitTest(index + 1, failed || !passedCurrent);
               }
               that.goalElements[index].animateTestResults(passedCurrent);
               setTimeout(timeoutFn, 400);
            }

            that.ide.runUnitTest(startWorld, endWorld, unitTestCallback);

         }

      }
      runUnitTest(0, false);

   }

   function finished() {
      runButton.setEnabled();
	   that.ide.getEditor().focus();
   }

   function animateCode() {

      that.ide.animateCode(starterCode, finished);
   }

   setTimeout(animateCode, 800);

   return that;
}

function BasicIdeDemo(soln, world, starterCode, editable, finishedCallback) {
   var that = {};
   that.elements = [];

   var IDE_WIDTH = 0.95;
   var IDE_LEFT = (1- IDE_WIDTH) / 2;
   var IDE_TOP = 0.05;
   var IDE_HEIGHT = 0.75;
   var dim = {
      left:IDE_LEFT,
      top:IDE_TOP,
      width:IDE_WIDTH,
      height:IDE_HEIGHT
   };

   var runDim = {
      left:0.35,
      top:0.85,
      width:0.3,
      height:0.12
   };

   var ideSettings = {};
   ideSettings.buttonBar = false;
   ideSettings.world = world;
   ideSettings.readOnly = true;
   that.ide = KarelIdeElement(dim, 'centerAreaDiv', ideSettings);
   var runButton = TextButton(runDim, 'Run', 'centerAreaDiv', function() {
      that.ide.getIde().playButton(function() {

         finishedCallback();
      });
   });
   runButton.setHeightFraction(0.60);
   runButton.setDisabled();
   that.elements.push(that.ide);
   that.elements.push(runButton);

   function finished() {
      that.ide.getEditor().setReadOnly(true);
      runButton.setEnabled();
   }

   function animateCode() {

      that.ide.animateCode(starterCode, finished);
   }

   setTimeout(animateCode, 800);

   return that;
}

function Unit12Lesson1(finishedCallback) {
   var world = '7x7';
   var starterCode = 'midpointStarter.js';
   var unitTests = {
      '5x5':'5x5MidSoln',
      '7x7':'7x7MidSoln',
   };
   var goalImages = {
      'images/goals/start9.PNG' : 'images/goals/goal14.PNG',
      'images/goals/start8.PNG' : 'images/goals/goal15.PNG',
   };
   var that = BasicIdeLesson(world, starterCode, unitTests, goalImages, finishedCallback);
   return that;
}

function Unit11Lesson2(finishedCallback) {
   var solution = 'karelCode/randomLesson2.js';
   var world = '9x9';
   var starterCode = 'randomLesson2.js';
   var that = BasicIdeDemo(solution, world, starterCode, false, finishedCallback);
   return that;
}

function Unit11Lesson1(finishedCallback) {
   var solution = 'karelCode/randomLesson1.js';
   var world = '9x9';
   var starterCode = 'randomLesson1.js';
   var that = BasicIdeDemo(solution, world, starterCode, false, finishedCallback);
   return that;
}

function Unit10Lesson2(finishedCallback) {
   var solution = 'karelCode/colorLesson2.js';
   var world = '3x6';
   var starterCode = 'colorLesson2.js';
   var that = BasicIdeDemo(solution, world, starterCode, false, finishedCallback);
   return that;
}

function Unit10Lesson1(finishedCallback) {
   var solution = 'karelCode/colorLesson1.js';
   var world = '2x2';
   var starterCode = 'colorLesson1.js';
   var that = BasicIdeDemo(solution, world, starterCode, false, finishedCallback);
   return that;
}

function Unit9Lesson2(finishedCallback) {
   var world = 'column1';
   var starterCode = 'columnStarter.js';
   var unitTests = {
      'column1':'column1Soln',
      'column2':'column2Soln',
   };
   var goalImages = {
      'images/goals/start16.PNG' : 'images/goals/goal16.PNG',
      'images/goals/start17.PNG' : 'images/goals/goal17.PNG',
   };
   var that = BasicIdeLesson(world, starterCode, unitTests, goalImages, finishedCallback);
   return that;
}

function Unit9Lesson1(finishedCallback) {
   var solution = 'karelCode/ifelse.js';
   var worlds = [
      'invert',
   ]
   var index = Math.floor(Math.random() * worlds.length);
   var world = worlds[index];
   var starterCode = 'ifelse.js';
   var that = BasicIdeDemo(solution, world, starterCode, false, finishedCallback);
   return that;
}

function Unit8Lesson5(finishedCallback) {
   var world = '8x8';
   var starterCode = 'whileLesson5.js';
   var unitTests = {
      '5x5':'5x5FillSoln',
      '8x8':'8x8FillSoln',
   };
   var goalImages = {
      'images/goals/start9.PNG' : 'images/goals/goal12.PNG',
      'images/goals/start8.PNG' : 'images/goals/goal13.PNG',
   };
   var that = BasicIdeLesson(world, starterCode, unitTests, goalImages, finishedCallback);
   return that;
}

function Unit8Lesson4(finishedCallback) {
   var solution = 'karelCode/whileLesson4.js';
   var worlds = [
      'clean1',
   ]
   var index = Math.floor(Math.random() * worlds.length);
   var world = worlds[index];
   var starterCode = 'whileLesson4.js';
   var that = BasicIdeDemo(solution, world, starterCode, false, finishedCallback);
   return that;
}

function Unit8Lesson3(finishedCallback) {
   var world = '8x8';
   var starterCode = 'whileLesson3.js';
   var unitTests = {
      '5x5':'5x5BeeperLineSoln',
      '8x8':'8x8BeeperLineSoln',
   };
   var goalImages = {
      'images/goals/start9.PNG' : 'images/goals/goal10.PNG',
      'images/goals/start8.PNG' : 'images/goals/goal11.PNG',
   };
   var that = BasicIdeLesson(world, starterCode, unitTests, goalImages, finishedCallback);
   return that;
}

function Unit8Lesson2(finishedCallback) {
   var world = '8x8';
   var starterCode = 'whileLesson2.js';
   var unitTests = {
      '5x5':'5x5WallSoln',
      '8x8':'8x8WallSoln',
   };
   var goalImages = {
      'images/goals/start9.PNG' : 'images/goals/goal9.PNG',
      'images/goals/start8.PNG' : 'images/goals/goal8.PNG',
   };
   var that = BasicIdeLesson(world, starterCode, unitTests, goalImages, finishedCallback);
   return that;
}

function Unit8Lesson1(finishedCallback) {
   var solution = 'karelCode/whileLesson1.js';
   var worlds = [
      'while1',
      'while2',
      'while3'
   ]
   var index = Math.floor(Math.random() * worlds.length);
   var world = worlds[index];
   var starterCode = 'whileLesson1.js';
   var that = BasicIdeDemo(solution, world, starterCode, false, finishedCallback);
   return that;
}

function Unit7Lesson3(finishedCallback) {
   var buttonSrcs = [
      './images/puzzles/image5.png',
      './images/puzzles/image6.png',
      './images/puzzles/image7.png',
      './images/puzzles/image8.png',
   ];
   var labels = [
      'notFacingSouth()',
      'frontIsBlocked()',
      'noBeepersPresent()',
      'rightIsClear()'
   ];
   return PictureLesson(buttonSrcs, labels, finishedCallback, false);
}

function Unit7Lesson2(finishedCallback) {
   var buttonSrcs = [
      './images/puzzles/image1.png',
      './images/puzzles/image2.png',
      './images/puzzles/image3.png',
      './images/puzzles/image4.png',
   ];
   var labels = [
      'frontIsClear()',
      'notFacingEast()',
      'leftIsClear()',
      'beepersPresent()'
   ];
   return PictureLesson(buttonSrcs, labels, finishedCallback, false);
}

function Unit7Lesson1(finishedCallback) {
   var buttonSrcs = [
      './images/northIcon.png',
      './images/southIcon.png',
      './images/eastIcon.png',
      './images/westIcon.png',
   ];
   var labels = [
      'facingNorth()',
      'facingSouth()',
      'facingEast()',
      'facingWest()'
   ];
   return PictureLesson(buttonSrcs, labels, finishedCallback, false);
}

function Unit6Lesson2(finishedCallback) {

   var world = '3x3';
   var starterCode = 'repeatLesson2.js';
   var unitTests = {
      '3x3':'putFifty',
   };
   var goalImages = {
      'images/goals/start7.PNG' : 'images/goals/goal7.PNG',
   };
   var that = BasicIdeLesson(world, starterCode, unitTests, goalImages, finishedCallback);
   return that;
}

function Unit6Lesson1(finishedCallback) {
   var solution = 'karelCode/repeatLesson1.js';
   var world = '3x3';
   var starterCode = 'repeatLesson1.js';
   var that = BasicIdeDemo(solution, world, starterCode, false, finishedCallback);
   return that;
}

function Unit5Lesson1(finishedCallback) {
   var world = 'collectNewspaper';
   var starterCode = 'newspaperStarter.js';
   var unitTests = {
      'collectNewspaper':'collectNewspaperSoln',
   };
   var goalImages = {
      'images/goals/start6.PNG' : 'images/goals/goal6.PNG',
   };
   var that = BasicIdeLesson(world, starterCode, unitTests, goalImages, finishedCallback);
   return that;
}

function Unit4Lesson2(finishedCallback) {
   var world = '2x2';
   var starterCode = 'fnsLesson2Starter.js';
   var unitTests = {
      '2x2':'turnArounds',
   };
   var goalImages = {
      'images/goals/start5.PNG' : 'images/goals/goal5.PNG',
   };
   var that = BasicIdeLesson(world, starterCode, unitTests, goalImages, finishedCallback);
   return that;
}

function Unit4Lesson1(finishedCallback) {
   var solution = 'karelCode/fnsLesson1Starter.js';
   var world = 'turnRight';
   var starterCode = 'fnsLesson1Starter.js';
   var that = BasicIdeDemo(solution, world, starterCode, false, finishedCallback);
   return that;
}

function Unit3Lesson6(finishedCallback) {
   var world = 'pickBeeper';
   var starterCode = 'runLesson6Starter.js';
   var unitTests = {
      'pickBeeper':'pickBeepers',
   };
   var goalImages = {
      'images/goals/start4.PNG' : 'images/goals/goal4.PNG',
   };
   var that = BasicIdeLesson(world, starterCode, unitTests, goalImages, finishedCallback);
   return that;
}

function Unit3Lesson5(finishedCallback) {
   var world = 'putBeeper';
   var starterCode = 'runLesson5Starter.js';
   var unitTests = {
      'putBeeper':'putBeepers',
   };
   var goalImages = {
      'images/goals/start3.PNG' : 'images/goals/goal3.PNG',
   };
   var that = BasicIdeLesson(world, starterCode, unitTests, goalImages, finishedCallback);
   return that;
}

function Unit3Lesson4(finishedCallback) {
   var world = 'singleStep';
   var starterCode = 'runLesson4Starter.js';
   var unitTests = {
      'singleStep':'singleSteps',
   };
   var goalImages = {
      'images/goals/start2.PNG' : 'images/goals/goal2.PNG',
   };
   var that = BasicIdeLesson(world, starterCode, unitTests, goalImages, finishedCallback);
   return that;
}

function Unit3Lesson3(finishedCallback) {
   var solution = 'karelCode/unit2Lesson3Soln.js';
   var world = '4x4';
   var starterCode = 'runLesson3Starter.js';
   var unitTests = {
      '4x4':'4x4s',
   };
   var goalImages = {
      'images/goals/start1.PNG' : 'images/goals/goal1.PNG',
   };
   var that = BasicIdeLesson(world, starterCode, unitTests, goalImages, finishedCallback);
   return that;
}

function Unit3Lesson2(finishedCallback) {
   var solution = 'karelCode/unit2Lesson2Soln.js';
   var world = '4x4';
   var starterCode = 'runLesson2Starter.js';
   var that = BasicIdeDemo(solution, world, starterCode, false, finishedCallback);
   return that;
}

function Unit3Lesson1(finishedCallback) {
   var solution = 'karelCode/unit2Lesson1Soln.js';
   var world = '4x4';
   var starterCode = 'runLesson1Starter.js';
   var that = BasicIdeDemo(solution, world, starterCode, false, finishedCallback);
   return that;
}

function Unit2Lesson8(finishedCallback) {
   var buttons = {
       move : true,
	   turnLeft : true,
	   putBeeper : true,
	   pickBeeper : true
   };
   return ButtonLesson(buttons, 'ledge', 'karelCode/unit1Lesson5Soln.js', finishedCallback);
}

function Unit2Lesson7(finishedCallback) {
   var buttons = {
       move : true,
	   turnLeft : true,
	   putBeeper : true,
	   pickBeeper : true
   };
   return ButtonLesson(buttons, '1x3Beeper', 'karelCode/moveAndPickSln.js', finishedCallback);
}

function Unit2Lesson6(finishedCallback) {
   var buttons = {
       move : true,
	   turnLeft : true,
	   putBeeper : true,
	   pickBeeper : true
   };
   return ButtonLesson(buttons, '1x3', 'karelCode/unit1Lesson4Soln.js', finishedCallback);
}

function Unit2Lesson5(finishedCallback) {
   var buttons = {
       move : false,
	   turnLeft : false,
	   putBeeper : true,
	   pickBeeper : false
   };
   return ButtonLesson(buttons, '1x1', 'karelCode/simplePutSln.js', finishedCallback);
}

function Unit2Lesson4(finishedCallback) {
   var buttons = {
       move : true,
	   turnLeft : true,
	   putBeeper : false,
	   pickBeeper : false
   };
   return ButtonLesson(buttons, 'turnLeft', 'karelCode/unit1Lesson3Soln.js', finishedCallback);
}

function Unit2Lesson3(finishedCallback) {
   var buttons = {
       move : false,
	   turnLeft : true,
	   putBeeper : false,
	   pickBeeper : false
   };
   return ButtonLesson(buttons, '1x1', 'karelCode/simpleTurnLeftSln.js', finishedCallback);
}

function Unit2Lesson2(finishedCallback) {
   var buttons = {
       move : true,
	   turnLeft : false,
	   putBeeper : false,
	   pickBeeper : false
   };
   return ButtonLesson(buttons, 'move', 'karelCode/unit1Lesson2Soln.js', finishedCallback);
}

function Unit2Lesson1(finishedCallback) {
   var buttons = {
       move : true,
	   turnLeft : false,
	   putBeeper : false,
	   pickBeeper : false
   };
   return ButtonLesson(buttons, '2x2', 'karelCode/simpleMoveSln.js', finishedCallback);
}

function ButtonLesson(buttonMap, world, solution, finishedCallback) {
   var that = {};

   var dynamicDim = {left:0.515, top:0.2, width:0.3, height:0.3};
   var staticDim = {left:0.185, top:0.2, width:0.3, height:0.3};
   var staticKarel = KarelStaticCanvasElement(staticDim,world);
   var dynamicKarel = KarelStaticCanvasElement(dynamicDim,world);
   var textDim1 = {left:0.185, top:0.1, width:0.3, height:0.074};
   var textDim2 = {left:0.515, top:0.1, width:0.3, height:0.074};
   var buttonDim1 = {left:0.35, top:0.7, width:0.3, height:0.12};
   var ide = dynamicKarel.getIde();

   that.elements = [];
   that.elements.push(staticKarel);
   that.elements.push(dynamicKarel);
   that.elements.push(TextBox(textDim1, 'Goal'));
   that.elements.push(TextBox(textDim2, 'World'));

   var actionMap = {};
   actionMap.move = AddEqualCheck(ide, staticKarel.getIde(), ide.stepMove, finishedCallback);
   actionMap.turnLeft = AddEqualCheck(ide, staticKarel.getIde(), ide.stepTurnLeft, finishedCallback);
   actionMap.putBeeper = AddEqualCheck(ide, staticKarel.getIde(), ide.stepPutBeeper, finishedCallback);
   actionMap.pickBeeper = AddEqualCheck(ide, staticKarel.getIde(), ide.stepPickBeeper, finishedCallback);

   var textMap = {};
   textMap.move = 'move();';
   textMap.turnLeft = 'turnLeft();';
   textMap.putBeeper = 'putBeeper();';
   textMap.pickBeeper = 'pickBeeper();';

   var buttonDim = [];
   buttonDim.push({left:0.185, top:0.65, width:0.3, height:0.12});
   buttonDim.push({left:0.515, top:0.65, width:0.3, height:0.12});
   buttonDim.push({left:0.185, top:0.8, width:0.3, height:0.12});
   buttonDim.push({left:0.515, top:0.8, width:0.3, height:0.12});

   var numButtons = 0;
   for (key in buttonMap) {
      if (buttonMap[key]) numButtons++;
   }

   that.buttons = [];
   var dimIndex = 0;
   for (key in buttonMap) {
      if (!buttonMap[key]) continue;
      var dim = buttonDim[dimIndex];
	  if (dimIndex == numButtons - 1 && numButtons % 2 == 1) {
         dim.left = (0.185 + 0.515) / 2 ;
	  }
	  var text = textMap[key];
	  var action = actionMap[key];
      that.buttons.push(KarelCommandButton(dim, text, action));
	  dimIndex++;
   }

   for (var i = 0; i < that.buttons.length; i++ ) {
      that.elements.push(that.buttons[i]);
   }

   function animationFinished() {
      for(var i = 0; i < that.buttons.length; i++) {
         that.buttons[i].setEnabled();
      }
   }

   function startAnimation() {
      for(var i = 0; i < that.buttons.length; i++) {
         that.buttons[i].setDisabled();
      }
      staticKarel.animate(solution, animationFinished);
   }

   setTimeout(startAnimation, 1500);

   return that;
}

function PictureDemo(buttonSrcs, labels, finishedCallback) {
   var that = {};
   var textDim = {left:0.342, top:0.014, width:0.316, height:0.074};

   var positions = [
      {left:0.169, top:0.11, width:0.316, height:0.42},
      {left:0.515, top:0.11, width:0.316, height:0.42},
      {left:0.169, top:0.56, width:0.316, height:0.42},
      {left:0.515, top:0.56, width:0.316, height:0.42}
   ];

   that.elements = [];
   that.imageButtons = [];
   for (var i = 0; i < buttonSrcs.length; i++) {
	 var callback = function(){};
	 var button = ImageButton(positions[i], buttonSrcs[i], callback, false);
	 that.elements.push(button);
	 that.imageButtons.push(button);
  }

  that.demoImage = function() {
     if (that.imageIndex == that.imageButtons.length) {
	    finishedCallback();
		return;
     }
	 var labelText = labels[that.imageIndex];
	 var labelDim = that.imageButtons[that.imageIndex].getLabelSlotDim();
     var label = TextBox(labelDim, labelText);
     label.setTextHeightFraction(0.6);
	 label.resize();
     that.elements.push(label);
	 $(label.div).fadeIn(500);
	 that.imageIndex += 1;
	 setTimeout(that.demoImage, 2000);
  }

  that.imageIndex = 0;
  setTimeout(that.demoImage, 500);

  return that;
}

function PictureLesson(buttonSrcs, labels, finishedCallback, demo) {
   var that = {};
   var textDim = {left:0.342, top:0.014, width:0.316, height:0.074};

   var positions = [
      {left:0.169, top:0.11, width:0.316, height:0.42},
      {left:0.515, top:0.11, width:0.316, height:0.42},
      {left:0.169, top:0.56, width:0.316, height:0.42},
      {left:0.515, top:0.56, width:0.316, height:0.42}
   ];

   that.generatePuzzle = function() {
      var orderMap = [];
      var indicies = [];
      for (var i = 0; i < buttonSrcs.length; i++){
         indicies.push(i);
      }
      for (var i = 0; i < buttonSrcs.length; i++) {
         var maxIndex = indicies.length;
         var randomIndex = Math.floor(Math.random()*maxIndex);
         orderMap.push(indicies[randomIndex]);
         indicies.splice(randomIndex, 1);
      }

      that.elements = [];
	  that.imageButtons = [];
      for (var i = 0; i < buttonSrcs.length; i++) {
         var buttonIndex = orderMap.indexOf(i);
         var callback;
         switch(i) {
            case 0: callback = function(){that.buttonClicked(0)}; break;
            case 1: callback = function(){that.buttonClicked(1)}; break;
            case 2: callback = function(){that.buttonClicked(2)}; break;
            case 3: callback = function(){that.buttonClicked(3)}; break;
         }
         var button = ImageButton(positions[i], buttonSrcs[buttonIndex], callback, true);
         that.elements.push(button);
		 that.imageButtons.push(button);
      }

      that.answerIndex = orderMap[that.questionIndex];
      var questionLabel = labels[that.questionIndex];
	  var labelDim = textDim;
      that.questionBox = TextBox(labelDim, questionLabel);
      that.questionBox.setTextHeightFraction(0.6);
      that.elements.push(that.questionBox);
   }

   that.buttonClicked = function(index) {
      if (index == that.answerIndex) {
         var button = that.elements[index];
         button.animateCorrect(that.questionBox, that.nextPuzzle);
      } else {
         that.elements[index].animateIncorrect();
      }
   }

   that.nextPuzzle = function() {
      function finishedFadeOut() {
         for (var i = 0; i < that.elements.length; i++) {
            that.elements[i].deleteDiv();

         }
         that.generatePuzzle();
         for (var i =0; i < that.elements.length; i++) {
            that.elements[i].resize();
            if (that.elements[i].innerImage != undefined) {
               $(that.elements[i].innerImage.div).fadeIn(600);
            }
            $(that.elements[i].div).fadeIn(600);
         }
      }

      that.questionIndex += 1;
      if (that.questionIndex >= buttonSrcs.length) {
         finishedCallback();
      } else {
         for (var i = 0; i < that.elements.length; i++) {
            if (that.elements[i].innerImage != undefined) {
               $(that.elements[i].innerImage.div).fadeOut(600);
            }
            $(that.elements[i].div).fadeOut(600);
         }
         setTimeout(finishedFadeOut, 600);
      }
   }

   that.questionIndex = 0;
   that.generatePuzzle();

   return that;
}

function Unit1Lesson2(finishedCallback) {
   var buttonSrcs = [
      './images/karelIcon.png',
      './images/beeperIcon.png',
      './images/world.png',
      './images/wall.png',
   ];
   var labels = [
      'Karel',
      'Beeper',
      'World',
      'Wall'
   ];
   return PictureLesson(buttonSrcs, labels, finishedCallback, false);
}

function Unit1Lesson1(finishedCallback) {
   var buttonSrcs = [
      './images/karelIcon.png',
      './images/beeperIcon.png',
      './images/world.png',
      './images/wall.png',
   ];
   var labels = [
      'Karel',
      'Beeper',
      'World',
      'Wall'
   ];
   return PictureDemo(buttonSrcs, labels, finishedCallback, true);
}


text:
/**
 * Typescript definition tests for d3/d3-collection module
 *
 * Note: These tests are intended to test the definitions only
 * in the sense of typing and call signature consistency. They
 * are not intended as functional tests.
 */

import * as d3Collection from 'd3-collection';
import { ascending } from 'd3-array';

// Preparatory steps --------------------------------------------------------------

const keyValueObj = {
    a: 'test',
    b: 123,
    c: [true, true, false]
};

const keyValueObj2 = {
    a: 'test',
    b: 'same',
    c: 'type'
};

let stringArray: string[];
let anyArray: any[];
let stringKVArray: Array<{ key: string, value: string }>;
let anyKVArray: Array<{ key: string, value: any }>;

let num: number;
let booleanFlag: boolean;

// ---------------------------------------------------------------------
// Test Objects
// ---------------------------------------------------------------------

// test keys(...) signatures ------------------------------------------------------

stringArray = d3Collection.keys(keyValueObj);
stringArray = d3Collection.keys([0, 1, 2]);

stringArray = d3Collection.keys(document); // purely for the fun of it

// test values(...) signatures ------------------------------------------------------

anyArray = d3Collection.values(keyValueObj);
// stringArray = d3Collection.values(keyValueObj); // test fails, as values in keyValueObj are not all strings

stringArray = d3Collection.values(keyValueObj2);
stringArray = d3Collection.values<string>(keyValueObj2);
// stringArray = d3Collection.values<string>(keyValueObj); // test fails, as values in keyValueObj do not meet generic constraint
stringArray = d3Collection.values(['1', '2']);

anyArray = d3Collection.values(document); // purely for the fun of it

// test entries(...) signatures ------------------------------------------------------

anyKVArray = d3Collection.entries(keyValueObj);
// stringKVArray = d3Collection.entries(keyValueObj); // test fails, as values in keyValueObj are not all strings

stringKVArray = d3Collection.entries(keyValueObj2);
stringKVArray = d3Collection.entries<string>(keyValueObj2);
// stringKVArray = d3Collection.entries<string>(keyValueObj); // test fails, as values in keyValueObj do not meet generic constraint

stringKVArray = d3Collection.entries(['1', '2']);
anyKVArray = d3Collection.entries(document); // purely for the fun of it

// ---------------------------------------------------------------------
// map / Map
// ---------------------------------------------------------------------

interface TestObject {
    name: string;
    val: number;
}

let testObjectMaybe: TestObject | undefined;
let testObjArray: TestObject[];
let testObjKVArray: Array<{ key: string, value: TestObject }>;

// Create Map ========================================================

let basicMap: d3Collection.Map<string>;
let anyMap: d3Collection.Map<any>;
anyMap = d3Collection.map(); // empty map
basicMap = d3Collection.map<string>(); // empty map

// from array with accessor without accessor
basicMap = d3Collection.map(['foo', 'bar']); // map with key-value pairs { '0': 'foo' } and { '1': 'bar'}

// from array with accessor
let testObjMap: d3Collection.Map<TestObject>;
testObjMap = d3Collection.map<TestObject>([{ name: 'foo', val: 10 }, { name: 'bar', val: 42 }], (value, i, array) => {
    return value.name;
});

// from existing map
basicMap = d3Collection.map(basicMap);
// basicMap = d3Collection.map(testObjMap); // fails, as maps have different value type

// from object
let objectMap: d3Collection.Map<any>;
objectMap = d3Collection.map(keyValueObj);

let objectMap2: d3Collection.Map<string>;
objectMap2 = d3Collection.map(keyValueObj2);

// Use Map ===========================================================

// has(...) ------------------------------------------------------------

booleanFlag = basicMap.has('foo');

// get(...) ------------------------------------------------------------

testObjectMaybe = testObjMap.get('foo');

// set(...) ------------------------------------------------------------

basicMap = basicMap.set('foo', '42');

// remove(...) ---------------------------------------------------------

booleanFlag = testObjMap.remove('bar');

// clear() -------------------------------------------------------------

basicMap.clear();

// keys() --------------------------------------------------------------

stringArray = testObjMap.keys();

// values() ------------------------------------------------------------

testObjArray = testObjMap.values();

// entries() -----------------------------------------------------------

testObjKVArray = testObjMap.entries();

// each() --------------------------------------------------------------

testObjMap.each((value, key, map) => {
    const v: TestObject = value;
    const k: string = key;
    const m: d3Collection.Map<TestObject> = map;
    console.log(v.val);
});

// empty() -------------------------------------------------------------

booleanFlag = testObjMap.empty();

// size() --------------------------------------------------------------

num = testObjMap.size();

// ---------------------------------------------------------------------
// set / Set
// ---------------------------------------------------------------------

// Create Set ========================================================

// TODO:
// - from set
// - from array with/without accessor

let basicSet: d3Collection.Set;
basicSet = d3Collection.set(); // empty set

// from array without accessor
basicSet = d3Collection.set(['foo', 'bar', 42]); // last element is coerced

// from array without accessor
basicSet = d3Collection.set(testObjArray, (value, index, array) => {
    const v: TestObject = value;
    const i: number = index;
    const a: TestObject[] = array;
    return v.name;
});

// from existing set

basicSet = d3Collection.set(basicSet);

// Use Set ===========================================================

// has(...) ------------------------------------------------------------

booleanFlag = basicSet.has('foo');

// add(...) ------------------------------------------------------------

basicSet = basicSet
    .add('foo')
    .add('bar')
    .add(42); // will be coerced to string

// remove(...) ---------------------------------------------------------

booleanFlag = basicSet.remove('bar');
booleanFlag = basicSet.remove(42);

// clear() -------------------------------------------------------------

basicSet.clear();

// values() ------------------------------------------------------------

stringArray = basicSet.values();

// each() --------------------------------------------------------------

basicSet.each((value, valueRepeat, set) => {
    const v: string = value;
    const vr: string = valueRepeat;
    const s: d3Collection.Set = set;
    console.log(v);
});

// empty() -------------------------------------------------------------

booleanFlag = basicSet.empty();

// size() --------------------------------------------------------------

num = basicSet.size();

// ---------------------------------------------------------------------
// nest / Nest
// ---------------------------------------------------------------------

interface Yield {
    yield: number;
    variety: string;
    year: number;
    site: string;
}

const raw: Yield[] = [
    { yield: 27.00, variety: 'Manchuria', year: 1931, site: 'University Farm' },
    { yield: 48.87, variety: 'Manchuria', year: 1931, site: 'Waseca' },
    { yield: 27.43, variety: 'Manchuria', year: 1931, site: 'Morris' },
    { yield: 43.07, variety: 'Glabron', year: 1931, site: 'University Farm' },
    { yield: 55.20, variety: 'Glabron', year: 1931, site: 'Waseca' },
    { yield: 26.00, variety: 'Manchuria', year: 1932, site: 'University Farm' },
    { yield: 47.87, variety: 'Manchuria', year: 1932, site: 'Waseca' },
    { yield: 26.43, variety: 'Manchuria', year: 1932, site: 'Morris' },
    { yield: 42.07, variety: 'Glabron', year: 1932, site: 'University Farm' },
    { yield: 54.20, variety: 'Glabron', year: 1932, site: 'Waseca' }
];

// Create Nest ========================================================

let nestL2: d3Collection.Nest<Yield, undefined>;
nestL2 = d3Collection.nest<Yield>();

let nestL1Rollup: d3Collection.Nest<Yield, number>;
nestL1Rollup = d3Collection.nest<Yield, number>();

// Configure Nest =====================================================

// key(...) and sortKeys(...) -----------------------------------------

nestL2 = nestL2
    .key(d => {
        return d.year.toString();
    });

// with 2nd key with sortkey(...)
nestL2 = nestL2
    .key(d => {
        return d.variety;
    })
    .sortKeys(ascending);

nestL1Rollup = nestL1Rollup
    .key(d => {
        return d.year.toString();
    });

// sortValues(...) ----------------------------------------------------

nestL2 = nestL2
    .sortValues((a, b) => {
        const val1: Yield = a; // data type Yield
        const val2: Yield = b; // data type Yield
        return a.yield - b.yield;
    });

// rollup(...) --------------------------------------------------------

nestL1Rollup = nestL1Rollup
    .rollup(values => {
        const vs: Yield[] = values; // correct data array type
        return vs.length;
    });

// Use Nest ===========================================================

// map(...) -----------------------------------------------------------

type TestL2NestedMap = d3Collection.Map<d3Collection.Map<Yield[]>>;

type TestL1NestedMapRollup = d3Collection.Map<number>;

let testL2NestedMap: TestL2NestedMap;
let testL1NestedMapRollup: TestL1NestedMapRollup;

testL2NestedMap = nestL2.map(raw);

num = testL2NestedMap.get('1931')!.get('Manchuria')![0].yield; // use existence assertion with care for access chain to leaf property

testL1NestedMapRollup = nestL1Rollup.map(raw);

num = testL1NestedMapRollup.get('1931')!; // get rollup value (use existence assertion with care)

// object(...) --------------------------------------------------------

interface TestL2NestedObject {
    [keyL1: string]: {
        [keyL2: string]: Yield[];
    };
}

interface TestL1NestedObjectRollup {
    [keyL1: string]: number;
}

let testL2NestedObject: TestL2NestedObject;
let testL1NestedObjectRollup: TestL1NestedObjectRollup;

testL2NestedObject = nestL2.object(raw);

num = testL2NestedObject['1931']['Manchuria'][0].yield; // access chain to leaf property

testL1NestedObjectRollup = nestL1Rollup.object(raw);

num = testL1NestedObjectRollup['1931']; // get rollup value

// entries(...) -------------------------------------------------------

type TestL2NestedArray = Array<{
    key: string;
    values: Array<{
        key: string;
        values: Yield[];
    }>
}>;

type TestL1NestedArrayRollup = Array<{
    key: string;
    value?: number | undefined; // conservatively allow for value to be undefined
}>;

let testL2NestedArray: TestL2NestedArray;
let testL1NestedArrayRollup: TestL1NestedArrayRollup;

testL2NestedArray = nestL2.entries(raw);

num = testL2NestedArray[0].values[0].values[0].yield; // access chain to leaf property

testL1NestedArrayRollup = nestL1Rollup.entries(raw);

num = testL1NestedArrayRollup[0].value!; // get rollup value use existence assertion with care


text:
All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

## [0.5.2] - 28 Sep 2021

- relax telemetry version [#26]

## [0.5.1] - 24 April 2021

- add connect_timeout option [#24]

## [0.5.0] - 10 Dec 2019

- add telemetry support [#23]

## [0.4.6] - 8 Aug 2019

- fix dialyzer spec [#20]

## [0.4.3] - 26 Sep 2017

- child_spec
- fix warnings and format code

## [0.4.2] - 14 Sep 2017

- add support for dynamic namespace [#6]
- update poison version [#9]

## [0.4.1] - 1 April 2017

- bug fix

## [0.4.0] - 20 Mar 2017

### New
- Uses a separate process to read response from the server. This would
  lead to increased throughput if same connection was accessed from
  different process concurrently.

### Breaking
- Removed Memcache.connection_pid. It was a mistake to expose the
  underlying connection id, as it creates problems for future
  additions like pool and cluster.

## [0.3.0] - 25 Feb 2017

### New
- add support for multi set & get

### Breaking
- changed the returned type of stat from HashDict to map
- dropped support for 1.1

## [0.2.1] - 25 July 2016

### New
- coder

## [0.2.0] - 23 July 2016

### New
- Plain auth.
- namespace and default ttl

### Breaking
- pid can't be used interchangeably between Memcache and
  Memcache.Connection
- Removed Memcache.execute. Get connection pid using
  Memcache.connection_pid and interact with the Memcache.Connection
  directly.


text:
#ifndef _MRVL_QOS_H_
#define _MRVL_QOS_H_

#include <rte_common.h>

#include "mrvl_ethdev.h"

/** Code Points per Traffic Class. Equals max(DSCP, PCP). */
#define MRVL_CP_PER_TC (64)

/** Value used as "unknown". */
#define MRVL_UNKNOWN_TC (0xFF)

/* config. */
struct mrvl_cfg {
	struct  {
		struct pp2_parse_udfs	prs_udfs;
	} pp2_cfg;
	struct port_cfg {
		enum pp2_ppio_eth_start_hdr eth_start_hdr;
		int rate_limit_enable;
		struct pp2_ppio_rate_limit_params rate_limit_params;
		struct {
			uint8_t inq[MRVL_PP2_RXQ_MAX];
			uint8_t dscp[MRVL_CP_PER_TC];
			uint8_t pcp[MRVL_CP_PER_TC];
			uint8_t inqs;
			uint8_t dscps;
			uint8_t pcps;
			enum pp2_ppio_color color;
		} tc[MRVL_PP2_TC_MAX];
		struct {
			enum pp2_ppio_outq_sched_mode sched_mode;
			uint8_t weight;
			int rate_limit_enable;
			struct pp2_ppio_rate_limit_params rate_limit_params;
		} outq[MRVL_PP2_RXQ_MAX];
		enum pp2_cls_qos_tbl_type mapping_priority;
		uint16_t inqs;
		uint16_t outqs;
		uint8_t default_tc;
		uint8_t use_qos_global_defaults;
		struct pp2_cls_plcr_params policer_params;
		uint8_t setup_policer;
		uint8_t forward_bad_frames;
		uint32_t fill_bpool_buffs;
	} port[RTE_MAX_ETHPORTS];
};

/** Global configuration. */
extern struct mrvl_cfg *mrvl_cfg;

/**
 * Parse configuration - rte_kvargs_process handler.
 *
 * Opens configuration file and parses its content.
 *
 * @param key Unused.
 * @param path Path to config file.
 * @param extra_args Pointer to configuration structure.
 * @returns 0 in case of success, exits otherwise.
 */
int
mrvl_get_cfg(const char *key __rte_unused, const char *path, void *extra_args);

/**
 * Configure RX Queues in a given port.
 *
 * Sets up RX queues, their Traffic Classes and DPDK rxq->(TC,inq) mapping.
 *
 * @param priv Port's private data
 * @param portid DPDK port ID
 * @param max_queues Maximum number of queues to configure.
 * @returns 0 in case of success, negative value otherwise.
 */
int
mrvl_configure_rxqs(struct mrvl_priv *priv, uint16_t portid,
		    uint16_t max_queues);

/**
 * Configure TX Queues in a given port.
 *
 * Sets up TX queues egress scheduler and limiter.
 *
 * @param priv Port's private data
 * @param portid DPDK port ID
 * @param max_queues Maximum number of queues to configure.
 * @returns 0 in case of success, negative value otherwise.
 */
int
mrvl_configure_txqs(struct mrvl_priv *priv, uint16_t portid,
		    uint16_t max_queues);

/**
 * Start QoS mapping.
 *
 * Finalize QoS table configuration and initialize it in SDK. It can be done
 * only after port is started, so we have a valid ppio reference.
 *
 * @param priv Port's private (configuration) data.
 * @returns 0 in case of success, exits otherwise.
 */
int
mrvl_start_qos_mapping(struct mrvl_priv *priv);

#endif /* _MRVL_QOS_H_ */


text:
namespace Firestorm.Rest.Web
{
    /// <summary>
    /// The body of a request from a Firestorm API endpoint.
    /// The can be either a collection, item or scalar value.
    /// </summary>
    /// <remarks>
    /// The inheritance hierarchy here is very similar to <see cref="IRestResource"/>.
    /// </remarks>
    public abstract class ResourceBody
    {
        internal ResourceBody()
        { }

        public abstract ResourceType ResourceType { get; }

        public abstract object GetObject();
    }
}


text:
package org.elasticsearch.painless.node;

import org.elasticsearch.painless.Definition;
import org.elasticsearch.painless.Definition.Method;
import org.elasticsearch.painless.Definition.MethodKey;
import org.elasticsearch.painless.Globals;
import org.elasticsearch.painless.Locals;
import org.elasticsearch.painless.Location;
import org.elasticsearch.painless.MethodWriter;

import java.util.List;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.painless.WriterConstants.CLASS_TYPE;

/**
 * Represents a user-defined call.
 */
public final class ECallLocal extends AExpression {

    private final String name;
    private final List<AExpression> arguments;

    private Method method = null;

    public ECallLocal(Location location, String name, List<AExpression> arguments) {
        super(location);

        this.name = Objects.requireNonNull(name);
        this.arguments = Objects.requireNonNull(arguments);
    }

    @Override
    void extractVariables(Set<String> variables) {
        for (AExpression argument : arguments) {
            argument.extractVariables(variables);
        }
    }

    @Override
    void analyze(Locals locals) {
        MethodKey methodKey = new MethodKey(name, arguments.size());
        method = locals.getMethod(methodKey);

        if (method == null) {
            throw createError(new IllegalArgumentException("Unknown call [" + name + "] with [" + arguments.size() + "] arguments."));
        }

        for (int argument = 0; argument < arguments.size(); ++argument) {
            AExpression expression = arguments.get(argument);

            expression.expected = method.arguments.get(argument);
            expression.internal = true;
            expression.analyze(locals);
            arguments.set(argument, expression.cast(locals));
        }

        statement = true;
        actual = method.rtn;
    }

    @Override
    void write(MethodWriter writer, Globals globals) {
        writer.writeDebugInfo(location);

        for (AExpression argument : arguments) {
            argument.write(writer, globals);
        }

        writer.invokeStatic(CLASS_TYPE, method.method);
    }

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


text:
'use strict';

angular.module('dashboard')
    .config(['$stateProvider', '$urlRouterProvider', 'RoutePermissionsProvider',
        function ($stateProvider, $urlRouterProvider, RoutePermissionsProvider) {

            $stateProvider.
                //Main dashboard route
                state('dashboard', {
                    url: '/dashboard',
                    templateUrl: 'app/modules/dashboard/views/dashboard.html',
                    controller: 'DashboardMainController',
                    controllerAs: 'dashboardCtrl',
                    resolve: RoutePermissionsProvider.isAdmin

                    // TODO: Add the abstract property if the main dashboard view will be skipped to prevent
                    //abstract: true
                })

                //Products routes
                .state('dashboard.products', {
                    url: '/products',
                    templateUrl: 'app/modules/dashboard/views/products.html',
                    controller: 'ProductsDashboardController',
                    controllerAs: 'productsDashboardCtrl'
                })
                .state('dashboard.products.productEdit', {
                    url: '/productEdit',
                    templateUrl: 'app/modules/dashboard/views/product-edit.html'
                })

                //Orders routes
                .state('dashboard.orders', {
                    url: '/orders',
                    templateUrl: 'app/modules/dashboard/views/orders.html',
                    controller: 'OrdersDashboardController',
                    controllerAs: 'ordersDashboardCtrl'
                })
                .state('dashboard.orders.details', {
                    url: '/details/:orderId',
                    templateUrl: 'app/modules/dashboard/views/order-details.html',
                    controller: 'OrderDetailsController',
                    controllerAs: 'orderDetailsCtrl'
                })

                //Category routes
                .state('dashboard.categories', {
                    url: '/categories',
                    templateUrl: 'app/modules/dashboard/views/categories.html',
                    controller: 'CategoriesDashboardController',
                    controllerAs: 'categoriesDashboardCtrl'
                })

                .state('dashboard.categories.categoryEdit', {
                    url: '/categories',
                    templateUrl: 'app/modules/dashboard/views/category-edit.html'
                });
        }
    ]);


text:
@(title: String)(content: Html)
<!doctype html>

        <title>@title</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=0.66">
        <link rel="shortcut icon" type="image/png" href="@routes.Assets.at("images/favicon.png")">
        <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/metro-bootstrap.min.css")">
        <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/metro-bootstrap-responsive.min.css")">
        <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/iconFont.css")">

                    <form>

                            <input ng-model="query" type="text" name="q" placeholder="Rechercher...">
                            <button class="btn-search" ng-click="search()"></button>

                    </form>

@title

tous les films

par genre

                        liens

Go to Imdb

Play ▶ Films on Facebook

            @content

© 2014 Play Film

dijit

mentions

aide

feedback


text:
package com.gome.haoyuangong.net.result.tougu;

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

import com.gome.haoyuangong.net.result.TouguBaseResult;

public class LiveExchangeBean extends TouguBaseResult {

	private List<LiveExchangeItem> data = new ArrayList<LiveExchangeItem>();

	public List<LiveExchangeItem> getData() {
		return data;
	}

	public void setData(List<LiveExchangeItem> data) {
		this.data = data;
	}

	public static class LiveExchangeItem{

		private String id;
		private String from_id;
		private String uid;
		private String uname;
		private String time;
		private long timeStamp;
		private String content;
		private int isMaster;
		private int growupVal;
		private String headPic;
		private int verify;
		private int type;
		private String company;
		private String position;
//		private Quote quote = new Quote();
		public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		public String getFrom_id() {
			return from_id;
		}
		public void setFrom_id(String from_id) {
			this.from_id = from_id;
		}
		public String getUid() {
			return uid;
		}
		public void setUid(String uid) {
			this.uid = uid;
		}
		public String getUname() {
			return uname;
		}
		public void setUname(String uname) {
			this.uname = uname;
		}
		public String getTime() {
			return time;
		}
		public void setTime(String time) {
			this.time = time;
		}
		public long getTimeStamp() {
			return timeStamp;
		}
		public void setTimeStamp(long timeStamp) {
			this.timeStamp = timeStamp;
		}
		public String getContent() {
			return content;
		}
		public void setContent(String content) {
			this.content = content;
		}
		public int getIsMaster() {
			return isMaster;
		}
		public void setIsMaster(int isMaster) {
			this.isMaster = isMaster;
		}
		public int getGrowupVal() {
			return growupVal;
		}
		public void setGrowupVal(int growupVal) {
			this.growupVal = growupVal;
		}
		public String getHeadPic() {
			return headPic;
		}
		public void setHeadPic(String headPic) {
			this.headPic = headPic;
		}
		public int getVerify() {
			return verify;
		}
		public void setVerify(int verify) {
			this.verify = verify;
		}
		public int getType() {
			return type;
		}
		public void setType(int type) {
			this.type = type;
		}
		public String getCompany() {
			return company;
		}
		public void setCompany(String company) {
			this.company = company;
		}
		public String getPosition() {
			return position;
		}
		public void setPosition(String position) {
			this.position = position;
		}
//		public Quote getQuote() {
//			return quote;
//		}
//		public void setQuote(Quote quote) {
//			this.quote = quote;
//		}

	}

	public static class Quote{
		private String uid;
		private String uname;
		private String time;
		private String timeStamp;
		private String content;
		public String getUid() {
			return uid;
		}
		public void setUid(String uid) {
			this.uid = uid;
		}
		public String getUname() {
			return uname;
		}
		public void setUname(String uname) {
			this.uname = uname;
		}
		public String getTime() {
			return time;
		}
		public void setTime(String time) {
			this.time = time;
		}
		public String getTimeStamp() {
			return timeStamp;
		}
		public void setTimeStamp(String timeStamp) {
			this.timeStamp = timeStamp;
		}
		public String getContent() {
			return content;
		}
		public void setContent(String content) {
			this.content = content;
		}

	}
}


text:
'use strict';

const path = require('path'),
      _ = require('lodash');

const Model = require(path.resolve('./models/model')),
      schema = require('./schema');

class UserTag extends Model {
  static async read(username, tagname) {
    const query = `
      FOR u IN users FILTER u.username == @username
        FOR v, e IN 1
          OUTBOUND u
          userTag
          FILTER v.tagname == @tagname
          LET ut = KEEP(e, 'story', 'created', 'relevance')
          LET us = MERGE(KEEP(u, 'username'), u.profile)
          LET tg = KEEP(v, 'tagname', 'description', 'created')
          RETURN MERGE(ut, { user: us }, { tag: tg })`;
    const params = { username, tagname };
    const cursor = await this.db.query(query, params);
    const out = await cursor.all();
    return out[0];
  }

  static async create({ username, tagname, story, relevance }) {
    const userTag = schema({ story, relevance });
    const query = `
      FOR u IN users FILTER u.username == @username
        FOR t IN tags FILTER t.tagname == @tagname
          INSERT MERGE({ _from: u._id, _to: t._id }, @userTag) IN userTag
          LET ut = KEEP(NEW, 'story', 'relevance', 'created')
          LET us = MERGE(KEEP(u, 'username'), u.profile)
          LET tg = KEEP(t, 'tagname', 'description', 'created')
          RETURN MERGE(ut, { user: us }, { tag: tg })`;
    const params = { username, tagname, userTag };
    const cursor = await this.db.query(query, params);
    const out = await cursor.all();

    if (out.length !== 1) return null;
    return out[0];
  }

  static async update(username, tagname, newData) {
    const newUserTagData = _.pick(newData, ['relevance', 'story']);
    const query = `
      FOR u IN users FILTER u.username == @username
        FOR v, e IN 1
          OUTBOUND u
          userTag
          FILTER v.tagname == @tagname
          UPDATE e WITH @newUserTagData IN userTag
          RETURN NEW`;
    const params = { username, tagname, newUserTagData };
    const cursor = await this.db.query(query, params);
    const [output] = await cursor.all();

    if (!output) {
      const e = new Error('user-tag doesn\'t exist');
      e.status = 404;

      throw e;
    }

    return output;
  }

  static async exists(username, tagname) {
    const query = `
      FOR u IN users FILTER u.username == @username
        FOR v IN 1
          OUTBOUND u
          userTag
          FILTER v.tagname == @tagname
          COLLECT WITH COUNT INTO length
          RETURN length`;
    const params = { username, tagname };
    const cursor = await this.db.query(query, params);
    const count = await cursor.next();

    switch (count) {
      case 0:
        return false;
      case 1:
        return true;
      default:
        throw new Error('bad output');
    }
  }

  static async delete(username, tagname) {
    const query = `
      FOR u IN users FILTER u.username == @username
        FOR v, e IN 1
          OUTBOUND u
          userTag
          FILTER v.tagname == @tagname
          REMOVE e IN userTag
          RETURN OLD`;
    const params = { username, tagname };
    const cursor = await this.db.query(query, params);
    const writes = cursor.extra.stats.writesExecuted;

    switch (writes) {
      case 0:
        return false;
      case 1:
        return true;
      default:
        throw new Error('database corruption');
    }
  }
}

module.exports = UserTag;