text:
<?php

namespace Entity;

class Basket
{
   // ATTRIBUTS

   private $titre;
   private $produitId;
   private $configId;
   private $quantite;
   private $prix;

   // GETTERS ET SETTERS

   public function getTitre() {
       return $this->titre;
   }

   public function getProduitId() {
       return $this->produitId;
   }

   public function getConfigId() {
       return $this->configId;
   }

   public function getQuantite() {
       return $this->quantite;
   }

   public function getPrix() {
       return $this->prix;
   }

   public function setTitre($titre) {
       $this->titre = $titre;
       return $this;
   }

   public function setProduitId($produitId) {
       $this->produitId = $produitId;
       return $this;
   }

   public function setConfigId($configId) {
       $this->configId = $configId;
       return $this;
   }

   public function setQuantite($quantite) {
       $this->quantite = $quantite;
       return $this;
   }

   public function setPrix($prix) {
       $this->prix = $prix;
       return $this;
   }

    // AUTRES FONCTIONS

}

//    SPECIFICATION BASKET/PANIER :
//			0) Creer 3 fichiers :
//				- Entity\Basket.php 'attribys et Getters/Setters'
//				- Service\BasketManager.php vide pour l'instant
//				- Controller\BasketController.php vide pour l'instant
//
//			Dans le Service\BasketManager.php :
//
//			1) Faire une méthode putProductToBasket($produit) qui met en SESSION dans le PANIER les infos du produit choisi dans la partie boutique (hors config demi-mesure)
//				=> fonction qui sera utilisée par Anzor : lors du click sur "Mettre au panier", Anzor fera appel à cette fonction
//
//			2) Faire une méthode putConfigToBasket($config) qui met en SESSION dans le PANIER les infos de la config (cf. chemise demi-mesure) choisi dans la partie boutique config chemise demi-mesure
//				=> fonction qui sera utilisé par Guillaume : lors du click sur "Mettre au panier", Guillaume fera appel à cette fonction
//
//			3) Faire une méthode readBasket() qui va lire les infos en session et les ramènent (cf. return)
//				=> fonction utilisé par le controleur Controller\BasketController.php (lorsque le visiteur a cliqué sur "Panier" pour voir son panier), page
//					qui sera appelé en GET avec action=consult
//
//                      4) Dans le Controller\BasketController.php :
//                      a) appeler readBasket() et afficher dans un tableau les infos PANIER (on y accède avec action=consult dans le GET) en appelant la vue basket\index.html.twig
//                      b) Faire la vue basket\index.html.twig
//                      c) rajouter dans le tableau fait ci-dessus des liens la MODIFICATION et SUPPRESSION des produits du panier
//                      d) Gérer la SUPPRESSION d'un produit du panier
//                      e) Gérer la MODIF d'un produit du panier
//                      f) rajouter un bouton paiement qui va prendre les DATA en session et "aller vers le paiement"


text:
package org.jboss.resteasy.plugins.guice;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.plugins.server.netty.NettyJaxrsServer;
import org.jboss.resteasy.test.TestPortProvider;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Module;

public class GuiceProviderTest
{
   private static NettyJaxrsServer server;
   private static Dispatcher dispatcher;

   @BeforeClass
   public static void beforeClass() throws Exception
   {
      server = new NettyJaxrsServer();
      server.setPort(TestPortProvider.getPort());
      server.setRootResourcePath("/");
      server.start();
      dispatcher = server.getDeployment().getDispatcher();
   }

   @AfterClass
   public static void afterClass() throws Exception
   {
      server.stop();
      server = null;
      dispatcher = null;
   }

   @Test
   public void testProvider()
   {
      final Module module = new Module()
      {
         @Override
         public void configure(final Binder binder)
         {
            binder.bind(TestExceptionProvider.class);
            binder.bind(TestResource.class).to(TestResourceException.class);
         }
      };
      final ModuleProcessor processor = new ModuleProcessor(dispatcher.getRegistry(), dispatcher.getProviderFactory());
      processor.processInjector(Guice.createInjector(module));
      final TestResource resource = TestPortProvider.createProxy(TestResource.class, TestPortProvider.generateBaseUrl());
      Assert.assertEquals("exception", resource.getName());
      dispatcher.getRegistry().removeRegistrations(TestResource.class);
   }

   @Path("test")
   public interface TestResource
   {
      @GET
      public String getName();
   }

   public static class TestResourceException implements TestResource
   {
      @Override
      public String getName()
      {
         throw new TestException();
      }
   }

   public static class TestException extends RuntimeException
   {
   }

   @Provider
   public static class TestExceptionProvider implements ExceptionMapper<TestException>
   {
      @Override
      public Response toResponse(final TestException exception)
      {
         return Response.ok("exception").build();
      }
   }
}

redpajama_set_name: RedPajamaGithub


text:
using namespace NetworkImportingKit;
using namespace BuilderElementsCommonKit;

CNeuron::CNeuron(void)
	// Base class constructors invocation
	: CCmnElement()
	, CCmnBuilderElement()
	, CCmnDataFlow()
	, CCmnDataConnector()
	// ICommon  data fields initialization
	, numRef_(0)
{
	// IElement data fields initialization (declared in CCmnElement wrapper)
	elementType_ = ET_PROCESSOR;
	sysName_ = "Neuron";
	sysTitle_ = "Neuron";
	sysShortName_ = "N";
	// IBuilderElement data fields initialization (declared in CCmnBuilderElement wrapper)
	menuResourceId_ = IDR_ELEMENTS_POPUPS;
	subMenuResourceId_ = IDR_EP_NEURON_MENU_ITEM;
	layerBehaviour_ = false;
	elementTextureActive_ = _T("Neuron_Active");
	elementTexturePassive_ = _T("Neuron_Passive");
	imageWidth_ = SIZE_NEURON_IMAGE_DIAMETER;
	imageHeight_ = SIZE_NEURON_IMAGE_DIAMETER;
	shortNameOffset_ = 8;
	nameOffset_ = 0;
	// IDataFlow data fields initialization (declared in CCmnDataFlow wrapper)
	// IDataConnector data fields initialization (declared in CCmnDataConnector wrapper)
	// ILayerControl data fields initialization (declared in CCmnLayerControl wrapper)
}

CNeuron::~CNeuron(void)
{
}

// Custom tools
void CNeuron::PostInitialize()
{
	CCmnDataFlow::piElementData_->CreateFactory(
		DEFAULT_ELEMENT_DATA_LENGTH);
}

// IElement implementations section

// IBuilderElement implementations section

// IDataFlow implementations section
void CNeuron::ProcessElement()
{
	IDataConnector* piDataConnector = QueryTool<CNeuron, IDataConnector>::
		QueryInterface(this, IID_IDataConnector);

	IConnectionsFactory* piConnectionsFactory = piDataConnector->GetConnectionsFactory(DC_INPUTS_FACTORY);

	float preparedOutput = 0.0f;

	IConnectionsEnumerator* piConnectionsEnum = piConnectionsFactory->GetConnectionsEnumerator();
	for(bool hasConnections = piConnectionsEnum->SelectFirst(); hasConnections; hasConnections = piConnectionsEnum->SelectNext())
	{
		CConnection* pConnection = piConnectionsEnum->GetSelected();

		for (uint i = 0;i < pConnection->data_.GetDataLength();i++)
			preparedOutput += pConnection->data_.GetItemData(i) *
				pConnection->weights_.GetItemData(i);
	}
	piConnectionsEnum->Release();

	if (CCmnDataFlow::pActivateFunction_)
		preparedOutput = (*CCmnDataFlow::pActivateFunction_->pProcesTransferFunction_)
			(
				CCmnDataFlow::pActivateFunction_, preparedOutput
			);

	CCmnDataFlow::piElementData_->SetItemData(0, preparedOutput);

	piConnectionsFactory->Release();

	piDataConnector->Release();
}

// IDataConnector implementations section

// IStorageController implementations section
result CNeuron::Serialize(FILEDev& fileDev, bool loading)
{
	CCmnElement::Serialize(fileDev, loading);
	CCmnBuilderElement::Serialize(fileDev, loading);
	CCmnDataFlow::Serialize(fileDev, loading);
	CCmnDataConnector::Serialize(fileDev, loading);

	if (loading)
	{} else	{}

	return S_OK;
}

// ICommon implementations section
ulong CNeuron::AddRef()
{
	return ++numRef_;
}

ulong CNeuron::Release()
{
	--numRef_;

	if (numRef_ == 0)
	{
		delete this;
		return 0;
	}

	return numRef_;
}

String CNeuron::GetClassString() const
{
	return _T("CNeuron");
}

result CNeuron::QueryInterface(REFIID iid, void** ppObject)
{
	if (iid == IID_ICommon)
	{
		*ppObject = (ICommon*)(IElement*)this;
	}
	else if (iid == IID_IElement)
	{
		*ppObject = (IElement*)this;
	}
	else if (iid == IID_IBuilderElement)
	{
		*ppObject = (IBuilderElement*)this;
	}
	else if (iid == IID_IDataFlow)
	{
		*ppObject = (IDataFlow*)this;
	}
	else if (iid == IID_IDataConnector)
	{
		*ppObject = (IDataConnector*)this;
	}
	else if (iid == IID_IStorageController)
	{
		*ppObject = (IStorageController*)(CCmnElement*)this;
	}
	else
	{
		*ppObject = NULL;
		return E_NOINTERFACE;
	}

	((ICommon*)(IElement*)this)->AddRef();
	return S_OK;
}


text:
from . import ping
from . import sitemaps


text:
#include <stdio.h>

#include "detector_defines.h"
#include "util_functions.h"
#include "universal_copy.h"
#include "cl_err.h"
#include "cl_utils.h"
#include "../gpu_check_utils.h"

#include "copy_canary_cl_buffer.h"

static cl_mem create_clmem_copies(cl_context kern_ctx,
        cl_command_queue cmd_queue, uint32_t num_cl_mem, void **buffer_ptrs,
        const cl_event *evt, cl_event *events, cl_event *mend_events)
{
    cl_int cl_err;
    cl_mem clmem_canary_copies = clCreateBuffer(kern_ctx, 0,
            POISON_FILL_LENGTH*POISON_REGIONS*num_cl_mem, 0, &cl_err);
    check_cl_error(__FILE__, __LINE__, cl_err);
    for(uint32_t i = 0; i < num_cl_mem; i++)
    {
        cl_memobj *m1 = cl_mem_find(get_cl_mem_alloc(), buffer_ptrs[i]);
        if(m1 == NULL)
        {
            det_fprintf(stderr, "failure to find cl_memobj at %s:%d.\n", __FILE__,
                    __LINE__);
            exit(-1);
        }

        uint32_t index = i * POISON_REGIONS;
        uint32_t offset = m1->size;
#ifdef UNDERFLOW_CHECK
        cl_buffer_copy(cmd_queue, m1->main_buff, clmem_canary_copies,
                0, index*POISON_FILL_LENGTH,
                POISON_FILL_LENGTH, 1, evt, &events[index]);

        index++;
        offset += POISON_FILL_LENGTH;
#endif

        cl_buffer_copy(cmd_queue, m1->main_buff, clmem_canary_copies,
                offset, index*POISON_FILL_LENGTH,
                POISON_FILL_LENGTH, 1, evt, &events[index]);

        cl_event copy_finish;
        clEnqueueMarkerWithWaitList(cmd_queue, POISON_REGIONS, &events[POISON_REGIONS*i], &copy_finish);

        mend_this_canary(kern_ctx, cmd_queue, m1->handle, copy_finish,
                &mend_events[i]);
    }
    return clmem_canary_copies;
}

