text:
package com.streamsets.pipeline.stage.processor.http;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.google.common.io.Resources;
import com.streamsets.pipeline.api.Field;
import com.streamsets.pipeline.api.Processor;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.config.DataFormat;
import com.streamsets.pipeline.lib.http.HttpMethod;
import com.streamsets.pipeline.sdk.ProcessorRunner;
import com.streamsets.pipeline.sdk.RecordCreator;
import com.streamsets.pipeline.sdk.StageRunner;
import com.streamsets.testing.SingleForkNoReuseTest;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

@Category(SingleForkNoReuseTest.class)
public class HttpProcessorIT extends JerseyTest {

  private static String getBody(String path) {
    try {
      return Resources.toString(Resources.getResource(path), Charsets.UTF_8);
    } catch (IOException e) {
      throw new RuntimeException("Failed to read test resource: " + path);
    }
  }

  @Path("/test/get")
  @Produces(MediaType.APPLICATION_JSON)
  public static class TestGet {
    @GET
    public Response get() {
      return Response.ok(getBody("http/get_response.json"))
          .header("x-test-header", "StreamSets")
          .header("x-list-header", ImmutableList.of("a", "b"))
          .build();
    }
  }

  public static class TestInput {
    public TestInput() {};

    public TestInput(String hello) {
      this.hello = hello;
    }

    @JsonProperty("hello")
    public String hello;
  }

  @Path("/test/put")
  @Consumes(MediaType.APPLICATION_JSON)
  public static class TestPut {
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response put(TestInput input) {
      return Response.ok(
          "{\"hello\":\"" + input.hello + "\"}"
      ).build();
    }
  }

  @Path("/test/xml/get")
  @Produces(MediaType.APPLICATION_XML)
  public static class TestXmlGet {
    @GET
    public Response get() {
      return Response.ok("<r><e>Hello</e><e>Bye</e></r>").build();
    }
  }

  @Override
  protected Application configure() {
    forceSet(TestProperties.CONTAINER_PORT, "0");
    return new ResourceConfig(
        Sets.newHashSet(
            TestGet.class,
            TestPut.class,
            TestXmlGet.class
        )
    );
  }

  @Test
  public void testHttpGetDefaultHeaderOutput() throws Exception {
    HttpProcessorConfig conf = new HttpProcessorConfig();
    conf.httpMethod = HttpMethod.GET;
    conf.outputField = "/output";
    conf.dataFormat = DataFormat.TEXT;
    conf.resourceUrl = getBaseUri() + "test/get";
    conf.headerOutputLocation = HeaderOutputLocation.HEADER;

    Record record = RecordCreator.create();
    record.set("/", Field.create(new HashMap<String, Field>()));

    List<Record> records = ImmutableList.of(record);
    Processor processor = new HttpProcessor(conf);
    ProcessorRunner runner = new ProcessorRunner.Builder(HttpDProcessor.class, processor)
        .addOutputLane("lane")
        .build();
    runner.runInit();
    try {
      StageRunner.Output output = runner.runProcess(records);
      List<Record> outputRecords = output.getRecords().get("lane");
      assertTrue(runner.getErrorRecords().isEmpty());
      assertEquals(1, outputRecords.size());
      assertTrue(outputRecords.get(0).has("/output"));
      assertEquals("{\"hello\":\"world!\"}", outputRecords.get(0).get("/output").getValueAsString());
      assertEquals("StreamSets", outputRecords.get(0).getHeader().getAttribute("x-test-header"));
      assertEquals("[a, b]", outputRecords.get(0).getHeader().getAttribute("x-list-header"));
    } finally {
      runner.runDestroy();
    }
  }

  @Test
  public void testHttpGetPrefixedHeaderOutput() throws Exception {
    HttpProcessorConfig conf = new HttpProcessorConfig();
    conf.httpMethod = HttpMethod.GET;
    conf.outputField = "/output";
    conf.dataFormat = DataFormat.TEXT;
    conf.resourceUrl = getBaseUri() + "test/get";
    conf.headerOutputLocation = HeaderOutputLocation.HEADER;
    conf.headerAttributePrefix = "test-prefix-";

    Record record = RecordCreator.create();
    record.set("/", Field.create(new HashMap<String, Field>()));

    List<Record> records = ImmutableList.of(record);
    Processor processor = new HttpProcessor(conf);
    ProcessorRunner runner = new ProcessorRunner.Builder(HttpDProcessor.class, processor)
        .addOutputLane("lane")
        .build();
    runner.runInit();
    try {
      StageRunner.Output output = runner.runProcess(records);
      List<Record> outputRecords = output.getRecords().get("lane");
      assertTrue(runner.getErrorRecords().isEmpty());
      assertEquals(1, outputRecords.size());
      assertTrue(outputRecords.get(0).has("/output"));
      assertEquals("{\"hello\":\"world!\"}", outputRecords.get(0).get("/output").getValueAsString());
      assertEquals(
          "StreamSets",
          outputRecords.get(0).getHeader().getAttribute(conf.headerAttributePrefix + "x-test-header")
      );
      assertEquals(
          "[a, b]",
          outputRecords.get(0).getHeader().getAttribute(conf.headerAttributePrefix + "x-list-header")
      );
    } finally {
      runner.runDestroy();
    }
  }

  @Test
  public void testHttpGetHeaderFieldOutput() throws Exception {
    HttpProcessorConfig conf = new HttpProcessorConfig();
    conf.httpMethod = HttpMethod.GET;
    conf.outputField = "/output";
    conf.dataFormat = DataFormat.TEXT;
    conf.resourceUrl = getBaseUri() + "test/get";
    conf.headerOutputLocation = HeaderOutputLocation.FIELD;
    conf.headerOutputField = "/headers";

    Record record = RecordCreator.create();
    record.set("/", Field.create(new HashMap<String, Field>()));

    List<Record> records = ImmutableList.of(record);
    Processor processor = new HttpProcessor(conf);
    ProcessorRunner runner = new ProcessorRunner.Builder(HttpDProcessor.class, processor)
        .addOutputLane("lane")
        .build();
    runner.runInit();
    try {
      StageRunner.Output output = runner.runProcess(records);
      List<Record> outputRecords = output.getRecords().get("lane");
      assertTrue(runner.getErrorRecords().isEmpty());
      assertEquals(1, outputRecords.size());
      assertTrue(outputRecords.get(0).has("/output"));
      assertEquals("{\"hello\":\"world!\"}", outputRecords.get(0).get("/output").getValueAsString());
      assertEquals(
          "StreamSets",
          outputRecords.get(0).get(conf.headerOutputField).getValueAsMap().get("x-test-header").getValueAsString()
      );
      assertEquals(
          "[a, b]",
          outputRecords.get(0).get(conf.headerOutputField).getValueAsMap().get("x-list-header").getValueAsString()
      );
    } finally {
      runner.runDestroy();
    }
  }

  @Test
  public void testHttpGetJson() throws Exception {
    HttpProcessorConfig conf = new HttpProcessorConfig();
    conf.httpMethod = HttpMethod.GET;
    conf.outputField = "/output";
    conf.dataFormat = DataFormat.JSON;
    conf.resourceUrl = getBaseUri() + "test/get";

    Record record = RecordCreator.create();
    record.set("/", Field.create(new HashMap<String, Field>()));

    List<Record> records = ImmutableList.of(record);
    Processor processor = new HttpProcessor(conf);
    ProcessorRunner runner = new ProcessorRunner.Builder(HttpDProcessor.class, processor)
        .addOutputLane("lane")
        .build();
    runner.runInit();
    try {
      StageRunner.Output output = runner.runProcess(records);
      List<Record> outputRecords = output.getRecords().get("lane");
      assertTrue(runner.getErrorRecords().isEmpty());
      assertEquals(1, outputRecords.size());
      assertTrue(outputRecords.get(0).has("/output"));
      Map<String, Field> outputMap = outputRecords.get(0).get("/output").getValueAsMap();
      assertTrue(!outputMap.isEmpty());
      assertTrue(outputMap.containsKey("hello"));
      assertEquals("world!", outputMap.get("hello").getValueAsString());

    } finally {
      runner.runDestroy();
    }
  }

  @Test
  public void testHttpPutJson() throws Exception {
    HttpProcessorConfig conf = new HttpProcessorConfig();
    conf.httpMethod = HttpMethod.POST;
    conf.outputField = "/output";
    conf.dataFormat = DataFormat.JSON;
    conf.resourceUrl = getBaseUri() + "test/put";
    conf.headers.put("Content-Type", "application/json");
    conf.requestBody = "{\"hello\":\"world!\"}";

    Record record = RecordCreator.create();
    record.set("/", Field.create(new HashMap<String, Field>()));

    List<Record> records = ImmutableList.of(record);
    Processor processor = new HttpProcessor(conf);
    ProcessorRunner runner = new ProcessorRunner.Builder(HttpDProcessor.class, processor)
        .addOutputLane("lane")
        .build();
    runner.runInit();
    try {
      StageRunner.Output output = runner.runProcess(records);
      List<Record> outputRecords = output.getRecords().get("lane");
      assertTrue(runner.getErrorRecords().isEmpty());
      assertEquals(1, outputRecords.size());
      assertTrue(outputRecords.get(0).has("/output"));
      Map<String, Field> outputMap = outputRecords.get(0).get("/output").getValueAsMap();
      assertTrue(!outputMap.isEmpty());
      assertTrue(outputMap.containsKey("hello"));
      assertEquals("world!", outputMap.get("hello").getValueAsString());

    } finally {
      runner.runDestroy();
    }
  }

  @Test
  public void testHttpGetXml() throws Exception {
    HttpProcessorConfig conf = new HttpProcessorConfig();
    conf.httpMethod = HttpMethod.GET;
    conf.outputField = "/output";
    conf.dataFormat = DataFormat.XML;
    conf.resourceUrl = getBaseUri() + "test/xml/get";

    Record record = RecordCreator.create();
    record.set("/", Field.create(new HashMap<String, Field>()));

    List<Record> records = ImmutableList.of(record);
    Processor processor = new HttpProcessor(conf);
    ProcessorRunner runner = new ProcessorRunner.Builder(HttpDProcessor.class, processor)
        .addOutputLane("lane")
        .build();
    runner.runInit();
    try {
      StageRunner.Output output = runner.runProcess(records);
      List<Record> outputRecords = output.getRecords().get("lane");
      assertTrue(runner.getErrorRecords().isEmpty());
      assertEquals(1, outputRecords.size());
      assertTrue(outputRecords.get(0).has("/output"));
      Map<String, Field> outputField = outputRecords.get(0).get("/output").getValueAsMap();
      List<Field> xmlFields = outputField.get("e").getValueAsList();
      assertEquals("Hello", xmlFields.get(0).getValueAsMap().get("value").getValueAsString());
      assertEquals("Bye", xmlFields.get(1).getValueAsMap().get("value").getValueAsString());
    } finally {
      runner.runDestroy();
    }
  }
}


text:
using System;
using System.Runtime.InteropServices;

