text:
package com.mesosphere.sdk.offer.evaluate;

import com.google.common.annotations.VisibleForTesting;
import com.google.protobuf.TextFormat;
import com.mesosphere.sdk.offer.*;
import com.mesosphere.sdk.offer.history.OfferOutcome;
import com.mesosphere.sdk.offer.history.OfferOutcomeTracker;
import com.mesosphere.sdk.offer.taskdata.TaskLabelReader;
import com.mesosphere.sdk.scheduler.SchedulerConfig;
import com.mesosphere.sdk.scheduler.plan.PodInstanceRequirement;
import com.mesosphere.sdk.scheduler.recovery.FailureUtils;
import com.mesosphere.sdk.scheduler.recovery.RecoveryType;
import com.mesosphere.sdk.specification.*;
import com.mesosphere.sdk.state.GoalStateOverride;
import com.mesosphere.sdk.state.StateStore;
import org.apache.mesos.Protos;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * The OfferEvaluator processes {@link Protos.Offer}s and produces {@link OfferRecommendation}s.
 * The determination of what {@link OfferRecommendation}s, if any should be made are made
 * in reference to {@link PodInstanceRequirement}s.
 */
public class OfferEvaluator {
    private static final Logger logger = LoggerFactory.getLogger(OfferEvaluator.class);

    private final StateStore stateStore;
    private final OfferOutcomeTracker offerOutcomeTracker;
    private final String serviceName;
    private final UUID targetConfigId;
    private final SchedulerConfig schedulerConfig;
    private final boolean useDefaultExecutor;

    public OfferEvaluator(
            StateStore stateStore,
            OfferOutcomeTracker offerOutcomeTracker,
            String serviceName,
            UUID targetConfigId,
            SchedulerConfig schedulerConfig,
            boolean useDefaultExecutor) {
        this.stateStore = stateStore;
        this.offerOutcomeTracker = offerOutcomeTracker;
        this.serviceName = serviceName;
        this.targetConfigId = targetConfigId;
        this.schedulerConfig = schedulerConfig;
        this.useDefaultExecutor = useDefaultExecutor;
    }

    public List<OfferRecommendation> evaluate(PodInstanceRequirement podInstanceRequirement, List<Protos.Offer> offers)
            throws InvalidRequirementException, IOException {
        // All tasks in the service (used by some PlacementRules):
        Map<String, Protos.TaskInfo> allTasks = stateStore.fetchTasks().stream()
                .collect(Collectors.toMap(Protos.TaskInfo::getName, Function.identity()));
        // Preexisting tasks for this pod (if any):
        Map<String, Protos.TaskInfo> thisPodTasks =
                TaskUtils.getTaskNames(podInstanceRequirement.getPodInstance()).stream()
                .map(taskName -> allTasks.get(taskName))
                .filter(taskInfo -> taskInfo != null)
                .collect(Collectors.toMap(Protos.TaskInfo::getName, Function.identity()));

        boolean noTasksRunning = thisPodTasks.values().stream()
                .map(taskInfo -> taskInfo.getName())
                .map(taskName -> stateStore.fetchStatus(taskName))
                .filter(Optional::isPresent)
                .map(taskStatus -> taskStatus.get())
                .noneMatch(taskStatus -> taskStatus.getState().equals(Protos.TaskState.TASK_RUNNING));

        Optional<Protos.ExecutorInfo> executorInfo = Optional.empty();
        if (!thisPodTasks.isEmpty()) {
            Protos.ExecutorInfo.Builder execInfoBuilder =
                    thisPodTasks.values().stream().findFirst().get().getExecutor().toBuilder();
            if (noTasksRunning) {
                execInfoBuilder.setExecutorId(Protos.ExecutorID.newBuilder().setValue(""));
            }

            executorInfo = Optional.of(execInfoBuilder.build());
        }

        for (int i = 0; i < offers.size(); ++i) {
            List<OfferEvaluationStage> evaluationStages =
                    getEvaluationPipeline(podInstanceRequirement, allTasks.values(), thisPodTasks, executorInfo);

            Protos.Offer offer = offers.get(i);

            MesosResourcePool resourcePool = new MesosResourcePool(
                    offer,
                    OfferEvaluationUtils.getRole(podInstanceRequirement.getPodInstance().getPod()));

            Map<TaskSpec, GoalStateOverride> overrideMap = new HashMap<>();
            for (TaskSpec taskSpec : podInstanceRequirement.getPodInstance().getPod().getTasks()) {
                GoalStateOverride override =
                        stateStore.fetchGoalOverrideStatus(
                                TaskSpec.getInstanceName(podInstanceRequirement.getPodInstance(), taskSpec))
                                .target;

                overrideMap.put(taskSpec, override);
            }

            PodInfoBuilder podInfoBuilder = new PodInfoBuilder(
                    podInstanceRequirement,
                    serviceName,
                    getTargetConfig(podInstanceRequirement, thisPodTasks.values()),
                    schedulerConfig,
                    thisPodTasks.values(),
                    stateStore.fetchFrameworkId().get(),
                    useDefaultExecutor,
                    overrideMap);
            List<EvaluationOutcome> outcomes = new ArrayList<>();
            int failedOutcomeCount = 0;

            for (OfferEvaluationStage evaluationStage : evaluationStages) {
                EvaluationOutcome outcome = evaluationStage.evaluate(resourcePool, podInfoBuilder);
                outcomes.add(outcome);
                if (!outcome.isPassing()) {
                    failedOutcomeCount++;
                }
            }

            StringBuilder outcomeDetails = new StringBuilder();
            for (EvaluationOutcome outcome : outcomes) {
                logOutcome(outcomeDetails, outcome, "");
            }
            if (outcomeDetails.length() != 0) {
                // trim extra trailing newline:
                outcomeDetails.deleteCharAt(outcomeDetails.length() - 1);
            }

            if (failedOutcomeCount != 0) {
                logger.info("Offer {}, {}: failed {} of {} evaluation stages:\n{}",
                        i + 1,
                        offer.getId().getValue(),
                        failedOutcomeCount,
                        evaluationStages.size(),
                        outcomeDetails.toString());

                offerOutcomeTracker.track(new OfferOutcome(
                        podInstanceRequirement.getName(),
                        false,
                        offer,
                        outcomeDetails.toString()));
            } else {
                List<OfferRecommendation> recommendations = outcomes.stream()
                        .map(outcome -> outcome.getOfferRecommendations())
                        .flatMap(xs -> xs.stream())
                        .collect(Collectors.toList());
                logger.info("Offer {}: passed all {} evaluation stages, returning {} recommendations:\n{}",
                        i + 1, evaluationStages.size(), recommendations.size(), outcomeDetails.toString());

                offerOutcomeTracker.track(new OfferOutcome(
                        podInstanceRequirement.getName(),
                        true,
                        offer,
                        outcomeDetails.toString()));

                return recommendations;
            }
        }

        return Collections.emptyList();
    }

    public List<OfferEvaluationStage> getEvaluationPipeline(
            PodInstanceRequirement podInstanceRequirement,
            Collection<Protos.TaskInfo> allTasks,
            Map<String, Protos.TaskInfo> thisPodTasks,
            Optional<Protos.ExecutorInfo> executorInfo) throws IOException {

        boolean noLaunchedTasksExist = thisPodTasks.values().stream()
                .flatMap(taskInfo -> taskInfo.getResourcesList().stream())
                .map(resource -> ResourceUtils.getResourceId(resource))
                .filter(resourceId -> resourceId.isPresent())
                .map(Optional::get)
                .filter(resourceId -> !resourceId.isEmpty())
                .count() == 0;

        boolean allTasksFailed = thisPodTasks.values().stream()
                .allMatch(taskInfo -> FailureUtils.isPermanentlyFailed(taskInfo));

        final String description;
        final boolean shouldGetNewRequirement;
        if (podInstanceRequirement.getRecoveryType().equals(RecoveryType.PERMANENT) || allTasksFailed) {
            description = "failed";
            shouldGetNewRequirement = true;
        } else if (noLaunchedTasksExist) {
            description = "new";
            shouldGetNewRequirement = true;
        } else {
            description = "existing";
            shouldGetNewRequirement = false;
        }
        logger.info("Generating requirement for {} pod '{}' containing tasks: {}.",
                description,
                podInstanceRequirement.getPodInstance().getName(),
                podInstanceRequirement.getTasksToLaunch());

        // Only create a TLS Evaluation Stage builder if the service actually uses TLS certs.
        // This avoids performing TLS cert generation in cases where the cluster may not support it (e.g. DC/OS Open).
        boolean anyTasksWithTLS = podInstanceRequirement.getPodInstance().getPod().getTasks().stream()
                .anyMatch(taskSpec -> !taskSpec.getTransportEncryption().isEmpty());
        Optional<TLSEvaluationStage.Builder> tlsStageBuilder = anyTasksWithTLS
                ? Optional.of(new TLSEvaluationStage.Builder(serviceName, schedulerConfig))
                : Optional.empty();

        List<OfferEvaluationStage> evaluationPipeline = new ArrayList<>();
        if (shouldGetNewRequirement) {
            evaluationPipeline.add(new ExecutorEvaluationStage(Optional.empty()));
            evaluationPipeline.addAll(getNewEvaluationPipeline(podInstanceRequirement, allTasks, tlsStageBuilder));
        } else {
            evaluationPipeline.add(new ExecutorEvaluationStage(getExecutorInfo(thisPodTasks.values())));
            evaluationPipeline.addAll(getExistingEvaluationPipeline(
                    podInstanceRequirement, thisPodTasks, allTasks, executorInfo.get(), tlsStageBuilder));
        }

        return evaluationPipeline;
    }

    private Optional<Protos.ExecutorInfo> getExecutorInfo(Collection<Protos.TaskInfo> taskInfos) {
        for (Protos.TaskInfo taskInfo : taskInfos) {
            if (taskHasReusableExecutor(taskInfo)) {
                logger.info("Using existing executor: {}", taskInfo.getExecutor().getExecutorId().getValue());
                return Optional.of(taskInfo.getExecutor());
            }
        }

        return Optional.empty();
    }

    private boolean taskHasReusableExecutor(Protos.TaskInfo taskInfo) {
        Optional<Protos.TaskStatus> taskStatus = stateStore.fetchStatus(taskInfo.getName());
        if (!taskStatus.isPresent() || FailureUtils.isPermanentlyFailed(taskInfo)) {
            return false;
        }

        Protos.TaskState state = taskStatus.get().getState();
        switch (state) {
            case TASK_STAGING:
            case TASK_STARTING:
            case TASK_RUNNING:
                return true;
            default:
                return false;
        }
    }

    static void logOutcome(StringBuilder stringBuilder, EvaluationOutcome outcome, String indent) {
        stringBuilder.append(String.format("  %s%s%n", indent, outcome.toString()));
        for (EvaluationOutcome child : outcome.getChildren()) {
            logOutcome(stringBuilder, child, indent + "  ");
        }
    }

    private static Map<String, ResourceSet> getNewResourceSets(PodInstanceRequirement podInstanceRequirement) {
        Map<String, ResourceSet> resourceSets =
                podInstanceRequirement.getPodInstance().getPod().getTasks().stream()
                        .filter(taskSpec -> podInstanceRequirement.getTasksToLaunch().contains(taskSpec.getName()))
                        .collect(Collectors.toMap(TaskSpec::getName, TaskSpec::getResourceSet));

        for (TaskSpec taskSpec : podInstanceRequirement.getPodInstance().getPod().getTasks()) {
            if (resourceSets.keySet().contains(taskSpec.getName())) {
                continue;
            }

            Set<String> resourceSetNames = resourceSets.values().stream()
                    .map(resourceSet -> resourceSet.getId())
                    .collect(Collectors.toSet());

            if (!resourceSetNames.contains(taskSpec.getResourceSet().getId())) {
                resourceSets.put(taskSpec.getName(), taskSpec.getResourceSet());
            }
        }

        return resourceSets;
    }

