text:
package com.netflix.spinnaker.orca.pipeline;

import java.util.*;
import java.util.stream.Stream;
import com.netflix.spinnaker.orca.ExecutionStatus;
import com.netflix.spinnaker.orca.pipeline.model.Execution;
import com.netflix.spinnaker.orca.pipeline.model.Stage;
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner;
import com.netflix.spinnaker.orca.pipeline.model.Task;
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository;
import com.netflix.spinnaker.security.AuthenticatedRequest;
import static com.netflix.spinnaker.orca.pipeline.TaskNode.Builder;
import static com.netflix.spinnaker.orca.pipeline.TaskNode.GraphType.FULL;
import static com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionEngine.v2;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;

public interface StageDefinitionBuilder {

  default TaskNode.TaskGraph buildTaskGraph(Stage<?> stage) {
    Builder graphBuilder = Builder(FULL);
    taskGraph(stage, graphBuilder);
    return graphBuilder.build();
  }

  default <T extends Execution<T>> void taskGraph(Stage<T> stage, Builder builder) {
  }

  default <T extends Execution<T>> List<Stage<T>> aroundStages(Stage<T> stage) {
    return emptyList();
  }

  /**
   * @return the stage type this builder handles.
   */
  default String getType() {
    return StageDefinitionBuilderSupport.getType(this.getClass());
  }

  // TODO: simplify signature once v2 is phased out
  default Stage prepareStageForRestart(
    ExecutionRepository executionRepository,
    Stage stage,
    Collection<StageDefinitionBuilder> allStageBuilders) {
    return StageDefinitionBuilderSupport
      .prepareStageForRestart(executionRepository, stage, this, allStageBuilders);
  }

  class StageDefinitionBuilderSupport {
    public static String getType(Class<? extends StageDefinitionBuilder> clazz) {
      String className = clazz.getSimpleName();
      return className.substring(0, 1).toLowerCase() + className.substring(1).replaceFirst("StageDefinitionBuilder$", "").replaceFirst("Stage$", "");
    }

    /**
     * Prepares a stage for restarting by:
     * - marking the halted task as NOT_STARTED and resetting its start and end times
     * - marking the stage as RUNNING
     */
    public static <T extends Execution<T>> Stage<T> prepareStageForRestart(
      ExecutionRepository executionRepository,
      Stage<T> stage,
      StageDefinitionBuilder self,
      Collection<StageDefinitionBuilder> allStageBuilders) {

      // TODO: all this can go once v2 is phased out
      if (stage.getExecution().getExecutionEngine() == v2) {
        stage.getExecution().setCanceled(false);

        List<Stage<T>> stages = stage.getExecution().getStages();
        stages
          .stream()
          .filter(s -> s.getStatus() == ExecutionStatus.CANCELED)
          .forEach(s -> {
              s.setStatus(ExecutionStatus.NOT_STARTED);
              List<Task> tasks = s.getTasks();
              tasks
                .stream()
                .filter(t -> t.getStatus() == ExecutionStatus.CANCELED)
                .forEach(t -> {
                  t.setStartTime(null);
                  t.setEndTime(null);
                  t.setStatus(ExecutionStatus.NOT_STARTED);
                });
            }
          );

        List<Stage<T>> childStages = stages
          .stream()
          .filter(it -> {
            Collection<String> requisiteStageRefIds = it.getRequisiteStageRefIds();
            if (requisiteStageRefIds == null) {
              requisiteStageRefIds = new ArrayList<>();
            }
            if (it.getContext().get("requisiteIds") != null) {
              requisiteStageRefIds.addAll((Collection<String>) it.getContext().get("requisiteIds"));
            }

            // only want to consider completed child stages
            return it.getStatus().isComplete() && requisiteStageRefIds.contains(stage.getRefId());
          })
          .collect(toList());

      List<String> restartingStageAndChildren = Stream.concat(Stream.of(stage),childStages.stream()).map(Stage::getId).collect(toList());
      List<Stage<T> > syntheticStages = stages
        .stream()
        .filter(it -> it.getStatus().isComplete() && restartingStageAndChildren.contains(it.getParentStageId()))
        .collect(toList());

      Stream
        .concat(childStages.stream(), syntheticStages.stream())
        .forEach(childStage -> {
        StageDefinitionBuilder stageBuilder = allStageBuilders
          .stream()
          .filter(it -> it.getType().equals(childStage.getType()))
          .findFirst()
          .orElse(self);
        stageBuilder.prepareStageForRestart(executionRepository, childStage, allStageBuilders);

          // the default `prepareStageForRestart` behavior sets a stage back to RUNNING, that's not appropriate for child stages
          childStage.setStatus(ExecutionStatus.NOT_STARTED);
          List<Task> childStageTasks = childStage.getTasks();
          childStageTasks.forEach(it -> {
            it.setStartTime(null);
            it.setEndTime(null);
            it.setStatus(ExecutionStatus.NOT_STARTED);
          });
          executionRepository.storeStage(childStage);
        });

        List<Task> tasks = stage.getTasks();
        tasks
          .stream()
          .filter(t -> t.getStatus().isHalt())
          .forEach(t -> {
            t.setStartTime(null);
            t.setEndTime(null);
            t.setStatus(ExecutionStatus.NOT_STARTED);
          });

        stage.getContext().put("restartDetails", new HashMap() {{
          put("restartedBy", AuthenticatedRequest.getSpinnakerUser().orElse("anonymous"));
          put("restartTime", System.currentTimeMillis());
          if (stage.getContext().containsKey("exception")) {
            put("previousException", stage.getContext().get("exception"));
            stage.getContext().remove("exception");
          }
        }});

        stage.setStatus(ExecutionStatus.RUNNING);
        stage.setStartTime(null);
        stage.setEndTime(null);
        executionRepository.storeStage(stage);

        Execution.PausedDetails paused = stage.getExecution().getPaused();
        if (paused != null && paused.isPaused()) {
          // pipeline appears to be PAUSED and should be resumed regardless of current TERMINAL status
          executionRepository.resume(
            stage.getExecution().getId(),
            AuthenticatedRequest.getSpinnakerUser().orElse("anonymous"),
            true
          );
        }
      }

      return stage;
    }

    public static <E extends Execution<E>> Stage<E> newStage(E execution,
                                                             String type,
                                                             String name,
                                                             Map<String, Object> context,
                                                             Stage<E> parent,
                                                             SyntheticStageOwner stageOwner) {
      Stage<E> stage = new Stage<>(execution, type, name, context);
      if (parent != null) {
        String stageName = Optional.ofNullable(name).map(s -> s.replaceAll("[^A-Za-z0-9]", "")).orElse(null);
        String id = parent.getId() + "-" + parent.getStageCounter().incrementAndGet() + "-" + stageName;

        Optional<Stage<E>> existingStage = execution.getStages().stream().filter(it -> it.getId().equals(id)).findFirst();
        if (existingStage.isPresent()) {
          // restarted pipelines will have synthetic stages already built so we
          // don't want to duplicate them
          return existingStage.get();
        } else {
          stage.setId(id);
        }
      }

      stage.setSyntheticStageOwner(stageOwner);

      if (parent != null) {
        stage.setParentStageId(parent.getId());

        // Look upstream until you find the ultimate ancestor parent (parent w/ no parentStageId)
        Collection<Stage<E>> executionStages = execution.getStages();
        while (parent.getParentStageId() != null) {
          String parentStageId = parent.getParentStageId();
          parent = executionStages
            .stream()
            .filter(s -> s.getId().equals(parentStageId))
            .findFirst()
            .orElse(null);
        }
      }

      return stage;
    }
  }
}


text:
"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

exports.__esModule = true;
exports.default = exports.StoreStateProvider = void 0;

var _react = _interopRequireWildcard(require("react"));

var _index = require("../../redux/index");

const StoreStateContext = (0, _react.createContext)((0, _index.getStore)().getState());

const StoreStateProvider = ({
  children
}) => {
  const _useState = (0, _react.useState)((0, _index.getStore)().getState()),
        state = _useState[0],
        setState = _useState[1];

  (0, _react.useEffect)(() => {
    const unsubscribe = (0, _index.onLogAction)(() => {
      setState((0, _index.getStore)().getState());
    });
    return unsubscribe;
  }, []);
  return _react.default.createElement(StoreStateContext.Provider, {
    value: state
  }, children);
};

exports.StoreStateProvider = StoreStateProvider;
var _default = StoreStateContext;
exports.default = _default;

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: What happens to the fixed effects?
---

<style TYPE="text/css">
code.has-jax {font: inherit; font-size: 100%; background: inherit; border: inherit;}
</style>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [['$','$'], ['\\(','\\)']],
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre'] // removed 'code' entry
    }
});
MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i = 0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';
    }
});
</script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

## Introduction

I am currently working on a problem which seems rather applied in nature: What happens to the fixed effects in a mixed effects model when certain variables are treated as fixed instead of random? Let me clear up what I mean...

Let's say of the predictors that you choose for your mixed model, there is some subset of these that are fixed effects only, with design $X_{p}$.
$X$ has the form

$$
X =
\begin{pmatrix}
X_1 \\
\vdots \\
X_N
\end{pmatrix}
$$
Where canonically, each $X_{i}$ corresponds to the design matrix of fixed effects for the $i^{th}$ cluster.

 Likewise there is a set of predictors that are treated only as random effects with design matrix $Z$, where $Z_{l}$ is block diagonal $Z_{l} = blockdiag(Z_1, ..., Z_N)$. Lastly, there is some subset of the predictors that are up for discussion. Let's assume that the rank of the design matrix $W$ for these predictors is relatively small. Then we are attempting to compare the fixed effects for the two following models.

$$
M_{0}: Y = X \beta + W \alpha + Z \gamma + \epsilon
$$

with $\beta$ fixed, $\alpha \sim N(0_{Nq}, A), \gamma \sim N(0_{Nl}, \Gamma), \epsilon \sim N(0_{N_{T}}, \sigma^2 I_{N_{T}})$ where $N_{T} = \sum_{i=1}^{N}n_{i}$

$$
M_{1}: Y = X^{*}\beta^{*} + Z\gamma + \epsilon
$$

with
$$
X^{*} = (X, WL)
$$,

$$
\beta^{*} = (\beta_{1}, \omega)^{T}
$$,