namespace SharpVk.Interop.Khronos
{
    /// <summary>
    ///
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public unsafe partial struct XcbSurfaceCreateInfo
    {
        /// <summary>
        /// The type of this structure.
        /// </summary>
        public SharpVk.StructureType SType;

        /// <summary>
        /// Null or an extension-specific structure.
        /// </summary>
        public void* Next;

        /// <summary>
        /// Reserved for future use.
        /// </summary>
        public SharpVk.Khronos.XcbSurfaceCreateFlags Flags;

        /// <summary>
        /// An xcb_connection_t to the X server.
        /// </summary>
        public IntPtr* Connection;

        /// <summary>
        /// The xcb_window_t for the X11 window to associate the surface with.
        /// </summary>
        public IntPtr Window;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.intel.analytics.bigdl.dllib.nn.mkldnn

import com.intel.analytics.bigdl.mkl.{DataType, Memory}
import com.intel.analytics.bigdl.dllib.nn.mkldnn.Phase.{InferencePhase, TrainingPhase}
import com.intel.analytics.bigdl.numeric.NumericFloat
import com.intel.analytics.bigdl.dllib.tensor.{DnnTensor, Tensor}
import com.intel.analytics.bigdl.dllib.utils.{BigDLSpecHelper, T}
import org.apache.commons.lang3.SerializationUtils

class ConcatTableSpec extends BigDLSpecHelper {
  "ConcatTable" should "throw exception when input shape is different" in {
    val container = ConcatTable()
    container.add(Input(Array(1, 2, 3, 4), Memory.Format.nchw))
    container.add(Input(Array(1, 3, 4, 2), Memory.Format.nchw))

    intercept[IllegalArgumentException] {
      container.compile(Phase.TrainingPhase, Array(HeapData(Array(1, 2, 3, 4), Memory.Format.nchw)))
    }
  }

  "ConcatTable" should "be good" in {
    val container = ConcatTable()
    container.add(ReorderMemory.create(
      HeapData(Array(3, 4), Memory.Format.nc),
      HeapData(Array(3, 4), Memory.Format.nc),
      HeapData(Array(3, 4), Memory.Format.nc),
      HeapData(Array(3, 4), Memory.Format.nc)))
    val subcontainer = Sequential()
    subcontainer.add(ReorderMemory.create(
      HeapData(Array(3, 4), Memory.Format.nc),
      NativeData(Array(3, 4), Memory.Format.nc),
      HeapData(Array(3, 4), Memory.Format.nc),
      NativeData(Array(3, 4), Memory.Format.nc)))
    subcontainer.add(ReorderMemory(NativeData(Array(3, 4), Memory.Format.io),
      NativeData(Array(3, 4), Memory.Format.nc)))
    subcontainer.add(ReorderMemory(HeapData(Array(3, 4), Memory.Format.nc),
      NativeData(Array(3, 4), Memory.Format.io)))
    container.add(subcontainer)

    container.compile(Phase.TrainingPhase, Array(HeapData(Array(3, 4), Memory.Format.nc)))
    val input1 = Tensor[Float](3, 4).rand()
    val output1 = container.forward(input1).toTable
    output1(1).asInstanceOf[Tensor[Float]] should be(input1)
    output1(2).asInstanceOf[Tensor[Float]] should be(input1)

    val grad1 = Tensor[Float](3, 4).rand()
    val nativeGrad = container.backward(input1, T(grad1, grad1)).asInstanceOf[Tensor[Float]]
    val heapGrad = Tensor[Float](3, 4).copy(nativeGrad)
    heapGrad should be(grad1 * 2)
    val input2 = Tensor[Float](3, 4).rand()
    val output2 = container.forward(input2).toTable
    output2(1).asInstanceOf[Tensor[Float]] should be(input2)
    output2(2).asInstanceOf[Tensor[Float]] should be(input2)

    val grad2 = Tensor[Float](3, 4).rand()
    val nativeGrad2 = container.backward(input1, T(grad2, grad2)).asInstanceOf[Tensor[Float]]
    val heapGrad2 = Tensor[Float](3, 4).copy(nativeGrad2)
    heapGrad2 should be(grad2 * 2)
  }

  "concat table with java serialization" should "work correctly" in {
    val shape = Array(2, 2)
    val input = Tensor(shape).fill(1)
    val gradOutput = T(Tensor(shape).fill(2), Tensor(shape).fill(2))

    val ct = ConcatTable()
    ct.add(Identity())
    ct.add(Identity())

    ct.compile(TrainingPhase, Array(HeapData(shape, Memory.Format.nc)))

    val cloned = SerializationUtils.clone(ct)
    cloned.compile(TrainingPhase, Array(HeapData(shape, Memory.Format.nc)))

    ct.forward(input)
    ct.backward(input, gradOutput)

    cloned.forward(input)
    cloned.backward(input, gradOutput)

    Tools.dense(ct.output.toTable(1)) should be(Tools.dense(cloned.output.toTable(1)))
    Tools.dense(ct.output.toTable(2)) should be(Tools.dense(cloned.output.toTable(2)))

    Tools.dense(ct.gradInput) should be(Tools.dense(cloned.gradInput))
  }

  "ConcatTable with U8" should "be good" in {
    val shape = Array(4, 3, 5, 5)
    val input = Tensor[Float](shape).rand(0, 1)

    println(input)

    val nativeData1 = NativeData(shape, Memory.Format.nchw, DataType.U8)
    val nativeData2 = NativeData(shape, Memory.Format.nchw, DataType.U8)
    val heapData = HeapData(shape, Memory.Format.nchw, DataType.F32)
    heapData.setMask(0)
    val inputScales = Array(input.clone().abs().max())
    heapData.setScales(inputScales.map(x => 255f / x))

    val concat = ConcatTable()

    concat.add(ReorderMemory(nativeData1))
    concat.add(ReorderMemory(nativeData2))
    concat.compile(Phase.InferencePhase, Array(heapData))

    concat.forward(input)

    val output1 = new Array[Byte](shape.product)
    Memory.CopyPtr2ByteArray(
      concat.output.toTable[Tensor[Float]](1)
        .asInstanceOf[DnnTensor[Byte]].storageAddress(),
      0, output1, 0, shape.product, 1)
    output1.foreach(println)

    val output2 = new Array[Byte](shape.product)
    Memory.CopyPtr2ByteArray(
      concat.output.toTable[Tensor[Float]](1)
        .asInstanceOf[DnnTensor[Byte]].storageAddress(),
      0, output2, 0, shape.product, 1)
    output2.foreach(println)

    output1 should be (output2)
  }
}


text:
#ifndef QV4REGISTERINFO_P_H
#define QV4REGISTERINFO_P_H

#include <QtCore/QString>

QT_BEGIN_NAMESPACE

namespace QV4 {
namespace JIT {

class RegisterInfo
{
public:
    enum { InvalidRegister = (1 << 29) - 1 };
    enum SavedBy { CallerSaved, CalleeSaved };
    enum RegisterType { RegularRegister, FloatingPointRegister };
    enum Usage { Predefined, RegAlloc };

public:
    RegisterInfo()
        : _savedBy(CallerSaved)
        , _usage(Predefined)
        , _type(RegularRegister)
        , _reg(InvalidRegister)
    {}

    RegisterInfo(int reg, const QString &prettyName, RegisterType type, SavedBy savedBy, Usage usage)
        : _prettyName(prettyName)
        , _savedBy(savedBy)
        , _usage(usage)
        , _type(type)
        , _reg(reg)
    {}

    bool operator==(const RegisterInfo &other) const
    { return _type == other._type && _reg == other._reg; }

    bool isValid() const { return _reg != InvalidRegister; }
    template <typename T> T reg() const { return static_cast<T>(_reg); }
    QString prettyName() const { return _prettyName; }
    bool isCallerSaved() const { return _savedBy == CallerSaved; }
    bool isCalleeSaved() const { return _savedBy == CalleeSaved; }
    bool isFloatingPoint() const { return _type == FloatingPointRegister; }
    bool isRegularRegister() const { return _type == RegularRegister; }
    bool useForRegAlloc() const { return _usage == RegAlloc; }
    bool isPredefined() const { return _usage == Predefined; }

private:
    QString _prettyName;
    unsigned _savedBy : 1;
    unsigned _usage   : 1;
    unsigned _type    : 1;
    unsigned _reg     : 29;
};
typedef QVector<RegisterInfo> RegisterInformation;

} // JIT namespace
} // QV4 namespace

QT_END_NAMESPACE

#endif // QV4REGISTERINFO_P_H


text:
<?php

/* WebProfilerBundle:Profiler:info.html.twig */
class __TwigTemplate_8ea15b2fe1547d7d686c7483958344d96aaaebc99a59f7a63425f673323c463c extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 1
        $this->parent = $this->loadTemplate("@WebProfiler/Profiler/layout.html.twig", "WebProfilerBundle:Profiler:info.html.twig", 1);
        $this->blocks = array(
            'summary' => array($this, 'block_summary'),
            'panel' => array($this, 'block_panel'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "@WebProfiler/Profiler/layout.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $__internal_75122bb63f60f958aa1de1d62350d322a7295e2247c7aad99eea93b2130f1388 = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
        $__internal_75122bb63f60f958aa1de1d62350d322a7295e2247c7aad99eea93b2130f1388->enter($__internal_75122bb63f60f958aa1de1d62350d322a7295e2247c7aad99eea93b2130f1388_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "WebProfilerBundle:Profiler:info.html.twig"));

        $__internal_78b3d54c418be3749aba27d91190037c622017553232f9ebd7eca43b744380c1 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_78b3d54c418be3749aba27d91190037c622017553232f9ebd7eca43b744380c1->enter($__internal_78b3d54c418be3749aba27d91190037c622017553232f9ebd7eca43b744380c1_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "WebProfilerBundle:Profiler:info.html.twig"));

        // line 3
        $context["messages"] = array("purge" => array("status" => "success", "title" => "The profiler database was purged successfully", "message" => "Now you need to browse some pages with the Symfony Profiler enabled to collect data."), "no_token" => array("status" => "error", "title" => (((((        // line 11
array_key_exists("token", $context)) ? (_twig_default_filter(($context["token"] ?? $this->getContext($context, "token")), "")) : ("")) == "latest")) ? ("There are no profiles") : ("Token not found")), "message" => (((((        // line 12
array_key_exists("token", $context)) ? (_twig_default_filter(($context["token"] ?? $this->getContext($context, "token")), "")) : ("")) == "latest")) ? ("No profiles found in the database.") : ((("Token \"" . ((array_key_exists("token", $context)) ? (_twig_default_filter(($context["token"] ?? $this->getContext($context, "token")), "")) : (""))) . "\" was not found in the database.")))), "upload_error" => array("status" => "error", "title" => "A problem occurred when uploading the data", "message" => "No file given or the file was not uploaded successfully."), "already_exists" => array("status" => "error", "title" => "A problem occurred when uploading the data", "message" => "The token already exists in the database."));
        // line 1
        $this->parent->display($context, array_merge($this->blocks, $blocks));

        $__internal_75122bb63f60f958aa1de1d62350d322a7295e2247c7aad99eea93b2130f1388->leave($__internal_75122bb63f60f958aa1de1d62350d322a7295e2247c7aad99eea93b2130f1388_prof);

        $__internal_78b3d54c418be3749aba27d91190037c622017553232f9ebd7eca43b744380c1->leave($__internal_78b3d54c418be3749aba27d91190037c622017553232f9ebd7eca43b744380c1_prof);

    }

    // line 26
    public function block_summary($context, array $blocks = array())
    {
        $__internal_3993679256b440fb535e125e7ffae70e55979afc8d691efba07fef34ffba439d = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
        $__internal_3993679256b440fb535e125e7ffae70e55979afc8d691efba07fef34ffba439d->enter($__internal_3993679256b440fb535e125e7ffae70e55979afc8d691efba07fef34ffba439d_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "summary"));

        $__internal_beddf7c2a523a897e7c7079484bc61c7e5e85593fb4f80e5cbe61ba7438bf27e = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_beddf7c2a523a897e7c7079484bc61c7e5e85593fb4f80e5cbe61ba7438bf27e->enter($__internal_beddf7c2a523a897e7c7079484bc61c7e5e85593fb4f80e5cbe61ba7438bf27e_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "summary"));

        // line 27
        echo "
