text:
package com.twitter.finatra.thrift

import com.google.inject.Module
import com.twitter.app.Flag
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.service.NilService
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.finagle.ListeningServer
import com.twitter.finagle.NullServer
import com.twitter.finagle.Service
import com.twitter.finagle.ThriftMux
import com.twitter.finagle.tracing.Tracer
import com.twitter.finatra.thrift.modules.ExceptionManagerModule
import com.twitter.finatra.thrift.modules.ThriftResponseClassifierModule
import com.twitter.finatra.thrift.response.ThriftResponseClassifier
import com.twitter.finatra.thrift.routing.JavaThriftRouter
import com.twitter.finatra.thrift.routing.ThriftRouter
import com.twitter.inject.annotations.Lifecycle
import com.twitter.inject.modules.StackTransformerModule
import com.twitter.inject.server.AbstractTwitterServer
import com.twitter.inject.server.PortUtils
import com.twitter.inject.server.TwitterServer
import com.twitter.util.Await
import com.twitter.util.Duration

import java.net.InetSocketAddress

private object ThriftServerTrait {

  /**
   * Sentinel used to indicate no thrift server announcement.
   */
  val NoThriftAnnouncement: String = ""
}

/**
 * A basic ThriftServer implemented by a {{{com.twitter.finagle.Service[Array[Byte], Array[Byte]]}}}.
 *
 * @note Java users are encouraged to use [[AbstractThriftServerTrait]] instead.
 */
trait ThriftServerTrait extends TwitterServer {

  /** Add Framework Modules */
  addFrameworkModules(
    ExceptionManagerModule,
    StackTransformerModule,
    thriftResponseClassifierModule)

  /**
   * Default external Thrift port used as the [[Flag]] default value for [[thriftPortFlag]]. This
   * can be overridden to provide a different default programmatically when a flag value cannot be
   * passed. The format of this value is expected to be a String in the form of ":port".
   *
   * In general, users should prefer setting the [[thriftPortFlag]] [[Flag]] value.
   *
   * @see [[com.twitter.finatra.thrift.ThriftServerTrait.thriftPortFlag]]
   */
  protected def defaultThriftPort: String = ":9999"

  /**
   * External Thrift port [[Flag]]. The default value is specified by [[defaultThriftPort]] which
   * can be overridden to provide a different default.
   *
   * @note the default value is ":9999" as defined by [[defaultThriftPort]].
   * @note the format of this flag is expected to be a String in the form of ":port".
   * @see [[com.twitter.finatra.thrift.ThriftServerTrait.defaultThriftPort]]
   * @see [[https://twitter.github.io/finatra/user-guide/getting-started/flags.html#passing-flag-values-as-command-line-arguments]]
   */
  private val thriftPortFlag: Flag[String] =
    flag("thrift.port", defaultThriftPort, "External Thrift server port")

  /**
   * Default shutdown timeout used as the [[Flag]] default value for [[thriftShutdownTimeoutFlag]].
   * This represents the deadline for the closing of this server which can be overridden to provide
   * a different default programmatically when a flag value cannot be passed.
   *
   * In general, users should prefer setting the [[thriftShutdownTimeoutFlag]] [[Flag]] value.
   *
   * @note the value is used to denote a delta "from now", that is this value is applied as:
   *       `server.close(shutdownTimeoutDuration.fromNow())`
   * @see [[com.twitter.finatra.thrift.ThriftServerTrait.thriftShutdownTimeoutFlag]]
   * @see [[com.twitter.util.Closable.close(deadline: Time)]]
   * @see [[https://github.com/twitter/util/blob/b0a5d06269b9526b4408239ce1441b2a213dd0df/util-core/src/main/scala/com/twitter/util/Duration.scala#L436]]
   */
  protected def defaultThriftShutdownTimeout: Duration = 1.minute

  /**
   * Shutdown timeout [[Flag]]. The default value is specified by [[defaultThriftShutdownTimeout]]
   * which can be overridden to provide a different default.
   *
   * @note the default value is "1.minute" as defined by [[defaultThriftShutdownTimeout]].
   * @note the format of this flag is expected to be a String which is parsable into a [[com.twitter.util.Duration]].
   * @see [[com.twitter.finatra.thrift.ThriftServerTrait.defaultThriftShutdownTimeout]]
   * @see [[https://twitter.github.io/finatra/user-guide/getting-started/flags.html#passing-flag-values-as-command-line-arguments]]
   */
  private val thriftShutdownTimeoutFlag: Flag[Duration] = flag(
    "thrift.shutdown.time",
    defaultThriftShutdownTimeout,
    "Maximum amount of time to wait for pending requests to complete on shutdown"
  )

  /**
   * Default server name for the external Thrift interface used as the [[Flag]] default value for
   * [[thriftServerNameFlag]]. This can be overridden to provide a different default programmatically
   * when a flag value cannot be passed.
   *
   * In general, users should prefer setting the [[thriftServerNameFlag]] [[Flag]] value.
   *
   * @see [[com.twitter.finatra.thrift.ThriftServerTrait.thriftServerNameFlag]]
   */
  protected def defaultThriftServerName: String = "thrift"

  /**
   * Server name for the external Thrift interface [[Flag]]. The default value is specified by
   * [[defaultThriftServerName]] which can be overridden to provide a different default.
   *
   * @note the default value is "thrift" as defined by [[defaultThriftServerName]].
   * @see [[com.twitter.finatra.thrift.ThriftServerTrait.defaultThriftServerName]]
   * @see [[https://twitter.github.io/finatra/user-guide/getting-started/flags.html#passing-flag-values-as-command-line-arguments]]
   */
  private val thriftServerNameFlag: Flag[String] =
    flag("thrift.name", defaultThriftServerName, "Thrift server name")

  /**
   * Default server announcement String used as the [[Flag]] default value for [[thriftAnnounceFlag]].
   * This can be overridden to provide a different default programmatically when a flag value cannot
   * be passed. An empty String value is an indication to not perform any announcement of the server.
   *
   * In general, users should prefer setting the [[thriftAnnounceFlag]] [[Flag]] value.
   *
   * @see [[com.twitter.finagle.ListeningServer.announce(addr: String)]]
   */
  protected def defaultThriftAnnouncement: String = ThriftServerTrait.NoThriftAnnouncement

  /**
   * Server announcement String [[Flag]]. The default value is specified by [[defaultThriftAnnouncement]]
   * which can be overridden to provide a different default. Setting an empty String is an indication
   * to not perform any announcement of the server.
   *
   * @note the default value is "No Announcement" (empty String) as defined by [[defaultThriftAnnouncement]].
   * @see [[com.twitter.finagle.ListeningServer.announce(addr: String)]]
   * @see [[com.twitter.finatra.thrift.ThriftServerTrait.defaultThriftAnnouncement]]
   * @see [[https://twitter.github.io/finatra/user-guide/getting-started/flags.html#passing-flag-values-as-command-line-arguments]]
   */
  private val thriftAnnounceFlag: Flag[String] =
    flag[String](
      "thrift.announce",
      defaultThriftAnnouncement,
      "Address for announcing Thrift server. Empty string indicates no announcement."
    )

  /* Private Mutable State */

  private var thriftServer: ListeningServer = NullServer

  /* Abstract */

  /**
   * The Finagle `Service[Array[Byte], Array[Byte]]` to serve on the configured [[ListeningServer]].
   *
   * Users must override with an implementation to serve a `Service[Array[Byte], Array[Byte]]`.
   */
  protected def thriftService: Service[Array[Byte], Array[Byte]]

  /**
   * The address to which the underlying [[ListeningServer]] is bound
   *
   * @note this returns [[None]] before the [[postWarmup()]] lifecycle phase is done or if the
   *       server fails to start up.
   */
  protected final def boundAddress: Option[InetSocketAddress] =
    if (thriftServer == NullServer)
      None
    else
      Some(thriftServer.boundAddress.asInstanceOf[InetSocketAddress])

  /* Lifecycle */

  @Lifecycle
  override protected def postWarmup(): Unit = {
    super.postWarmup()

    val baseSrv = ThriftMux.server
      .withLabel(thriftServerNameFlag())
      .withStatsReceiver(injector.instance[StatsReceiver].scope("srv"))
      .withResponseClassifier(injector.instance[ThriftResponseClassifier])

    // The inject.TwitterServer installs the TracerModule, which uses a bindOption for configuring a Tracer. This
    // approach differs from the pattern used with StatsReceiver & StatsReceiverModule in order to work
    // backwards compatibly with implementations that already bind their own customer Tracer.
    // If a Tracer is bound to the object graph we configure it here, otherwise the default Tracer
    // configuration is used. This is our primary integration point for verifying traces via test.
    val srv = injector.instance[Option[Tracer]] match {
      case Some(tracer) => baseSrv.withTracer(tracer)
      case _ => baseSrv
    }

    thriftServer = build(
      thriftPortFlag(),
      frameworkConfigureServer(
        configureThriftServer(
          srv
        )
      )
    )

    onExit {
      Await.result(thriftServer.close(thriftShutdownTimeoutFlag().fromNow))
    }
    await(thriftServer)

    thriftAnnounceFlag() match {
      case ThriftServerTrait.NoThriftAnnouncement => // no-op
      case addr =>
        info(s"thrift server announced to $addr")
        thriftServer.announce(addr)
    }
    info(s"thrift server started on port ${PortUtils.getPort(thriftServer.boundAddress)}")
  }

  /* Overrides */

  override def thriftPort: Option[Int] = Some(PortUtils.getPort(thriftServer))

  /* Protected */

  /**
   * Default [[com.twitter.inject.TwitterModule]] for providing a [[ThriftResponseClassifier]].
   *
   * @return a [[com.twitter.inject.TwitterModule]] which provides a [[ThriftResponseClassifier]] implementation.
   */
  protected def thriftResponseClassifierModule: Module = ThriftResponseClassifierModule

  /**
   * This method allows for further configuration of the thrift server for parameters not exposed by
   * this trait or for overriding defaults provided herein, e.g.,
   *
   * override def configureThriftServer(server: ThriftMux.Server): ThriftMux.Server = {
   *   server
   *     .withMaxReusableBufferSize(...)
   * }
   *
   * @param server - the [[com.twitter.finagle.ThriftMux.Server]] to configure.
   * @return a configured ThriftMux.Server.
   */
  protected def configureThriftServer(server: ThriftMux.Server): ThriftMux.Server = {
    server
  }

  /* Configuration of the server reserved by the framework */
  protected[finatra] def frameworkConfigureServer(server: ThriftMux.Server): ThriftMux.Server = {
    server
  }

  /**
   * Construct a [[com.twitter.finagle.ListeningServer]] from the given String addr
   * and configured [[ThriftMux.Server]] stack.
   *
   * @param addr the [[String]] address to bind the resultant [[ListeningServer]].
   * @param server the configured [[ThriftMux.Server]] stack.
   * @return a constructed [[ListeningServer]].
   */
  private[thrift] def build(addr: String, server: ThriftMux.Server): ListeningServer = {
    server.serve(addr, this.thriftService)
  }
}

/**
 * A basic ThriftServer implemented by a {{{com.twitter.finagle.Service<byte[], byte[]>}}}.
 *
 * @note Scala users are encouraged to use [[ThriftServerTrait]] instead.
 */
abstract class AbstractThriftServerTrait extends AbstractTwitterServer with ThriftServerTrait

/**
 * A Finagle server which exposes an external Thrift interface implemented by a
 * {{{Service<byte[], byte[]>}}} configured via a [[ThriftRouter]]. This trait is
 * intended for use from Scala or with generated Scala code.
 *
 * @note Java users are encouraged to use [[AbstractThriftServer]] instead.
 */
trait ThriftServer extends ThriftServerTrait {

  /**
   * Configuration of the `Service[Array[Byte], Array[Byte]]` to serve on the [[ListeningServer]]
   * is defined by configuring the [[ThriftRouter]] and not by implementation of this method,
   * thus this method overridden to be final and set to a `NilService`.
   */
  final override protected def thriftService: Service[Array[Byte], Array[Byte]] =
    NilService

  /** Serve the `Service[Array[Byte], Array[Byte]]` from the configured [[ThriftRouter]]. */
  override private[thrift] def build(addr: String, server: ThriftMux.Server): ListeningServer = {
    val router = injector.instance[ThriftRouter]
    server.serveIface(addr, router.thriftService)
  }

  /* Abstract */