static void *create_svm_copies(cl_context kern_ctx, cl_command_queue cmd_queue,
        uint32_t num_svm, void **buffer_ptrs, const cl_event *evt,
        cl_event *events, cl_event *mend_events)
{
    void *svm_canary_copies;
#ifdef CL_VERSION_2_0
    cl_svm_memobj *m1;
    svm_canary_copies = clSVMAlloc(kern_ctx, CL_MEM_READ_WRITE,
            POISON_REGIONS*POISON_FILL_LENGTH*num_svm, 0);
    if (svm_canary_copies == NULL)
    {
        det_fprintf(stderr, "Failed to SVMAlloc at %s:%d\n", __FILE__,
                __LINE__);
        exit(-1);
    }
    m1 = cl_svm_mem_find(get_cl_svm_mem_alloc(), svm_canary_copies);
    if (m1 == NULL)
    {
        det_fprintf(stderr, "failure to find cl_svm_memobj at %s:%d.\n", __FILE__,
                __LINE__);
        exit(-1);
    }
    m1->detector_internal_buffer = 1;

    for(uint32_t i = 0; i < num_svm; i++)
    {
        m1 = cl_svm_mem_find(get_cl_svm_mem_alloc(), buffer_ptrs[i]);
        if(m1 == NULL)
        {
            det_fprintf(stderr, "failure to find cl_svm_memobj at %s:%d.\n", __FILE__,
                    __LINE__);
            exit(-1);
        }

        char *base_ptr = (char*)m1->main_buff;
        uint32_t offset = m1->size;
        uint32_t index = i * POISON_REGIONS;
        char *canary_ptr = base_ptr;
        char *map_ptr = ((char*)svm_canary_copies)+(index*POISON_FILL_LENGTH);

        cl_int cl_err;
#ifdef UNDERFLOW_CHECK
        cl_err = clEnqueueSVMMemcpy(cmd_queue, CL_NON_BLOCKING, map_ptr,
                canary_ptr, POISON_FILL_LENGTH, 1, evt, &events[index]);
        check_cl_error(__FILE__, __LINE__, cl_err);

        offset += POISON_FILL_LENGTH;
        index += 1;
#endif

        canary_ptr = base_ptr + offset;
        map_ptr = ((char*)svm_canary_copies)+(index*POISON_FILL_LENGTH);

        cl_err = clEnqueueSVMMemcpy(cmd_queue, CL_NON_BLOCKING, map_ptr,
                canary_ptr, POISON_FILL_LENGTH, 1, evt, &events[index]);
        check_cl_error(__FILE__, __LINE__, cl_err);

        cl_event copy_finish;
        clEnqueueMarkerWithWaitList(cmd_queue, POISON_REGIONS, &events[POISON_REGIONS*i], &copy_finish);

        mend_this_canary(kern_ctx, cmd_queue, m1->handle, copy_finish, &mend_events[i]);
    }
#else
    svm_canary_copies = NULL;
    (void)kern_ctx;
    (void)cmd_queue;
    (void)num_svm;
    (void)buffer_ptrs;
    (void)evt;
    (void)events;
    (void)mend_events;
#endif
    return svm_canary_copies;
}

static void ** create_svm_ptr_copies(cl_context kern_ctx,
        cl_command_queue cmd_queue, uint32_t num_svm, void **buffer_ptrs,
        void **ret_clmem, const cl_event *evt, cl_event *events)
{
    void **ret_poison_ptrs;
    if (num_svm == 0)
    {
        if (ret_clmem != NULL)
            *ret_clmem = NULL;
        return NULL;
    }

#ifdef CL_VERSION_2_0
    cl_int cl_err;
    if (ret_clmem == NULL)
        return NULL;

    ret_poison_ptrs = calloc(sizeof(void*), POISON_REGIONS*num_svm);
    cl_mem temp_ptr = clCreateBuffer(kern_ctx, 0, sizeof(void*) * POISON_REGIONS*num_svm, 0,
            &cl_err);
    *ret_clmem = (void*)temp_ptr;
    check_cl_error(__FILE__, __LINE__, cl_err);

    for(uint32_t i = 0; i < num_svm; i++)
    {
        cl_svm_memobj *m1 = cl_svm_mem_find(get_cl_svm_mem_alloc(),
                buffer_ptrs[i]);
        if(m1 == NULL)
        {
            det_fprintf(stderr, "failure to find cl_svm_memobj.\n");
            exit(-1);
        }

        char *ptr_base = (char *)m1->main_buff;
        uint32_t index = i * POISON_REGIONS;
        uint32_t offset = m1->size;
#ifdef UNDERFLOW_CHECK
        ret_poison_ptrs[index] = ptr_base;
        index++;
        offset += POISON_FILL_LENGTH;
#endif
        ret_poison_ptrs[index] = ptr_base + offset;
    }
    cl_err = clEnqueueWriteBuffer(cmd_queue, *ret_clmem, CL_NON_BLOCKING,
            0, sizeof(void*) * POISON_REGIONS*num_svm, ret_poison_ptrs, 1, evt,
            &events[0]);
    check_cl_error(__FILE__, __LINE__, cl_err);
    // We only need one event from this one.
    for (uint32_t i = 1; i < POISON_REGIONS*num_svm; i++)
        events[i] = create_complete_user_event(kern_ctx);
#else
    ret_poison_ptrs = NULL;
    (void)cmd_queue;
    (void)buffer_ptrs;
    (void)ret_clmem;
    (void)evt;
    for (uint32_t i = 0; i < POISON_REGIONS*num_svm; i++)
        events[i] = create_complete_user_event(kern_ctx);
#endif
    return ret_poison_ptrs;
}

static cl_event perform_cl_buffer_checks(cl_context kern_ctx,
        cl_command_queue cmd_queue, uint32_t num_cl_mem, uint32_t num_svm,
        uint32_t total_buffs, cl_mem clmem_canary_copies,
        void *svm_canary_copies, int copy_svm_ptrs, cl_event *init_evts,
        cl_event *mend_events, cl_mem result)
{
    size_t global_work[3] = {POISON_REGIONS*poisonWordLen, 1, 1};
    size_t local_work[3] = {256, 1, 1};
    size_t max_work_items[3] = {1, 1, 1};
    global_work[0] *= POISON_REGIONS*total_buffs;

    uint32_t buff_end = num_cl_mem * POISON_REGIONS*poisonWordLen;
    uint32_t svm_end = buff_end + num_svm * POISON_REGIONS*poisonWordLen;
    unsigned len_in_words = POISON_REGIONS*poisonWordLen;

    cl_kernel check_kern;
#ifdef CL_VERSION_2_0
    // No way to be in this "if" if CL_VERSION != 2.0
    if (num_svm > 0)
    {
        check_kern = get_canary_check_kernel(kern_ctx);
        if (copy_svm_ptrs)
        {
            cl_set_arg_and_check(check_kern, 5, sizeof(cl_mem),
                    &svm_canary_copies);
        }
        else
            cl_set_svm_arg_and_check(check_kern, 5, svm_canary_copies);
        cl_set_arg_and_check(check_kern, 6, sizeof(void*), (void*) &result);
    }
    else
#else
    (void)svm_canary_copies;
    (void)copy_svm_ptrs;
#endif
    {
        check_kern = get_canary_check_kernel_no_svm(kern_ctx);
        cl_set_arg_and_check(check_kern, 5, sizeof(void*), (void*) &result);
    }
    cl_set_arg_and_check(check_kern, 0, sizeof(unsigned), &len_in_words);
    cl_set_arg_and_check(check_kern, 1, sizeof(unsigned), &buff_end);
    cl_set_arg_and_check(check_kern, 2, sizeof(unsigned), &svm_end);
    cl_set_arg_and_check(check_kern, 3, sizeof(unsigned), &poisonFill_32b);
    cl_set_arg_and_check(check_kern, 4, sizeof(cl_mem), &clmem_canary_copies);

    cl_device_id dev_id;
    clGetContextInfo(kern_ctx, CL_CONTEXT_DEVICES, sizeof(cl_device_id), &dev_id, NULL);
    clGetKernelWorkGroupInfo(check_kern, dev_id, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t), max_work_items, NULL);

    local_work[0] = max_work_items[0];

    cl_event kern_end;
    launchOclKernelStruct ocl_args = setup_ocl_args(cmd_queue, check_kern,
            1, NULL, global_work, local_work, POISON_REGIONS*total_buffs + 1, init_evts,
            &kern_end);
    cl_int cl_err = runNDRangeKernel( &ocl_args );
    check_cl_error(__FILE__, __LINE__, cl_err);

    if(global_tool_stats_flags & STATS_CHECKER_TIME)
    {
        clFinish(cmd_queue);
        uint64_t times[4];
        populateKernelTimes(&kern_end, &times[0], &times[1], &times[2],
                &times[3]);
        add_to_kern_runtime((times[3] - times[2]) / 1000);
    }

    cl_event finish;
    if(!get_error_envvar())
    {
#ifdef CL_VERSION_1_2
        cl_event mend_finish;
        cl_err = clEnqueueMarkerWithWaitList(cmd_queue, total_buffs,
                mend_events, &mend_finish);
        check_cl_error(__FILE__, __LINE__, cl_err);
        cl_event evt_list[] = {mend_finish, kern_end};
        cl_err = clEnqueueMarkerWithWaitList(cmd_queue, 2, evt_list, &finish);
#else
        (void)mend_events;
        cl_err = clEnqueueMarker(cmd_queue, &finish);
#endif
        check_cl_error(__FILE__, __LINE__, cl_err);
    }
    else
        finish = kern_end;
    return finish;
}

/*
 * launch checker kernel for cl_mem and svm buffers
 */
