text:
namespace Combat_Module
{
    namespace Impact_Module
    {
        typedef class StdImpact039_T : public ImpactLogic_T
        {
            public:
                enum
                {
                    ID = STD_IMPACT_039,
                };
                class OwnImpactParamIndex_T
                {
                    public:
                        enum
                        {
                        };
                };
                class ImpactDataDescriptorIndex_T
                {
                    public:
                        enum
                        {
                            IDX_CRITICAL_REFIX = 0,
                            IDX_RAGE_REGENERATE_REFIX,
                        };
                };
                StdImpact039_T() {};
                ~StdImpact039_T() {};
                BOOL IsOverTimed(VOID) const {return TRUE;};
                BOOL IsIntervaled(VOID) const {return FALSE;};

                INT GetCriticalRefix(OWN_IMPACT const& rImp) const
                {
                    return Impact_GetImpactDataDescriptorValueByIndex(rImp.GetDataIndex(), ImpactDataDescriptorIndex_T::IDX_CRITICAL_REFIX);
                };
                INT GetRageRegenerateRefix(OWN_IMPACT const& rImp) const
                {
                    return Impact_GetImpactDataDescriptorValueByIndex(rImp.GetDataIndex(), ImpactDataDescriptorIndex_T::IDX_RAGE_REGENERATE_REFIX);
                };
            public: //message handler
                VOID RefixRageRegeneration(OWN_IMPACT const& rImp, INT& rRageRegeneration) const;
                VOID MarkModifiedAttrDirty(OWN_IMPACT & rImp, Obj_Character & rMe) const;
                BOOL GetIntAttrRefix(OWN_IMPACT & rImp, Obj_Character& rMe, CharIntAttrRefixs_T::Index_T nIdx, INT & rIntAttrRefix) const;
            protected:
            private:
        } SOT_ShaoLin007_T;
    };
};
#endif //STDIMPACT039_H


text:
<?php

/**
 * Autoloads DataTable classes
 *
 * @package DataTable
 * @author	Marc Roulias <marc@lampjunkie.com>
 */
class DataTable_Autoloader
{
    /**
     * Registers this as an SPL autoloader.
     */
    static public function register()
    {
        ini_set('unserialize_callback_func', 'spl_autoload_call');
        spl_autoload_register(array(new self, 'autoload'));
    }