    private static List<ResourceSpec> getOrderedResourceSpecs(ResourceSet resourceSet) {
        // Statically defined ports, then dynamic ports, then everything else
        List<ResourceSpec> staticPorts = new ArrayList<>();
        List<ResourceSpec> dynamicPorts = new ArrayList<>();
        List<ResourceSpec> simpleResources = new ArrayList<>();

        for (ResourceSpec resourceSpec : resourceSet.getResources()) {
            if (resourceSpec instanceof PortSpec) {
                if (((PortSpec) resourceSpec).getPort() == 0) {
                    dynamicPorts.add(resourceSpec);
                } else {
                    staticPorts.add(resourceSpec);
                }
            } else {
                simpleResources.add(resourceSpec);
            }
        }

        List<ResourceSpec> resourceSpecs = new ArrayList<>();
        resourceSpecs.addAll(staticPorts);
        resourceSpecs.addAll(dynamicPorts);
        resourceSpecs.addAll(simpleResources);
        return resourceSpecs;
    }

    private List<OfferEvaluationStage> getNewEvaluationPipeline(
            PodInstanceRequirement podInstanceRequirement,
            Collection<Protos.TaskInfo> allTasks,
            Optional<TLSEvaluationStage.Builder> tlsStageBuilder) {
        List<OfferEvaluationStage> evaluationStages = new ArrayList<>();
        if (podInstanceRequirement.getPodInstance().getPod().getPlacementRule().isPresent()) {
            evaluationStages.add(new PlacementRuleEvaluationStage(
                    allTasks, podInstanceRequirement.getPodInstance().getPod().getPlacementRule().get()));
        }

        for (VolumeSpec volumeSpec : podInstanceRequirement.getPodInstance().getPod().getVolumes()) {
            evaluationStages.add(
                    new VolumeEvaluationStage(
                            volumeSpec, null, Optional.empty(), Optional.empty(), useDefaultExecutor));
        }

        String preReservedRole = null;
        String role = null;
        String principal = null;
        boolean shouldAddExecutorResources = useDefaultExecutor;
        for (Map.Entry<String, ResourceSet> entry : getNewResourceSets(podInstanceRequirement).entrySet()) {
            String taskName = entry.getKey();
            List<ResourceSpec> resourceSpecs = getOrderedResourceSpecs(entry.getValue());

            for (ResourceSpec resourceSpec : resourceSpecs) {
                if (resourceSpec instanceof NamedVIPSpec) {
                    evaluationStages.add(
                            new NamedVIPEvaluationStage((NamedVIPSpec) resourceSpec, taskName, Optional.empty()));
                } else if (resourceSpec instanceof PortSpec) {
                    evaluationStages.add(new PortEvaluationStage((PortSpec) resourceSpec, taskName, Optional.empty()));
                } else {
                    evaluationStages.add(new ResourceEvaluationStage(resourceSpec, Optional.empty(), taskName));
                }

                if (preReservedRole == null && role == null && principal == null) {
                    preReservedRole = resourceSpec.getPreReservedRole();
                    role = resourceSpec.getRole();
                    principal = resourceSpec.getPrincipal();
                }
            }

            for (VolumeSpec volumeSpec : entry.getValue().getVolumes()) {
                evaluationStages.add(
                        new VolumeEvaluationStage(
                                volumeSpec, taskName, Optional.empty(), Optional.empty(), useDefaultExecutor));
            }

            if (shouldAddExecutorResources) {
                // The default executor needs a constant amount of resources, account for them here.
                for (ResourceSpec resourceSpec : getExecutorResources(preReservedRole, role, principal)) {
                    evaluationStages.add(new ResourceEvaluationStage(resourceSpec, Optional.empty(), null));
                }
                shouldAddExecutorResources = false;
            }

            // TLS evaluation stages should be added for all tasks regardless of the tasks to launch list to ensure
            // ExecutorInfo equality when launching new tasks
            for (TaskSpec taskSpec : podInstanceRequirement.getPodInstance().getPod().getTasks()) {
                if (!taskSpec.getTransportEncryption().isEmpty()) {
                    evaluationStages.add(tlsStageBuilder.get().build(taskSpec.getName()));
                }
            }

            boolean shouldBeLaunched = podInstanceRequirement.getTasksToLaunch().contains(taskName);
            evaluationStages.add(new LaunchEvaluationStage(taskName, shouldBeLaunched, useDefaultExecutor));
        }

        return evaluationStages;
    }

    private static List<ResourceSpec> getExecutorResources(String preReservedRole, String role, String principal) {
        List<ResourceSpec> resources = new ArrayList<>();

        resources.add(DefaultResourceSpec.newBuilder()
                .name("cpus")
                .preReservedRole(preReservedRole)
                .role(role)
                .principal(principal)
                .value(Protos.Value.newBuilder()
                        .setType(Protos.Value.Type.SCALAR)
                        .setScalar(Protos.Value.Scalar.newBuilder().setValue(0.1))
                        .build())
                .build());

        resources.add(DefaultResourceSpec.newBuilder()
                .name("mem")
                .preReservedRole(preReservedRole)
                .role(role)
                .principal(principal)
                .value(Protos.Value.newBuilder()
                        .setType(Protos.Value.Type.SCALAR)
                        .setScalar(Protos.Value.Scalar.newBuilder().setValue(32.0))
                        .build())
                .build());

        resources.add(DefaultResourceSpec.newBuilder()
                .name("disk")
                .preReservedRole(preReservedRole)
                .role(role)
                .principal(principal)
                .value(Protos.Value.newBuilder()
                        .setType(Protos.Value.Type.SCALAR)
                        .setScalar(Protos.Value.Scalar.newBuilder().setValue(256.0))
                        .build())
                .build());

        return resources;
    }

    private List<OfferEvaluationStage> getExistingEvaluationPipeline(
            PodInstanceRequirement podInstanceRequirement,
            Map<String, Protos.TaskInfo> podTasks,
            Collection<Protos.TaskInfo> allTasks,
            Protos.ExecutorInfo executorInfo,
            Optional<TLSEvaluationStage.Builder> tlsStageBuilder) {
        List<TaskSpec> taskSpecs = podInstanceRequirement.getPodInstance().getPod().getTasks().stream()
                .filter(taskSpec -> podInstanceRequirement.getTasksToLaunch().contains(taskSpec.getName()))
                .collect(Collectors.toList());

        List<OfferEvaluationStage> evaluationStages = new ArrayList<>();

        // TLS evaluation stages should be added for all tasks regardless of the tasks to launch list to ensure
        // ExecutorInfo equality when launching new tasks
        for (TaskSpec taskSpec : podInstanceRequirement.getPodInstance().getPod().getTasks()) {
            if (!taskSpec.getTransportEncryption().isEmpty()) {
                evaluationStages.add(tlsStageBuilder.get().build(taskSpec.getName()));
            }
        }

        if (podInstanceRequirement.getPodInstance().getPod().getPlacementRule().isPresent() &&
                podInstanceRequirement.getRecoveryType().equals(RecoveryType.PERMANENT)) {
            evaluationStages.add(new PlacementRuleEvaluationStage(
                    allTasks, podInstanceRequirement.getPodInstance().getPod().getPlacementRule().get()));
        }

        ResourceSpec firstResource = taskSpecs.get(0).getResourceSet().getResources().iterator().next();
        String preReservedRole = firstResource.getPreReservedRole();
        String role = firstResource.getRole();
        String principal = firstResource.getPrincipal();

        ExecutorResourceMapper executorResourceMapper = new ExecutorResourceMapper(
                podInstanceRequirement.getPodInstance().getPod(),
                getExecutorResources(preReservedRole, role, principal),
                executorInfo,
                useDefaultExecutor);
        executorResourceMapper.getOrphanedResources()
                .forEach(resource -> evaluationStages.add(new DestroyEvaluationStage(resource)));
        executorResourceMapper.getOrphanedResources()
                .forEach(resource -> evaluationStages.add(new UnreserveEvaluationStage(resource)));
        evaluationStages.addAll(executorResourceMapper.getEvaluationStages());

        for (TaskSpec taskSpec : taskSpecs) {
            String taskInstanceName =
                    TaskSpec.getInstanceName(podInstanceRequirement.getPodInstance(), taskSpec.getName());
            Protos.TaskInfo taskInfo =
                    getTaskInfoSharingResourceSet(podInstanceRequirement.getPodInstance(), taskSpec, podTasks);
            if (taskInfo == null) {
                logger.error("Failed to fetch task {}.  Cannot generate resource map.", taskInstanceName);
                return Collections.emptyList();
            }

            TaskResourceMapper taskResourceMapper = new TaskResourceMapper(taskSpec, taskInfo, useDefaultExecutor);
            taskResourceMapper.getOrphanedResources()
                    .forEach(resource -> evaluationStages.add(new UnreserveEvaluationStage(resource)));
            evaluationStages.addAll(taskResourceMapper.getEvaluationStages());

            boolean shouldLaunch = podInstanceRequirement.getTasksToLaunch().contains(taskSpec.getName());
            evaluationStages.add(new LaunchEvaluationStage(taskSpec.getName(), shouldLaunch, useDefaultExecutor));
        }

        return evaluationStages;
    }

    private static Protos.TaskInfo getTaskInfoSharingResourceSet(
            PodInstance podInstance,
            TaskSpec taskSpec,
            Map<String, Protos.TaskInfo> podTasks) {

        String taskInfoName = TaskSpec.getInstanceName(podInstance, taskSpec.getName());
        Protos.TaskInfo taskInfo = podTasks.get(taskInfoName);
        if (taskInfo != null) {
            return taskInfo;
        }

        String resourceSetId = taskSpec.getResourceSet().getId();
        List<String> sharedTaskNames = podInstance.getPod().getTasks().stream()
                .filter(ts -> ts.getResourceSet().getId().equals(resourceSetId))
                .map(ts -> TaskSpec.getInstanceName(podInstance, ts.getName()))
                .collect(Collectors.toList());

        for (String taskName : sharedTaskNames) {
            taskInfo = podTasks.get(taskName);
            if (taskInfo != null) {
                return taskInfo;
            }
        }

        return null;
    }

    @VisibleForTesting
    UUID getTargetConfig(PodInstanceRequirement podInstanceRequirement, Collection<Protos.TaskInfo> taskInfos) {
        if (podInstanceRequirement.getRecoveryType().equals(RecoveryType.NONE) || taskInfos.isEmpty()) {
            return targetConfigId;
        } else {
            // 1. Recovery always only handles tasks with a goal state of RUNNING
            // 2. All tasks in a pod should be launched with the same configuration
            // Therefore it is correct to take the target configuration of one task as being
            // representative of the whole of the pod. If tasks in the same pod with a goal
            // state of RUNNING had different target configurations this should be rectified
            // in any case, so it is doubly proper to choose a single target configuration as
            // representative of the whole pod's target configuration.

            Protos.TaskInfo taskInfo = taskInfos.stream().findFirst().get();
            try {
                return new TaskLabelReader(taskInfo).getTargetConfiguration();
            } catch (TaskException e) {
                logger.error(String.format(
                        "Falling back to current target configuration '%s'. " +
                                "Failed to determine target configuration for task: %s",
                                targetConfigId, TextFormat.shortDebugString(taskInfo)), e);
                return targetConfigId;
            }
        }
    }

}


text:
using System;