env, $this->getAttribute($this->getAttribute(($context["messages"] ?? $this->getContext($context, "messages")), ($context["about"] ?? $this->getContext($context, "about")), array(), "array"), "status", array()), "html", null, true);
        echo "\">

";
        // line 29
        echo twig_escape_filter($this->env, twig_title_string_filter($this->env, $this->getAttribute($this->getAttribute(($context["messages"] ?? $this->getContext($context, "messages")), ($context["about"] ?? $this->getContext($context, "about")), array(), "array"), "status", array())), "html", null, true);
        echo "

";

        $__internal_beddf7c2a523a897e7c7079484bc61c7e5e85593fb4f80e5cbe61ba7438bf27e->leave($__internal_beddf7c2a523a897e7c7079484bc61c7e5e85593fb4f80e5cbe61ba7438bf27e_prof);

        $__internal_3993679256b440fb535e125e7ffae70e55979afc8d691efba07fef34ffba439d->leave($__internal_3993679256b440fb535e125e7ffae70e55979afc8d691efba07fef34ffba439d_prof);

    }

    // line 34
    public function block_panel($context, array $blocks = array())
    {
        $__internal_b61e200a2ce5826051fadbe83071e8f592538e0e72079814ca59b93b414f66f0 = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension");
        $__internal_b61e200a2ce5826051fadbe83071e8f592538e0e72079814ca59b93b414f66f0->enter($__internal_b61e200a2ce5826051fadbe83071e8f592538e0e72079814ca59b93b414f66f0_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "panel"));

        $__internal_e9ae7f4a36c9c2ef7dfd83cfda760ddff981a263dcd5573037a5da46ff9c445a = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension");
        $__internal_e9ae7f4a36c9c2ef7dfd83cfda760ddff981a263dcd5573037a5da46ff9c445a->enter($__internal_e9ae7f4a36c9c2ef7dfd83cfda760ddff981a263dcd5573037a5da46ff9c445a_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "panel"));

        // line 35
        echo "
";
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute(($context["messages"] ?? $this->getContext($context, "messages")), ($context["about"] ?? $this->getContext($context, "about")), array(), "array"), "title", array()), "html", null, true);
        echo "

";
        // line 36
        echo twig_escape_filter($this->env, $this->getAttribute($this->getAttribute(($context["messages"] ?? $this->getContext($context, "messages")), ($context["about"] ?? $this->getContext($context, "about")), array(), "array"), "message", array()), "html", null, true);
        echo "

";

        $__internal_e9ae7f4a36c9c2ef7dfd83cfda760ddff981a263dcd5573037a5da46ff9c445a->leave($__internal_e9ae7f4a36c9c2ef7dfd83cfda760ddff981a263dcd5573037a5da46ff9c445a_prof);

        $__internal_b61e200a2ce5826051fadbe83071e8f592538e0e72079814ca59b93b414f66f0->leave($__internal_b61e200a2ce5826051fadbe83071e8f592538e0e72079814ca59b93b414f66f0_prof);

    }

    public function getTemplateName()
    {
        return "WebProfilerBundle:Profiler:info.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  89 => 36,  84 => 35,  75 => 34,  61 => 29,  55 => 27,  46 => 26,  36 => 1,  34 => 12,  33 => 11,  32 => 3,  11 => 1,);
    }

    /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */
    public function getSource()
    {
        @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);

        return $this->getSourceContext()->getCode();
    }

    public function getSourceContext()
    {
        return new Twig_Source("{% extends '@WebProfiler/Profiler/layout.html.twig' %}

{% set messages = {
    'purge' : {
        status:  'success',
        title:   'The profiler database was purged successfully',
        message: 'Now you need to browse some pages with the Symfony Profiler enabled to collect data.'
    },
    'no_token' : {
        status:  'error',
        title:   (token|default('') == 'latest') ? 'There are no profiles' : 'Token not found',
        message: (token|default('') == 'latest') ? 'No profiles found in the database.' : 'Token \"' ~ token|default('') ~ '\" was not found in the database.'
    },
    'upload_error' : {
        status:  'error',
        title:   'A problem occurred when uploading the data',
        message: 'No file given or the file was not uploaded successfully.'
    },
    'already_exists' : {
        status:  'error',
        title:   'A problem occurred when uploading the data',
        message: 'The token already exists in the database.'
    }
} %}

{% block summary %}

{{ messages[about].status|title }}

{% endblock %}

{% block panel %}

{{ messages[about].title }}

{{ messages[about].message }}

{% endblock %}
", "WebProfilerBundle:Profiler:info.html.twig", "C:\\wamp64\\www\\Projet\\CFPMS\\siteweb\\dudeego\\vendor\\symfony\\symfony\\src\\Symfony\\Bundle\\WebProfilerBundle/Resources/views/Profiler/info.html.twig");
    }
}


text:
<?php

namespace Cupon\OfertaBundle\Tests\Entity;

use Symfony\Component\Validator\Validation;
use Cupon\OfertaBundle\Entity\Oferta;

class OfertaTest extends \PHPUnit_Framework_TestCase
{
	/*private $validator;

	public function setUp()
	{
		$this->validator = Validation::createValidatorBuilder()
		->enableAnnotationMapping()
		->getValidator();
	}

	public function testValidarSlug()
	{
		$oferta = new Oferta();
		$oferta->setNombre('Oferta de prueba');
		$slug = $oferta->getSlug();
		$this->assertEquals('oferta-de-prueba', $slug,
		'El slug se asigna automáticamente a partir del nombre'
		);
	}

	public function testValidarDescripcion()
	{
		$oferta = new Oferta();
		$oferta->setNombre('Oferta de prueba');
		$listaErrores = $this->validator->validate($oferta);
		$this->assertGreaterThan(0, $listaErrores->count(),
		'La descripción no puede dejarse en blanco'
		);

		$error = $listaErrores[0];
		$this->assertEquals('This value should not be blank.',
		$error->getMessage());
		$this->assertEquals('descripcion', $error->getPropertyPath());
		$oferta->setDescripcion('Descripción de prueba');
		$listaErrores = $this->validator->validate($oferta);
		$this->assertGreaterThan(0, $listaErrores->count(),
		'La descripción debe tener al menos 30 caracteres'
		);

		$error = $listaErrores[0];
		$this->assertRegExp("/This value is too short/", $error->getMessage());
		$this->assertEquals('descripcion', $error->getPropertyPath());
	}

	public function testValidarFechas()
	{
		$oferta = new Oferta();
		$oferta->setNombre('Oferta de prueba');
		$oferta->setDescripcion('Descripción de prueba - Descripción de prueba
		- Descripción de prueba');
		$oferta->setFechaPublicacion(new \DateTime('today'));
		$oferta->setFechaExpiracion(new \DateTime('yesterday'));
		$listaErrores = $this->validator->validate($oferta);
		$this->assertGreaterThan(0, $listaErrores->count(),
		'La fecha de expiración debe ser posterior a la fecha de
		publicación'
		);

		$error = $listaErrores[0];
		$this->assertEquals('La fecha de expiración debe ser posterior a la
		fecha de publicación', $error->getMessage());
		$this->assertEquals('fechaValida', $error->getPropertyPath());
	}

	public function testValidarPrecio()
	{
		$oferta = new Oferta();
		$oferta->setNombre('Oferta de prueba');
		$oferta->setDescripcion('Descripción de prueba - Descripción de prueba
		- Descripción de prueba');
		$oferta->setFechaPublicacion(new \DateTime('today'));
		$oferta->setFechaExpiracion(new \DateTime('tomorrow'));
		$oferta->setUmbral(3);
		$oferta->setPrecio(-10);
		$listaErrores = $this->validator->validate($oferta);
		$this->assertGreaterThan(0, $listaErrores->count(),
		'El precio no puede ser un número negativo'
		);
		$error = $listaErrores[0];
		$this->assertRegExp("/This value should be .* or more/",
		$error->getMessageTemplate());
		$this->assertEquals('precio', $error->getPropertyPath());
	}*/
}


text:
module StorageResourceHelper::TextualSummary
  include TextualMixins::TextualGroupTags

  #
  # Groups
  #

  def textual_group_properties
    TextualGroup.new(
      _("Properties"),
      %i[
        name
        logical_free
        logical_total
      ]
    )
  end

  def textual_group_relationships
  end

  #
  # Items
  #

  def textual_name
    {:label => _("Name"), :value => @record.name}
  end

  def textual_logical_free
    {:label => _("Free Space"), :value => number_to_human_size(@record.logical_free, :precision => 2)}
  end

  def textual_logical_total
    {:label => _("Total Size"), :value => number_to_human_size(@record.logical_total, :precision => 2)}
  end
end