void verify_cl_buffer_copy(cl_context kern_ctx, cl_command_queue cmd_queue,
        uint32_t num_cl_mem, uint32_t num_svm, void **buffer_ptrs,
        int copy_svm_ptrs, kernel_info *kern_info, uint32_t *dupe,
        const cl_event *evt, cl_event *ret_evt)
{
    cl_int cl_err;
    uint32_t total_buffs = num_cl_mem + num_svm;

    if(total_buffs == 0)
    {
        if (ret_evt != NULL)
            *ret_evt = create_complete_user_event(kern_ctx);
        return;
    }

    cl_mem clmem_canary_copies = NULL;
    void *svm_canary_copies = NULL;
    void **poison_pointers = NULL;

    cl_event *events = calloc(sizeof(cl_event), (POISON_REGIONS*total_buffs+1));
    cl_event *mend_events = calloc(sizeof(cl_event), (total_buffs));

    if (num_cl_mem > 0)
    {
        clmem_canary_copies = create_clmem_copies(kern_ctx, cmd_queue,
                num_cl_mem, buffer_ptrs, evt, events, mend_events);
    }
    else
    {
        clmem_canary_copies = clCreateBuffer(kern_ctx, 0, 1, 0, &cl_err);
        check_cl_error(__FILE__, __LINE__, cl_err);
    }

    uint32_t first_svm_evt_index = POISON_REGIONS*num_cl_mem;
    if (num_svm > 0 && copy_svm_ptrs)
    {
        poison_pointers = create_svm_ptr_copies(kern_ctx, cmd_queue,
                num_svm, &(buffer_ptrs[num_cl_mem]), &svm_canary_copies,
                evt, &(events[first_svm_evt_index]));
        for (uint32_t i = num_cl_mem; i < total_buffs; i++)
            mend_events[i] = create_complete_user_event(kern_ctx);
    }
    else if (num_svm > 0)
    {
        svm_canary_copies = create_svm_copies(kern_ctx, cmd_queue, num_svm,
                &(buffer_ptrs[num_cl_mem]), evt, &(events[first_svm_evt_index]),
                &(mend_events[num_cl_mem]));
    }

    uint32_t finish_evt_index = POISON_REGIONS*total_buffs;
    cl_mem result = create_result_buffer(kern_ctx, cmd_queue, total_buffs,
            &events[finish_evt_index]);

    cl_event kern_end = perform_cl_buffer_checks(kern_ctx, cmd_queue,
            num_cl_mem, num_svm, total_buffs, clmem_canary_copies,
            svm_canary_copies, copy_svm_ptrs, events, mend_events, result);

    for (uint32_t i = 0; i < total_buffs; i++)
    {
        uint32_t evt_index = POISON_REGIONS*i;
        clReleaseEvent(events[evt_index]);
#ifdef UNDERFLOW_CHECK
        clReleaseEvent(events[evt_index+1]);
#endif
        clReleaseEvent(mend_events[i]);
    }
    clReleaseEvent(events[finish_evt_index]);
    free(events);
    free(mend_events);

    cl_event read_result;
    int * first_change = get_change_buffer(cmd_queue, total_buffs, result, 1,
            &kern_end, &read_result);

    if(ret_evt)
        *ret_evt = read_result;

    analyze_check_results(cmd_queue, read_result, kern_info, total_buffs,
            buffer_ptrs, svm_canary_copies, copy_svm_ptrs, poison_pointers,
            first_change, dupe);

    clReleaseEvent(kern_end);
    clReleaseMemObject(result);
    clReleaseMemObject(clmem_canary_copies);
}


text:
#include <sstream>
#include <sys/time.h>
#include "Zerocoin.h"

namespace libzerocoin {

//Accumulator class
Accumulator::Accumulator(const AccumulatorAndProofParams* p, const CoinDenomination d): params(p), denomination(d) {
	if (!(params->initialized)) {
		throw ZerocoinException("Invalid parameters for accumulator");
	}

	this->value = this->params->accumulatorBase;
}

Accumulator::Accumulator(const Params* p, const CoinDenomination d) {
	this->params = &(p->accumulatorParams);
	this->denomination = d;

	if (!(params->initialized)) {
		throw ZerocoinException("Invalid parameters for accumulator");
	}

	this->value = this->params->accumulatorBase;
}

void Accumulator::accumulate(const PublicCoin& coin) {
	// Make sure we're initialized
	if(!(this->value)) {
		throw ZerocoinException("Accumulator is not initialized");
	}

	if(this->denomination != coin.getDenomination()) {
		//std::stringstream msg;
		std::string msg;
		msg = "Wrong denomination for coin. Expected coins of denomination: ";
		msg += this->denomination.getValue();
		msg += ". Instead, got a coin of denomination: ";
		msg += coin.getDenomination().getValue();
		throw ZerocoinException(msg);
	}

	if(coin.validate()) {
		struct timeval tv0, tv1;
		double elapsed;
		// Compute new accumulator = "old accumulator"^{element} mod N
		gettimeofday(&tv0, NULL);
		this->value = this->value.pow_mod(coin.getValue(), this->params->accumulatorModulus);
		gettimeofday(&tv1, NULL);
		elapsed = (tv1.tv_sec  - tv0.tv_sec) +
		          (tv1.tv_usec - tv0.tv_usec) / 1e6;
		cout << "GNOSIS DEBUG: accumulate time: " << elapsed << endl;

	} else {
		throw ZerocoinException("Coin is not valid");
	}
}

CoinDenomination Accumulator::getDenomination() const {
	return this->denomination;
}

Bignum Accumulator::getValue() const {
	return this->value;
}

Accumulator& Accumulator::operator += (const PublicCoin& c) {
	this->accumulate(c);
	return *this;
}

bool Accumulator::operator == (const Accumulator rhs) const {
	return this->value == rhs.value;
}

//AccumulatorWitness class
AccumulatorWitness::AccumulatorWitness(const Params* p,
                                       const Accumulator& checkpoint, const PublicCoin coin): params(p), witness(checkpoint), element(coin) {
}

void AccumulatorWitness::AddElement(const PublicCoin& c) {
	if(element != c) {
		witness += c;
	}
}

Bignum AccumulatorWitness::getValue() const {
	return this->witness.getValue();
}

bool AccumulatorWitness::VerifyWitness(const Accumulator& a, const PublicCoin &publicCoin) const {
	Accumulator temp(witness);
	temp += element;
	return (temp == a && this->element == publicCoin);
}

AccumulatorWitness& AccumulatorWitness::operator +=(
    const PublicCoin& rhs) {
	this->AddElement(rhs);
	return *this;
}

} /* namespace libzerocoin */


text:
package es.voghdev.prjrenderers.ui.presenter;

import android.content.Context;

import java.util.Collections;
import java.util.List;
import java.util.Random;

import javax.inject.Inject;

import es.voghdev.prjrenderers.R;
import es.voghdev.prjrenderers.datasource.GetCustomers;
import es.voghdev.prjrenderers.datasource.GetVideos;
import es.voghdev.prjrenderers.global.model.Customer;
import es.voghdev.prjrenderers.global.model.Video;
import es.voghdev.prjrenderers.ui.renderer.model.CustomerEntity;
import es.voghdev.prjrenderers.ui.renderer.model.Entity;
import es.voghdev.prjrenderers.ui.renderer.model.VideoEntity;

public class VideoListPresenterImpl extends VideoListPresenter {

    private final Context mContext;
    private GetVideos videosInteractor;
    private GetCustomers customersInteractor;
    private List<Customer> customers = Collections.emptyList();

    public VideoListPresenterImpl(Context context, GetVideos videosInteractor, GetCustomers customersInteractor) {
        this.mContext = context;
        this.videosInteractor = videosInteractor;
        this.customersInteractor = customersInteractor;
    }

    @Override
    public void onItemSelected(int position) {

    }

    @Override
    public void initialize() {
        view.showLoading();

        customersInteractor.getCustomersAsync(new GetCustomers.Listener() {
            @Override
            public void onCustomersAvailable(final List<Customer> list) {
                customers = list;
            }

            @Override
            public void onError(Exception e) {
                view.showError(e);
            }
        });

        videosInteractor.getVideosAsync(new GetVideos.Listener() {
            @Override
            public void onVideoListReceived(List<Video> list) {
                videos = list;
                view.showVideoList(list);
                view.hideLoading();
            }

            @Override
            public void onVideoListError(Exception e) {
                view.showError(e);
                view.hideLoading();
            }
        });
    }

    @Override
    public void resume() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void onRowClicked(Entity entity) {
        if(entity instanceof VideoEntity)
            view.showVideoClickedMessage( ((VideoEntity)entity).getVideo() );
        else if(entity instanceof CustomerEntity)
            view.showCustomerClickedMessage( ((CustomerEntity)entity).getCustomer() );
    }

    @Override
    public void onThumbnailClicked(Entity entity) {
        VideoEntity videoEntity = (VideoEntity)entity;
        videoEntity.getVideo().addCustomer( getRandomCustomer() );
        view.highlightVideo( ((VideoEntity)entity).getVideo() );
        view.showVideoList(videos);
    }

    private Customer getRandomCustomer(){
        if(customers.isEmpty()) {
            return generateDummyCustomer();
        }

        int rnd = new Random().nextInt(customers.size()-1);

        return customers.get(rnd);
    }

    private Customer generateDummyCustomer(){
        Customer c = new Customer();
        c.setId(999);
        c.setName( mContext.getString(R.string.dummy_customer, c.getId()) );
        return c;
    }
}


text:
package com.github.kickshare.security.permission;

/**
 * @author Jan.Kucera
 * @since 6.7.2017
 */
public final class PermissionConstants {
    public static final String IS_MEMBER = "isMember";
    public static final String IS_OWNER = "isOwner";

    public static final String ADMIN_AUTHORITY = "ADMIN";
    //@TODO - consider rename to loader
    public static final String LEADER_AUTHORITY = "CREATE_GROUP";

    private PermissionConstants() {}
}


text:
drop table if exists person;
create table person (
id int,
name varchar(32),
billing_address_id int,
shipping_address_id int,
room_id int
);

drop table if exists address;
create table address (
id int,
state varchar(32),
city varchar(32),
phone1_id int,
phone2_id int,
addr_type int,
caution varchar(64)
);

drop table if exists zip;
create table zip (
state varchar(32),
city varchar(32),
zip_code int
);

drop table if exists phone;
create table phone (
id int,
phone varchar(32),
area_code varchar(2)
);

drop table if exists pet;
create table pet (
id int,
owner_id int,
name varchar(32),
room_id int
);

drop table if exists state_bird;
create table state_bird (
state varchar(32),
bird varchar(32)
);

drop table if exists room;
create table room (
room_id int,
room_name varchar(32)
);

drop table if exists brand;
create table brand (
id int,
name varchar(32)
);

-- make columns case sensitive
drop table if exists product;
create table product (
"product_id" int,
"product_name" varchar(32),
brand_id int
);

insert into room (room_id, room_name) values (31, 'Sakura');
insert into room (room_id, room_name) values (32, 'Ume');
insert into room (room_id, room_name) values (33, 'Tsubaki');