$$
L =
\begin{pmatrix}
I_q \\
\vdots \\
I_q
\end{pmatrix}
$$

with dimension $Nq \times q$. $L$ flattens the block diagonal version of $W$ into a population averaged version. I.e. if

$$
W =

\begin{pmatrix}
W_1 & 0 & \dots & 0 \\
0 & W_2 & \dots & 0 \\
0 & 0 & \ddots & 0 \\
0 & 0 & 0 & W_N
\end{pmatrix}
$$

Then
$$
WL =
\begin{pmatrix}
W_1 \\
\vdots \\
W_N
\end{pmatrix}
$$

So as you can probably tell by now, I want to know what happens to the hypothesis tests for the $\beta$ and $\beta_1$ when the $W$ variables to
be either fixed or random effects. This question has come as a consequence of fitting models to electrophysiological data, namely, averaged EEG data.
Due to the central limit theorem, the response $Y$, average amplitude of the electrical signal is guaranteed to be normal. Electrode label is a factor determining the location of the electrical response, and is the $W$ that inspired this line of work. This would result in a mostly sparse $W$ or $WL$ in either
instance, where the non-zero entries are just identity for all entries which coincide with some electrode position. While there are instances of treating electrode position as a fixed effect, it seemingly makes more sense to me to treat it as random. My reasoning is that while typically the positions of the electrodes are fixed on the EEG caps, the sample space of the electrode postions (i.e. the head) is not discrete. We do not exhaust all possible positions of
electrode site. We are probably closer to taking a random sample of electrode positions on the skull. Moreover the interpretation for the parameter estimates
of $\omega$ is messy at best, as we would have to pick some electrode position to be the reference level, and thus the inferences of $\hat{\omega}$ would have to be made relative to that level.

Moreover if we treat electrode position as random, we more or less avoid these issues. The random effects are treated as nuissance parameters and are integrated out of the likelihood. We also get the interpretation of electrode site contributing to the variance structure of the model, which would make sense in the case that observations are spatially correlated depending on the electrode site.

## Relative Efficiency

If we use maximum likelihood to estimate either model, we end up with
$$
\hat{\beta}_{GLS} = (X^{T}V^{-1}X)^{-1}X^{T}V^{-1}Y
$$
when $V$ is held constant.
One result I am trying to establish is under what conditions is the Wald test of the fixed effects in model $M_{0}$ is asymptotically relatively efficient to $M_{1}$. While there is a large issue of determining the distribution of $t$ test for fixed effects in mixed models, (see note 1), there is no controversy in terms of determining the asymptotic relative efficiency. We proceed in the fashion of Lehman and Romano.

### Theorem 1.
Consider two competing sequences of testing sequences $\{\phi\}, \{ \hat{\phi }\}$, based on test statistics $T_{n}$, and $\hat{T_{n}}$. Fix $0 < \alpha < \beta < 1$, and let $\beta{j} > \beta_{j0}$, then let $N(\beta_j)$ and $\hat{N(\beta_{j0})}$ be the smallest sample sizes necessary for $\phi$ and $\hat{\phi}$ to have
power of $\beta$ against $\beta_{j0}$. Then

$$
lim_{\beta_j \rightarrow \beta_{j0}} \frac{N(\beta_j)}{\hat{N(\beta_{j0})}} = (\frac{\hat{(d\mu/d\beta)/\sigma}}{(d\mu/d\beta)/\sigma})^2
$$
the right hand side is called the (Pitman) Asymptotic Relative Efficiency.

### Covariance Matrices.

One result to compare the relative efficiency of the two models' t-test for corresponding effects
$$
\beta_{j}, \beta^{*}_{j}
$$

This is the bulk of what I'm trying to establish in this work. Moreover, I am attempting to show this for the case that
both models are misspecified, and the true error distribution of $\epsilon$ is $\Sigma$.

Therefore, let

$$
\hat{\beta}_{GLS} = (X^{T}V_1^{-1}X)^{-1}X^{T}V_1^{-1}Y
$$

be the fixed effects estimator for model $M_0$. And likewise for $M_1$
$$
\hat{\beta^{*}}_{GLS} = (X^{*T}V_2^{-1}X^{*})^{-1}X^{*T}V_2^{-1}Y
$$

Then under the assumption $Y_{N_{T}\times 1} \sim N(\mu, \Sigma)$, with $\mu \approx X\beta $, then the results of
theorem 1 hold. There are alot of steps being skipped here, but essentially, the relative efficiency of the t-test is
equivalent to the asymptotic efficiency of the effect estimates.

We can find the variance matrices by applying the variance function, which results in

$$
V_1 = Z\Gamma Z^T + W E(\alpha \gamma^T) Z^{T} + Z E(\gamma \alpha^T) W^T + W A W^{T} + I_{N_{T}}\sigma^2
$$
which under the simplifying assumption that $\alpha \perp \gamma$ we get

$$
V_1 =  Z\Gamma Z^T  + W A W^{T} + I_{N_{T}}\sigma^2
$$

$$
V_2  = Z\Gamma Z^T + I_{N_{T}}\sigma^2
$$

We can find the variance of the parameter estimates
$\hat{\beta}_{GLS}$
and
$$
\hat{\beta^{*}}_{GLS}
$$
which results in

$$
 Cov(\hat{\beta}_{GLS}) = (X^{T}V_1^{-1}X)^{-1}X^{T}V_1^{-1} Cov(Y) V_1^{-1} X^{T} (X^{T}V_1^{-1}X)^{-1} =  (X^{T}V_1^{-1}X)^{-1}X^{T}V_1^{-1}  \Sigma  V_1^{-1}  X^{T} (X^{T}V_1^{-1}X)^{-1}
$$

and

$$
Cov(\hat{\beta^{*}}_{GLS} ) = (X^{*T}V_2^{-1}X^{*})^{-1}X^{*T}V_2^{-1} \Sigma V_2^{-1} X^{*T} (X^{*T}V_2^{-1}X^{*})^{-1}
$$

We establish asymptotic relative efficiency of the wald $t$ test if the difference in the covariance matricies

$$
Cov(\hat{\beta^{*}}_{1} ) - Var(\hat{\beta}_{GLS})
$$

is postive definite. This is sufficient, but not nessecary condition for the test of the $j^{th}$ fixed effect estimate for all point one sided
null hypotheses.

### Some Technical Results

#### The following is a set of some boring technical results.
The term
$$
(X^{*T}V_2^{-1}X^{*})^{-1}
$$
bookends the equation for the variance of the variance of $M_1$.
Using block inversion, we find that

$$
(X^{*T}V_2^{-1}X^{*})^{-1} =

\begin{pmatrix}
X^T V_2^{-1}X & X^{T}V_{2}^{-1} W L \\
L^T W^T V_2^{-1} X & L^T W^T V_{2}^{-1} W L
\end{pmatrix}^{-1}

=
\begin{pmatrix}
U_1 & U_2 \\
U_3 & U_4
\end{pmatrix}
$$

The $U_{i}'s$ are found by block inversion. But as we are only taking the first $p$ entries of
$$
\hat{\beta^{*}}
$$

, then we only need
$U_1, U_2$ as the others get multiplied by 0 by applying $(I_p, 0)\hat{\beta^{*}}$ to take the first $p$ entries that correspond to the
same fixed effects.

$$
U_1 = (X^T V_2^{-1}X - X^{T}V_{2}^{-1} W L (L^T W^T V_{2}^{-1} W L )^{-1}L^T W^T V_2^{-1} X)^{-1}
$$

and

$$
U_2 = -(X^T V_2^{-1}X)^{-1} X^{T}V_{2}^{-1} W L (L^T W^T V_{2}^{-1} W L - L^T W^T V_2^{-1} X (X^T V_2^{-1}X)^{-1}  X^{T}V_{2}^{-1} W L  )^{-1}
$$

## If only everything is instantly positive definite

$$
Cov(\hat{\beta^{*}}_1) = U_1X^{T}\Sigma X U_1 + U_2 L^{T}W^{T} \Sigma X U_{1} + U_{1}X^{T}\Sigma W L U_{2}^{T} + U_{2}L^{T}W^{T}\Sigma W L U_2^{T}
$$

and

$$
Cov(\hat{\beta}) = (X^{T}V_1^{-1}X)^{-1}X^{T}V_1^{-1}  \Sigma  V_1^{-1}  X^{T} (X^{T}V_1^{-1}X)^{-1}
$$

We can see an obvious difference between the two matricies. In $M_{2}$ we have a fixed effects parameter that has a much more complicated mean structure,
whereas for $M_1$ we end up with a more complicated covariance structure. There may be a large set of cases in which the


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;

// "用户控件"项模板在 http://go.microsoft.com/fwlink/?LinkId=234235 上有介绍

namespace Anony.Controls
{
    public sealed class HintTextBox : TextBox
    {
        public HintTextBox()
        {
            this.DefaultStyleKey = typeof(HintTextBox);
        }
    }
}


text:
require "chef/resource"
require "chef/platform/query_helpers"