text:
function CookieBanner (module) {
    this.module = module;
    this.settings = {
      seenCookieName: 'DASSeenCookieMessage',
      env: window.GOVUK.getEnv(),
      cookiePolicy: {
        AnalyticsConsent: false
      }
    }
    if ( !window.GOVUK.cookie(this.settings.seenCookieName + this.settings.env) ) {
      this.start()
    }
  }

  CookieBanner.prototype.start = function () {
    this.module.cookieBanner = this.module.querySelector('.das-cookie-banner')
    this.module.cookieBannerInnerWrap = this.module.querySelector('.das-cookie-banner__wrapper')
    this.module.cookieBannerConfirmationMessage = this.module.querySelector('.das-cookie-banner__confirmation')
    this.setupCookieMessage()
  }

  CookieBanner.prototype.setupCookieMessage = function () {
    this.module.hideLink = this.module.querySelector('button[data-hide-cookie-banner]')
    this.module.acceptCookiesButton = this.module.querySelector('button[data-accept-cookies]')

    if (this.module.hideLink) {
      this.module.hideLink.addEventListener('click', this.hideCookieBanner.bind(this))
    }

    if (this.module.acceptCookiesButton) {
      this.module.acceptCookiesButton.addEventListener('click', this.acceptAllCookies.bind(this))
    }
    this.showCookieBanner()
  }

  CookieBanner.prototype.showCookieBanner = function () {
    var cookiePolicy = this.settings.cookiePolicy,
        that = this;
    this.module.cookieBanner.style.display = 'block';

    // Create the default cookies based on settings
    Object.keys(cookiePolicy).forEach(function (cookieName) {
      window.GOVUK.cookie(cookieName + that.settings.env, cookiePolicy[cookieName].toString(), { days: 365 })
    });

  }

  CookieBanner.prototype.hideCookieBanner = function () {
    this.module.cookieBanner.style.display = 'none';
    window.GOVUK.cookie(this.settings.seenCookieName + this.settings.env, true, { days: 365 })
  }

  CookieBanner.prototype.acceptAllCookies = function () {
    var that = this;
    this.module.cookieBannerInnerWrap.style.display = 'none';
    this.module.cookieBannerConfirmationMessage.style.display = 'block';

    window.GOVUK.cookie(this.settings.seenCookieName + this.settings.env, true, { days: 365 })

    Object.keys(this.settings.cookiePolicy).forEach(function (cookieName) {
      window.GOVUK.cookie(cookieName + that.settings.env, true, { days: 365 })
    });
  }

  window.GOVUK = window.GOVUK || {}

  window.GOVUK.cookie = function (name, value, options) {
      if (typeof value !== 'undefined') {
        if (value === false || value === null) {
          return window.GOVUK.setCookie(name, '', { days: -1 })
        } else {
          // Default expiry date of 30 days
          if (typeof options === 'undefined') {
            options = { days: 30 }
          }
          return window.GOVUK.setCookie(name, value, options)
        }
      } else {
        return window.GOVUK.getCookie(name)
      }
    }

    window.GOVUK.setCookie = function (name, value, options) {

        if (typeof options === 'undefined') {
         options = {}
        }

        var cookieString = name + '=' + value + '; path=/;SameSite=None'

        if (options.days) {
          var date = new Date()
          date.setTime(date.getTime() + (options.days * 24 * 60 * 60 * 1000))
          cookieString = cookieString + '; expires=' + date.toGMTString()
        }

        if (!options.domain) {
          options.domain = window.GOVUK.getDomain()
        }

        if (document.location.protocol === 'https:') {
          cookieString = cookieString + '; Secure'
        }

        document.cookie = cookieString  + ';domain=' + options.domain
    }

    window.GOVUK.getCookie = function (name) {
      var nameEQ = name + '='
      var cookies = document.cookie.split(';')
      for (var i = 0, len = cookies.length; i < len; i++) {
        var cookie = cookies[i]
        while (cookie.charAt(0) === ' ') {
          cookie = cookie.substring(1, cookie.length)
        }
        if (cookie.indexOf(nameEQ) === 0) {
          return decodeURIComponent(cookie.substring(nameEQ.length))
        }
      }
      return null
    }

    window.GOVUK.getDomain = function () {
      return window.location.hostname.indexOf('.') !== -1
      ? '.' + window.location.hostname.slice(window.location.hostname.indexOf('.') + 1)
      : window.location.hostname;
    }

    window.GOVUK.getEnv = function () {
      var domain = window.location.hostname;
      if (domain.indexOf("at-") >= 0) {
        return "AT"
      }
      if (domain.indexOf("test-") >= 0) {
        return "TEST"
      }
      if (domain.indexOf("test2-") >= 0) {
        return "TEST2"
      }
      if (domain.indexOf("pp-") >= 0) {
        return "PP"
      }
      return "";
    }

  // Legacy cookie clean up

  var currentDomain = window.location.hostname;
  var cookieDomain = window.GOVUK.getDomain();

  if (currentDomain !== cookieDomain) {
      // Delete the 3 legacy cookies without the domain attribute defined
      document.cookie = "DASSeenCookieMessage=false; path=/;SameSite=None; expires=Thu, 01 Jan 1970 00:00:01 GMT";
      document.cookie = "AnalyticsConsent=false; path=/;SameSite=None; expires=Thu, 01 Jan 1970 00:00:01 GMT";
      document.cookie = "MarketingConsent=false; path=/;SameSite=None; expires=Thu, 01 Jan 1970 00:00:01 GMT";
  }

  var $cookieBanner = document.querySelector('[data-module="cookie-banner"]');
  if ($cookieBanner != null) {
      new CookieBanner($cookieBanner);
  }


text:
package table

// Resolver is an interface implemented by objects that can lookup an ACPI table
// by its name.
//
// LookupTable attempts to locate a table by name returning back a pointer to
// its standard header or nil if the table could not be found. The resolver
// must make sure that the entire table contents are mapped so they can be
// accessed by the caller.
type Resolver interface {
	LookupTable(string) *SDTHeader
}

// RSDPDescriptor defines the root system descriptor pointer for ACPI 1.0. This
// is used as the entry-point for parsing ACPI data.
type RSDPDescriptor struct {
	// The signature must contain "RSD PTR " (last byte is a space).
	Signature [8]byte

	// A value that when added to the sum of all other bytes contained in
	// this descriptor should result in the value 0.
	Checksum uint8

	OEMID [6]byte

	// ACPI revision number. It is 0 for ACPI1.0 and 2 for versions 2.0 to 6.2.
	Revision uint8

	// Physical address of 32-bit root system descriptor table.
	RSDTAddr uint32
}

// ExtRSDPDescriptor extends RSDPDescriptor with additional fields. It is used
// when RSDPDescriptor.revision > 1.
type ExtRSDPDescriptor struct {
	RSDPDescriptor

	// The size of the 64-bit root system descriptor table.
	Length uint32

	// Physical address of 64-bit root system descriptor table.
	XSDTAddr uint64

	// A value that when added to the sum of all other bytes contained in
	// this descriptor should result in the value 0.
	ExtendedChecksum uint8

	reserved [3]byte
}

// SDTHeader defines the common header for all ACPI-related tables.
type SDTHeader struct {
	// The signature defines the table type.
	Signature [4]byte

	// The length of the table
	Length uint32

	// If this header belongs to a DSDT/SSDT table, the revision is also
	// used to indicate whether the AML VM should treat integers as 32-bits
	// (revision < 2) or 64-bits (revision >= 2).
	Revision uint8

	// A value that when added to the sum of all other bytes in the table
	// should result in the value 0.
	Checksum uint8

	// OEM specific information
	OEMID       [6]byte
	OEMTableID  [8]byte
	OEMRevision uint32

	// Information about the ASL compiler that generated this table
	CreatorID       uint32
	CreatorRevision uint32
}

// AddressSpace defines the location where a set of registers resides.
type AddressSpace uint8

// The list of supported address space types.
const (
	AddressSpaceSysMemory AddressSpace = iota
	AddressSpaceSysIO
	AddressSpacePCI
	AddressSpaceEmbController
	AddressSpaceSMBus
	AddressSpaceFuncFixedHW = 0x7f
)

// GenericAddress specifies a register range located in a particular address
// space.
type GenericAddress struct {
	Space      AddressSpace
	BitWidth   uint8
	BitOffset  uint8
	AccessSize uint8
	Address    uint64
}

// PowerProfileType describes a power profile referenced by the FADT table.
type PowerProfileType uint8

// The list of supported power profile types
const (
	PowerProfileUnspecified PowerProfileType = iota
	PowerProfileDesktop
	PowerProfileMobile
	PowerProfileWorkstation
	PowerProfileEnterpriseServer
	PowerProfileSOHOServer
	PowerProfileAppliancePC
	PowerProfilePerformanceServer
)

// FADT64 contains the 64-bit FADT extensions which are used by ACPI2+
type FADT64 struct {
	FirmwareControl uint64

	Dsdt uint64

	PM1aEventBlock   GenericAddress
	PM1bEventBlock   GenericAddress
	PM1aControlBlock GenericAddress
	PM1bControlBlock GenericAddress
	PM2ControlBlock  GenericAddress
	PMTimerBlock     GenericAddress
	GPE0Block        GenericAddress
	GPE1Block        GenericAddress
}

// FADT (Fixed ACPI Description Table) is an ACPI table containing information
// about fixed register blocks used for power management.
type FADT struct {
	SDTHeader

	FirmwareCtrl uint32
	Dsdt         uint32

	reserved uint8

	PreferredPowerManagementProfile PowerProfileType
	SCIInterrupt                    uint16
	SMICommandPort                  uint32
	AcpiEnable                      uint8
	AcpiDisable                     uint8
	S4BIOSReq                       uint8
	PSTATEControl                   uint8
	PM1aEventBlock                  uint32
	PM1bEventBlock                  uint32
	PM1aControlBlock                uint32
	PM1bControlBlock                uint32
	PM2ControlBlock                 uint32
	PMTimerBlock                    uint32
	GPE0Block                       uint32
	GPE1Block                       uint32
	PM1EventLength                  uint8
	PM1ControlLength                uint8
	PM2ControlLength                uint8
	PMTimerLength                   uint8
	GPE0Length                      uint8
	GPE1Length                      uint8
	GPE1Base                        uint8
	CStateControl                   uint8
	WorstC2Latency                  uint16
	WorstC3Latency                  uint16
	FlushSize                       uint16
	FlushStride                     uint16
	DutyOffset                      uint8
	DutyWidth                       uint8
	DayAlarm                        uint8
	MonthAlarm                      uint8
	Century                         uint8

	// Reserved in ACPI 1.0; used since ACPI 2.0+
	BootArchitectureFlags uint16

	reserved2 uint8
	Flags     uint32

	ResetReg GenericAddress

	ResetValue uint8
	reserved3  [3]uint8

	// 64-bit pointers to the above structures used by ACPI 2.0+
	Ext FADT64
}

// MADT (Multiple APIC Description Table) is an ACPI table containing
// information about the interrupt controllers and the number of installed
// CPUs. Following the table header are a series of variable sized records
// (MADTEntry) which contain additional information.
type MADT struct {
	SDTHeader

	LocalControllerAddress uint32
	Flags                  uint32
}

// MADTEntryLocalAPIC describes a single physical processor and its local
// interrupt controller.
type MADTEntryLocalAPIC struct {
	ProcessorID uint8
	APICID      uint8
	Flags       uint32
}

// MADTEntryIOAPIC describes an I/O Advanced Programmable Interrupt Controller.
type MADTEntryIOAPIC struct {
	APICID   uint8
	reserved uint8

	// Address contains the address of the controller.
	Address uint32

	// SysInterruptBase defines the first interrupt number that this
	// controller handles.
	SysInterruptBase uint32
}

// MADTEntryInterruptSrcOverride contains the data for an Interrupt Source
// Override.  This mechanism is used to map IRQ sources to global system
// interrupts.
type MADTEntryInterruptSrcOverride struct {
	BusSrc          uint8
	IRQSrc          uint8
	GlobalInterrupt uint32
	Flags           uint16
}

// MADTEntryNMI describes a non-maskable interrupt that we need to set up for
// a single processor or all processors.
type MADTEntryNMI struct {
	// Processor specifies the local APIC that we need to configure for
	// this NMI. If set to 0xff we need to configure all processor APICs.
	Processor uint8

	Flags uint16

	// This value will be either 0 or 1 and specifies which entry in the
	// local vector table of the processor's local APIC we need to setup.
	LINT uint8
}

// MADTEntryType describes the type of a MADT record.
type MADTEntryType uint8

// The list of supported MADT entry types.
const (
	MADTEntryTypeLocalAPIC MADTEntryType = iota
	MADTEntryTypeIOAPIC
	MADTEntryTypeIntSrcOverride
	MADTEntryTypeNMI
)

// MADTEntry describes a MADT table entry that follows the MADT definition. As
// MADT entries are variable sized records, this struct works as a union. The
// consumer of this struct must check the type value before accessing the union
// values.
type MADTEntry struct {
	Type   MADTEntryType
	Length uint8
}


text:
package org.ovirt.engine.api.restapi.resource.externalhostproviders;

import java.util.List;

import org.ovirt.engine.api.model.Host;
import org.ovirt.engine.api.model.KatelloErrata;
import org.ovirt.engine.api.model.KatelloErratum;
import org.ovirt.engine.api.resource.externalhostproviders.KatelloErrataResource;
import org.ovirt.engine.api.resource.externalhostproviders.KatelloErratumResource;
import org.ovirt.engine.api.restapi.resource.AbstractBackendCollectionResource;
import org.ovirt.engine.core.common.businessentities.Erratum;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryType;

public class BackendHostKatelloErrataResource extends AbstractBackendCollectionResource<KatelloErratum, Erratum> implements KatelloErrataResource {

    private String hostId;

    public BackendHostKatelloErrataResource(String hostId) {
        super(KatelloErratum.class, Erratum.class);
        this.hostId = hostId;
    }

    @Override
    public KatelloErrata list() {
        return mapCollection(getBackendCollection(VdcQueryType.GetErrataForHost, new IdQueryParameters(asGuid(hostId))));
    }

