text:
#ifndef SEQAN_HEADER_RAZERS_WINDOW_H
#define SEQAN_HEADER_RAZERS_WINDOW_H

#include <iostream>

namespace SEQAN_NAMESPACE_MAIN {

//////////////////////////////////////////////////////////////////////////////
// Find read matches in a single genome sequence
//
// Creates finder on the contig given by the ID and a verifier.
// Searches through the contig using the findWindowNext() function.
// The results are dumped in the (aligned) store.
template <
    typename TFragmentStore,
    typename TReadIndex,
    typename TSwiftSpec,
    typename TPreprocessing,
    typename TCounts,
    typename TRazerSOptions,
    typename TRazerSMode>
void _mapSingleReadsToContigWindow(
    TFragmentStore & store,
    unsigned                                  contigId,                     // ... and its sequence number
    Pattern<TReadIndex, Swift<TSwiftSpec> > & swiftPattern,
    TPreprocessing & preprocessing,
    TCounts & cnts,
    char                                      orientation,                      // q-gram index of reads
    TRazerSOptions & options,
    TRazerSMode                       const & mode)
{
    _mapSingleReadsToContigWindow(store, store, contigId, swiftPattern, swiftPattern, preprocessing, cnts, orientation, options, mode);
}

//////////////////////////////////////////////////////////////////////////////
// Find read matches in a single genome sequence
//
// Creates finder on the contig given by the ID and a verifier.
// Searches through the contig using the findWindowNext() function.
// The results are dumped in the (aligned) store.
// Specialized version: Contigs are taken from the main store but the results
//   are written to the block store. Used in the parallel reads over whole
//   genome version.
template <
    typename TFragmentStore,
    typename TReadIndex,
    typename TSwiftSpec,
    typename TSwiftPatternHandler,
    typename TPreprocessing,
    typename TCounts,
    typename TRazerSOptions,
    typename TRazerSMode>
void _mapSingleReadsToContigWindow(
    TFragmentStore & mainStore,
    TFragmentStore & blockStore,
    unsigned                                  contigId,                     // ... and its sequence number
    Pattern<TReadIndex, Swift<TSwiftSpec> > & swiftPattern,
    TSwiftPatternHandler & swiftPatternHandler,
    TPreprocessing & preprocessing,
    TCounts & cnts,
    char                                      orientation,                      // q-gram index of reads
    TRazerSOptions & options,
    TRazerSMode                      const & mode)
{
    // FILTRATION
    typedef typename TFragmentStore::TContigSeq             TContigSeq;
    typedef Finder<TContigSeq, Swift<TSwiftSpec> >          TSwiftFinder;
    typedef Pattern<TReadIndex, Swift<TSwiftSpec> >         TSwiftPattern;

    // VERIFICATION
    typedef MatchVerifier<
        TFragmentStore,
        TRazerSOptions,
        TRazerSMode,
        TPreprocessing,
        TSwiftPattern,
        TCounts>                                           TVerifier;
    typedef typename Fibre<TReadIndex, FibreText>::Type TReadSet;

    // HITS
    typedef typename TSwiftFinder::THitString               THitString;
    typedef typename Value<THitString>::Type                TSwiftHit;
    typedef typename Size<THitString>::Type                 THitStringSize;

    typedef typename Size<typename TFragmentStore::TAlignedReadStore>::Type TAlignedReadStoreSize;

    // output what is done if verbous
    if (options._debugLevel >= 1)
    {
        std::cerr << std::endl << "Process genome seq #" << contigId;
        if (orientation == 'F')
            std::cerr << "[fwd]";
        else
            std::cerr << "[rev]";
    }
    // lock contig
    lockContig(mainStore, contigId);
    TContigSeq & contigSeq = mainStore.contigStore[contigId].seq;
    if (orientation == 'R')
        reverseComplement(contigSeq);

    // Create finder and verifier
    TSwiftFinder    swiftFinder(contigSeq, options.repeatLength, 1);
    TVerifier       verifier(blockStore, options, preprocessing, swiftPattern, cnts);

    // initialize verifier
    verifier.onReverseComplement = (orientation == 'R');
    verifier.genomeLength = length(contigSeq);
    verifier.m.contigId = contigId;

    // if the pattern can be initialized and there is a non-repeat region in the contig that fits a qgram.
    if (windowFindBegin(swiftFinder, swiftPattern, options.errorRate))
    {

        _proFloat myTime = sysTime();

        bool sequenceLeft = true;

        // while there is more contig sequence to search through
        while (sequenceLeft)
        {
            sequenceLeft = windowFindNext(swiftFinder, swiftPattern, 1000000);

            printf("filter: %f sec\n", sysTime() - myTime);
            myTime = sysTime();

            // get the found hits from the finder
            THitString hits = getSwiftHits(swiftFinder);
            // verifiy them
            for (THitStringSize h = 0; h < length(hits); ++h)
            {
                verifier.m.readId = hits[h].ndlSeqNo;             //array oder jedesmal berechnen
                matchVerify(verifier, swiftInfix(hits[h], contigSeq), hits[h].ndlSeqNo, host(host(swiftPattern))[hits[h].ndlSeqNo], mode);
                ++options.countFiltration;
            }

            printf("verify: %f sec\n", sysTime() - myTime);
            myTime = sysTime();

            // compact matches if neccessary
            if (length(blockStore.alignedReadStore) > options.compactThresh)
            {
                TAlignedReadStoreSize oldSize = length(blockStore.alignedReadStore);
                if (IsSameType<typename TRazerSMode::TGapMode, RazerSGapped>::VALUE)
                    maskDuplicates(blockStore, mode);       // overlapping parallelograms cause duplicates

                compactMatches(blockStore, cnts, options, mode, swiftPatternHandler, COMPACT);
                if (options._debugLevel >= 2)
                    std::cerr << '(' << oldSize - length(blockStore.alignedReadStore) << " matches removed)";
            }

        }

        // clear finders
        windowFindEnd(swiftFinder, swiftPattern);

    }

    if (!unlockAndFreeContig(mainStore, contigId))                              // if the contig is still used
        if (orientation == 'R')
            reverseComplement(contigSeq);
    // we have to restore original orientation
}

}

#endif


text:
<?php

if (!defined('_PS_VERSION_'))
	exit;

function upgrade_module_1_1_4($object)
{
	return	$object->createAjaxController();
}

redpajama_set_name: RedPajamaGithub


text:
* Run multiple Kubernetes clusters. Run across platforms. Plan for regional and cloud outages.
* Require applications be platform agnostic. Moving an application between a Kubernetes AWS cluster and a Kubernetes bare-metal cluster should be normal.
* Strive to make single-cluster outages tolerable. Practice performing failovers.
* Strive to make single-cluster outages a non-event. Load balance applications between multiple clusters, automate failover behaviors, and adjust alerting behaviors.

## Versioning

Typhoon provides tagged releases to allow clusters to be versioned using ordinary Terraform configs.

```
module "yavin" {
  source = "git::https://github.com/poseidon/typhoon//google-cloud/fedora-coreos/kubernetes?ref=v1.25.4"
  ...
}

module "mercury" {
  source = "git::https://github.com/poseidon/typhoon//bare-metal/flatcar-linux/kubernetes?ref=v1.25.4"
  ...
}
```