class Chef
  class Resource
    class WindowsFeatureDism < Chef::Resource
      resource_name :windows_feature_dism
      provides(:windows_feature_dism) { true }

      description "Use the windows_feature_dism resource to add, remove, or entirely delete Windows features and roles using DISM."
      introduced "14.0"

      property :feature_name, [Array, String],
               description: "The name of the feature(s) or role(s) to install, if it differs from the resource name.",
               coerce: proc { |x| to_formatted_array(x) },
               name_property: true

      property :source, String,
               description: "Specify a local repository for the feature install."

      property :all, [TrueClass, FalseClass],
               description: "Install all sub-features. When set to 'true', this is the equivalent of specifying the /All switch to dism.exe",
               default: false

      property :timeout, Integer,
               description: "Specifies a timeout (in seconds) for the feature installation.",
               default: 600

      # @return [Array] lowercase the array unless we're on < Windows 2012
      def to_formatted_array(x)
        x = x.split(/\s*,\s*/) if x.is_a?(String) # split multiple forms of a comma separated list

        # feature installs on windows < 2012 are case sensitive so only downcase when on 2012+
        older_than_win_2012_or_8? ? x : x.map(&:downcase)
      end

      action :install do
        description "Install a Windows role/feature using DISM"

        reload_cached_dism_data unless node["dism_features_cache"]
        fail_if_unavailable # fail if the features don't exist

        logger.trace("Windows features needing installation: #{features_to_install.empty? ? 'none' : features_to_install.join(',')}")
        unless features_to_install.empty?
          message = "install Windows feature#{'s' if features_to_install.count > 1} #{features_to_install.join(',')}"
          converge_by(message) do
            install_command = "dism.exe /online /enable-feature #{features_to_install.map { |f| "/featurename:#{f}" }.join(' ')} /norestart"
            install_command << " /LimitAccess /Source:\"#{new_resource.source}\"" if new_resource.source
            install_command << " /All" if new_resource.all
            begin
              shell_out!(install_command, returns: [0, 42, 127, 3010], timeout: new_resource.timeout)
            rescue Mixlib::ShellOut::ShellCommandFailed => e
              raise "Error 50 returned by DISM related to parent features, try setting the 'all' property to 'true' on the 'windows_feature_dism' resource." if required_parent_feature?(e.inspect)
              raise e.message
            end

            reload_cached_dism_data # Reload cached dism feature state
          end
        end
      end

      action :remove do
        description "Remove a Windows role/feature using DISM"

        reload_cached_dism_data unless node["dism_features_cache"]

        logger.trace("Windows features needing removal: #{features_to_remove.empty? ? 'none' : features_to_remove.join(',')}")
        unless features_to_remove.empty?
          message = "remove Windows feature#{'s' if features_to_remove.count > 1} #{features_to_remove.join(',')}"

          converge_by(message) do
            shell_out!("dism.exe /online /disable-feature #{features_to_remove.map { |f| "/featurename:#{f}" }.join(' ')} /norestart", returns: [0, 42, 127, 3010], timeout: new_resource.timeout)

            reload_cached_dism_data # Reload cached dism feature state
          end
        end
      end

      action :delete do
        description "Remove a Windows role/feature from the image using DISM"

        raise_if_delete_unsupported

        reload_cached_dism_data unless node["dism_features_cache"]

        fail_if_unavailable # fail if the features don't exist

        logger.trace("Windows features needing deletion: #{features_to_delete.empty? ? 'none' : features_to_delete.join(',')}")
        unless features_to_delete.empty?
          message = "delete Windows feature#{'s' if features_to_delete.count > 1} #{features_to_delete.join(',')} from the image"
          converge_by(message) do
            shell_out!("dism.exe /online /disable-feature #{features_to_delete.map { |f| "/featurename:#{f}" }.join(' ')} /Remove /norestart", returns: [0, 42, 127, 3010], timeout: new_resource.timeout)

            reload_cached_dism_data # Reload cached dism feature state
          end
        end
      end

      action_class do
        # @return [Array] features the user has requested to install which need installation
        def features_to_install
          @install ||= begin
            # disabled features are always available to install
            available_for_install = node["dism_features_cache"]["disabled"].dup

            # removed features are also available for installation
            available_for_install.concat(node["dism_features_cache"]["removed"])

            # the intersection of the features to install & disabled/removed features are what needs installing
            new_resource.feature_name & available_for_install
          end
        end

        # @return [Array] features the user has requested to remove which need removing
        def features_to_remove
          # the intersection of the features to remove & enabled features are what needs removing
          @remove ||= new_resource.feature_name & node["dism_features_cache"]["enabled"]
        end

        # @return [Array] features the user has requested to delete which need deleting
        def features_to_delete
          # the intersection of the features to remove & enabled/disabled features are what needs removing
          @remove ||= begin
            all_available = node["dism_features_cache"]["enabled"] +
              node["dism_features_cache"]["disabled"]
            new_resource.feature_name & all_available
          end
        end

        # if any features are not supported on this release of Windows or
        # have been deleted raise with a friendly message. At one point in time
        # we just warned, but this goes against the behavior of ever other package
        # provider in Chef and it isn't clear what you'd want if you passed an array
        # and some features were available and others were not.
        # @return [void]
        def fail_if_unavailable
          all_available = node["dism_features_cache"]["enabled"] +
            node["dism_features_cache"]["disabled"] +
            node["dism_features_cache"]["removed"]

          # the difference of desired features to install to all features is what's not available
          unavailable = (new_resource.feature_name - all_available)
          raise "The Windows feature#{'s' if unavailable.count > 1} #{unavailable.join(',')} #{unavailable.count > 1 ? 'are' : 'is'} not available on this version of Windows. Run 'dism /online /Get-Features' to see the list of available feature names." unless unavailable.empty?
        end

        # run dism.exe to get a list of all available features and their state
        # and save that to the node at node.override level.
        # We do this because getting a list of features in dism takes at least a second
        # and this data will be persisted across multiple resource runs which gives us
        # a much faster run when no features actually need to be installed / removed.
        # @return [void]
        def reload_cached_dism_data
          logger.trace("Caching Windows features available via dism.exe.")
          node.override["dism_features_cache"] = Mash.new
          node.override["dism_features_cache"]["enabled"] = []
          node.override["dism_features_cache"]["disabled"] = []
          node.override["dism_features_cache"]["removed"] = []

          # Grab raw feature information from dism command line
          raw_list_of_features = shell_out("dism.exe /Get-Features /Online /Format:Table /English").stdout

          # Split stdout into an array by windows line ending
          features_list = raw_list_of_features.split("\r\n")
          features_list.each do |feature_details_raw|
            case feature_details_raw
            when /Payload Removed/ # matches 'Disabled with Payload Removed'
              add_to_feature_mash("removed", feature_details_raw)
            when /Enable/ # matches 'Enabled' and 'Enable Pending' aka after reboot
              add_to_feature_mash("enabled", feature_details_raw)
            when /Disable/ # matches 'Disabled' and 'Disable Pending' aka after reboot
              add_to_feature_mash("disabled", feature_details_raw)
            end
          end
          logger.trace("The cache contains\n#{node['dism_features_cache']}")
        end

        # parse the feature string and add the values to the appropriate array
        # in the
        # strips trailing whitespace characters then split on n number of spaces
        # + | +  n number of spaces
        # @return [void]
        def add_to_feature_mash(feature_type, feature_string)
          feature_details = feature_string.strip.split(/\s+[|]\s+/).first

          # dism on windows 2012+ isn't case sensitive so it's best to compare
          # lowercase lists so the user input doesn't need to be case sensitive
          # @todo when we're ready to remove windows 2008R2 the gating here can go away
          feature_details.downcase! unless older_than_win_2012_or_8?
          node.override["dism_features_cache"][feature_type] << feature_details
        end

        # Fail unless we're on windows 8+ / 2012+ where deleting a feature is supported
        # @return [void]
        def raise_if_delete_unsupported
          raise Chef::Exceptions::UnsupportedAction, "#{self} :delete action not supported on Windows releases before Windows 8/2012. Cannot continue!" if older_than_win_2012_or_8?
        end

        def required_parent_feature?(error_message)
          error_message.include?("Error: 50") && error_message.include?("required parent feature")
        end
      end
    end
  end
end


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.geospatial;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Predicate;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;

import static com.google.common.base.Preconditions.checkArgument;
import static io.prestosql.geospatial.KdbTree.Node.newInternal;
import static io.prestosql.geospatial.KdbTree.Node.newLeaf;
import static java.util.Objects.requireNonNull;

/**
 * 2-dimensional K-D-B Tree
 * see https://en.wikipedia.org/wiki/K-D-B-tree
 */
public class KdbTree
{
    private static final int MAX_LEVELS = 10_000;

    private final Node root;

    public static final class Node
    {
        private final Rectangle extent;
        private final OptionalInt leafId;
        private final Optional<Node> left;
        private final Optional<Node> right;

        public static Node newLeaf(Rectangle extent, int leafId)
        {
            return new Node(extent, OptionalInt.of(leafId), Optional.empty(), Optional.empty());
        }

        public static Node newInternal(Rectangle extent, Node left, Node right)
        {
            return new Node(extent, OptionalInt.empty(), Optional.of(left), Optional.of(right));
        }

        @JsonCreator
        public Node(
                @JsonProperty("extent") Rectangle extent,
                @JsonProperty("leafId") OptionalInt leafId,
                @JsonProperty("left") Optional<Node> left,
                @JsonProperty("right") Optional<Node> right)
        {
            this.extent = requireNonNull(extent, "extent is null");
            this.leafId = requireNonNull(leafId, "leafId is null");
            this.left = requireNonNull(left, "left is null");
            this.right = requireNonNull(right, "right is null");
            if (leafId.isPresent()) {
                checkArgument(leafId.getAsInt() >= 0, "leafId must be >= 0");
                checkArgument(!left.isPresent(), "Leaf node cannot have left child");
                checkArgument(!right.isPresent(), "Leaf node cannot have right child");
            }
            else {
                checkArgument(left.isPresent(), "Intermediate node must have left child");
                checkArgument(right.isPresent(), "Intermediate node must have right child");
            }
        }

        @JsonProperty
        public Rectangle getExtent()
        {
            return extent;
        }

        @JsonProperty
        public OptionalInt getLeafId()
        {
            return leafId;
        }

        @JsonProperty
        public Optional<Node> getLeft()
        {
            return left;
        }

        @JsonProperty
        public Optional<Node> getRight()
        {
            return right;
        }

        @Override
        public boolean equals(Object obj)
        {
            if (obj == null) {
                return false;
            }

            if (!(obj instanceof Node)) {
                return false;
            }

            Node other = (Node) obj;
            return this.extent.equals(other.extent)
                    && Objects.equals(this.leafId, other.leafId)
                    && Objects.equals(this.left, other.left)
                    && Objects.equals(this.right, other.right);
        }

        @Override
        public int hashCode()
        {
            return Objects.hash(extent, leafId, left, right);
        }
    }

    @JsonCreator
    public KdbTree(@JsonProperty("root") Node root)
    {
        this.root = requireNonNull(root, "root is null");
    }

    @JsonProperty
    public Node getRoot()
    {
        return root;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (obj == null) {
            return false;
        }

        if (!(obj instanceof KdbTree)) {
            return false;
        }

        KdbTree other = (KdbTree) obj;
        return this.root.equals(other.root);
    }

    @Override
    public int hashCode()
    {
        return Objects.hash(root);
    }

    public Map<Integer, Rectangle> getLeaves()
    {
        ImmutableMap.Builder<Integer, Rectangle> leaves = ImmutableMap.builder();
        addLeaves(root, leaves, node -> true);
        return leaves.build();
    }

    public Map<Integer, Rectangle> findIntersectingLeaves(Rectangle envelope)
    {
        ImmutableMap.Builder<Integer, Rectangle> leaves = ImmutableMap.builder();
        addLeaves(root, leaves, node -> node.extent.intersects(envelope));
        return leaves.build();
    }

    private static void addLeaves(Node node, ImmutableMap.Builder<Integer, Rectangle> leaves, Predicate<Node> predicate)
    {
        if (!predicate.apply(node)) {
            return;
        }

        if (node.leafId.isPresent()) {
            leaves.put(node.leafId.getAsInt(), node.extent);
        }
        else {
            addLeaves(node.left.get(), leaves, predicate);
            addLeaves(node.right.get(), leaves, predicate);
        }
    }

    private interface SplitDimension
    {
        Comparator<Rectangle> getComparator();

        double getValue(Rectangle rectangle);

        SplitResult<Rectangle> split(Rectangle rectangle, double value);
    }

    private static final SplitDimension BY_X = new SplitDimension()
    {
        private final Comparator<Rectangle> comparator = (first, second) -> ComparisonChain.start()
                .compare(first.getXMin(), second.getXMin())
                .compare(first.getYMin(), second.getYMin())
                .result();

        @Override
        public Comparator<Rectangle> getComparator()
        {
            return comparator;
        }

        @Override
        public double getValue(Rectangle rectangle)
        {
            return rectangle.getXMin();
        }

        @Override
        public SplitResult<Rectangle> split(Rectangle rectangle, double x)
        {
            checkArgument(rectangle.getXMin() < x && x < rectangle.getXMax());
            return new SplitResult<>(
                    new Rectangle(rectangle.getXMin(), rectangle.getYMin(), x, rectangle.getYMax()),
                    new Rectangle(x, rectangle.getYMin(), rectangle.getXMax(), rectangle.getYMax()));
        }
    };

    private static final SplitDimension BY_Y = new SplitDimension()
    {
        private final Comparator<Rectangle> comparator = (first, second) -> ComparisonChain.start()
                .compare(first.getYMin(), second.getYMin())
                .compare(first.getXMin(), second.getXMin())
                .result();

        @Override
        public Comparator<Rectangle> getComparator()
        {
            return comparator;
        }

        @Override
        public double getValue(Rectangle rectangle)
        {
            return rectangle.getYMin();
        }

        @Override
        public SplitResult<Rectangle> split(Rectangle rectangle, double y)
        {
            checkArgument(rectangle.getYMin() < y && y < rectangle.getYMax());
            return new SplitResult<>(
                    new Rectangle(rectangle.getXMin(), rectangle.getYMin(), rectangle.getXMax(), y),
                    new Rectangle(rectangle.getXMin(), y, rectangle.getXMax(), rectangle.getYMax()));
        }
    };

    private static final class LeafIdAllocator
    {
        private int nextId;

        public int next()
        {
            return nextId++;
        }
    }

    public static KdbTree buildKdbTree(int maxItemsPerNode, Rectangle extent, List<Rectangle> items)
    {
        checkArgument(maxItemsPerNode > 0, "maxItemsPerNode must be > 0");
        requireNonNull(extent, "extent is null");
        requireNonNull(items, "items is null");
        return new KdbTree(buildKdbTreeNode(maxItemsPerNode, 0, extent, items, new LeafIdAllocator()));
    }

    private static Node buildKdbTreeNode(int maxItemsPerNode, int level, Rectangle extent, List<Rectangle> items, LeafIdAllocator leafIdAllocator)
    {
        checkArgument(maxItemsPerNode > 0, "maxItemsPerNode must be > 0");
        checkArgument(level >= 0, "level must be >= 0");
        checkArgument(level <= MAX_LEVELS, "level must be <= 10,000");
        requireNonNull(extent, "extent is null");
        requireNonNull(items, "items is null");

        if (items.size() <= maxItemsPerNode || level == MAX_LEVELS) {
            return newLeaf(extent, leafIdAllocator.next());
        }

        // Split over longer side
        boolean splitVertically = extent.getWidth() >= extent.getHeight();
        Optional<SplitResult<Node>> splitResult = trySplit(splitVertically ? BY_X : BY_Y, maxItemsPerNode, level, extent, items, leafIdAllocator);
        if (!splitResult.isPresent()) {
            // Try spitting by the other side
            splitResult = trySplit(splitVertically ? BY_Y : BY_X, maxItemsPerNode, level, extent, items, leafIdAllocator);
        }

        if (!splitResult.isPresent()) {
            return newLeaf(extent, leafIdAllocator.next());
        }

        return newInternal(extent, splitResult.get().getLeft(), splitResult.get().getRight());
    }

    private static final class SplitResult<T>
    {
        private final T left;
        private final T right;

        private SplitResult(T left, T right)
        {
            this.left = requireNonNull(left, "left is null");
            this.right = requireNonNull(right, "right is null");
        }

        public T getLeft()
        {
            return left;
        }

        public T getRight()
        {
            return right;
        }
    }

    private static Optional<SplitResult<Node>> trySplit(SplitDimension splitDimension, int maxItemsPerNode, int level, Rectangle extent, List<Rectangle> items, LeafIdAllocator leafIdAllocator)
    {
        checkArgument(items.size() > 1, "Number of items to split must be > 1");

        // Sort envelopes by xMin or yMin
        List<Rectangle> sortedItems = ImmutableList.sortedCopyOf(splitDimension.getComparator(), items);

        // Find a mid-point
        int middleIndex = (sortedItems.size() - 1) / 2;
        Rectangle middleEnvelope = sortedItems.get(middleIndex);
        double splitValue = splitDimension.getValue(middleEnvelope);
        int splitIndex = middleIndex;

        // skip over duplicate values
        while (splitIndex < sortedItems.size() && splitDimension.getValue(sortedItems.get(splitIndex)) == splitValue) {
            splitIndex++;
        }

        // all values between left-of-middle and the end are the same, so can't split
        if (splitIndex == sortedItems.size()) {
            return Optional.empty();
        }

        // about half of the objects are <= splitValue, the rest are >= next value
        // assuming the input set of objects is a sample from a much larger set,
        // let's split in the middle; this way objects from the larger set with values
        // between splitValue and next value will get split somewhat evenly into left
        // and right partitions
        splitValue = (splitValue + splitDimension.getValue(sortedItems.get(splitIndex))) / 2;

        SplitResult<Rectangle> childExtents = splitDimension.split(extent, splitValue);

        return Optional.of(new SplitResult<>(
                buildKdbTreeNode(maxItemsPerNode, level + 1, childExtents.getLeft(), sortedItems.subList(0, splitIndex), leafIdAllocator),
                buildKdbTreeNode(maxItemsPerNode, level + 1, childExtents.getRight(), sortedItems.subList(splitIndex, sortedItems.size()), leafIdAllocator)));
    }
}


text:
using UnityEngine;
using System.Collections;
using Fineness.Framework.Interfaces;
using System;
using Fineness.Framework;

public delegate void FLoaderComplete(WWW target);
public delegate void FLoaderProgress(float progress);

public enum WWWLoaderType
{
    Normal = 0,
    FromCacheOrDL,
}

public class WWWLoader : IWWWLoader {

    private WWWLoaderType mLoaderType;
    private string mUrl;
    private WWW mWWW;
    private FLoaderProgress mLoaderProgress;
    private FLoaderComplete mLoaderComplete;
    private int mVersion;

    public WWWLoader(string url = null, FLoaderComplete complete = null, FLoaderProgress progress = null, WWWLoaderType loaderType = WWWLoaderType.Normal, int version = 0)
    {
        mUrl = url;
        mLoaderComplete += complete;
        mLoaderProgress += progress;
        mLoaderType = loaderType;
        mVersion = version;
    }

    public void Dispose()
    {
        if (mIsDispose)
            return;
        mIsDispose = true;

        mUrl = string.Empty;
        mOnNextUnit = null;
        mOnUnitExecuted = null;
        mOnUnitCompleted = null;

        Purge();
        PurgeCallback();
    }

    protected virtual void Purge()
    {
        PurgeWWW();
    }

    /// 回收 WWW 对象
    /// <param name="isRemoveUpdate">防止先关闭刷帧功能后立即开启刷帧功能引起的冲突问题</param>
    protected virtual void PurgeWWW(bool isRemoveUpdate = true)
    {
        IsFrameUpdate = !isRemoveUpdate;
        if (mWWW != null)
            mWWW.Dispose();
        mWWW = null;
    }

    protected virtual void PurgeCallback()
    {
        mLoaderComplete = null;
        mLoaderProgress = null;
    }

    public void Load(string url = null)
    {
        Stop();
        if(!string.IsNullOrEmpty(url))
            mUrl = url;
        if (!string.IsNullOrEmpty(mUrl))
        {
            IsFrameUpdate = true;
            if (mLoaderType == WWWLoaderType.Normal)
            {
                mWWW = new WWW(mUrl);
            }
            else if (mLoaderType == WWWLoaderType.FromCacheOrDL)
            {
                mWWW = WWW.LoadFromCacheOrDownload(mUrl, mVersion);
            }
        }
    }

    public void Stop()
    {
        PurgeWWW(false);
    }

    #region 刷帧函数
    /// 帧更新
    public virtual void OnUpdate(int dTime)
    {
        if(mWWW != null)
        {
            if(mWWW.isDone)
            {
                if(mLoaderComplete != null)
                    mLoaderComplete.Invoke(mWWW);
                if(mOnUnitCompleted != null)
                    mOnUnitCompleted.Invoke(this);
                QueueNext();
                Purge();
            }
            else
            {
                if (mLoaderProgress != null)
                    mLoaderProgress.Invoke(mWWW.progress);
            }
        }

    }

    /// 是否每帧更新
    public virtual bool IsUpdate
    {
        get
        {
            return true;
        }
    }
    #endregion

    #region 可控刷帧功能
    /// 是否加入了刷帧队列
    private bool mIsFrameUpdate = false;
    public bool IsFrameUpdate
    {
        set
        {
            mIsFrameUpdate = value;

            if (value)
                LoaderManagerComponent.Instance.AddUpdateLoader(this);
            else
                LoaderManagerComponent.Instance.RemoveUpdateLoader(this);
        }
        get
        {
            return mIsFrameUpdate;
        }
    }
    #endregion

    #region 执行队列单元的实现代码
    private bool mIsDispose;
    private QueueNextUnit mOnNextUnit;
    private QueueUnitExecuted mOnUnitExecuted;
    private QueueUnitCompleted mOnUnitCompleted;

    public virtual void Commit()
    {
        if (string.IsNullOrEmpty(mUrl))
            QueueNext();
        else
            Load();
    }

    public void QueueNext()
    {
        if (mOnNextUnit != null)
            mOnNextUnit(this);//让所在的队列执行器执行下一个队列单元
    }

    public QueueNextUnit OnNextUnit
    {
        get
        {
            return mOnNextUnit;
        }

        set
        {
            mOnNextUnit = value;
        }
    }

    public QueueUnitCompleted OnUnitCompleted
    {
        get
        {
            return mOnUnitCompleted;
        }

        set
        {
            mOnUnitCompleted = value;
        }
    }

    public QueueUnitExecuted OnUnitExecuted
    {
        get
        {
            return mOnUnitExecuted;
        }

        set
        {
            mOnUnitExecuted = value;
        }
    }

    public int QueueSize
    {
        get
        {
            return 1;
        }
    }
    #endregion

    public bool IsLoaded
    {
        get
        {
            return (mWWW != null) ? mWWW.isDone : false;
        }
    }

    public FLoaderProgress OnProgress
    {
        set
        {
            mLoaderProgress = value;
        }
        get
        {
            return mLoaderProgress;
        }
    }

    public FLoaderComplete OnComplete
    {
        set
        {
            mLoaderComplete = value;
        }
        get
        {
            return mLoaderComplete;
        }
    }

    public string URL
    {
        set
        {
            mUrl = value;
        }
        get
        {
            return mUrl;
        }
    }

    public WWW LoaderData
    {
        get
        {
            return mWWW;
        }
    }

    public string Error
    {
        get
        {
            return (mWWW != null) ? mWWW.error : string.Empty;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace MahApps.Metro.Controls
{
    /// <summary>
    /// A helper class that provides various attached properties for the ComboBox control.
    /// <see cref="ComboBox"/>
    /// </summary>
    public class ComboBoxHelper : DependencyObject
    {
        public static readonly DependencyProperty EnableVirtualizationWithGroupingProperty = DependencyProperty.RegisterAttached("EnableVirtualizationWithGrouping", typeof(bool), typeof(ComboBox), new FrameworkPropertyMetadata(false));

        public static void SetEnableVirtualizationWithGrouping(DependencyObject obj, bool value)
        {
            if (obj is ComboBox)
            {
#if NET4_5
                ComboBox comboBox = obj as ComboBox;

                comboBox.SetValue(EnableVirtualizationWithGroupingProperty, value);
                comboBox.SetValue(VirtualizingPanel.IsVirtualizingProperty, value);
                comboBox.SetValue(VirtualizingPanel.IsVirtualizingWhenGroupingProperty, value);
#else
                obj.SetValue(EnableVirtualizationWithGroupingProperty, false);
#endif
            }
        }

        public static bool GetEnableVirtualizationWithGrouping(DependencyObject obj)
        {
            return (bool)obj.GetValue(EnableVirtualizationWithGroupingProperty);
        }
    }
}


text:
<?php
/*
Template Name: Show Team Members
*/

get_template_part('templates/content', 'page'); ?>


text:
WXDLLIMPEXP_GL WXGLContext WXGLCreateContext( WXGLPixelFormat pixelFormat, WXGLContext shareContext );
WXDLLIMPEXP_GL void WXGLDestroyContext( WXGLContext context );

WXDLLIMPEXP_GL WXGLContext WXGLGetCurrentContext();
WXDLLIMPEXP_GL bool WXGLSetCurrentContext(WXGLContext context);

WXDLLIMPEXP_GL WXGLPixelFormat WXGLChoosePixelFormat(const int *attribList);
WXDLLIMPEXP_GL void WXGLDestroyPixelFormat( WXGLPixelFormat pixelFormat );

class WXDLLIMPEXP_GL wxGLContext : public wxGLContextBase
{
public:
    wxGLContext(wxGLCanvas *win, const wxGLContext *other = NULL);
    virtual ~wxGLContext();

    virtual bool SetCurrent(const wxGLCanvas& win) const;

    // Mac-specific
    WXGLContext GetWXGLContext() const { return m_glContext; }

private:
    WXGLContext m_glContext;

    wxDECLARE_NO_COPY_CLASS(wxGLContext);
};

class WXDLLIMPEXP_GL wxGLCanvas : public wxGLCanvasBase
{
public:
    wxGLCanvas(wxWindow *parent,
               wxWindowID id = wxID_ANY,
               const int *attribList = NULL,
               const wxPoint& pos = wxDefaultPosition,
               const wxSize& size = wxDefaultSize,
               long style = 0,
               const wxString& name = wxGLCanvasName,
               const wxPalette& palette = wxNullPalette);

    bool Create(wxWindow *parent,
                wxWindowID id = wxID_ANY,
                const wxPoint& pos = wxDefaultPosition,
                const wxSize& size = wxDefaultSize,
                long style = 0,
                const wxString& name = wxGLCanvasName,
                const int *attribList = NULL,
                const wxPalette& palette = wxNullPalette);

    virtual ~wxGLCanvas();

    // implement wxGLCanvasBase methods
    virtual bool SwapBuffers();

    // Mac-specific functions
    // ----------------------

    // return true if multisample extension is supported
    static bool IsAGLMultiSampleAvailable();

    // return the pixel format used by this window
    WXGLPixelFormat GetWXGLPixelFormat() const { return m_glFormat; }

    // update the view port of the current context to match this window
    void SetViewport();

    // deprecated methods
    // ------------------

#if WXWIN_COMPATIBILITY_2_8
    wxDEPRECATED(
    wxGLCanvas(wxWindow *parent,
               wxWindowID id = wxID_ANY,
               const wxPoint& pos = wxDefaultPosition,
               const wxSize& size = wxDefaultSize,
               long style = 0,
               const wxString& name = wxGLCanvasName,
               const int *attribList = NULL,
               const wxPalette& palette = wxNullPalette)
    );

    wxDEPRECATED(
    wxGLCanvas(wxWindow *parent,
               const wxGLContext *shared,
               wxWindowID id = wxID_ANY,
               const wxPoint& pos = wxDefaultPosition,
               const wxSize& size = wxDefaultSize,
               long style = 0,
               const wxString& name = wxGLCanvasName,
               const int *attribList = NULL,
               const wxPalette& palette = wxNullPalette)
    );

    wxDEPRECATED(
    wxGLCanvas(wxWindow *parent,
               const wxGLCanvas *shared,
               wxWindowID id = wxID_ANY,
               const wxPoint& pos = wxDefaultPosition,
               const wxSize& size = wxDefaultSize,
               long style = 0,
               const wxString& name = wxGLCanvasName,
               const int *attribList = NULL,
               const wxPalette& palette = wxNullPalette)
    );
#endif // WXWIN_COMPATIBILITY_2_8

    // implementation-only from now on

#if wxOSX_USE_CARBON
    // Unlike some other platforms, this must get called if you override it,
    // i.e. don't forget "event.Skip()" in your EVT_SIZE handler
    void OnSize(wxSizeEvent& event);

    virtual void MacSuperChangedPosition();
    virtual void MacTopLevelWindowChangedPosition();
    virtual void MacVisibilityChanged();

    void MacUpdateView();

    GLint GetAglBufferName() const { return m_bufferName; }
#endif

protected:
    WXGLPixelFormat m_glFormat;

#if wxOSX_USE_CARBON
    bool m_macCanvasIsShown,
         m_needsUpdate;
    WXGLContext m_dummyContext;
    GLint m_bufferName;
#endif

    DECLARE_EVENT_TABLE()
    DECLARE_CLASS(wxGLCanvas)
};

#endif // _WX_GLCANVAS_H_


text:
PyPred
======
[![Build Status](https://travis-ci.org/armon/pypred.png)](https://travis-ci.org/armon/pypred)

PyPred is a package to do predicate evaluation in Python. It uses a
PLY (Lex/Yacc for Python) to parse inputs into an AST tree which it
then evaluates. The PyPred provides simple APIs to do the evaluation
is most sitations, but allows for customized evaluation techniques for
more complex situations.

Additionally, PyPred supports the notion of predicate "sets". This is
a collection of predicates that are all simultaneously evaluated against
a single input document. For example, in a Pub/Sub system, each subscription
can be modeled as a predicate. When a new event arrives, the predicate set
of all subscriptions can be evaluated to find all matching subscriptions.

PyPred provides a PredicateSet model as well as an OptimizedPredicateSet.
The optimized variant trades memory for speed. It extracts common
sub-expressions into a branch, and conditionally executes different sets
of predicates to prune the predicates that will not match most efficiently.
The parameters of the optimization can be tweaked to find a speed/memory
balance.

Grammar
=======

The grammar that PyPred understands is limited to simple comparisons
and boolean logic.

It supports the following:

* Logical operators `not`, `and`, `or`
* Comparison operators >, >=, <, <=, =, !=, 'is', 'is not'
* Parenthesis to disambiguate
* The subset check operator `contains`
* The regular expression matcher `matches`
* String literals, quoted if they include spaces
* Numeric literals
* Constants true, false, undefined, null, empty
* Set literal, containing string literals, numeric and constant values

Grammar Examples
================

To demonstate the capabilities of the pypred grammar, the following
examples are provided.

    name is 'Jack' and friend_name is 'Jill'

This predicate checks that the input document has a field name equal to
"Jack", and a field friend\_name equal to "Jill"

    event is "Record Score" and ((score >= 500 and highest_score_wins) or (score < 10 and lowest_score_wins))

This is a slightly more advanced predicate. It checks that this is a "Record Score" event,
and that the score is either greater than or equal to 500 in the case that a high score is desireable,
or that the score is less than 10 if a low score is desirable.

    server matches "east-web-([\d]+)" and errors contains "CPU load" and environment != test

This checks for any webserver hostname matching a numeric suffix, such as "east-web-001", with
"CPU load" being reported as an error in a non-test environment.

If you want to use regular expression with modifiers, you can try out the following example:

    haiku matches /^my life,\s-.How much.*brief\.$/mis

This regular expression will match the following haiku:

    My life, -
    How much more of it remains?
    The night is brief.

Notice that in previous example we used slashes instead of quotation marks. This allowed us to set modifiers (after slashes). This behaviour is very similar to Javascript regular expressions. Supported modifiers are:

* _i_ (ignore case)
* _m_ (multiline)
* _s_ (dotall)
* _u_ (unicode)
* _l_ (locale)

Literal sets can be used to check for multiple clauses:

    {"WARN" "ERR" "CRIT"} contains error_level or {500 501 503} contains status_code

This provides two literal sets which are used to check against the dynamic values
of error\_level and status\_code.

API
===

Predicates themselves have a single interface, which is the `Predicate` class.
It is instantiated with a string predicate.

The main API's for it are:
* Predicate(Pred) : Creates a new predicate object

* Predicate.description(): Returns a human readable version of the tree if valid

* Predicate.is\_valid() : Returns if the predicate is valid

* Predicate.errors(): If not valid, returns a list of tokenization, syntax, and semantic errors

* Predicate.evaluate(document) : Evaluates the given document against the predicate

* Predicate.analyze(document) : Evaluates the given document against the predicate,
  returns the results, as well as the evaluation context that includes more information about
  the evaluation, including the failure reasons. This is generally much slower than
  evaluate in the failure cases.

One of the critical aspects of evaluating a predicate is the resolution of
literals. When the AST needs a value to substitute a variable, it calls the
`resolve_identifier` method of the Predicate. The default behavior is flexible,
and support string literals, dictionary lookups, nested dictionaries, and
call back resolution via `set_resolver`. However, if a client wants to customize
the resolution of identifier, they can simply override this method.

Predicate Sets have two main interfaces, either the `PredicateSet` or `OptimizedPredicateSet`.

Both share part a subset of their calls:

* Set(preds=None) : Instantiate the set, optionally with a list of predicates

* Set.add(predicate) : Adds a predicate to the set

* Set.update(predicates) : Extends to include a list of predicates

* Set.evaluate(document) : Evaluates the document against the predicates and returns a list of matches

The OptimizedPredicateSet supports an extended set of API's:

* OptSet.description() : Returns ahuman readable version of the optimized tree

* OptSet.analyze(document) : Like Predicate.analyze(), but returns a boolean, a list, and the evaluation context.

* OptSet.compile\_ast() : Forces compilation of the interal AST

* OptSet.finalize() : Prunes the AST of sub-predicates, and removes any instance data that is not used
  as part of the evaluation of the optimized set. Not usually needed, but can reduce the total memory
  footprint, and is useful if the object is going to be pickled.

The standard PredicateSet relies on the underlying predicates to do
resolution of literals, however the OptimizedPredicateSet implements
`resolve_identifier` to do so. Thus if custom behavior is wanted, the
optimized set must be sub-classed.

Human Readable Outputs
======================

PyPred tries to make it possible to provide human readable output of
both predicates as well as any error messages that are encountered.
Here is an example of a human readable description of:

    p = Predicate('server matches "east-web-([\d]+)" and errors contains "CPU load" and environment != test')
    print p.description()

    AND operator at line: 1, col 34
        MatchOperator at line: 1, col 7
            Literal server at line: 1, col 0
            Regex 'east-web-([\\d]+)' at line: 1, col 15
        AND operator at line: 1, col 65
            ContainsOperator at line: 1, col 45
                Literal errors at line: 1, col 38
                Literal "CPU load" at line: 1, col 54
            != comparison at line: 1, col 81
                Literal environment at line: 1, col 69
                Literal test at line: 1, col 84

Here is an example of the output during a failed evaluation:

    p = Predicate('server matches "east-web-([\d]+)" and errors contains "CPU load" and environment != test')
    res, ctx = p.analyze({'server': 'east-web-001', 'errors': [], 'environment': 'prod'})
    assert res == False

    pprint.pprint(ctx.failed)
     ["Right side: 'CPU load' not in left side: [] for ContainsOperator at line: 1, col 45",
                 'Left hand side of AND operator at line: 1, col 65 failed',
                 'Right hand side of AND operator at line: 1, col 34 failed']

    pprint.pprint(ctx.literals)
     {'"CPU load"': 'CPU load',
      'errors': [],
      'server': 'east-web-001'}


text:
    _tab_and_enter_keypress : function (e, curVal) {
         if ( e.keyCode === $.ui.keyCode.ENTER && $('table.CrEaTeDtAbLeStYlE td.mo').length === 0 ||
                 e.keyCode === $.ui.keyCode.TAB && curVal.length === 0 ) {
             e.preventDefault();
             var keytype = e.keyCode === $.ui.keyCode.ENTER ? "ENTERKey" : "TABKey";
             if ( curVal.length > 0 && this.options.UserInputAllowed === true ||
                  e.keyCode === $.ui.keyCode.ENTER && $('table.CrEaTeDtAbLeStYlE tr').length === 0 ) {
                 /*--  this catches user input that is not in the autocomplete list  --*/
                this.__exec_trigger({ 'newCode': -1, 'noGreenChk': true, 'newVal' : curVal, 'type': keytype });
             } else {
                this.__exec_trigger({ 'newCode': $('table.CrEaTeDtAbLeStYlE td:first').attr('menu_opt_key'),
                            'newVal' : $('table.CrEaTeDtAbLeStYlE td:first').text(), 'type': keytype });
             }
         } else if (e.keyCode === $.ui.keyCode.TAB ) {
            if ( curVal.length > 0) {
                var matched =  this._build_match_ary(e, curVal);
                if ( matched.length > 0 ) {
                    var newval = matched[0].val.replace(/<span class=match>|<\/span>|<img[\w\W ]*?>/g, '');
                    this.__exec_trigger({ 'newCode': matched[0].ky,
                                 'newVal' : newval, 'type': "TABKey" });
                } else if ( this._match_complete() === true ) {
                    this.__exec_trigger({ 'newCode': curVal, 'newVal' : curVal, 'type': "TABKey" });
                }
            }
        }
        this.__set_help_msg('', '');
    },

    _clear_filter : function (e) {
         this.options._CurrentFilter = '';
    },

    _bind_events: function ( on_or_off ) {
        var ky = '',
            Sel = {},
            elem_id = 'span#SP_' + this.options._ID;
        this._off(this.element, 'touchend mousedown click mouseenter focus keypress keydown input keyup search mouseleave blur');
        // set mouseenter class for table cell
        ky = 'mouseenter ' + elem_id + ' table.CrEaTeDtAbLeStYlE td.dflt';
        Sel[ky] = '_hiLiteOnOff';
        /*--  header filter logic  --*/
        ky = 'mouseenter ' + elem_id + ' table#HF_' + this._event_ns + ' td.hf_td';
        Sel[ky] = '_run_header_filter';
        /*--  remove dropdown if navbar-toggle clicked --*/
        ky = 'click button.navbar-toggle';
        Sel[ky] = '_remove_dropdown';
        // when user chooses (clicks), insert text into input box
        ky = 'mousedown ' + elem_id + ' table.CrEaTeDtAbLeStYlE td ';
        Sel[ky] = '_choice_selected';
        // when mouse leaves the container, remove it from DOM
        ky = 'mouseleave ' + elem_id;
        Sel[ky] = '_remove_dropdown';
        if ( /on/i.test(on_or_off) ) {
            this._on($('body'), Sel);
            // highlight the clear button
            this._on(this.cached['.clearBtn'], {
                'mouseleave': '_hiLiteOnOff',
                'mouseenter': '_hiLiteOnOff',
                'mousedown': '_clearInput'
                /*--  'click': '_clearInput'  --*/
            });
            // bind events to this.element
            this._on({
                'touchend':  '_build_whole_dropdown',
                'mousedown':  '_build_whole_dropdown',
                'click':  '_build_whole_dropdown',
                'mouseenter':  '_build_whole_dropdown',
                'focus':  '_build_whole_dropdown',
                'keypress': '_build_whole_dropdown',
                'keydown': '_build_whole_dropdown',
                'input': '_build_whole_dropdown',
                'keyup': '_build_whole_dropdown',
                'search':  '_build_whole_dropdown',
                'mouseleave':  '_remove_dropdown',
                'blur': '_remove_dropdown',
            });
        } else {
            if ( this.cached['.clearBtn'] !== undefined ) {
                this._off(this.cached['.clearBtn'], 'mouseleave mouseenter mousedown');
            }
            this._off(this.element, 'touchend mousedown click mouseenter focus keypress keydown input keyup search mouseleave blur');
        }

    },


text:
require 'faf/markdown/parser/simple_node'

module FAF
  module Markdown
    class EmphNode < SimpleNode
      def to_s
        content_tag(:em, @data.join)
      end
    end
  end
end


text:
#include "test.hpp"

namespace
{
	char const * VERT_SHADER_SOURCE_X("gl-320/texture-derivative-x.vert");
	char const * FRAG_SHADER_SOURCE_X("gl-320/texture-derivative-x.frag");
	char const * VERT_SHADER_SOURCE_Y("gl-320/texture-derivative-y.vert");
	char const * FRAG_SHADER_SOURCE_Y("gl-320/texture-derivative-y.frag");

	GLsizei const VertexCount(4);
	GLsizeiptr const VertexSize = VertexCount * sizeof(glf::vertex_v2fv2f);
	glf::vertex_v2fv2f const VertexData[VertexCount] =
	{
		glf::vertex_v2fv2f(glm::vec2(-1.0f,-1.0f), glm::vec2(0.0f, 1.0f)),
		glf::vertex_v2fv2f(glm::vec2( 1.0f,-1.0f), glm::vec2(1.0f, 1.0f)),
		glf::vertex_v2fv2f(glm::vec2( 1.0f, 1.0f), glm::vec2(1.0f, 0.0f)),
		glf::vertex_v2fv2f(glm::vec2(-1.0f, 1.0f), glm::vec2(0.0f, 0.0f))
	};

	GLsizei const ElementCount(6);
	GLsizeiptr const ElementSize = ElementCount * sizeof(GLushort);
	GLushort const ElementData[ElementCount] =
	{
		0, 1, 2,
		2, 3, 0
	};

	namespace buffer
	{
		enum type
		{
			VERTEX,
			ELEMENT,
			TRANSFORM,
			MAX
		};
	}//namespace buffer

	GLuint VertexArrayName(0);
	GLuint ProgramName(0);
	GLuint TextureName(0);
	std::vector<GLuint> BufferName(buffer::MAX);
	GLint UniformTransform(0);
	GLint UniformDiffuse(0);
}//namespace

class gl_320_texture_derivative : public test
{
public:
	gl_320_texture_derivative(int argc, char* argv[]) :
		test(argc, argv, "gl-320-texture-derivative", test::CORE, 3, 2, glm::vec2(glm::pi<float>() * 0.05f, -glm::pi<float>() * 0.49f))
	{}

private:
	bool initProgram()
	{
		bool Validated(true);

		if(Validated)
		{
			compiler Compiler;
			GLuint VertShaderName = Compiler.create(GL_VERTEX_SHADER, getDataDirectory() + VERT_SHADER_SOURCE_X, "--version 150 --profile core");
			GLuint FragShaderName = Compiler.create(GL_FRAGMENT_SHADER, getDataDirectory() + FRAG_SHADER_SOURCE_X, "--version 150 --profile core");
			Validated = Validated && Compiler.check();

			ProgramName = glCreateProgram();
			glAttachShader(ProgramName, VertShaderName);
			glAttachShader(ProgramName, FragShaderName);

			glBindAttribLocation(ProgramName, semantic::attr::POSITION, "Position");
			glBindAttribLocation(ProgramName, semantic::attr::TEXCOORD, "Texcoord");
			glBindFragDataLocation(ProgramName, semantic::frag::COLOR, "Color");
			glLinkProgram(ProgramName);
			Validated = Validated && Compiler.checkProgram(ProgramName);
		}

		if(Validated)
		{
			UniformTransform = glGetUniformBlockIndex(ProgramName, "transform");
			UniformDiffuse = glGetUniformLocation(ProgramName, "Diffuse");
		}

		Validated = Validated && this->checkError("initProgram");

		return Validated;
	}

	bool initBuffer()
	{
		glGenBuffers(buffer::MAX, &BufferName[0]);

		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferName[buffer::ELEMENT]);
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, ElementSize, ElementData, GL_STATIC_DRAW);
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

		glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::VERTEX]);
		glBufferData(GL_ARRAY_BUFFER, VertexSize, VertexData, GL_STATIC_DRAW);
		glBindBuffer(GL_ARRAY_BUFFER, 0);

		GLint UniformBufferOffset(0);

		glGetIntegerv(
			GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT,
			&UniformBufferOffset);

		GLint UniformBlockSize = glm::max(GLint(sizeof(glm::mat4)), UniformBufferOffset);

		glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::TRANSFORM]);
		glBufferData(GL_UNIFORM_BUFFER, UniformBlockSize, NULL, GL_DYNAMIC_DRAW);
		glBindBuffer(GL_UNIFORM_BUFFER, 0);

		return this->checkError("initBuffer");
	}

	bool initTexture()
	{
		gli::texture2D Texture(gli::RGBA8_UNORM, gli::texture2D::dim_type(64));
		gli::texture2D::size_type Level = Texture.levels();

		Texture[0].clear(glm::u8vec4(255, 0, 0, 255));
		Texture[1].clear(glm::u8vec4(255, 128, 0, 255));
		Texture[2].clear(glm::u8vec4(255, 255, 0, 255));
		Texture[3].clear(glm::u8vec4(0, 255, 0, 255));
		Texture[4].clear(glm::u8vec4(0, 255, 255, 255));
		Texture[5].clear(glm::u8vec4(0, 0, 255, 255));
		Texture[6].clear(glm::u8vec4(255, 0, 0, 255));

		glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

		glGenTextures(1, &TextureName);

		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, TextureName);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, GLint(Texture.levels() - 1));
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

		for(gli::texture2D::size_type Level = 0; Level < Texture.levels(); ++Level)
		{
			glTexImage2D(GL_TEXTURE_2D,
				GLint(Level),
				gli::internal_format(Texture.format()),
				GLsizei(Texture[Level].dimensions().x),
				GLsizei(Texture[Level].dimensions().y),
				0,
				gli::external_format(Texture.format()),
				gli::type_format(Texture.format()),
				Texture[Level].data());
		}

		if(Texture.levels() == 1)
			glGenerateMipmap(GL_TEXTURE_2D);

		glPixelStorei(GL_UNPACK_ALIGNMENT, 4);

		return this->checkError("initTexture");
	}

	bool initVertexArray()
	{
		glGenVertexArrays(1, &VertexArrayName);
		glBindVertexArray(VertexArrayName);
			glBindBuffer(GL_ARRAY_BUFFER, BufferName[buffer::VERTEX]);
			glVertexAttribPointer(semantic::attr::POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v2fv2f), BUFFER_OFFSET(0));
			glVertexAttribPointer(semantic::attr::TEXCOORD, 2, GL_FLOAT, GL_FALSE, sizeof(glf::vertex_v2fv2f), BUFFER_OFFSET(sizeof(glm::vec2)));
			glBindBuffer(GL_ARRAY_BUFFER, 0);

			glEnableVertexAttribArray(semantic::attr::POSITION);
			glEnableVertexAttribArray(semantic::attr::TEXCOORD);

			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, BufferName[buffer::ELEMENT]);
		glBindVertexArray(0);

		return this->checkError("initVertexArray");
	}

	bool begin()
	{
		bool Validated = true;

		if(Validated)
			Validated = initBuffer();
		if(Validated)
			Validated = initTexture();
		if(Validated)
			Validated = initProgram();
		if(Validated)
			Validated = initVertexArray();

		glEnable(GL_SAMPLE_SHADING);
		glMinSampleShading(4.0f);

		return Validated && this->checkError("begin");
	}

	bool end()
	{
		glDeleteBuffers(buffer::MAX, &BufferName[0]);
		glDeleteProgram(ProgramName);
		glDeleteTextures(1, &TextureName);
		glDeleteVertexArrays(1, &VertexArrayName);

		return this->checkError("end");
	}

	bool render()
	{
		glm::ivec2 WindowSize(this->getWindowSize());

		{
			glBindBuffer(GL_UNIFORM_BUFFER, BufferName[buffer::TRANSFORM]);
			glm::mat4* Pointer = (glm::mat4*)glMapBufferRange(
				GL_UNIFORM_BUFFER, 0,	sizeof(glm::mat4),
				GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);

			glm::mat4 Projection = glm::perspective(glm::pi<float>() * 0.25f, 4.0f / 3.0f, 0.1f, 100.0f);
			glm::mat4 Model = glm::scale(glm::mat4(1.0f), glm::vec3(2.0f));

			*Pointer = Projection * this->view() * Model;

			// Make sure the uniform buffer is uploaded
			glUnmapBuffer(GL_UNIFORM_BUFFER);
		}

		glViewport(0, 0, WindowSize.x, WindowSize.y);
		glClearBufferfv(GL_COLOR, 0, &glm::vec4(1.0f, 0.5f, 0.0f, 1.0f)[0]);

		glUseProgram(ProgramName);
		glUniform1i(UniformDiffuse, 0);
		glUniformBlockBinding(ProgramName, UniformTransform, semantic::uniform::TRANSFORM0);

		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, TextureName);
		glBindBufferBase(GL_UNIFORM_BUFFER, semantic::uniform::TRANSFORM0, BufferName[buffer::TRANSFORM]);
		glBindVertexArray(VertexArrayName);

		glDrawElementsInstancedBaseVertex(GL_TRIANGLES, ElementCount, GL_UNSIGNED_SHORT, 0, 1, 0);

		return true;
	}
};