    private KatelloErrata mapCollection(List<Erratum> entities) {
        KatelloErrata collection = new KatelloErrata();
        for (org.ovirt.engine.core.common.businessentities.Erratum entity : entities) {
            collection.getKatelloErrata().add(addLinks(populate(map(entity), entity), Host.class));
        }

        return collection;
    }

    @Override
    public KatelloErratumResource getKatelloErratumSubResource(String id) {
        return inject(new BackendHostKatelloErratumResource(id, hostId));
    }

    @Override
    protected KatelloErratum addParents(KatelloErratum erratum) {
        Host host = new Host();
        host.setId(hostId);
        erratum.setHost(host);
        return super.addParents(erratum);
    }
}


text:
<?php
/**
 * This file is part of BraincraftedBootstrapBundle.
 * (c) 2012-2013 by Florian Eckerstorfer
 */

namespace Braincrafted\Bundle\BootstrapBundle\Twig;

/**
 * BootstrapFormExtension
 *
 * @package    BraincraftedBootstrapBundle
 * @subpackage Twig
 * @author     Florian Eckerstorfer <florian@eckerstorfer.co>
 * @copyright  2012-2013 Florian Eckerstorfer
 * @license    http://opensource.org/licenses/MIT The MIT License
 * @link       http://bootstrap.braincrafted.com Bootstrap for Symfony2
 */
class BootstrapFormExtension extends \Twig_Extension
{
    /** @var string */
    private $style;

    /** @var string */
    private $colSize = 'lg';

    /** @var integer */
    private $widgetCol = 10;

    /** @var integer */
    private $labelCol = 2;

    /** @var integer */
    private $simpleCol = false;

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('bootstrap_set_style', array($this, 'setStyle')),
            new \Twig_SimpleFunction('bootstrap_get_style', array($this, 'getStyle')),
            new \Twig_SimpleFunction('bootstrap_set_col_size', array($this, 'setColSize')),
            new \Twig_SimpleFunction('bootstrap_get_col_size', array($this, 'getColSize')),
            new \Twig_SimpleFunction('bootstrap_set_widget_col', array($this, 'setWidgetCol')),
            new \Twig_SimpleFunction('bootstrap_get_widget_col', array($this, 'getWidgetCol')),
            new \Twig_SimpleFunction('bootstrap_set_label_col', array($this, 'setLabelCol')),
            new \Twig_SimpleFunction('bootstrap_get_label_col', array($this, 'getLabelCol')),
            new \Twig_SimpleFunction('bootstrap_set_simple_col', array($this, 'setSimpleCol')),
            new \Twig_SimpleFunction('bootstrap_get_simple_col', array($this, 'getSimpleCol')),
            'checkbox_row'  => new \Twig_Function_Node(
                'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode',
                array('is_safe' => array('html'))
            ),
            'radio_row'  => new \Twig_Function_Node(
                'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode',
                array('is_safe' => array('html'))
            ),
            'global_form_errors'  => new \Twig_Function_Node(
                'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode',
                array('is_safe' => array('html'))
            )
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'braincrafted_bootstrap_form';
    }

    /**
     * Sets the style.
     *
     * @param string $style Name of the style
     */
    public function setStyle($style)
    {
        $this->style = $style;
    }

    /**
     * Returns the style.
     *
     * @return string Name of the style
     */
    public function getStyle()
    {
        return $this->style;
    }

    /**
     * Sets the column size.
     *
     * @param string $colSize Column size (xs, sm, md or lg)
     */
    public function setColSize($colSize)
    {
        $this->colSize = $colSize;
    }

    /**
     * Returns the column size.
     *
     * @return string Column size (xs, sm, md or lg)
     */
    public function getColSize()
    {
        return $this->colSize;
    }

    /**
     * Sets the number of columns of widgets.
     *
     * @param integer $widgetCol Number of columns.
     */
    public function setWidgetCol($widgetCol)
    {
        $this->widgetCol = $widgetCol;
    }

    /**
     * Returns the number of columns of widgets.
     *
     * @return integer Number of columns.
     */
    public function getWidgetCol()
    {
        return $this->widgetCol;
    }

    /**
     * Sets the number of columns of labels.
     *
     * @param integer $labelCol Number of columns.
     */
    public function setLabelCol($labelCol)
    {
        $this->labelCol = $labelCol;
    }

    /**
     * Returns the number of columns of labels.
     *
     * @return integer Number of columns.
     */
    public function getLabelCol()
    {
        return $this->labelCol;
    }

    /**
     * Sets the number of columns of simple widgets.
     *
     * @param integer $simpleCol Number of columns.
     */
    public function setSimpleCol($simpleCol)
    {
        $this->simpleCol = $simpleCol;
    }

    /**
     * Returns the number of columns of simple widgets.
     *
     * @return integer Number of columns.
     */
    public function getSimpleCol()
    {
        return $this->simpleCol;
    }
}


text:
export KUBERNETES_MASTER_IP=10.211.56.101
export KUBERNETES_MASTER="http://10.211.56.101:8888"
export PATH="$PATH:/usr/local/src/kubernetes/_output/local/go/bin:/usr/local/src/kubernetes.git/_output/local/bin/linux/amd64"
export MESOS_MASTER=10.211.56.101:5050


text:
package rockredis

import (
	"errors"
	"sync"
	"sync/atomic"
	"time"

	"github.com/youzan/ZanRedisDB/common"
	"github.com/youzan/ZanRedisDB/engine"
)

var localExpCheckInterval = 300

const (
	localBatchedBufSize = 16 * 1024
	// should less than max batch keys for batch write
	localBatchedMaxKeysNum = 1024
)

var (
	ErrLocalBatchFullToCommit = errors.New("batched is fully filled and should commit right now")
	ErrLocalBatchedBuffFull   = errors.New("the local batched buffer is fully filled")
	errTTLCheckTooLong        = errors.New("the local ttl scan take too long")
	errChangeTTLNotSupported  = errors.New("change ttl is not supported in current expire policy")
)

type localExpiration struct {
	*TTLChecker
	db      *RockDB
	stopCh  chan struct{}
	wg      sync.WaitGroup
	running int32
}

func newLocalExpiration(db *RockDB) *localExpiration {
	exp := &localExpiration{
		db:         db,
		TTLChecker: newTTLChecker(db),
	}

	return exp
}

func (exp *localExpiration) encodeToVersionKey(dt byte, h *headerMetaValue, key []byte) []byte {
	return key
}

func (exp *localExpiration) decodeFromVersionKey(dt byte, key []byte) ([]byte, int64, error) {
	return key, 0, nil
}

func (exp *localExpiration) encodeToRawValue(dataType byte, h *headerMetaValue) []byte {
	return h.UserData
}

func (exp *localExpiration) decodeRawValue(dataType byte, rawValue []byte) (*headerMetaValue, error) {
	var h headerMetaValue
	h.UserData = rawValue
	return &h, nil
}

func (exp *localExpiration) getRawValueForHeader(ts int64, dataType byte, key []byte) ([]byte, error) {
	return nil, nil
}

func (exp *localExpiration) isExpired(ts int64, dataType byte, key []byte, rawValue []byte, useLock bool) (bool, error) {
	return false, nil
}

func (exp *localExpiration) ExpireAt(dataType byte, key []byte, rawValue []byte, when int64) (int64, error) {
	if when == 0 {
		return 0, errChangeTTLNotSupported
	}
	wb := exp.db.wb
	defer wb.Clear()
	_, err := exp.rawExpireAt(dataType, key, rawValue, when, wb)
	if err != nil {
		return 0, err
	}
	if err := exp.db.rockEng.Write(wb); err != nil {
		return 0, err
	}
	return 1, nil
}

func (exp *localExpiration) rawExpireAt(dataType byte, key []byte, rawValue []byte, when int64, wb engine.WriteBatch) ([]byte, error) {
	tk := expEncodeTimeKey(dataType, key, when)
	mk := expEncodeMetaKey(dataType, key)
	wb.Put(tk, mk)
	exp.setNextCheckTime(when, false)
	return rawValue, nil
}

func (exp *localExpiration) ttl(int64, byte, []byte, []byte) (int64, error) {
	return -1, nil
}

func (exp *localExpiration) renewOnExpired(ts int64, dataType byte, key []byte, oldh *headerMetaValue) {
	// local expire should not renew on expired data, since it will be checked by expire handler
	// and it will clean ttl and all the sub data
	return
}

func (exp *localExpiration) delExpire(dt byte, key []byte, rawv []byte, keepV bool, wb engine.WriteBatch) ([]byte, error) {
	return rawv, nil
}

func (exp *localExpiration) check(buffer common.ExpiredDataBuffer, stop chan struct{}) error {
	return errors.New("can not check expired data through local expiration policy")
}

func (exp *localExpiration) Start() {
	if atomic.CompareAndSwapInt32(&exp.running, 0, 1) {
		exp.stopCh = make(chan struct{})
		exp.wg.Add(1)
		go func() {
			defer exp.wg.Done()
			exp.applyExpiration(exp.stopCh)
		}()
	}
}

func (exp *localExpiration) applyExpiration(stop chan struct{}) {
	dbLog.Infof("start to apply-expiration using Local-Deletion policy")
	defer dbLog.Infof("apply-expiration using Local-Deletion policy exit")

	t := time.NewTicker(time.Second * time.Duration(localExpCheckInterval))
	defer t.Stop()

	checker := exp.TTLChecker
	localBuffer := newLocalBatchedBuffer(exp.db, localBatchedBufSize)
	defer localBuffer.Destroy()
	for {
		select {
		case <-t.C:
			for {
				err := checker.check(localBuffer, stop)
				select {
				case <-stop:
					localBuffer.Clear()
					return
				default:
					localBuffer.commit()
				}
				//start the next check immediately if the last check is stopped because of the buffer is fully filled
				if err == ErrLocalBatchedBuffFull {
					// avoid 100% cpu
					time.Sleep(time.Millisecond)
					continue
				} else if err == errTTLCheckTooLong {
					// do not do manual compact ttl here, it may cause write stall
					//
				} else if err != nil {
					dbLog.Errorf("check expired data failed at applying expiration, err:%s", err.Error())
				}
				break
			}
		case <-stop:
			return
		}
	}
}

type localBatchedBuffer struct {
	db      *RockDB
	buff    []*expiredMeta
	batched [common.ALL - common.NONE]*localBatch
	cap     int
}

func newLocalBatchedBuffer(db *RockDB, cap int) *localBatchedBuffer {
	batchedBuff := &localBatchedBuffer{
		buff: make([]*expiredMeta, 0, cap),
		db:   db,
		cap:  cap,
	}

	types := []common.DataType{common.KV, common.LIST, common.HASH,
		common.SET, common.ZSET}

	for _, t := range types {
		batchedBuff.batched[t] = newLocalBatch(db, t)
	}

	return batchedBuff
}

func (lbb *localBatchedBuffer) Clear() {
	lbb.buff = lbb.buff[:0]
	for _, b := range lbb.batched {
		if b != nil {
			b.clear()
		}
	}
}

func (lbb *localBatchedBuffer) Destroy() {
	for _, b := range lbb.batched {
		if b != nil {
			b.destroy()
		}
	}
}

func (self *localBatchedBuffer) Write(meta *expiredMeta) error {
	if len(self.buff) >= self.cap {
		return ErrLocalBatchedBuffFull
	} else {
		self.buff = append(self.buff, meta)
		return nil
	}
}