  /**
   * Users MUST provide an implementation to configure the provided [[ThriftRouter]]. The [[ThriftRouter]]
   * exposes a DSL which results in a configured Finagle `Service[-Req, +Rep]` to serve on
   * the [[ListeningServer]].
   *
   * @param router the [[ThriftRouter]] to configure.
   */
  protected def configureThrift(router: ThriftRouter): Unit

  /* Lifecycle */

  @Lifecycle
  override protected def postInjectorStartup(): Unit = {
    super.postInjectorStartup()
    configureRouter()
  }

  /**
   * Configure the appropriate router for this server.
   * @note Users SHOULD NOT override/replace this method.
   */
  private[thrift] def configureRouter(): Unit = {
    configureThrift(injector.instance[ThriftRouter])
  }
}

/**
 * A Finagle server which exposes an external Thrift interface implemented by a
 * `Service[Array[Byte], Array[Byte]]` configured via a [[JavaThriftRouter]]. This abstract class is
 * intended for use from Java or with generated Java code.
 *
 * @note Scala users are encouraged to use [[ThriftServer]] instead.
 */
abstract class AbstractThriftServer extends AbstractTwitterServer with ThriftServer {

  /** Serve the `Service[Array[Byte], Array[Byte]]` from the configured [[JavaThriftRouter]]. */
  override private[thrift] final def build(
    addr: String,
    server: ThriftMux.Server
  ): ListeningServer = {
    val router = injector.instance[JavaThriftRouter]
    // Configure the service first so that serviceClazzStackParam is defined
    // by the time it is checked (for Java servers configured via JavaThriftRouter)
    val service = configureService(router.createService(server.serverParam))
    router.getServiceClazzStackParam match {
      case Some(serviceClazz) =>
        server
          .withServiceClass(serviceClazz)
          .serve(addr, service)
      case _ =>
        server.serve(addr, service)
    }
  }

  /** Users are expected to use [[configureThrift(router: JavaThriftRouter)]] */
  override protected final def configureThrift(router: ThriftRouter): Unit =
    throw new IllegalStateException("Use 'configureThrift(router: JavaThriftRouter)'")

  /* Abstract */

  /**
   * Users MUST provide an implementation to configure the provided [[JavaThriftRouter]]. The [[JavaThriftRouter]]
   * exposes a DSL which results in a configured Finagle `Service[-Req, +Rep]` to serve on the [[ListeningServer]].
   *
   * @param router the [[JavaThriftRouter]] to configure.
   */
  protected def configureThrift(router: JavaThriftRouter): Unit

  /* Protected */

  /**
   * Override to provide further configuration to the `Service[Array[Byte], Array[Byte]]` served.
   * For example, to add "global" filters over the resultant `Service[Array[Byte], Array[Byte]]`.
   *
   * E.g.
   *
   * {{{
   *   override protected def configureService(
   *     service: Service[Array[Byte], Array[Byte]]
   *   ): Service[Array[Byte], Array[Byte]] = {
   *      injector.instance[MyGreatServiceFilter].andThen(service)
   *   }
   * }}}
   */
  protected def configureService(
    service: Service[Array[Byte], Array[Byte]]
  ): Service[Array[Byte], Array[Byte]] = service

  /* Lifecycle */

  /**
   * Configure the appropriate router for this server.
   * @note Users SHOULD NOT override/replace this method.
   */
  override private[thrift] final def configureRouter(): Unit = {
    configureThrift(injector.instance[JavaThriftRouter])
  }
}


text:
package com.supinfo.suprails.resources;

import com.supinfo.suprails.entity.CustomerOrder;
import com.supinfo.suprails.service.CustomerOrderService;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URI;

/**
 * Created by Alexandre NGUYEN on 13/10/2014.
 */

@Path("/customerOrders")
@Stateless
public class CustomerOrderResources {

    @EJB
    CustomerOrderService customerOrderService;

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public Response processOrder(CustomerOrder customerOrder) {
        customerOrderService.processCustomerOrder(customerOrder);
        String location = "/" + customerOrder.getId();
        return Response.created(URI.create(location)).build();
    }
}

redpajama_set_name: RedPajamaGithub


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

#pragma once

#if !defined(ISPC)
#include "../math/sampling.h"
#include "../lights/light.h"
#include "../lights/ambient_light.h"
#include "../lights/directional_light.h"
#include "../lights/point_light.h"
#include "../lights/quad_light.h"
#include "../lights/spot_light.h"
#include "scene.h"
#else
#include "../lights/light.isph"
#endif

#include "../scenegraph/texture.h"
#include "../scenegraph/materials.h"

#if !defined(ISPC)

#define CPPTUTORIAL
#include "../scenegraph/materials.h"
#undef CPPTUTORIAL

namespace embree
{
#endif

  struct ISPCTriangle
  {
    unsigned int v0;                /*< first triangle vertex */
    unsigned int v1;                /*< second triangle vertex */
    unsigned int v2;                /*< third triangle vertex */
  };

  struct ISPCQuad
  {
    unsigned int v0;                /*< first triangle vertex */
    unsigned int v1;                /*< second triangle vertex */
    unsigned int v2;                /*< third triangle vertex */
    unsigned int v3;                /*< fourth triangle vertex */
  };

  struct ISPCHair
  {
    unsigned int vertex;
    unsigned int id;
  };

  enum ISPCType { TRIANGLE_MESH, SUBDIV_MESH, HAIR_SET, INSTANCE, GROUP, QUAD_MESH, LINE_SEGMENTS, CURVES };
  enum ISPCBasis { BEZIER_BASIS, BSPLINE_BASIS };

  struct ISPCGeometry
  {
#if !defined(ISPC)
    ISPCGeometry (ISPCType type) : type(type) {}
#endif
    ISPCType type;
  };

#if !defined(ISPC)
  enum TEXTURE_FORMAT {
    Texture_RGBA8        = 1,
    Texture_RGB8         = 2,
    Texture_FLOAT32      = 3,
  };
#endif

  struct ISPCTriangleMesh
  {
#if !defined(ISPC)
    ISPCTriangleMesh (TutorialScene* scene_in, Ref<SceneGraph::TriangleMeshNode> in);
    ~ISPCTriangleMesh ();
#endif

    ISPCGeometry geom;
    Vec3fa** positions;     //!< vertex position array with all timesteps
    Vec3fa* normals;       //!< vertex normal array
    Vec2f* texcoords;      //!< vertex texcoord array
    ISPCTriangle* triangles;  //!< list of triangles

    unsigned int numTimeSteps;
    unsigned int numVertices;
    unsigned int numTriangles;
    RTCScene scene;
    unsigned int geomID;
    unsigned int materialID;
  };

  struct ISPCQuadMesh
  {
#if !defined(ISPC)
    ISPCQuadMesh (TutorialScene* scene_in, Ref<SceneGraph::QuadMeshNode> in);
    ~ISPCQuadMesh ();
#endif

    ISPCGeometry geom;
    Vec3fa** positions;    //!< vertex position array
    Vec3fa* normals;       //!< vertex normal array
    Vec2f* texcoords;     //!< vertex texcoord array
    ISPCQuad* quads;      //!< list of quads

    unsigned int numTimeSteps;
    unsigned int numVertices;
    unsigned int numQuads;
    RTCScene scene;
    unsigned int geomID;
    unsigned int materialID;
  };

  struct ISPCSubdivMesh
  {
#if !defined(ISPC)
    ISPCSubdivMesh (TutorialScene* scene_in, Ref<SceneGraph::SubdivMeshNode> in);
    ~ISPCSubdivMesh ();

  private:
    ISPCSubdivMesh (const ISPCSubdivMesh& other) DELETED; // do not implement
    ISPCSubdivMesh& operator= (const ISPCSubdivMesh& other) DELETED; // do not implement

  public:
#endif

    ISPCGeometry geom;
    Vec3fa** positions;       //!< vertex positions
    Vec3fa* normals;         //!< face vertex normals
    Vec2f* texcoords;        //!< face texture coordinates
    unsigned int* position_indices;   //!< position indices for all faces
    unsigned int* normal_indices;     //!< normal indices for all faces
    unsigned int* texcoord_indices;   //!< texcoord indices for all faces
    RTCSubdivisionMode position_subdiv_mode;
    RTCSubdivisionMode normal_subdiv_mode;
    RTCSubdivisionMode texcoord_subdiv_mode;
    unsigned int* verticesPerFace;    //!< number of indices of each face
    unsigned int* holes;              //!< face ID of holes
    float* subdivlevel;      //!< subdivision level
    Vec2i* edge_creases;          //!< crease index pairs
    float* edge_crease_weights;   //!< weight for each crease
    unsigned int* vertex_creases;          //!< indices of vertex creases
    float* vertex_crease_weights; //!< weight for each vertex crease
    unsigned int* face_offsets;

    unsigned int numTimeSteps;
    unsigned int numVertices;
    unsigned int numFaces;
    unsigned int numEdges;
    unsigned int numEdgeCreases;
    unsigned int numVertexCreases;
    unsigned int numHoles;
    unsigned int numNormals;
    unsigned int numTexCoords;
    unsigned int materialID;
    RTCScene scene;
    unsigned int geomID;
  };

  struct ISPCLineSegments
  {
#if !defined(ISPC)
    ISPCLineSegments (TutorialScene* scene_in, Ref<SceneGraph::LineSegmentsNode> in);
    ~ISPCLineSegments();
#endif

    ISPCGeometry geom;
    Vec3fa** positions;        //!< control points (x,y,z,r)
    unsigned int* indices;        //!< for each segment, index to first control point

    unsigned int numTimeSteps;
    unsigned int numVertices;
    unsigned int numSegments;
    unsigned int materialID;
    RTCScene scene;
    unsigned int geomID;
  };

  struct ISPCHairSet
  {
#if !defined(ISPC)
    ISPCHairSet (TutorialScene* scene_in, SceneGraph::HairSetNode::Type type, SceneGraph::HairSetNode::Basis basis, Ref<SceneGraph::HairSetNode> in);
    ~ISPCHairSet();
#endif

    ISPCGeometry geom;
    Vec3fa** positions;       //!< hair control points (x,y,z,r)
    ISPCHair* hairs;         //!< for each hair, index to first control point
    ISPCBasis basis;
    unsigned int numTimeSteps;
    unsigned int numVertices;
    unsigned int numHairs;
    unsigned int materialID;
    RTCScene scene;
    unsigned int geomID;
    unsigned int tessellation_rate;
  };

  struct ISPCInstance
  {
#if !defined(ISPC)
    ALIGNED_STRUCT;

    static ISPCInstance* create (TutorialScene* scene, Ref<SceneGraph::TransformNode> in);

  private:
    ISPCInstance (TutorialScene* scene, Ref<SceneGraph::TransformNode> in);

  public:
#endif
    ISPCGeometry geom;
    unsigned int geomID;
    unsigned int numTimeSteps;
    unsigned int align;
    AffineSpace3fa spaces[1];
  };

  struct ISPCGroup
  {
#if !defined(ISPC)
    ISPCGroup (TutorialScene* scene, Ref<SceneGraph::GroupNode> in);
    ~ISPCGroup();

  private:
    ISPCGroup (const ISPCGroup& other) DELETED; // do not implement
    ISPCGroup& operator= (const ISPCGroup& other) DELETED; // do not implement

  public:
#endif
    ISPCGeometry geom;
    ISPCGeometry** geometries;
    size_t numGeometries;
  };

  struct ISPCScene
  {
#if !defined(ISPC)
    ISPCScene(TutorialScene* in)
    {
      geometries = new ISPCGeometry*[in->geometries.size()];
      for (size_t i=0; i<in->geometries.size(); i++)
        geometries[i] = convertGeometry(in,in->geometries[i]);
      numGeometries = unsigned(in->geometries.size());

      materials = new ISPCMaterial*[in->materials.size()];
      for (size_t i=0; i<in->materials.size(); i++)
        materials[i] = (ISPCMaterial*) in->materials[i]->material();
      numMaterials = unsigned(in->materials.size());

      lights = new Light*[in->lights.size()];
      numLights = 0;
      for (size_t i=0; i<in->lights.size(); i++)
      {
        Light* light = convertLight(in->lights[i]);
        if (light) lights[numLights++] = light;
      }

      geomID_to_scene = in->geomID_to_scene.data();
      geomID_to_inst = (ISPCInstance**) in->geomID_to_inst.data();
    }