int main(int argc, char* argv[])
{
	int Error(0);

	gl_320_texture_derivative Test(argc, argv);
	Error += Test();

	return Error;
}


text:
#include "NativeWindow.h"

namespace nwtpi {

bool 		 NativeWindow::bcmInitState = false;
bool 		 NativeWindow::deviceOpenState[] = { false, false, false, false };

NativeWindow::NativeWindow (unsigned int width, unsigned int height, NATIVE_DEVICE_ENUM _device, unsigned char alpha)
	: device(_device), windowWidth(width), windowHeight(height), windowAlpha(alpha), currentElementId(-1), elementSyncLockId(-1)
{

	displayOpen(device);

	makeCurrentElement(addElement());
	syncElement(currentElementId);

}

NativeWindow::~NativeWindow() {
	// delete elements[*]

	if ( displayClose(displayHandle) == 0 )	// closing current device's displayHandle
		deviceOpenState[device] = false;
	else
		throw runtime_error("runtime error : ~NativeWindow ** cannot close device");
}

void NativeWindow::displayOpen(NATIVE_DEVICE_ENUM dev)
{
	if ( ! bcmInitState ) {
		bcm_host_init();
		bcmInitState = true;
	}

	if ( ! deviceOpenState[dev] ) {
		if ( graphics_get_display_size( dev, &deviceWidth, &deviceHeight) < 0)
			throw runtime_error("runtime error : NativeWindow::NativeWindow ** cannot get graphic_display_size.");

		DEBUG ( "NativeWindow", "graphicsGetDisplaySize done : " << deviceWidth << "," << deviceHeight );

		if ( ( windowWidth > deviceWidth ) || ( windowHeight > deviceHeight ) )
			throw runtime_error("runtime error : NativeWindow::NativeWindow ** window sizes exceed device capabilities.");

		displayHandle = vc_dispmanx_display_open( (uint32_t) dev );
		if ( displayHandle == DISPMANX_NO_HANDLE )
			throw runtime_error("runtime error : NativeWindow::displayOpen ** does not return an handle");

		deviceOpenState[dev] = true;
	} else
		throw runtime_error("runtime error : NativeWindow::NativeWindow ** cannot open device twice.");
}

int NativeWindow::displayClose(DISPMANX_DISPLAY_HANDLE_T disp) {

	return vc_dispmanx_display_close( disp );

}

/**
 * 		\fn		int addElement()
 * 		\brief	add an element that will fill the entire window
 * 		\param	none
 * 		\return (int) elementId
 */
int NativeWindow::addElement()
{
	return ( addElement(0, 0, windowWidth, windowHeight, windowAlpha) );
}

/**
 *  	\fn		int addElement(unsigned int x, unsigned int y, unsigned int width, unsigned int height, bool opaqueness)
 *  	\brief	add an element created from a marked out region
 *  	\param	x Position
 *  	\param 	y Position
 *  	\param	width Size
 *  	\param	height Size
 *  	\param	alpha Alpha level (0x00=no alpha, 0xff full transparent)
 *  	\return	(int) elementId
 */
int NativeWindow::addElement(unsigned int x, unsigned int y, unsigned int w, unsigned int h, unsigned char windowAlphaLevel)
{
	NativeElement * elem = new NativeElement(displayHandle, x, y, w, h, windowAlphaLevel );

	elements.push_back(elem);

	return ( elem->getId() );

}

/**
 *  	\fn		int addElementImage
 *  	\brief	add an element created from an image resource
 *  	\param	uint width, uint height, bool opaqueness, VC_IMAGE_TYPE_T imageType, void * imageData
 *  	\return	(int) elementId
 */
//int NativeWindow::addElementImage(unsigned int width, unsigned int height, bool opaqueness, VC_IMAGE_TYPE_T imageType, void * imageData)
//{
//	//NativeElement * elem;
//	// resource_create
//
//	// resource_write
//
//	// NativeElement * elem = new element(..)
//	// elements.push_back(elem);
//	// ++currentElement;
//
//
//}

/**
 * 		\fn		void makeCurrentElement
 * 		\brief	set currentElementId
 * 		\param	int elementId
 * 		\return	void
 */
void NativeWindow::makeCurrentElement(int elementId)
{
	currentElementId = elementId;
}

NativeElement * NativeWindow::getCurrentElement()
{
	return elements[currentElementId];
}

bool NativeWindow::syncElement(int elementToSync)
{
	if ( elementSyncLockId != -1 )
		elements[elementSyncLockId]->setUpdateLockState(false);

	elements[elementToSync]->updateSync();
	elementSyncLockId = elementToSync;
	elements[elementToSync]->setUpdateLockState(true);

	return true; 	// TODO check updateSync() return value
}

int NativeWindow::getLastElementId()
{
	return elements.back()->getId();
}

NativeElement * NativeWindow::findElementById(int elemId)
{
	vector<int>::size_type vsize = elements.size();
	unsigned int i;
	NativeElement * result = NULL;					// TODO ... NWTPI_NATIVE_NO_ELEMENT

	for (i=0 ; i<vsize; i++) {
		if ( elements[i]->getId() == elemId ) {
			result = elements[i];
			break;
		}
	}

	return ( result );
}

#ifdef DEBUG_ON
void NativeWindow::logd(string method, ostream& message) {
	ostringstream& s = dynamic_cast<ostringstream&>(message);
	cout << "==> " << method << " : " << s.str() << endl;
}
#endif

} // namespace nwtpi