    /**
     * Handles autoloading of classes.
     *
     * @param  string  $class  A class name.
     *
     * @return boolean Returns true if the class has been loaded
     */
    static public function autoload($class)
    {
        if (0 !== strpos($class, 'DataTable')) {
            return;
        }

        if (file_exists($file = dirname(__FILE__).'/../'.str_replace('_', '/', $class).'.php')) {
            require $file;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"expvar"
	"flag"
	"github.com/tonnerre/x509keyserver"
	"log"
	"strconv"
	"strings"
	"time"
)

func main() {
	var kc *x509keyserver.X509KeyClient
	var fetch_interval, cache_prune_interval, timeout time.Duration
	var server, fetch_ids, id string
	var fetch_idlist []string
	var max_records int
	var err error

	flag.StringVar(&server, "server", "localhost:1234",
		"host:port pair of the x509 key server")
	flag.IntVar(&max_records, "max-cache-records", 4,
		"Maximum number of certificates to keep in the cache")
	flag.StringVar(&fetch_ids, "ids", "",
		"Comma-separated list of certificate IDs to fetch")
	flag.DurationVar(&fetch_interval, "fetch-interval", 0,
		"How long to wait between individual fetches (to test caching)")
	flag.DurationVar(&cache_prune_interval, "cache-prune-interval", time.Second,
		"How long to wait between two cache prunes (to test caching)")
	flag.DurationVar(&timeout, "timeout", 100*time.Millisecond,
		"How long to wait for server responses before cancelling them")
	flag.Parse()

	kc, err = x509keyserver.NewX509KeyClient(
		server, max_records, timeout, cache_prune_interval)
	if err != nil {
		log.Fatal("Unable to connect to ", server, ": ", err)
	}

	fetch_idlist = strings.Split(fetch_ids, ",")
	for _, id = range fetch_idlist {
		var index uint64
		var sz string
		index, err = strconv.ParseUint(id, 10, 64)
		if err != nil {
			log.Print("Unable to parse ", id, " as a number, skipping.")
			continue
		}
		sz = expvar.Get("x509-key-cache-size").String()
		_, err = kc.RetrieveCertificateByIndex(index)
		if err != nil {
			log.Print("Error retrieving certificate ", index, ": ", err)
		}
		log.Print("Cache size: ", sz, " -> ", expvar.Get("x509-key-cache-size").String())
		log.Print("Cache stats: hits: ", expvar.Get("x509-key-cache-hits").String(),
			", misses: ", expvar.Get("x509-key-cache-misses"))

		if fetch_interval > 0 {
			time.Sleep(fetch_interval)
		}
	}
}


text: <button id="button" class="autocompare">Set new data</button>


text:
<?php

namespace Tests\Builders\Overrides;

use Doctrine\ORM\Mapping\Builder\ClassMetadataBuilder;
use Doctrine\ORM\Mapping\ClassMetadataInfo;
use Doctrine\ORM\Mapping\DefaultNamingStrategy;
use InvalidArgumentException;
use LaravelDoctrine\Fluent\Builders\Overrides\AssociationOverride;
use LaravelDoctrine\Fluent\Builders\Overrides\AttributeOverride;
use LaravelDoctrine\Fluent\Builders\Overrides\OverrideBuilderFactory;
use PHPUnit\Framework\TestCase;
use Tests\Stubs\Entities\StubEntity;

class OverrideBuilderFactoryTest extends TestCase
{
    public function test_can_create_attribute_override()
    {
        $builder = new ClassMetadataBuilder(new ClassMetadataInfo(
            StubEntity::class
        ));

        $builder->addField('attribute', 'string');

        $override = OverrideBuilderFactory::create(
            $builder,
            new DefaultNamingStrategy(),
            'attribute',
            function ($attribute) {
                return $attribute;
            }
        );

        $this->assertInstanceOf(AttributeOverride::class, $override);
    }

    public function test_can_create_association_override()
    {
        $builder = new ClassMetadataBuilder(new ClassMetadataInfo(
            StubEntity::class
        ));

        $builder->addOwningManyToMany('owner', StubEntity::class);

        $override = OverrideBuilderFactory::create(
            $builder,
            new DefaultNamingStrategy(),
            'owner',
            function ($relation) {
                return $relation;
            }
        );

        $this->assertInstanceOf(AssociationOverride::class, $override);
    }

    public function test_can_only_create_overrides_for_existing_attributes_or_relations()
    {
        $this->expectException(InvalidArgumentException::class);
        $this->expectExceptionMessage('No attribute or association could be found for some_field');

        $builder = new ClassMetadataBuilder(new ClassMetadataInfo(
            StubEntity::class
        ));

        OverrideBuilderFactory::create(
            $builder,
            new DefaultNamingStrategy(),
            'some_field',
            function ($relation) {
                return $relation;
            }
        );
    }
}


text:
package org.seyster.seystertron;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class GainPanel extends javax.swing.JPanel
{
    String name;
    SynthGain gain;

    JSlider sliderGain;
    JSlider sliderLatency;

    int latency;  //The latency, in samples

    public GainPanel(String n, SynthGain sg)
    {
        name = n;
        gain = sg;

        latency = 4410;

        initComponents();
    }

    private void initComponents()
    {
        setBorder(new javax.swing.border.EtchedBorder());
        setLayout(new BorderLayout());

        add(new JLabel(name), BorderLayout.NORTH);

        //Set sliderGain options
        sliderGain = new JSlider(JSlider.VERTICAL);
        sliderGain.setPaintTicks(true);
        sliderGain.setToolTipText("Master Gain");
        sliderGain.setMinimum(0);
        sliderGain.setMaximum(3000);
        sliderGain.setMinorTickSpacing(1000);
        sliderGain.setMajorTickSpacing(3000);
        sliderGain.setValue(1000);
        sliderGain.addChangeListener(new GainListener(gain));
        add(sliderGain, BorderLayout.CENTER);

        add(new JLabel("Gain"), BorderLayout.SOUTH);

        add(latencyPanel(), BorderLayout.EAST);
    }

    //Returns a panel with the latency slider
    private JPanel latencyPanel()
    {
        JPanel panel = new JPanel();
        JLabel label;

        panel.setLayout(new GridLayout(4, 1));
        panel.add(new JLabel()); //Filler label

        label = new JLabel("Latency:");
        label.setVerticalTextPosition(JLabel.BOTTOM);
        label.setHorizontalAlignment(JLabel.LEFT);
        panel.add(label);

        sliderLatency = new JSlider(JSlider.HORIZONTAL);
        sliderLatency.setPreferredSize(new Dimension(
            label.getPreferredSize().width * 3 / 2,
            sliderLatency.getPreferredSize().height));
        sliderLatency.setPaintTicks(true);
        sliderLatency.setToolTipText("Latency");
        sliderLatency.setMinimum(2205);
        sliderLatency.setMaximum(8820);
        sliderLatency.setMinorTickSpacing(2205);
        sliderLatency.setMajorTickSpacing(4410);
        sliderLatency.setValue(4410);
        sliderLatency.addChangeListener(new LatencyListener(this));
        panel.add(sliderLatency);

        panel.add(new JLabel());  //Bottom filler

        return panel;
    }

    //The gain panel holds the master options, so it is responsible for
    //storing the value for master latency
    public void setLatency(int l)
    {
        if (l < 2205)
            l = 2205;

        if (l > 8820)
            l = 8820;

        latency = l;
    }

    public int getLatency()
    {
        return latency;
    }
}

class GainListener implements ChangeListener
{
    SynthGain gain;

    public GainListener(SynthGain sg)
    {
        gain = sg;
    }

    public void stateChanged(ChangeEvent e)
    {
        JSlider sliderGain = (JSlider)e.getSource();
        int gainValue = (int)sliderGain.getValue();
        gain.setGain((double)gainValue / 1000.0d);
    }
}

class LatencyListener implements ChangeListener
{
    GainPanel gainPanel;

    public LatencyListener(GainPanel gp)
    {
        gainPanel = gp;
    }

    public void stateChanged(ChangeEvent e)
    {
        JSlider sliderLatency = (JSlider)e.getSource();
        int latency = (int)sliderLatency.getValue();
        gainPanel.setLatency(latency);
    }
}


text:
package com.sequenceiq.cloudbreak.cm;

import static com.sequenceiq.cloudbreak.cluster.model.ParcelStatus.ACTIVATED;
import static com.sequenceiq.cloudbreak.cluster.model.ParcelStatus.AVAILABLE_REMOTELY;
import static com.sequenceiq.cloudbreak.cluster.model.ParcelStatus.DISTRIBUTED;
import static com.sequenceiq.cloudbreak.cluster.model.ParcelStatus.DOWNLOADED;
import static com.sequenceiq.cloudbreak.cluster.model.ParcelStatus.UNKNOWN;
import static com.sequenceiq.cloudbreak.cm.util.TestUtil.CDH;
import static com.sequenceiq.cloudbreak.cm.util.TestUtil.FLINK;
import static com.sequenceiq.cloudbreak.cm.util.TestUtil.SPARK3;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.Set;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import com.cloudera.api.swagger.ClouderaManagerResourceApi;
import com.cloudera.api.swagger.ParcelResourceApi;
import com.cloudera.api.swagger.ParcelsResourceApi;
import com.cloudera.api.swagger.client.ApiClient;
import com.cloudera.api.swagger.client.ApiException;
import com.cloudera.api.swagger.model.ApiCommand;
import com.cloudera.api.swagger.model.ApiConfigList;
import com.cloudera.api.swagger.model.ApiParcel;
import com.cloudera.api.swagger.model.ApiParcelList;
import com.sequenceiq.cloudbreak.cloud.model.ClouderaManagerProduct;
import com.sequenceiq.cloudbreak.cluster.model.ParcelInfo;
import com.sequenceiq.cloudbreak.cluster.model.ParcelStatus;
import com.sequenceiq.cloudbreak.cm.model.ParcelResource;
import com.sequenceiq.cloudbreak.cm.polling.ClouderaManagerPollingServiceProvider;
import com.sequenceiq.cloudbreak.cm.polling.PollingResultErrorHandler;
import com.sequenceiq.cloudbreak.domain.stack.Stack;
import com.sequenceiq.cloudbreak.polling.ExtendedPollingResult;
import com.sequenceiq.cloudbreak.polling.PollingResult;
import com.sequenceiq.cloudbreak.service.CloudbreakException;

@ExtendWith(MockitoExtension.class)
class ClouderaManagerParcelManagementServiceTest {

    private static final String STACK_NAME = "stack-name";

    private static final String VIEW = "summary";

    private static Stack stack;

    @InjectMocks
    private ClouderaManagerParcelManagementService underTest;

    @Mock
    private ClouderaManagerPollingServiceProvider clouderaManagerPollingServiceProvider;

    @Mock
    private PollingResultErrorHandler pollingResultErrorHandler;

    @Mock
    private ParcelsResourceApi parcelsResourceApi;

    @Mock
    private ParcelResourceApi parcelResourceApi;

    @Mock
    private ClouderaManagerResourceApi clouderaManagerResourceApi;

    @Mock
    private ApiClient apiClient;

    @BeforeAll
    static void before() {
        stack = createStack();
    }

    private static Stack createStack() {
        Stack stack = new Stack();
        stack.setName("stack-name");
        return stack;
    }

    @Test
    void testGetParcelsInStatusShouldReturnAllParcelsInTheRequiredStatus() throws ApiException {
        when(parcelsResourceApi.readParcels(STACK_NAME, VIEW)).thenReturn(new ApiParcelList()
                .addItemsItem(createApiParcel(CDH, "7.2.7", ACTIVATED.name()))
                .addItemsItem(createApiParcel(CDH, "7.2.12", DISTRIBUTED.name()))
                .addItemsItem(createApiParcel(CDH, "7.2.15", DISTRIBUTED.name()))
                .addItemsItem(createApiParcel(SPARK3, "5.4.1", DISTRIBUTED.name()))
                .addItemsItem(createApiParcel(FLINK, "1.2.2", DOWNLOADED.name())));

        Set<ParcelInfo> actual = underTest.getParcelsInStatus(parcelsResourceApi, STACK_NAME, DISTRIBUTED);

        assertEquals(3, actual.size());
        assertParcel(actual, CDH, "7.2.12", DISTRIBUTED);
        assertParcel(actual, CDH, "7.2.15", DISTRIBUTED);
        assertParcel(actual, SPARK3, "5.4.1", DISTRIBUTED);
    }

    @Test
    void testGetParcelsInStatusShouldReturnEmptySetWhenThereAreNoParcelInTheRequiredStatus() throws ApiException {
        when(parcelsResourceApi.readParcels(STACK_NAME, VIEW)).thenReturn(new ApiParcelList()
                .addItemsItem(createApiParcel(CDH, "7.2.7", ACTIVATED.name()))
                .addItemsItem(createApiParcel(CDH, "7.2.12", DISTRIBUTED.name()))
                .addItemsItem(createApiParcel(CDH, "7.2.15", DISTRIBUTED.name()))
                .addItemsItem(createApiParcel(SPARK3, "5.4.1", DISTRIBUTED.name())));

        Set<ParcelInfo> actual = underTest.getParcelsInStatus(parcelsResourceApi, STACK_NAME, DOWNLOADED);

        assertEquals(Collections.emptySet(), actual);
    }

    @Test
    void testGetParcelsInStatusShouldThrowExceptionWhenUnableToReadTheParcelsFromCm() throws ApiException {
        when(parcelsResourceApi.readParcels(STACK_NAME, VIEW)).thenThrow(new ApiException("Failed to read parcels"));
        assertThrows(ClouderaManagerOperationFailedException.class, () -> underTest.getParcelsInStatus(parcelsResourceApi, STACK_NAME, DOWNLOADED));
    }

    @Test
    void testGetAllParcelsShouldReturnAllParcelsFromCm() throws ApiException {
        when(parcelsResourceApi.readParcels(STACK_NAME, VIEW)).thenReturn(new ApiParcelList()
                .addItemsItem(createApiParcel(CDH, "7.2.7", ACTIVATED.name()))
                .addItemsItem(createApiParcel(CDH, "7.2.12", DISTRIBUTED.name()))
                .addItemsItem(createApiParcel(CDH, "7.2.15", DISTRIBUTED.name()))
                .addItemsItem(createApiParcel(SPARK3, "5.4.1", AVAILABLE_REMOTELY.name()))
                .addItemsItem(createApiParcel(FLINK, "1.2.2", DOWNLOADED.name())));

        Set<ParcelInfo> actual = underTest.getAllParcels(parcelsResourceApi, STACK_NAME);

        assertEquals(5, actual.size());
        assertParcel(actual, CDH, "7.2.7", ACTIVATED);
        assertParcel(actual, CDH, "7.2.12", DISTRIBUTED);
        assertParcel(actual, CDH, "7.2.15", DISTRIBUTED);
        assertParcel(actual, SPARK3, "5.4.1", AVAILABLE_REMOTELY);
        assertParcel(actual, FLINK, "1.2.2", DOWNLOADED);
    }

    @Test
    void testGetAllParcelsShouldReturnUnknownWhenUnknownStatus() throws ApiException {
        when(parcelsResourceApi.readParcels(STACK_NAME, VIEW)).thenReturn(new ApiParcelList()
                .addItemsItem(createApiParcel(CDH, "7.2.7", "anUnknownStatus")));

        Set<ParcelInfo> actual = underTest.getAllParcels(parcelsResourceApi, STACK_NAME);

        assertEquals(1, actual.size());
        assertParcel(actual, CDH, "7.2.7", UNKNOWN);
    }

    @Test
    void testSetParcelReposShouldSetTheRequiredParcelBaseUrlsInCm() throws ApiException {
        ClouderaManagerProduct cdhProduct = new ClouderaManagerProduct().withParcel("https://cdh.parcel");
        ClouderaManagerProduct flinkProduct = new ClouderaManagerProduct().withParcel("https://flink.parcel");
        ArgumentCaptor<ApiConfigList> apiConfigListCaptor = ArgumentCaptor.forClass(ApiConfigList.class);
        when(clouderaManagerResourceApi.updateConfig(eq("Updated configurations."), apiConfigListCaptor.capture())).thenReturn(new ApiConfigList());

        underTest.setParcelRepos(Set.of(cdhProduct, flinkProduct), clouderaManagerResourceApi);

        ApiConfigList apiConfigList = apiConfigListCaptor.getValue();
        assertTrue(apiConfigList.getItems().stream().anyMatch(apiConfig ->
                apiConfig.getName().equals("remote_parcel_repo_urls") &&
                        apiConfig.getValue().contains(cdhProduct.getParcel()) &&
                        apiConfig.getValue().contains(flinkProduct.getParcel())));
    }

    @Test
    void testRefreshParcelReposShouldCallCmApi() throws ApiException {
        ApiCommand apiCommand = new ApiCommand().id(BigDecimal.ONE);
        when(clouderaManagerResourceApi.refreshParcelRepos()).thenReturn(apiCommand);

        underTest.refreshParcelRepos(clouderaManagerResourceApi, stack, apiClient);

        verify(clouderaManagerResourceApi).refreshParcelRepos();
        verify(clouderaManagerPollingServiceProvider).startPollingCmParcelRepositoryRefresh(stack, apiClient, apiCommand.getId());
    }

    @Test
    void testDownloadParcelsShouldCallCmApiToDownloadParcels() throws CloudbreakException, ApiException {
        ClouderaManagerProduct cdhProduct = new ClouderaManagerProduct().withName(CDH).withVersion("7.2.15");
        ClouderaManagerProduct flinkProduct = new ClouderaManagerProduct().withName(FLINK).withVersion("1.2.3");
        ApiCommand cdhDownloadCommand = new ApiCommand().id(BigDecimal.ONE);
        ApiCommand flinkDownloadCommand = new ApiCommand().id(BigDecimal.TEN);
        ExtendedPollingResult pollingResult = createPollingResult();
        when(parcelResourceApi.startDownloadCommand(stack.getName(), cdhProduct.getName(), cdhProduct.getVersion())).thenReturn(cdhDownloadCommand);
        when(parcelResourceApi.startDownloadCommand(stack.getName(), flinkProduct.getName(), flinkProduct.getVersion())).thenReturn(flinkDownloadCommand);
        when(clouderaManagerPollingServiceProvider.startPollingCdpRuntimeParcelDownload(eq(stack), eq(apiClient), eq(cdhDownloadCommand.getId()),
                any(ParcelResource.class))).thenReturn(pollingResult);
        when(clouderaManagerPollingServiceProvider.startPollingCdpRuntimeParcelDownload(eq(stack), eq(apiClient), eq(flinkDownloadCommand.getId()),
                any(ParcelResource.class))).thenReturn(pollingResult);

        underTest.downloadParcels(Set.of(cdhProduct, flinkProduct), parcelResourceApi, stack, apiClient);

        verify(parcelResourceApi).startDownloadCommand(stack.getName(), cdhProduct.getName(), cdhProduct.getVersion());
        verify(parcelResourceApi).startDownloadCommand(stack.getName(), flinkProduct.getName(), flinkProduct.getVersion());
        verify(clouderaManagerPollingServiceProvider).startPollingCdpRuntimeParcelDownload(eq(stack), eq(apiClient), eq(cdhDownloadCommand.getId()),
                any(ParcelResource.class));
        verify(clouderaManagerPollingServiceProvider).startPollingCdpRuntimeParcelDownload(eq(stack), eq(apiClient), eq(flinkDownloadCommand.getId()),
                any(ParcelResource.class));
        verify(pollingResultErrorHandler, times(2)).handlePollingResult(pollingResult.getPollingResult(),
                "Cluster was terminated while waiting for CDP Runtime Parcel to be downloaded", "Timeout during the updated CDP Runtime Parcel download.");
    }

    @Test
    void testDistributeParcelsShouldCallCmApiToDistributeParcels() throws CloudbreakException, ApiException {
        ClouderaManagerProduct cdhProduct = new ClouderaManagerProduct().withName(CDH).withVersion("7.2.15");
        ClouderaManagerProduct flinkProduct = new ClouderaManagerProduct().withName(FLINK).withVersion("1.2.3");
        ApiCommand cdhDistributeCommand = new ApiCommand().id(BigDecimal.ONE);
        ApiCommand flinkDistributeCommand = new ApiCommand().id(BigDecimal.TEN);
        ExtendedPollingResult pollingResult = createPollingResult();
        when(parcelResourceApi.startDistributionCommand(stack.getName(), cdhProduct.getName(), cdhProduct.getVersion())).thenReturn(cdhDistributeCommand);
        when(parcelResourceApi.startDistributionCommand(stack.getName(), flinkProduct.getName(), flinkProduct.getVersion())).thenReturn(flinkDistributeCommand);
        when(clouderaManagerPollingServiceProvider.startPollingCdpRuntimeParcelDistribute(eq(stack), eq(apiClient), eq(cdhDistributeCommand.getId()),
                any(ParcelResource.class))).thenReturn(pollingResult);
        when(clouderaManagerPollingServiceProvider.startPollingCdpRuntimeParcelDistribute(eq(stack), eq(apiClient), eq(flinkDistributeCommand.getId()),
                any(ParcelResource.class))).thenReturn(pollingResult);

        underTest.distributeParcels(Set.of(cdhProduct, flinkProduct), parcelResourceApi, stack, apiClient);

        verify(parcelResourceApi).startDistributionCommand(stack.getName(), cdhProduct.getName(), cdhProduct.getVersion());
        verify(parcelResourceApi).startDistributionCommand(stack.getName(), flinkProduct.getName(), flinkProduct.getVersion());
        verify(clouderaManagerPollingServiceProvider).startPollingCdpRuntimeParcelDistribute(eq(stack), eq(apiClient), eq(cdhDistributeCommand.getId()),
                any(ParcelResource.class));
        verify(clouderaManagerPollingServiceProvider).startPollingCdpRuntimeParcelDistribute(eq(stack), eq(apiClient), eq(flinkDistributeCommand.getId()),
                any(ParcelResource.class));
        verify(pollingResultErrorHandler, times(2)).handlePollingResult(pollingResult.getPollingResult(),
                "Cluster was terminated while waiting for CDP Runtime Parcel to be distributed", "Timeout during the updated CDP Runtime Parcel distribution.");
    }

    @Test
    void testActivateParcelsShouldCallCmApiToActivateParcels() throws CloudbreakException, ApiException {
        ClouderaManagerProduct cdhProduct = new ClouderaManagerProduct().withName(CDH).withVersion("7.2.15");
        ClouderaManagerProduct flinkProduct = new ClouderaManagerProduct().withName(FLINK).withVersion("1.2.3");
        ApiCommand cdhActivationCommand = new ApiCommand().id(BigDecimal.ONE);
        ApiCommand flinkActivationCommand = new ApiCommand().id(BigDecimal.TEN);
        ExtendedPollingResult pollingResult = createPollingResult();
        when(parcelResourceApi.activateCommand(stack.getName(), cdhProduct.getName(), cdhProduct.getVersion())).thenReturn(cdhActivationCommand);
        when(parcelResourceApi.activateCommand(stack.getName(), flinkProduct.getName(), flinkProduct.getVersion())).thenReturn(flinkActivationCommand);
        when(clouderaManagerPollingServiceProvider.startPollingCmSingleParcelActivation(stack, apiClient, cdhActivationCommand.getId(), cdhProduct))
                .thenReturn(pollingResult);
        when(clouderaManagerPollingServiceProvider.startPollingCmSingleParcelActivation(stack, apiClient, flinkActivationCommand.getId(), flinkProduct))
                .thenReturn(pollingResult);

        underTest.activateParcels(Set.of(cdhProduct, flinkProduct), parcelResourceApi, stack, apiClient);

        verify(parcelResourceApi).activateCommand(stack.getName(), cdhProduct.getName(), cdhProduct.getVersion());
        verify(parcelResourceApi).activateCommand(stack.getName(), flinkProduct.getName(), flinkProduct.getVersion());
        verify(clouderaManagerPollingServiceProvider).startPollingCmSingleParcelActivation(stack, apiClient, cdhActivationCommand.getId(), cdhProduct);
        verify(clouderaManagerPollingServiceProvider).startPollingCmSingleParcelActivation(stack, apiClient, flinkActivationCommand.getId(), flinkProduct);
        verify(pollingResultErrorHandler, times(2)).handlePollingResult(pollingResult.getPollingResult(),
                "Cluster was terminated while waiting for CDP Runtime Parcel to be activated", "Timeout during the updated CDP Runtime Parcel activation.");
    }

    @Test
    void testCheckParcelApiAvailabilityShouldPollCmParcelApi() throws CloudbreakException {
        ExtendedPollingResult pollingResult = createPollingResult();
        when(clouderaManagerPollingServiceProvider.startPollingParcelsApiAvailable(stack, apiClient)).thenReturn(pollingResult);

        underTest.checkParcelApiAvailability(stack, apiClient);

        verify(clouderaManagerPollingServiceProvider).startPollingParcelsApiAvailable(stack, apiClient);
        verify(pollingResultErrorHandler).handlePollingResult(pollingResult.getPollingResult(),
                "Cluster was terminated while waiting for Parcels API to be available", "Timeout during waiting for CM Parcels API to be available.");
    }

    private ExtendedPollingResult createPollingResult() {
        return new ExtendedPollingResult.ExtendedPollingResultBuilder().withPollingResult(PollingResult.SUCCESS).build();
    }

    private void assertParcel(Set<ParcelInfo> actual, String name, String version, ParcelStatus status) {
        assertTrue(actual.stream().anyMatch(parcelInfo ->
                parcelInfo.getName().equals(name)
                        && parcelInfo.getVersion().equals(version)
                        && parcelInfo.getStatus().equals(status)));
    }

    private ApiParcel createApiParcel(String name, String version, String status) {
        ApiParcel apiParcel = new ApiParcel();
        apiParcel.setProduct(name);
        apiParcel.setVersion(version);
        apiParcel.setStage(status);
        return apiParcel;
    }
}


text:
namespace krono
{

OpenGLTexture::OpenGLTexture(void)
{
}

OpenGLTexture::~OpenGLTexture(void)
{
}

GLenum OpenGLTexture::gTextureFormatMapping[DataFormat::TypeCount][4] = {
	{GL_R32F, GL_RG32F, GL_RGB32F, GL_RGBA32F},
	{GL_R8, GL_RG8, GL_RGB8, GL_RGBA8},
	{GL_DEPTH_COMPONENT16, 0, 0, 0},
	{GL_DEPTH_COMPONENT24, 0, 0, 0},
	{GL_DEPTH_COMPONENT32F, 0, 0, 0},
	{GL_DEPTH24_STENCIL8, 0, 0, 0},
	{GL_DEPTH32F_STENCIL8, 0, 0, 0},
};

GLenum OpenGLTexture::GetTextureFormat(DataFormat format)
{
	return gTextureFormatMapping[format.type][format.count - 1];
}

GLenum OpenGLTexture::gTextureChannelMapping[] = {
	GL_RED,
	GL_RG,
	GL_RGB,
	GL_RGBA
};

GLenum OpenGLTexture::GetTextureChannelType(size_t channelCount)
{
	return gTextureChannelMapping[channelCount - 1];
}

}


text:
/**
 * @name spawn-rmrf (main)
 * @description `rm -rf` spawned.
 * @author Nicolas Tallefourtane <dev@nicolab.net>
 * @link https://github.com/Nicolab/node-spawn-rmrf
 * @license MIT https://github.com/Nicolab/node-spawn-rmrf/blob/master/LICENSE
 */

'use strict';

var spawn = require('spawn-handler');

/**
 * rm -rf `filePath` then `done`
 *
 * @see https://github.com/Nicolab/node-spawn-handler
 *
 * @param  {string}   filePath File path to remove (recursively).
 * @param  {function} done     Callback executed at the end.
 * @return {ChildProcess}      ChildProcess object.
 */
module.exports = function rmrf(filePath, done) {
  return spawn.handle(spawn.run('rm', ['-rf', filePath]), done, 'rmrf');
};


text:
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook

class TestCompareXLSXFiles(ExcelComparisonTest):
    """
    Test file created by XlsxWriter against a file created by Excel.

    """

    def setUp(self):
        self.maxDiff = None

        filename = 'outline01.xlsx'

        test_dir = 'xlsxwriter/test/comparison/'
        self.got_filename = test_dir + '_test_' + filename
        self.exp_filename = test_dir + 'xlsx_files/' + filename

        self.ignore_files = ['xl/calcChain.xml', '[Content_Types].xml', 'xl/_rels/workbook.xml.rels']
        self.ignore_elements = {}

    def test_create_file(self):
        """
        Test the creation of a outlines in a XlsxWriter file. These tests are
        based on the outline programs in the examples directory.
        """

        workbook = Workbook(self.got_filename)

        worksheet1 = workbook.add_worksheet('Outlined Rows')

        bold = workbook.add_format({'bold': 1})

        worksheet1.set_row(1, None, None, {'level': 2})
        worksheet1.set_row(2, None, None, {'level': 2})
        worksheet1.set_row(3, None, None, {'level': 2})
        worksheet1.set_row(4, None, None, {'level': 2})
        worksheet1.set_row(5, None, None, {'level': 1})

        worksheet1.set_row(6, None, None, {'level': 2})
        worksheet1.set_row(7, None, None, {'level': 2})
        worksheet1.set_row(8, None, None, {'level': 2})
        worksheet1.set_row(9, None, None, {'level': 2})
        worksheet1.set_row(10, None, None, {'level': 1})

        worksheet1.set_column('A:A', 20)

        worksheet1.write('A1', 'Region', bold)
        worksheet1.write('A2', 'North')
        worksheet1.write('A3', 'North')
        worksheet1.write('A4', 'North')
        worksheet1.write('A5', 'North')
        worksheet1.write('A6', 'North Total', bold)

        worksheet1.write('B1', 'Sales', bold)
        worksheet1.write('B2', 1000)
        worksheet1.write('B3', 1200)
        worksheet1.write('B4', 900)
        worksheet1.write('B5', 1200)
        worksheet1.write('B6', '=SUBTOTAL(9,B2:B5)', bold, 4300)

        worksheet1.write('A7', 'South')
        worksheet1.write('A8', 'South')
        worksheet1.write('A9', 'South')
        worksheet1.write('A10', 'South')
        worksheet1.write('A11', 'South Total', bold)

        worksheet1.write('B7', 400)
        worksheet1.write('B8', 600)
        worksheet1.write('B9', 500)
        worksheet1.write('B10', 600)
        worksheet1.write('B11', '=SUBTOTAL(9,B7:B10)', bold, 2100)

        worksheet1.write('A12', 'Grand Total', bold)
        worksheet1.write('B12', '=SUBTOTAL(9,B2:B10)', bold, 6400)

        workbook.close()

        self.assertExcelEqual()


text:
Replaces text blocks between named comments inside HTML and JavaScript files.

- - -

__NOT RELEASED YET! DO NOT USE.__

[Signup to my newsletter](http://eepurl.com/b4lTdL) to get updated about this.


text:
<?php

namespace Composer\Semver;

use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\ConstraintInterface;

/**
 * Helper class to evaluate constraint by compiling and reusing the code to evaluate
 */
class CompilingMatcher
{
    private static $compiledCheckerCache = array();
    private static $enabled;

    /**
     * @phpstan-var array<Constraint::OP_*, string>
     */
    private static $transOpInt = array(
        Constraint::OP_EQ => '==',
        Constraint::OP_LT => '<',
        Constraint::OP_LE => '<=',
        Constraint::OP_GT => '>',
        Constraint::OP_GE => '>=',
        Constraint::OP_NE => '!=',
    );

    /**
     * Evaluates the expression: $constraint match $operator $version
     *
     * @param ConstraintInterface $constraint
     * @param int                 $operator
     * @phpstan-param Constraint::OP_*  $operator
     * @param string              $version
     *
     * @return mixed
     */
    public static function match(ConstraintInterface $constraint, $operator, $version)
    {
        if (self::$enabled === null) {
            self::$enabled = !\in_array('eval', explode(',', ini_get('disable_functions')), true);
        }
        if (!self::$enabled) {
            return $constraint->matches(new Constraint(self::$transOpInt[$operator], $version));
        }

        $cacheKey = $operator.$constraint;
        if (!isset(self::$compiledCheckerCache[$cacheKey])) {
            $code = $constraint->compile($operator);
            self::$compiledCheckerCache[$cacheKey] = $function = eval('return function($v, $b){return '.$code.';};');
        } else {
            $function = self::$compiledCheckerCache[$cacheKey];
        }

        return $function($version, strpos($version, 'dev-') === 0);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--

 This file is part of the Sylius package.

 (c) Paweł Jędrzejewski

 For the full copyright and license information, please view the LICENSE
 file that was distributed with this source code.

-->

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"
>
    <services>
        <defaults public="true" />

        <service id="api_platform.swagger.action.ui" class="Sylius\Bundle\ApiBundle\ApiPlatform\Bridge\Symfony\Bundle\Action\SwaggerUiAction">
            <argument type="service" id="api_platform.metadata.resource.name_collection_factory" />
            <argument type="service" id="api_platform.metadata.resource.metadata_factory" />
            <argument type="service" id="api_platform.serializer" />
            <argument type="service" id="twig" />
            <argument type="service" id="router" />
            <argument>%api_platform.title%</argument>
            <argument>%api_platform.description%</argument>
            <argument>%api_platform.version%</argument>
            <argument>%api_platform.formats%</argument>
            <argument>%api_platform.oauth.enabled%</argument>
            <argument>%api_platform.oauth.clientId%</argument>
            <argument>%api_platform.oauth.clientSecret%</argument>
            <argument>%api_platform.oauth.type%</argument>
            <argument>%api_platform.oauth.flow%</argument>
            <argument>%api_platform.oauth.tokenUrl%</argument>
            <argument>%api_platform.oauth.authorizationUrl%</argument>
            <argument>%api_platform.oauth.scopes%</argument>
            <argument>%api_platform.show_webby%</argument>
            <argument>%api_platform.enable_swagger_ui%</argument>
            <argument>%api_platform.enable_re_doc%</argument>
            <argument>%api_platform.graphql.enabled%</argument>
            <argument>%api_platform.graphql.graphiql.enabled%</argument>
            <argument>%api_platform.graphql.graphql_playground.enabled%</argument>
            <argument>%api_platform.swagger.versions%</argument>
        </service>

        <service
            id="Sylius\Bundle\ApiBundle\Swagger\AdminAuthenticationTokenDocumentationNormalizer"
            decorates="api_platform.swagger.normalizer.documentation"
            autoconfigure="false"
            decoration-priority="20"
        >
            <argument type="service" id="Sylius\Bundle\ApiBundle\Swagger\AdminAuthenticationTokenDocumentationNormalizer.inner" />
            <argument>%sylius.security.new_api_route%</argument>
        </service>

        <service
            id="Sylius\Bundle\ApiBundle\Swagger\ShopAuthenticationTokenDocumentationNormalizer"
            decorates="api_platform.swagger.normalizer.documentation"
            autoconfigure="false"
            decoration-priority="10"
        >
            <argument type="service" id="Sylius\Bundle\ApiBundle\Swagger\ShopAuthenticationTokenDocumentationNormalizer.inner" />
            <argument>%sylius.security.new_api_route%</argument>
        </service>

        <service
            id="Sylius\Bundle\ApiBundle\Swagger\ProductDocumentationNormalizer"
            decorates="api_platform.swagger.normalizer.documentation"
            autoconfigure="false"
            decoration-priority="20"
        >
            <argument type="service" id="Sylius\Bundle\ApiBundle\Swagger\ProductDocumentationNormalizer.inner" />
        </service>

        <service
            id="Sylius\Bundle\ApiBundle\Swagger\ProductImageDocumentationNormalizer"
            decorates="api_platform.swagger.normalizer.documentation"
            autoconfigure="false"
            decoration-priority="20"
        >
            <argument type="service" id="Sylius\Bundle\ApiBundle\Swagger\ProductImageDocumentationNormalizer.inner" />
            <argument type="service" id="Sylius\Bundle\ApiBundle\Provider\ProductImageFilterProviderInterface" />
            <argument>%sylius.security.new_api_route%</argument>
        </service>

        <service
            id="Sylius\Bundle\ApiBundle\Swagger\ProductSlugDocumentationNormalizer"
            decorates="api_platform.swagger.normalizer.documentation"
            autoconfigure="false"
            decoration-priority="20"
        >
            <argument type="service" id="Sylius\Bundle\ApiBundle\Swagger\ProductSlugDocumentationNormalizer.inner" />
            <argument>%sylius.security.new_api_route%</argument>
        </service>

        <service
            id="Sylius\Bundle\ApiBundle\Swagger\ProductVariantDocumentationNormalizer"
            decorates="api_platform.swagger.normalizer.documentation"
            autoconfigure="false"
            decoration-priority="20"
        >
            <argument type="service" id="Sylius\Bundle\ApiBundle\Swagger\ProductVariantDocumentationNormalizer.inner" />
        </service>

        <service
            id="Sylius\Bundle\ApiBundle\Swagger\ShippingMethodDocumentationNormalizer"
            decorates="api_platform.swagger.normalizer.documentation"
            autoconfigure="false"
            decoration-priority="20"
        >
            <argument type="service" id="Sylius\Bundle\ApiBundle\Swagger\ShippingMethodDocumentationNormalizer.inner" />
        </service>

        <service
            id="Sylius\Bundle\ApiBundle\Swagger\PathHiderDocumentationNormalizer"
            decorates="api_platform.swagger.normalizer.documentation"
            autoconfigure="false"
            decoration-priority="20"
        >
            <argument type="service" id="Sylius\Bundle\ApiBundle\Swagger\PathHiderDocumentationNormalizer.inner" />
            <argument>%sylius.api.paths_to_hide%</argument>
        </service>

        <service
            id="Sylius\Bundle\ApiBundle\Swagger\AcceptLanguageHeaderDocumentationNormalizer"
            decorates="api_platform.swagger.normalizer.documentation"
            autoconfigure="false"
            decoration-priority="20"
        >
            <argument type="service" id="Sylius\Bundle\ApiBundle\Swagger\AcceptLanguageHeaderDocumentationNormalizer.inner" />
            <argument type="service" id="sylius.repository.locale" />
        </service>
    </services>
</container>


text:
{% extends "layout.html" %}

{% block page_title %}Unauthorized{% endblock %}

{% block content %}

401

You are not authorized to see this page.

{% endblock %}


text:
$(function () {
    'use strict'

    QUnit.module('Store', {
        beforeEach: function () {
            Store.clear()
        }
    })

    QUnit.test('getId', function (assert) {
        var rect1 = $('#rect1')[0]
        var rect2 = $('#rect2')[0]
        var div3 = $('.other-rect')[0]

        assert.equal(Store.getId(rect1), 'rect1')
        assert.equal(Store.getId(rect2), 'rect2')
        assert.ok(Store.getId(div3).match(/lt-\d+/))
    })

    QUnit.test('set and get', function (assert) {
        var item = $('#rect1')[0]
        var event = {}
        var loaded

        Store.set(event, item)

        loaded = Store.get(event)

        assert.equal(item, loaded)
    })

    QUnit.test('set and get with DataTransfer', function (assert) {
        var item = $('#rect1')[0]
        var event = {}
        var loaded

        event.dataTransfer = {
            setData: function (type, data) {
                this.type = type
                this.data = data
            },
            getData: function (type) {
                if (type === this.type) {
                    return this.data
                }
            }
        }

        Store.set(event, item)

        loaded = Store.get(event)

        assert.deepEqual(item, loaded)

        assert.equal(event.dataTransfer.type, 'text')
        assert.equal(event.dataTransfer.data, '{"LTWidget":"rect1"}')
    })

    QUnit.test('get without data', function (assert) {
        var event = {}
        var loaded

        event.dataTransfer = {
            getData: function () {
                return ''
            }
        }

        loaded = Store.get(event)

        assert.equal(undefined, loaded)
    })
})


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace CSScripting
{
    class Profiler
    {
        static public Stopwatch Stopwatch = new Stopwatch();

        static public string EngineContext = "";

        static Dictionary<string, Stopwatch> items = new Dictionary<string, Stopwatch>();

        public static bool has(string key) => items.ContainsKey(key);

        public static Stopwatch get(string key)
        {
            if (!items.ContainsKey(key))
                items[key] = new Stopwatch();
            return items[key];
        }

        public static void measure(string name, Action action)
        {
            var sw = new Stopwatch();
            try
            {
                sw.Start();
                action();
            }
            finally
            {
                Console.WriteLine($"{name}: {sw.Elapsed}");
            }
        }
    }
}


text:
using Orleans.TestingHost;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Tester;
using TestExtensions;
using Orleans.Internal;
using UnitTests.GrainInterfaces;
using Xunit;
using Xunit.Abstractions;

namespace AWSUtils.Tests.StorageTests
{
    public abstract class Base_PersistenceGrainTests_AWSStore : OrleansTestingBase
    {
        private readonly ITestOutputHelper output;
        protected TestCluster HostedCluster { get; private set; }
        private readonly double timingFactor;

        private const int LoopIterations_Grain = 1000;
        private const int BatchSize = 100;

        private const int MaxReadTime = 200;
        private const int MaxWriteTime = 2000;
        private readonly BaseTestClusterFixture fixture;

        public Base_PersistenceGrainTests_AWSStore(ITestOutputHelper output, BaseTestClusterFixture fixture)
        {
            if (!AWSTestConstants.IsDynamoDbAvailable)
                throw new SkipException("Unable to connect to DynamoDB simulator");

            this.output = output;
            this.fixture = fixture;
            HostedCluster = fixture.HostedCluster;
            timingFactor = TestUtils.CalibrateTimings();
        }

        protected async Task Grain_AWSStore_Delete()
        {
            Guid id = Guid.NewGuid();
            IAWSStorageTestGrain grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain>(id);

            await grain.DoWrite(1);

            await grain.DoDelete();

            int val = await grain.GetValue(); // Should this throw instead?
            Assert.Equal(0, val);  // "Value after Delete"

            await grain.DoWrite(2);

            val = await grain.GetValue();
            Assert.Equal(2, val);  // "Value after Delete + New Write"
        }

        protected async Task Grain_AWSStore_Read()
        {
            Guid id = Guid.NewGuid();
            IAWSStorageTestGrain grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain>(id);

            int val = await grain.GetValue();

            Assert.Equal(0, val);  // "Initial value"
        }

        protected async Task Grain_GuidKey_AWSStore_Read_Write()
        {
            Guid id = Guid.NewGuid();
            IAWSStorageTestGrain grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain>(id);

            int val = await grain.GetValue();

            Assert.Equal(0, val);  // "Initial value"

            await grain.DoWrite(1);
            val = await grain.GetValue();
            Assert.Equal(1, val);  // "Value after Write-1"

            await grain.DoWrite(2);
            val = await grain.GetValue();
            Assert.Equal(2, val);  // "Value after Write-2"

            val = await grain.DoRead();

            Assert.Equal(2, val);  // "Value after Re-Read"
        }

        protected async Task Grain_LongKey_AWSStore_Read_Write()
        {
            long id = random.Next();
            IAWSStorageTestGrain_LongKey grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain_LongKey>(id);

            int val = await grain.GetValue();

            Assert.Equal(0, val);  // "Initial value"

            await grain.DoWrite(1);
            val = await grain.GetValue();
            Assert.Equal(1, val);  // "Value after Write-1"

            await grain.DoWrite(2);
            val = await grain.GetValue();
            Assert.Equal(2, val);  // "Value after Write-2"

            val = await grain.DoRead();

            Assert.Equal(2, val);  // "Value after Re-Read"
        }

        protected async Task Grain_LongKeyExtended_AWSStore_Read_Write()
        {
            long id = random.Next();
            string extKey = random.Next().ToString(CultureInfo.InvariantCulture);

            IAWSStorageTestGrain_LongExtendedKey
                grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain_LongExtendedKey>(id, extKey, null);

            int val = await grain.GetValue();

            Assert.Equal(0, val);  // "Initial value"

            await grain.DoWrite(1);
            val = await grain.GetValue();
            Assert.Equal(1, val);  // "Value after Write-1"

            await grain.DoWrite(2);
            val = await grain.GetValue();
            Assert.Equal(2, val);  // "Value after Write-2"

            val = await grain.DoRead();
            Assert.Equal(2, val);  // "Value after DoRead"

            val = await grain.GetValue();
            Assert.Equal(2, val);  // "Value after Re-Read"

            string extKeyValue = await grain.GetExtendedKeyValue();
            Assert.Equal(extKey, extKeyValue);  // "Extended Key"
        }

        protected async Task Grain_GuidKeyExtended_AWSStore_Read_Write()
        {
            var id = Guid.NewGuid();
            string extKey = random.Next().ToString(CultureInfo.InvariantCulture);

            IAWSStorageTestGrain_GuidExtendedKey
                grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain_GuidExtendedKey>(id, extKey, null);

            int val = await grain.GetValue();

            Assert.Equal(0, val);  // "Initial value"

            await grain.DoWrite(1);
            val = await grain.GetValue();
            Assert.Equal(1, val);  // "Value after Write-1"

            await grain.DoWrite(2);
            val = await grain.GetValue();
            Assert.Equal(2, val);  // "Value after Write-2"

            val = await grain.DoRead();
            Assert.Equal(2, val);  // "Value after DoRead"

            val = await grain.GetValue();
            Assert.Equal(2, val);  // "Value after Re-Read"

            string extKeyValue = await grain.GetExtendedKeyValue();
            Assert.Equal(extKey, extKeyValue);  // "Extended Key"
        }

        protected async Task Grain_Generic_AWSStore_Read_Write()
        {
            long id = random.Next();

            IAWSStorageGenericGrain<int> grain = this.fixture.GrainFactory.GetGrain<IAWSStorageGenericGrain<int>>(id);

            int val = await grain.GetValue();

            Assert.Equal(0, val);  // "Initial value"

            await grain.DoWrite(1);
            val = await grain.GetValue();
            Assert.Equal(1, val);  // "Value after Write-1"

            await grain.DoWrite(2);
            val = await grain.GetValue();
            Assert.Equal(2, val);  // "Value after Write-2"

            val = await grain.DoRead();

            Assert.Equal(2, val);  // "Value after Re-Read"
        }

        protected async Task Grain_Generic_AWSStore_DiffTypes()
        {
            long id1 = random.Next();
            long id2 = id1;
            long id3 = id1;

            IAWSStorageGenericGrain<int> grain1 = this.fixture.GrainFactory.GetGrain<IAWSStorageGenericGrain<int>>(id1);

            IAWSStorageGenericGrain<string> grain2 = this.fixture.GrainFactory.GetGrain<IAWSStorageGenericGrain<string>>(id2);

            IAWSStorageGenericGrain<double> grain3 = this.fixture.GrainFactory.GetGrain<IAWSStorageGenericGrain<double>>(id3);

            int val1 = await grain1.GetValue();
            Assert.Equal(0, val1);  // "Initial value - 1"

            string val2 = await grain2.GetValue();
            Assert.Null(val2);  // "Initial value - 2"

            double val3 = await grain3.GetValue();
            Assert.Equal(0.0, val3);  // "Initial value - 3"

            int expected1 = 1;
            await grain1.DoWrite(expected1);
            val1 = await grain1.GetValue();
            Assert.Equal(expected1, val1);  // "Value after Write#1 - 1"

            string expected2 = "Three";
            await grain2.DoWrite(expected2);
            val2 = await grain2.GetValue();
            Assert.Equal(expected2, val2);  // "Value after Write#1 - 2"

            double expected3 = 5.1;
            await grain3.DoWrite(expected3);
            val3 = await grain3.GetValue();
            Assert.Equal(expected3, val3);  // "Value after Write#1 - 3"

            val1 = await grain1.GetValue();
            Assert.Equal(expected1, val1);  // "Value before Write#2 - 1"
            expected1 = 2;
            await grain1.DoWrite(expected1);
            val1 = await grain1.GetValue();
            Assert.Equal(expected1, val1);  // "Value after Write#2 - 1"
            val1 = await grain1.DoRead();
            Assert.Equal(expected1, val1);  // "Value after Re-Read - 1"

            val2 = await grain2.GetValue();
            Assert.Equal(expected2, val2);  // "Value before Write#2 - 2"
            expected2 = "Four";
            await grain2.DoWrite(expected2);
            val2 = await grain2.GetValue();
            Assert.Equal(expected2, val2);  // "Value after Write#2 - 2"
            val2 = await grain2.DoRead();
            Assert.Equal(expected2, val2);  // "Value after Re-Read - 2"

            val3 = await grain3.GetValue();
            Assert.Equal(expected3, val3);  // "Value before Write#2 - 3"
            expected3 = 6.2;
            await grain3.DoWrite(expected3);
            val3 = await grain3.GetValue();
            Assert.Equal(expected3, val3);  // "Value after Write#2 - 3"
            val3 = await grain3.DoRead();
            Assert.Equal(expected3, val3);  // "Value after Re-Read - 3"
        }

        protected async Task Grain_AWSStore_SiloRestart()
        {
            var initialServiceId = this.HostedCluster.Options.ServiceId;
            var initialDeploymentId = this.HostedCluster.Options.ClusterId;
            var serviceId = await this.HostedCluster.Client.GetGrain<IServiceIdGrain>(Guid.Empty).GetServiceId();
            output.WriteLine("ClusterId={0} ServiceId={1}", this.HostedCluster.Options.ClusterId, serviceId);

            Guid id = Guid.NewGuid();
            IAWSStorageTestGrain grain = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain>(id);

            int val = await grain.GetValue();

            Assert.Equal(0, val);  // "Initial value"

            await grain.DoWrite(1);

            output.WriteLine("About to reset Silos");
            foreach (var silo in this.HostedCluster.GetActiveSilos().ToList())
            {
                await this.HostedCluster.RestartSiloAsync(silo);
            }
            this.HostedCluster.InitializeClient();

            output.WriteLine("Silos restarted");

            serviceId = await this.HostedCluster.Client.GetGrain<IServiceIdGrain>(Guid.Empty).GetServiceId();
            output.WriteLine("ClusterId={0} ServiceId={1}", this.HostedCluster.Options.ClusterId, serviceId);
            Assert.Equal(initialServiceId, serviceId);  // "ServiceId same after restart."
            Assert.Equal(initialDeploymentId, this.HostedCluster.Options.ClusterId);  // "ClusterId same after restart."

            val = await grain.GetValue();
            Assert.Equal(1, val);  // "Value after Write-1"

            await grain.DoWrite(2);
            val = await grain.GetValue();
            Assert.Equal(2, val);  // "Value after Write-2"

            val = await grain.DoRead();

            Assert.Equal(2, val);  // "Value after Re-Read"
        }

        protected void Persistence_Perf_Activate()
        {
            const string testName = "Persistence_Perf_Activate";
            int n = LoopIterations_Grain;
            TimeSpan target = TimeSpan.FromMilliseconds(MaxReadTime * n);

            // Timings for Activate
            RunPerfTest(n, testName, target,
                grainNoState => grainNoState.PingAsync(),
                grainMemory => grainMemory.DoSomething(),
                grainMemoryStore => grainMemoryStore.GetValue(),
                grainAWSStore => grainAWSStore.GetValue());
        }

        protected void Persistence_Perf_Write()
        {
            const string testName = "Persistence_Perf_Write";
            int n = LoopIterations_Grain;
            TimeSpan target = TimeSpan.FromMilliseconds(MaxWriteTime * n);

            // Timings for Write
            RunPerfTest(n, testName, target,
                grainNoState => grainNoState.EchoAsync(testName),
                grainMemory => grainMemory.DoWrite(n),
                grainMemoryStore => grainMemoryStore.DoWrite(n),
                grainAWSStore => grainAWSStore.DoWrite(n));
        }

        protected void Persistence_Perf_Write_Reread()
        {
            const string testName = "Persistence_Perf_Write_Read";
            int n = LoopIterations_Grain;
            TimeSpan target = TimeSpan.FromMilliseconds(MaxWriteTime * n);

            // Timings for Write
            RunPerfTest(n, testName + "--Write", target,
                grainNoState => grainNoState.EchoAsync(testName),
                grainMemory => grainMemory.DoWrite(n),
                grainMemoryStore => grainMemoryStore.DoWrite(n),
                grainAWSStore => grainAWSStore.DoWrite(n));

            // Timings for Activate
            RunPerfTest(n, testName + "--ReRead", target,
                grainNoState => grainNoState.GetLastEchoAsync(),
                grainMemory => grainMemory.DoRead(),
                grainMemoryStore => grainMemoryStore.DoRead(),
                grainAWSStore => grainAWSStore.DoRead());
        }

        protected async Task Persistence_Silo_StorageProvider_AWS(Type providerType)
        {
            List<SiloHandle> silos = this.HostedCluster.GetActiveSilos().ToList();
            foreach (var silo in silos)
            {
                string provider = providerType.FullName;
                ICollection<string> providers = await this.HostedCluster.Client.GetTestHooks(silo).GetStorageProviderNames();
                Assert.True(providers.Contains(provider), $"No storage provider found: {provider}");
            }
        }

        // ---------- Utility functions ----------

        protected void RunPerfTest(int n, string testName, TimeSpan target,
            Func<IEchoTaskGrain, Task> actionNoState,
            Func<IPersistenceTestGrain, Task> actionMemory,
            Func<IMemoryStorageTestGrain, Task> actionMemoryStore,
            Func<IAWSStorageTestGrain, Task> actionAWSTable)
        {
            IEchoTaskGrain[] noStateGrains = new IEchoTaskGrain[n];
            IPersistenceTestGrain[] memoryGrains = new IPersistenceTestGrain[n];
            IAWSStorageTestGrain[] awsStoreGrains = new IAWSStorageTestGrain[n];
            IMemoryStorageTestGrain[] memoryStoreGrains = new IMemoryStorageTestGrain[n];

            for (int i = 0; i < n; i++)
            {
                Guid id = Guid.NewGuid();
                noStateGrains[i] = this.fixture.GrainFactory.GetGrain<IEchoTaskGrain>(id);
                memoryGrains[i] = this.fixture.GrainFactory.GetGrain<IPersistenceTestGrain>(id);
                awsStoreGrains[i] = this.fixture.GrainFactory.GetGrain<IAWSStorageTestGrain>(id);
                memoryStoreGrains[i] = this.fixture.GrainFactory.GetGrain<IMemoryStorageTestGrain>(id);
            }

            TimeSpan baseline, elapsed;

            elapsed = baseline = TestUtils.TimeRun(n, TimeSpan.Zero, testName + " (No state)",
                () => RunIterations(testName, n, i => actionNoState(noStateGrains[i])));

            elapsed = TestUtils.TimeRun(n, baseline, testName + " (Local Memory Store)",
                () => RunIterations(testName, n, i => actionMemory(memoryGrains[i])));

            elapsed = TestUtils.TimeRun(n, baseline, testName + " (Dev Store Grain Store)",
                () => RunIterations(testName, n, i => actionMemoryStore(memoryStoreGrains[i])));

            elapsed = TestUtils.TimeRun(n, baseline, testName + " (AWS Table Store)",
                () => RunIterations(testName, n, i => actionAWSTable(awsStoreGrains[i])));

            if (elapsed > target.Multiply(timingFactor))
            {
                string msg = string.Format("{0}: Elapsed time {1} exceeds target time {2}", testName, elapsed, target);

                if (elapsed > target.Multiply(2.0 * timingFactor))
                {
                    Assert.True(false, msg);
                }
                else
                {
                    throw new SkipException(msg);
                }
            }
        }

        private void RunIterations(string testName, int n, Func<int, Task> action)
        {
            List<Task> promises = new List<Task>();
            Stopwatch sw = Stopwatch.StartNew();
            // Fire off requests in batches
            for (int i = 0; i < n; i++)
            {
                var promise = action(i);
                promises.Add(promise);
                if ((i % BatchSize) == 0 && i > 0)
                {
                    Task.WaitAll(promises.ToArray());
                    promises.Clear();
                    //output.WriteLine("{0} has done {1} iterations  in {2} at {3} RPS",
                    //                  testName, i, sw.Elapsed, i / sw.Elapsed.TotalSeconds);
                }
            }
            Task.WaitAll(promises.ToArray());
            sw.Stop();
            output.WriteLine("{0} completed. Did {1} iterations in {2} at {3} RPS",
                              testName, n, sw.Elapsed, n / sw.Elapsed.TotalSeconds);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace SoftJail.Data.Models.Enums
{
    public enum Position
    {
        Overseer = 0,
        Guard,
        Watcher,
        Labour
    }
}


text:
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------

#include "platform/platform.h"
#include "materials/materialList.h"

#include "materials/matInstance.h"
#include "materials/materialManager.h"
#include "materials/materialFeatureTypes.h"
#include "materials/processedMaterial.h"
#include "core/volume.h"
#include "console/simSet.h"

MaterialList::MaterialList()
{
   VECTOR_SET_ASSOCIATION(mMatInstList);
   VECTOR_SET_ASSOCIATION(mMaterialNames);
}

MaterialList::MaterialList(const MaterialList* pCopy)
{
   VECTOR_SET_ASSOCIATION(mMatInstList);
   VECTOR_SET_ASSOCIATION(mMaterialNames);

   mMaterialNames.setSize(pCopy->mMaterialNames.size());
   S32 i;
   for (i = 0; i < mMaterialNames.size(); i++)
   {
      mMaterialNames[i] = pCopy->mMaterialNames[i];
   }

   clearMatInstList();
   mMatInstList.setSize(pCopy->size());
   for( i = 0; i < mMatInstList.size(); i++ )
   {
      if( i < pCopy->mMatInstList.size() && pCopy->mMatInstList[i] )
      {
         mMatInstList[i] = pCopy->mMatInstList[i]->getMaterial()->createMatInstance();
      }
      else
      {
         mMatInstList[i] = NULL;
      }
   }
}

MaterialList::MaterialList(U32 materialCount, const char **materialNames)
{
   VECTOR_SET_ASSOCIATION(mMaterialNames);

   set(materialCount, materialNames);
}

//--------------------------------------
void MaterialList::set(U32 materialCount, const char **materialNames)
{
   free();
   mMaterialNames.setSize(materialCount);
   clearMatInstList();
   mMatInstList.setSize(materialCount);
   for(U32 i = 0; i < materialCount; i++)
   {
      mMaterialNames[i] = materialNames[i];
      mMatInstList[i] = NULL;
   }
}

//--------------------------------------
MaterialList::~MaterialList()
{
   free();
}

//--------------------------------------
void MaterialList::setMaterialName(U32 index, const String& name)
{
   if (index < mMaterialNames.size())
      mMaterialNames[index] = name;
}

//--------------------------------------
GFXTextureObject *MaterialList::getDiffuseTexture(U32 index)
{
   AssertFatal(index < (U32) mMatInstList.size(), "MaterialList::getDiffuseTex: index lookup out of range.");

   MatInstance *matInst = dynamic_cast<MatInstance*>(mMatInstList[index]);
   if (matInst && matInst->getProcessedMaterial())
      return matInst->getProcessedMaterial()->getStageTexture(0, MFT_DiffuseMap);
   else
      return NULL;
}

//--------------------------------------
void MaterialList::free()
{
   clearMatInstList();
   mMatInstList.clear();
   mMaterialNames.clear();
}

/*
//--------------------------------------
U32 MaterialList::push_back(GFXTexHandle textureHandle, const String &filename)
{
   mMaterialNames.push_back(filename);
   mMatInstList.push_back(NULL);

   // return the index
   return mMaterialNames.size()-1;
}
*/

//--------------------------------------
U32 MaterialList::push_back(const String &filename, Material* material)
{
   mMaterialNames.push_back(filename);
   mMatInstList.push_back(material ? material->createMatInstance() : NULL);

   // return the index
   return mMaterialNames.size()-1;
}

//--------------------------------------
bool MaterialList::read(Stream &stream)
{
   free();

   // check the stream version
   U8 version;
   if ( stream.read(&version) && version != BINARY_FILE_VERSION)
      return readText(stream,version);

   // how many materials?
   U32 count;
   if ( !stream.read(&count) )
      return false;

   // pre-size the vectors for efficiency
   mMaterialNames.reserve(count);

   // read in the materials
   for (U32 i=0; i<count; i++)
   {
      // Load the bitmap name
      char buffer[256];
      stream.readString(buffer);
      if( !buffer[0] )
      {
         AssertWarn(0, "MaterialList::read: error reading stream");
         return false;
      }

      // Material paths are a legacy of Tribes tools,
      // strip them off...
      char *name = &buffer[dStrlen(buffer)];
      while (name != buffer && name[-1] != '/' && name[-1] != '\\')
         name--;

      // Add it to the list
      mMaterialNames.push_back(name);
      mMatInstList.push_back(NULL);
   }

   return (stream.getStatus() == Stream::Ok);
}

//--------------------------------------
bool MaterialList::write(Stream &stream)
{
   stream.write((U8)BINARY_FILE_VERSION);          // version
   stream.write((U32)mMaterialNames.size());       // material count

   for(S32 i=0; i < mMaterialNames.size(); i++)    // material names
      stream.writeString(mMaterialNames[i]);

   return (stream.getStatus() == Stream::Ok);
}

//--------------------------------------
bool MaterialList::readText(Stream &stream, U8 firstByte)
{
   free();

   if (!firstByte)
      return (stream.getStatus() == Stream::Ok || stream.getStatus() == Stream::EOS);

   char buf[1024];
   buf[0] = firstByte;
   U32 offset = 1;

   for(;;)
   {
      stream.readLine((U8*)(buf+offset), sizeof(buf)-offset);
      if(!buf[0])
         break;
      offset = 0;

      // Material paths are a legacy of Tribes tools,
      // strip them off...
      char *name = &buf[dStrlen(buf)];
      while (name != buf && name[-1] != '/' && name[-1] != '\\')
         name--;

      // Add it to the list
      mMaterialNames.push_back(name);
      mMatInstList.push_back(NULL);
   }

   return (stream.getStatus() == Stream::Ok || stream.getStatus() == Stream::EOS);
}

bool MaterialList::readText(Stream &stream)
{
   U8 firstByte;
   stream.read(&firstByte);
   return readText(stream,firstByte);
}

//--------------------------------------
bool MaterialList::writeText(Stream &stream)
{
   for(S32 i=0; i < mMaterialNames.size(); i++)
      stream.writeLine((U8*)(mMaterialNames[i].c_str()));
   stream.writeLine((U8*)"");

   return (stream.getStatus() == Stream::Ok);
}

//--------------------------------------------------------------------------
// Clear all materials in the mMatInstList member variable
//--------------------------------------------------------------------------
void MaterialList::clearMatInstList()
{
   // clear out old materials.  any non null element of the list should be pointing at deletable memory,
   // although multiple indexes may be pointing at the same memory so we have to be careful (see
   // comment in loop body)
   for (U32 i=0; i<mMatInstList.size(); i++)
   {
      if (mMatInstList[i])
      {
         BaseMatInstance* current = mMatInstList[i];

         // ok, since ts material lists can remap difference indexes to the same object
         // we need to make sure that we don't delete the same memory twice.  walk the
         // rest of the list and null out any pointers that match the one we deleted.
         for (U32 j=0; j<mMatInstList.size(); j++)
            if (mMatInstList[j] == current)
               mMatInstList[j] = NULL;

         mMatInstList[i] = NULL;
         delete current;
      }
   }
}

//--------------------------------------------------------------------------
// Map materials - map materials to the textures in the list
//--------------------------------------------------------------------------
void MaterialList::mapMaterials()
{
   mMatInstList.setSize( mMaterialNames.size() );

   for( U32 i=0; i<mMaterialNames.size(); i++ )
      mapMaterial( i );
}

/// Map the material name at the given index to a material instance.
///
/// @note The material instance that is created will not be initialized.

void MaterialList::mapMaterial( U32 i )
{
   AssertFatal( i < size(), "MaterialList::mapMaterialList - index out of bounds" );

   if( mMatInstList[i] != NULL )
      return;

   // lookup a material property entry
   const String &matName = getMaterialName(i);

   // JMQ: this code assumes that all materials have names.
   if( matName.isEmpty() )
   {
      mMatInstList[i] = NULL;
      return;
   }

   String materialName = MATMGR->getMapEntry(matName);

   // IF we didn't find it, then look for a PolyStatic generated Material
   //  [a little cheesy, but we need to allow for user override of generated Materials]
   if ( materialName.isEmpty() )
      materialName = MATMGR->getMapEntry( String::ToString( "polyMat_%s", matName.c_str() ) );

   if ( materialName.isNotEmpty() )
   {
      Material * mat = MATMGR->getMaterialDefinitionByName( materialName );
      mMatInstList[i] = mat ? mat->createMatInstance() : MATMGR->createWarningMatInstance();
   }
   else
   {
      if ( Con::getBoolVariable( "$Materials::createMissing", true ) )
      {
         // No Material found, create new "default" material with just a diffuseMap

         // First see if there is a valid diffuse texture
         GFXTexHandle texHandle;
         if (mLookupPath.isEmpty())
         {
            texHandle.set( mMaterialNames[i], &GFXStaticTextureSRGBProfile, avar("%s() - handle (line %d)", __FUNCTION__, __LINE__) );
         }
         else
         {
            // Should we strip off the extension of the path here before trying
            // to load the texture?
            String fullPath = String::ToString( "%s/%s", mLookupPath.c_str(), mMaterialNames[i].c_str() );
            texHandle.set( fullPath, &GFXStaticTextureSRGBProfile, avar("%s() - handle (line %d)", __FUNCTION__, __LINE__) );
         }

         if ( texHandle.isValid() )
         {
            String newMatName = Sim::getUniqueName( "DefaultMaterial" );
            Material *newMat = MATMGR->allocateAndRegister( newMatName, mMaterialNames[i] );

            // Flag this as an autogenerated Material
            newMat->mAutoGenerated = true;

            // Overwrite diffuseMap in new material
            newMat->mDiffuseMapFilename[0] = texHandle->mTextureLookupName;

            // Set up some defaults for transparent textures
            if (texHandle->mHasTransparency)
            {
               newMat->mTranslucent = true;
               newMat->mTranslucentBlendOp = Material::LerpAlpha;
               newMat->mTranslucentZWrite = true;
               newMat->mAlphaRef = 20;
            }

            // create a MatInstance for the new material
            mMatInstList[i] = newMat->createMatInstance();

            #ifndef TORQUE_SHIPPING
               Con::warnf( "[MaterialList::mapMaterials] Creating missing material for texture: %s", texHandle->mTextureLookupName.c_str() );
            #endif
         }
         else
         {
            Con::errorf( "[MaterialList::mapMaterials] Unable to find material for texture: %s", mMaterialNames[i].c_str() );
            mMatInstList[i] = MATMGR->createWarningMatInstance();
         }
      }
      else
      {
         mMatInstList[i] = MATMGR->createWarningMatInstance();
      }
   }
}

void MaterialList::initMatInstances(   const FeatureSet &features,
                                       const GFXVertexFormat *vertexFormat )
{
   for( U32 i=0; i < mMatInstList.size(); i++ )
   {
      BaseMatInstance *matInst = mMatInstList[i];
      if ( !matInst )
         continue;

      if ( !matInst->init( features, vertexFormat ) )
      {
         Con::errorf( "MaterialList::initMatInstances - failed to initialize material instance for '%s'",
            matInst->getMaterial()->getName() );

         // Fall back to warning material.

         SAFE_DELETE( matInst );
         matInst = MATMGR->createMatInstance( "WarningMaterial" );
         matInst->init( MATMGR->getDefaultFeatures(), vertexFormat );
         mMatInstList[ i ] = matInst;
      }
   }

}

void MaterialList::setMaterialInst( BaseMatInstance *matInst, U32 texIndex )
{
   AssertFatal( texIndex < mMatInstList.size(), "MaterialList::setMaterialInst - index out of bounds" );
   mMatInstList[texIndex] = matInst;
}


text:
<?php

/**
 * Geoplace utility
 * @since Version 3.9.1
 * @package Railpage
 * @author Michael Greenhill
 */

namespace Railpage\Images\Utility;

use Exception;
use InvalidArgumentException;
use DateTime;
use DateTimeZone;
use Railpage\AppCore;
use Railpage\Images\ImageFactory;
use Railpage\Images\Images;
use Railpage\Images\Image;
use Railpage\Place;
use Railpage\Locations\Country;
use Railpage\Locations\Region;

class Geoplace {

    /**
     * Get photo neighbourhoods including photo counts
     * @since Version 3.9.1
     * @return array
     * @param string|null $country
     * @param string|null $region
     */

    public static function getNeighbourhoods($country = NULL, $region = NULL) {

        $params = array();

        if (!is_null($country)) {
            $params[] = strtoupper($country);
            $country = " AND country_code = ?";
        }

        if (!is_null($region)) {
            $params[] = strtoupper($region);
            $region = " AND region_code = ?";
        }

        $Database = (new AppCore)->getDatabaseConnection();

        $query = "SELECT g.country_code, g.country_name, g.region_code, g.region_name, g.neighbourhood, g.id,
                X(g.point) AS lat, Y(g.point) AS lon, g.timezone, COUNT(*) AS count,
                GROUP_CONCAT(i.id) AS image_ids, CONCAT('/place?lat=', X(g.point), '&lon=', Y(g.point)) AS url
            FROM image AS i
            LEFT JOIN geoplace AS g ON i.geoplace = g.id
            WHERE i.geoplace != 0
            " . $country . "
            " . $region . "
            GROUP BY g.id
            ORDER BY g.country_code, g.region_code, g.neighbourhood";

        $result = $Database->fetchAll($query, $params);

        foreach ($result as $key => $val) {
            $result[$key]['image_ids'] = array_slice(explode(",", $val['image_ids']), 0, 5);
            //$result[$key]['photos'] = ImageFactory::GetThumbnails($result[$key]['image_ids']);
            //$result[$key]['photos_html'] = implode("", array_column($result[$key]['photos'], "html"));
        }

        return $result;

    }

    /**
     * Get regions
     * @since Version 3.9.1
     * @return array
     * @param string|null $country
     */

    public static function getRegions($country = NULL) {

        $params = [];
        $where = [];

        if (!is_null($country)) {
            $where[] = " country_code = ?";
            $params[] = strtoupper($country);
        }

        $query = "SELECT DISTINCT region_code, region_name, country_code, country_name FROM geoplace";

        if (count($where)) {
            $query .= " WHERE " . implode(" AND ", $where);
        }

        $query .= " ORDER BY country_code, region_code";

        $Database = (new AppCore)->getDatabaseConnection();

        $return = array();

        foreach ($Database->fetchAll($query, $params) as $row) {
            if (!isset($return[$row['country_code']])) {
                $return[$row['country_code']] = array(
                    "country_code" => $row['country_code'],
                    "country_name" => $row['country_name'],
                    "regions" => []
                );
            }

            $return[$row['country_code']]['regions'][$row['region_code']] = array(
                "region_code" => $row['region_code'],
                "region_name" => $row['region_name']
            );
        }

        return $return;

    }
}


text:
The Node.JS client to communicate with the Embdr REST API

## Dependencies

 * Node.JS

## Installation

You can install the client through [NPM](https://www.npmjs.org/package/embdr)

```
npm install embdr
```

## Example

```javascript
var Embdr = require('embdr');

// Create a new embdr instance
var embdr = new Embdr('VUT6blsAabPE2Vw7BkDZiCJ45duoBtit');

// Process a file on disk
embdr.process('path/to/my/file.xlsx', {
    // Invoked when something went wrong trying to contact the Embdr REST API
    'error': function(err) {
        console.error('Failed to process a resource');
        console.error(err);
    },

    // Invoked when the upload request finishes
    'start': function(resource) {
        console.log('Uploaded a resource for processing');
        console.log(resource);
    },

    'thumbnails': {
        // Specify the desired sizes of the thumbnails
        'sizes': ['64x64', '256x256'],

        // Invoked when the thumbnails are ready
        'complete': function(thumbnails) {
            console.log('Generated thumbnails');
            console.log(thumbnails);
        }
    },

    'images': {
        // Specify the desired sizes of the image previews. When only one side of the dimension is
        // specified, the image will be scaled so the original ratio is retained. Image previews
        // will never be scaled up
        'sizes': ['768x'],

        // Invoked when the image previews are ready
        'complete': function(images) {
            console.log('Generated images');
            console.log(images);
        }
    },

    // Invoked when the entire file has been processed
    'complete': function(resource) {
        console.log('Completely processed a resource');
        console.log(resource);
    }
});
```

The `process` function is overloaded and can take other types such as HTTP links:
```
var url = 'https://upload.wikimedia.org/wikipedia/meta/b/be/Wikipedia-logo-v2_2x.png';
embdr.process(url, {
    'complete': function(resource) {
        console.log('Completely processed a URL
        ');
        console.log(resource);
    }
});
```

It can also take in any kind of readable stream:
```
var stream = myFunctionThatReturnsAStream();

embdr.process(stream, {
    'complete': function(resource) {
        console.log('Completely processed a resource');
        console.log(resource);
    }
});
```

## Documentation

TODO


text:
{-# LANGUAGE PatternGuards #-}
module Action where

import           Control.Applicative
import           Control.Monad
import qualified Data.ByteString                      as B
import qualified Data.ByteString.Lazy                 as L
import           Data.Char
import           Data.List                            (intersperse, nub)

import           Test.Framework
import           Test.Framework.Providers.QuickCheck2
import           Test.QuickCheck

import           Arbitrary                            ()
import qualified Data.Binary.Get                      as Binary

tests :: [Test]
tests = [ testProperty "action" prop_action
        , testProperty "label" prop_label
        , testProperty "fail" prop_fail ]

data Action
  = Actions [Action]
  | GetByteString Int
  | GetByteStringL Int
  | Skip Int
  | Isolate Int [Action]
  | Try [Action] [Action]
  | Label String [Action]
  | LookAhead [Action]
  -- | First argument is True if this action returns Just, otherwise False.
  | LookAheadM Bool [Action]
  -- | First argument is True if this action returns Right, otherwise Left.
  | LookAheadE Bool [Action]
  | BytesRead
  | Fail
  deriving (Show, Eq)

instance Arbitrary Action where
  arbitrary = fmap Actions (gen_actions False)
  shrink action =
    case action of
      Actions [a] -> [a]
      Actions as -> [ Actions as' | as' <- shrink as ]
      BytesRead -> []
      Fail -> []
      GetByteString n -> [ GetByteString n' | n' <- shrink n ]
      GetByteStringL n -> [ GetByteStringL n' | n' <- shrink n ]
      Skip n -> [ Skip n' | n' <- shrink n ]
      Isolate n as -> nub $ Actions as :
        [ Isolate n' as' | (n',as') <- shrink (n,as)
                         , n' >= 0
                         , n' <= max_len as' + 1 ]
      Label str a -> Actions a : [ Label str a' | a' <- shrink a ]
      LookAhead a -> Actions a : [ LookAhead a' | a' <- shrink a ]
      LookAheadM b a -> Actions a : [ LookAheadM b a' | a' <- shrink a ]
      LookAheadE b a -> Actions a : [ LookAheadE b a' | a' <- shrink a ]
      Try [Fail] b -> Actions b : [ Try [Fail] b' | b' <- shrink b ]
      Try a b ->
        [Actions a | not (willFail' a)]
        ++ [ Try a' b' | (a',b') <- shrink (a,b) ]

willFail :: Int -> [Action] -> Bool
willFail inp xxs =
  case eval inp xxs of
    EFail {} -> True
    _ -> False

willFail' :: [Action] -> Bool
willFail' = willFail maxBound

-- | The maximum length of input decoder can request.
-- The decoder may end up using less, but never more.
-- This way, you know how much input to generate for running a decoder test.
max_len :: [Action] -> Int
max_len [] = 0
max_len (x:xs) =
  case x of
    Actions xs' -> max_len (xs' ++ xs)
    BytesRead -> max_len xs
    Fail -> 0
    GetByteString n -> n + max_len xs
    GetByteStringL n -> n + max_len xs
    Skip n -> n + max_len xs
    Isolate n xs'
      | Just _ <- actual_len' [Isolate n xs'] -> n + max_len xs
      | otherwise -> n
    Label _ xs' -> max_len (xs' ++ xs)
    LookAhead xs'
      | willFail' xs' -> max_len xs'
      | otherwise -> max (max_len xs') (max_len xs)
    LookAheadM consume xs'
      | consume -> max_len (xs' ++ xs)
      | otherwise -> max_len (LookAhead xs' : xs)
    LookAheadE consume xs'
      | consume -> max_len (xs' ++ xs)
      | otherwise -> max_len (LookAhead xs' : xs)
    Try a b
      | willFail' a && willFail' b -> max (max_len a) (max_len b)
      | willFail' a -> max (max_len a) (max_len b) + max_len xs
      | otherwise ->  max_len (a ++ xs)

-- | The actual length of input that will be consumed when
-- a decoder is executed, or Nothing if the decoder will fail.
actual_len :: Int -> [Action] -> Maybe Int
actual_len inp xs =
  case eval inp xs of
    ESuccess inp' -> Just (inp - inp')
    _ -> Nothing

actual_len' :: [Action] -> Maybe Int
actual_len' = actual_len maxBound

randomInput :: Int -> Gen L.ByteString
randomInput 0 = return L.empty
randomInput n = do
  m <- choose (1, min n 10)
  s <- vectorOf m $ choose ('a', 'z')
  let b = B.pack $ map (fromIntegral.ord) s
  rest <- randomInput (n-m)
  return (L.append (L.fromChunks [b]) rest)

-- | Build binary programs and compare running them to running a (hopefully)
-- identical model.
-- Tests that 'bytesRead' returns correct values when used together with '<|>'
-- and 'fail'.
prop_action :: Property
prop_action =
  forAllShrink (gen_actions False) shrink $ \ actions ->
    let max_len_input = max_len actions in
    forAll (randomInput max_len_input) $ \ lbs ->
      let allInput = B.concat (L.toChunks lbs) in
      case Binary.runGetOrFail (execute allInput actions) lbs of
        Right (_inp, _off, _x) -> True
        Left (_inp, _off, _msg) -> True

-- | When a decoder aborts with 'fail', check that all relevant uses of 'label'
-- are respected.
prop_label :: Property
prop_label =
  forAllShrink (gen_actions True) shrink $ \ actions ->
    let max_len_input = max_len actions in
    forAll (randomInput max_len_input) $ \ lbs ->
      let allInput = B.concat (L.toChunks lbs) in
      collect (failReason $ eval max_len_input actions) $
      case Binary.runGetOrFail (execute allInput actions) lbs of
        Left (_inp, _off, msg) ->
          let lbls = case collectLabels max_len_input actions of
                         Just lbls' -> lbls'
                         Nothing -> error ("expected labels, got: " ++ msg)
              expectedMsg = concat $ intersperse "\n" lbls
          in expectedMsg === msg
        Right (_inp, _off, _value) -> label "test case without 'fail'" $ True

-- | When a decoder aborts with 'fail', check the fail position and
-- remaining input.
prop_fail :: Property
prop_fail =
  forAllShrink (gen_actions True) shrink $ \ actions ->
    let max_len_input = max_len actions in
    forAll (randomInput max_len_input) $ \ lbs ->
      let allInput = B.concat (L.toChunks lbs) in
      collect (failReason $ eval max_len_input actions) $
      case Binary.runGetOrFail (execute allInput actions) lbs of
        Left (inp, off, _msg) ->
          case () of
            _ | Just off /= findFailPosition max_len_input actions ->
                  error ("fail position incorrect, expected " ++
                         show (findFailPosition max_len_input actions) ++
                         " but got " ++ show off)
              | inp /= L.drop (fromIntegral off) lbs ->
                  error $ "remaining output incorrect, was: " ++ show inp ++
                    ", should hav been: " ++ show (L.drop (fromIntegral off) lbs)
              | otherwise -> property True
        Right (_inp, _off, _value) -> label "test case without 'fail'" $ property True

-- | Collect all the labels up to a 'fail', or Nothing if the
-- decoder will not fail.
collectLabels :: Int -> [Action] -> Maybe [String]
collectLabels inp xxs =
  case eval inp xxs of
    EFail _ lbls _ -> Just lbls
    _ -> Nothing

-- | Finds at which byte offset the decoder will fail,
-- or Nothing if it won't fail.
findFailPosition :: Int -> [Action] -> Maybe Binary.ByteOffset
findFailPosition inp xxs =
  case eval inp xxs of
    EFail _ _ inp' -> return (fromIntegral (inp-inp'))
    _ -> Nothing

failReason :: Eval -> String
failReason (EFail fr _ _) = show fr
failReason _ = "NoFail"

-- | The result of an evaluation.
data Eval = ESuccess Int
          -- ^ The evalutation completed successfully. Contains the number of
          -- remaining bytes of the input.
          | EFail FailReason [String] Int
          -- ^ The evaluation completed with a failure. Contains the labels up
          -- to the failure, and the number of remaining bytes of the input.
          deriving (Show,Eq)

data FailReason
  = FRFail
  | FRIsolateTooMuch
  | FRIsolateTooLittle
  | FRTooMuch
  deriving (Show,Eq)

-- | Given the number of input bytes and a list of actions, evaluate the
-- actions and return whether the actions succeeed or fail.
eval :: Int -> [Action] -> Eval
eval inp0 = go inp0 []
  where
    step :: Int -> Int -> [String] -> [Action] -> Eval
    step inp n lbls xs
      | inp - n < 0 =
          let msg = "not enough bytes"
          in EFail FRTooMuch (msg:lbls) inp
      | otherwise = go (inp-n) lbls xs
    go :: Int -> [String] -> [Action] -> Eval
    go inp _lbls [] = ESuccess inp
    go inp lbls (x:xs) =
      case x of
        Actions xs' -> go inp lbls (xs'++xs)
        BytesRead -> go inp lbls xs
        Fail -> EFail FRFail ("fail":lbls) inp
        GetByteString n -> step inp n lbls xs
        GetByteStringL n -> step inp n lbls xs
        Skip n -> step inp n lbls xs
        Isolate n xs'
          | n > inp ->
              case go inp lbls xs' of
                ESuccess inp' ->
                  let msg = "isolate: the decoder consumed " ++ show (inp - inp') ++
                            " bytes which is less than the expected " ++ (show n) ++
                            " bytes"
                   in EFail FRTooMuch (msg:lbls) inp'
                efail -> efail
          | otherwise ->
              case go n lbls xs' of
                EFail fr lbls' inp' -> EFail fr lbls' (inp - n + inp')
                ESuccess 0          -> go (inp-n) lbls xs
                ESuccess inp'       ->
                  let msg = "isolate: the decoder consumed " ++ show (n - inp') ++
                            " bytes which is less than the expected " ++ (show n) ++
                            " bytes"
                  in EFail FRIsolateTooLittle (msg:lbls) (inp - n + inp')
        Label str xs' ->
          case go inp (str:lbls) xs' of
            EFail fr lbls' inp' -> EFail fr lbls' inp'
            ESuccess inp' -> go inp' lbls xs
        LookAhead xs'
          | EFail fr lbls' inp' <- go inp lbls xs' -> EFail fr lbls' inp'
          | otherwise -> go inp lbls xs
        LookAheadM consume xs'
          | consume -> go inp lbls (xs'++xs)
          | otherwise -> go inp lbls (LookAhead xs' : xs)
        LookAheadE consume xs'
          | consume -> go inp lbls (xs'++xs)
          | otherwise -> go inp lbls (LookAhead xs' : xs)
        Try a b ->
          case go inp lbls a of
            ESuccess inp' -> go inp' lbls     xs
            EFail {}      -> go inp  lbls (b++xs)

-- | Execute (run) the model.
-- First argument is all the input that will be used when executing
-- this decoder. It is used in this function to compare the expected
-- value with the actual value from the decoder functions.
-- The second argument is the model - the actions we will execute.
execute :: B.ByteString -> [Action] -> Binary.Get ()
execute inp acts0 = go 0 acts0 >> return ()
  where
  inp_len = B.length inp
  go _ [] = return ()
  go pos (x:xs) =
    case x of
      Actions a -> go pos (a++xs)
      GetByteString n -> do
        -- Run the operation in the Get monad...
        actual <- Binary.getByteString n
        let expected = B.take n . B.drop pos $ inp
        -- ... and compare that we got what we expected.
        when (actual /= expected) $ error $
          "execute(getByteString): actual /= expected at pos " ++ show pos ++
          ", got: " ++ show actual ++ ", expected: " ++ show expected
        go (pos+n) xs
      GetByteStringL n -> do
        -- Run the operation in the Get monad...
        actual <- L.toStrict <$> Binary.getLazyByteString (fromIntegral n)
        let expected = B.take n . B.drop pos $ inp
        -- ... and compare that we got what we expected.
        when (actual /= expected) $ error $
          "execute(getLazyByteString): actual /= expected at pos " ++ show pos ++
          ", got: " ++ show actual ++ ", expected: " ++ show expected
        go (pos+n) xs
      Skip n -> do
        Binary.skip n
        go (pos+n) xs
      BytesRead -> do
        pos' <- Binary.bytesRead
        if pos == fromIntegral pos'
          then go pos xs
          else error $ "execute(bytesRead): expected " ++
            show pos ++ " but got " ++ show pos'
      Fail -> fail "fail"
      Isolate n as -> do
        let str = B.take n (B.drop pos inp)
        _ <- Binary.isolate n (execute str as)
        when (willFail (inp_len - pos) [Isolate n as]) $
          error "expected isolate to fail"
        go (pos + n) xs
      Label str as -> do
        len <- Binary.label str (leg pos as)
        go (pos+len) xs
      LookAhead a -> do
        _ <- Binary.lookAhead (go pos a)
        go pos xs
      LookAheadM b a -> do
        let f True = Just <$> leg pos a
            f False = go pos a >> return Nothing
        len <- Binary.lookAheadM (f b)
        case len of
          Nothing -> go pos xs
          Just offset -> go (pos+offset) xs
      LookAheadE b a -> do
        let f True = Right <$> leg pos a
            f False = go pos a >> return (Left ())
        len <- Binary.lookAheadE (f b)
        case len of
          Left _ -> go pos xs
          Right offset -> go (pos+offset) xs
      Try a b -> do
        offset <- leg pos a <|> leg pos b
        go (pos+offset) xs
  leg pos t = do
    go pos t
    case actual_len (inp_len - pos) t of
      Nothing -> error "impossible: branch should have failed"
      Just offset -> return offset

gen_actions :: Bool -> Gen [Action]
gen_actions genFail = do
  acts <- sized (go False)
  return acts
  where
  go :: Bool -> Int -> Gen [Action]
  go     _ 0 = return []
  go inTry s = oneof $ [ do n <- choose (0,10)
                            (:) (GetByteString n) <$> go inTry (s-1)
                       , do n <- choose (0,10)
                            (:) (GetByteStringL n) <$> go inTry (s-1)
                       , do n <- choose (0,10)
                            (:) (Skip n) <$> go inTry (s-1)
                       , do (:) BytesRead <$> go inTry (s-1)
                       , do t1 <- go True (s `div` 2)
                            t2 <- go inTry (s `div` 2)
                            (:) (Try t1 t2) <$> go inTry (s `div` 2)
                       , do t <- go inTry (s`div`2)
                            (:) (LookAhead t) <$> go inTry (s-1)
                       , do t <- go inTry (s`div`2)
                            b <- arbitrary
                            (:) (LookAheadM b t) <$> go inTry (s-1)
                       , do t <- go inTry (s`div`2)
                            b <- arbitrary
                            (:) (LookAheadE b t) <$> go inTry (s-1)
                       , do t <- go inTry (s`div`2)
                            Positive n <- arbitrary :: Gen (Positive Int)
                            (:) (Label ("some label: " ++ show n) t) <$> go inTry (s-1)
                       , do t <- resize (s`div`2) (gen_isolate (genFail || inTry))
                            (:) t <$> go inTry (s-1)
                       ] ++ [frequency [(if inTry || genFail then 1 else 0, return [Fail])
                                        ,(9                               , go inTry s)]]

gen_isolate :: Bool -> Gen Action
gen_isolate genFail = gen_actions genFail >>= go
  where
  go t0 = do
    -- We can isolate the decoder with three different ranges;
    --  * give too few bytes -> isolate will fail
    --  * give exactly right amount of bytes -> isolate
    --    will succeed if the given decoder succeeds
    --  * give too many bytes -> isolate will fail
    -- Here we generate Isolates that belong to the different
    -- buckets.
    let t = t0
        tooFewBytes n = do
          n' <- choose (0, n)
          return (n',t)
        requiredBytes n = return (n,t)
        tooManyBytes n = do
          n' <- choose (n+1, n+10)
          return (n+n',t)
    let trees
          | Just n <- actual_len' t = oneof $
              [ requiredBytes n ] ++
              [ tooFewBytes n | genFail ] ++
              [ tooManyBytes n | genFail ]
          | otherwise = return (max_len t, t)
    (n,t') <- trees
    return (Isolate n t')


text:
@(
  util: lib.Util,
  user: Option[io.apibuilder.api.v0.models.User]
)

@doc.main(routes.DocController.playRoutesFile.url, user, Some("Play Union Types")) {

    API Builder provides support for declaring your own union types
    (sometimes referred to as sum or algebraic types). The basic idea
    is that you can express that a particular variable is one of a
    known set of types.

    As an example, in an ecommerce system, you might want to accept
    orders from both registered users (people who actually have a
    username and password with your service) and also from guest users
    (e.g. people who have never visited your application before). One
    way to model this is to define two types, Registered User and
    Guest User, a single union type User that can be either a
    Registered User or a Guest User, and then to model your order as
    having a User.

    Union types, especially when combined with expressive programming
    languages like Scala, can prove to be very useful and pragmatic
    tools for modeling problems like this.

    Over the wire, union types in the play 2_x clients are
    represented in one of two ways based on the presence of the discriminator field.

With a discriminator

    Union type is serialized as a Json Object with the discriminator
    field injected. For example, assume the discriminator field is set
    to "type":

    Example serializations:

    {
      "type": "registered_user",
      "guid":"f30dc64e-1793-4d59-aa47-71f000e06851",
      "email":"registered@@test.apibuilder.io"
    }

    {
      "type": "guest_user",
      "guid":"f30dc64e-1793-4d59-aa47-71f000e06851",
      "email":"guest@@test.apibuilder.io"
    }

With no discriminator

    Union type is serialized as a Json Object with one element. The
    key is the name of the type and the value is the Json
    serialization of the actual object.

    Example serializations:

    {
      "registered_user": {
        "guid":"f30dc64e-1793-4d59-aa47-71f000e06851",
        "email":"registered@@test.apibuilder.io"
      }
    }

    {
      "guest_user": {
        "guid":"f30dc64e-1793-4d59-aa47-71f000e06851",
        "email":"guest@@test.apibuilder.io"
      }
    }

    We also maintain example applications that demonstrate the use of
    the union types with and without discriminators. For more
    information:

 example w/ discriminator

 example w/out discriminator

}


text:
def main(request, response):
    response.headers.set(
        "Content-Security-Policy",
        "connect-src http://www.w3.org")
    response.headers.set(
        "X-Content-Security-Policy",
        "connect-src http://www.w3.org")
    response.headers.set("X-WebKit-CSP", "connect-src http://www.w3.org")
    return """<!DOCTYPE html>

    <title>CSP Test: csp_connect-src_cross-origin_xmlhttprequest</title>
    <link rel="author" title="Intel" href="http://www.intel.com"/>
    <link rel="help" href="http://www.w3.org/TR/2012/CR-CSP-20121115/#connect-src"/>
    <meta name="flags" content=""/>
    <meta name="assert" content="connect-src http://www.w3.org"/>
    <meta charset="utf-8"/>

 """


text:
CI configuration for Elasticsearch
==================================

Layout and Syntax
-----------------

CI is run by Jenkins at [elasticsearch-ci](https://elasticsearch-ci.elastic.co/).
Jobs live in the [jobs.t](jobs.t) directory, these are defined in YML using a syntax
simmilar to [JJB](https://elasticsearch-ci.elastic.co/view/Elasticsearch%20master/).
Macros are not allowed, and each job must be defined in its own file.
Merging of the default configuration is customized so unlike in standard JJB,
it recurses into YML objects.
Further (internal) documentation  on the setup
[is available](https://github.com/elastic/infra/blob/master/flavortown/jjbb/README.md)
.