insert into pet (id, owner_id, name, room_id) values (100, 1, 'Kotetsu', 32);
insert into pet (id, owner_id, name, room_id) values (101, 1, 'Chien', null);
insert into pet (id, owner_id, name, room_id) values (102, 3, 'Dodo', 31);

insert into phone (id, phone, area_code) values (1000, '0123', '11');
insert into phone (id, phone, area_code) values (1001, '4567', '33');
insert into phone (id, phone, area_code) values (1002, '8888', '55');
insert into phone (id, phone, area_code) values (1003, '9999', '77');

insert into state_bird (state, bird) values ('IL', 'Cardinal');
insert into state_bird (state, bird) values ('CA', 'California Valley Quail');
insert into state_bird (state, bird) values ('TX', 'Mockingbird');

insert into zip (state, city, zip_code) values ('IL', 'Chicago', 81);
insert into zip (state, city, zip_code) values ('CA', 'San Francisco', 82);
insert into zip (state, city, zip_code) values ('CA', 'Los Angeles', 83);
insert into zip (state, city, zip_code) values ('TX', 'Dallas', 84);

insert into address (id, state, city, phone1_id, phone2_id, addr_type, caution) values (10, 'IL', 'Chicago', 1000, 1001, 0, null);
insert into address (id, state, city, phone1_id, phone2_id, addr_type, caution) values (11, 'CA', 'San Francisco', 1002, null, 1, 'Has a big dog.');
insert into address (id, state, city, phone1_id, phone2_id, addr_type, caution) values (12, 'CA', 'Los Angeles', null, null, 1, 'No door bell.');
insert into address (id, state, city, phone1_id, phone2_id, addr_type, caution) values (13, 'TX', 'Dallas', 1003, 1001, 0, null);

insert into person (id, name, billing_address_id, shipping_address_id, room_id) values (1, 'John', 10, 11, 33);
insert into person (id, name, billing_address_id, shipping_address_id, room_id) values (2, 'Rebecca', 12, null, null);
insert into person (id, name, billing_address_id, shipping_address_id, room_id) values (3, 'Keith', null, 13, null);

insert into brand (id, name) values (1, 'alpha');

insert into product ("product_id", "product_name", brand_id) values (10, 'alpha', 1);
insert into product ("product_id", "product_name", brand_id) values (20, 'beta', 1);


text:
package loon.action;

import loon.utils.ArrayMap;
import loon.utils.CollectionUtils;
import loon.utils.TArray;

public class Actions {

	final private ArrayMap actions;

	Actions() {
		this.actions = new ArrayMap(CollectionUtils.INITIAL_CAPACITY);
	}

	public void clear() {
		actions.clear();
	}

	public TArray<ActionBind> keys() {
		TArray<ActionBind> list = new TArray<ActionBind>(actions.size());
		for (int i = 0; i < actions.size(); i++) {
			Object key = actions.getKey(i);
			if (key != null && key instanceof ActionBind) {
				list.add((ActionBind) key);
			}
		}
		return list;
	}

	public boolean stopNames(ActionBind k, String name) {
		ActionElement eles = (ActionElement) actions.getValue(k);
		if (eles == null || name == null) {
			return true;
		}
		TArray<ActionEvent> eves = eles.actions;
		if (eves == null || eves.size == 0) {
			return true;
		}
		int count = 0;
		for (int i = 0, size = eves.size; i < size; i++) {
			ActionEvent e = eves.get(i);
			if (e != null && name.trim().toLowerCase().equals(e.getName())) {
				e.kill();
				count++;
			}
		}
		return count > 0;
	}

	public boolean stopTags(ActionBind k, Object tag) {
		ActionElement eles = (ActionElement) actions.getValue(k);
		if (eles == null || tag == null) {
			return true;
		}
		TArray<ActionEvent> eves = eles.actions;
		if (eves == null || eves.size == 0) {
			return true;
		}
		int count = 0;
		for (int i = 0, size = eves.size; i < size; i++) {
			ActionEvent e = eves.get(i);
			if (e != null && (tag.equals(e.getTag()) || tag == e.getTag())) {
				e.kill();
				count++;
			}
		}
		return count > 0;
	}

	public boolean isCompleted(ActionBind k) {
		ActionElement eles = (ActionElement) actions.getValue(k);
		if (eles == null) {
			return true;
		}
		TArray<ActionEvent> eves = eles.actions;
		if (eves == null || eves.size == 0) {
			return true;
		}
		int count = 0;
		for (int i = 0, size = eves.size; i < size; i++) {
			ActionEvent e = eves.get(i);
			if (e != null && e.isComplete()) {
				count++;
			}
		}
		return count == eves.size;
	}

	public boolean containsKey(ActionBind k) {
		return actions.containsKey(k);
	}

	public boolean containsValue(ActionEvent v) {
		return actions.containsValue(v);
	}

	public void addAction(ActionEvent action, ActionBind actObject, boolean paused) {
		ActionElement element = (ActionElement) actions.get(actObject);
		if (element == null) {
			element = new ActionElement(actObject, paused);
			actions.put(actObject, element);
		}
		element.actions.add(action);
		action.start(actObject);
	}

	private void deleteElement(ActionElement element) {
		element.actions.clear();
		actions.remove(element.key);
	}

	public void removeAllActions(ActionBind actObject) {
		if (actObject == null) {
			return;
		}
		Object o = actions.get(actObject);
		if (o != null) {
			ActionElement element = (ActionElement) o;
			if (element != null) {
				element.actions.clear();
				deleteElement(element);
			}
		}
	}

	private void removeAction(int index, ActionElement element) {
		element.actions.removeIndex(index);
		if (element.actionIndex >= index) {
			element.actionIndex--;
		}
		if (element.actions.isEmpty()) {
			deleteElement(element);
		}
	}

	public int getCount() {
		return actions.size();
	}

	public void removeAction(Object tag, ActionBind actObject) {
		ActionElement element = (ActionElement) actions.get(actObject);
		if (element != null) {
			if (element.actions != null) {
				int limit = element.actions.size;
				for (int i = 0; i < limit; i++) {
					ActionEvent a = element.actions.get(i);
					if (a.getTag() == tag && a.getOriginal() == actObject) {
						removeAction(i, element);
					}
				}
			}
		}
	}

	public void removeAction(ActionEvent action) {
		if (action == null) {
			return;
		}
		ActionElement element = (ActionElement) actions.get(action.getOriginal());
		if (element != null) {
			int i = element.actions.indexOf(action);
			if (i != -1) {
				removeAction(i, element);
			}
		}
	}

	public ActionEvent getAction(Object tag, ActionBind actObject) {
		ActionElement element = (ActionElement) actions.get(actObject);
		if (element != null) {
			if (element.actions != null) {
				int limit = element.actions.size;
				for (int i = 0; i < limit; i++) {
					ActionEvent a = element.actions.get(i);
					if (a.getTag() == tag)
						return a;
				}
			}
		}
		return null;
	}

	public void update(long elapsedTime) {
		int size = actions.size();
		for (int i = size - 1; i > -1; --i) {
			ActionElement currentTarget = (ActionElement) actions.get(i);
			if (currentTarget == null) {
				continue;
			}
			synchronized (currentTarget) {
				if (!currentTarget.paused) {
					for (currentTarget.actionIndex = 0; currentTarget.actionIndex < currentTarget.actions.size; currentTarget.actionIndex++) {
						currentTarget.currentAction = currentTarget.actions.get(currentTarget.actionIndex);
						if (currentTarget.currentAction == null) {
							continue;
						}
						if (!currentTarget.currentAction.isInit) {
							currentTarget.currentAction.isInit = true;
							currentTarget.currentAction.onLoad();
						}
						currentTarget.currentAction.step(elapsedTime);
						if (currentTarget.currentAction.isComplete()) {
							currentTarget.currentAction.stop();
							removeAction(currentTarget.currentAction);
						}
						currentTarget.currentAction = null;
					}
				}
				if (currentTarget.actions.isEmpty()) {
					deleteElement(currentTarget);
				}
			}
		}
	}

	public void paused(boolean pause, ActionBind actObject) {
		ActionElement element = (ActionElement) actions.get(actObject);
		if (element != null) {
			element.paused = pause;
		}
	}

	public void stop(ActionBind actObject) {
		ActionElement element = (ActionElement) actions.get(actObject);
		if (element != null) {
			element.paused = true;
		}
	}

	public void start(ActionBind actObject) {
		ActionElement element = (ActionElement) actions.get(actObject);
		if (element != null) {
			element.paused = false;
		}
	}

	public void start() {
		for (int i = 0; i < actions.size(); i++) {
			((ActionElement) actions.get(i)).paused = false;
		}
	}

	public void stop() {
		for (int i = 0; i < actions.size(); i++) {
			((ActionElement) actions.get(i)).paused = true;
		}
	}

	final static class ActionElement {

		private ActionBind key;

		private int actionIndex;

		private boolean paused;

		private TArray<ActionEvent> actions;

		private ActionEvent currentAction;

		public ActionElement(ActionBind k, boolean v) {
			this.actions = new TArray<ActionEvent>(CollectionUtils.INITIAL_CAPACITY);
			this.key = k;
			this.paused = v;
		}
	}
}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Example
 *
 * This is an example of a few basic user interaction methods you could use
 * all done with a hardcoded array.
 *
 * @package		CodeIgniter
 * @subpackage	Rest Server
 * @category	Model
 * @author		Riccardo
 * @link		--
*/

class Stock extends CI_Model {

    function __construct()
    {
        parent::__construct();
        define("STOCKFILE", "/ariston/server/stockwithflag.csv");
    }
/* STOCKFILE FORMAT
 * { name: 'chiave', type: 'string' },
 * { name: 'disponibilita', type: 'string' },
 * { name: 'dispimmediata', type: 'string' },
 * { name: 'esistenza', type: 'string' },
 * { name: 'data', type: 'string' },
 * { name: 'alternativo', type: 'string' },
 * { name: 'soldout', type: 'number' }
*/
    function queryStock($var)
    {
    	$assoc = [];
    	$queryString = $var["code"].".".$var["shade"];
		$command = "awk -F',' '{ if ($1 ~ /".$queryString."/)  { print $0 } }' ".$_SERVER['DOCUMENT_ROOT'].STOCKFILE;
		log_message('error', 'command: '.var_export($command,TRUE));
		$res = shell_exec($command);
		log_message('error', 'command output: '.var_export($res,TRUE));

		if ($res){
			$array = str_getcsv($res);
			$codeShade = explode(".",$array[0]);
			$assoc['code'] = $codeShade[0];
			$assoc['shade'] = $codeShade[1];
			$assoc['availability'] = $array[1];
			$assoc['immavailability'] = $array[2];
			$assoc['existence'] = $array[3];
			$assoc['date'] = $array[4];
			$assoc['substitute'] = $array[5];
			$assoc['soldout'] = $array[6];
		}
        return $assoc;
    }
}