text:
module Typhoeus
  class Hydra

    # This module contains logic to run a hydra.
    module Runnable

      # Start the hydra run.
      #
      # @example Start hydra run.
      #   hydra.run
      #
      # @return [ Symbol ] Return value from multi.perform.
      def run
        number_requests = 0
        loop do
          break if number_requests == max_concurrency || queued_requests.empty?
          number_requests += queued_requests.pop(max_concurrency).map do |request|
            add(request)
          end.size
        end
        multi.perform
      end
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace GZSpotGate.Core
{
    internal class DataEventArgs : EventArgs
    {
        public string readerIp { get; set; }

        public bool ICData { get; set; }

        public bool QRData { get; set; }

        public bool IDData { get; set; }

        public bool FaceData { get; set; }

        public string Name { get; set; }

        public string Data { get; set; }

        public bool GateOpen { get; set; }

        public bool PersonIn { get; set; }
    }
}


text:
import argparse
import json
import logging
import os
import sys
import time

import boto.ec2
import boto.ec2.autoscale
import boto.sqs

from boto.route53.connection import Route53Connection

from boto.sqs.message import RawMessage

UPDATE = ["autoscaling:EC2_INSTANCE_LAUNCH"]
SKIP = ["autoscaling:TEST_NOTIFICATION",
        "autoscaling:EC2_INSTANCE_LAUNCH_ERROR"]