    ~ISPCScene()
    {
      /* delete all geometries */
      for (size_t i=0; i<numGeometries; i++)
      {
        switch (geometries[i]->type) {
        case TRIANGLE_MESH: delete (ISPCTriangleMesh*) geometries[i]; break;
        case SUBDIV_MESH  : delete (ISPCSubdivMesh*) geometries[i]; break;
        case HAIR_SET: delete (ISPCHairSet*) geometries[i]; break;
        case INSTANCE: delete (ISPCInstance*) geometries[i]; break;
        case GROUP: delete (ISPCGroup*) geometries[i]; break;
        case QUAD_MESH: delete (ISPCQuadMesh*) geometries[i]; break;
        case LINE_SEGMENTS: delete (ISPCLineSegments*) geometries[i]; break;
        case CURVES: delete (ISPCHairSet*) geometries[i]; break;
        default: assert(false); break;
        }
      }
      delete[] geometries;
      delete[] materials;
      // FIXME: currently lights cannot get deleted
      delete[] lights;
    }

    static ISPCGeometry* convertGeometry (TutorialScene* scene, Ref<SceneGraph::Node> in);

    static Light* convertLight(Ref<SceneGraph::Light> in)
    {
      void* out = 0;

      switch (in->getType())
      {
      case SceneGraph::LIGHT_AMBIENT:
      {
        Ref<SceneGraph::AmbientLight> inAmbient = in.dynamicCast<SceneGraph::AmbientLight>();
        out = AmbientLight_create();
        AmbientLight_set(out, inAmbient->L);
        break;
      }
      case SceneGraph::LIGHT_DIRECTIONAL:
      {
        Ref<SceneGraph::DirectionalLight> inDirectional = in.dynamicCast<SceneGraph::DirectionalLight>();
        out = DirectionalLight_create();
        DirectionalLight_set(out, -normalize(inDirectional->D), inDirectional->E, 1.0f);
        break;
      }
      case SceneGraph::LIGHT_DISTANT:
      {
        Ref<SceneGraph::DistantLight> inDistant = in.dynamicCast<SceneGraph::DistantLight>();
        out = DirectionalLight_create();
        DirectionalLight_set(out,
                             -normalize(inDistant->D),
                             inDistant->L * rcp(uniformSampleConePDF(inDistant->cosHalfAngle)),
                             inDistant->cosHalfAngle);
        break;
      }
      case SceneGraph::LIGHT_POINT:
      {
        Ref<SceneGraph::PointLight> inPoint = in.dynamicCast<SceneGraph::PointLight>();
        out = PointLight_create();
        PointLight_set(out, inPoint->P, inPoint->I, 0.f);
        break;
      }
      case SceneGraph::LIGHT_SPOT:
      case SceneGraph::LIGHT_TRIANGLE:
      case SceneGraph::LIGHT_QUAD:
      {
        // FIXME: not implemented yet
        break;
      }

      default:
        THROW_RUNTIME_ERROR("unknown light type");
      }

      return (Light*)out;
    }

  private:
    ISPCScene (const ISPCScene& other) DELETED; // do not implement
    ISPCScene& operator= (const ISPCScene& other) DELETED; // do not implement

  public:
#endif
    ISPCGeometry** geometries;   //!< list of geometries
    ISPCMaterial** materials;     //!< material list
    unsigned int numGeometries;           //!< number of geometries
    unsigned int numMaterials;            //!< number of materials

    Light** lights;              //!< list of lights
    unsigned int numLights;               //!< number of lights

    RTCScene* geomID_to_scene;
    ISPCInstance** geomID_to_inst;
  };

#if !defined(ISPC)
  extern "C" RTCScene ConvertScene(RTCDevice g_device, ISPCScene* scene_in, RTCSceneFlags sflags, RTCAlgorithmFlags aflags, RTCGeometryFlags gflags);
#else
  unmasked extern "C" RTCScene ConvertScene (RTCDevice g_device, ISPCScene* uniform scene_in, uniform RTCSceneFlags sflags, uniform RTCAlgorithmFlags aflags, uniform RTCGeometryFlags gflags);
#endif

#if !defined(ISPC)
}
#endif


text:
from datetime import datetime
from django.conf import settings
from django.db.models import CharField, DateTimeField
from jeevesdb.JeevesModel import JeevesModel as Model, JeevesForeignKey as ForeignKey
from jeevesdb.JeevesModel import label_for

import pytz

from sourcetrans.macro_module import macros, jeeves
import JeevesLib

# An example model.
# Right now self-reference is either impossible or difficult because JeevesForeignKey
# only supports a model class (not a string) as the related object. (TODO fix this.)
class UserProfile(Model):
    username = CharField(max_length=256)
    name = CharField(max_length=512)
    email = CharField(max_length=256)

    @staticmethod
    def jeeves_get_private_email(user):
	return "[redacted]"

    @staticmethod
    @label_for('email')
    @jeeves
    def jeeves_restrict_userprofilelabel(user, ctxt):
        return user == ctxt

    @jeeves
    def has_event(self,event):
        return (EventGuest.objects.get(event=event, guest=self) != None) \
            or (EventHost.objects.get(event=event, host=self) != None)

    @jeeves
    def get_events(self):
        guest_events = EventGuest.objects.filter(guest=self).all()
        host_events = EventHost.objects.filter(host=self).all()
        events = []
        for event in guest_events:
            events.append(event.event)
        for event in host_events:
            events.append(event.event)
        return events

class Event(Model):
    VISIBILITY = (('E', 'Everyone'), ('G', 'Guests' ))

    name = CharField(max_length=256)
    location = CharField(max_length=512)
    time = DateTimeField()
    description = CharField(max_length=1024)
    visibility = CharField(max_length=1, choices=VISIBILITY, default='E')

    @jeeves
    def has_host(self, host):
        return EventHost.objects.get(event=self, host=host) != None

    @jeeves
    def has_guest(self, guest):
        return EventGuest.objects.get(event=self, guest=guest) != None

    @staticmethod
    def jeeves_get_private_name(event):
        return "Private event"
    @staticmethod
    def jeeves_get_private_location(event):
        return "Undisclosed location"
    @staticmethod
    def jeeves_get_private_time(event):
        return datetime.now(tz=pytz.utc)
    @staticmethod
    def jeeves_get_private_description(event):
        return "An event."

    @staticmethod
    @label_for('name', 'location', 'time', 'description')
    @jeeves
    def jeeves_restrict_event(event, ctxt):
        if event.visibility == 'G':
            return event.has_host(ctxt) or event.has_guest(ctxt)
        else:
            return True

class EventHost(Model):
    """Relates events to hosts.
    """
    event = ForeignKey(Event, null=True)
    host = ForeignKey(UserProfile, null=True)

class EventGuest(Model):
    """Relates events to guests.
    """
    event = ForeignKey(Event, null=True)
    guest = ForeignKey(UserProfile, null=True)

from django.dispatch import receiver
from django.db.models.signals import post_syncdb
import os
import sys
current_module = sys.modules[__name__]
@receiver(post_syncdb, sender=current_module)
def dbSynced(sender, **kwargs):
    if settings.DEBUG:
        execfile(os.path.join(settings.BASE_DIR, '..', 'SampleData.py'))


text:
package de.lessvoid.nifty.examples.lwjgl.defaultcontrolsxml;

import de.lessvoid.nifty.examples.defaultcontrolsxml.ScrollpanelExample;
import de.lessvoid.nifty.examples.lwjgl.NiftyExampleLoaderLWJGL;

/**
 * @author Aaron Mahan <aaron@forerunnergames.com>
 */
public class ScrollpanelDemoMain {
  public static void main(final String[] args) {
    NiftyExampleLoaderLWJGL.run(new ScrollpanelExample());
  }
}


text:
package com.google.common.collect;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.truth.Truth.assertThat;
import static java.util.Arrays.asList;

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.testing.ListTestSuiteBuilder;
import com.google.common.collect.testing.MinimalCollection;
import com.google.common.collect.testing.SetTestSuiteBuilder;
import com.google.common.collect.testing.TestStringListGenerator;
import com.google.common.collect.testing.TestStringSetGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.collect.testing.google.MultisetTestSuiteBuilder;
import com.google.common.collect.testing.google.TestStringMultisetGenerator;
import com.google.common.collect.testing.google.UnmodifiableCollectionTests;
import com.google.common.testing.EqualsTester;
import com.google.common.testing.NullPointerTester;
import com.google.common.testing.SerializableTester;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Tests for {@link ImmutableMultiset}.
 *
 * @author Jared Levy
 */
@GwtCompatible(emulated = true)
public class ImmutableMultisetTest extends TestCase {

  @GwtIncompatible("suite") // TODO(cpovirk): add to collect/gwt/suites
  @SuppressUnderAndroid
  public static Test suite() {
    TestSuite suite = new TestSuite();
    suite.addTestSuite(ImmutableMultisetTest.class);

    suite.addTest(MultisetTestSuiteBuilder.using(
        new TestStringMultisetGenerator() {
          @Override protected Multiset<String> create(String[] elements) {
            return ImmutableMultiset.copyOf(elements);
          }
        })
        .named("ImmutableMultiset")
        .withFeatures(CollectionSize.ANY,
            CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS,
            CollectionFeature.ALLOWS_NULL_QUERIES)
        .createTestSuite());

    suite.addTest(SetTestSuiteBuilder.using(new TestStringSetGenerator() {
          @Override protected Set<String> create(String[] elements) {
            return ImmutableMultiset.copyOf(elements).elementSet();
          }
        })
        .named("ImmutableMultiset, element set")
        .withFeatures(CollectionSize.ANY,
            CollectionFeature.SERIALIZABLE,
            CollectionFeature.ALLOWS_NULL_QUERIES)
        .createTestSuite());

    suite.addTest(ListTestSuiteBuilder.using(new TestStringListGenerator() {
          @Override protected List<String> create(String[] elements) {
            return ImmutableMultiset.copyOf(elements).asList();
          }

          @Override
          public List<String> order(List<String> insertionOrder) {
            List<String> order = new ArrayList<String>();
            for (String s : insertionOrder) {
              int index = order.indexOf(s);
              if (index == -1) {
                order.add(s);
              } else {
                order.add(index, s);
              }
            }
            return order;
          }
        })
        .named("ImmutableMultiset.asList")
        .withFeatures(CollectionSize.ANY,
            CollectionFeature.SERIALIZABLE,
            CollectionFeature.ALLOWS_NULL_QUERIES)
        .createTestSuite());

    suite.addTest(ListTestSuiteBuilder.using(new TestStringListGenerator() {
          @Override protected List<String> create(String[] elements) {
            Set<String> set = new HashSet<String>();
            ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder();
            for (String s : elements) {
              checkArgument(set.add(s));
              builder.addCopies(s, 2);
            }
            ImmutableSet<String> elementSet = (ImmutableSet<String>) builder.build().elementSet();
            return elementSet.asList();
          }
        })
        .named("ImmutableMultiset.elementSet.asList")
        .withFeatures(CollectionSize.ANY,
            CollectionFeature.REJECTS_DUPLICATES_AT_CREATION,
            CollectionFeature.SERIALIZABLE,
            CollectionFeature.ALLOWS_NULL_QUERIES)
        .createTestSuite());

    return suite;
  }

  public void testCreation_noArgs() {
    Multiset<String> multiset = ImmutableMultiset.of();
    assertTrue(multiset.isEmpty());
  }

  public void testCreation_oneElement() {
    Multiset<String> multiset = ImmutableMultiset.of("a");
    assertEquals(HashMultiset.create(asList("a")), multiset);
  }

  public void testCreation_twoElements() {
    Multiset<String> multiset = ImmutableMultiset.of("a", "b");
    assertEquals(HashMultiset.create(asList("a", "b")), multiset);
  }

  public void testCreation_threeElements() {
    Multiset<String> multiset = ImmutableMultiset.of("a", "b", "c");
    assertEquals(HashMultiset.create(asList("a", "b", "c")), multiset);
  }

  public void testCreation_fourElements() {
    Multiset<String> multiset = ImmutableMultiset.of("a", "b", "c", "d");
    assertEquals(HashMultiset.create(asList("a", "b", "c", "d")), multiset);
  }

  public void testCreation_fiveElements() {
    Multiset<String> multiset = ImmutableMultiset.of("a", "b", "c", "d", "e");
    assertEquals(HashMultiset.create(asList("a", "b", "c", "d", "e")),
        multiset);
  }