func (self *localBatchedBuffer) commit() {
	if len(self.buff) == 0 {
		return
	}

	for _, v := range self.buff {
		dt, key, _, err := expDecodeTimeKey(v.timeKey)
		if err != nil || dataType2CommonType(dt) == common.NONE {
			// currently the bitmap/json type is not supported
			if err != nil {
				dbLog.Errorf("decode time-key failed, bad data encounter, err:%s, %v", err, dt)
			}
			continue
		}

		batched := self.batched[dataType2CommonType(dt)]

		err = batched.propose(v.timeKey, v.metaKey, key)
		if err == ErrLocalBatchFullToCommit {
			err = batched.commit()

			//propose the expired-data again as the
			//last propose has failed as the buffer is full
			batched.propose(v.timeKey, v.metaKey, key)
		}
		if err != nil {
			dbLog.Errorf("batch delete expired data of type:%s failed, err:%s", TypeName[dt], err.Error())
		}
	}

	//clean the buffer
	self.buff = self.buff[:0]
	for t := common.KV; t < common.ALL; t++ {
		if err := self.batched[t].commit(); err != nil {
			dbLog.Errorf("batch delete expired data of type:%s failed, err:%s", common.DataType(t).String(), err.Error())
		}
	}
}

func (exp *localExpiration) Stop() {
	if atomic.CompareAndSwapInt32(&exp.running, 1, 0) {
		close(exp.stopCh)
		exp.wg.Wait()
	}
}

func (exp *localExpiration) Destroy() {
	exp.Stop()
}

func createLocalDelFunc(dt common.DataType, db *RockDB, wb engine.WriteBatch) func(keys [][]byte) error {
	switch dt {
	case common.KV:
		return func(keys [][]byte) error {
			defer wb.Clear()
			for _, k := range keys {
				db.KVDelWithBatch(k, wb)
			}
			err := db.rockEng.Write(wb)
			if err != nil {
				return err
			}
			for _, k := range keys {
				db.delPFCache(k)
			}
			return nil
		}
	case common.HASH:
		return func(keys [][]byte) error {
			defer wb.Clear()
			for _, hkey := range keys {
				if err := db.hClearWithBatch(hkey, wb); err != nil {
					return err
				}
			}
			return db.rockEng.Write(wb)
		}
	case common.LIST:
		return func(keys [][]byte) error {
			defer wb.Clear()
			if err := db.lMclearWithBatch(wb, keys...); err != nil {
				return err
			}
			return db.rockEng.Write(wb)
		}
	case common.SET:
		return func(keys [][]byte) error {
			defer wb.Clear()
			if err := db.sMclearWithBatch(wb, keys...); err != nil {
				return err
			}
			return db.rockEng.Write(wb)
		}
	case common.ZSET:
		return func(keys [][]byte) error {
			defer wb.Clear()
			if err := db.zMclearWithBatch(wb, keys...); err != nil {
				return err
			}
			return db.rockEng.Write(wb)
		}
	default:
		// TODO: currently bitmap/json is not handled
		return nil
	}
}

type localBatch struct {
	keys       [][]byte
	dt         common.DataType
	wb         engine.WriteBatch
	localDelFn func([][]byte) error
}

func newLocalBatch(db *RockDB, dt common.DataType) *localBatch {
	batch := &localBatch{
		dt:   dt,
		wb:   db.rockEng.NewWriteBatch(),
		keys: make([][]byte, 0, localBatchedMaxKeysNum),
	}
	batch.localDelFn = createLocalDelFunc(dt, db, batch.wb)
	return batch
}

func (batch *localBatch) clear() {
	if batch.wb != nil {
		batch.wb.Clear()
	}
	batch.keys = batch.keys[:0]
}

func (batch *localBatch) destroy() {
	if batch.wb != nil {
		batch.wb.Destroy()
	}
}

func (batch *localBatch) commit() error {
	if len(batch.keys) == 0 {
		return nil
	}
	err := batch.localDelFn(batch.keys)
	batch.keys = batch.keys[:0]
	return err
}

func (batch *localBatch) propose(tk []byte, mk []byte, key []byte) error {
	if len(batch.keys) >= localBatchedMaxKeysNum {
		return ErrLocalBatchFullToCommit
	} else {
		batch.wb.Delete(tk)
		batch.wb.Delete(mk)
		batch.keys = append(batch.keys, key)
		return nil
	}
}


text:
    public function index({{ $config->modelNames->name }}DataTable ${{ $config->modelNames->camel }}DataTable)
    {
    return ${{ $config->modelNames->camel }}DataTable->render('{{ $config->modelNames->snakePlural }}.index');
    }


text:
@interface DVTTextLayer : CATextLayer
{
}

- (void)drawInContext:(struct CGContext *)arg1;

@end


text:
package aries.codegen.configuration;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import nam.model.Application;
import nam.model.Channel;
import nam.model.Configuration;
import nam.model.Dependency;
import nam.model.DependencyScope;
import nam.model.DependencyType;
import nam.model.Import;
import nam.model.Information;
import nam.model.Link;
import nam.model.Module;
import nam.model.ModuleLevel;
import nam.model.ModuleType;
import nam.model.Namespace;
import nam.model.Project;
import nam.model.Property;
import nam.model.Service;
import nam.model.util.ApplicationUtil;
import nam.model.util.InformationUtil;
import nam.model.util.MessagingUtil;
import nam.model.util.ModuleFactory;
import nam.model.util.ModuleUtil;
import nam.model.util.NamespaceUtil;
import nam.model.util.ProjectUtil;

import org.aries.Assert;

import aries.codegen.AbstractFileBuilder;
import aries.generation.model.ModelDependency;
import aries.generation.model.ModelPom;

public abstract class AbstractPOMBuilder extends AbstractFileBuilder {

	public String getGroupId(Module module) {
		Application application = context.getApplication();
		if (application != null)
			return application.getGroupId();
		return module.getGroupId();
	}

	public String getArtifactId(ModuleType moduleType) {
		Application application = context.getApplication();
		String artifactId = ModuleFactory.getDefaultArtifactId(application, moduleType);
		return artifactId;
	}

	public String getVersion() {
		return "0.0.1-SNAPSHOT";
	}

	public String getType(ModuleType moduleType) {
		switch (moduleType) {
		case POM: return "pom";
		case MODEL: return "jar";
		case DATA: return "ejb";
		case CLIENT: return "ejb";
		//TODO add conditional here for EJB or JAR
		case SERVICE: return "ejb";
		case TEST: return "test";
		case VIEW: return "jar";
		case EAR: return "ear";
		default: return null;
		}
	}

	public Set<Link> getLinks(Service service) {
		return MessagingUtil.getLinks(context.getProjectList(), service);
	}

	public List<Channel> getChannels(Service service) {
		return MessagingUtil.getChannels(context.getProjectList(), service);
	}

	public ModelPom createPom(Project project, Module module) throws Exception {
		ModelPom pom = new ModelPom();
		pom.setGroupId(getGroupId(module));

		String artifactId = null;
		if (context.isOptionLimitToSingleModule()) {
		//if (context.isOptionLimitToSingleModule() || module.getType() == ModuleType.VIEW) {
			artifactId = context.getApplication().getArtifactId();
		} else {
			artifactId = module.getArtifactId();
		}

		pom.setArtifactId(artifactId);
		pom.setName(artifactId);
		pom.setVersion(getVersion());
		pom.setDescription("Project object model for: "+artifactId);
		//determine and configure the correct parent pom
		pom.setParentPom(createParentPom(project, module, pom));
		if (module.getType() == ModuleType.POM)
			pom.setModules(initializePomModules(module));
		pom.setProperties(initializePomProperties());
		pom.setFilters(initializePomFilters());
		pom.setResources(initializePomResources());
		pom.setTestResources(initializePomTestResources());
		pom.setPlugins(initializePomPlugins());
		pom.setProfiles(initializePomProfiles());
		pom.setManagedDependencies(initializePomManagedDependencies(module));
		pom.setDependencies(initializePomDependencies(module));
		pom.setPackaging(initializePomPackaging(module));
		return pom;
	}

	protected ModelPom createParentPom(Project project, Module module, ModelPom pom) throws Exception {
		//determine and configure parent pom
		if (module.getType() == ModuleType.POM & module.getLevel() == ModuleLevel.PROJECT_LEVEL) {
			pom.setModules(initializePomModules(module, ModuleLevel.PROJECT_LEVEL));
			return createAriesParentPomAsParent();

		} else if (module.getType() == ModuleType.POM & module.getLevel() == ModuleLevel.GROUP_LEVEL) {
			pom.setModules(initializePomModules(module, ModuleLevel.GROUP_LEVEL));
			return createAriesParentPomAsParent();

		} else if (module.getType() == ModuleType.POM & module.getLevel() == ModuleLevel.APPLICATION_LEVEL) {
			pom.setModules(initializePomModules(module, ModuleLevel.APPLICATION_LEVEL));
			Collection<Application> applications = ProjectUtil.getApplications(project);
			if (applications.size() == 1)
				return createAriesParentPomAsParent();
			return createProjectPomAsParent(pom);

		} else if (!context.isOptionLimitToSingleModule() || module.getType() == ModuleType.VIEW) {
			ModelPom parentPom = null;
			Collection<Application> applications = ProjectUtil.getApplications(project);
			if (applications.size() == 1 && module.getLevel() == ModuleLevel.PROJECT_LEVEL) {
				parentPom  = createAriesParentPomAsParent();
			} else if (context.getApplication() == null) {
				parentPom  = createProjectPomAsParent(pom);
			} else {
				parentPom  = createApplicationPomAsParent(pom);
			}

			if (parentPom == null)
				parentPom = createProjectPomAsParent(pom);
			if (parentPom == null)
				parentPom = createAriesParentPomAsParent();
			return parentPom;
		} else {
			return createAriesParentPomAsParent();
		}
	}

//	public ModelPom createProjectPomAsParent(ModelPom childPom) throws Exception {
//		ModelPom pom = new ModelPom();
//		Project project = context.getProject();
//		List<Module> pomModules = ProjectUtil.getPomModules(project);
//		//TODO assuming only one parent per project for now
//		Assert.isTrue(pomModules.size() <= 1, "Supporting only 1 POM-module per Model");
//		if (pomModules.size() == 1) {
//			Module pomModule = pomModules.get(0);
//			pom.setGroupId(pomModule.getGroupId());
//			pom.setArtifactId(pomModule.getArtifactId());
//			pom.setName(pomModule.getName());
//		} else {
//			pom.setGroupId(childPom.getGroupId());
//			String artifactId = childPom.getArtifactId();
//			int lastIndexOf = artifactId.lastIndexOf("-");
//			if (lastIndexOf != -1)
//				artifactId = artifactId.substring(0, lastIndexOf);
//			pom.setArtifactId(artifactId);
//			pom.setName(artifactId);
//		}
//		pom.setVersion("0.0.1-SNAPSHOT");
//		Application application = ProjectUtil.getApplication(project);
//		pom.setDescription("Parent pom for application: "+application.getName());
//		pom.setParentPom(createGrandparentPom());
//		//TODO pom.setDependencies(initializePomDependencies());
//		pom.setPackaging("pom");
//		return pom;
//	}

	public ModelPom createProjectPomAsParent(ModelPom childPom) {
		Project project = context.getProject();
		Set<Module> pomModules = ProjectUtil.getProjectModules(project, ModuleType.POM);
		Assert.isTrue(pomModules.size() <= 1, "Supporting only 1 POM-module per project");
		if (pomModules.size() == 0)
			return null;
		ModelPom pom = new ModelPom();
		Module pomModule = pomModules.iterator().next();
		pom.setName(pomModule.getName());
		pom.setGroupId(pomModule.getGroupId());
		pom.setArtifactId(pomModule.getArtifactId());
		pom.setVersion("0.0.1-SNAPSHOT");
		Application application = context.getApplication();
		if (application != null)
			pom.setDescription("Parent pom for application modules: "+application.getName());
		else pom.setDescription("Parent pom for project modules: "+project.getName());
		//pom.setParentPom(createGrandparentPom());
		//TODO pom.setDependencies(initializePomDependencies());
		pom.setPackaging("pom");
		return pom;
	}