namespace SelfLoadRO.DataAccess
{
    /// <summary>
    /// Defines the SelfLoadRO DAL manager interface for DAL providers.
    /// </summary>
    public interface IDalManagerSelfLoadRO : IDisposable
    {
        /// <summary>
        /// Gets the DAL provider for a given object Type.
        /// </summary>
        /// <typeparam name="T">Object Type that requires a SelfLoadRO DAL provider.</typeparam>
        /// <returns>A new SelfLoadRO DAL instance for the given Type.</returns>
        T GetProvider<T>() where T : class;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package newrelic

import (
	"fmt"
	"log"
	"strconv"

	"github.com/hashicorp/terraform/helper/schema"
	"github.com/hashicorp/terraform/helper/validation"
	newrelic "github.com/paultyng/go-newrelic/api"
)

var alertConditionTypes = map[string][]string{
	"apm_app_metric": []string{
		"apdex",
		"error_percentage",
		"response_time_background",
		"response_time_web",
		"throughput_background",
		"throughput_web",
		"user_defined",
	},
	"apm_kt_metric": []string{
		"apdex",
		"error_count",
		"error_percentage",
		"response_time",
		"throughput",
	},
	"browser_metric": []string{
		"ajax_response_time",
		"ajax_throughput",
		"dom_processing",
		"end_user_apdex",
		"network",
		"page_rendering",
		"page_view_throughput",
		"page_views_with_js_errors",
		"request_queuing",
		"total_page_load",
		"user_defined",
		"web_application",
	},
	"mobile_metric": []string{
		"database",
		"images",
		"json",
		"mobile_crash_rate",
		"network_error_percentage",
		"network",
		"status_error_percentage",
		"user_defined",
		"view_loading",
	},
	"servers_metric": []string{
		"cpu_percentage",
		"disk_io_percentage",
		"fullest_disk_percentage",
		"load_average_one_minute",
		"memory_percentage",
		"user_defined",
	},
}

func resourceNewRelicAlertCondition() *schema.Resource {
	validAlertConditionTypes := make([]string, 0, len(alertConditionTypes))
	for k := range alertConditionTypes {
		validAlertConditionTypes = append(validAlertConditionTypes, k)
	}

	return &schema.Resource{
		Create: resourceNewRelicAlertConditionCreate,
		Read:   resourceNewRelicAlertConditionRead,
		Update: resourceNewRelicAlertConditionUpdate,
		Delete: resourceNewRelicAlertConditionDelete,
		Importer: &schema.ResourceImporter{
			State: schema.ImportStatePassthrough,
		},
		Schema: map[string]*schema.Schema{
			"policy_id": {
				Type:     schema.TypeInt,
				Required: true,
				ForceNew: true,
			},
			"name": {
				Type:     schema.TypeString,
				Required: true,
			},
			"type": {
				Type:         schema.TypeString,
				Required:     true,
				ValidateFunc: validation.StringInSlice(validAlertConditionTypes, false),
			},
			"entities": {
				Type:     schema.TypeList,
				Elem:     &schema.Schema{Type: schema.TypeInt},
				Required: true,
				MinItems: 1,
			},
			"metric": {
				Type:     schema.TypeString,
				Required: true,
				//TODO: ValidateFunc from map
			},
			"runbook_url": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"term": {
				Type: schema.TypeList,
				Elem: &schema.Resource{
					Schema: map[string]*schema.Schema{
						"duration": {
							Type:         schema.TypeInt,
							Required:     true,
							ValidateFunc: intInSlice([]int{5, 10, 15, 30, 60, 120}),
						},
						"operator": {
							Type:         schema.TypeString,
							Optional:     true,
							Default:      "equal",
							ValidateFunc: validation.StringInSlice([]string{"above", "below", "equal"}, false),
						},
						"priority": {
							Type:         schema.TypeString,
							Optional:     true,
							Default:      "critical",
							ValidateFunc: validation.StringInSlice([]string{"critical", "warning"}, false),
						},
						"threshold": {
							Type:         schema.TypeFloat,
							Required:     true,
							ValidateFunc: float64Gte(0.0),
						},
						"time_function": {
							Type:         schema.TypeString,
							Required:     true,
							ValidateFunc: validation.StringInSlice([]string{"all", "any"}, false),
						},
					},
				},
				Required: true,
				MinItems: 1,
			},
			"user_defined_metric": {
				Type:     schema.TypeString,
				Optional: true,
			},
			"user_defined_value_function": {
				Type:         schema.TypeString,
				Optional:     true,
				ValidateFunc: validation.StringInSlice([]string{"average", "min", "max", "total", "sample_size"}, false),
			},
		},
	}
}

func buildAlertConditionStruct(d *schema.ResourceData) *newrelic.AlertCondition {
	entitySet := d.Get("entities").([]interface{})
	entities := make([]string, len(entitySet))

	for i, entity := range entitySet {
		entities[i] = strconv.Itoa(entity.(int))
	}

	termSet := d.Get("term").([]interface{})
	terms := make([]newrelic.AlertConditionTerm, len(termSet))

	for i, termI := range termSet {
		termM := termI.(map[string]interface{})

		terms[i] = newrelic.AlertConditionTerm{
			Duration:     termM["duration"].(int),
			Operator:     termM["operator"].(string),
			Priority:     termM["priority"].(string),
			Threshold:    termM["threshold"].(float64),
			TimeFunction: termM["time_function"].(string),
		}
	}

	condition := newrelic.AlertCondition{
		Type:     d.Get("type").(string),
		Name:     d.Get("name").(string),
		Enabled:  true,
		Entities: entities,
		Metric:   d.Get("metric").(string),
		Terms:    terms,
		PolicyID: d.Get("policy_id").(int),
	}

	if attr, ok := d.GetOk("runbook_url"); ok {
		condition.RunbookURL = attr.(string)
	}

	if attrM, ok := d.GetOk("user_defined_metric"); ok {
		if attrVF, ok := d.GetOk("user_defined_value_function"); ok {
			condition.UserDefined = newrelic.AlertConditionUserDefined{
				Metric:        attrM.(string),
				ValueFunction: attrVF.(string),
			}
		}
	}

	return &condition
}

func readAlertConditionStruct(condition *newrelic.AlertCondition, d *schema.ResourceData) error {
	ids, err := parseIDs(d.Id(), 2)
	if err != nil {
		return err
	}

	policyID := ids[0]

	entities := make([]int, len(condition.Entities))
	for i, entity := range condition.Entities {
		v, err := strconv.ParseInt(entity, 10, 32)
		if err != nil {
			return err
		}
		entities[i] = int(v)
	}

	d.Set("policy_id", policyID)
	d.Set("name", condition.Name)
	d.Set("type", condition.Type)
	d.Set("metric", condition.Metric)
	d.Set("runbook_url", condition.RunbookURL)
	d.Set("user_defined_metric", condition.UserDefined.Metric)
	d.Set("user_defined_value_function", condition.UserDefined.ValueFunction)
	if err := d.Set("entities", entities); err != nil {
		return fmt.Errorf("[DEBUG] Error setting alert condition entities: %#v", err)
	}

	var terms []map[string]interface{}

	for _, src := range condition.Terms {
		dst := map[string]interface{}{
			"duration":      src.Duration,
			"operator":      src.Operator,
			"priority":      src.Priority,
			"threshold":     src.Threshold,
			"time_function": src.TimeFunction,
		}
		terms = append(terms, dst)
	}

	if err := d.Set("term", terms); err != nil {
		return fmt.Errorf("[DEBUG] Error setting alert condition terms: %#v", err)
	}

	return nil
}

func resourceNewRelicAlertConditionCreate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*newrelic.Client)
	condition := buildAlertConditionStruct(d)

	log.Printf("[INFO] Creating New Relic alert condition %s", condition.Name)

	condition, err := client.CreateAlertCondition(*condition)
	if err != nil {
		return err
	}

	d.SetId(serializeIDs([]int{condition.PolicyID, condition.ID}))

	return nil
}

func resourceNewRelicAlertConditionRead(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*newrelic.Client)

	log.Printf("[INFO] Reading New Relic alert condition %s", d.Id())

	ids, err := parseIDs(d.Id(), 2)
	if err != nil {
		return err
	}

	policyID := ids[0]
	id := ids[1]

	condition, err := client.GetAlertCondition(policyID, id)
	if err != nil {
		if err == newrelic.ErrNotFound {
			d.SetId("")
			return nil
		}

		return err
	}

	return readAlertConditionStruct(condition, d)
}

func resourceNewRelicAlertConditionUpdate(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*newrelic.Client)
	condition := buildAlertConditionStruct(d)

	ids, err := parseIDs(d.Id(), 2)
	if err != nil {
		return err
	}

	policyID := ids[0]
	id := ids[1]

	condition.PolicyID = policyID
	condition.ID = id

	log.Printf("[INFO] Updating New Relic alert condition %d", id)

	updatedCondition, err := client.UpdateAlertCondition(*condition)
	if err != nil {
		return err
	}

	return readAlertConditionStruct(updatedCondition, d)
}

func resourceNewRelicAlertConditionDelete(d *schema.ResourceData, meta interface{}) error {
	client := meta.(*newrelic.Client)

	ids, err := parseIDs(d.Id(), 2)
	if err != nil {
		return err
	}

	policyID := ids[0]
	id := ids[1]

	log.Printf("[INFO] Deleting New Relic alert condition %d", id)

	if err := client.DeleteAlertCondition(policyID, id); err != nil {
		return err
	}

	d.SetId("")

	return nil
}


text: Tools for working with Lego Digital Designer(tm) LXF Files and Brick Link(tm).


text:
<script type="text/javascript">
    //require(["dojo/parser", "dojo/dom",
    //         "dijit/layout/BorderContainer", "dijit/layout/ContentPane", "dijit/layout/TabContainer", "dijit/layout/SplitContainer",
    //         "dijit/form/DropDownButton", "dijit/PopupMenuItem",
    //         "dijit/Dialog", "dijit/TooltipDialog",
    //         "dojo/dnd/Target",
    //         "dojo/domReady!"],
    //         function(parser){
    //            parser.parse();
    //            test();
    //         }
    //);

    dojo.require("dojo.parser");
    dojo.require("dojo.cookie");

    dojo.require("dojo.dnd.Source");
    dojo.require("dojo.dnd.Moveable");

    dojo.require("dijit.layout.TabContainer");
    dojo.require("dijit.layout.BorderContainer");
    dojo.require("dijit.layout.SplitContainer");

    dojo.require("dijit.Dialog");
    dojo.require("dijit.Tooltip");
    dojo.require("dijit.TooltipDialog");
    dojo.require("dijit.Editor");

    /* basic dijit form classes */
    dojo.require('dijit.form.CheckBox');
    dojo.require('dijit.form.Textarea');
    dojo.require('dijit.form.FilteringSelect');
    dojo.require('dijit.form.TextBox');
    dojo.require('dijit.form.ValidationTextBox');
    dojo.require('dijit.form.DateTextBox');
    dojo.require('dijit.form.TimeTextBox');
    dojo.require('dijit.form.Button');
    dojo.require('dijit.form.RadioButton');
    dojo.require('dijit.form.Form');
    dojo.require('dijit.form.DateTextBox');

    dojo.require('dojox.validate');
    dojo.require('dojox.validate.us');
    dojo.require('dojox.validate.web');

    /* basic dojox classes */
    dojo.require('dojox.form.BusyButton');
    dojo.require('dojox.form.CheckedMultiSelect');

    dojo.require("dojox.widget.Standby");
</script>


text:
// Since zip codes can span over multiple counties, this provides a poper taxonomy mapping
// For the US, converted CSV at
// http://www2.census.gov/geo/docs/maps-data/data/rel/zcta_county_rel_10.txt
import usZctaCounty from "../public/geo/zcta-county-us.json";
import auZctaCounty from "../public/geo/zcta-county-au.json";
import gbCountyFipsCode from "../public/geo/gb-counties-fips.json";
import auCountyFipsCode from "../public/geo/au-counties-fips.json";

const AU_CAMBELLTOWN_CITY_COUNCIL_CODE = {
    "AU-NSW": "11500",
    "AU-SA": "40910",
};

const usCountyZctaMap = usZctaCounty.reduce((acc,r)=> {
    acc.set(r.geoid,r.zcta)
    return acc;
}, new Map<string, Array<string>>());

const auCountyZctaMap = auZctaCounty.reduce((acc, r) => {
    acc.set(r.geoid, r.zcta)
    return acc;
}, new Map<string, Array<string>>());

/**
 * Mapping of county names as appear in data CSV file to county IDs as they appear in
 * the map shapefile for the UK
 */
const gbCountyFipsCodeMap = gbCountyFipsCode.reduce((acc, r) => {
    acc.set(r.county_name, r.county_fips_code)
    return acc;
}, new Map<string, string>());

/**
 * Mapping of county names as appear in data CSV file to county IDs as they appear in
 * the map shapefile for Australia
 */