  public void testCreation_sixElements() {
    Multiset<String> multiset = ImmutableMultiset.of(
        "a", "b", "c", "d", "e", "f");
    assertEquals(HashMultiset.create(asList("a", "b", "c", "d", "e", "f")),
        multiset);
  }

  public void testCreation_sevenElements() {
    Multiset<String> multiset = ImmutableMultiset.of(
        "a", "b", "c", "d", "e", "f", "g");
    assertEquals(
        HashMultiset.create(asList("a", "b", "c", "d", "e", "f", "g")),
        multiset);
  }

  public void testCreation_emptyArray() {
    String[] array = new String[0];
    Multiset<String> multiset = ImmutableMultiset.copyOf(array);
    assertTrue(multiset.isEmpty());
  }

  public void testCreation_arrayOfOneElement() {
    String[] array = new String[] { "a" };
    Multiset<String> multiset = ImmutableMultiset.copyOf(array);
    assertEquals(HashMultiset.create(asList("a")), multiset);
  }

  public void testCreation_arrayOfArray() {
    String[] array = new String[] { "a" };
    Multiset<String[]> multiset = ImmutableMultiset.<String[]>of(array);
    Multiset<String[]> expected = HashMultiset.create();
    expected.add(array);
    assertEquals(expected, multiset);
  }

  public void testCreation_arrayContainingOnlyNull() {
    String[] array = new String[] { null };
    try {
      ImmutableMultiset.copyOf(array);
      fail();
    } catch (NullPointerException expected) {}
  }

  public void testCopyOf_collection_empty() {
    // "<String>" is required to work around a javac 1.5 bug.
    Collection<String> c = MinimalCollection.<String>of();
    Multiset<String> multiset = ImmutableMultiset.copyOf(c);
    assertTrue(multiset.isEmpty());
  }

  public void testCopyOf_collection_oneElement() {
    Collection<String> c = MinimalCollection.of("a");
    Multiset<String> multiset = ImmutableMultiset.copyOf(c);
    assertEquals(HashMultiset.create(asList("a")), multiset);
  }

  public void testCopyOf_collection_general() {
    Collection<String> c = MinimalCollection.of("a", "b", "a");
    Multiset<String> multiset = ImmutableMultiset.copyOf(c);
    assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset);
  }

  public void testCopyOf_collectionContainingNull() {
    Collection<String> c = MinimalCollection.of("a", null, "b");
    try {
      ImmutableMultiset.copyOf(c);
      fail();
    } catch (NullPointerException expected) {}
  }

  public void testCopyOf_multiset_empty() {
    Multiset<String> c = HashMultiset.create();
    Multiset<String> multiset = ImmutableMultiset.copyOf(c);
    assertTrue(multiset.isEmpty());
  }

  public void testCopyOf_multiset_oneElement() {
    Multiset<String> c = HashMultiset.create(asList("a"));
    Multiset<String> multiset = ImmutableMultiset.copyOf(c);
    assertEquals(HashMultiset.create(asList("a")), multiset);
  }

  public void testCopyOf_multiset_general() {
    Multiset<String> c = HashMultiset.create(asList("a", "b", "a"));
    Multiset<String> multiset = ImmutableMultiset.copyOf(c);
    assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset);
  }

  public void testCopyOf_multisetContainingNull() {
    Multiset<String> c = HashMultiset.create(asList("a", null, "b"));
    try {
      ImmutableMultiset.copyOf(c);
      fail();
    } catch (NullPointerException expected) {}
  }

  public void testCopyOf_iterator_empty() {
    Iterator<String> iterator = Iterators.emptyIterator();
    Multiset<String> multiset = ImmutableMultiset.copyOf(iterator);
    assertTrue(multiset.isEmpty());
  }

  public void testCopyOf_iterator_oneElement() {
    Iterator<String> iterator = Iterators.singletonIterator("a");
    Multiset<String> multiset = ImmutableMultiset.copyOf(iterator);
    assertEquals(HashMultiset.create(asList("a")), multiset);
  }

  public void testCopyOf_iterator_general() {
    Iterator<String> iterator = asList("a", "b", "a").iterator();
    Multiset<String> multiset = ImmutableMultiset.copyOf(iterator);
    assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset);
  }

  public void testCopyOf_iteratorContainingNull() {
    Iterator<String> iterator = asList("a", null, "b").iterator();
    try {
      ImmutableMultiset.copyOf(iterator);
      fail();
    } catch (NullPointerException expected) {}
  }

  private static class CountingIterable implements Iterable<String> {
    int count = 0;
    @Override
    public Iterator<String> iterator() {
      count++;
      return asList("a", "b", "a").iterator();
    }
  }

  public void testCopyOf_plainIterable() {
    CountingIterable iterable = new CountingIterable();
    Multiset<String> multiset = ImmutableMultiset.copyOf(iterable);
    assertEquals(HashMultiset.create(asList("a", "b", "a")), multiset);
    assertEquals(1, iterable.count);
  }

  public void testCopyOf_shortcut_empty() {
    Collection<String> c = ImmutableMultiset.of();
    assertSame(c, ImmutableMultiset.copyOf(c));
  }

  public void testCopyOf_shortcut_singleton() {
    Collection<String> c = ImmutableMultiset.of("a");
    assertSame(c, ImmutableMultiset.copyOf(c));
  }

  public void testCopyOf_shortcut_immutableMultiset() {
    Collection<String> c = ImmutableMultiset.of("a", "b", "c");
    assertSame(c, ImmutableMultiset.copyOf(c));
  }

  public void testBuilderAdd() {
    ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>()
        .add("a")
        .add("b")
        .add("a")
        .add("c")
        .build();
    assertEquals(HashMultiset.create(asList("a", "b", "a", "c")), multiset);
  }

  public void testBuilderAddAll() {
    List<String> a = asList("a", "b");
    List<String> b = asList("c", "d");
    ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>()
        .addAll(a)
        .addAll(b)
        .build();
    assertEquals(HashMultiset.create(asList("a", "b", "c", "d")), multiset);
  }

  public void testBuilderAddAllMultiset() {
    Multiset<String> a = HashMultiset.create(asList("a", "b", "b"));
    Multiset<String> b = HashMultiset.create(asList("c", "b"));
    ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>()
        .addAll(a)
        .addAll(b)
        .build();
    assertEquals(
        HashMultiset.create(asList("a", "b", "b", "b", "c")), multiset);
  }

  public void testBuilderAddAllIterator() {
    Iterator<String> iterator = asList("a", "b", "a", "c").iterator();
    ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>()
        .addAll(iterator)
        .build();
    assertEquals(HashMultiset.create(asList("a", "b", "a", "c")), multiset);
  }

  public void testBuilderAddCopies() {
    ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>()
        .addCopies("a", 2)
        .addCopies("b", 3)
        .addCopies("c", 0)
        .build();
    assertEquals(
        HashMultiset.create(asList("a", "a", "b", "b", "b")), multiset);
  }

  public void testBuilderSetCount() {
    ImmutableMultiset<String> multiset = new ImmutableMultiset.Builder<String>()
        .add("a")
        .setCount("a", 2)
        .setCount("b", 3)
        .build();
    assertEquals(
        HashMultiset.create(asList("a", "a", "b", "b", "b")), multiset);
  }

  public void testBuilderAddHandlesNullsCorrectly() {
    ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder();
    try {
      builder.add((String) null);
      fail("expected NullPointerException");
    } catch (NullPointerException expected) {}
  }

  public void testBuilderAddAllHandlesNullsCorrectly() {
    ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder();
    try {
      builder.addAll((Collection<String>) null);
      fail("expected NullPointerException");
    } catch (NullPointerException expected) {}

    builder = ImmutableMultiset.builder();
    List<String> listWithNulls = asList("a", null, "b");
    try {
      builder.addAll(listWithNulls);
      fail("expected NullPointerException");
    } catch (NullPointerException expected) {}

    builder = ImmutableMultiset.builder();
    Multiset<String> multisetWithNull
        = LinkedHashMultiset.create(asList("a", null, "b"));
    try {
      builder.addAll(multisetWithNull);
      fail("expected NullPointerException");
    } catch (NullPointerException expected) {}
  }

  public void testBuilderAddCopiesHandlesNullsCorrectly() {
    ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder();
    try {
      builder.addCopies(null, 2);
      fail("expected NullPointerException");
    } catch (NullPointerException expected) {}
  }

  public void testBuilderAddCopiesIllegal() {
    ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder();
    try {
      builder.addCopies("a", -2);
      fail("expected IllegalArgumentException");
    } catch (IllegalArgumentException expected) {}
  }

  public void testBuilderSetCountHandlesNullsCorrectly() {
    ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder();
    try {
      builder.setCount(null, 2);
      fail("expected NullPointerException");
    } catch (NullPointerException expected) {}
  }

  public void testBuilderSetCountIllegal() {
    ImmutableMultiset.Builder<String> builder = ImmutableMultiset.builder();
    try {
      builder.setCount("a", -2);
      fail("expected IllegalArgumentException");
    } catch (IllegalArgumentException expected) {}
  }

  @GwtIncompatible("NullPointerTester")
  public void testNullPointers() {
    NullPointerTester tester = new NullPointerTester();
    tester.testAllPublicStaticMethods(ImmutableMultiset.class);
  }

  @GwtIncompatible("SerializableTester")
  public void testSerialization_empty() {
    Collection<String> c = ImmutableMultiset.of();
    assertSame(c, SerializableTester.reserialize(c));
  }

  @GwtIncompatible("SerializableTester")
  public void testSerialization_multiple() {
    Collection<String> c = ImmutableMultiset.of("a", "b", "a");
    Collection<String> copy = SerializableTester.reserializeAndAssert(c);
    assertThat(copy).containsExactly("a", "a", "b").inOrder();
  }

  @GwtIncompatible("SerializableTester")
  public void testSerialization_elementSet() {
    Multiset<String> c = ImmutableMultiset.of("a", "b", "a");
    Collection<String> copy =
        LenientSerializableTester.reserializeAndAssertLenient(c.elementSet());
    assertThat(copy).containsExactly("a", "b").inOrder();
  }

  @GwtIncompatible("SerializableTester")
  public void testSerialization_entrySet() {
    Multiset<String> c = ImmutableMultiset.of("a", "b", "c");
    SerializableTester.reserializeAndAssert(c.entrySet());
  }

  public void testEquals_immutableMultiset() {
    Collection<String> c = ImmutableMultiset.of("a", "b", "a");
    assertEquals(c, ImmutableMultiset.of("a", "b", "a"));
    assertEquals(c, ImmutableMultiset.of("a", "a", "b"));
    assertThat(c).isNotEqualTo(ImmutableMultiset.of("a", "b"));
    assertThat(c).isNotEqualTo(ImmutableMultiset.of("a", "b", "c", "d"));
  }

  public void testIterationOrder() {
    Collection<String> c = ImmutableMultiset.of("a", "b", "a");
    assertThat(c).containsExactly("a", "a", "b").inOrder();
  }

  public void testMultisetWrites() {
    Multiset<String> multiset = ImmutableMultiset.of("a", "b", "a");
    UnmodifiableCollectionTests.assertMultisetIsUnmodifiable(multiset, "test");
  }

  public void testAsList() {
    ImmutableMultiset<String> multiset
        = ImmutableMultiset.of("a", "a", "b", "b", "b");
    ImmutableList<String> list = multiset.asList();
    assertEquals(ImmutableList.of("a", "a", "b", "b", "b"), list);
    assertEquals(2, list.indexOf("b"));
    assertEquals(4, list.lastIndexOf("b"));
  }

  @GwtIncompatible("SerializableTester")
  public void testSerialization_asList() {
    ImmutableMultiset<String> multiset
        = ImmutableMultiset.of("a", "a", "b", "b", "b");
    SerializableTester.reserializeAndAssert(multiset.asList());
  }

  public void testEquals() {
    new EqualsTester()
        .addEqualityGroup(ImmutableMultiset.of(), ImmutableMultiset.of())
        .addEqualityGroup(ImmutableMultiset.of(1), ImmutableMultiset.of(1))
        .addEqualityGroup(ImmutableMultiset.of(1, 1), ImmutableMultiset.of(1, 1))
        .addEqualityGroup(ImmutableMultiset.of(1, 2, 1), ImmutableMultiset.of(2, 1, 1))
        .testEquals();
  }
}


text:
<?php