	public ModelPom createProjectAppPomAsParent(ModelPom childPom) {
		ModelPom pom = new ModelPom();
		Application application = context.getApplication();
		pom.setName(application.getArtifactId());
		pom.setGroupId(application.getGroupId());
		pom.setArtifactId(application.getArtifactId());
		pom.setVersion(application.getVersion());
		pom.setDescription("Parent pom for application: "+application.getName());
		//TODO pom.setDependencies(initializePomDependencies());
		pom.setPackaging("pom");
		return pom;
	}

	public ModelPom createApplicationPomAsParent(ModelPom childPom) {
		ModelPom pom = new ModelPom();
		Application application = context.getApplication();
		pom.setName(application.getArtifactId());
		pom.setGroupId(application.getGroupId());
		pom.setArtifactId(application.getArtifactId());
		pom.setVersion(application.getVersion());
		pom.setDescription("Parent pom for application: "+application.getName());
		//TODO pom.setDependencies(initializePomDependencies());
		pom.setPackaging("pom");
		return pom;
	}

	public ModelPom createAriesParentPomAsParent() {
		ModelPom pom = new ModelPom();
		pom.setGroupId("org.aries");
		pom.setArtifactId("aries-parent");
		pom.setName("aries-parent");
		pom.setVersion("0.0.1-SNAPSHOT");
		pom.setDescription("Parent pom for Aries framework");
		pom.setPackaging("pom");
		return pom;
	}

	public ModelPom createCommonPomAsParent() {
		ModelPom pom = new ModelPom();
		pom.setGroupId("org.aries");
		pom.setArtifactId("common");
		pom.setName("common");
		pom.setVersion("0.0.1-SNAPSHOT");
		pom.setDescription("Parent pom for common framework");
		pom.setParentPom(createGrandparentPom());
		//TODO pom.setDependencies(initializePomDependencies());
		pom.setPackaging("pom");
		return pom;
	}

	public ModelPom createGrandparentPom() {
		ModelPom pom = new ModelPom();
		pom.setGroupId("org.aries");
		pom.setArtifactId("aries");
		pom.setName("aries");
		pom.setVersion("0.0.1-SNAPSHOT");
		pom.setDescription("Grandparent pom for common framework");
		//TODO pom.setDependencies(initializePomDependencies());
		pom.setPackaging("pom");
		return pom;
	}

	public String initializePomPackaging(Module module) throws Exception {
		switch (module.getType()) {
		case POM:
			return "pom";
		case EAR:
			return "ear";
		case DATA:
		case CLIENT:
		case SERVICE:
			return "ejb";
		case VIEW:
			return "war";
		case MODEL:
		case TEST:
		default:
			return "jar";
		}
	}

	public ModelPom initializeParentPom(Application application) throws Exception {
		ModelPom pom = new ModelPom();
		pom.setGroupId(context.getApplication().getGroupId());
		pom.setArtifactId(application.getArtifactId());
		pom.setName(application.getName());
		pom.setVersion("0.0.1-SNAPSHOT");
		pom.setDescription(application.getName());
		pom.setPackaging("pom");
		return pom;
	}

	public List<String> initializePomModules(Module module) throws Exception {
		return initializePomModules(module, module.getLevel());
	}

	public List<String> initializePomModules(Module module, ModuleLevel moduleLevel) throws Exception {
		List<Module> earModules = new ArrayList<Module>();
		List<Module> warModules = new ArrayList<Module>();

		Map<ModuleType, List<Module>> moduleMap = new HashMap<ModuleType, List<Module>>();
		List<String> list = new ArrayList<String>();

		switch (moduleLevel) {
		case PROJECT_LEVEL: {
			Set<Module> projectModules = ProjectUtil.getProjectModules(context.getProject());
			Iterator<Module> moduleIterator = projectModules.iterator();
			while (moduleIterator.hasNext()) {
				Module projectModule = moduleIterator.next();
				ModuleType moduleType = projectModule.getType();
				if (context.canGenerate(moduleType) && moduleType != ModuleType.POM) {
					addModuleToMap(moduleMap, projectModule);
				}
			}

			Collection<Application> applications = ProjectUtil.getApplications(context.getProject());
			Iterator<Application> applicationIterator = applications.iterator();
			while (applicationIterator.hasNext()) {
				Application application = applicationIterator.next();
				list.add(application.getArtifactId());
			}
			break;
		}

		case GROUP_LEVEL:
		case APPLICATION_LEVEL: {
			Project project = context.getProject();
			List<Project> subProjects = ProjectUtil.getSubProjects(project);
			Iterator<Project> projectIterator = subProjects.iterator();
			while (projectIterator.hasNext()) {
				Project subProject = projectIterator.next();
				Module pomModule = ProjectUtil.getPomModule(subProject);
				if (pomModule != null)
					addModuleToMap(moduleMap, pomModule);
			}

			Collection<Application> applications = ProjectUtil.getApplications(project);
			boolean includeProjectModules = applications.size() == 1;
			if (includeProjectModules) {
				Set<Module> projectModules = ProjectUtil.getProjectModules(project);
				Iterator<Module> projectModuleIterator = projectModules.iterator();
				while (projectModuleIterator.hasNext()) {
					Module projectModule = projectModuleIterator.next();
					if (projectModule.getType() != ModuleType.POM)
						addModuleToMap(moduleMap, projectModule);
				}
			}

			String applicationArtifactId = module.getArtifactId();
			Application application = ProjectUtil.getApplicationByArtifactId(project, applicationArtifactId);
			if (application != null) {
				Set<Module> applicationModules = ModuleUtil.getModules(application.getModules());
				Iterator<Module> applicationModuleIterator = applicationModules.iterator();
				while (applicationModuleIterator.hasNext()) {
					Module applicationModule = applicationModuleIterator.next();
					if (applicationModule.getType() != ModuleType.POM)
						addModuleToMap(moduleMap, applicationModule);
				}
			}

//			Collection<Application> applications = ProjectUtil.getApplications(context.getProject());
//			Iterator<Application> applicationIterator = applications.iterator();
//			while (applicationIterator.hasNext()) {
//				Application application = applicationIterator.next();
//				List<Module> modules = application.getModules().getModules();
//				Iterator<Module> applicationModuleIterator = modules.iterator();
//				while (applicationModuleIterator.hasNext()) {
//					Module applicationModule = applicationModuleIterator.next();
//					if (applicationModule.getType() != ModuleType.POM) {
//						list.add(applicationModule.getArtifactId());
//					}
//				}
//			}
			break;
		}
		}

		if (context.canGenerateModel())
			list.addAll(getArtifactIds(moduleMap, ModuleType.MODEL));
		if (context.canGenerateClient())
			list.addAll(getArtifactIds(moduleMap, ModuleType.CLIENT));
		if (context.canGenerateData())
			list.addAll(getArtifactIds(moduleMap, ModuleType.DATA));
		if (context.canGenerateService())
			list.addAll(getArtifactIds(moduleMap, ModuleType.SERVICE));
		if (context.canGenerateWAR())
			list.addAll(getArtifactIds(moduleMap, ModuleType.VIEW));
		if (context.canGenerateEAR())
			list.addAll(getArtifactIds(moduleMap, ModuleType.EAR));
		return list;
	}

	private void addModuleToMap(Map<ModuleType, List<Module>> map, Module module) {
		List<Module> list = map.get(module.getType());
		if (list == null) {
			list = new ArrayList<Module>();
			map.put(module.getType(), list);
		}
		list.add(module);
	}

	private List<String> getArtifactIds(Map<ModuleType, List<Module>> map, ModuleType moduleType) {
		List<Module> modules = map.get(moduleType);
		List<String> list = new ArrayList<String>();
		if (modules != null) {
			Iterator<Module> iterator = modules.iterator();
			while (iterator.hasNext()) {
				Module module = iterator.next();
				list.add(module.getArtifactId());
			}
		}
		return list;
	}

//	protected Properties initializePomProperties() throws Exception {
//		Properties properties = new Properties();
//		return properties;
//	}

	protected List<Property> initializePomProperties() throws Exception {
		List<Property> properties = new ArrayList<Property>();
		Collection<Application> applications = ProjectUtil.getApplications(context.getProject());
		if (context.getApplication() == null || context.getModule().getLevel() == ModuleLevel.GROUP_LEVEL) {
			String prefix = context.getProject().getName();
			properties.add(createProperty(prefix + ".model.home", "../../model"));
			properties.add(createProperty(prefix + ".runtime.home", "../../runtime"));
		} else if (applications.size() > 1) {
			String prefix = context.getProject().getName();
			properties.add(createProperty(prefix + ".model.home", "../../model"));
			properties.add(createProperty(prefix + ".runtime.home", "../runtime"));
		} else {
			String prefix = context.getApplication().getArtifactId();
			properties.add(createProperty(prefix + ".model.home", "../../model"));
			properties.add(createProperty(prefix + ".runtime.home", "../../runtime"));
		}
		return properties;
	}

	protected Property createProperty(String name, String value) {
		Property property = new Property();
		property.setName(name);
		property.setValue(value);
		return property;
	}

	public List<String> initializePomFilters() {
		List<String> filters = new ArrayList<String>();
		return filters;
	}

	protected List<String> initializePomResources() {
		List<String> resources = new ArrayList<String>();
		return resources;
	}

	protected List<String> initializePomTestResources() {
		List<String> testResources = new ArrayList<String>();
		return testResources;
	}

	public List<String> initializePomPlugins() throws Exception {
		List<String> plugins = new ArrayList<String>();
		return plugins;
	}

	public List<String> initializePomProfiles() throws Exception {
		List<String> profiles = new ArrayList<String>();
		return profiles;
	}

	public Set<ModelDependency> initializePomManagedDependencies(Module module) throws Exception {
		Set<ModelDependency> dependencies = new LinkedHashSet<ModelDependency>();
		return dependencies;
	}

	public Set<ModelDependency> initializePomDependencies(Module module) throws Exception {
		Set<ModelDependency> plugins = new LinkedHashSet<ModelDependency>();
		return plugins;
	}

	public List<ModelDependency> initializePomDependenciesForTestProject() throws Exception {
		List<ModelDependency> dependencies = new ArrayList<ModelDependency>();
		dependencies.addAll(createPomProjectDependencies(ModuleType.MODEL));
		dependencies.addAll(createPomProjectDependencies(ModuleType.CLIENT));
		dependencies.add(createPomDependency("org.aries", "common-util"));
		dependencies.add(createPomDependency("org.aries", "common-model"));
		dependencies.addAll(createPomApplicationDependencies("model"));
		dependencies.addAll(createPomApplicationDependencies("client"));
		return dependencies;
	}

	public List<ModelDependency> initializePomDependenciesForEarProject() throws Exception {
		List<ModelDependency> dependencies = new ArrayList<ModelDependency>();
		return dependencies;
	}

//	public ModelDependency createPomApplicationDependency(ModuleType moduleType) {
//		String groupId = getGroupId();
//		String artifactId = getArtifactId(moduleType);
//		String version = getVersion();
//		ModelDependency dependency = createPomDependency(groupId, artifactId, version);
//		return dependency;
//	}