const auCountyFipsCodeMap = auCountyFipsCode.reduce((acc, r) => {
    acc.set(r.county_name, r.county_fips_code)
    return acc;
}, new Map<string, string>());

/**
 * In case sub_region_2_code is missing in the data file (currently only relevant for AU and GB),
 * use the lookup table to match county name with the map shape ID of that county.
 */
export function getCountyFipsCode(county_name: string, state_name: string, country_code: string) {
    switch (country_code) {
        case "AU":
            // Region with the same county name, but located in different states
            if (county_name == "Campbelltown City Council") {
                return AU_CAMBELLTOWN_CITY_COUNCIL_CODE[state_name];
            } else {
                return auCountyFipsCodeMap.get(county_name);
            }
        case "GB":
            return gbCountyFipsCodeMap.get(county_name);
        default:
            return ""
    }
}

/**
 * Get list of zip codes for the country
 */
export function getCountyZctas(fipsCode: string, country_code: string) {
    switch (country_code) {
        case "AU":
            return auCountyZctaMap.get(fipsCode);
        case "US":
            return usCountyZctaMap.get(fipsCode);
        default:
            return ""
    }
}


text: Detects if the Python plugin is available, which is necessary for editing the Pants BUILD files


text:
package com.github.piasy.taskdemo.launch_mode;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import com.github.piasy.taskdemo.R;

public class SingleTop extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d("TaskDemo", "SingleTop onCreate");

        setContentView(R.layout.activity_single_top);

        findViewById(R.id.mSingleTop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(SingleTop.this, SingleTop.class));
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();

        Log.d("TaskDemo", "SingleTop onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();

        Log.d("TaskDemo", "SingleTop onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();

        Log.d("TaskDemo", "SingleTop onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();

        Log.d("TaskDemo", "SingleTop onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Log.d("TaskDemo", "SingleTop onDestroy");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        Log.d("TaskDemo", "SingleTop onNewIntent");
    }
}


text:
require 'goliath/validation/error'
require 'goliath/validation/standard_http_errors'


text:
{{+bindTo:partials.standard_nacl_api}}

PP_VideoPicture Struct Reference

{{- dummy div to appease doxygen -}}

Data Fields

uint32_t 	decode_id

uint32_t 	texture_id

uint32_t 	texture_target

struct PP_Size 	texture_size

struct PP_Rect 	visible_rect

Detailed Description

Struct describing a decoded video picture.

The decoded picture data is stored in the GL texture corresponding to |texture_id|. The plugin can determine which Decode call generated the picture using |decode_id|.

Field Documentation

uint32_t PP_VideoPicture::decode_id

|decode_id| parameter of the Decode call which generated this picture.

See the PPB_VideoDecoder function Decode() for more details.

uint32_t PP_VideoPicture::texture_id

Texture ID in the plugin's GL context.

The plugin can use this to render the decoded picture.

struct PP_Size PP_VideoPicture::texture_size

Dimensions of the texture holding the decoded picture.

uint32_t PP_VideoPicture::texture_target

The GL texture target for the decoded picture.

Possible values are: GL_TEXTURE_2D GL_TEXTURE_RECTANGLE_ARB GL_TEXTURE_EXTERNAL_OES

The pixel format of the texture is GL_RGBA.

struct PP_Rect PP_VideoPicture::visible_rect

The visible subrectangle of the picture.

The plugin should display only this part of the picture.

The documentation for this struct was generated from the following file:

pp_codecs.h

{{/partials.standard_nacl_api}}


text:
// ReplSetTest.java

package com.mongodb;

import java.util.*;

public class ReplSetTest {

    static void _sleep()
        throws InterruptedException {
        //Thread.sleep( 500 );
    }

    static class R extends Thread {
        @SuppressWarnings("deprecation")
        R( ServerAddress a ){
            _a = a;
            _mongo = new MongoClient(a);
            _db = _mongo.getDB( "test" );
            _coll = _db.getCollection( "foo" );

            _coll.slaveOk();
        }

        public void run(){
            while ( true ){
                try {
                    _sleep();
                    _coll.findOne();
                }
                catch ( NullPointerException n ){
                    n.printStackTrace();
                }
                catch ( Exception e ){
                    System.out.println( _a + "\t" + e );
                }
            }
        }

        final ServerAddress _a;
        final Mongo _mongo;
        final DB _db;
        final DBCollection _coll;
    }

    @SuppressWarnings("deprecation")
    public static void main( String args[] )
        throws Exception {

        boolean rs = true;

        List<ServerAddress> addrs = new ArrayList<ServerAddress>();
        if ( rs ){
            addrs.add( new ServerAddress( "localhost" , 27018 ) );
            addrs.add( new ServerAddress( "localhost" , 27019 ) );
            addrs.add( new ServerAddress( "localhost" , 27020 ) );
            addrs.add( new ServerAddress( "localhost" , 27021 ) );
        }

        Mongo m = rs ? new MongoClient( addrs ) : new MongoClient();
        DB db = m.getDB( "test" );
        DBCollection c = db.getCollection( "foo" );
        c.drop();
        c.insert( new BasicDBObject( "_id" , 17 ) );
        c.slaveOk();

        for ( ServerAddress a : addrs ){
            new R(a).start();
        }

        while ( true ){
            _sleep();
            try {
                DBObject x = c.findOne(new BasicDBObject( "_id", 17 ), null);
                System.out.println( x );
                Integer n = (Integer) x.get( "x" );
                if (n != null && n >= 150 )
                    break;
                c.update( new BasicDBObject( "_id", 17 ), new BasicDBObject( "$inc", new BasicDBObject( "x", 1 ) ) );
            }
            catch ( Exception e ){
                e.printStackTrace();
            }
        }
    }
}


text:
<?php
declare(strict_types = 1);

namespace acceptance;

use AcceptanceTester;

class T100_SetupProjects_Cest{
  public function _failed(AcceptanceTester $I): void{
    $I->terminate();
  }

  private function createProject(AcceptanceTester $I, string $name, string $url): void{
    $I->amOnPage('/');

    $I->fillField('#Create-1-Name', $name);
    $I->fillField('#Create-1-Url', $url);
    $I->checkOption('#Create-1-Hidden');
    $I->click('#Create-1 button[type="submit"]');
    $I->seeCurrentUrlEquals('/project/'.$url);
  }

  public function run(AcceptanceTester $I): void{
    $I->amLoggedIn('User1');
    $this->createProject($I, 'Project 1', 'p1');

    $I->amLoggedIn('User2');
    $this->createProject($I, 'Project 2', 'p2');
  }
}

?>


text:
/*The Main Styling for the Nav Bar*/

/***********************
        Navigation
*************************/
/* Logo Style */
#logo{
  float: left;
  text-align: center;
  margin: 10px 10px;
    border-radius: 100%;
}
#logo nav ul a{
  background-color: none;
  padding: 0;
  border-radius: 100%;
}
nav img{
  max-height: 35px;
  max-width:35px;
  position: inherit;
  border-radius: 100%;
  background-color: #fff;
}
/*navbar*/
nav {
    text-align: right;
    padding: 0;
    margin: 0 10px 0 0;
    width:100%;
    height: 50px;

}
nav ul {
    list-style: none;
    margin: 0;
    padding: 0;
}
nav li {
    display: inline-block;
    margin: 0 1.5px 0;
}
nav ul ol li{
  background-color: #fff;
  text-align: center;
}
nav ul li a:hover{
  background-color: #000;
  padding: 15px 0 15px;
  border-left: 5px solid #000;
  border-right: 5px solid #000;
}
nav a{
    font-weight:800;
    padding: 0;
    text-decoration:none;
}
/*Dropdown Button*/
nav .dropbtn {
  background-color: #212F3D;
  color:#fff;
  padding: 16px;
  font-size:16px;
  border: none;
  cursor:pointer;
  border-radius: 5%;
}
/* Dropdown button on hover & focus */
nav .dropbtn:hover,
.dropbtn:focus {
    background-color: #000;
}

/* The container <div> - needed to position the dropdown content */
nav .dropdown {
    position: relative;
    display: inline-block;
}

/* Dropdown Content (Hidden by Default) */
nav .dropdown-content {
    display: none;
    position: relative;
    float:right;
    background-color: #fff;
    max-width: 300px;
    box-shadow: 5px 8px 16px 5px rgba(0,0,0,0.2);
}

/* Links inside the dropdown */
nav .dropdown-content a {
    color: #fff;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: center;
    margin: auto;
}