namespace Ekyna\Bundle\CmsBundle\Validator\Constraints;

use Ekyna\Bundle\CmsBundle\Editor\Plugin\Block\Model;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

/**
 * Class TabsValidator
 * @package Ekyna\Bundle\CmsBundle\Validator\Constraints
 * @author  Etienne Dauvergne <contact@ekyna.com>
 */
class TabsValidator extends ConstraintValidator
{
    /**
     * @inheritDoc
     */
    public function validate($tabs, Constraint $constraint)
    {
        if (!$tabs instanceof Model\Tabs) {
            throw new UnexpectedTypeException($tabs, Model\Tabs::class);
        }
        if (!$constraint instanceof Tabs) {
            throw new UnexpectedTypeException($constraint, Tabs::class);
        }

        $locales = array_keys($tabs->getTranslations()->toArray());

        foreach ($tabs->getTabs() as $index => $tab) {
            /** @var Model\TabTranslation[] $translations */
            $translations = $tab->getTranslations()->toArray();

            $l = array_keys($translations);
            if (!empty(array_diff($locales, $l)) or !empty(array_diff($l, $locales))) {
                $this
                    ->context
                    ->buildViolation($constraint->locales_miss_match)
                    ->atPath("tabs[$index].translations")
                    ->addViolation();
            }

            $hasMedia = null;
            foreach ($translations as $locale => $translation) {
                if (is_null($hasMedia)) {
                    $hasMedia = !is_null($translation->getMedia());

                    continue;
                }

                if ($hasMedia xor !is_null($tab->getMedia())) {
                    $this
                        ->context
                        ->buildViolation($constraint->media_must_be_null)
                        ->atPath("tabs[$index].translations[$locale].media")
                        ->addViolation();
                }
            }
        }
    }
}


text:
package cache

import (
	"strconv"

	"github.com/docker/docker/daemon/logger"
	"github.com/docker/docker/daemon/logger/local"
	"github.com/pkg/errors"
)

func init() {
	for k, v := range local.LogOptKeys {
		builtInCacheLogOpts[cachePrefix+k] = v
	}
	logger.AddBuiltinLogOpts(builtInCacheLogOpts)
	logger.RegisterExternalValidator(validateLogCacheOpts)
}

func validateLogCacheOpts(cfg map[string]string) error {
	if v := cfg[cacheDisabledKey]; v != "" {
		_, err := strconv.ParseBool(v)
		if err != nil {
			return errors.Errorf("invalid value for option %s: %s", cacheDisabledKey, cfg[cacheDisabledKey])
		}
	}
	return nil
}

// MergeDefaultLogConfig reads the default log opts and makes sure that any caching related keys that exist there are
// added to dst.
func MergeDefaultLogConfig(dst, defaults map[string]string) {
	for k, v := range defaults {
		if !builtInCacheLogOpts[k] {
			continue
		}
		if _, exists := dst[k]; !exists {
			dst[k] = v
		}
	}
}


text:
package io.datalayer.kafka

class Test {

}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>PsyclePanel | psyborg</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					psyborg

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					"psyborg/Psycle/PsyclePanel"

					psyborg

					PsyclePanel

Class PsyclePanel

スライドショーパネル要素

since

0.1.0

param

対象要素

param

パネル番号

param

パネル要素リスト

Hierarchy

						PsyborgElement

								PsyclePanel

										PsyclePanelClone

Index

Constructors

constructor

Properties

$el

_list

el

has<wbr>Images

index

loaded

Methods

_load<wbr>Image<wbr>Observe

clone

get<wbr>Height

get<wbr>Max<wbr>Height

get<wbr>Min<wbr>Height

get<wbr>Width

hide

off

on

set<wbr>Height

set<wbr>Width

show

trigger

Constructors

constructor

new <wbr>Psycle<wbr>Panel($el: JQuery, index: number, list: PsyclePanelList): PsyclePanel

Overrides PsyborgElement.constructor

Defined in psyborg/Psycle/PsyclePanel.ts:11

Parameters

$el: JQuery

index: number

list: PsyclePanelList

Returns PsyclePanel

Properties

$el

$el: JQuery

Inherited from PsyborgElement.$el

Defined in psyborg/PsyborgElement.ts:25

内包するjQuery要素

since

0.1.0

Private _list

_list: PsyclePanelList

Defined in psyborg/Psycle/PsyclePanel.ts:32

スライドショーパネル要素リスト

since

0.1.0

el

el: Element

Inherited from PsyborgElement.el

Defined in psyborg/PsyborgElement.ts:32

内包するDOM要素

since

0.9.0

has<wbr>Images

has<wbr>Images: boolean = false

Defined in psyborg/Psycle/PsyclePanel.ts:39

パネル内に画像を含むかどうか

since

0.5.1

index

index: number

Defined in psyborg/Psycle/PsyclePanel.ts:25

自身のパネル番号

since

0.1.0

loaded

loaded: boolean = false

Defined in psyborg/Psycle/PsyclePanel.ts:46

パネル内に画像の読み込みが完了したかどうか

since

0.5.1

Methods

Protected _load<wbr>Image<wbr>Observe

_load<wbr>Image<wbr>Observe(): void

Defined in psyborg/Psycle/PsyclePanel.ts:96

画像が読み込まれたかどうか監視する
									インスタンスの load イベントにより通知する

since

0.5.1

Returns void

clone

clone(addDOM?: boolean, addList?: boolean): PsyclePanelClone

Defined in psyborg/Psycle/PsyclePanel.ts:79

クローン要素(クラスは異なる)を作る
									デフォルトではDOMやリストに追加される

since

0.1.0

Parameters

Default value addDOM: boolean = true

DOMに追加するかどうか

Default value addList: boolean = true

リストに追加するかどうか

Returns PsyclePanelClone

自身のクローン要素

get<wbr>Height

get<wbr>Height(): number

Inherited from PsyborgElement.getHeight

Defined in psyborg/PsyborgElement.ts:68

要素の高さを取得

since

0.4.3

Returns number

要素の高さ

get<wbr>Max<wbr>Height

get<wbr>Max<wbr>Height(): number

Inherited from PsyborgElement.getMaxHeight

Defined in psyborg/PsyborgElement.ts:78

要素から最大の高さを取得

since

0.9.1

Returns number

要素の高さ

get<wbr>Min<wbr>Height

get<wbr>Min<wbr>Height(): number

Inherited from PsyborgElement.getMinHeight

Defined in psyborg/PsyborgElement.ts:92

要素から最小の高さを取得

since

0.9.1

Returns number

要素の高さ

get<wbr>Width

get<wbr>Width(): number

Inherited from PsyborgElement.getWidth

Defined in psyborg/PsyborgElement.ts:58

要素の幅を取得

since

0.4.3

Returns number

要素の幅

hide

hide(): PsyclePanel

Defined in psyborg/Psycle/PsyclePanel.ts:65

要素を隠す

since

0.1.0

Returns PsyclePanel

自身

off

off(types: string, listener?: Function): void

Inherited from PsyborgEventDispacther.off

Defined in psyborg/PsyborgEventDispacther.ts:50

イベントを削除する

since

0.1.0

Parameters

types: string

イベントの種類(スペース区切りで複数可)

Optional listener: Function

リスナー関数

Returns void

on

on(types: string | string[], listener: function): void

Inherited from PsyborgEventDispacther.on

Defined in psyborg/PsyborgEventDispacther.ts:28

イベントを登録する

since

0.8.1

since

0.1.0

Parameters

types: string | string[]

イベントの種類(スペース区切りで複数可)

listener: function

リスナー関数

(e: PsyborgEvent): any

Parameters

e: PsyborgEvent

Returns any

Returns void

set<wbr>Height

set<wbr>Height(value: number): PsyborgElement

Inherited from PsyborgElement.setHeight

Defined in psyborg/PsyborgElement.ts:122

要素の高さを設定

since

0.4.3

Parameters

value: number

指定の値

Returns PsyborgElement

自身

set<wbr>Width

set<wbr>Width(value: number): PsyborgElement

Inherited from PsyborgElement.setWidth

Defined in psyborg/PsyborgElement.ts:110

要素の幅を設定

since

0.4.3

Parameters

value: number

指定の値

Returns PsyborgElement

自身

show

show(): PsyclePanel

Defined in psyborg/Psycle/PsyclePanel.ts:54

要素を表示する

since

0.1.0

Returns PsyclePanel

自身

trigger

trigger(type: string, data?: any, context?: any): boolean

Inherited from PsyborgElement.trigger

Overrides PsyborgEventDispacther.trigger

Defined in psyborg/PsyborgElement.ts:44

イベントを任意に発火させる 要素にバインドされているイベントも同時に発火する

since

0.3.0

override

Parameters

type: string

イベントの種類

Default value data: any = {}

発火と同時にリスナー関数に渡すハッシュデータ

Default value context: any = this

リスナー関数のthisコンテクスト

Returns boolean

デフォルトのイベントの抑制がされていないかどうか

						Globals

						"psyborg/<wbr>Psycle/<wbr>Psycle<wbr>Panel"

								psyborg

						Psycle<wbr>Panel

								constructor

								$el

								_list

								el

								has<wbr>Images

								index

								loaded

								_load<wbr>Image<wbr>Observe

								clone

								get<wbr>Height

								get<wbr>Max<wbr>Height

								get<wbr>Min<wbr>Height

								get<wbr>Width

								hide

								off

								on

								set<wbr>Height

								set<wbr>Width

								show

								trigger

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
A collection of scripts to parse Indian Budget documents into clean machine readable formats.

## Installation Notes
Currently tested on Linux and Mac OS

1. Clone the repository
`git clone https://github.com/cbgaindia/parsers.git`

2. Install package dependencies:
`pip install -r requirements.txt`

3. Install software dependencies:
  - Tabula Java: https://github.com/tabulapdf/tabula-java
  - ImageMagic: https://www.imagemagick.org/script/install-source.php

4. Finding appropriate parser:
All parsers are arranged according to tiers of government, to see usage run script with help(-h) option.

## Related Repository
To scrape budget data files from various sources, please refer to https://github.com/cbgaindia/scrapers

## Documentation
Please refer to http://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html for documentation style guide lines.


text:
title: Create a Hash-like structure with Bash
created_at: 2013-12-17 13:55
updated_at: 2013-12-17 13:55
kind: blog-post
author: Gabe Koss
summary: TIL you can create a hash like structure using bashes 'declare'
tags:
 - bash
---

This is pretty cool and worth sharing. In Bash you can use `declare -A VarName`
to create a Hash-like structure which you can use to store key / value pairs
in.

Lets take a look:

```bash
$ declare -A CapitalCity
$ CapitalCity[France]="Paris"
$ echo "${CapitalCity['France']}"
Paris
```