	public List<ModelDependency> createPomProjectDependencies(ModuleType moduleType) {
		List<ModelDependency> dependencies = new ArrayList<ModelDependency>();
		Map<String, Module> modules = ProjectUtil.getModulesAsMap(context.getProject(), moduleType);
		Iterator<Module> iterator = modules.values().iterator();
		while (iterator.hasNext()) {
			Module module = iterator.next();
			dependencies.add(createPomDependency(module));
			dependencies.add(createPomDependency(module, "test", "test-jar"));
		}
		return dependencies;
	}

	public List<ModelDependency> createPomApplicationDependencies(ModuleType moduleType) {
		List<ModelDependency> dependencies = new ArrayList<ModelDependency>();
		Application application = context.getApplication();
		if (application != null) {
			Collection<Module> modules = ApplicationUtil.getModules(application, moduleType);
			Iterator<Module> iterator = modules.iterator();
			while (iterator.hasNext()) {
				Module module = iterator.next();
				dependencies.add(createPomDependency(module));
				dependencies.add(createPomDependency(module, "test", "test-jar"));
			}
		}
		return dependencies;
	}

	public List<ModelDependency> createPomApplicationDependencies(String moduleType) {
		List<ModelDependency> list = new ArrayList<ModelDependency>();
		Application application = context.getApplication();
		if (application != null) {
			List<Dependency> dependencies = ApplicationUtil.getDependencies(application);
			Iterator<Dependency> iterator = dependencies.iterator();
			while (iterator.hasNext()) {
				Dependency dependency = iterator.next();
				String groupId = dependency.getGroupId();
				String artifactId = dependency.getArtifactId()+"-"+moduleType;
				String version = dependency.getVersion();
				if (version == null)
					version = "0.0.1-SNAPSHOT";
				list.add(createPomDependency(groupId, artifactId, version));
			}
		}
		return list;
	}

	protected List<ModelDependency> createPomDependencies(List<Dependency> dependencies) {
		List<ModelDependency> modelDependencies = new ArrayList<ModelDependency>();
		Iterator<Dependency> iterator = dependencies.iterator();
		while (iterator.hasNext()) {
			Dependency dependency = iterator.next();
			modelDependencies.add(createPomDependency(dependency));
		}
		return modelDependencies;
	}

	public List<ModelDependency> createPomDependenciesForModelModule(Namespace namespace) {
		return createPomDependenciesForModule(namespace, ModuleType.MODEL);
	}

	public List<ModelDependency> createPomDependenciesForDataModule(Namespace namespace) {
		return createPomDependenciesForModule(namespace, ModuleType.DATA);
	}

	public ModelDependency createPomDependencyForModelModule(Namespace namespace) {
		return createPomDependencyForModule(namespace, ModuleType.MODEL);
	}

	public ModelDependency createPomDependencyForDataModule(Namespace namespace) {
		return createPomDependencyForModule(namespace, ModuleType.DATA);
	}

	public List<ModelDependency> createPomDependenciesForModule(Namespace namespace, ModuleType moduleType) {
		List<ModelDependency> dependencies = new ArrayList<ModelDependency>();
		ModelDependency releaseModule = createPomDependencyForModule(namespace, moduleType);
		ModelDependency testModule = createPomDependencyForModule(namespace, moduleType);
		testModule.setScope("test");
		testModule.setType("test-jar");
		dependencies.add(releaseModule);
		dependencies.add(testModule);
		return dependencies;
	}

	public ModelDependency createPomDependencyForModule(Namespace namespace, ModuleType moduleType) {
		//String groupId = NamespaceUtil.getGroupIdFromNamespace(namespace);
		String groupId = context.getProject().getDomain();
		String artifactId = getArtifactIdForModule(namespace, moduleType);
		String version = NamespaceUtil.getVersionFromNamespace(namespace);
		ModelDependency modelDependency = createPomDependency(groupId, artifactId, version);
		switch (moduleType) {
		case CLIENT:
		case DATA:
		case SERVICE:
			modelDependency.setType("ejb");
			break;
		default:
			break;
		}
		return modelDependency;
	}

	public String getArtifactIdForModule(Namespace namespace, ModuleType moduleType) {
		String artifactId = NamespaceUtil.getArtifactIdFromNamespace(namespace);
		switch (moduleType) {
		case DATA:
			//TODO - Externalize this properly
			artifactId = artifactId.replace("-model", "-persistence");
			return artifactId;
		default:
			return artifactId;
		}
	}

	public ModelDependency createPomDependency(Module module) {
		return createPomDependency(module.getGroupId(), module.getArtifactId(), module.getVersion(), "provided", getType(module.getType()));
	}

	public ModelDependency createPomDependency(Module module, String scope, String type) {
		return createPomDependency(module.getGroupId(), module.getArtifactId(), module.getVersion(), scope, type);
	}

	public ModelDependency createPomDependency(Application application) {
		return createPomDependency(application.getGroupId(), application.getArtifactId(), application.getVersion(), "provided", "pom");
	}

	public ModelDependency createPomDependency(Configuration configuration) {
		return createPomDependency(configuration.getGroupId(), configuration.getArtifactId(), configuration.getVersion(), "import", "pom");
	}

	public ModelDependency createPomDependency(String groupId, String artifactId) {
		return createPomDependency(groupId, artifactId, null, "provided");
	}

	public ModelDependency createPomDependency(String groupId, String artifactId, String version) {
		return createPomDependency(groupId, artifactId, version, "provided");
	}

	public ModelDependency createPomDependency(String groupId, String artifactId, String version, String scope) {
		return createPomDependency(groupId, artifactId, version, scope, "jar");
	}

	public ModelDependency createPomDependency(String groupId, String artifactId, String version, String scope, String type) {
		ModelDependency dependency = new ModelDependency();
		dependency.setGroupId(groupId);
		dependency.setArtifactId(artifactId);
		dependency.setVersion(version);
		dependency.setScope(scope);
		dependency.setType(type);
		return dependency;
	}

	public ModelDependency createPomDependency(Dependency dependency) {
		ModelDependency modelDependency = new ModelDependency();
		modelDependency.setGroupId(dependency.getGroupId());
		modelDependency.setArtifactId(dependency.getArtifactId());
		modelDependency.setVersion(dependency.getVersion());

		String type = "jar";
		String scope = "compile";
		DependencyType dependencyType = dependency.getType();
		DependencyScope dependencyScope = dependency.getScope();
		if (dependencyType == DependencyType.TEST_JAR)
			dependencyScope = DependencyScope.TEST;
		if (dependencyType != null)
			type = dependencyType.name().toLowerCase();
		if (dependencyScope != null)
			scope = dependencyScope.name().toLowerCase();
		if (type.equals("test_jar"))
			type = "test-jar";
		modelDependency.setType(type);
		modelDependency.setScope(scope);
		return modelDependency;
	}

	protected void addDependency(Set<ModelDependency> dependencies, Set<ModelDependency> dependencySet, ModelDependency dependency) {
		if (!dependencySet.contains(dependency)) {
			dependencySet.add(dependency);
			dependencies.add(dependency);
		}
	}

//	protected Collection<ModelDependency> getModelModuleDependencies(Project project) {
//		Set<ModelDependency> dependencies = new LinkedHashSet<ModelDependency>();
//		List<Information> informationBlocks = ProjectUtil.getInformationBlocks(project);
//		Iterator<Information> iterator = informationBlocks.iterator();
//		while (iterator.hasNext()) {
//			Information information = iterator.next();
//			Collection<ModelDependency> list = getModelModuleDependencies(context.getModule(), information);
//			dependencies.addAll(list);
//		}
//		return dependencies;
//	}

	protected Collection<ModelDependency> getModelModuleDependencies(Project project) {
		Set<ModelDependency> dependencies = new LinkedHashSet<ModelDependency>();
		Set<Module> modelModules = ModuleUtil.getModelModules(project);
		Iterator<Module> iterator = modelModules.iterator();
		while (iterator.hasNext()) {
			Module module = iterator.next();
			Collection<ModelDependency> list = getModelModuleDependencies(module);
			dependencies.addAll(list);
		}
		return dependencies;
	}

	protected Collection<ModelDependency> getModelModuleDependencies(Module module) {
		return getModelModuleDependencies(module, module.getInformation());
	}

	protected Collection<ModelDependency> getModelModuleDependencies(Information information) {
		return getModelModuleDependencies(context.getModule(), information);
	}

	protected Collection<ModelDependency> getModelModuleDependencies(Module module, Information information) {
		Set<ModelDependency> dependencies = new LinkedHashSet<ModelDependency>();
		if (information != null) {
			Collection<Namespace> namespacesToDependUpon = InformationUtil.getAllNamespaces(information);
			Iterator<Namespace> iterator = namespacesToDependUpon.iterator();
			while (iterator.hasNext()) {
				Namespace namespace = iterator.next();
				if (module.getNamespace().equals(namespace.getUri()))
					continue;
				if (namespace.getFilePath() == null)
					continue;

				Module moduleforNamespace = context.getModelModuleByNamespace(namespace);
				if (moduleforNamespace == null) {
					dependencies.addAll(createPomDependenciesForModelModule(namespace));
				} else {
					ModelDependency releaseDependency = createPomDependency(moduleforNamespace);
					ModelDependency testDependency = createPomDependency(moduleforNamespace);
					testDependency.setScope("test");
					testDependency.setType("test-jar");
					dependencies.add(releaseDependency);
					dependencies.add(testDependency);
				}
			}
		}

		return dependencies;
	}

	protected Collection<ModelDependency> getDataModuleDependencies(Project project) {
		Set<ModelDependency> dependencies = new LinkedHashSet<ModelDependency>();
		Set<Module> modelModules = ModuleUtil.getModelModules(project);
		Iterator<Module> iterator = modelModules.iterator();
		while (iterator.hasNext()) {
			Module module = iterator.next();
			Collection<ModelDependency> list = getDataModuleDependencies(module);
			dependencies.addAll(list);
		}
		return dependencies;
	}

	protected Collection<ModelDependency> getDataModuleDependencies(Module module) {
		return getDataModuleDependencies(module.getInformation());
	}

	protected Collection<ModelDependency> getDataModuleDependencies(Information information) {
		Set<ModelDependency> dependencies = new LinkedHashSet<ModelDependency>();
		if (information != null) {
			Collection<Namespace> namespacesToDependUpon = InformationUtil.getAllNamespaces(information);
			Iterator<Namespace> iterator = namespacesToDependUpon.iterator();
			while (iterator.hasNext()) {
				Namespace namespace = iterator.next();
				if (namespace.getFilePath() == null)
					continue;

				Module moduleforNamespace = context.getDataModuleByNamespace(namespace);
				if (moduleforNamespace == null) {
					List<ModelDependency> modelDependencies = createPomDependenciesForDataModule(namespace);
					dependencies.addAll(modelDependencies);
				} else {
					ModelDependency releaseDependency = createPomDependency(moduleforNamespace);
					ModelDependency testDependency = createPomDependency(moduleforNamespace);
					testDependency.setScope("test");
					testDependency.setType("test-jar");
					dependencies.add(releaseDependency);
					dependencies.add(testDependency);
				}
			}
		}

		return dependencies;
	}

	protected void printDependencies(List<Dependency> dependencies) {
		Iterator<Dependency> iterator = dependencies.iterator();
		while (iterator.hasNext()) {
			Dependency dependency = (Dependency) iterator.next();
			System.out.println(dependency.getGroupId()+":"+dependency.getArtifactId()+" "+dependency.getType()+" "+dependency.getVersion());
		}
	}

}