text:
from django.db import models

class Course(models.Model):
    name = models.CharField(max_length=255)

class Theme(models.Model):
    name = models.CharField(max_length=255)
    course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='themes')

class Document(models.Model):
    name = models.CharField(max_length=255)
    content = models.TextField()
    course = models.ManyToManyField(Course, related_name='documents')

class Question(models.Model):
    text = models.TextField()
    theme = models.ForeignKey(Theme, on_delete=models.CASCADE, related_name='questions')

# pretty dirty
# better practice should be storing only link to document and help position
class Help(models.Model):
    name = models.CharField(max_length=255)
    content = models.TextField()
    question = models.ForeignKey(Question, related_name='help')

class Option(models.Model):
    text = models.TextField()
    right = models.BooleanField()
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='options')


text:
Object.defineProperty(exports,"__esModule",{value:true});exports.default=

defaultrequestLoggerPublic;var _debug=require('../_configuration/debug');var _log=require('./log');var _log2=_interopRequireDefault(_log);var _matchInDepth=require('./matchInDepth');var _matchInDepth2=_interopRequireDefault(_matchInDepth);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function defaultrequestLoggerPublic(requestAndResponse){
var logLevel=null;

if((0,_matchInDepth2.default)(requestAndResponse,_debug.debugWriteToLogServerRequestPublic))
logLevel='info';

if(logLevel)_log2.default.log(logLevel,'Public request',requestAndResponse);
}
//# sourceMappingURL=defaultRequestLoggerPublic.js.map


text:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect"
	dynamicConfig="true">

	<defaultCache name="defaut" maxElementsInMemory="10000" maxEntriesLocalHeap="10000" maxEntriesLocalDisk="50000" eternal="false"
		timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="false" memoryStoreEvictionPolicy="LRU">

		<persistence strategy="localTempSwap" />
	</defaultCache>

	<diskStore path="java.io.tmpdir" />

	<!-- SPRING -->
	<cache name="misc" maxEntriesLocalHeap="1000" memoryStoreEvictionPolicy="LFU" transactionalMode="off" timeToIdleSeconds="60" timeToLiveSeconds="60">
		<persistence strategy="localTempSwap" />
	</cache>

	<!-- HIBERNATE -->

	<cache name="items" maxEntriesLocalHeap="10000" eternal="false" timeToLiveSeconds="86400" />

	<cache name="default-update-timestamps-region" maxEntriesLocalHeap="5000" eternal="true">
		<persistence strategy="localTempSwap" />
	</cache>
	<cache name="default-query-results-region" maxElementsInMemory="10000" eternal="false" timeToLiveSeconds="86400" overflowToDisk="false"
		memoryStoreEvictionPolicy="LRU" />

	<cache name="org.hibernate.cache.UpdateTimestampsCache" maxEntriesLocalHeap="5000" eternal="true">
		<persistence strategy="localTempSwap" />
	</cache>
	<cache name="org.hibernate.cache.StandardQueryCache" maxElementsInMemory="10000" eternal="false" timeToLiveSeconds="86400" overflowToDisk="false"
		memoryStoreEvictionPolicy="LRU" />
</ehcache>


text:
layout: organization
category: local

title: Woodside On The Move Inc
impact_area: Children
keywords:
location_services:
location_offices:
website: http://www.woodsideonthemove.org/

description:
mission: |
  This organization is dedicated to helping students and youth focus on their education.  They also help students with employment.

cash_grants:
grants:
service_opp:
services:

learn:
cont_relationship:

salutation:
first_name:
last_name:
title_contact_person:

city: Queens
state: NY
address: |
  39-42 59th Street
  Queens NY 11377
lat: 40.746253
lng: -73.905117
phone: 718-476-8449
ext:
fax: 718-476-6946
email:
preferred_contact:
contact_person_intro:
---


text:
<?php

namespace DevelSuite\exception;

use DevelSuite\exception\dsIErrorCode;
use DevelSuite\exception\spl\dsNullPointerException;
use DevelSuite\util\dsStringTools;

/**
 * Defining the key in an ini-bundle,
 * where the error message can be found.
 *
 * @package DevelSuite\exception
 * @author  Georg Henkel <info@develman.de>
 * @version 1.0
 */
class dsErrorCode implements dsIErrorCode {
	/**
	 * FilePath of the ini-file
	 * @var string
	 */
	private $filePath;
	/**
	 * Name of the ini-bundle
	 * @var string
	 */
	private $bundleName;

	/**
	 * Key in the ini-file
	 * @var string
	 */
	private $key;

	/**
	 * Constructor
	 *
	 * @param string $filePath
	 * 		Path to the error bundle
	 * @param string $bundleName
	 * 		Name of the bundle in which the error message are saved
	 * @param string $key
	 * 		Key of the error message
	 */
	public function __construct($filePath, $bundleName, $key) {
		if (dsStringTools::isNullOrEmpty($filePath)) {
			throw new dsNullPointerException("filePath is null");
		}

		if (dsStringTools::isNullOrEmpty($bundleName)) {
			throw new dsNullPointerException("bundleName is null");
		}

		if(dsStringTools::isNullOrEmpty($key)) {
			throw new dsNullPointerException("key is null");
		}

		$this->filePath = $filePath;
		$this->bundleName = $bundleName;
		$this->key = $key;
	}

	/**
	 * (non-PHPdoc)
	 * @see DevelSuite\exception.dsIErrorCode::getFilePath()
	 */
	public function getFilePath() {
		return $this->filePath;
	}

	/**
	 * (non-PHPdoc)
	 * @see DevelSuite\exception.dsIErrorCode::getSection()
	 */
	public function getBundleName() {
		return $this->bundleName;
	}

	/**
	 * (non-PHPdoc)
	 * @see DevelSuite\exception.dsIErrorCode::getKey()
	 */
	public function getKey() {
		return $this->key;
	}
}


text:
package netty.cookbook.chapter8.recipe3;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http.QueryStringDecoder;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.jedis.exceptions.JedisException;
import netty.cookbook.common.http.ContentTypePool;
import netty.cookbook.common.http.HttpRequestEvent;
import netty.cookbook.common.http.NettyHttpUtil;
import netty.cookbook.common.redis.RedisCommand;
import netty.cookbook.common.redis.RedisInfo;

import com.allanbank.mongodb.MongoClient;
import com.allanbank.mongodb.MongoClientConfiguration;
import com.allanbank.mongodb.MongoCollection;
import com.allanbank.mongodb.MongoDatabase;
import com.allanbank.mongodb.MongoDbException;
import com.allanbank.mongodb.MongoFactory;
import com.allanbank.mongodb.MongoIterator;
import com.allanbank.mongodb.bson.Document;
import com.allanbank.mongodb.builder.QueryBuilder;

import static com.allanbank.mongodb.builder.QueryBuilder.and;
import static com.allanbank.mongodb.builder.QueryBuilder.or;
import static com.allanbank.mongodb.builder.QueryBuilder.not;
import static com.allanbank.mongodb.builder.QueryBuilder.where;

/**
 * the public handler for all Netty's message, transform to HttpRequestEvent and
 * routing all matched processors
 *
 * @author trieu
 *
 */