Pretty damn cool. I discovered this trick in Jason Brittains 'Bash as a Modern
Programming Language' presentation. [Slides are
available.](http://digital-era.net/wp-content/uploads/2013/12/BASH-as-a-Modern-Programming-Language-Presentation-1.pdf)

## Enumerate set values from `declare`

To get a list of set values you can run `declare -A` and it will print a list
similar to the following:

```bash
$ declare -A
declare -A BASH_ALIASES='()'
declare -A BASH_CMDS='()'
declare -A CapitalCity='([France]="Paris" )'
declare -A _xspecs='(... <many many> ...)'
```


text:
<?php

return [
    'create_form_title' => 'Geschenk Titel',
    'create_title' => ' Geschenk erstellen',
    'create_form_description' => 'Beschreibung',
    'form_button_remove_link' => 'Link löschen',
    'form_label_links' => 'Link zum Geschenk eintragen',
    'form_button_add_link' => 'Link hinzufügen',
    'create_form_imagepath' => 'Bild',
    'create_form_links' => 'Links',
    'delete_success' => 'Das Geschenk ":Title" (:Id) wurde erfolgreich gelöscht.',
    'create_success' => 'Das Geschenk ":Title" wurde erfolgreich unter der Nummer :Id angelegt',
    'release_success' => 'Das Geschenk ":Title" wurde erfolgreich released',
    'draft_success' => 'Das Geschenk ":Title" wurde erfolgreich wieder auf Entwurf gestellt',
    'reset_success' => 'Das Geschenk ":Title" wurde erfolgreich wieder freigegeben.',
    'status_draft' => 'Entwurf',
    'details_title' => 'Details vom Geschenk :Title',
    'share_success' => 'Du hast das Geschenk ":Title" mit dem Code zur freigabe :Code gewählt',
    'share_error' => 'Das Geschenk :Title ist schon ausgewählt.',

    'status_release' => 'Veröffentlicht',
    'status_select' => 'Ausgewählt',
    'status_unkown' => 'Unbekannt',
    'error_title' => 'ACHTUNG!',
    'error_title_text' => 'Da gab es wohl ein Fehler. Bitte überprüfen:',
    'edit_title' => 'Geschenk :Title mit der ID :Id editieren',

    'reset_error' => 'Der Code passt leider nicht',

];


text:
package mesosphere.marathon.core.task.bus

import org.apache.mesos.Protos.TaskStatus

sealed trait MarathonTaskStatus {
  def terminal: Boolean = false
  def mesosStatus: Option[TaskStatus]
}

// FIXME (merge): Merge MarathonTaskStatus and MesosTaskStatus
object MarathonTaskStatus {
  import org.apache.mesos.Protos.TaskState._

  def apply(mesosStatus: TaskStatus): MarathonTaskStatus = {
    val constructor: Option[TaskStatus] => MarathonTaskStatus = mesosStatus.getState match {
      case TASK_STAGING => Staging
      case TASK_STARTING => Starting
      case TASK_RUNNING => Running
      case TASK_KILLING => Killing
      case TASK_FINISHED => Finished
      case TASK_FAILED => Failed
      case TASK_KILLED => Killed
      case TASK_LOST => Lost
      case TASK_ERROR => Error
    }
    constructor(Some(mesosStatus))
  }

  case class Staging(mesosStatus: Option[TaskStatus]) extends MarathonTaskStatus
  case class Starting(mesosStatus: Option[TaskStatus]) extends MarathonTaskStatus
  case class Running(mesosStatus: Option[TaskStatus]) extends MarathonTaskStatus
  case class Killing(mesosStatus: Option[TaskStatus]) extends MarathonTaskStatus

  // Note that we need to distinguish between TemporarilyUnreachable tasks and really lost tasks that won't come back
  // tl;dr: don't use Lost
  case class Lost(mesosStatus: Option[TaskStatus]) extends MarathonTaskStatus

  sealed trait Terminal extends MarathonTaskStatus {
    override def terminal: Boolean = true
    def killed: Boolean = false
  }
  object Terminal {
    def unapply(terminal: Terminal): Option[Terminal] = Some(terminal)
    def unapply(status: MarathonTaskStatus): Option[MarathonTaskStatus] = status.mesosStatus match {
      case Some(MesosTaskStatus.Terminal(_)) => Some(status)
      case _ => None
    }
  }

  object WithMesosStatus {
    def unapply(marathonTaskStatus: MarathonTaskStatus): Option[TaskStatus] = marathonTaskStatus.mesosStatus
  }

  case class Finished(mesosStatus: Option[TaskStatus]) extends Terminal
  case class Failed(mesosStatus: Option[TaskStatus]) extends Terminal
  case class Killed(mesosStatus: Option[TaskStatus]) extends Terminal {
    override def killed: Boolean = true
  }
  case class Error(mesosStatus: Option[TaskStatus]) extends Terminal
}


text:
@interface StarView : UIView

@property (assign, nonatomic) float score;

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Semantics</title>

My Blog Site

Home

About

Contact

Latest Posts

Blog Post 3 Title

                    Read More

Published on <time datetime="2001-05-15 19:00">May 15</time>.

Nulla vitae elit libero, a pharetra augue.

Blog Post 2 Title

                    Read More

Published on <time datetime="2001-05-12 11:00">May 12</time>.

Ut enim ad minim veniam, quis nostrud exercitation.

Blog Post 1 Title

                    Read More

Published on <time datetime="2001-05-09 15:00">May 9</time>.

Excepteur sint occaecat cupidatat non proident.

© Copyright 2015 Nobody. No rights reserved.


text:
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')

describe "Bootcamp::Base" do

end


text:
  Brossac est
       un village
       situé dans le département de Charente en Poitou-Charentes. Elle totalisait 564 habitants en 2008.

La commune propose quelques  équipements, elle propose entre autres un bassin de natation, un terrain de tennis et un terrain de sport.

À Brossac, le prix moyen à la vente d'un appartement se situe à zero € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 981 € du m². À la location le prix moyen se situe à 0 € du m² mensuel.

Le nombre d'habitations, à Brossac, se décomposait en 2011 en 33 appartements et 365 maisons soit
 un marché relativement équilibré.

À proximité de Brossac sont localisées les communes de
Bardenac à 3 km, 229 habitants,
Sainte-Souline située à 5 km, 123 habitants,
Chillac localisée à 4 km, 195 habitants,
Curac localisée à 6 km, 119 habitants,
Saint-Vallier à 4 km, 153 habitants,
Châtignac localisée à 3 km, 202 habitants,
 entre autres. De plus, Brossac est située à seulement 18 km de Barbezieux-Saint-Hilaire.

Si vous envisagez de venir habiter à Brossac, vous pourrez facilement trouver une maison à vendre.


text:
<?php

namespace Sonata\AdminBundle\Tests\Fixtures\Admin;

use Sonata\AdminBundle\Admin\Admin;

class CleanAdmin extends Admin
{
}


text:
package nz.co.doltech.gwtjui.core.client.events;

import com.google.gwt.event.shared.EventHandler;
import nz.co.doltech.gwtjui.core.client.JuiWrapper;
import nz.co.doltech.gwtjui.core.client.base.EventHash;

/**
 * This event is triggered when sorting starts.
 *
 * @author Ben Dol
 */
public interface StartHandler<T extends JuiWrapper, H extends EventHash> extends EventHandler {
    void onStart(StartEvent<T, H> event);
}


text:
<manifest package="com.jgrife.configdrawer">

    <application />

</manifest>


text:
package com.opower.rest.test.resource;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Optional;
import java.util.Random;
import org.joda.time.LocalDate;

/**
 * Simple entity used for exercising JAX-RS implementations.
 */
public class Frob {

    private static final int MAX_RAND = 100;
    private static final int HALF_MAX = MAX_RAND / 2;

    @JsonProperty
    private String id;

    @JsonProperty
    private Integer counter = new Random(MAX_RAND).nextInt();

    @JsonProperty
    private Optional<Long> optionalField = this.counter < HALF_MAX ? Optional.<Long>absent() : Optional.of(new Random().nextLong());

    @JsonProperty
    private LocalDate localDate = new LocalDate();

    /**
     * Simple constructor.
     */
    public Frob() {

    }

    /**
     * Construct a Frob with the given id.
     * @param id id to use
     */
    public Frob(String id) {
        this.id = id;
    }

    /**
     * This optional field will make sure that introducing Optional fields to classes will work at
     * runtime.
     * @return the sample optionalField
     */
    public Optional<Long> getOptionalField() {
        return this.optionalField;
    }

    /**
     * This LocalDate field will ensure that introducing joda classes to the various client tests will
     * work at runtime.
     * @return the sample localDate field
     */
    public LocalDate getLocalDate() {
        return this.localDate;
    }

    /**
     * Get the id of the Frob instance.
     * @return the id.
     */
    public String getId() {
        return this.id;
    }

    /**
     * A simple integer field.
     * @return the value of counter
     */
    public Integer getCounter() {
        return this.counter;
    }
}


text:
/*
 * matchinggraph.h
 *
 *  Created on: 8-feb-2011
 *      Author: M. El-Kebir
 */

#ifndef MATCHINGGRAPH_H_
#define MATCHINGGRAPH_H_

#include <assert.h>
#include <string>
#include <fstream>
#include <list>
#include <lemon/core.h>
#include <lemon/connectivity.h>
#include <lemon/lgf_reader.h>
#include <lemon/lgf_writer.h>
#include "input/gmlparser.h"
#include "input/graphmlparser.h"
#include "input/stringparser.h"
#include "input/lgfparser.h"
#include "input/csvparser.h"
#include "input/ledaparser.h"
#include "input/parser.h"
#include "verbose.h"
#include "input/bpparser.h"
#include "webserver.h"

namespace nina {
namespace gna {

template<typename GR, typename BGR>
class MatchingGraph
{
public:
  /// The graph type of the input graphs
  typedef GR Graph;
  /// The graph type of the bipartite matching graph
  typedef BGR BpGraph;
  /// Weights on original edges
  typedef typename Graph::template EdgeMap<double> WeightEdgeMap;
  /// Weights on matching edges
  typedef typename BpGraph::template EdgeMap<double> BpWeightEdgeMap;

protected:
  TEMPLATE_GRAPH_TYPEDEFS(Graph);

  typedef typename BpGraph::Node BpNode;
  typedef typename BpGraph::Edge BpEdge;
  typedef typename BpGraph::NodeIt BpNodeIt;
  typedef typename BpGraph::EdgeIt BpEdgeIt;
  typedef typename BpGraph::IncEdgeIt BpIncEdgeIt;
  typedef typename BpGraph::RedNode BpRedNode;
  typedef typename BpGraph::BlueNode BpBlueNode;
  typedef typename BpGraph::RedNodeIt BpRedNodeIt;
  typedef typename BpGraph::BlueNodeIt BpBlueNodeIt;

  /// Labels of the nodes
  typedef typename Graph::template NodeMap<std::string> OrigLabelNodeMap;
  /// Mapping from original nodes to matching nodes
  typedef typename Graph::template NodeMap<BpNode> OrigNodeToMatchNodeMap;
  /// Mapping from matching nodes to original nodes
  typedef typename BpGraph::template NodeMap<Node> MatchNodeToOrigNodeMap;
  /// Mapping from matching nodes to original nodes
  typedef typename BpGraph::template NodeMap<std::string> BpStringNodeMap;
  /// Mapping from labels to original nodes
  typedef std::map<std::string, typename Graph::Node> InvOrigLabelNodeMap;
  /// Parser type
  typedef Parser<Graph> ParserType;
  /// Bipartite parser type
  typedef BpParser<Graph, BpGraph> BpParserType;

  /// Matching graph
  BpGraph _gm;
  /// Input graph 1 (\f$G_1\f$)
  Graph _g1;
  /// Input graph 2 (\f$G_2\f$)
  Graph _g2;
  /// Node labels for \f$G_1\f$
  OrigLabelNodeMap _labelG1;
  /// Node labels for \f$G_2\f$
  OrigLabelNodeMap _labelG2;
  /// Inverse map from label to node in G_1
  InvOrigLabelNodeMap _invLabelG1;
  /// Inverse map from label to node in G_2
  InvOrigLabelNodeMap _invLabelG2;
  /// Mapping from original nodes in \f$G_1\f$ to matching nodes
  OrigNodeToMatchNodeMap _g1ToGm;
  /// Mapping from original nodes in \f$G_2\f$ to matching nodes
  OrigNodeToMatchNodeMap _g2ToGm;
  /// Mapping from matching nodes to original nodes
  MatchNodeToOrigNodeMap _gmToG12;
  /// Weights on edges in G_1
  WeightEdgeMap _weightG1;
  /// Weights on edges in G_2
  WeightEdgeMap _weightG2;
  /// Weights on edges in G_m
  BpWeightEdgeMap _weightGm;
  /// Alternative weights on edges in G_m
  BpWeightEdgeMap _weightAltGm;
  /// Number of matching edges
  int _nEdgesGm;
  /// Number of nodes in \f$G_1\f$
  int _nNodesG1;
  /// Number of nodes in \f$G_2\f$
  int _nNodesG2;
  /// Number of edges in \f$G_1\f$
  int _nEdgesG1;
  /// Number of edges in \f$G_2\f$
  int _nEdgesG2;
  /// Allows looking up edges in \f$O(\log d)\f$ time in \f$G_1\f$
  lemon::ArcLookUp<Graph> _arcLookUpG1;
  /// Allows looking up edges in \f$O(\log d)\f$ time in \f$G_2\f$
  lemon::ArcLookUp<Graph> _arcLookUpG2;
  /// Score model
  //const ScoreModel<Graph, BpGraph>* _pScore;

  bool parse(ParserType* pParser);
  bool parse(BpParserType* pBpParser);

  /// Load G_m in LGF format
  void loadGm(std::istream& in);

public:
  /// Constructor
  MatchingGraph();
  /// Virtual destructor
  virtual ~MatchingGraph() {}
  /// Initialize G_1, G_2 and G_m
  virtual bool init(ParserType* pParserG1,
                    ParserType* pParserG2,
                    BpParserType* pParserGm);
  /// Return the label of a node in \f$G_m\f$
  const std::string& getLabelGm(BpNode n) const;
  /// Return the label of a node in \f$G_1\f$
  const std::string& getLabelG1(Node n) const;
  /// Return the label of a node in \f$G_2\f$
  const std::string& getLabelG2(Node n) const;
  /// Return map of labels of nodes in \f$G_1\f$
  const OrigLabelNodeMap& getMapLabelG1() const { return _labelG1; }
  /// Return map of labels of nodes in \f$G_2\f$
  const OrigLabelNodeMap& getMapLabelG2() const { return _labelG2; }
  /// Get node in \f$G_1\f$ by label
  Node getNodeG1(const std::string& label) const;
  /// Get node in \f$G_2\f$ by label
  Node getNodeG2(const std::string& label) const;
  /// Find an edge between two nodes in \f$G_1\f$
  Edge getEdgeG1(Node u, Node v) const { return _arcLookUpG1(u, v); }
  /// Find an edge between two nodes in \f$G_2\f$
  Edge getEdgeG2(Node u, Node v) const { return _arcLookUpG2(u, v); }
  /// Return node in \f$G_m\f$ corresponding to node n in \f$G_1\f$
  virtual BpNode mapG1ToGm(Node n) const;
  /// Return node in \f$G_m\f$ corresponding to node n in \f$G_2\f$
  virtual BpNode mapG2ToGm(Node n) const;
  /// Return node in \f$G_1\f$ corresponding to node n in \f$G_m\f$
  virtual Node mapGmToG1(BpNode n) const;
  /// Return node in \f$G_2\f$ corresponding to node n in \f$G_m\f$
  virtual Node mapGmToG2(BpNode n) const;
  /// Return \f$G_m\f$
  const BpGraph& getGm() const { return _gm; }
  /// Return \f$G_1\f$
  const Graph& getG1() const { return _g1; }
  /// Return \f$G_2\f$
  const Graph& getG2() const { return _g2; }
  /// Return number of edges in \f$G_m\f$
  int getEdgeCountGm() const { return _nEdgesGm; }
  /// Return number of edges in \f$G_1\f$
  int getEdgeCountG1() const { return _nEdgesG1; }
  /// Return number of edges in \f$G_2\f$
  int getEdgeCountG2() const { return _nEdgesG2; }
  /// Return number of nodes in \f$G_1\f$
  int getNodeCountG1() const { return _nNodesG1; }
  /// Return number of nodes in \f$G_2\f$
  int getNodeCountG2() const { return _nNodesG2; }
  /// Return weight of edge in G_1
  double getWeightG1(Edge ij) const { return _weightG1[ij]; }
  /// Return weight of edge in G_2
  double getWeightG2(Edge kl) const { return _weightG2[kl]; }
  /// Return weight of edge in G_m
  double getWeightGm(BpEdge ik) const { return _weightGm[ik]; }
  /// Return alternative weight of edge in G_m
  double getWeightAltGm(BpEdge ik) const { return _weightAltGm[ik]; }
  /// Return matching edge weight map
  const BpWeightEdgeMap& getWeightGmMap() const { return _weightGm; }
  /// Return matching edge weight map
  BpWeightEdgeMap& getWeightGmMap() { return _weightGm; }
  /// Return matching edge weight map
  const BpWeightEdgeMap& getWeightAltGmMap() const { return _weightAltGm; }
  /// Save G_1 in LGF format
  void saveG1(std::ostream& out) const;
  /// Save G_2 in LGF format
  void saveG2(std::ostream& out) const;
  /// Save G_m in LGF format
  void saveGm(std::ostream& out) const;
};

template<typename GR, typename BGR>
inline MatchingGraph<GR, BGR>::MatchingGraph()
  : _gm()
  , _g1()
  , _g2()
  , _labelG1(_g1)
  , _labelG2(_g2)
  , _invLabelG1()
  , _invLabelG2()
  , _g1ToGm(_g1)
  , _g2ToGm(_g2)
  , _gmToG12(_gm)
  , _weightG1(_g1)
  , _weightG2(_g2)
  , _weightGm(_gm)
  , _weightAltGm(_gm)
  , _nEdgesGm(0)
  , _nNodesG1(0)
  , _nNodesG2(0)
  , _nEdgesG1(0)
  , _nEdgesG2(0)
  , _arcLookUpG1(_g1)
  , _arcLookUpG2(_g2)
{
}

template<typename GR, typename BGR>
inline bool MatchingGraph<GR, BGR>::init(ParserType* pParserG1,
                                         ParserType* pParserG2,
                                         BpParserType* pParserGm)
{
  assert(pParserG1 && pParserG2 && pParserGm);

  pParserG1->setGraph(&_g1);
  pParserG1->setIdNodeMap(&_labelG1);
  pParserG1->setInvIdNodeMap(&_invLabelG1);
  pParserG1->setWeightEdgeMap(&_weightG1);

  pParserG2->setGraph(&_g2);
  pParserG2->setIdNodeMap(&_labelG2);
  pParserG2->setInvIdNodeMap(&_invLabelG2);
  pParserG2->setWeightEdgeMap(&_weightG2);

  if (parse(pParserG1) && parse(pParserG2))
  {
    _nNodesG1 = pParserG1->getNodeCount();
    _nEdgesG1 = pParserG1->getEdgeCount();
    _nNodesG2 = pParserG2->getNodeCount();
    _nEdgesG2 = pParserG2->getEdgeCount();
    _arcLookUpG1.refresh();
    _arcLookUpG2.refresh();
  }
  else
  {
    return false;
  }

  pParserGm->setGraph(&_gm);
  pParserGm->setWeightEdgeMap(&_weightGm);
  pParserGm->setWeightAltEdgeMap(&_weightAltGm);
  pParserGm->setG1ToGmMap(&_g1ToGm);
  pParserGm->setG2ToGmMap(&_g2ToGm);
  pParserGm->setGmToG12Map(&_gmToG12);

  if (!parse(pParserGm))
    return false;

  _nEdgesGm = pParserGm->getEdgeCount();
  return true;
}

template<typename GR, typename BGR>
inline bool MatchingGraph<GR, BGR>::parse(ParserType* pParser)
{
  if (!pParser->parse())
    return false;

  const std::string& filename = pParser->getFilename();
  int nNodes = pParser->getNodeCount();
  int nEdges = pParser->getEdgeCount();

  if (!lemon::simpleGraph(*pParser->getGraph()))
  {
    std::cerr << "'" << (g_webserver ? "input graph" : filename)
              << "' is not a simple graph." << std::endl;
    return false;
  }
  else if (g_verbosity >= VERBOSE_ESSENTIAL)
  {
    std::cout << "Successfully parsed '"
              << (g_webserver ? "input graph" : filename)
              << "': contains " << nNodes << " nodes and "
              << nEdges << " edges" << std::endl;
  }

  return true;
}

template<typename GR, typename BGR>
inline bool MatchingGraph<GR, BGR>::parse(BpParserType* pBpParser)
{
  if (!pBpParser->parse())
    return false;

  const std::string& filename = pBpParser->getFilename();
  int nEdges = pBpParser->getEdgeCount();

  if (!lemon::simpleGraph(*pBpParser->getGraph()))
  {
    std::cerr << "'" << (g_webserver ? "input graph" : filename)
              << "' is not a simple graph." << std::endl;
    return false;
  }
  else if (g_verbosity >= VERBOSE_ESSENTIAL)
  {
    std::cout << "Successfully parsed '"
              << (g_webserver || filename.empty() ? "matching graph" : filename)
              << "': contains " << nEdges << " matching edges" << std::endl;
  }

  return true;
}

template<typename GR, typename BGR>
inline const std::string& MatchingGraph<GR, BGR>::getLabelGm(BpNode n) const
{
  assert(n != lemon::INVALID && _gm.valid(n));

  if (_gm.red(n))
  {
    Node r = _gmToG12[n];
    return _labelG1[r];
  }
  else
  {
    assert(_gm.blue(n));
    Node b = _gmToG12[n];
    return _labelG2[b];
  }
}

template<typename GR, typename BGR>
inline void MatchingGraph<GR, BGR>::saveG1(std::ostream& out) const
{
  IntNodeMap idMap(_g1);
  for (NodeIt n(_g1); n != lemon::INVALID; ++n)
  {
    idMap[n] = _gm.id(_g1ToGm[n]);
  }

  graphWriter(_g1, out)
    .nodeMap("id", _labelG1)
    .nodeMap("mapToGm", idMap)
    .edgeMap("weight", _weightG1)
    .run();
}

template<typename GR, typename BGR>
inline void MatchingGraph<GR, BGR>::saveG2(std::ostream& out) const
{
  IntNodeMap idMap(_g2);
  for (NodeIt n(_g2); n != lemon::INVALID; ++n)
  {
    idMap[n] = _gm.id(_g2ToGm[n]);
  }

  graphWriter(_g2, out)
    .nodeMap("id", _labelG2)
    .nodeMap("mapToGm", idMap)
    .edgeMap("weight", _weightG2)
    .run();
}

template<typename GR, typename BGR>
inline void MatchingGraph<GR, BGR>::saveGm(std::ostream& out) const
{
  BpStringNodeMap idMap(_gm);

  for (BpNodeIt n(_gm); n != lemon::INVALID; ++n)
  {
    idMap[n] = getLabelGm(n);
  }

  bpGraphWriter(_gm, out)
    .nodeMap("id", idMap)
    .edgeMap("weight", _weightGm)
    .run();
}

template<typename GR, typename BGR>
inline typename GR::Node MatchingGraph<GR, BGR>::getNodeG1(const std::string& label) const
{
  typename InvOrigLabelNodeMap::const_iterator it = _invLabelG1.find(label);
  if (it == _invLabelG1.end())
    return lemon::INVALID;
  else
    return it->second;
}

template<typename GR, typename BGR>
inline typename GR::Node MatchingGraph<GR, BGR>::getNodeG2(const std::string& label) const
{
  typename InvOrigLabelNodeMap::const_iterator it = _invLabelG2.find(label);
  if (it == _invLabelG2.end())
    return lemon::INVALID;
  else
    return it->second;
}

template<typename GR, typename BGR>
inline const std::string& MatchingGraph<GR, BGR>::getLabelG1(Node n) const
{
  assert(n != lemon::INVALID && _g1.valid(n));
  return _labelG1[n];
}

template<typename GR, typename BGR>
inline const std::string& MatchingGraph<GR, BGR>::getLabelG2(Node n) const
{
  assert(n != lemon::INVALID && _g2.valid(n));
  return _labelG2[n];
}

template<typename GR, typename BGR>
inline typename BGR::Node MatchingGraph<GR, BGR>::mapG1ToGm(Node n) const
{
  assert(n != lemon::INVALID && _g1.valid(n));
  return _g1ToGm[n];
}

template<typename GR, typename BGR>
inline typename BGR::Node MatchingGraph<GR, BGR>::mapG2ToGm(Node n) const
{
  assert(n != lemon::INVALID && _g2.valid(n));
  return _g2ToGm[n];
}

template<typename GR, typename BGR>
inline typename GR::Node MatchingGraph<GR, BGR>::mapGmToG1(BpNode n) const
{
  assert(n != lemon::INVALID && _gm.valid(n));

  if (_gm.red(n))
    return _gmToG12[n];
  else
    return lemon::INVALID;
}

template<typename GR, typename BGR>
inline typename GR::Node MatchingGraph<GR, BGR>::mapGmToG2(BpNode n) const
{
  assert(n != lemon::INVALID && _gm.valid(n));

  if (_gm.blue(n))
    return _gmToG12[n];
  else
    return lemon::INVALID;
}

} // namespace gna
} // namespace nina

#endif /* MATCHINGGRAPH_H_ */


text:
tastyroot
=========

Webservice API framework for Go.

It's mostly built for fun and practice, thus:

1. It lacks a lot of REST frameworks' features.
2. Decisions made in it may not be perfect.


text:
package org.apache.servicemix.locks.impl;

import java.util.concurrent.locks.Lock;

import junit.framework.TestCase;

public class SimpleLockTest extends TestCase {

    public void testSimple() {
        @SuppressWarnings("deprecation")
        Lock l = new SimpleLock();

        assertTrue(l.tryLock());
        assertFalse(l.tryLock());
        l.unlock();
        l.lock();
        l.unlock();
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--Currently Google SignIn button in Android does not support dark scheme.
    Using light scheme instead -->
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_enabled="false"
        android:drawable="@drawable/common_google_signin_btn_text_dark_disabled" />
    <item
        android:state_pressed="true"
        android:drawable="@drawable/common_google_signin_btn_text_dark_pressed" />
    <item
        android:state_focused="true"
        android:drawable="@drawable/common_google_signin_btn_text_dark_focused" />
    <item
        android:drawable="@drawable/common_google_signin_btn_text_dark_normal" />
</selector>
<!-- From: file:/tmp/tmp-deduplicated6141127760898580491/java/com/google/android/gmscore/integ/client/base/res/drawable/common_google_signin_btn_text_dark.xml -->


text:
package com.nirima.jenkins.plugins.docker.client;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.DockerCmdExecFactory;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.DockerClientConfig;
import com.github.dockerjava.core.DockerClientImpl;
import com.github.dockerjava.jaxrs.DockerCmdExecFactoryImpl;

import java.util.ServiceLoader;

/**
 * Created by magnayn on 10/07/2015.
 */
public class ClientBuilderForPlugin  {

    private final DockerClientConfig config;

    private ClientBuilderForPlugin(DockerClientConfig config) {
        this.config = config;
    }

    public static ClientBuilderForPlugin getInstance(DockerClientConfig.DockerClientConfigBuilder dockerClientConfigBuilder) {
        return getInstance(dockerClientConfigBuilder.build());
    }

    public static ClientBuilderForPlugin getInstance(DockerClientConfig dockerClientConfig) {
        return new ClientBuilderForPlugin(dockerClientConfig);
    }

    public static ClientBuilderForPlugin getInstance(ClientConfigBuilderForPlugin dockerClientConfig) {
        return new ClientBuilderForPlugin(dockerClientConfig.build());
    }

    public DockerClient build() {
        return DockerClientBuilder.getInstance(config)
                .withDockerCmdExecFactory(new DockerCmdExecFactoryImpl())
                .build();

    }
}


text:
package com.xiaomi.linden.core;

import org.junit.Assert;
import org.junit.Test;

import java.io.File;

public class TestLindenConfigBuilder {
  @Test
  public void configurationTest() throws Exception {
    File file = new File(getClass().getResource("/conf_test.properties").getPath());
    LindenConfig lindenConf = LindenConfigBuilder.build(file);
    Assert.assertEquals("./target/tmp", lindenConf.getIndexDirectory());
    Assert.assertEquals("127.0.0.1:2181,127.0.0.2:2181/linden_test", lindenConf.getClusterUrl());
    Assert.assertEquals(9091, lindenConf.getPort());
    Assert.assertTrue(lindenConf.isEnableParallelSearch());

    Assert.assertEquals(LindenConfig.LindenCoreMode.MULTI, lindenConf.getLindenCoreMode());
    Assert.assertEquals(LindenConfig.MultiIndexDivisionType.TIME_MONTH, lindenConf.getMultiIndexDivisionType());
    Assert.assertEquals(10, lindenConf.getMultiIndexMaxLiveIndexNum());
  }
}


text:
require('./angular-locale_tzm-latn-ma');
module.exports = 'ngLocale';


text:
using Bridge.Test.NUnit;
using System;

namespace TestCase67
{
    class Optional<T>
    {
        public Optional(T value)
        {
            Value = value;
        }

        public T Value { get; }
    }

    class SubClass
    {
        public class Optional<T>
        {
            public Optional(T value)
            {
                Value = value;
            }

            public T Value { get; }
        }
    }
}

namespace TestCase67.SubNameSpace
{
    class Optional<T>
    {
        public Optional(T value)
        {
            Value = value;
        }

        public T Value { get; }
    }

    class SubClass
    {
        public class Optional<T>
        {
            public Optional(T value)
            {
                Value = value;
            }

            public T Value { get; }
        }
    }
}

namespace Newtonsoft.Json.Tests.Issues
{
    /// <summary>
    /// The test here consists in verifying whether generic types are correctly
    /// serialized in different class and namespaces situations and when
    /// System.Uri is used as generics' specialization.
    /// </summary>
    /// <remarks>
    /// System.Uri should output System and not mscorlib, and class depth
    /// delimiter must be '+' and not '.'.
    /// </remarks>
    [Category("Issues")]
    [TestFixture(TestNameFormat = "#67 - {0}")]
    public class Case67
    {
        /// <summary>
        /// A test object implementing C# generics.
        /// </summary>
        class Optional<T>
        {
            public Optional(T value)
            {
                Value = value;
            }

            public T Value { get; }
        }

        /// <summary>
        /// The test here basically checks if the serialized string has the
        /// same output generated by an analog console application using the
        /// C# version of Newtonsoft.Json.
        /// </summary>
        /// <remarks>
        /// A transcript of Program.cs equivalent to this sequence of tests
        /// that can be used to fetch the expected output from a pure C#
        /// application is commented out at the end of this source file.
        /// </remarks>
        [Test]
        public static void TestTypeGenericSerialize()
        {
            var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects };

            Console.WriteLine("{\"$type\":\"Newtonsoft.Json.Tests.Issues.Case67+Optional`1[[System.Int32, mscorlib]], Newtonsoft.Json.Tests\",\"Value\":1}");
            Console.WriteLine(JsonConvert.SerializeObject(new Optional<int>(1), settings));
            // First, the console application output, then our equivalent.
            Assert.AreEqual(
                "{\"$type\":\"Newtonsoft.Json.Tests.Issues.Case67+Optional`1[[System.Int32, mscorlib]], Newtonsoft.Json.Tests\",\"Value\":1}",
                JsonConvert.SerializeObject(new Optional<int>(1), settings),
                "Simple int. Local object to the test method.");
            Assert.AreEqual(
                "{\"$type\":\"TestCase67.Optional`1[[System.Int32, mscorlib]], Newtonsoft.Json.Tests\",\"Value\":1}",
                JsonConvert.SerializeObject(new TestCase67.Optional<int>(1), settings),
                "Simple int. Root object on a root namespace.");

            // sub classes have a '+' separator between the object depths
            Assert.AreEqual(
                "{\"$type\":\"TestCase67.SubClass+Optional`1[[System.Int32, mscorlib]], Newtonsoft.Json.Tests\",\"Value\":1}",
                JsonConvert.SerializeObject(new TestCase67.SubClass.Optional<int>(1), settings),
                "Simple int. Subclass object on a root namespace.");
            Assert.AreEqual(
                "{\"$type\":\"TestCase67.SubNameSpace.Optional`1[[System.Int32, mscorlib]], Newtonsoft.Json.Tests\",\"Value\":1}",
                JsonConvert.SerializeObject(new TestCase67.SubNameSpace.Optional<int>(1), settings),
                "Simple int. Root object on a sub namespace.");
            Assert.AreEqual(
                "{\"$type\":\"TestCase67.SubNameSpace.SubClass+Optional`1[[System.Int32, mscorlib]], Newtonsoft.Json.Tests\",\"Value\":1}",
                JsonConvert.SerializeObject(new TestCase67.SubNameSpace.SubClass.Optional<int>(1), settings),
                "Simple int. Subclass object on a sub namespace.");

            var myUri = new Uri("http://www.google.com/");
            Assert.AreEqual(
                "{\"$type\":\"Newtonsoft.Json.Tests.Issues.Case67+Optional`1[[System.Uri, System]], Newtonsoft.Json.Tests\",\"Value\":\"http://www.google.com/\"}",
                JsonConvert.SerializeObject(new Optional<Uri>(myUri), settings),
                "System.Uri. Local object to the test method.");
            Assert.AreEqual(
                "{\"$type\":\"TestCase67.Optional`1[[System.Uri, System]], Newtonsoft.Json.Tests\",\"Value\":\"http://www.google.com/\"}",
                JsonConvert.SerializeObject(new TestCase67.Optional<Uri>(myUri), settings),
                "System.Uri. Root object on a root namespace.");

            // sub classes have a '+' separator between the object depths
            Assert.AreEqual(
                "{\"$type\":\"TestCase67.SubClass+Optional`1[[System.Uri, System]], Newtonsoft.Json.Tests\",\"Value\":\"http://www.google.com/\"}",
                JsonConvert.SerializeObject(new TestCase67.SubClass.Optional<Uri>(myUri), settings),
                "System.Uri. Subclass object on a root namespace.");
            Assert.AreEqual(
                "{\"$type\":\"TestCase67.SubNameSpace.Optional`1[[System.Uri, System]], Newtonsoft.Json.Tests\",\"Value\":\"http://www.google.com/\"}",
                JsonConvert.SerializeObject(new TestCase67.SubNameSpace.Optional<Uri>(myUri), settings),
                "System.Uri. Root object on a sub namespace.");
            Assert.AreEqual(
                "{\"$type\":\"TestCase67.SubNameSpace.SubClass+Optional`1[[System.Uri, System]], Newtonsoft.Json.Tests\",\"Value\":\"http://www.google.com/\"}",
                JsonConvert.SerializeObject(new TestCase67.SubNameSpace.SubClass.Optional<Uri>(myUri), settings),
                "System.Uri. Subclass object on a sub namespace.");
        }
    }
}

// For convenience a whole transcript of the actual Program.cs for the Console
// Application equivalent used for output gathering is commented out below.
// The console application project name should be "Newtonsoft.Json.Tests for
// the output to be consistent to the one expected here.
/*

using System;

namespace TestCase67
{
    class Optional<T>
    {
        public Optional(T value)
        {
            Value = value;
        }

        public T Value { get; }
    }

    class SubClass
    {
        public class Optional<T>
        {
            public Optional(T value)
            {
                Value = value;
            }

            public T Value { get; }
        }
    }
}

namespace TestCase67.SubNameSpace
{
    class Optional<T>
    {
        public Optional(T value)
        {
            Value = value;
        }

        public T Value { get; }
    }

    class SubClass
    {
        public class Optional<T>
        {
            public Optional(T value)
            {
                Value = value;
            }

            public T Value { get; }
        }
    }
}

namespace Newtonsoft.Json.Tests.Issues
{
    /// <summary>
    /// The test here consists in verifying whether generic types are correctly
    /// serialized when type name is serialized with the object.
    /// </summary>
    //[Category("Issues")]
    //[TestFixture(TestNameFormat = "#67 - {0}")]
    public class Case67
    {
        /// <summary>
        /// A test object implementing C# generics.
        /// </summary>
        class Optional<T>
        {
            public Optional(T value)
            {
                Value = value;
            }

            public T Value { get; }
        }

        /// <summary>
        /// The test here should basically check if the serialized object has
        /// value on its properties once it is deserialized.
        /// </summary>
        //[Test]
        public static void TestTypeGenericSerialize()
        {
            var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects };

            Console.WriteLine(JsonConvert.SerializeObject(new Optional<int>(1), settings).Replace("\"", "\\\""));
            Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.Optional<int>(1), settings).Replace("\"", "\\\""));
            Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.SubClass.Optional<int>(1), settings).Replace("\"", "\\\""));
            Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.SubNameSpace.Optional<int>(1), settings).Replace("\"", "\\\""));
            Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.SubNameSpace.SubClass.Optional<int>(1), settings).Replace("\"", "\\\""));

            var myUri = new Uri("http://www.google.com/");
            Console.WriteLine(JsonConvert.SerializeObject(new Optional<Uri>(myUri), settings).Replace("\"", "\\\""));
            Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.Optional<Uri>(myUri), settings).Replace("\"", "\\\""));
            Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.SubClass.Optional<Uri>(myUri), settings).Replace("\"", "\\\""));
            Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.SubNameSpace.Optional<Uri>(myUri), settings).Replace("\"", "\\\""));
            Console.WriteLine(JsonConvert.SerializeObject(new TestCase67.SubNameSpace.SubClass.Optional<Uri>(myUri), settings).Replace("\"", "\\\""));
        }
    }
}

namespace Newtonsoft.Json.Tests
{
    /// <summary>
    ///  Console application entry point
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            Newtonsoft.Json.Tests.Issues.Case67.TestTypeGenericSerialize();
        }
    }
}

 */


text:
Noisesoup is a website to post short, public, audio snippets (notes).

Not much of a point to it really. More of a random project to learn web
development.

Still in development - not running anywhere yet - but you are welcome to
take a look at the code and make any suggestions.

##To-Do
* Allow background to be scrolled