/* Change color of dropdown links on hover */
nav .dropdown-content a:hover {background-color: #f1f1f1}

/* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
nav .show {display:block;}

nav.toggle-content{
  margin: auto;
}

/*************************
          Colors
**************************/

/* anchors CSS */
a{
  color: #000;
}
/* Navigation CSS */
nav {
 background: #212F3D;
  border-radius: 5%;
}

nav a, nav a:visited {
  color: #fff;
  }
nav a.active, nav a:hover {
  color: #e6e600;
}
/* Site Body CSS */
body {
  background-color: #fff;
  color: #000;
}
footer{
  background-color: #000;
  color:#fff;
}
button{
  color: grey;
  border-color: #fff;
}


text:
namespace s {

BlockRef Gen::newBlockRef(Gen *gen, unsigned char *instruction, unsigned char *address) {
    FunctionBody *body = &gen->m_body;
    const size_t currentLength = (unsigned char *)body->m_instructionsEnd - (unsigned char *)body->m_instructions;
    const size_t delta = address - instruction;
    return currentLength + delta;
}

void Gen::setBlockRef(Gen *gen, BlockRef offset, size_t value) {
    FunctionBody *body = &gen->m_body;
    *(size_t *)((unsigned char *)body->m_instructions + offset) = value;
}

void Gen::useRangeStart(Gen *gen, FileRange *range) {
    if (!gen) return;
    U_ASSERT(!gen->m_currentRange);
    gen->m_currentRange = range;
}

void Gen::useRangeEnd(Gen *gen, FileRange *range) {
    if (!gen) return;
    U_ASSERT(gen->m_currentRange == range);
    gen->m_currentRange = nullptr;
}

FileRange *Gen::newRange(char *text) {
    FileRange *range = (FileRange *)Memory::allocate(sizeof *range, 1);
    FileRange::recordStart(text, range);
    return range;
}

void Gen::delRange(FileRange *range) {
    Memory::free(range);
}

size_t Gen::newBlock(Gen *gen) {
    U_ASSERT(gen->m_blockTerminated);
    FunctionBody *body = &gen->m_body;
    const size_t offset = (unsigned char *)body->m_instructionsEnd - (unsigned char *)body->m_instructions;
    body->m_blocks = (InstructionBlock *)Memory::reallocate(body->m_blocks, ++body->m_count * sizeof *body->m_blocks);
    body->m_blocks[body->m_count - 1] = { offset, 0 };
    gen->m_blockTerminated = false;
    return body->m_count - 1;
}

void Gen::terminate(Gen *gen) {
    addReturn(gen, 0);
}

void Gen::addInstruction(Gen *gen, size_t size, Instruction *instruction) {
    U_ASSERT(Instruction::size(instruction) == size);
    U_ASSERT(!gen->m_blockTerminated);
    U_ASSERT(gen->m_currentRange);
    instruction->m_belongsTo = gen->m_currentRange;
    instruction->m_contextSlot = gen->m_scope;
    FunctionBody *body = &gen->m_body;
    InstructionBlock *block = &body->m_blocks[body->m_count - 1];
    const size_t currentLength = (unsigned char *)body->m_instructionsEnd - (unsigned char *)body->m_instructions;
    const size_t newLength = currentLength + size;
    body->m_instructions = (Instruction *)Memory::reallocate(body->m_instructions, newLength);
    body->m_instructionsEnd = (Instruction *)((unsigned char *)body->m_instructions + newLength);
    block->m_size += size;
    memcpy((unsigned char *)body->m_instructions + currentLength, instruction, size);
    if (instruction->m_type == kBranch || instruction->m_type == kTestBranch || instruction->m_type == kReturn)
        gen->m_blockTerminated = true;
}

void Gen::addLike(Gen *gen, Instruction *basis, size_t size, Instruction *instruction) {
    const Slot backup = Gen::scopeEnter(gen);
    useRangeStart(gen, basis->m_belongsTo);
    scopeSet(gen, basis->m_contextSlot);
    addInstruction(gen, size, instruction);
    useRangeEnd(gen, basis->m_belongsTo);
    scopeLeave(gen, backup);
}

Slot Gen::addAccess(Gen *gen, Slot objectSlot, Slot keySlot) {
    Instruction::Access access;
    access.m_type = kAccess;
    access.m_belongsTo = nullptr;
    access.m_objectSlot = objectSlot;
    access.m_keySlot = keySlot;
    access.m_targetSlot = gen->m_slot++;
    addInstruction(gen, sizeof access, (Instruction *)&access);
    return access.m_targetSlot;
}

void Gen::addAssign(Gen *gen, Slot objectSlot, Slot keySlot, Slot valueSlot, AssignType assignType) {
    Instruction::Assign assign;
    assign.m_type = kAssign;
    assign.m_belongsTo = nullptr;
    assign.m_objectSlot = objectSlot;
    assign.m_keySlot = keySlot;
    assign.m_valueSlot = valueSlot;
    assign.m_assignType = assignType;
    addInstruction(gen, sizeof assign, (Instruction *)&assign);
}

void Gen::addCloseObject(Gen *gen, Slot objectSlot) {
    Instruction::CloseObject closeObject;
    closeObject.m_type = kCloseObject;
    closeObject.m_belongsTo = nullptr;
    closeObject.m_slot = objectSlot;
    addInstruction(gen, sizeof closeObject, (Instruction *)&closeObject);
}

void Gen::addSetConstraint(Gen *gen, Slot objectSlot, Slot keySlot, Slot constraintSlot) {
    Instruction::SetConstraint setConstraint;
    setConstraint.m_type = kSetConstraint;
    setConstraint.m_belongsTo = nullptr;
    setConstraint.m_objectSlot = objectSlot;
    setConstraint.m_keySlot = keySlot;
    setConstraint.m_constraintSlot = constraintSlot;
    addInstruction(gen, sizeof setConstraint, (Instruction *)&setConstraint);
}

Slot Gen::addNewObject(Gen *gen, Slot parentSlot) {
    Instruction::NewObject newObject;
    newObject.m_type = kNewObject;
    newObject.m_belongsTo = nullptr;
    newObject.m_targetSlot = gen->m_slot++;
    newObject.m_parentSlot = parentSlot;
    addInstruction(gen, sizeof newObject, (Instruction *)&newObject);
    return gen->m_slot - 1;
}

Slot Gen::addNewIntObject(Gen *gen, int value) {
    Instruction::NewIntObject newIntObject;
    newIntObject.m_type = kNewIntObject;
    newIntObject.m_belongsTo = nullptr;
    newIntObject.m_targetSlot = gen->m_slot++;
    newIntObject.m_value = value;
    newIntObject.m_intObject = nullptr;
    addInstruction(gen, sizeof newIntObject, (Instruction *)&newIntObject);
    return gen->m_slot - 1;
}

Slot Gen::addNewFloatObject(Gen *gen, float value) {
    Instruction::NewFloatObject newFloatObject;
    newFloatObject.m_type = kNewFloatObject;
    newFloatObject.m_belongsTo = nullptr;
    newFloatObject.m_targetSlot = gen->m_slot++;
    newFloatObject.m_value = value;
    newFloatObject.m_floatObject = nullptr;
    addInstruction(gen, sizeof newFloatObject, (Instruction *)&newFloatObject);
    return gen->m_slot - 1;
}

Slot Gen::addNewArrayObject(Gen *gen) {
    Instruction::NewArrayObject newArrayObject;
    newArrayObject.m_type = kNewArrayObject;
    newArrayObject.m_belongsTo = nullptr;
    newArrayObject.m_targetSlot = gen->m_slot++;
    addInstruction(gen, sizeof newArrayObject, (Instruction *)&newArrayObject);
    return gen->m_slot - 1;
}

Slot Gen::addNewStringObject(Gen *gen, const char *value) {
    Instruction::NewStringObject newStringObject;
    newStringObject.m_type = kNewStringObject;
    newStringObject.m_belongsTo = nullptr;
    newStringObject.m_targetSlot = gen->m_slot++;
    newStringObject.m_value = value;
    newStringObject.m_stringObject = nullptr;
    addInstruction(gen, sizeof newStringObject, (Instruction *)&newStringObject);
    return gen->m_slot - 1;
}

Slot Gen::addNewClosureObject(Gen *gen, UserFunction *function) {
    Instruction::NewClosureObject newClosureObject;
    newClosureObject.m_type = kNewClosureObject;
    newClosureObject.m_belongsTo = nullptr;
    newClosureObject.m_targetSlot = gen->m_slot++;
    newClosureObject.m_function = function;
    addInstruction(gen, sizeof newClosureObject, (Instruction *)&newClosureObject);
    return gen->m_slot - 1;
}

Slot Gen::addCall(Gen *gen, Slot functionSlot, Slot thisSlot, Slot *arguments, size_t count) {
    // Avoid allocating memory for function calls with few arguments
    Instruction::Call *call = nullptr;
    unsigned char storage[sizeof *call + sizeof(Slot) * 10];
    if (count <= 10)
        call = (Instruction::Call *)storage;
    else
        call = (Instruction::Call *)Memory::allocate(sizeof *call + sizeof *arguments * count);
    call->m_type = kCall;
    call->m_belongsTo = nullptr;
    call->m_functionSlot = functionSlot;
    call->m_thisSlot = thisSlot;
    call->m_count = count;
    memcpy((Slot *)(call + 1), arguments, sizeof *arguments * count);
    addInstruction(gen, sizeof *call + sizeof *arguments * count, (Instruction *)call);
    if (count > 10)
        Memory::free(call);

    Instruction::SaveResult saveResult;
    saveResult.m_type = kSaveResult;
    saveResult.m_targetSlot = gen->m_slot++;
    addInstruction(gen, sizeof saveResult, (Instruction *)&saveResult);

    return gen->m_slot - 1;
}

Slot Gen::addCall(Gen *gen, Slot functionSlot, Slot thisSlot) {
    return addCall(gen, functionSlot, thisSlot, nullptr, 0);
}

Slot Gen::addCall(Gen *gen, Slot functionSlot, Slot thisSlot, Slot argument0) {
    Slot arguments[1];
    arguments[0] = argument0;
    return addCall(gen, functionSlot, thisSlot, arguments, 1);
}

Slot Gen::addCall(Gen *gen, Slot functionSlot, Slot thisSlot, Slot argument0, Slot argument1) {
    Slot arguments[2];
    arguments[0] = argument0;
    arguments[1] = argument1;
    return addCall(gen, functionSlot, thisSlot, arguments, 2);
}

void Gen::addTestBranch(Gen *gen, Slot testSlot, BlockRef *trueBranch, BlockRef *falseBranch) {
    Instruction::TestBranch testBranch;
    testBranch.m_type = kTestBranch;
    testBranch.m_belongsTo = nullptr;
    testBranch.m_testSlot = testSlot;
    *trueBranch = newBlockRef(gen, (unsigned char *)&testBranch, (unsigned char *)&testBranch.m_trueBlock);
    *falseBranch = newBlockRef(gen, (unsigned char *)&testBranch, (unsigned char *)&testBranch.m_falseBlock);

    addInstruction(gen, sizeof testBranch, (Instruction *)&testBranch);
}

void Gen::addBranch(Gen *gen, BlockRef *branchBlock) {
    Instruction::Branch branch;
    branch.m_type = kBranch;
    branch.m_belongsTo = nullptr;
    *branchBlock = newBlockRef(gen, (unsigned char *)&branch, (unsigned char *)&branch.m_block);
    addInstruction(gen, sizeof branch, (Instruction *)&branch);
}

void Gen::addReturn(Gen *gen, Slot returnSlot) {
    Instruction::Return return_;
    return_.m_type = kReturn;
    return_.m_belongsTo = nullptr;
    return_.m_returnSlot = returnSlot;

    addInstruction(gen, sizeof return_, (Instruction *)&return_);
}

void Gen::addFreeze(Gen *gen, Slot object) {
    Instruction::Freeze freeze;
    freeze.m_type = kFreeze;
    freeze.m_belongsTo = nullptr;
    freeze.m_slot = object;
    addInstruction(gen, sizeof freeze, (Instruction *)&freeze);
}

Slot Gen::addDefineFastSlot(Gen *gen, Slot objectSlot, const char *key) {
    Instruction::DefineFastSlot defineFastSlot;
    const size_t keyLength = strlen(key);
    defineFastSlot.m_type = kDefineFastSlot;
    defineFastSlot.m_belongsTo = nullptr;
    defineFastSlot.m_objectSlot = objectSlot;
    defineFastSlot.m_key = key;
    defineFastSlot.m_keyLength = keyLength;
    defineFastSlot.m_keyHash = djb2(key, keyLength);
    defineFastSlot.m_targetSlot = gen->m_fastSlot++;
    addInstruction(gen, sizeof defineFastSlot, (Instruction *)&defineFastSlot);
    return defineFastSlot.m_targetSlot;
}

void Gen::addReadFastSlot(Gen *gen, Slot sourceSlot, Slot targetSlot) {
    Instruction::ReadFastSlot readFastSlot;
    readFastSlot.m_type = kReadFastSlot;
    readFastSlot.m_belongsTo = nullptr;
    readFastSlot.m_sourceSlot = sourceSlot;
    readFastSlot.m_targetSlot = targetSlot;
    addInstruction(gen, sizeof readFastSlot, (Instruction *)&readFastSlot);
}

void Gen::addWriteFastSlot(Gen *gen, Slot sourceSlot, Slot targetSlot) {
    Instruction::WriteFastSlot writeFastSlot;
    writeFastSlot.m_type = kWriteFastSlot;
    writeFastSlot.m_belongsTo = nullptr;
    writeFastSlot.m_sourceSlot = sourceSlot;
    writeFastSlot.m_targetSlot = targetSlot;
    addInstruction(gen, sizeof writeFastSlot, (Instruction *)&writeFastSlot);
}

UserFunction *Gen::buildFunction(Gen *gen) {
    U_ASSERT(gen->m_blockTerminated);
    UserFunction *function = (UserFunction *)Memory::allocate(sizeof *function);
    function->m_arity = gen->m_count;
    function->m_slots = gen->m_slot;
    function->m_fastSlots = gen->m_fastSlot;
    function->m_name = gen->m_name;
    function->m_body = gen->m_body;
    function->m_isMethod = false;
    function->m_hasVariadicTail = gen->m_hasVariadicTail;
    return function;
}

UserFunction *Gen::optimize(UserFunction *function) {
    function = Optimize::inlinePass(function);
    function = Optimize::predictPass(function);
    function = Optimize::fastSlotPass(function);
    return function;
}

Slot Gen::scopeEnter(Gen *gen) {
    gen->m_lastScope = gen->m_scope;
    return gen->m_scope;
}

void Gen::scopeLeave(Gen *gen, Slot backup) {
    scopeSet(gen, backup);
}

void Gen::scopeSet(Gen *gen, Slot scope) {
    gen->m_scope = scope;
}

}


text:
<?php namespace CoandaCMS\CoandaWebForms\FieldTypes;

use CoandaCMS\CoandaWebForms\FieldType;

class Country extends FieldType {

    /**
     * @return string
     */
    public function name()
    {
        return 'Country List';
    }

    /**
     * @return string
     */
    public function identifier()
    {
        return 'country';
    }
}


text:
import pytest

from icap import ICAPRequest, ICAPResponse, RequestLine, HeadersDict, HTTPRequest, HTTPResponse, StatusLine
from icap.errors import ICAPAbort
from icap.models import ICAPMessage, HTTPMessage

class TestHTTPMessage(object):
    def test_is_request_and_is_response(self):
        m = HTTPMessage()
        assert not (m.is_request or m.is_response)

        m = HTTPRequest()
        assert m.is_request
        assert not m.is_response

        m = HTTPResponse()
        assert not m.is_request
        assert m.is_response

    @pytest.mark.parametrize('cls', [
        HTTPRequest,
        HTTPResponse,
    ])
    def test_default_attributes(self, cls):
        m = cls()

        assert m.request_line == RequestLine('GET', '/', 'HTTP/1.1')
        assert m.headers == HeadersDict()

        if cls == HTTPResponse:
            assert m.request_headers == HeadersDict()
            assert m.status_line == StatusLine('HTTP/1.1', 200, 'OK')

    def test_body_setter(self):
        m = HTTPMessage()

        m.body = b'foo'
        assert m.body_bytes == b'foo'

        try:
            m.body = 1
        except TypeError:
            pass
        else:
            assert False, "invalid body type should throw error"

        m.body = 'non-bytestring'

        m.headers['Content-Type'] = 'text/plain'

        try:
            m.body = 'non-bytestring'
        except TypeError:
            pass
        else:
            assert False, "Content-Type with no charset should raise TypeError"

        m.headers.replace('Content-Type', 'image/png')

        try:
            m.body = 'non-bytestring'
        except TypeError:
            pass
        else:
            assert False, "Content-Type with no charset should raise TypeError"

class TestICAPMessage(object):
    def test_is_response_and_is_response(self):
        m = ICAPMessage()
        assert not (m.is_request or m.is_response)

        m = ICAPRequest()
        assert m.is_request
        assert not m.is_response

        m = ICAPResponse()
        assert not m.is_request
        assert m.is_response

    def test_has_body(self):
        r = self.request('OPTIONS')
        assert not r.has_body

        r = self.request('OPTIONS')
        r.headers['Encapsulated'] = 'null-body=0'
        assert not r.has_body

        r = self.request('REQMOD')
        r.headers['Encapsulated'] = 'req-body=0'
        assert r.has_body

        r = self.request('RESPMOD')
        r.headers['Encapsulated'] = 'resp-body=0'
        assert r.has_body

    def request(self, method, *args, **kwargs):
        return ICAPRequest(RequestLine(method, '/', 'ICAP/1.0'), *args, **kwargs)

class TestICAPRequest(object):
    def test_allow_204(self):
        request = self.request('REQMOD')
        assert not request.allow_204

        request = self.request('REQMOD', headers=HeadersDict([('Allow', '204')]))
        assert request.allow_204

    def test_init_defaults(self):
        d = ICAPRequest()
        assert bytes(d.request_line) == b'UNKNOWN / ICAP/1.0'

    def test_is_reqmod(self):
        assert self.request('REQMOD').is_reqmod
        assert not self.request('RESPMOD').is_reqmod

    def test_is_respmod(self):
        assert self.request('RESPMOD').is_respmod
        assert not self.request('REQMOD').is_respmod

    def test_is_options(self):
        assert not self.request('REQMOD').is_options
        assert not self.request('RESPMOD').is_options
        assert self.request('OPTIONS').is_options

    def request(self, method, *args, **kwargs):
        return ICAPRequest(RequestLine(method, '/', 'ICAP/1.0'), *args, **kwargs)

class TestICAPResponse(object):
    def test_from_error(self):
        s = ICAPResponse.from_error(200)
        assert bytes(s) == b'ICAP/1.0 200 OK\r\n'

        s = ICAPResponse.from_error(ICAPAbort(200))
        assert bytes(s) == b'ICAP/1.0 200 OK\r\n'

        s = ICAPResponse.from_error(ICAPAbort(204))
        assert bytes(s) == b'ICAP/1.0 204 No Modifications Needed\r\n'

        headers = HeadersDict([
            ('header', 'value'),
        ])

        s = ICAPResponse.from_error(ICAPAbort(204))
        s.headers = headers
        assert bytes(s) == b'ICAP/1.0 204 No Modifications Needed\r\nheader: value\r\n'

def test_StatusLine_defaults():
    s = StatusLine('HTTP/1.1', 200)
    assert s.reason == 'OK'

    s = StatusLine('ICAP/1.1', 204)
    assert s.reason == 'No Modifications Needed'

def test_HeadersDict():
    h = HeadersDict()
    h['Foo'] = 'bar'
    h['Foo'] = 'baz'

    assert h['foo'] == 'bar'
    assert h['FOO'] == 'bar'
    assert h.get('foo') == 'bar'
    assert h.get('bar') is None
    assert h.get('baz', 'asdf') == 'asdf'
    assert h.getlist('foo') == ['bar', 'baz']
    assert h.getlist('bar') == []

    h.replace('Foo', 'bar')
    assert h.getlist('Foo') == ['bar']

    b = HeadersDict()

    for i in range(6):
        b['Foo'] = 'bar'

    a = HeadersDict([
        ('Foo', 'bar'),
        ('Foo', 'bar'),
        ('Foo', 'bar'),
        ('Foo', 'bar'),
        ('Foo', 'bar'),
        ('Foo', 'bar'),
    ])

    c = HeadersDict([
        ('lamp', 'i love lamp'),
    ])

    d = HeadersDict([
        ('lamp', 'i dont love lamp'),
    ])

    assert 'LAMP' in d
    assert 'LaMp' in d
    assert 'lamp' in d

    assert a == b
    assert a != c
    assert c != d

    assert bytes(a) == '\r\n'.join(['Foo: bar']*6).encode('utf8') + b'\r\n'
    assert bytes(c) == b'lamp: i love lamp\r\n'
    assert bytes(d) == b'lamp: i dont love lamp\r\n'
    assert bytes(HeadersDict()) == b''

    e = HeadersDict()

    e['foo'] = b'bar'
    e[b'bar'] = 'baz'
    try:
        b[1] = 'bar'
    except TypeError:
        pass
    else:
        assert False, "non-str key should raise TypeError"
    try:
        b['baz'] = 1
    except TypeError:
        pass
    else:
        assert False, "non-str value should raise TypeError"

    assert e['foo'] == 'bar'
    assert e[b'bar'] == 'baz'
    assert b'bar' in e


text:
title: "Class 3: HTML Basics 2"
date: 2017-09-12 12:00:00
description: "HTML Lists, Links, Images, Tables, Forms and Extra Markup"
assignment: HTML Basics 2
reading:

HTML&CSS - Ch. 3 Lists, Ch.4 Links, Ch. 5 Images, Ch.6 Tables, Ch.7 Forms, Ch.8 Extra Markup

Absolute vs. Relative Paths and Links (Just Scan)

due: HTML Basics 1 and Explore RWD Group 2
part: "1"
layout: wide
current: no
semester: fall-2017
slides: "/class/slides/3/3-Slides-RWD.pdf"
status: blog-post-date--past

---

## Outline

* HTML Basics 1 Discussion (20 min - end 5:50)
* Remaining Case Studies (15 min - end 6:10)
* HTML: Lists/Links/RWD (20 min - end 6:30)
* Research Discussion (15 min - end 6:45)
* BREAK (5 min)
* Semester Project Introduction & Groups (15 min - end 7:00)
* Research Assignment Discussion (15 min - end 7:15)
* Set up GitHub Repository (40 min - end 8:00)


text:
<?php

namespace AcceptOn;

/**
 * @property bool $active The activity status of the subscription.
 * @property string $email The email belonging to the subscription.
 * @property string $id The subscription identifier.
 * @property string $lastBilledAt The time the subscription was last billed.
 * @property AcceptOn\Plan $plan The plan the subscription is connected to.
 */
class Subscription extends \AcceptOn\Base
{
    protected static $allowedProperties = array(
        "active" => "bool",
        "email" => "string",
        "id" => "string",
        "lastBilledAt" => "date",
        "plan" => "AcceptOn\Plan",
    );
}


text:
package com.example.google.playservices.placecomplete;

/**
 * Created by Dr.Abhay on 08-06-2015.
 */
public class DataBean {
    String age;
    String username;
    String gender;
    String outofway;
    String source;
    String dest;

    public String getRideid() {
        return rideid;
    }

    public void setRideid(String rideid) {
        this.rideid = rideid;
    }

    String rideid;

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getOutofway() {
        return outofway;
    }

    public void setOutofway(String outofway) {
        this.outofway = outofway;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getDest() {
        return dest;
    }

    public void setDest(String dest) {
        this.dest = dest;
    }

    public DataBean(String a, String b, String c, String d, String e, String f, String g) {
        age=a;
        username=b;
        gender=c;
        outofway=d;
        source=e;
        dest=f;
        rideid=g;
    }

}


text:
// Copyright NVIDIA Corporation 2011-2015
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//  * Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//  * Neither the name of NVIDIA CORPORATION nor the names of its
//    contributors may be used to endorse or promote products derived
//    from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include <dp/rix/gl/inc/ContainerGL.h>
#include <dp/rix/gl/inc/BufferGL.h>
#include <dp/rix/gl/inc/Sampler.h>
#include <dp/rix/gl/inc/DataTypeConversionGL.h>
#include <algorithm>
#include <cstring>
#include <typeinfo>
#include <dp/rix/gl/RiXGL.h>

namespace dp
{
  namespace rix
  {
    namespace gl
    {
      using namespace dp::rix::core;

      using dp::Int8;
      using dp::Int16;
      using dp::Int32;
      using dp::Int64;

      using dp::Uint8;
      using dp::Uint16;
      using dp::Uint32;
      using dp::Uint64;

      size_t getSizeOfComponent( ContainerParameterType parameterType )
      {
        switch ( parameterType )
        {
        case CPT_FLOAT:
        case CPT_FLOAT2:
        case CPT_FLOAT3:
        case CPT_FLOAT4:
          return sizeof(float);

        case CPT_INT_8:
        case CPT_INT2_8:
        case CPT_INT3_8:
        case CPT_INT4_8:
          return sizeof(Int8);

        case CPT_INT_16:
        case CPT_INT2_16:
        case CPT_INT3_16:
        case CPT_INT4_16:
          return sizeof(Int16);

        case CPT_INT_32:
        case CPT_INT2_32:
        case CPT_INT3_32:
        case CPT_INT4_32:
          return sizeof(Int32);

        case CPT_INT_64:
        case CPT_INT2_64:
        case CPT_INT3_64:
        case CPT_INT4_64:
          return sizeof(Int64);

        case CPT_UINT_8:
        case CPT_UINT2_8:
        case CPT_UINT3_8:
        case CPT_UINT4_8:
          return sizeof(Uint8);

        case CPT_UINT_16:
        case CPT_UINT2_16:
        case CPT_UINT3_16:
        case CPT_UINT4_16:
          return sizeof(Uint16);

        case CPT_UINT_32:
        case CPT_UINT2_32:
        case CPT_UINT3_32:
        case CPT_UINT4_32:
          return sizeof(Uint32);

        case CPT_UINT_64:
        case CPT_UINT2_64:
        case CPT_UINT3_64:
        case CPT_UINT4_64:
          return sizeof(Uint64);

        case CPT_BOOL:
        case CPT_BOOL2:
        case CPT_BOOL3:
        case CPT_BOOL4:
          return sizeof(Uint8);

        case CPT_MAT2X2:
        case CPT_MAT2X3:
        case CPT_MAT2X4:
          return sizeof(float);

        case CPT_MAT3X2:
        case CPT_MAT3X3:
        case CPT_MAT3X4:
          return sizeof(float);

        case CPT_MAT4X2:
        case CPT_MAT4X3:
        case CPT_MAT4X4:
          return sizeof(float);

        case CPT_BUFFER_ADDRESS:
          return sizeof(long long); // 64 bit value

        case CPT_SAMPLER:
          return sizeof(ContainerGL::ParameterDataSampler);

        case CPT_IMAGE:
          return sizeof(ContainerGL::ParameterDataImage);

        case CPT_BUFFER:
          return sizeof(ContainerGL::ParameterDataBuffer);

        case CPT_CALLBACK:
          return sizeof(CallbackObject);

        default:
          DP_ASSERT( !"unsupported parameter type" );
          return 0;
        }
      }

      size_t getSizeOf( ContainerParameterType parameterType )
      {
        switch ( parameterType )
        {
        case CPT_FLOAT:
          return sizeof(float);
        case CPT_FLOAT2:
          return sizeof(float) * 2;
        case CPT_FLOAT3:
          return sizeof(float) * 3;
        case CPT_FLOAT4:
          return sizeof(float) * 4;

        case CPT_INT_8:
          return sizeof(Int8);
        case CPT_INT2_8:
          return sizeof(Int8) * 2;
        case CPT_INT3_8:
          return sizeof(Int8) * 3;
        case CPT_INT4_8:
          return sizeof(Int8) * 4;

        case CPT_INT_16:
          return sizeof(Int16);
        case CPT_INT2_16:
          return sizeof(Int16) * 2;
        case CPT_INT3_16:
          return sizeof(Int16) * 3;
        case CPT_INT4_16:
          return sizeof(Int16) * 4;

        case CPT_INT_32:
          return sizeof(Int32);
        case CPT_INT2_32:
          return sizeof(Int32) * 2;
        case CPT_INT3_32:
          return sizeof(Int32) * 3;
        case CPT_INT4_32:
          return sizeof(Int32) * 4;

        case CPT_INT_64:
          return sizeof(Int64);
        case CPT_INT2_64:
          return sizeof(Int64) * 2;
        case CPT_INT3_64:
          return sizeof(Int64) * 3;
        case CPT_INT4_64:
          return sizeof(Int64) * 4;

        case CPT_UINT_8:
          return sizeof(Uint8);
        case CPT_UINT2_8:
          return sizeof(Uint8) * 2;
        case CPT_UINT3_8:
          return sizeof(Uint8) * 3;
        case CPT_UINT4_8:
          return sizeof(Uint8) * 4;

        case CPT_UINT_16:
          return sizeof(Uint16);
        case CPT_UINT2_16:
          return sizeof(Uint16) * 2;
        case CPT_UINT3_16:
          return sizeof(Uint16) * 3;
        case CPT_UINT4_16:
          return sizeof(Uint16) * 4;

        case CPT_UINT_32:
          return sizeof(Uint32);
        case CPT_UINT2_32:
          return sizeof(Uint32) * 2;
        case CPT_UINT3_32:
          return sizeof(Uint32) * 3;
        case CPT_UINT4_32:
          return sizeof(Uint32) * 4;

        case CPT_UINT_64:
          return sizeof(Uint64);
        case CPT_UINT2_64:
          return sizeof(Uint64) * 2;
        case CPT_UINT3_64:
          return sizeof(Uint64) * 3;
        case CPT_UINT4_64:
          return sizeof(Uint64) * 4;

        case CPT_BOOL:
          return sizeof(Uint8);
        case CPT_BOOL2:
          return sizeof(Uint8) * 2;
        case CPT_BOOL3:
          return sizeof(Uint8) * 3;
        case CPT_BOOL4:
          return sizeof(Uint8) * 4;

        case CPT_MAT2X2:
          return sizeof(float) * 4;
        case CPT_MAT2X3:
          return sizeof(float) * 6;
        case CPT_MAT2X4:
          return sizeof(float) * 8;

        case CPT_MAT3X2:
          return sizeof(float) * 6;
        case CPT_MAT3X3:
          return sizeof(float) * 9;
        case CPT_MAT3X4:
          return sizeof(float) * 12;

        case CPT_MAT4X2:
          return sizeof(float) * 8;
        case CPT_MAT4X3:
          return sizeof(float) * 12;
        case CPT_MAT4X4:
          return sizeof(float) * 16;

        case CPT_BUFFER_ADDRESS:
          return sizeof(long long); // 64 bit value

        case CPT_SAMPLER:
          return sizeof(ContainerGL::ParameterDataSampler);

        case CPT_IMAGE:
          return sizeof(ContainerGL::ParameterDataImage);

        case CPT_BUFFER:
          return sizeof(ContainerGL::ParameterDataBuffer);

        case CPT_CALLBACK:
          return sizeof(CallbackObject);

        default:
          DP_ASSERT( !"unsupported parameter type" );
          return 0;
        }
      }

      // initialize the first used id to something > 0
      unsigned int ContainerDescriptorGL::m_freeId = 42;

      ContainerDescriptorGL::ContainerDescriptorGL( RiXGL* renderer, size_t numParameters, ProgramParameter* parameters )
        : m_id( m_freeId++ << 16 )
        , m_size(0)
        , m_renderer(renderer)
      {
        for ( size_t i = 0; i < numParameters; ++i )
        {
          ContainerDescriptorGL::ParameterInfo pi;

          pi.m_type      = parameters[i].m_type;
          pi.m_name      = parameters[i].m_name;
          pi.m_offset    = m_size;
          pi.m_arraySize = parameters[i].m_arraySize;

          // TODO: move all size types from unsigned int to size_t?
          // CK: why? hardly likely we have single arrays/types above 4 gb, keeps thing tight in cache
          pi.m_elementSize  = (unsigned int)getSizeOf( pi.m_type );
          pi.m_componentSize = (unsigned int)getSizeOfComponent( pi.m_type );

          pi.m_size = pi.m_elementSize * std::max<unsigned int>(pi.m_arraySize, 1);
          m_parameterInfos.push_back( pi );
          m_size += pi.m_size;
        }
      }

      ContainerGL::ContainerGL(dp::rix::gl::RiXGL *renderer, ContainerDescriptorGLSharedHandle const & desc)
        : m_descriptor( desc )
        , m_size( desc->m_size )
        , m_data( nullptr )
        , m_count( 0 )
        , m_renderer(renderer)
      {
        m_uniqueID = renderer->aquireContainerID();
        if ( m_size )
        {
          m_data = malloc( m_size );
          // must be initialized with 0 so that pointer references can
          // be detected properly
          memset( m_data, 0, m_size );
          DP_ASSERT( m_data );
        }
      }

      ContainerGL::~ContainerGL()
      {
        m_renderer->releaseUniqueContainerID(m_uniqueID);
        for (size_t index = 0; index < m_descriptor->m_parameterInfos.size(); index++)
        {
          const ContainerDescriptorGL::ParameterInfo &descr = m_descriptor->m_parameterInfos[index];
          switch( descr.m_type )
          {
          case CPT_SAMPLER:
            {
              char* selfdata = static_cast<char*>(m_data) + descr.m_offset;
              ParameterDataSampler* parameterData = reinterpret_cast<ParameterDataSampler*>(selfdata);

              if ( parameterData->m_samplerHandle )
              {
                parameterData->m_samplerHandle->detach( this );
                handleReset( parameterData->m_samplerHandle );
              }
            }
            break;
          case CPT_IMAGE:
            {
              char* selfdata = static_cast<char*>(m_data) + descr.m_offset;
              ParameterDataImage* parameterImage = reinterpret_cast<ParameterDataImage*>(selfdata);

              handleReset( parameterImage->m_textureHandle );
            }
            break;
          case CPT_BUFFER:
            {
              DP_ASSERT( (descr.m_size / descr.m_elementSize) == 1);

              char* selfdata =  static_cast<char*>(m_data) + descr.m_offset;
              ParameterDataBuffer *parameterData = reinterpret_cast<ParameterDataBuffer*>(selfdata);
              if ( parameterData->m_bufferHandle )
              {
                parameterData->m_bufferHandle->detach( this );
                handleReset(parameterData->m_bufferHandle);
              }
            }
            break;
          default:
            break;
          }
        }

        free(m_data);
      }

      void ContainerGL::setData( ContainerEntry entry, const ContainerData& containerData )
      {
        unsigned short index = m_descriptor->getIndex( entry );
        if ( index != (unsigned short)(~0) )
        {
          DP_ASSERT(index < m_descriptor->m_parameterInfos.size());

          const ContainerDescriptorGL::ParameterInfo &parameterInfo = m_descriptor->m_parameterInfos[index];

          switch ( containerData.getContainerDataType() )
          {
          case CDT_RAW:
            DP_ASSERT( dynamic_cast<const ContainerDataRaw*>(&containerData) );
            setData( parameterInfo, static_cast<const ContainerDataRaw&>( containerData ) );
            break;
          case CDT_BUFFER:
            DP_ASSERT( dynamic_cast<const ContainerDataBuffer*>(&containerData) );
            setData( parameterInfo, static_cast<const ContainerDataBuffer&>( containerData ) );
            break;
          case CDT_SAMPLER:
            DP_ASSERT( dynamic_cast<const ContainerDataSampler*>(&containerData) );
            setData( parameterInfo, static_cast<const ContainerDataSampler&>( containerData ) );
            break;
          case CDT_IMAGE:
            DP_ASSERT( dynamic_cast< const ContainerDataImage*>(&containerData) );
            setData( parameterInfo, static_cast<const ContainerDataImage&>( containerData ) );
            break;
          default:
            DP_ASSERT(!"Unsupported ContainerData type.");
            // returning here. Since nothing has changes it's not necessary to notify.
            return;
          }
          notify( ContainerGL::Event(this) );
        }
      }

      void ContainerGL::setData( const ContainerDescriptorGL::ParameterInfo& parameterInfo, const ContainerDataRaw& containerData )
      {
        size_t size = containerData.m_size;
        size_t offset = containerData.m_offset;
        const void *data = containerData.m_data;

        if ( size + offset <= parameterInfo.m_size )
        {
          DP_ASSERT ( (size   % parameterInfo.m_componentSize == 0) && "update size not multiple of component size" );
          DP_ASSERT ( (offset % parameterInfo.m_componentSize == 0) && "update offset not multiple of component size" );

          switch( parameterInfo.m_type )
          {
          case CPT_FLOAT:
          case CPT_FLOAT2:
          case CPT_FLOAT3:
          case CPT_FLOAT4:
          case CPT_INT_8:
          case CPT_INT2_8:
          case CPT_INT3_8:
          case CPT_INT4_8:
          case CPT_INT_16:
          case CPT_INT2_16:
          case CPT_INT3_16:
          case CPT_INT4_16:
          case CPT_INT_32:
          case CPT_INT2_32:
          case CPT_INT3_32:
          case CPT_INT4_32:
          case CPT_INT_64:
          case CPT_INT2_64:
          case CPT_INT3_64:
          case CPT_INT4_64:
          case CPT_UINT_8:
          case CPT_UINT2_8:
          case CPT_UINT3_8:
          case CPT_UINT4_8:
          case CPT_UINT_16:
          case CPT_UINT2_16:
          case CPT_UINT3_16:
          case CPT_UINT4_16:
          case CPT_UINT_32:
          case CPT_UINT2_32:
          case CPT_UINT3_32:
          case CPT_UINT4_32:
          case CPT_UINT_64:
          case CPT_UINT2_64:
          case CPT_UINT3_64:
          case CPT_UINT4_64:
          case CPT_BOOL:
          case CPT_BOOL2:
          case CPT_BOOL3:
          case CPT_BOOL4:
          case CPT_MAT2X2: // DAR What about transpose handling?
          case CPT_MAT2X3:
          case CPT_MAT2X4:
          case CPT_MAT3X2:
          case CPT_MAT3X3:
          case CPT_MAT3X4:
          case CPT_MAT4X2:
          case CPT_MAT4X3:
          case CPT_MAT4X4:
          case CPT_BUFFER_ADDRESS:
          case CPT_CALLBACK:
            {
              memcpy( static_cast<char*>(m_data) + parameterInfo.m_offset + offset, data, size );
            }
            break;
          default:
            DP_ASSERT( !"unsupported ContainerParameterType!" );
            // returning here. Since nothing has changes it's not necessary to notify.
            return;
          }
          notify( ContainerGL::Event(this) );
        }
        else
        {
          DP_ASSERT(!"Container buffer not big enough to hold data.");
        }
      }

      void ContainerGL::setData( const ContainerDescriptorGL::ParameterInfo& parameterInfo, const ContainerDataBuffer& containerData )
      {
        switch (parameterInfo.m_type)
        {
        case CPT_BUFFER:
          {
            char* selfdata =  static_cast<char*>(m_data) + parameterInfo.m_offset;
            ParameterDataBuffer* parameterData = reinterpret_cast<ParameterDataBuffer*>(selfdata);

            if ( parameterData->m_bufferHandle != containerData.m_bufferHandle.get() )
            {
              BufferGLHandle bufferGL = containerData.m_bufferHandle ? handleCast<BufferGL>(containerData.m_bufferHandle.get()) : nullptr;

              // observe buffer to get notified about buffer size changes
              if ( parameterData->m_bufferHandle )
              {
                parameterData->m_bufferHandle->detach( this );
              }

              if ( bufferGL )
              {
                bufferGL->attach( this );
              }

              // assign new buffer
              handleAssign( parameterData->m_bufferHandle, bufferGL );
            }

            parameterData->m_offset   = containerData.m_offset;
            parameterData->m_length   = containerData.m_length;

          }
          break;
        default:
          // returning here. Since nothing has changes it's not necessary to notify.
          DP_ASSERT(!"Unsupported combination of ContainerParameterType and ContainerDataType.");
          return;
        }
        notify( ContainerGL::Event(this) );
      }

      void ContainerGL::setData( const ContainerDescriptorGL::ParameterInfo& parameterInfo, const ContainerDataSampler& containerData )
      {
        switch ( parameterInfo.m_type )
        {
        case CPT_SAMPLER:
          {
            char* selfdata = static_cast<char*>(m_data) + parameterInfo.m_offset;
            ParameterDataSampler* parameterData = reinterpret_cast<ParameterDataSampler*>(selfdata);

            if ( parameterData->m_samplerHandle )
            {
              parameterData->m_samplerHandle->detach( this );
            }

            handleAssign( parameterData->m_samplerHandle, handleCast<Sampler>( containerData.m_samplerHandle ) );

            if ( parameterData->m_samplerHandle )
            {
              parameterData->m_samplerHandle->attach( this );
            }

          }
          break;
        default:
          // returning here. Since nothing has changes it's not necessary to notify.
          DP_ASSERT(!"Unsupported combination of ContainerParameterType and ContainerDataType.");
          return;
        }
        notify( ContainerGL::Event(this) );
      }

      void ContainerGL::setData( const ContainerDescriptorGL::ParameterInfo& parameterInfo, const ContainerDataImage& containerData )
      {
        switch ( parameterInfo.m_type )
        {
        case CPT_IMAGE:
          {
            char* selfdata = static_cast<char*>(m_data) + parameterInfo.m_offset;
            ParameterDataImage* parameterDataImage = reinterpret_cast<ParameterDataImage*>(selfdata);
            if( containerData.m_textureHandle )
            {
              handleAssign( parameterDataImage->m_textureHandle, handleCast<TextureGL>(containerData.m_textureHandle) );
            }
            else
            {
              handleReset( parameterDataImage->m_textureHandle );
            }
            parameterDataImage->m_level   = containerData.m_level;
            parameterDataImage->m_layered = containerData.m_layered;
            parameterDataImage->m_layer   = containerData.m_layer;
            parameterDataImage->m_access  = getGLAccessMode( containerData.m_access );
          }
          break;
        default:
          DP_ASSERT(!"Unsupported combination of ContainerParameterType and ContainerDataType.");
          // returning here. Since nothing has changes it's not necessary to notify.
          return;
        }
        notify( ContainerGL::Event(this) );
      }

      void ContainerGL::onNotify( const dp::util::Event &event, dp::util::Payload* /*payload*/ )
      {
        if ( typeid(event) == typeid( const BufferGL::Event& ) )
        {
          // Buffer Events are only of interest if the size does change
          const BufferGL::Event& bufferEvent = static_cast<const BufferGL::Event&>(event);
          if ( bufferEvent.m_eventType == BufferGL::Event::DATA_AND_SIZE_CHANGED )
          {
            notify( ContainerGL::Event(this) );
          }
        }
        else
        {
          notify( ContainerGL::Event( this ) );
        }
      }

      void ContainerGL::onDestroyed( const dp::util::Subject& /*subject*/, dp::util::Payload* /*payload*/ )
      {
        DP_ASSERT( !"need to detach something?" );
      }

    } // namespace gl
  } // namespace rix
} // namespace dp


text:
.class Lcom/mediatek/mmsdk/CameraEffectImpl$CaptureCallbackHolder;
.super Ljava/lang/Object;
.source "CameraEffectImpl.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/mediatek/mmsdk/CameraEffectImpl;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x2
    name = "CaptureCallbackHolder"
.end annotation

# instance fields
.field private final mCaptureCallback:Lcom/mediatek/mmsdk/CameraEffectImpl$CaptureCallback;

.field private final mHandler:Landroid/os/Handler;

.field final synthetic this$0:Lcom/mediatek/mmsdk/CameraEffectImpl;

# direct methods
.method constructor <init>(Lcom/mediatek/mmsdk/CameraEffectImpl;Lcom/mediatek/mmsdk/CameraEffectImpl$CaptureCallback;Landroid/os/Handler;)V
    .locals 0
    .param p2, "callback"    # Lcom/mediatek/mmsdk/CameraEffectImpl$CaptureCallback;
    .param p3, "handler"    # Landroid/os/Handler;

    .prologue
    .line 770
    iput-object p1, p0, Lcom/mediatek/mmsdk/CameraEffectImpl$CaptureCallbackHolder;->this$0:Lcom/mediatek/mmsdk/CameraEffectImpl;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 771
    iput-object p2, p0, Lcom/mediatek/mmsdk/CameraEffectImpl$CaptureCallbackHolder;->mCaptureCallback:Lcom/mediatek/mmsdk/CameraEffectImpl$CaptureCallback;

    .line 772
    iput-object p3, p0, Lcom/mediatek/mmsdk/CameraEffectImpl$CaptureCallbackHolder;->mHandler:Landroid/os/Handler;

    .line 773
    return-void
.end method

# virtual methods
.method public getCaptureCallback()Lcom/mediatek/mmsdk/CameraEffectImpl$CaptureCallback;
    .locals 1

    .prologue
    .line 776
    iget-object v0, p0, Lcom/mediatek/mmsdk/CameraEffectImpl$CaptureCallbackHolder;->mCaptureCallback:Lcom/mediatek/mmsdk/CameraEffectImpl$CaptureCallback;

    return-object v0
.end method

.method public getHandler()Landroid/os/Handler;
    .locals 1

    .prologue
    .line 780
    iget-object v0, p0, Lcom/mediatek/mmsdk/CameraEffectImpl$CaptureCallbackHolder;->mHandler:Landroid/os/Handler;

    return-object v0
.end method


text:
import React from 'react';
import Icon from '../../../Icon';

const MediaDevicesControls = ({ snaps, areMultipleVideoDevices, handleVideoDeviceChange }) => (
  <div
    className="experiment__playground__content--media-devices__controls"
  >
    <div
      className="experiment__playground__content--media-devices__controls__strip"
    >
      {
        snaps && snaps.map((snap, index) => (
          <img
            className="experiment__playground__content--media-devices__controls__strip__item"
            alt={`Snap ${index}`}
            key={index}
            src={snap}
          />
        ))
      }
    </div>
    {areMultipleVideoDevices &&
      <button
        className="experiment__playground__content__button"
        onClick={handleVideoDeviceChange}
      >
        <Icon
          name="switch_video"
        />
      </button>
    }
  </div>
);

export default MediaDevicesControls;


text:
import {
  mixin,
  Mixin
} from 'ember-metal/mixin';

QUnit.module('Mixin Methods');

QUnit.test('defining simple methods', function() {
  let MixinA, obj, props;

  props = {
    publicMethod() { return 'publicMethod'; },
    _privateMethod() { return 'privateMethod'; }
  };

  MixinA = Mixin.create(props);
  obj = {};
  MixinA.apply(obj);

  // but should be defined
  equal(props.publicMethod(), 'publicMethod', 'publicMethod is func');
  equal(props._privateMethod(), 'privateMethod', 'privateMethod is func');
});

QUnit.test('overriding public methods', function() {
  let MixinA, MixinB, MixinD, MixinF, obj;

  MixinA = Mixin.create({
    publicMethod() { return 'A'; }
  });

  MixinB = Mixin.create(MixinA, {
    publicMethod() { return this._super(...arguments) + 'B'; }
  });

  MixinD = Mixin.create(MixinA, {
    publicMethod() { return this._super(...arguments) + 'D'; }
  });

  MixinF = Mixin.create({
    publicMethod() { return this._super(...arguments) + 'F'; }
  });

  obj = {};
  MixinB.apply(obj);
  equal(obj.publicMethod(), 'AB', 'should define super for A and B');

  obj = {};
  MixinD.apply(obj);
  equal(obj.publicMethod(), 'AD', 'should define super for A and B');

  obj = {};
  MixinA.apply(obj);
  MixinF.apply(obj);
  equal(obj.publicMethod(), 'AF', 'should define super for A and F');

  obj = { publicMethod() { return 'obj'; } };
  MixinF.apply(obj);
  equal(obj.publicMethod(), 'objF', 'should define super for F');
});

QUnit.test('overriding inherited objects', function() {
  let cnt = 0;
  let MixinA = Mixin.create({
    foo() { cnt++; }
  });

  let MixinB = Mixin.create({
    foo() {
      this._super(...arguments);
      cnt++;
    }
  });

  let objA = {};
  MixinA.apply(objA);

  let objB = Object.create(objA);
  MixinB.apply(objB);

  cnt = 0;
  objB.foo();
  equal(cnt, 2, 'should invoke both methods');

  cnt = 0;
  objA.foo();
  equal(cnt, 1, 'should not screw w/ parent obj');
});

QUnit.test('Including the same mixin more than once will only run once', function() {
  let cnt = 0;
  let MixinA = Mixin.create({
    foo() { cnt++; }
  });

  let MixinB = Mixin.create(MixinA, {
    foo() { this._super(...arguments); }
  });

  let MixinC = Mixin.create(MixinA, {
    foo() { this._super(...arguments); }
  });

  let MixinD = Mixin.create(MixinB, MixinC, MixinA, {
    foo() { this._super(...arguments); }
  });

  let obj = {};
  MixinD.apply(obj);
  MixinA.apply(obj); // try to apply again..

  cnt = 0;
  obj.foo();

  equal(cnt, 1, 'should invoke MixinA.foo one time');
});

QUnit.test('_super from a single mixin with no superclass does not error', function() {
  let MixinA = Mixin.create({
    foo() {
      this._super(...arguments);
    }
  });

  let obj = {};
  MixinA.apply(obj);

  obj.foo();
  ok(true);
});

QUnit.test('_super from a first-of-two mixins with no superclass function does not error', function() {
  // _super was previously calling itself in the second assertion.
  // Use remaining count of calls to ensure it doesn't loop indefinitely.
  let remaining = 3;
  let MixinA = Mixin.create({
    foo() {
      if (remaining-- > 0) {
        this._super(...arguments);
      }
    }
  });

  let MixinB = Mixin.create({
    foo() { this._super(...arguments); }
  });

  let obj = {};
  MixinA.apply(obj);
  MixinB.apply(obj);

  obj.foo();
  ok(true);
});

// ..........................................................
// CONFLICTS
//

QUnit.module('Method Conflicts');

QUnit.test('overriding toString', function() {
  let MixinA = Mixin.create({
    toString() { return 'FOO'; }
  });

  let obj = {};
  MixinA.apply(obj);
  equal(obj.toString(), 'FOO', 'should override toString w/o error');

  obj = {};
  mixin(obj, { toString() { return 'FOO'; } });
  equal(obj.toString(), 'FOO', 'should override toString w/o error');
});

// ..........................................................
// BUGS
//

QUnit.module('system/mixin/method_test BUGS');

QUnit.test('applying several mixins at once with sup already defined causes infinite loop', function() {
  let cnt = 0;
  let MixinA = Mixin.create({
    foo() { cnt++; }
  });

  let MixinB = Mixin.create({
    foo() {
      this._super(...arguments);
      cnt++;
    }
  });

  let MixinC = Mixin.create({
    foo() {
      this._super(...arguments);
      cnt++;
    }
  });

  let obj = {};
  mixin(obj, MixinA); // sup already exists
  mixin(obj, MixinB, MixinC); // must be more than one mixin

  cnt = 0;
  obj.foo();
  equal(cnt, 3, 'should invoke all 3 methods');
});