REMOVE = ["autoscaling:EC2_INSTANCE_TERMINATE",
          "autoscaling:EC2_INSTANCE_TERMINATE_ERROR"]

LOG_FORMAT = '%(asctime)s [%(name)s] %(levelname)s %(message)s'
LOG_DATE = '%Y-%m-%d %I:%M:%S %p'

logger = logging.getLogger('autoscale-dns')

class AutorouteError(Exception):
    pass

# check if the record is there
# if it isn't add the record
def add_record(id):
    # queue the route53 addition (may take time for ip address to get assigned)
    instance = ec2.get_only_instances([id])[0]

    if instance.public_dns_name is not None \
            and len(instance.public_dns_name) > 0:
        dns_name = instance.public_dns_name

        try:
            # get the tag data from the instance
            d = json.loads(instance.tags['dns'])

            name = "%s.%s" % (d['record'], d['zone'])
        except:
            raise AutorouteError("unable to get dns information")

        zone = r53.get_zone(d['zone'])
        records = zone.find_records(name, 'CNAME', all=True)

        # add DNS record
        # is this a list, or just one.
        if records is None:
            # straight up add
            logger.debug('no matching records, add')
            pass

        elif isinstance(records, list):
            for r in records:
                if r.identifier == id:
                    # is dns the same
                    if dns_name in r.resource_records:
                        logger.debug('found matching record, skip')
                        return

                    else:
                        # update or delete.
                        logger.debug('found matching record, update')
                        zone.update_record(r, dns_name, new_identifier=(id, 1))
                        return

        elif records.identifier == id:
            # is dns the same
            if dns_name in records.resource_records:
                logger.debug('found matching record, skip')
                return

            else:
                logger.debug('found matching record, update')
                zone.update_record(records, dns_name, new_identifier=(id, 1))
                return

        # this is a new record
        logger.debug(
            'adding record %s CNAME %s, (%s,1)' % (name, dns_name, id))
        zone.add_record(
            "CNAME", name, dns_name, ttl=60,
            identifier=(id, 1), comment='autoscaling group increased')

        return