public class HttpEventProcessingHandler extends
		SimpleChannelInboundHandler<Object> {

	private static final String _123456 = "123456";
	static ShardedJedisPool jedisPool = (new RedisInfo("127.0.0.1", 6379)).getShardedJedisPool();

	public HttpEventProcessingHandler() {

	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
		if (msg instanceof HttpRequest) {
			//HttpRequest request = (HttpRequest) msg;
			// TODO filter DDOS/bad/attacking requests

//			String uri = request.getUri();
//			String remoteIp = NettyHttpUtil.getRemoteIP(ctx, request);
//			String localIp = NettyHttpUtil.getLocalIP(ctx);

			// System.out.println(request.getMethod().name() + "==> uri: " +
			// uri);
			//QueryStringDecoder qDecoder = new QueryStringDecoder(uri);
			//Map<String, List<String>> params = qDecoder.parameters();

			// boolean isPOSTMethod = "POST".equals(request.getMethod().name());

			//HttpRequestEvent event = new HttpRequestEvent(localIp, remoteIp,uri, params, request);
			FullHttpResponse response = NettyHttpUtil.theHttpContent(_123456, ContentTypePool.TEXT_UTF8);;//processEvent(event);

			// set version to response header
			//response.headers().add("Server", HttpServer.SERVER_INFO_VERSION);

			// Write the response.
			ChannelFuture future = ctx.write(response);
			ctx.flush().close();

			// callback and free resources
//			if (event != null) {
//				event.clear();
//			}

			// Close the non-keep-alive connection after the write operation is
			// done.
			future.addListener(ChannelFutureListener.CLOSE);

		}

		if (msg instanceof HttpContent) {
			if (msg instanceof LastHttpContent) {
				NettyHttpUtil.response1pxGifImage(ctx);
			}
		}
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		ctx.flush().close();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		ctx.flush().close();
	}

	FullHttpResponse processEvent(HttpRequestEvent event) {
		String rs = "";
		try {
			rs = (new RedisCommand<Long>(jedisPool) {
				@Override
				protected Long build() throws JedisException {
					return Long.parseLong(jedis.hget("2014-12-04", "click"));
				}
			}).execute().toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {

		}
		FullHttpResponse response = NettyHttpUtil.theHttpContent(rs, ContentTypePool.TEXT_UTF8);
		return response;
	}
}


text:
package Map;

public interface Structure<T,V> extends Iterable<T> {

    boolean insert(T key, V value);
    V get(T key);
    boolean delete(T key);

}


text:
package net.emaze.dysfunctional;

import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import net.emaze.dysfunctional.contracts.dbc;
import net.emaze.dysfunctional.dispatching.actions.TriConsumer;
import net.emaze.dysfunctional.dispatching.delegates.TriFunction;
import net.emaze.dysfunctional.dispatching.logic.TriPredicate;
import net.emaze.dysfunctional.tuples.*;

/**
 * tupled.
 *
 * @author rferranti
 */
public abstract class Tuples {

    /**
     * Adapts a binary function to a function accepting a pair.
     *
     * @param <T> the function first parameter type
     * @param <U> the function second parameter type
     * @param <R> the function return type
     * @param function the function to be adapted
     * @return the adapted function
     */
    public static <T, U, R> Function<Pair<T, U>, R> tupled(BiFunction<T, U, R> function) {
        dbc.precondition(function != null, "cannot apply a pair to a null function");
        return pair -> function.apply(pair.first(), pair.second());
    }

    /**
     * Adapts a binary predicate to a predicate accepting a pair.
     *
     * @param <T> the predicate first parameter type
     * @param <U> the predicate second parameter type
     * @param predicate the predicate to be adapted
     * @return the adapted predicate
     */
    public static <T, U> Predicate<Pair<T, U>> tupled(BiPredicate<T, U> predicate) {
        dbc.precondition(predicate != null, "cannot apply a pair to a null predicate");
        return pair -> predicate.test(pair.first(), pair.second());
    }

    /**
     * Adapts a binary consumer to an consumer accepting a pair.
     *
     * @param <T> the consumer first parameter type
     * @param <U> the consumer second parameter type
     * @param consumer the consumer to be adapted
     * @return the adapted consumer
     */
    public static <T, U> Consumer<Pair<T, U>> tupled(BiConsumer<T, U> consumer) {
        dbc.precondition(consumer != null, "cannot apply a pair to a null consumer");
        return pair -> consumer.accept(pair.first(), pair.second());
    }

    /**
     * Adapts a ternary function to a function accepting a triple.
     *
     * @param <T> the function first parameter type
     * @param <U> the function second parameter type
     * @param <V> the function third parameter type
     * @param <R> the function return type
     * @param function the function to be adapted
     * @return the adapted function
     */
    public static <T, U, V, R> Function<Triple<T, U, V>, R> tupled(TriFunction<T, U, V, R> function) {
        dbc.precondition(function != null, "cannot apply a triple to a null function");
        return triple -> function.apply(triple.first(), triple.second(), triple.third());
    }

    /**
     * Adapts a ternary predicate to a predicate accepting a triple.
     *
     * @param <T> the predicate first parameter type
     * @param <U> the predicate second parameter type
     * @param <V> the predicate third parameter type
     * @param predicate the predicate to be adapted
     * @return the adapted predicate
     */
    public static <T, U, V> Predicate<Triple<T, U, V>> tupled(TriPredicate<T, U, V> predicate) {
        dbc.precondition(predicate != null, "cannot apply a triple to a null predicate");
        return triple -> predicate.test(triple.first(), triple.second(), triple.third());
    }

    /**
     * Adapts a ternary consumer to an consumer accepting a triple.
     *
     * @param <T> the consumer first parameter type
     * @param <U> the consumer second parameter type
     * @param <V> the consumer third parameter type
     * @param consumer the consumer to be adapted
     * @return the adatped consumer
     */
    public static <T, U, V> Consumer<Triple<T, U, V>> tupled(TriConsumer<T, U, V> consumer) {
        dbc.precondition(consumer != null, "cannot apply a triple to a null consumer");
        return triple -> consumer.accept(triple.first(), triple.second(), triple.third());
    }

    /**
     * untupled.
     */
    public abstract static class Pairs {

        /**
         * Adapts a function accepting a pair to a binary function.
         *
         * @param <T> the function first parameter type
         * @param <U> the function second parameter type
         * @param <R> the function return type
         * @param function the function to be adapted
         * @return the adapted function
         */
        public static <T, U, R> BiFunction<T, U, R> untupled(Function<Pair<T, U>, R> function) {
            dbc.precondition(function != null, "cannot untuple a null function");
            return (first, second) -> function.apply(Pair.of(first, second));
        }

        /**
         * Adapts a predicate accepting a pair to a binary predicate.
         *
         * @param <T> the predicate first parameter type
         * @param <U> the predicate second parameter type
         * @param predicate the predicate to be adapted
         * @return the adapted predicate
         */
        public static <T, U> BiPredicate<T, U> untupled(Predicate<Pair<T, U>> predicate) {
            dbc.precondition(predicate != null, "cannot untuple a null predicate");
            return (first, second) -> predicate.test(Pair.of(first, second));
        }

        /**
         * Adapts an consumer accepting a pair to a binary consumer.
         *
         * @param <T> the consumer first parameter type
         * @param <U> the consumer second parameter type
         * @param consumer the consumer to be adapted
         * @return the adapted consumer
         */
        public static <T, U> BiConsumer<T, U> untupled(Consumer<Pair<T, U>> consumer) {
            dbc.precondition(consumer != null, "cannot untuple a null consumer");
            return (first, second) -> consumer.accept(Pair.of(first, second));
        }
    }

    /**
     * untupled.
     */
    public abstract static class Triples {

        /**
         * Adapts a function accepting a triple to a ternary function.
         *
         * @param <T> the function first parameter type
         * @param <U> the function second parameter type
         * @param <V> the function third parameter type
         * @param <R> the function return type
         * @param function the function to be adapted
         * @return the adapted function
         */
        public static <T, U, V, R> TriFunction<T, U, V, R> untupled(Function<Triple<T, U, V>, R> function) {
            dbc.precondition(function != null, "cannot untuple a null function");
            return (first, second, third) -> function.apply(Triple.of(first, second, third));
        }

        /**
         * Adapts a predicate accepting a triple to a ternary predicate.
         *
         * @param <T> the predicate first parameter type
         * @param <U> the predicate second parameter type
         * @param <V> the predicate third parameter type
         * @param predicate the predicate to be adapted
         * @return the adapted predicate
         */
        public static <T, U, V> TriPredicate<T, U, V> untupled(Predicate<Triple<T, U, V>> predicate) {
            dbc.precondition(predicate != null, "cannot untuple a null predicate");
            return (first, second, third) -> predicate.test(Triple.of(first, second, third));
        }

        /**
         * Adapts an consumer accepting a triple to a ternary consumer.
         *
         * @param <T> the consumer first parameter type
         * @param <U> the consumer second parameter type
         * @param <V> the consumer third parameter type
         * @param consumer the consumer to be adapted
         * @return the adatped consumer
         */
        public static <T, U, V> TriConsumer<T, U, V> untupled(Consumer<Triple<T, U, V>> consumer) {
            dbc.precondition(consumer != null, "cannot untuple a null consumer");
            return (first, second, third) -> consumer.accept(Triple.of(first, second, third));
        }
    }
}


text:
import 'bootstrap/dist/js/bootstrap.bundle';

// multilevel dropdown
$('.dropdown-menu a.dropdown-toggle').on('click', function (e) {
	e.preventDefault();
	e.stopImmediatePropagation();
	if (!$(this).next().hasClass('show')) {
		$(this).parents('.dropdown-menu').first().find('.show').removeClass("show");
	}
	var $subMenu = $(this).next(".dropdown-menu");
	$subMenu.toggleClass('show');

	$(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function () {
		$('.dropdown-submenu .show').removeClass("show");
	});

	return false;
});

frappe.get_modal = function(title, content) {
	return $(
		`

${title}

						<button type="button" class="close" data-dismiss="modal" aria-label="Close">
							×
						</button>

						${content}

						<button type="button" class="btn btn-sm btn-primary hidden"></button>

`
	);
};

frappe.ui.Dialog = class Dialog extends frappe.ui.Dialog {
	get_primary_btn() {
		return this.$wrapper.find(".modal-footer .btn-primary");
	}

	set_primary_action(label, click) {
		this.$wrapper.find('.modal-footer').removeClass('hidden');
		return super.set_primary_action(label, click)
			.removeClass('hidden');
	}

	make() {
		super.make();
		if (this.fields) {
			this.$wrapper.find('.section-body').addClass('w-100');
		}
	}
};


text:
import os

import quickstart_list_saved_queries

PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"]

def test_list_saved_queries(capsys):
    parent_resource = f"projects/{PROJECT}"
    quickstart_list_saved_queries.list_saved_queries(parent_resource)
    out, _ = capsys.readouterr()
    assert "saved_queries" in out


text:
package jenkins.slaves.restarter;

import hudson.ExtensionList;
import hudson.ExtensionPoint;
import java.io.Serializable;
import java.util.logging.Logger;

/**
 * Extension point to control how to restart JNLP agent when it loses the connection with the master.
 *
 *

 * Objects are instantiated on the master, then transferred to an agent via serialization.
 *
 * @author Kohsuke Kawaguchi
 */
public abstract class SlaveRestarter implements ExtensionPoint, Serializable {
    /**
     * Called on the agent to see if this restarter can work on this agent.
     */
    public abstract boolean canWork();

    /**
     * If {@link #canWork()} method returns true, this method is called later when
     * the connection is lost to restart the agent.
     *
     *

     * Note that by the time this method is called, classloader is no longer capable of
     * loading any additional classes. Therefore {@link #canWork()} method must have
     * exercised enough of the actual restart process so that this call can proceed
     * without trying to load additional classes nor resources.
     *
     *

     * This method is not expected to return, and the JVM should terminate before this call returns.
     * If the method returns normally, the JNLP agent will move on to the reconnection without restart.
     * If an exception is thrown, it is reported as an error and then the JNLP agent will move on to the
     * reconnection without restart.
     */
    public abstract void restart() throws Exception;

    public static ExtensionList<SlaveRestarter> all() {
        return ExtensionList.lookup(SlaveRestarter.class);
    }

    private static final Logger LOGGER = Logger.getLogger(SlaveRestarter.class.getName());

    private static final long serialVersionUID = 1L;
}


text:
package ar.com.larreta.stepper.validators;

import java.lang.annotation.Annotation;
import java.util.Collection;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import ar.com.larreta.annotations.Log;
import ar.com.larreta.stepper.validators.annotations.OnlyOne;

public class OnlyOneValidator implements ConstraintValidator<Annotation, Object> {

	private static @Log Logger LOG;

	@Autowired
	protected ServletContext context;

	@Autowired
	protected HttpServletRequest request;

	private OnlyOne onlyOne;

	@Override
	public void initialize(Annotation annotation) {
		onlyOne = (OnlyOne) annotation;
	}

	@Override
	public boolean isValid(Object object, ConstraintValidatorContext context) {
		try {
			Object fieldValue = BeanUtils.getProperty(object, onlyOne.field());
			Object linkedFieldValue = BeanUtils.getProperty(object, onlyOne.linkedField());

			Boolean fieldValueIsNull = (fieldValue==null) || ((fieldValue instanceof String) && StringUtils.isEmpty((String) fieldValue));
			Boolean linkedFieldValueIsNull = (linkedFieldValue==null) || ((linkedFieldValue instanceof String) && StringUtils.isEmpty((String) linkedFieldValue));

			return (
					(!onlyOne.required() && (fieldValueIsNull && linkedFieldValueIsNull)) ||
					(onlyOne.required() && (fieldValueIsNull && !linkedFieldValueIsNull)) ||
					(onlyOne.required() && (!fieldValueIsNull && linkedFieldValueIsNull))
					);
		} catch (Exception e){
			LOG.error("Ocurrio un error validando onlyOne", e);
		}
		return Boolean.FALSE;
	}
}


text:
// -----------------------------------------------------------------------
// <copyright file="MessageServices.cs" company="Andrey Kurdiumov">
// Copyright (c) Andrey Kurdiumov. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------

namespace Dub.Web.Mvc
{
#if !NOMAIL
    using System.Net.Mail;
#endif
    using System.Threading.Tasks;

#if NETCORE
    /// <summary>
    /// Message services.
    /// </summary>
    public class MessageServices
    {
        /// <summary>
        /// Sends the email.
        /// </summary>
        /// <param name="email">Recepient's email.</param>
        /// <param name="subject">Email subject</param>
        /// <param name="message">Email message text.</param>
        /// <returns>Task which asynchronously send email.</returns>
        public static async Task SendEmailAsync(string email, string subject, string message)
        {
#if !NOMAIL
            SmtpClient client = new SmtpClient("smtp.sendgrid.net");
            client.Credentials = new System.Net.NetworkCredential("azure_246b6e0fe9ab9e8997340a3bc3b8e480@azure.com", "Xp8YZpA_");
            var template = System.IO.File.ReadAllText("mailtemplate.html");
            await client.SendMailAsync("info@hotlola.com", email, subject, template.Replace("$message", message));
#else
            // Plug in your email service
            await Task.FromResult(0);
#endif
        }

        public static Task SendSmsAsync(string number, string message)
        {
            // Plug in your sms service
            return Task.FromResult(0);
        }
    }
#endif
}


text:
<?php

namespace Site\Bundle\BackendBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * CarsRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class CarsRepository extends EntityRepository
{
    public $all_cars = false;

    public function getCarsBlocks($body_id, $stype)
    {
        $em = $this->getEntityManager();

        $qb = $em->createQueryBuilder();
        $qb->select('b')
            ->from('SiteBackendBundle:BaseAutoCarsBlocks','b')
            ->where('b.carId = '.$body_id.' AND b.blockType = '.$stype)
            ->orderBy('b.pos', 'ASC');

        $blocks = $qb->getQuery()->getResult();

        return $blocks;
    }

    public function getCarsSlider($body_id, $stype)
    {
        $em = $this->getEntityManager();

        $qb = $em->createQueryBuilder();
        $qb->select('s')
            ->from('SiteBackendBundle:BaseAutoSliderSlides','s')
            ->where('s.carId = '.$body_id.' AND s.sliderPos = '.$stype)
            ->orderBy('s.pos', 'ASC');
        $slider = $qb->getQuery()->getResult();

        return $slider;
    }

    public function getCarsGallery($body_id)
    {
        $em = $this->getEntityManager();

        $qb = $em->createQueryBuilder();
        $qb->select('g')
            ->from('SiteBackendBundle:BaseAutoGallery','g')
            ->where('g.carId = '.$body_id)
            ->orderBy('g.pos', 'ASC');

        $gallery = $qb->getQuery()->getResult();

        return $gallery;
    }

    public function getCarsInfo($id, $bodyid = false, $tab = false, $ids = false, $onpage = false)
    {
        $em = $this->getEntityManager();

        $qb = $em->createQueryBuilder()
            ->select(array(
                'b.id AS body_id',
                'b.name AS body_name',
                'c.id AS model_id',
                'c.name AS model_name',
                'ig.id AS group_id',
                'ig.name AS group_name',
                'i.id AS info_id',
                'i.name AS info_name',
                'i.seltype AS info_seltype',
                'i.pages as onpages',
                'ci.valueId AS value_id',
                'iv.name AS value_name',
            ))
            ->from('SiteBackendBundle:CarsInfo', 'ci')
            ->leftJoin('SiteBackendBundle:InfoValue',   'iv', 'WITH','ci.valueId = iv.id')
            ->leftJoin('SiteBackendBundle:Info',        'i', 'WITH', 'i.id = ci.infoId')
            ->leftJoin('SiteBackendBundle:InfoGroups',  'ig', 'WITH', 'ig.id = i.groupId')
            ->leftJoin('SiteBackendBundle:Cars',        'c','WITH','c.id = ci.carModelId')
            ->leftJoin('SiteBackendBundle:BaseAutoBodyTypes',        'b','WITH','b.id = c.bodyId')
            ->where("b.carId = '$id' AND ci.valueId IS NOT NULL AND ci.valueId != 0")
            ->orderBy('ig.id', 'ASC')
            ->addOrderBy('i.pos', 'ASC');

        if($bodyid)
            $qb->andWhere("b.id = '$bodyid'");

        if($tab !== false)
            $qb->andWhere("ig.tabPlace = '$tab'");
        if($ids != false)
            $qb->andWhere($qb->expr()->in('ci.infoId', $ids));

        $models = $qb->getQuery()->getResult();

        $info_data = array();

        if(!$this->all_cars)
        {
            $all_cars = array();
            foreach($models as $model)
            {
                if(!array_key_exists($model['model_id'], $all_cars))
                $all_cars[$model['model_id']] = '';
            }
        }
        else
            $all_cars = $this->all_cars;

        foreach($models as $model)
        {
			//Отображаем только те характеристики, которые отмечены для вывода на указанной странице (это решается в контроллере при вызове функции)
			if ($onpage !== false)
			{
				$ShowIn = unserialize($model['onpages']);
				if (isset($ShowIn[(int)$onpage]) && !$ShowIn[(int)$onpage])
					continue;
			}
            $groupid = ($model['group_id'] == '') ? 0 : $model['group_id'];
            if($model['body_id'] != '' && !array_key_exists($model['body_id'], $info_data))
                $info_data[$model['body_id']] = array('label' => $model['body_name'], 'groups' => array());

            if(!array_key_exists($groupid, $info_data[$model['body_id']]['groups']))
                $info_data[$model['body_id']]['groups'][$groupid] = array('label' => $model['group_name'], 'features' => array());

            if($model['info_id'] != '' && !array_key_exists($model['info_id'], $info_data[$model['body_id']]['groups'][$groupid]['features']))
                $info_data[$model['body_id']]['groups'][$groupid]['features'][$model['info_id']] = array('label' => $model['info_name'], 'seltype' => $model['info_seltype'], 'values' => $all_cars);

            if($model['info_id'] != '')
            {
                if($info_data[$model['body_id']]['groups'][$groupid]['features'][$model['info_id']]['seltype'] == 'yesno')
                    $info_data[$model['body_id']]['groups'][$groupid]['features'][$model['info_id']]['values'][$model['model_id']] = $model['value_id'];
                else
                    $info_data[$model['body_id']]['groups'][$groupid]['features'][$model['info_id']]['values'][$model['model_id']] = $model['value_name'];
            }
        }

        return $info_data;
    }

    public function getTopInfo($id, $bodyid = false, $onpage = false)
    {
        $em = $this->getEntityManager();

        $qb = $em->createQueryBuilder()
            ->select(array(
                'b.id AS body_id',
                'b.name AS body_name',
                'c.id AS model_id',
                'c.name AS model_name',
                'i.id AS info_id',
                'i.name AS info_name',
                'i.seltype AS info_seltype',
                'i.pages as onpages',
                'ci.valueId AS value_id',
                'iv.name AS value_name',
            ))
            ->from('SiteBackendBundle:CarsInfo', 'ci')
            ->leftJoin('SiteBackendBundle:InfoValue',   'iv', 'WITH','ci.valueId = iv.id')
            ->leftJoin('SiteBackendBundle:Info',        'i', 'WITH', 'i.id = ci.infoId')
            ->leftJoin('SiteBackendBundle:Cars',        'c','WITH','c.id = ci.carModelId')
            ->leftJoin('SiteBackendBundle:BaseAutoBodyTypes',        'b','WITH','b.id = c.bodyId')
            ->where("b.carId = '$id' AND ci.valueId IS NOT NULL AND ci.valueId != 0 AND i.groupId = 0")
            ->orderBy('i.pos', 'ASC');

        if($bodyid)
            $qb->andWhere("b.id = '$bodyid'");

        $models = $qb->getQuery()->getResult();

        $info_data = array();
        if(!$this->all_cars)
        {
            $all_cars = array();
            foreach($models as $model)
            {
                if(!array_key_exists($model['model_id'], $all_cars))
                $all_cars[$model['model_id']] = '';
            }
        }
        else
            $all_cars = $this->all_cars;

        foreach($models as $model)
        {
			//Отображаем только те характеристики, которые отмечены для вывода на указанной странице (это решается в контроллере при вызове функции)
			if ($onpage !== false)
			{
				$ShowIn = unserialize($model['onpages']);
				if (isset($ShowIn[(int)$onpage]) && !$ShowIn[(int)$onpage])
					continue;
			}

            if($model['info_id'] != '' && !array_key_exists($model['info_id'], $info_data))
                $info_data[$model['info_id']] = array('label' => $model['info_name'], 'seltype' => $model['info_seltype'], 'values' => $all_cars);

            if($model['info_id'] != '' )
            {
                if($info_data[$model['info_id']]['seltype'] == 'yesno')
                    $info_data[$model['info_id']]['values'][$model['model_id']] = $model['value_id'];
                else
                    $info_data[$model['info_id']]['values'][$model['model_id']] = $model['value_name'];
            }
        }
        return $info_data;
    }

    public function getCompetitorsInfo($car_id)
    {
        $em = $this->getEntityManager();

        $qb = $em->createQueryBuilder()
            ->select(array(
                'baca.id AS competitor_id',
                'baca.name AS competitor_name',
                'bacai.infoId AS info_id',
                'bacai.value AS info_value',
                'baci.name AS info_name',
                'baci.maxValue AS info_value_max',
                'bacaa.isMain AS is_main',
            ))
            ->from('SiteBackendBundle:BaseAutoCompetitorsAutoAssigned', 'bacaa')
            ->leftJoin('SiteBackendBundle:BaseAutoCompetitorsAuto',   'baca', 'WITH','baca.id = bacaa.competitorId')
            ->leftJoin('SiteBackendBundle:BaseAutoCompetitorsAutoInfo',   'bacai', 'WITH','baca.id = bacai.autoId')
            ->leftJoin('SiteBackendBundle:BaseAutoCompetitorsInfo',   'baci', 'WITH','baci.id = bacai.infoId')
            ->where("bacaa.carId = '$car_id'")
            ->orderBy('bacaa.isMain', 'DESC');

        $data = $qb->getQuery()->getResult();

        $all_values = array();
        foreach($data as $d)
        {
            if(!array_key_exists($d['competitor_id'], $all_values))
            {
                $all_cars[$d['competitor_id']] = array('label' => $d['competitor_name'], 'value' => '', 'max_value' => '', 'is_main' => 0);
            }
        }

        $cdata = array();
        foreach($data as $d)
        {
            if($d['info_id'] != '' && !array_key_exists($d['info_id'], $cdata))
            {
                $cdata[$d['info_id']] = array('label' => $d['info_name'], 'cars' => $all_cars);
            }
            $cdata[$d['info_id']]['cars'][$d['competitor_id']]['value'] = $d['info_value'];
            $cdata[$d['info_id']]['cars'][$d['competitor_id']]['max_value'] = $d['info_value_max'];
            $cdata[$d['info_id']]['cars'][$d['competitor_id']]['is_main'] = $d['is_main'];
        }

        return $cdata;
    }

    public function getCarsReviews($car_id, $limit = false, $bid = null)
    {
        $em = $this->getEntityManager();

        $qb = $em->createQueryBuilder()->distinct()
            ->select('r.id, r.name, r.description, r.file, r.authorName, r.authorStatus')
            ->from('SiteBackendBundle:BaseAutoReviews', 'r')
            ->leftJoin('SiteBackendBundle:BaseAutoReviewsAsigned','ra', 'WITH', 'ra.reviewId = r.id')
            ->leftJoin('SiteBackendBundle:BaseAutoBodyTypes','bt', 'WITH', 'bt.id = ra.carId');

        if (is_null($bid)) {
            $qb->where("bt.carId = '$car_id' AND r.isActive = 1");
        } else {
            $qb->where("bt.carId = '$car_id' AND r.isActive = 1 AND bt.id = '$bid'");
        }

        $reviews = $qb->getQuery()->getResult();

        if($limit)
        {
            $reviews = array_slice($reviews, 0, $limit);
        }

        return $reviews;
    }

    public function getCarsDocuments($body_id)
    {
        $em = $this->getEntityManager();

        $qb = $em->createQueryBuilder();
        $qb->select('d')
            ->from('SiteBackendBundle:BaseAutoDocuments','d')
            ->where('d.carId = '.$body_id);

        $documents = $qb->getQuery()->getResult();

        return $documents;
    }
}


text:
namespace omaha_query_params {

class OmahaQueryParamsDelegate;

// Generates a string of URL query parameters to be used when getting
// component and extension updates. These parameters generally remain
// fixed for a particular build. Embedders can use the delegate to
// define different implementations. This should be used only in the
// browser process.
class OmahaQueryParams {
 public:
  enum ProdId {
    CHROME = 0,
    CRX,
  };

  // Generates a string of URL query parameters for Omaha. Includes the
  // following fields: "os", "arch", "nacl_arch", "prod", "prodchannel",
  // "prodversion", and "lang"
  static std::string Get(ProdId prod);

  // Returns the value we use for the "prod=" parameter. Possible return values
  // include "chrome", "chromecrx", "chromiumcrx", and "unknown".
  static const char* GetProdIdString(ProdId prod);

  // Returns the value we use for the "os=" parameter. Possible return values
  // include: "mac", "win", "android", "cros", "linux", and "openbsd".
  static const char* GetOS();

  // Returns the value we use for the "arch=" parameter. Possible return values
  // include: "x86", "x64", and "arm".
  static const char* GetArch();

  // Returns the value we use for the "nacl_arch" parameter. Note that this may
  // be different from the "arch" parameter above (e.g. one may be 32-bit and
  // the other 64-bit). Possible return values include: "x86-32", "x86-64",
  // "arm", and "mips32".
  static const char* GetNaclArch();

  // Use this delegate.
  static void SetDelegate(OmahaQueryParamsDelegate* delegate);

 private:
  DISALLOW_IMPLICIT_CONSTRUCTORS(OmahaQueryParams);
};

}  // namespace omaha_query_params

#endif  // COMPONENTS_OMAHA_QUERY_PARAMS_OMAHA_QUERY_PARAMS_H_


text:
package com.ms_square.etsyblur;

import android.graphics.Color;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;

/**
 * BlurConfig.java
 *
 * @author Manabu-GT on 3/17/17.
 */
public class BlurConfig {

    public static final int DEFAULT_RADIUS = 10;
    public static final int DEFAULT_DOWN_SCALE_FACTOR = 4;
    public static final int DEFAULT_OVERLAY_COLOR = Color.TRANSPARENT;
    public static final boolean DEFAULT_ALLOW_FALLBACK = true;
    public static final AsyncPolicy DEFAULT_ASYNC_POLICY = new SimpleAsyncPolicy();
    public static final boolean DEFAULT_DEBUG = false;

    public static final BlurConfig DEFAULT_CONFIG = new BlurConfig(DEFAULT_RADIUS,
            DEFAULT_DOWN_SCALE_FACTOR, DEFAULT_OVERLAY_COLOR, DEFAULT_ALLOW_FALLBACK,
            DEFAULT_ASYNC_POLICY, DEFAULT_DEBUG);

    private final int radius;

    private final int downScaleFactor;

    @ColorInt
    private final int overlayColor;

    private final boolean allowFallback;

    private final AsyncPolicy asyncPolicy;

    private final boolean debug;

    private BlurConfig(int radius, int downScaleFactor, @ColorInt int overlayColor,
                       boolean allowFallback, @NonNull AsyncPolicy asyncPolicy, boolean debug) {
        this.radius = radius;
        this.downScaleFactor = downScaleFactor;
        this.overlayColor = overlayColor;
        this.allowFallback = allowFallback;
        this.asyncPolicy = asyncPolicy;
        this.debug = debug;
    }

    public int radius() {
        return radius;
    }

    public int downScaleFactor() {
        return downScaleFactor;
    }

    public int overlayColor() {
        return overlayColor;
    }

    public boolean allowFallback() {
        return allowFallback;
    }

    public AsyncPolicy asyncPolicy() {
        return asyncPolicy;
    }

    public boolean debug() {
        return debug;
    }

    public static void checkRadius(int radius) {
        if (radius <= 0 || radius > 25) {
            throw new IllegalArgumentException("radius must be greater than 0 and less than or equal to 25");
        }
    }

    public static void checkDownScaleFactor(int downScaleFactor) {
        if (downScaleFactor <= 0) {
            throw new IllegalArgumentException("downScaleFactor must be greater than 0.");
        }
    }

    public static class Builder {

        private int radius;

        private int downScaleFactor;

        @ColorInt
        private int overlayColor;

        private boolean allowFallback;

        private AsyncPolicy asyncPolicy;

        private boolean debug;

        public Builder() {
            radius = DEFAULT_RADIUS;
            downScaleFactor = DEFAULT_DOWN_SCALE_FACTOR;
            overlayColor = DEFAULT_OVERLAY_COLOR;
            allowFallback = DEFAULT_ALLOW_FALLBACK;
            asyncPolicy = DEFAULT_ASYNC_POLICY;
            debug = DEFAULT_DEBUG;
        }

        public Builder radius(int radius) {
            checkRadius(radius);
            this.radius = radius;
            return this;
        }

        public Builder downScaleFactor(int downScaleFactor) {
            checkDownScaleFactor(downScaleFactor);
            this.downScaleFactor = downScaleFactor;
            return this;
        }

        public Builder overlayColor(int overlayColor) {
            this.overlayColor = overlayColor;
            return this;
        }

        public Builder allowFallback(boolean allowFallback) {
            this.allowFallback = allowFallback;
            return this;
        }

        public Builder asyncPolicy(@NonNull AsyncPolicy asyncPolicy) {
            this.asyncPolicy = asyncPolicy;
            return this;
        }

        public Builder debug(boolean debug) {
            this.debug = debug;
            return this;
        }

        public BlurConfig build() {
            return new BlurConfig(radius, downScaleFactor, overlayColor,
                    allowFallback, asyncPolicy, debug);
        }
    }
}


text:
package org.jboss.jbossts.qa.ArjunaCore.Common;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.util.ArrayList;

public class UidTestProcess
{
	public UidTestProcess(String command, int numberofuids)
	{
		mComand = command + " " + numberofuids;

		Thread mMainThread = new Thread("comand thread")
		{
			public void run()
			{
				try
				{
					mProcess = Runtime.getRuntime().exec(mComand);
				}
				catch (OutOfMemoryError ome)
				{
					System.out.println("Out of memeory end test = " + ome);
				}
				catch (IOException io)
				{
					System.out.println("runtime exception " + io);
				}
				getResults();
			}
		};
		mMainThread.start();
	}

	/**
	 * We are only bothered about the output stream.
	 */
	public void getResults()
	{
		Thread mOutReader = new Thread()
		{
			public void run()
			{
				try
				{
					BufferedReader br = new BufferedReader(new InputStreamReader(mProcess.getInputStream()));
					String line = br.readLine();
					while ((!isInterrupted() && line != null))
					{
						line = line.trim();
						mResults.add(line);
						line = br.readLine();
					}
				}
				catch (InterruptedIOException e)
				{
				}
				catch (Exception e)
				{
				}
			}
		};

		//we will process the error stream just in case
		Thread mErrReader = new Thread()
		{
			public void run()
			{
				try
				{
					BufferedReader br = new BufferedReader(new InputStreamReader(mProcess.getErrorStream()));
					String line = br.readLine();
					while ((!isInterrupted() && line != null))
					{
						line = line.trim();
						System.out.println(line);
						line = br.readLine();
					}
				}
				catch (InterruptedIOException e)
				{
				}
				catch (Exception e)
				{
				}
			}
		};

		mOutReader.start();
		mErrReader.start();

		//wait for process to end.
		try
		{
			mProcess.waitFor();
		}
		catch (Exception e)
		{
			System.err.println("process exception");
		}
		mFinished = true;
	}

	private Process mProcess;
	private String mComand;

	public boolean mFinished = false;
	public ArrayList mResults = new ArrayList();
}


text:
require 'spec_helper'

describe Twig do
  it "should have a VERSION constant" do
    expect(subject.const_get('VERSION')).to_not be_empty
  end
end


text:
void xrServer::OnProcessClientMapData(NET_Packet& P, ClientID const& clientID) {
#ifdef DEBUG
    Msg("--- Sending map data to client 0x%08x", clientID);
#endif // #ifdef DEBUG
    NET_Packet responseP;
    string128 client_map_name;
    string128 client_map_version;
    u32 client_geom_crc32;

    P.r_stringZ_s(client_map_name);
    P.r_stringZ_s(client_map_version);
    P.r_u32(client_geom_crc32);

    LPCSTR server_map_name = Level().get_net_DescriptionData().map_name;
    LPCSTR server_map_version = Level().get_net_DescriptionData().map_version;

    responseP.w_begin(M_SV_MAP_NAME);

    if ((xr_strcmp(server_map_name, client_map_name)) ||
        (xr_strcmp(server_map_version, client_map_version))) {
        responseP.w_u8(static_cast<u8>(YouHaveOtherMap));
#ifdef DEBUG
        Msg("--- Client [0x%08x] has incorrect map [%s] or version [%s]", client_map_name,
            client_map_version);
#endif  // #ifdef DEBUG
        // here we can make hard disconnect of this client...
    } else if (!Level().IsChecksumsEqual(client_geom_crc32)) {
        responseP.w_u8(static_cast<u8>(InvalidChecksum));
    } else {
        responseP.w_u8(static_cast<u8>(SuccessSync));
    }

    SendTo(clientID, responseP, net_flags(TRUE, TRUE));
}