Main is updated regularly, so it is recommended to [pin](https://www.terraform.io/docs/modules/sources.html) modules to a [release tag](https://github.com/poseidon/typhoon/releases) or [commit](https://github.com/poseidon/typhoon/commits/main) hash. Pinning ensures `terraform get --update` only fetches the desired version.

## Terraform Versions

Typhoon modules support Terraform v0.13.x and higher. Poseidon publishes [providers](/topics/security/#terraform-providers) to the Terraform Provider Registry for automatic install via `terraform init`.

| Typhoon Release   | Terraform version   |
|-------------------|---------------------|
| v1.21.2 - ?       | v0.13.x, v0.14.4+, v0.15.x, v1.0.x |
| v1.21.1 - v1.21.1 | v0.13.x, v0.14.4+, v0.15.x |
| v1.20.2 - v1.21.0 | v0.13.x, v0.14.4+   |
| v1.20.0 - v1.20.2 | v0.13.x             |
| v1.18.8 - v1.19.4 | v0.12.26+, v0.13.x  |
| v1.15.0 - v1.18.8 | v0.12.x             |
| v1.10.3 - v1.15.0 | v0.11.x             |
| v1.9.2 - v1.10.2  | v0.10.4+ or v0.11.x |
| v1.7.3 - v1.9.1   | v0.10.x             |
| v1.6.4 - v1.7.2   | v0.9.x              |

## Cluster Upgrades

Typhoon recommends upgrading clusters using a blue-green replacement strategy and migrating workloads.

1. Launch new (candidate) clusters from tagged releases
2. Apply workloads from existing cluster(s)
3. Evaluate application health and performance
4. Migrate application traffic to the new cluster
5. Compare metrics and delete old cluster when ready

Blue-green replacement reduces risk for clusters running critical applications. Candidate clusters allow baseline properties of clusters to be assessed (e.g. pod-to-pod bandwidth). Applying application workloads allows health to be assessed before being subjected to traffic (e.g. detect any changes in Kubernetes behavior between versions). Migration to the new cluster can be controlled according to requirements. Migration may mean updating DNS records to resolve the new cluster's ingress or may involve a load balancer gradually shifting traffic to the new cluster "backend". Retain the old cluster for a time to compare metrics or for fallback if issues arise.

Blue-green replacement provides some subtler benefits as well:

* Encourages investment in tooling for traffic migration and failovers. When a cluster incident arises, shifting applications to a healthy cluster will be second nature.
* Discourages reliance on in-place opaque state. Retain confidence in your ability to create infrastructure from scratch.
* Allows Typhoon to make architecture changes between releases and eases the burden on Typhoon maintainers. By contrast, distros promising in-place upgrades get stuck with their mistakes or require complex and error-prone migrations.

### Bare-Metal

Typhoon bare-metal clusters are provisioned by a PXE-enabled network boot environment and a [Matchbox](https://github.com/poseidon/matchbox) service. To upgrade, re-provision machines into a new cluster.

Failover application workloads to another cluster (varies).

```
kubectl config use-context other-context
kubectl apply -f mercury -R
# DNS or load balancer changes
```

Power off bare-metal machines and set their next boot device to PXE.

```
ipmitool -H node1.example.com -U USER -P PASS power off
ipmitool -H node1.example.com -U USER -P PASS chassis bootdev pxe
```

Delete or comment the Terraform config for the cluster.

```
- module "mercury" {
-   source = "git::https://github.com/poseidon/typhoon//bare-metal/flatcar-linux/kubernetes"
-   ...
-}
```

Apply to delete old provisioning configs from Matchbox.

```
$ terraform apply
Apply complete! Resources: 0 added, 0 changed, 55 destroyed.
```

Re-provision a new cluster by following the bare-metal [tutorial](../fedora-coreos/bare-metal.md#cluster).

### Cloud

Create a new cluster following the tutorials. Failover application workloads to the new cluster (varies).

```
kubectl config use-context other-context
kubectl apply -f mercury -R
# DNS or load balancer changes
```

Once you're confident in the new cluster, delete the Terraform config for the old cluster.

```
- module "yavin" {
-   source = "git::https://github.com/poseidon/typhoon//google-cloud/flatcar-linux/kubernetes"
-   ...
-}
```

Apply to delete the cluster.

```
$ terraform apply
Apply complete! Resources: 0 added, 0 changed, 55 destroyed.
```

### Alternatives

#### In-place Edits

Typhoon uses a static pod Kubernetes control plane which allows certain manifest upgrades to be performed in-place. Components like `kube-apiserver`, `kube-controller-manager`, and `kube-scheduler` are run as static pods. Components `flannel`/`calico`, `coredns`, and `kube-proxy` are scheduled on Kubernetes and can be edited via `kubectl`.

In certain scenarios, in-place edits can be useful for quickly rolling out security patches (e.g. bumping `coredns`) or prioritizing speed over the safety of a proper cluster re-provision and transition.

!!! note
    Rarely, we may test certain security in-place edits and mention them as an option in release notes.

!!! warning
    Typhoon does not support or document in-place edits as an upgrade strategy. They involve inherent risks and we choose not to make recommendations or guarentees about the safety of different in-place upgrades. Its explicitly a non-goal.

#### Node Replacement

Typhoon supports multi-controller clusters, so it is possible to upgrade a cluster by deleting and replacing nodes one by one.

!!! warning
    Typhoon does not support or document node replacement as an upgrade strategy. It limits Typhoon's ability to make infrastructure and architectural changes between tagged releases.

## Node Configuration Updates

Typhoon worker instance groups (default workers and [worker pools](../advanced/worker-pools.md)) on AWS and Google Cloud gradually rolling replace worker instances when configuration changes are applied.

### AWS

On AWS, worker instances belong to an auto-scaling group. When an auto-scaling group's launch configuration changes, an AWS [Instance Refresh](https://docs.aws.amazon.com/autoscaling/ec2/userguide/asg-instance-refresh.html) gradually replaces worker instances.

Instance refresh creates surge instances, waits for a warm-up period, then deletes old instances.

```diff
module "tempest" {
  source = "git::https://github.com/poseidon/typhoon//aws/VARIANT/kubernetes?ref=VERSION"

  # AWS
  cluster_name = "tempest"
  ...

  # optional
  worker_count = 2
- worker_type  = "t3.small"
+ worker_type  = "t3a.small"

  # change from on-demand to spot
+ worker_price = "0.0309"

  # default is 30GB
+ disk_size = 50

  # change worker snippets
+ worker_snippets = [
+   file("butane/feature.yaml"),
+ ]
}
```

Applying edits to most worker fields will start an instance refresh:

* `worker_type`
* `disk_*`
* `worker_price` (i.e. spot)
* `worker_target_groups`
* `worker_snippets`

However, changing `os_stream`/`os_channel` or new AMIs becoming available will NOT change the launch configuration or trigger an Instance Refresh. This allows Fedora CoreOS or Flatcar Linux to auto-update themselves via reboots and avoids unexpected terraform diffs for new AMIs.

!!! note
    Before Typhoon v1.25.4, worker nodes only used new launch configurations when replaced manually (or due to failure). If you must change node configuration manually, it's still possible. Create a new [worker pool](../advanced/worker-pools.md), then scale down the old worker pool as desired.

### Google Cloud

On Google Cloud, worker instances belong to a [managed instance group](https://cloud.google.com/compute/docs/instance-groups#managed_instance_groups). When a group's launch template changes, a [rolling update](https://cloud.google.com/compute/docs/instance-groups/rolling-out-updates-to-managed-instance-groups) gradually replaces worker instances.

The rolling update creates surge instances, waits for instances to be healthy, then deletes old instances.

```diff
module "yavin" {
  source = "git::https://github.com/poseidon/typhoon//google-cloud/VARIANT/kubernetes?ref=VERSION"

  # Google Cloud
  cluster_name  = "yavin"
  ...

  # optional
  worker_count = 2
+ worker_type = "n2-standard-2"
+ worker_preemptible = true

  # default is 30GB
+ disk_size = 50

  # change worker snippets
+ worker_snippets = [
+   file("butane/feature.yaml"),
+ ]
}
```

Applying edits to most worker fields will start an instance refresh:

* `worker_type`
* `disk_*`
* `worker_preemptible` (i.e. spot)
* `worker_snippets`

However, changing `os_stream`/`os_channel` or new compute images becoming available will NOT change the launch template or update instances. This allows Fedora CoreOS or Flatcar Linux to auto-update themselves via reboots and avoids unexpected terraform diffs for new AMIs.

!!! note
    Before Typhoon v1.25.4, worker nodes only used new launch templates when replaced manually (or due to failure). If you must change node configuration manually, it's still possible. Create a new [worker pool](../advanced/worker-pools.md), then scale down the old worker pool as desired.

## Upgrade poseidon/ct

The [poseidon/ct](https://github.com/poseidon/terraform-provider-ct) Terraform provider plugin parses, validates, and converts Butane Configs to Ignition user-data for provisioning instances. Since Typhoon v1.12.2+, the plugin can be updated in-place so that on apply, only workers will be replaced.

Update the version of the `ct` plugin in each Terraform working directory. Typhoon clusters managed in the working directory **must** be v1.12.2 or higher.

```diff
provider "ct" {}

terraform {
  required_providers {
    ct = {
      source  = "poseidon/ct"
-     version = "0.10.0"
+     version = "0.11.0"
    }
    ...
  }
}
```

Run init and plan to check that no diff is proposed for the controller nodes (a diff would destroy cluster state).

```
terraform init
terraform plan
```

Apply the change. If worker nodes' user-data is changed and workers will be replaced. Rollout happens slightly differently on each platform:

#### AWS

See AWS node [config updates](#aws).

#### Azure

Azure edits the worker scale set in-place instantly. Manually terminate workers to create replacement workers using the new user-data.

#### Bare-Metal

No action is needed. Bare-Metal machines do not re-PXE unless explicitly made to do so.

#### DigitalOcean

DigitalOcean destroys existing worker nodes and DNS records, then creates new workers and DNS records. DigitalOcean lacks a "managed group" notion. For worker droplets to join the cluster, you **must** taint the secret copying step to indicate it must be repeated to add the kubeconfig to new workers.

```
# old workers destroyed, new workers created
terraform apply

# add kubeconfig to new workers
terraform state list | grep null_resource
terraform taint module.nemo.null_resource.copy-worker-secrets[N]
terraform apply
```

Expect downtime.

#### Google Cloud

See Google Cloud node [config updates](#google-cloud).


text:
package org.itas.common.net;

/**
 * ���������
 * @author Administrator
 */
public interface NetServerListener {

	/**
	 * ���Ӵ򿪼���
	 * @param netconnection
	 */
    public abstract void connectionOpened(NetConnection netconnection);

    /**
     * ���ӹرռ���
     * @param netconnection
     */
    public abstract void connectionClosed(NetConnection netconnection);
}


text:
package org.terasology.engine.rendering.opengl;

import com.google.common.base.Objects;
import com.google.common.collect.Sets;
import gnu.trove.iterator.TIntIntIterator;
import gnu.trove.map.TIntIntMap;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TIntIntHashMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import org.joml.Matrix3fc;
import org.joml.Matrix4fc;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL20;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.terasology.engine.core.GameThread;
import org.terasology.engine.core.subsystem.lwjgl.LwjglGraphicsProcessing;
import org.terasology.engine.registry.CoreRegistry;
import org.terasology.engine.rendering.ShaderManager;
import org.terasology.engine.rendering.assets.material.BaseMaterial;
import org.terasology.engine.rendering.assets.material.MaterialData;
import org.terasology.engine.rendering.assets.shader.ShaderParameterMetadata;
import org.terasology.engine.rendering.assets.shader.ShaderProgramFeature;
import org.terasology.engine.rendering.assets.texture.Texture;
import org.terasology.gestalt.assets.AssetType;
import org.terasology.gestalt.assets.DisposableResource;
import org.terasology.gestalt.assets.ResourceUrn;

import java.nio.FloatBuffer;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;

public class GLSLMaterial extends BaseMaterial {

    private static final Logger logger = LoggerFactory.getLogger(GLSLMaterial.class);
    private final LwjglGraphicsProcessing graphicsProcessing;

    private int textureIndex;

    private TObjectIntMap<String> bindMap = new TObjectIntHashMap<>();
    private TIntObjectMap<Texture> textureMap = new TIntObjectHashMap<>();

    private GLSLShader shader;
    private boolean activeFeaturesChanged;
    private TObjectIntMap<UniformId> uniformLocationMap = new TObjectIntHashMap<>();

    private EnumSet<ShaderProgramFeature> activeFeatures = Sets.newEnumSet(Collections.emptyList(), ShaderProgramFeature.class);
    private int activeFeaturesMask;

    private ShaderManager shaderManager;

    private DisposalAction disposalAction;
    private MaterialData materialData;

    private final FloatBuffer matrixBuffer = BufferUtils.createFloatBuffer(16);

    public GLSLMaterial(ResourceUrn urn, AssetType<?, MaterialData> assetType, MaterialData data,
                        LwjglGraphicsProcessing graphicsProcessing, GLSLMaterial.DisposalAction disposalAction) {
        super(urn, assetType, disposalAction);
        this.graphicsProcessing = graphicsProcessing;
        this.disposalAction = disposalAction;
        this.materialData = data;
        shaderManager = CoreRegistry.get(ShaderManager.class);
        graphicsProcessing.asynchToDisplayThread(() -> {
            reload(data);
        });
    }

    public static GLSLMaterial create(ResourceUrn urn, LwjglGraphicsProcessing graphicsProcessing,
                                      AssetType<?, MaterialData> assetType, MaterialData data) {
        return new GLSLMaterial(urn, assetType, data, graphicsProcessing, new DisposalAction(urn, graphicsProcessing));
    }

    @Override
    public void enable() {
        if (shaderManager.getActiveMaterial() != this || activeFeaturesChanged) {
            GL13.glActiveTexture(GL13.GL_TEXTURE0);
            GL20.glUseProgram(getActiveShaderProgramId());

            // Make sure the shader manager knows that this program is currently active
            shaderManager.setActiveMaterial(this);
            activeFeaturesChanged = false;
        }
    }

    @Override
    public void bindTextures() {
        if (isDisposed()) {
            return;
        }

        enable();
        for (int slot : textureMap.keys()) {
            Texture texture = textureMap.get(slot);
            if (texture.isDisposed()) {
                textureMap.remove(slot);
                logger.error("Attempted to bind disposed texture {}", texture);
            } else {
                shaderManager.bindTexture(slot, texture);
            }
        }
    }

    @Override
    public boolean isRenderable() {
        for (Texture texture : textureMap.valueCollection()) {
            if (!texture.isLoaded()) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void recompile() {
        TIntIntIterator it = disposalAction.shaderPrograms.iterator();
        while (it.hasNext()) {
            it.advance();
            GL20.glDeleteProgram(it.value());
        }
        disposalAction.shaderPrograms.clear();
        uniformLocationMap.clear();
        bindMap.clear();

        disposalAction.shaderPrograms.put(0, shader.linkShaderProgram(0));
        for (Set<ShaderProgramFeature> permutation : Sets.powerSet(shader.getAvailableFeatures())) {
            int featureMask = ShaderProgramFeature.getBitset(permutation);
            disposalAction.shaderPrograms.put(featureMask, shader.linkShaderProgram(featureMask));
        }

        //resolves #966
        //Some of the uniforms are not updated constantly between frames
        //this function will rebind any uniforms that are not bound
        rebindVariables(materialData);
    }

    @Override
    public final void doReload(MaterialData data) {
        try {
            GameThread.synch(() -> {
                disposalAction.close();
                uniformLocationMap.clear();

                shader = (GLSLShader) data.getShader();
                recompile();
                rebindVariables(data);
            });
        } catch (InterruptedException e) {
            logger.error("Failed to reload {}", getUrn(), e);
        }
    }

    private void rebindVariables(MaterialData data) {
        for (Map.Entry<String, Texture> entry : data.getTextures().entrySet()) {
            setTexture(entry.getKey(), entry.getValue());
        }

        for (Map.Entry<String, Float> entry : data.getFloatParams().entrySet()) {
            setFloat(entry.getKey(), entry.getValue());
        }

        for (Map.Entry<String, Integer> entry : data.getIntegerParams().entrySet()) {
            setInt(entry.getKey(), entry.getValue());
        }

        for (Map.Entry<String, float[]> entry : data.getFloatArrayParams().entrySet()) {
            float[] value = entry.getValue();
            switch (value.length) {
                case 1:
                    setFloat(entry.getKey(), value[0]);
                    break;
                case 2:
                    setFloat2(entry.getKey(), value[0], value[1]);
                    break;
                case 3:
                    setFloat3(entry.getKey(), value[0], value[1], value[2]);
                    break;
                case 4:
                    setFloat4(entry.getKey(), value[0], value[1], value[2], value[3]);
                    break;
                default:
                    logger.error("MaterialData contains float array entry of size > 4");
                    break;
            }
        }
    }

    @Override
    public void setTexture(String desc, Texture texture) {
        if (isDisposed()) {
            return;
        }

        int texId;
        if (bindMap.containsKey(desc)) {
            texId = bindMap.get(desc);
        } else {
            // TODO: do this initially, and try and have similar textures in similar slots for all materials.
            ShaderParameterMetadata metadata = shader.getParameter(desc);
            if (metadata == null || !metadata.getType().isTexture()) {
                return;
            }
            texId = textureIndex++;

            // Make sure to bind the texture for all permutations
            setInt(desc, texId);

            bindMap.put(desc, texId);
        }

        textureMap.put(texId, texture);
    }

    @Override
    public void activateFeature(ShaderProgramFeature feature) {
        if (shader.getAvailableFeatures().contains(feature)) {
            activeFeatures.add(feature);
            activeFeaturesMask = ShaderProgramFeature.getBitset(activeFeatures);
            activeFeaturesChanged = true;
        } else {
            logger.error("Attempt to activate unsupported feature {} for material {} using shader {}", feature, getUrn(), shader.getUrn());
        }
    }

    @Override
    public void deactivateFeature(ShaderProgramFeature feature) {
        if (activeFeatures.remove(feature)) {
            activeFeaturesMask = ShaderProgramFeature.getBitset(activeFeatures);
            activeFeaturesChanged = true;
        }
    }

    @Override
    public void deactivateFeatures(ShaderProgramFeature... features) {
        Arrays.asList(features).forEach(this::deactivateFeature);
    }

    @Override
    public boolean supportsFeature(ShaderProgramFeature feature) {
        return shader.getAvailableFeatures().contains(feature);
    }

    @Override
    public void setFloat(String desc, float f, boolean currentOnly) {
        if (isDisposed()) {
            return;
        }
        if (currentOnly) {
            enable();
            int id = getUniformLocation(getActiveShaderProgramId(), desc);
            GL20.glUniform1f(id, f);
        } else {
            TIntIntIterator it = disposalAction.shaderPrograms.iterator();
            while (it.hasNext()) {
                it.advance();

                GL20.glUseProgram(it.value());
                int id = getUniformLocation(it.value(), desc);
                GL20.glUniform1f(id, f);
            }

            restoreStateAfterUniformsSet();
        }
    }

    @Override
    public void setFloat1(String desc, FloatBuffer buffer, boolean currentOnly) {
        if (isDisposed()) {
            return;
        }
        if (currentOnly) {
            enable();
            int id = getUniformLocation(getActiveShaderProgramId(), desc);
            GL20.glUniform1fv(id, buffer);
        } else {
            TIntIntIterator it = disposalAction.shaderPrograms.iterator();
            while (it.hasNext()) {
                it.advance();

                GL20.glUseProgram(it.value());
                int id = getUniformLocation(it.value(), desc);
                GL20.glUniform1fv(id, buffer);
            }

            restoreStateAfterUniformsSet();
        }
    }

    @Override
    public void setFloat2(String desc, float f1, float f2, boolean currentOnly) {
        if (isDisposed()) {
            return;
        }
        if (currentOnly) {
            enable();
            int id = getUniformLocation(getActiveShaderProgramId(), desc);
            GL20.glUniform2f(id, f1, f2);
        } else {
            TIntIntIterator it = disposalAction.shaderPrograms.iterator();
            while (it.hasNext()) {
                it.advance();

                GL20.glUseProgram(it.value());
                int id = getUniformLocation(it.value(), desc);
                GL20.glUniform2f(id, f1, f2);
            }

            restoreStateAfterUniformsSet();
        }
    }

    @Override
    public void setFloat2(String desc, FloatBuffer buffer, boolean currentOnly) {
        if (isDisposed()) {
            return;
        }
        if (currentOnly) {
            enable();
            int id = getUniformLocation(getActiveShaderProgramId(), desc);
            GL20.glUniform2fv(id, buffer);
        } else {
            TIntIntIterator it = disposalAction.shaderPrograms.iterator();
            while (it.hasNext()) {
                it.advance();

                GL20.glUseProgram(it.value());
                int id = getUniformLocation(it.value(), desc);
                GL20.glUniform2fv(id, buffer);
            }

            restoreStateAfterUniformsSet();
        }
    }

    @Override
    public void setFloat3(String desc, float f1, float f2, float f3, boolean currentOnly) {
        if (isDisposed()) {
            return;
        }
        if (currentOnly) {
            enable();
            int id = getUniformLocation(getActiveShaderProgramId(), desc);
            GL20.glUniform3f(id, f1, f2, f3);
        } else {
            TIntIntIterator it = disposalAction.shaderPrograms.iterator();
            while (it.hasNext()) {
                it.advance();

                GL20.glUseProgram(it.value());
                int id = getUniformLocation(it.value(), desc);
                GL20.glUniform3f(id, f1, f2, f3);
            }

            restoreStateAfterUniformsSet();
        }
    }

    @Override
    public void setFloat3(String desc, FloatBuffer buffer, boolean currentOnly) {
        if (isDisposed()) {
            return;
        }
        if (currentOnly) {
            enable();
            int id = getUniformLocation(getActiveShaderProgramId(), desc);
            GL20.glUniform3fv(id, buffer);
        } else {
            TIntIntIterator it = disposalAction.shaderPrograms.iterator();
            while (it.hasNext()) {
                it.advance();

                GL20.glUseProgram(it.value());
                int id = getUniformLocation(it.value(), desc);
                GL20.glUniform3fv(id, buffer);
            }

            restoreStateAfterUniformsSet();
        }
    }

    @Override
    public void setFloat4(String desc, float f1, float f2, float f3, float f4, boolean currentOnly) {
        if (isDisposed()) {
            return;
        }
        if (currentOnly) {
            enable();
            int id = getUniformLocation(getActiveShaderProgramId(), desc);
            GL20.glUniform4f(id, f1, f2, f3, f4);
        } else {
            TIntIntIterator it = disposalAction.shaderPrograms.iterator();
            while (it.hasNext()) {
                it.advance();

                GL20.glUseProgram(it.value());
                int id = getUniformLocation(it.value(), desc);
                GL20.glUniform4f(id, f1, f2, f3, f4);
            }

            restoreStateAfterUniformsSet();
        }
    }

    @Override
    public void setFloat4(String desc, FloatBuffer buffer, boolean currentOnly) {
        if (isDisposed()) {
            return;
        }
        if (currentOnly) {
            enable();
            int id = getUniformLocation(getActiveShaderProgramId(), desc);
            GL20.glUniform4fv(id, buffer);
        } else {
            TIntIntIterator it = disposalAction.shaderPrograms.iterator();
            while (it.hasNext()) {
                it.advance();

                GL20.glUseProgram(it.value());
                int id = getUniformLocation(it.value(), desc);
                GL20.glUniform4fv(id, buffer);
            }

            restoreStateAfterUniformsSet();
        }
    }

    @Override
    public void setInt(String desc, int i, boolean currentOnly) {
        if (isDisposed()) {
            return;
        }
        if (currentOnly) {
            enable();
            int id = getUniformLocation(getActiveShaderProgramId(), desc);
            GL20.glUniform1i(id, i);
        } else {
            TIntIntIterator it = disposalAction.shaderPrograms.iterator();
            while (it.hasNext()) {
                it.advance();

                GL20.glUseProgram(it.value());
                int id = getUniformLocation(it.value(), desc);
                GL20.glUniform1i(id, i);
            }

            restoreStateAfterUniformsSet();
        }
    }

    @Override
    public void setBoolean(String desc, boolean value, boolean currentOnly) {
        if (isDisposed()) {
            return;
        }
        if (currentOnly) {
            enable();
            int id = getUniformLocation(getActiveShaderProgramId(), desc);
            GL20.glUniform1i(id, value ? 1 : 0);
        } else {
            TIntIntIterator it = disposalAction.shaderPrograms.iterator();
            while (it.hasNext()) {
                it.advance();

                GL20.glUseProgram(it.value());
                int id = getUniformLocation(it.value(), desc);
                GL20.glUniform1i(id, value ? 1 : 0);
            }

            restoreStateAfterUniformsSet();
        }
    }

    @Override
    public void setMatrix3(String desc, Matrix3fc value, boolean currentOnly) {
        if (isDisposed()) {
            return;
        }
        matrixBuffer.rewind();
        value.get(matrixBuffer);
        if (currentOnly) {
            enable();
            int id = getUniformLocation(getActiveShaderProgramId(), desc);
            GL20.glUniformMatrix3fv(id, false, matrixBuffer);
        } else {
            TIntIntIterator it = disposalAction.shaderPrograms.iterator();
            while (it.hasNext()) {
                it.advance();

                GL20.glUseProgram(it.value());
                int id = getUniformLocation(it.value(), desc);
                GL20.glUniformMatrix3fv(id, false, matrixBuffer);
            }

            restoreStateAfterUniformsSet();
        }
    }

    @Override
    public void setMatrix3(String desc, FloatBuffer value, boolean currentOnly) {
        if (isDisposed()) {
            return;
        }
        if (currentOnly) {
            enable();
            int id = getUniformLocation(getActiveShaderProgramId(), desc);
            GL20.glUniformMatrix3fv(id, false, value);
        } else {
            TIntIntIterator it = disposalAction.shaderPrograms.iterator();
            while (it.hasNext()) {
                it.advance();

                GL20.glUseProgram(it.value());
                int id = getUniformLocation(it.value(), desc);
                GL20.glUniformMatrix3fv(id, false, value);
            }

            restoreStateAfterUniformsSet();
        }
    }

    @Override
    public void setMatrix4(String desc, Matrix4fc value, boolean currentOnly) {
        if (isDisposed()) {
            return;
        }
        matrixBuffer.rewind();
        value.get(matrixBuffer);
        if (currentOnly) {
            enable();
            int id = getUniformLocation(getActiveShaderProgramId(), desc);
            GL20.glUniformMatrix4fv(id, false, matrixBuffer);
        } else {
            TIntIntIterator it = disposalAction.shaderPrograms.iterator();
            while (it.hasNext()) {
                it.advance();

                GL20.glUseProgram(it.value());
                int id = getUniformLocation(it.value(), desc);
                GL20.glUniformMatrix4fv(id, false, matrixBuffer);
            }

            restoreStateAfterUniformsSet();
        }
    }

    @Override
    public void setMatrix4(String desc, FloatBuffer value, boolean currentOnly) {
        if (isDisposed()) {
            return;
        }
        if (currentOnly) {
            enable();
            int id = getUniformLocation(getActiveShaderProgramId(), desc);
            GL20.glUniformMatrix4fv(id, false, value);
        } else {
            TIntIntIterator it = disposalAction.shaderPrograms.iterator();
            while (it.hasNext()) {
                it.advance();

                GL20.glUseProgram(it.value());
                int id = getUniformLocation(it.value(), desc);
                GL20.glUniformMatrix4fv(id, false, value);
            }

            restoreStateAfterUniformsSet();
        }
    }

    private int getActiveShaderProgramId() {
        return disposalAction.shaderPrograms.get(activeFeaturesMask);
    }

    private int getUniformLocation(int activeShaderProgramId, String desc) {
        UniformId id = new UniformId(activeShaderProgramId, desc);

        if (uniformLocationMap.containsKey(id)) {
            return uniformLocationMap.get(id);
        }

        int loc = GL20.glGetUniformLocation(activeShaderProgramId, desc);
        uniformLocationMap.put(id, loc);

        return loc;
    }

    private void restoreStateAfterUniformsSet() {
        if (shaderManager.getActiveMaterial() == this) {
            GL20.glUseProgram(getActiveShaderProgramId());
        } else {
            enable();
        }
    }

    private static final class UniformId {
        private int shaderProgramId;
        private String name;
        private int hashCode;

        // made package-private after Jenkins' suggestion
        UniformId(int shaderProgramId, String name) {
            this.shaderProgramId = shaderProgramId;
            this.name = name;
            this.hashCode = Objects.hashCode(shaderProgramId, name);
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == this) {
                return true;
            }
            if (obj instanceof UniformId) {
                UniformId other = (UniformId) obj;
                return shaderProgramId == other.shaderProgramId && Objects.equal(name, other.name);
            }
            return false;
        }

        @Override
        public int hashCode() {
            return this.hashCode;
        }
    }

    private static class DisposalAction implements DisposableResource {

        private final ResourceUrn urn;
        private final LwjglGraphicsProcessing graphicsProcessing;

        private TIntIntMap shaderPrograms = new TIntIntHashMap();

        // made package-private after Jenkins' suggestion
        DisposalAction(ResourceUrn urn, LwjglGraphicsProcessing graphicsProcessing) {
            this.urn = urn;
            this.graphicsProcessing = graphicsProcessing;
        }

        @Override
        public void close() {
            try {
                GameThread.synch(() -> {
                    logger.debug("Disposing material {}.", urn);
                    final TIntIntMap deletedPrograms = new TIntIntHashMap(shaderPrograms);
                    graphicsProcessing.asynchToDisplayThread(() -> {
                        TIntIntIterator it = deletedPrograms.iterator();
                        while (it.hasNext()) {
                            it.advance();
                            GL20.glDeleteProgram(it.value());
                        }
                    });
                    shaderPrograms.clear();
                });
            } catch (InterruptedException e) {
                logger.error("Failed to dispose {}", urn, e);
            }
        }
    }
}


text:
package org.apache.camel.component.salesforce.api.dto.composite;

import java.util.Arrays;
import java.util.Collections;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.thoughtworks.xstream.XStream;
import org.apache.camel.component.salesforce.api.dto.RestError;
import org.apache.camel.component.salesforce.api.utils.JsonUtils;
import org.apache.camel.component.salesforce.api.utils.XStreamUtils;
import org.junit.Test;

import static org.hamcrest.core.IsCollectionContaining.hasItems;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class SObjectTreeResponseTest {

    @Test
    public void shouldDeserializeJsonFromSalesforceExample() throws Exception {
        final String json = "{\n"//
                            + "    \"hasErrors\" : false,\n"//
                            + "    \"results\" : [{\n"//
                            + "     \"referenceId\" : \"ref1\",\n"//
                            + "     \"id\" : \"001D000000K0fXOIAZ\"\n"//
                            + "     },{\n"//
                            + "     \"referenceId\" : \"ref4\",\n"//
                            + "     \"id\" : \"001D000000K0fXPIAZ\"\n"//
                            + "     },{\n"//
                            + "     \"referenceId\" : \"ref2\",\n"//
                            + "     \"id\" : \"003D000000QV9n2IAD\"\n"//
                            + "     },{\n"//
                            + "     \"referenceId\" : \"ref3\",\n"//
                            + "     \"id\" : \"003D000000QV9n3IAD\"\n"//
                            + "     }]\n"//
                            + "}";

        final ObjectMapper mapper = JsonUtils.createObjectMapper();

        final ObjectReader reader = mapper.readerFor(SObjectTreeResponse.class);
        final SObjectTreeResponse response = reader.readValue(json);

        assertNotNull("Response should be parsed", response);

        assertFalse("`hasErrors` flag should be false", response.hasErrors());

        assertEquals("Should read 4 references", 4, response.getResults().size());
        assertThat("4 references should be read as expected", response.getResults(), hasItems(new ReferenceId("ref1", "001D000000K0fXOIAZ", Collections.emptyList()), //
                                                                                new ReferenceId("ref4", "001D000000K0fXPIAZ", Collections.emptyList()), //
                                                                                new ReferenceId("ref2", "003D000000QV9n2IAD", Collections.emptyList()), //
                                                                                new ReferenceId("ref3", "003D000000QV9n3IAD", Collections.emptyList())));
    }

    @Test
    public void shouldDeserializeJsonFromSalesforceFailureExample() throws Exception {
        final String json = "{\n"//
                            + "   \"hasErrors\" : true,\n"//
                            + "   \"results\" : [{\n"//
                            + "     \"referenceId\" : \"ref2\",\n"//
                            + "     \"errors\" : [{\n"//
                            + "       \"statusCode\" : \"INVALID_EMAIL_ADDRESS\",\n"//
                            + "       \"message\" : \"Email: invalid email address: 123\",\n"//
                            + "       \"fields\" : [ \"Email\" ]\n"//
                            + "       }]\n"//
                            + "     }]\n"//
                            + "}";

        final ObjectMapper mapper = JsonUtils.createObjectMapper();

        final ObjectReader reader = mapper.readerFor(SObjectTreeResponse.class);
        final SObjectTreeResponse response = reader.readValue(json);

        assertNotNull("Response should be parsed", response);

        assertTrue("`hasErrors` flag should be true", response.hasErrors());

        assertEquals("Should read one reference", 1, response.getResults().size());
        assertThat("The reference should be read as expected", response.getResults(),
                   hasItems(new ReferenceId("ref2", null, Arrays.asList(new RestError("INVALID_EMAIL_ADDRESS", "Email: invalid email address: 123", Arrays.asList("Email"))))));
    }

    @Test
    public void shouldDeserializeXmlFromSalesforceExample() throws Exception {
        final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"//
                           + "<Result>\n"//
                           + "    <hasErrors>false</hasErrors>\n"//
                           + "    <results>\n"//
                           + "        <id>001D000000K0fXOIAZ</id>\n"//
                           + "        <referenceId>ref1</referenceId>\n"//
                           + "    </results>\n"//
                           + "    <results>\n"//
                           + "        <id>001D000000K0fXPIAZ</id>\n"//
                           + "        <referenceId>ref4</referenceId>\n"//
                           + "    </results>\n"//
                           + "    <results>\n"//
                           + "        <id>003D000000QV9n2IAD</id>\n"//
                           + "        <referenceId>ref2</referenceId>\n"//
                           + "    </results>\n"//
                           + "    <results>\n"//
                           + "        <id>003D000000QV9n3IAD</id>\n"//
                           + "        <referenceId>ref3</referenceId>\n"//
                           + "    </results>\n"//
                           + "</Result>";

        final XStream xStream = XStreamUtils.createXStream(SObjectTreeResponse.class);

        final SObjectTreeResponse response = (SObjectTreeResponse)xStream.fromXML(xml);

        assertNotNull("Response should be parsed", response);

        assertFalse("`hasErrors` flag should be false", response.hasErrors());

        assertEquals("Should read 4 references", 4, response.getResults().size());
        assertThat("4 references should be read as expected", response.getResults(), hasItems(new ReferenceId("ref1", "001D000000K0fXOIAZ", Collections.emptyList()), //
                                                                                new ReferenceId("ref4", "001D000000K0fXPIAZ", Collections.emptyList()), //
                                                                                new ReferenceId("ref2", "003D000000QV9n2IAD", Collections.emptyList()), //
                                                                                new ReferenceId("ref3", "003D000000QV9n3IAD", Collections.emptyList())));
    }

    @Test
    public void shouldDeserializeXmlFromSalesforceFailureExample() throws Exception {
        final String xml = "<Result>\n"//
                           + "    <hasErrors>true</hasErrors>\n"//
                           + "    <results>\n"//
                           + "        <errors>\n"//
                           + "            <fields>Email</fields>\n"//
                           + "            <message>Email: invalid email address: 123</message>\n"//
                           + "            <statusCode>INVALID_EMAIL_ADDRESS</statusCode>\n"//
                           + "        </errors>\n"//
                           + "        <referenceId>ref2</referenceId>\n"//
                           + "    </results>\n"//
                           + "</Result>";

        final XStream xStream = XStreamUtils.createXStream(SObjectTreeResponse.class);

        final SObjectTreeResponse response = (SObjectTreeResponse)xStream.fromXML(xml);

        assertNotNull("Response should be parsed", response);

        assertTrue("`hasErrors` flag should be true", response.hasErrors());

        assertEquals("Should read one reference", 1, response.getResults().size());
        assertThat("The reference should be read as expected", response.getResults(),
                   hasItems(new ReferenceId("ref2", null, Arrays.asList(new RestError("INVALID_EMAIL_ADDRESS", "Email: invalid email address: 123", Arrays.asList("Email"))))));
    }
}


text:
package org.andengine.extension.tmx;

import java.util.ArrayList;

import org.andengine.extension.tmx.util.constants.TMXConstants;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.util.SAXUtils;
import org.xml.sax.Attributes;

import android.util.SparseArray;

/**
 * (c) 2010 Nicolas Gramlich
 * (c) 2011 Zynga Inc.
 *
 * @author Nicolas Gramlich
 * @since 19:38:11 - 20.07.2010
 */
public class TMXTiledMap implements TMXConstants {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	private final String mOrientation;
	private final int mTileColumns;
	private final int mTilesRows;
	private final int mTileWidth;
	private final int mTileHeight;

	private final ArrayList<TMXTileSet> mTMXTileSets = new ArrayList<TMXTileSet>();
	private final ArrayList<TMXLayer> mTMXLayers = new ArrayList<TMXLayer>();
	private final ArrayList<TMXObjectGroup> mTMXObjectGroups = new ArrayList<TMXObjectGroup>();

	private final SparseArray<ITextureRegion> mGlobalTileIDToTextureRegionCache = new SparseArray<ITextureRegion>();
	private final SparseArray<TMXProperties<TMXTileProperty>> mGlobalTileIDToTMXTilePropertiesCache = new SparseArray<TMXProperties<TMXTileProperty>>();

	private final TMXProperties<TMXTiledMapProperty> mTMXTiledMapProperties = new TMXProperties<TMXTiledMapProperty>();

	// ===========================================================
	// Constructors
	// ===========================================================

	TMXTiledMap(final Attributes pAttributes) {
		this.mOrientation = pAttributes.getValue("", TMXConstants.TAG_MAP_ATTRIBUTE_ORIENTATION);
		if(!this.mOrientation.equals(TMXConstants.TAG_MAP_ATTRIBUTE_ORIENTATION_VALUE_ORTHOGONAL)) {
			throw new IllegalArgumentException(TMXConstants.TAG_MAP_ATTRIBUTE_ORIENTATION + ": '" + this.mOrientation + "' is not supported.");
		}
		this.mTileColumns = SAXUtils.getIntAttributeOrThrow(pAttributes, TMXConstants.TAG_MAP_ATTRIBUTE_WIDTH);
		this.mTilesRows = SAXUtils.getIntAttributeOrThrow(pAttributes, TMXConstants.TAG_MAP_ATTRIBUTE_HEIGHT);
		this.mTileWidth = SAXUtils.getIntAttributeOrThrow(pAttributes, TMXConstants.TAG_MAP_ATTRIBUTE_TILEWIDTH);
		this.mTileHeight = SAXUtils.getIntAttributeOrThrow(pAttributes, TMXConstants.TAG_MAP_ATTRIBUTE_TILEHEIGHT);
	}

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	public final String getOrientation() {
		return this.mOrientation;
	}
	/**
	 * @deprecated Instead use {@link TMXTiledMap#getTileColumns()} * {@link TMXTiledMap#getTileWidth()}.
	 * @return
	 */
	@Deprecated
	public final int getWidth() {
		return this.mTileColumns;
	}

	public final int getTileColumns() {
		return this.mTileColumns;
	}

	/**
	 * @deprecated Instead use {@link TMXTiledMap#getTileRows()} * {@link TMXTiledMap#getTileHeight()}.
	 * @return
	 */
	@Deprecated
	public final int getHeight() {
		return this.mTilesRows;
	}

	public final int getTileRows() {
		return this.mTilesRows;
	}

	public final int getTileWidth() {
		return this.mTileWidth;
	}

	public final int getTileHeight() {
		return this.mTileHeight;
	}

	void addTMXTileSet(final TMXTileSet pTMXTileSet) {
		this.mTMXTileSets.add(pTMXTileSet);
	}

	public ArrayList<TMXTileSet> getTMXTileSets() {
		return this.mTMXTileSets;
	}

	void addTMXLayer(final TMXLayer pTMXLayer) {
		this.mTMXLayers.add(pTMXLayer);
	}

	public ArrayList<TMXLayer> getTMXLayers() {
		return this.mTMXLayers;
	}

	void addTMXObjectGroup(final TMXObjectGroup pTMXObjectGroup) {
		this.mTMXObjectGroups.add(pTMXObjectGroup);
	}

	public ArrayList<TMXObjectGroup> getTMXObjectGroups() {
		return this.mTMXObjectGroups;
	}

	public TMXProperties<TMXTileProperty> getTMXTilePropertiesByGlobalTileID(final int pGlobalTileID) {
		return this.mGlobalTileIDToTMXTilePropertiesCache.get(pGlobalTileID);
	}

	public void addTMXTiledMapProperty(final TMXTiledMapProperty pTMXTiledMapProperty) {
		this.mTMXTiledMapProperties.add(pTMXTiledMapProperty);
	}

	public TMXProperties<TMXTiledMapProperty> getTMXTiledMapProperties() {
		return this.mTMXTiledMapProperties;
	}

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	// ===========================================================
	// Methods
	// ===========================================================

	public TMXProperties<TMXTileProperty> getTMXTileProperties(final int pGlobalTileID) {
		final SparseArray<TMXProperties<TMXTileProperty>> globalTileIDToTMXTilePropertiesCache = this.mGlobalTileIDToTMXTilePropertiesCache;

		final TMXProperties<TMXTileProperty> cachedTMXTileProperties = globalTileIDToTMXTilePropertiesCache.get(pGlobalTileID);
		if(cachedTMXTileProperties != null) {
			return cachedTMXTileProperties;
		} else {
			final ArrayList<TMXTileSet> tmxTileSets = this.mTMXTileSets;

			for(int i = tmxTileSets.size() - 1; i >= 0; i--) {
				final TMXTileSet tmxTileSet = tmxTileSets.get(i);
				if(pGlobalTileID >= tmxTileSet.getFirstGlobalTileID()) {
					return tmxTileSet.getTMXTilePropertiesFromGlobalTileID(pGlobalTileID);
				}
			}
			throw new IllegalArgumentException("No TMXTileProperties found for pGlobalTileID=" + pGlobalTileID);
		}
	}

	public ITextureRegion getTextureRegionFromGlobalTileID(final int pGlobalTileID) {
		final SparseArray<ITextureRegion> globalTileIDToTextureRegionCache = this.mGlobalTileIDToTextureRegionCache;

		final ITextureRegion cachedTextureRegion = globalTileIDToTextureRegionCache.get(pGlobalTileID);
		if(cachedTextureRegion != null) {
			return cachedTextureRegion;
		} else {
			final ArrayList<TMXTileSet> tmxTileSets = this.mTMXTileSets;

			for(int i = tmxTileSets.size() - 1; i >= 0; i--) {
				final TMXTileSet tmxTileSet = tmxTileSets.get(i);
				if(pGlobalTileID >= tmxTileSet.getFirstGlobalTileID()) {
					final ITextureRegion textureRegion = tmxTileSet.getTextureRegionFromGlobalTileID(pGlobalTileID);
					/* Add to cache for the all future pGlobalTileIDs with the same value. */
					globalTileIDToTextureRegionCache.put(pGlobalTileID, textureRegion);
					return textureRegion;
				}
			}
			throw new IllegalArgumentException("No TextureRegion found for pGlobalTileID=" + pGlobalTileID);
		}
	}

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}


text:
class SpreadTestClass {
  self = null;
  x = null;
  y = null;
  SpreadTestClass = SpreadTestClass;
  new(x, y) {
    this.self = this;
    this.x = x;
    this.y = y;
  }
}

var object = new SpreadTestClass(...[0, 1]);

// ----------------------------------------------------------------------------

assertEquals(object.x, 0);
assertEquals(object.y, 1);
assertEquals(object.self, object);
assertTrue(object instanceof object.SpreadTestClass);


text:
package com.zhan_dui.evermemo;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.umeng.analytics.MobclickAgent;
import com.zhan_dui.data.Memo;
import com.zhan_dui.data.MemoDB;
import com.zhan_dui.data.MemoProvider;
import com.zhan_dui.sync.Evernote;

public class MemoActivity extends ActionBarActivity implements OnClickListener,
		OnKeyListener {

	private EditText mContentEditText;
	private Memo memo;
	private boolean mCreateNew;
	private Context mContext;

	private String mLastSaveContent;

	private Timer mTimer;
	private Evernote mEvernote;

	private boolean mTextChanged = false;

	private final String mBullet = " • ";
	private final String mNewLine = "\n";
	public static final String LogTag = "MemoActivity Log";
	public static String sEditCount = "EditCount";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		mContext = this;
		overridePendingTransition(R.anim.push_up, R.anim.push_down);
		super.onCreate(savedInstanceState);
		getSupportActionBar().setDisplayShowTitleEnabled(true);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setDisplayUseLogoEnabled(false);
		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setTitle(getString(R.string.app_memo));
		setContentView(R.layout.activity_memo);
		mContentEditText = (EditText) findViewById(R.id.content);
		Bundle bundle = getIntent().getExtras();
		if (bundle != null && bundle.getSerializable("memo") != null) {
			memo = (Memo) bundle.getSerializable("memo");
			mCreateNew = false;
			mLastSaveContent = memo.getContent();
		} else {
			memo = new Memo();
			mCreateNew = true;
		}

		mContentEditText.setText(Html.fromHtml(memo.getContent()));
		if (mCreateNew) {
			getWindow().setSoftInputMode(
					WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
			mContentEditText.requestFocus();
			MobclickAgent.onEvent(mContext, "new_memo");
		} else {
			MobclickAgent.onEvent(mContext, "edit_memo");
		}

		mContentEditText.setOnKeyListener(this);
		mEvernote = new Evernote(mContext);
		findViewById(R.id.edit_container).setOnClickListener(this);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			saveMemoAndLeave();
			return true;
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.edit_container:
			InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			inputMethodManager.toggleSoftInputFromWindow(
					findViewById(R.id.edit_container)
							.getApplicationWindowToken(),
					InputMethodManager.SHOW_FORCED, 0);
			break;
		default:
			break;
		}
	}

	private void share() {
		Intent shareIntent = new Intent(Intent.ACTION_SEND);
		shareIntent.setType("text/plain");
		shareIntent.putExtra(android.content.Intent.EXTRA_TITLE,
				getText(R.string.share_title));
		shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
				mContentEditText.getText());

		startActivity(Intent.createChooser(shareIntent,
				getText(R.string.share_via)));
	}

	private boolean clickEnter() {
		int currentPosition = mContentEditText.getSelectionStart();
		int newPosition = currentPosition;
		String currentText = mContentEditText.getText().toString();
		StringBuffer contentBuffer = new StringBuffer(currentText);
		int maxEnd = contentBuffer.length();
		int before3 = ((currentPosition - mBullet.length()) < 0) ? 0
				: (currentPosition - mBullet.length());
		int start = currentText.lastIndexOf(mNewLine, currentPosition - 1) + 1;
		start = (start == -1) ? 0 : start;
		int end = ((start + mBullet.length()) > maxEnd) ? maxEnd
				: (start + mBullet.length());

		if (contentBuffer.substring(start, end).equals(mBullet)) {
			if (maxEnd == end) {
				contentBuffer.replace(start, end, "\n");
				mContentEditText.setText(contentBuffer);
				mContentEditText.setSelection(contentBuffer.length());
				return true;
			} else if (contentBuffer.substring(before3, currentPosition)
					.equals(mBullet)) {
				contentBuffer.replace(start, end, "");
				newPosition = currentPosition - (end - start) + 1;
				mContentEditText.setText(contentBuffer);
				mContentEditText.setSelection(newPosition);
			} else {
				contentBuffer.insert(currentPosition, mNewLine + mBullet);
				mContentEditText.setText(contentBuffer);
				newPosition = ((currentPosition + mBullet.length() + mNewLine
						.length()) > contentBuffer.length()) ? contentBuffer
						.length()
						: (currentPosition + mBullet.length() + mNewLine
								.length());
				mContentEditText.setSelection(newPosition);
			}
			return true;
		}
		return false;

	}

	private void clickList() {
		int currentPosition = mContentEditText.getSelectionStart();
		int newPosition = currentPosition;
		String currentText = mContentEditText.getText().toString();
		StringBuffer contentBuffer = new StringBuffer(currentText);
		int maxEnd = contentBuffer.length();
		int start = currentText.lastIndexOf(mNewLine, currentPosition - 1) + 1;
		int end = ((start + mBullet.length()) > maxEnd) ? maxEnd
				: (start + mBullet.length());
		if (contentBuffer.substring(start, end).equals(mBullet)) {
			contentBuffer.replace(start, start + mBullet.length(), "");
			newPosition -= mBullet.length();
			newPosition = (newPosition < start) ? start : newPosition;
			newPosition = newPosition < 0 ? 0 : newPosition;
		} else {
			contentBuffer.insert(start, mBullet);
			if (currentPosition < currentPosition + mBullet.length()) {
				newPosition = currentPosition + mBullet.length();
			} else {
				newPosition += mBullet.length();
			}
		}
		mContentEditText.setText(contentBuffer);
		mContentEditText.setSelection(newPosition);
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {

		if (event.getAction() != KeyEvent.KEYCODE_BACK) {
			mTextChanged = true;
		}

		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& keyCode == KeyEvent.KEYCODE_ENTER) {
			return clickEnter();
		}
		return false;
	}

	private void saveMemo(Boolean toLeave) {
		if (mCreateNew
				&& mContentEditText.getText().toString().trim().length() == 0) {
			return;
		}

		if (mLastSaveContent == null) {
			mLastSaveContent = new String(mContentEditText.getText().toString());
		} else {
			if (mLastSaveContent.equals(mContentEditText.getText().toString())) {
				return;
			}
		}
		memo.setContent(Html.toHtml(mContentEditText.getText()));
		memo.setCursorPosition(mContentEditText.getSelectionStart());
		ContentValues values = memo.toContentValues();
		values.put(MemoDB.SYNCSTATUS, Memo.NEED_SYNC_UP);
		values.put(MemoDB.UPDATEDTIME, new Date().getTime());
		if (mCreateNew) {
			mCreateNew = false;
			Uri retUri = getContentResolver().insert(MemoProvider.MEMO_URI,
					values);
			memo.setId(Integer.valueOf(retUri.getLastPathSegment()));
		} else {
			if (mContentEditText.getText().toString().trim().length() == 0) {
				getContentResolver().delete(
						ContentUris.withAppendedId(MemoProvider.MEMO_URI,
								memo.getId()), null, null);
				mCreateNew = true;
			} else {
				getContentResolver().update(
						ContentUris.withAppendedId(MemoProvider.MEMO_URI,
								memo.getId()), values, null, null);
			}
		}
		if (toLeave && mTextChanged) {
			mEvernote.sync(true, false, null);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		mTimer.cancel();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		mTimer = new Timer();
		mTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				saveMemo(false);
			}
		}, 5000, 10000);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.memo, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			saveMemoAndLeave();
			break;
		case R.id.li:
			clickList();
			break;
		case R.id.delete:
			AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			builder.setMessage(R.string.give_up_edit)
					.setTitle(R.string.give_up_title)
					.setPositiveButton(R.string.give_up_sure,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									deleteAndLeave();
									MobclickAgent.onEvent(mContext,
											"delete_memo");
								}
							}).setNegativeButton(R.string.give_up_cancel, null)
					.create().show();
			break;
		case R.id.share_to:
			share();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void saveMemoAndLeave() {
		saveMemo(true);
		int count = PreferenceManager.getDefaultSharedPreferences(mContext)
				.getInt(sEditCount, 0);
		if (count < 5) {
			count++;
			PreferenceManager.getDefaultSharedPreferences(mContext).edit()
					.putInt(sEditCount, count).commit();
		}
		mEvernote.sync(true, false, null);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		finish();
		overridePendingTransition(R.anim.out_push_up, R.anim.out_push_down);
	}

	private void deleteAndLeave() {
		if (memo.getId() != 0) {
			getContentResolver().delete(
					ContentUris.withAppendedId(MemoProvider.MEMO_URI,
							memo.getId()), null, null);
			mEvernote.sync(true, false, null);
		}
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		finish();
		overridePendingTransition(R.anim.out_push_up, R.anim.out_push_down);
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			findViewById(R.id.more).performClick();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}

}


text:
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Automation;
using System.Collections;
using System.Drawing;
using System.CodeDom;
using System.Threading;
using System.Diagnostics;

namespace Microsoft.Test.UIAutomation.Core
{
    using UIVerifyLogger = Microsoft.Test.UIAutomation.Logging.UIVerifyLogger;
	using InternalHelper;

    /// -----------------------------------------------------------------------
    ///
    /// -----------------------------------------------------------------------
    public class TestMenu : IDisposable
    {
        /// -------------------------------------------------------------------
        ///
        /// -------------------------------------------------------------------
        AutomationElement _element;

        /// -------------------------------------------------------------------
        /// Used for debuging
        /// -------------------------------------------------------------------
        string _name;

        /// -------------------------------------------------------------------
        ///
        /// -------------------------------------------------------------------
        const int TIMEWAIT = 1;

        /// -------------------------------------------------------------------
        ///
        /// -------------------------------------------------------------------
        const int MAXWAIT = 5000;

        /// -------------------------------------------------------------------
        ///
        /// -------------------------------------------------------------------
        private ManualResetEvent _ev = new ManualResetEvent(false);

        /// -------------------------------------------------------------------
        ///
        /// -------------------------------------------------------------------
        ExpandCollapseState _desiredState;

        /// -------------------------------------------------------------------
        ///
        /// AutomationElement for the menu associated with this object
        ///
        /// -------------------------------------------------------------------
        public AutomationElement AutomationElement
        {
            get
            {
                return _element;
            }
        }

        /// -------------------------------------------------------------------
        ///
        /// Constructor for the menu object
        ///
        /// -------------------------------------------------------------------
        public TestMenu(AutomationElement element)
        {
            if (element == null)
                throw new ArgumentException();

            _element = element;
            _name = _element.Current.Name;
        }

        #region IDispose

        /// -------------------------------------------------------------------
        ///
        ///
        /// -------------------------------------------------------------------
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// -------------------------------------------------------------------
        ///
        ///
        /// -------------------------------------------------------------------
        public void Dispose(bool disposing)
        {
            if (disposing)
            {
                //_ev.Dispose(); PreSharp says we need this, but it's private
            }
        }

        #endregion IDispose

        /// -------------------------------------------------------------------
        ///
        /// Expand the menu object
        ///
        /// -------------------------------------------------------------------
        public TestMenu Expand()
        {
            expandCollapseMenu(ExpandCollapseState.Expanded);
            return this;
        }

        /// -------------------------------------------------------------------
        ///
        /// Collapse the menu object
        ///
        /// -------------------------------------------------------------------
        public TestMenu Collapse()
        {
            expandCollapseMenu(ExpandCollapseState.Collapsed);
            return this;
        }

        /// -------------------------------------------------------------------
        ///
        /// Return the sub menu for this menu that can be identified by
        /// using FindFirst(TreeScope.Descendants, new PropertyCondition(property, indentifer));
        ///
        /// -------------------------------------------------------------------
        public TestMenu SubMenu(string indentifer, AutomationProperty property)
        {
            PropertyCondition pc = new PropertyCondition(property, indentifer);
            AutomationElement element = _element.FindFirst(TreeScope.Descendants, pc);
            return new TestMenu(element);
        }

        /// -------------------------------------------------------------------
        ///
        /// Get the first child menu using ControlViewWalker
        ///
        /// -------------------------------------------------------------------
        public TestMenu GetFirstSubMenu()
        {
            AutomationElement element = TreeWalker.ControlViewWalker.GetFirstChild(_element);

            UIVerifyLogger.LogComment(Library.GetUISpyLook(_element) + "'s ControlViewWalker.GetFirstChild = " + Library.GetUISpyLook(element));
            return new TestMenu(element);
        }

        /// -------------------------------------------------------------------
        ///
        /// Get the next sibling menu using ControlViewWalker
        ///
        /// -------------------------------------------------------------------
        public TestMenu GetNextSiblingMenu()
        {
            AutomationElement element = TreeWalker.ControlViewWalker.GetNextSibling(_element);
            UIVerifyLogger.LogComment(_element.Current.Name + "'s ControlViewWalker.GetNextSibling = " + element.Current.Name);
            return new TestMenu(element);
        }

        /// -------------------------------------------------------------------
        ///
        /// Returns true if the menu's IsExpandCollapsePatternAvailableProperty is true, else false
        ///
        /// -------------------------------------------------------------------
        public bool Expandable
        {
            get
            {
                return (bool)this.AutomationElement.GetCurrentPropertyValue(AutomationElement.IsExpandCollapsePatternAvailableProperty);
            }
        }

        /// -------------------------------------------------------------------
        ///
        /// Invoke the menu
        ///
        /// -------------------------------------------------------------------
        public bool Invoke()
        {
            throw new NotImplementedException();
        }

        /// ---------------------------------------------------------------
        ///
        /// Will call the approprate ExpandCollapse state to happen
        ///
        /// ---------------------------------------------------------------
        void expandCollapseMenu(ExpandCollapseState desiredState)
        {
            ExpandCollapsePattern ecp = this.AutomationElement.GetCurrentPattern(ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;

            _desiredState = desiredState;

            if (ecp == null)
                throw new InvalidOperationException("The element does not support ExpandCallapsePattern");

            _ev.Reset();

            Automation.AddAutomationPropertyChangedEventHandler(
                _element,
                TreeScope.Element,
                new AutomationPropertyChangedEventHandler(ExpandCollapseEventHandler),
                new AutomationProperty[] { ExpandCollapsePattern.ExpandCollapseStateProperty });

            // Cause the state to happen
            switch (desiredState)
            {
                case ExpandCollapseState.Collapsed:
                    ecp.Collapse();
                    break;

                case ExpandCollapseState.Expanded:
                    /* changing to new flexible logging */
                    //Logger.LogComment("Expanding " + _element.Current.Name);
                    UIVerifyLogger.LogComment("Expanding " + _element.Current.Name);

                    // There can be times when there is already another menu opened and
                    // we throw an expection, which will dismiss it, do it again.
                    try
                    {
                        ecp.Expand();
                    }
                    catch (Exception exception)
                    {
						if (Library.IsCriticalException(exception))
                            throw;

                        ecp.Expand();
                    }
                    break;

                case ExpandCollapseState.LeafNode:
                    throw new NotImplementedException();

                case ExpandCollapseState.PartiallyExpanded:
                    throw new NotImplementedException();

                default:
                    throw new Exception("Have not implemented case for " + desiredState);

            }

            _ev.WaitOne(10000, false);

            while (ecp.Current.ExpandCollapseState != desiredState)
            {
                throw new Exception("ExpandCollapsePattern.ExpandCollapseStateProperty != " + desiredState.ToString());
            }
        }

        /// -------------------------------------------------------------------
        ///
        /// Event handler
        ///
        /// -------------------------------------------------------------------
        private void ExpandCollapseEventHandler(object src, AutomationPropertyChangedEventArgs arguments)
        {
            if (Automation.Compare((AutomationElement)src, _element))
            {
                if (arguments.Property == ExpandCollapsePattern.ExpandCollapseStateProperty)
                    if (_desiredState == (ExpandCollapseState)arguments.NewValue)
                        _ev.Set();

            }

        }
    }
}


text:
var fs = require('fs');
var Path = require('path');
var replacestream = require('replacestream');
var glob = require("glob");
var async = require("async");

module.exports = function(params, cb){
  var regex = params.regex;
  var replacement = params.replacement;
  var path = params.path;
  glob("*/**", {
    cwd: path,
    dot: true
  }, function(err, files){
    if(err) return cb(err);
    async.each(files, function(file, cb){
      if (!file) return cb();
      file = Path.join(path, file);
      fs.stat(file, function(err, stat){
        if(err) return cb(err);
        if(!stat.isFile()) return cb();
        var stream = fs.createReadStream(file);
        stream.pipe(replacestream(regex, replacement, {regExpOptions: 'gm'})).pipe(fs.createWriteStream(file + '.next', {mode: stat.mode}));
        stream.on('end', function(){
          fs.unlink(file, function(err){
            if(err) return cb(err);
            fs.rename(file + '.next', file, cb);
          });
        }).on('error', function(err){
          return cb(err);
        });
      });
    }, cb);
  });
};


text:
CREATE TABLE guess_country_code (
    cc      text not null,
    name    text not null
);
ALTER TABLE guess_country_code ADD CONSTRAINT guess_country_code_name_pkey PRIMARY KEY (name);
CREATE INDEX guess_country_code_cc_index ON guess_country_code (cc);

CREATE OR REPLACE FUNCTION guess_country_code(a_name text) RETURNS text AS $$
    SELECT cc FROM guess_country_code WHERE name=lower($1 COLLATE "ru_RU.UTF-8");
$$ LANGUAGE sql IMMUTABLE STRICT;


text:
require 'spec_helper'

def brew_prefix
   command('brew --prefix | tr -d "\n"').stdout
end

describe package('dnscrypt-proxy') do
  it { should be_installed }
end

describe command('brew services list') do
  its(:exit_status) { should eq 0 }
  its(:stdout) { should include('dnscrypt-proxy started') }
end

describe file("#{brew_prefix}/etc/dnscrypt-proxy.toml") do
  it { should be_file }
  its(:content) { should match /blacklist_file(\s)+(.*)dnscrypt-proxy-blacklist.txt/ }
  its(:content) { should match /listen_addresses = \['127.0.0.1:53'\]/ }
end

describe command('dig wikipedia.org @127.0.0.1') do
  its(:stdout) { should match /^wikipedia.org.(\s)+(\d)+(\s)+IN(\s)+A.*$/ }
end


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*=============================================================
**
** Source:  virtualalloc.c
**
** Purpose: Negative test the VirtualAlloc API.
**          Call VirtualAlloc with MEM_COMMIT allocation type
**          and PAGE_READWRITE access protection

**
**============================================================*/
#include <palsuite.h>

int __cdecl main(int argc, char *argv[])
{
    int err;
    LPVOID lpVirtualAddress;

    //Initialize the PAL environment
    err = PAL_Initialize(argc, argv);
    if(0 != err)
    {
        ExitProcess(FAIL);
    }

    //Allocate the physical storage in memory or in the paging file on disk
    lpVirtualAddress = VirtualAlloc(NULL,//system determine where to allocate the region
            (SIZE_T)(2147483647000000), //specify the size to be int32.maxvalue mega bytes
            MEM_COMMIT,      //allocation type
            PAGE_READWRITE);  //access protection
    if(NULL != lpVirtualAddress)
    {
        Fail("\nWelcome to the Future, where Unlimited Memory is Available, disregard this test!\n");
    }

    PAL_Terminate();
    return PASS;
}


text:
.. (c) 2012-2014 Michal Kalewski  <mkalewski at cs.put.poznan.pl>
   This file is a part of the Simple Network Simulator (sim2net) project.  USE,
   MODIFICATION, COPYING AND DISTRIBUTION OF THIS SOFTWARE IS SUBJECT TO THE
   TERMS AND CONDITIONS OF THE MIT LICENSE.  YOU SHOULD HAVE RECEIVED A COPY OF
   THE MIT LICENSE ALONG WITH THIS SOFTWARE; IF NOT, YOU CAN DOWNLOAD A COPY
   FROM HTTP://WWW.OPENSOURCE.ORG/.

.. _sim2net-code-documentation-utility:

Package :mod:`sim2net.utility`
==============================
.. automodule:: sim2net.utility
    :synopsis: This package contains miscellaneous utility modules and classes.
.. contents:: Package modules:
    :local:

Module :mod:`sim2net.utility.logger`
------------------------------------
.. automodule:: sim2net.utility.logger
    :members:
    :private-members:
    :show-inheritance:
    :synopsis: This module provides functions which implement an event logging
               system.

Module :mod:`sim2net.utility.randomness`
----------------------------------------
.. automodule:: sim2net.utility.randomness
    :members:
    :private-members:
    :show-inheritance:
    :synopsis: This module provides a pseudo-random number generator.

Module :mod:`sim2net.utility.validation`
----------------------------------------
.. automodule:: sim2net.utility.validation
    :members:
    :private-members:
    :show-inheritance:
    :synopsis: This module provides a collection of source code validation
               functions.


text:
/*
 * AtomModule.java
 *
 * Created on June 14, 2006, 11:06 PM
 *
 * (C) R. Alexander Milowski alex@milowski.com
 */

package org.exist.atom;

import java.io.IOException;
import java.net.URL;

import org.exist.EXistException;
import org.exist.http.BadRequestException;
import org.exist.http.NotFoundException;
import org.exist.security.PermissionDeniedException;
import org.exist.storage.DBBroker;

/**
 *
 * @author R. Alexander Milowski
 */
public interface AtomModule {
   public interface Context {
      String getDefaultCharset();
      String getParameter(String name);
      String getContextPath();
      URL getContextURL();
      String getModuleLoadPath();
   }
   void init(Context context) throws EXistException;
   void process(DBBroker broker,IncomingMessage message,OutgoingMessage response)
      throws BadRequestException,PermissionDeniedException,NotFoundException,EXistException,IOException;
}


text:
package pointer

import (
	"golang.org/x/tools/go/types"
)

type constraint interface {
	// For a complex constraint, returns the nodeid of the pointer
	// to which it is attached.   For addr and copy, returns dst.
	ptr() nodeid

	// renumber replaces each nodeid n in the constraint by mapping[n].
	renumber(mapping []nodeid)

	// presolve is a hook for constraint-specific behaviour during
	// pre-solver optimization.  Typical implementations mark as
	// indirect the set of nodes to which the solver will add copy
	// edges or PTS labels.
	presolve(h *hvn)

	// solve is called for complex constraints when the pts for
	// the node to which they are attached has changed.
	solve(a *analysis, delta *nodeset)

	String() string
}

// dst = &src
// pts(dst) ⊇ {src}
// A base constraint used to initialize the solver's pt sets
type addrConstraint struct {
	dst nodeid // (ptr)
	src nodeid
}

func (c *addrConstraint) ptr() nodeid { return c.dst }
func (c *addrConstraint) renumber(mapping []nodeid) {
	c.dst = mapping[c.dst]
	c.src = mapping[c.src]
}

// dst = src
// A simple constraint represented directly as a copyTo graph edge.
type copyConstraint struct {
	dst nodeid // (ptr)
	src nodeid
}

func (c *copyConstraint) ptr() nodeid { return c.dst }
func (c *copyConstraint) renumber(mapping []nodeid) {
	c.dst = mapping[c.dst]
	c.src = mapping[c.src]
}

// dst = src[offset]
// A complex constraint attached to src (the pointer)
type loadConstraint struct {
	offset uint32
	dst    nodeid
	src    nodeid // (ptr)
}

func (c *loadConstraint) ptr() nodeid { return c.src }
func (c *loadConstraint) renumber(mapping []nodeid) {
	c.dst = mapping[c.dst]
	c.src = mapping[c.src]
}

// dst[offset] = src
// A complex constraint attached to dst (the pointer)
type storeConstraint struct {
	offset uint32
	dst    nodeid // (ptr)
	src    nodeid
}

func (c *storeConstraint) ptr() nodeid { return c.dst }
func (c *storeConstraint) renumber(mapping []nodeid) {
	c.dst = mapping[c.dst]
	c.src = mapping[c.src]
}

// dst = &src.f  or  dst = &src[0]
// A complex constraint attached to dst (the pointer)
type offsetAddrConstraint struct {
	offset uint32
	dst    nodeid
	src    nodeid // (ptr)
}

func (c *offsetAddrConstraint) ptr() nodeid { return c.src }
func (c *offsetAddrConstraint) renumber(mapping []nodeid) {
	c.dst = mapping[c.dst]
	c.src = mapping[c.src]
}

// dst = src.(typ)  where typ is an interface
// A complex constraint attached to src (the interface).
// No representation change: pts(dst) and pts(src) contains tagged objects.
type typeFilterConstraint struct {
	typ types.Type // an interface type
	dst nodeid
	src nodeid // (ptr)
}

func (c *typeFilterConstraint) ptr() nodeid { return c.src }
func (c *typeFilterConstraint) renumber(mapping []nodeid) {
	c.dst = mapping[c.dst]
	c.src = mapping[c.src]
}

// dst = src.(typ)  where typ is a concrete type
// A complex constraint attached to src (the interface).
//
// If exact, only tagged objects identical to typ are untagged.
// If !exact, tagged objects assignable to typ are untagged too.
// The latter is needed for various reflect operators, e.g. Send.
//
// This entails a representation change:
// pts(src) contains tagged objects,
// pts(dst) contains their payloads.
type untagConstraint struct {
	typ   types.Type // a concrete type
	dst   nodeid
	src   nodeid // (ptr)
	exact bool
}

func (c *untagConstraint) ptr() nodeid { return c.src }
func (c *untagConstraint) renumber(mapping []nodeid) {
	c.dst = mapping[c.dst]
	c.src = mapping[c.src]
}

// src.method(params...)
// A complex constraint attached to iface.
type invokeConstraint struct {
	method *types.Func // the abstract method
	iface  nodeid      // (ptr) the interface
	params nodeid      // the start of the identity/params/results block
}

func (c *invokeConstraint) ptr() nodeid { return c.iface }
func (c *invokeConstraint) renumber(mapping []nodeid) {
	c.iface = mapping[c.iface]
	c.params = mapping[c.params]
}


text:
namespace bytecode {
faststack::faststack()
{
		faststack::index = 0;
		faststack::size = faststack::initialsize;
		faststack::contents = new stackvalue[faststack::initialsize];
}
faststack::~faststack(){
		if (faststack::index != 0)
				delete [] faststack::contents;
}
}


text:
using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;

namespace UnityEditor.ShaderGraph
{
    enum ExponentialBase
    {
        BaseE,
        Base2
    };

    [Title("Math", "Advanced", "Exponential")]
    class ExponentialNode : CodeFunctionNode
    {
        public ExponentialNode()
        {
            name = "Exponential";
        }

        [SerializeField]
        private ExponentialBase m_ExponentialBase = ExponentialBase.BaseE;

        [EnumControl("Base")]
        public ExponentialBase exponentialBase
        {
            get { return m_ExponentialBase; }
            set
            {
                if (m_ExponentialBase == value)
                    return;

                m_ExponentialBase = value;
                Dirty(ModificationScope.Graph);
            }
        }

        protected override MethodInfo GetFunctionToConvert()
        {
            switch (m_ExponentialBase)
            {
                case ExponentialBase.Base2:
                    return GetType().GetMethod("Unity_Exponential2", BindingFlags.Static | BindingFlags.NonPublic);
                default:
                    return GetType().GetMethod("Unity_Exponential", BindingFlags.Static | BindingFlags.NonPublic);
            }
        }

        static string Unity_Exponential(
            [Slot(0, Binding.None)] DynamicDimensionVector In,
            [Slot(1, Binding.None)] out DynamicDimensionVector Out)
        {
            return
                @"
{
    Out = exp(In);
}
";
        }

        static string Unity_Exponential2(
            [Slot(0, Binding.None)] DynamicDimensionVector In,
            [Slot(1, Binding.None)] out DynamicDimensionVector Out)
        {
            return
                @"
{
    Out = exp2(In);
}
";
        }
    }
}


text:
namespace Rotterdam.Data.Sql.EntityFramework.Static
{
    using System;
    using System.Collections.Generic;

    public partial class ManagedEntity
    {
        public ManagedEntity()
        {
            this.DataspaceReferences = new HashSet<DataspaceReference>();
        }

        public System.Guid ManagedEntityId { get; set; }
        public System.Guid ManagedTypeId { get; set; }
        public string Name { get; set; }
        public bool IsDeleted { get; set; }
        public System.DateTime DateCreated { get; set; }
        public System.DateTime DateModified { get; set; }

        public virtual ICollection<DataspaceReference> DataspaceReferences { get; set; }
        public virtual ManagedType ManagedType { get; set; }
        public virtual ManagedTreeEntity ManagedTreeEntity { get; set; }
    }
}


text:
<component name="ProjectDictionaryState">
  <dictionary name="np74420" />
</component>


text:
import React from 'react';

export default class ServiceContainer extends React.Component {

  handleClick() {
    this.props.onClick(this.props.index);
  }

  componentDidMount() {
      require('./ServicesPage.scss');
  }

  render () {
    return (
      this.props.isActive
      ?
{this.props.children}

      :
{this.props.children}

    );
  }
}


text:
import appendTo from './appendTo';
import insertBefore from './insertBefore';
import $ from './dollr';

export default function wrap(element, ufo) {
  // TODO enable by tagName
  // TODO enable possibility of multilevel wrap. Such as
  ufo = (ufo instanceof Element) ? ufo.cloneNode() : $(ufo);

  insertBefore(ufo, element);

  appendTo(element, ufo);
}


text: NSLocalizedString(@"<#Message#>", <#Comment#>)


text:
package com.redkite.plantcare.service.impl;

import com.redkite.plantcare.PlantCareException;
import com.redkite.plantcare.common.dto.ItemList;
import com.redkite.plantcare.common.dto.PasswordUpdateDto;
import com.redkite.plantcare.common.dto.UserRequest;
import com.redkite.plantcare.common.dto.UserResponse;
import com.redkite.plantcare.controllers.filters.UserFilter;
import com.redkite.plantcare.convertors.UserConverter;
import com.redkite.plantcare.dao.RoleDao;
import com.redkite.plantcare.dao.UserDao;
import com.redkite.plantcare.model.Plant;
import com.redkite.plantcare.model.Role;
import com.redkite.plantcare.model.Sensor;
import com.redkite.plantcare.model.User;
import com.redkite.plantcare.service.DataCollectionService;
import com.redkite.plantcare.service.SensorService;
import com.redkite.plantcare.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import java.lang.reflect.Array;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;

@Service
public class UserServiceImpl implements UserService {

  private static final String REGULAR_USER_ROLE = "regularUser";
  private static final String ADMIN_ROLE = "admin";

  // @Autowired
  private PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

  @Autowired
  private UserDao userDao;

  @Autowired
  private RoleDao roleDao;

  @Autowired
  private UserConverter userConverter;

  @Autowired
  private DataCollectionService dataCollectionService;

  @Autowired
  @Qualifier("transactionManager")
  private PlatformTransactionManager txManager;

  @Value("${spring.jpa.hibernate.ddl-auto}")
  private String createDefaults;

  //TODO move defaults creation to separate SQL script

  /**
   * Create default admin in database add two roles -- regularUser and admin.
   */
  @PostConstruct
  public void init() {
    if (!createDefaults.equals("create-drop")) {
      return;
    }

    TransactionTemplate tmpl = new TransactionTemplate(txManager);
    tmpl.execute(new TransactionCallbackWithoutResult() {
      @Override
      protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
        Role regularUser = new Role();
        regularUser.setName(REGULAR_USER_ROLE);
        regularUser.setLimitOfPlants(10);
        regularUser.setLimitOfPrecessingData(1000);
        roleDao.save(regularUser);

        Role adminUser = new Role();
        adminUser.setName(ADMIN_ROLE);
        adminUser.setLimitOfPlants(-1);
        adminUser.setLimitOfPrecessingData(-1);
        roleDao.save(adminUser);

        UserRequest user = new UserRequest();
        user.setEmail("admin@gmail.com");
        user.setPassword("admin123");
        createUser(user, ADMIN_ROLE);
      }
    });
  }

  @Override
  @Transactional(isolation = Isolation.REPEATABLE_READ)
  public UserResponse createUser(UserRequest userRequest) {
    UserResponse userResponse = userConverter.toDto(createUser(userRequest, REGULAR_USER_ROLE));
    userResponse.setEmail(null);
    userResponse.setFirstName(null);
    userResponse.setLastName(null);
    userResponse.setRoles(null);
    return userResponse;
  }

  private User createUser(UserRequest userRequest, String roleName) {
    if (userDao.existsByEmail(userRequest.getEmail())) {
      throw new PlantCareException("User with email [" + userRequest.getEmail() + "] already exists", HttpStatus.CONFLICT);
    }
    User user = userConverter.toModel(userRequest);
    user.setCreationDate(LocalDateTime.now());
    user.setRole(roleDao.findByName(roleName));
    return userDao.save(user);
  }

  @Override
  @Transactional(readOnly = true)
  public ItemList<UserResponse> findUsers(UserFilter filter) {
    Page<User> users = userDao.findUserByFilter(filter.getEmail(), filter);
    List<UserResponse> userResponses = userConverter.toDtoList(users.getContent());
    return new ItemList<>(userResponses, users.getTotalElements());
  }

  @Override
  public UserResponse getUserByEmail(String email) {
    checkExistence(email);
    return userConverter.toDto(userDao.findByEmail(email));
  }

  @Override
  @Transactional(readOnly = true)
  public UserResponse getUser(Long userId) {
    checkExistence(userId);
    return userConverter.toDto(userDao.getOne(userId));
  }

  @Override
  @Transactional(readOnly = true)
  public User getFullUser(Long userId) {
    checkExistence(userId);
    return userDao.getOne(userId);
  }

  @Override
  @Transactional(isolation = Isolation.REPEATABLE_READ)
  public void editUser(Long userId, UserRequest userRequest) {
    checkExistence(userId);
    User user = userDao.getOne(userId);
    user.merge(userRequest);
  }

  @Override
  @Transactional(isolation = Isolation.REPEATABLE_READ)
  public void deleteUser(Long userId) {
    checkExistence(userId);
    User user = userDao.getOne(userId);
    Set<Plant> plants = user.getPlants();
    for (Plant plant : plants) {
      dataCollectionService.deleteDataByPlantId(plant.getId());
    }
    userDao.delete(userId);
  }

  @Override
  @Transactional(isolation = Isolation.REPEATABLE_READ)
  public void changePassword(Long userId, PasswordUpdateDto passwordUpdateDto) {
    checkExistence(userId);
    User user = userDao.getOne(userId);
    if (!passwordEncoder.matches(passwordUpdateDto.getOldPassword(), user.getPasswordHash())) {
      throw new PlantCareException("Password mismatch", HttpStatus.FORBIDDEN);
    }
    user.setPasswordHash(passwordEncoder.encode(passwordUpdateDto.getNewPassword()));
  }

  @Override
  public boolean checkPasswordMatching(String email, String password) {
    User user = userDao.findByEmail(email);
    return passwordEncoder.matches(password, user.getPasswordHash());
  }

  private void checkExistence(Long userId) {
    if (!userDao.exists(userId)) {
      throw new PlantCareException("User with id [" + userId + "] does not exist", HttpStatus.NOT_FOUND);
    }
  }

  private void checkExistence(String email) {
    if (!userDao.existsByEmail(email)) {
      throw new PlantCareException("User with email [" + email + "] does not exist", HttpStatus.NOT_FOUND);
    }
  }

}