def remove_record(id):
    instance = ec2.get_only_instances([id])[0]

    try:
        d = json.loads(instance.tags['dns'])

        name = "%s.%s" % (d['record'], d['zone'])
    except:
        raise AutorouteError("unable to get dns information")

    zone = r53.get_zone(d['zone'])
    records = zone.find_records(name, 'CNAME', all=True)

    if records is None:
        logger.debug("no records found for %s" % (name))
        return
    elif isinstance(records, list):
        for r in records:
            if r.identifier == id:
                logger.debug('deleting record %s, %s' % (name, id))
                zone.delete_record(r)
    elif records.identifier == id:
        logger.debug('deleting record %s, %s' % (name, id))
        zone.delete_record(records)

# todo: finish implementing this and have it run periodically
def sync_group():
    id = "i-f4bd6ea9"
    i = ec2.get_only_instances([id])[0]

    g = i.tags['aws:autoscaling:groupName']

    s = autoscale.get_all_groups(names=[g])[0]

    for ai in s.instances:
        #ai_id = ai.instance_id
        # get instance
        # get public dns
        # check r53
        pass

parser = argparse.ArgumentParser(description='do the dns')
parser.add_argument('--key', default=None)
parser.add_argument('--secret', default=None)
parser.add_argument('--region', default="us-west-1")
parser.add_argument('-q', '--queue', default="autoroute")
parser.add_argument('-l', '--level', default='info')

args = parser.parse_args()

logging.basicConfig(format=LOG_FORMAT,
                    datefmt=LOG_DATE,
                    level=args.level.upper())

# check for argument, env
key = args.key or os.environ.get('AWS_ACCESS_KEY_ID')
secret = args.secret or os.environ.get('AWS_SECRET_ACCESS_KEY')

logger.debug('attempting to connect to aws resources')

if key is not None:
    sqs = boto.sqs.connect_to_region(
        args.region, aws_access_key_id=key, aws_secret_access_key=secret)
    ec2 = boto.ec2.connect_to_region(
        args.region, aws_access_key_id=key, aws_secret_access_key=secret)
    autoscale = boto.ec2.autoscale.connect_to_region(
        args.region, aws_access_key_id=key, aws_secret_access_key=secret)
    r53 = Route53Connection(key, secret)
# fall back to instance role
else:
    sqs = boto.sqs.connect_to_region(args.region)
    ec2 = boto.ec2.connect_to_region(args.region)
    autoscale = boto.ec2.autoscale.connect_to_region(args.region)
    r53 = Route53Connection()

logger.debug('connceted to aws resources')

logger.info('hello')

# connect to SQS Queue
queue = sqs.get_queue(args.queue)

if queue is None:
    logger.error("unable to attach to queue '%s'" % (args.queue))
    sys.exit(1)

queue.set_message_class(RawMessage)

# on event
while True:
    try:
        message = queue.read(visibility_timeout=10, wait_time_seconds=20)
    except KeyboardInterrupt:
        logger.info('Goodbye')
        sys.exit(0)
    except Exception as e:
        logger.exception(e)
        logger.error('error reading from queue: %s' % (str(e)))
        message = None

    delete = False

    if message is not None:
        # in this case the data should be a json object, with an embedded
        # json message
        try:
            data = json.loads(message.get_body())
            details = json.loads(data['Message'])

            event = details["Event"]

            logger.debug('message about %s' % (event))

            # if launch, add (or queue) r53 update
            if event == "autoscaling:EC2_INSTANCE_LAUNCH":
                add_record(details["EC2InstanceId"])
                # if we get here (no exceptions), delete!
                delete = True

            elif event in SKIP:
                # we aren't going to do anything with this one.
                delete = True

            elif event in REMOVE:
                # we are going to attempt to remove the DNS record
                remove_record(details["EC2InstanceId"])
                # if we get here (no exceptions), delete!
                delete = True

            else:
                # whoops, whats this message here for
                delete = True

        except AutorouteError:
            # these failures shouldn't be retried later
            delete = True
        except Exception as e:
            # for now leave on queue and retry when they are visible
            logger.warn('error reading message: %s' % (str(e)))
            # delete = True

        if delete:
            queue.delete_message(message)
    else:
        try:
            time.sleep(3)
        except KeyboardInterrupt:
            logger.info('Goodbye')
            sys.exit(0)