text:
// .NAME vtkImageMathematics - Add, subtract, multiply, divide, invert, sin,
// cos, exp, log.
// .SECTION Description
// vtkImageMathematics implements basic mathematic operations SetOperation is
// used to select the filters behavior.  The filter can take two or one
// input.

#ifndef __vtkImageMathematics_h
#define __vtkImageMathematics_h

// Operation options.
#define VTK_ADD                0
#define VTK_SUBTRACT           1
#define VTK_MULTIPLY           2
#define VTK_DIVIDE             3
#define VTK_INVERT             4
#define VTK_SIN                5
#define VTK_COS                6
#define VTK_EXP                7
#define VTK_LOG                8
#define VTK_ABS                9
#define VTK_SQR               10
#define VTK_SQRT              11
#define VTK_MIN               12
#define VTK_MAX               13
#define VTK_ATAN              14
#define VTK_ATAN2             15
#define VTK_MULTIPLYBYK       16
#define VTK_ADDC              17
#define VTK_CONJUGATE         18
#define VTK_COMPLEX_MULTIPLY  19
#define VTK_REPLACECBYK       20

#include "vtkImagingMathModule.h" // For export macro
#include "vtkThreadedImageAlgorithm.h"

class VTKIMAGINGMATH_EXPORT vtkImageMathematics : public vtkThreadedImageAlgorithm
{
public:
  static vtkImageMathematics *New();
  vtkTypeMacro(vtkImageMathematics,vtkThreadedImageAlgorithm);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description:
  // Set/Get the Operation to perform.
  vtkSetMacro(Operation,int);
  vtkGetMacro(Operation,int);

  // Description:
  // Set each pixel in the output image to the sum of the corresponding pixels
  // in Input1 and Input2.
  void SetOperationToAdd() {this->SetOperation(VTK_ADD);};

  // Description:
  // Set each pixel in the output image to the difference of the corresponding pixels
  // in Input1 and Input2 (output = Input1 - Input2).
  void SetOperationToSubtract() {this->SetOperation(VTK_SUBTRACT);};

  // Description:
  // Set each pixel in the output image to the product of the corresponding pixels
  // in Input1 and Input2.
  void SetOperationToMultiply() {this->SetOperation(VTK_MULTIPLY);};

  // Description:
  // Set each pixel in the output image to the quotient of the corresponding pixels
  // in Input1 and Input2 (Output = Input1 / Input2).
  void SetOperationToDivide() {this->SetOperation(VTK_DIVIDE);};

  void SetOperationToConjugate() {this->SetOperation(VTK_CONJUGATE);};

  void SetOperationToComplexMultiply()
    {this->SetOperation(VTK_COMPLEX_MULTIPLY);};

  // Description:
  // Set each pixel in the output image to 1 over the corresponding pixel
  // in Input1 and Input2 (output = 1 / Input1). Input2 is not used.
  void SetOperationToInvert() {this->SetOperation(VTK_INVERT);};

  // Description:
  // Set each pixel in the output image to the sine of the corresponding pixel
  // in Input1. Input2 is not used.
  void SetOperationToSin() {this->SetOperation(VTK_SIN);};

  // Description:
  // Set each pixel in the output image to the cosine of the corresponding pixel
  // in Input1. Input2 is not used.
  void SetOperationToCos() {this->SetOperation(VTK_COS);};

  // Description:
  // Set each pixel in the output image to the exponential of the corresponding pixel
  // in Input1. Input2 is not used.
  void SetOperationToExp() {this->SetOperation(VTK_EXP);};

  // Description:
  // Set each pixel in the output image to the log of the corresponding pixel
  // in Input1. Input2 is not used.
  void SetOperationToLog() {this->SetOperation(VTK_LOG);};

  // Description:
  // Set each pixel in the output image to the absolute value of the corresponding pixel
  // in Input1. Input2 is not used.
  void SetOperationToAbsoluteValue() {this->SetOperation(VTK_ABS);};

  // Description:
  // Set each pixel in the output image to the square of the corresponding pixel
  // in Input1. Input2 is not used.
  void SetOperationToSquare() {this->SetOperation(VTK_SQR);};

  // Description:
  // Set each pixel in the output image to the square root of the corresponding pixel
  // in Input1. Input2 is not used.
  void SetOperationToSquareRoot() {this->SetOperation(VTK_SQRT);};

  // Description:
  // Set each pixel in the output image to the minimum of the corresponding pixels
  // in Input1 and Input2. (Output = min(Input1, Input2))
  void SetOperationToMin() {this->SetOperation(VTK_MIN);};

  // Description:
  // Set each pixel in the output image to the maximum of the corresponding pixels
  // in Input1 and Input2. (Output = max(Input1, Input2))
  void SetOperationToMax() {this->SetOperation(VTK_MAX);};

  // Description:
  // Set each pixel in the output image to the arctangent of the corresponding pixel
  // in Input1. Input2 is not used.
  void SetOperationToATAN() {this->SetOperation(VTK_ATAN);};

  void SetOperationToATAN2() {this->SetOperation(VTK_ATAN2);};

  // Description:
  // Set each pixel in the output image to the product of ConstantK with the
  // corresponding pixel in Input1. Input2 is not used.
  void SetOperationToMultiplyByK() {this->SetOperation(VTK_MULTIPLYBYK);};

  // Description:
  // Set each pixel in the output image to the product of ConstantC with the
  // corresponding pixel in Input1. Input2 is not used.
  void SetOperationToAddConstant() {this->SetOperation(VTK_ADDC);};

  // Description:
  // Find every pixel in Input1 that equals ConstantC and set the corresponding pixels
  // in the Output to ConstantK. Input2 is not used.
  void SetOperationToReplaceCByK() {this->SetOperation(VTK_REPLACECBYK);};

  // Description:
  // A constant used by some operations (typically multiplicative). Default is 1.
  vtkSetMacro(ConstantK,double);
  vtkGetMacro(ConstantK,double);

  // Description:
  // A constant used by some operations (typically additive). Default is 0.
  vtkSetMacro(ConstantC,double);
  vtkGetMacro(ConstantC,double);

  // Description:
  // How to handle divide by zero. Default is 0.
  vtkSetMacro(DivideByZeroToC,int);
  vtkGetMacro(DivideByZeroToC,int);
  vtkBooleanMacro(DivideByZeroToC,int);

  // Description:
  // Set the two inputs to this filter. For some operations, the second input
  // is not used.
  virtual void SetInput1Data(vtkDataObject *in) { this->SetInputData(0,in); }
  virtual void SetInput2Data(vtkDataObject *in) { this->SetInputData(1,in); }

protected:
  vtkImageMathematics();
  ~vtkImageMathematics() {}

  int Operation;
  double ConstantK;
  double ConstantC;
  int DivideByZeroToC;

  virtual int RequestInformation (vtkInformation *,
                                  vtkInformationVector **,
                                  vtkInformationVector *);

  virtual void ThreadedRequestData(vtkInformation *request,
                                   vtkInformationVector **inputVector,
                                   vtkInformationVector *outputVector,
                                   vtkImageData ***inData,
                                   vtkImageData **outData,
                                   int extent[6], int threadId);

  virtual int FillInputPortInformation(int port, vtkInformation* info);

private:
  vtkImageMathematics(const vtkImageMathematics&);  // Not implemented.
  void operator=(const vtkImageMathematics&);  // Not implemented.
};

#endif


text:
<?php
namespace ProductBundle\Controller;
use ProductBundle\Entity\Product;
use ProductBundle\Entity\ImageProduct;
use ProductBundle\Entity\ProductLog;
use UserBundle\Entity\User;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use ProductBundle\Form\ProductType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
/**
 * Product controller.
 *
 * @Route("product")
 */
class ProductController extends Controller
{
    private $ImageProduct;
    public function __construct()
    {
        $this->ImageProduct = new ImageProduct();
    }
    /**
     * Lists all product entities.
     *
     * @Route("/", name="product_index")

     */
    public function indexAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $products = $em->getRepository('ProductBundle:Product')->getAllProducts();
        $categories = $em->getRepository('CategoryBundle:Category')->getAllRootCat();
        $sub_categories = $em->getRepository('CategoryBundle:Category')->getAllSubCat();
        $providers = $em->getRepository('ProviderBundle:Provider')->findBy(array('deleted_at' => NULL));

        return $this->render('product/index.html.twig', array(
            'products' => $products,
            'categories' => $categories,
            'sub_categories' => $sub_categories,
            'providers' => $providers,
        ));
    }
    /**
     * Creates a new product entity.
     *
     * @Route("/new", name="product_new", options={"expose"=true})
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request){
        $em = $this->getDoctrine()->getManager();
        $product = new Product();
        $productlog = new ProductLog();
        $form = $this->createForm('ProductBundle\Form\ProductType', $product);
        $form->handleRequest($request);
        $categories = $em->getRepository('CategoryBundle:Category')->getAllRootCat();

        $em = $this->getDoctrine()->getEntityManager();
        if ($form->isSubmitted() && $form->isValid()){
            //cat and subcat selected
            $cat_id=$request->request->get('categories');
            $sub_cat_id= $request->request->get('s_categories');
            //add product to cat selected
            $Category=$em->getRepository('CategoryBundle:Category')->findById( array($cat_id, $sub_cat_id));
            //get code of cat and subcat selected
            if(!empty($cat_id)){
              $query=$em->createQuery('SELECT c.code FROM CategoryBundle:Category c
              WHERE c.id = '.$cat_id);
              $catCode = $query->getSingleScalarResult();
              //var_dump($catCode); die();
              $getcatcode = $catCode;
            }

            if(!empty($sub_cat_id)){
              $query1=$em->createQuery('SELECT c.code FROM CategoryBundle:Category c
                WHERE c.id = '.$sub_cat_id);
              $subcatCode = $query1->getSingleScalarResult();
              if(!empty($subcatCode)){
                $getsubcatCode = $subcatCode;
              }else{
                $getsubcatCode = "000";
              }
            }else{
              $getsubcatCode = "000";
            }
            $countryCode="6";
            $prodQuery = $em->createQuery("SELECT COUNT(p) FROM
                            ProductBundle:Product p");
            $productCount = $prodQuery->getSingleScalarResult();
            $productCount +=1;
            if($productCount < 10){
              $prodCode = '000000'.$productCount;
            }elseif($productCount < 100){
              $prodCode = '00000'.$productCount;
            }elseif($productCount < 1000){
              $prodCode = '0000'.$productCount;
            }elseif($productCount < 10000){
              $prodCode = '000'.$productCount;
            }elseif($productCount < 100000){
              $prodCode = '00'.$productCount;
            }elseif($productCount < 1000000){
              $prodCode = '0'.$productCount;
            }else{
              $prodCode = $productCount;
            }
            $serialNumber=$prodCode;

            $files = $product->getImages();

            $images = array();
            if($files != null) {
                $key = 0;
                foreach ($files as $file){
                    $fileName = $file->getClientOriginalName();
                    $file->move($this->getParameter('images_directory'),$fileName);
                    $imageProduct  = new ImageProduct();
                    $imageProduct->setProduct($product);
                    $imageProduct->setPath($fileName);
                    $images[] = $imageProduct;
                }
            }
            if($getcatcode != null ){
              $productCodeBar=$countryCode.$getcatcode.$getsubcatCode.$serialNumber;
            }else{
              $productCodeBar=$countryCode.'00'.$getsubcatCode.$serialNumber;
            }

            $product->setCodeBar($productCodeBar);
            $product->setImages($images);
            $product->setCategories($Category);

            $productlog->setProduct($product);
            $productlog->setUser($this->getUser());
            $productlog->setAction("Add");

            $productlog->setUnitPrice($product->getUnitPrice());
            $productlog->setWholesalePrice($product->getWholesalePrice());
            $productlog->setSpecialPrice($product->getSpecialPrice());
            $productlog->setInternetPrice($product->getInternetPrice());

            $em->persist($product);
            $em->persist($productlog);
            $em->flush();
            $url = $this->generateUrl('product_show', [ 'id' => $product->getId() ]);
            $this->get('session')->getFlashBag()->add(
                'addProduct',
                array(
                    'alert' => 'success',
                    'title' => 'success.title',
                    'message' => 'product.add.flush.success',
                    'url' => $url
                )
            );
            return $this->redirectToRoute('product_index');
        }
        return $this->render('product/new.html.twig', array(
            'product' => $product,
            'categories' => $categories,
            'form' => $form->createView(),

        ));
    }
    /**
     * Finds and displays a product entity.
     *
     * @Route("/details/{id}", name="product_show" ,options={"expose"=true})
     * @Method("GET")
     */
    public function showAction(Product $product)
    {
      $em = $this->getDoctrine()->getEntityManager();
      $priceslog = $em->getRepository('ProductBundle:Product')->getPricesLog($product->getId());
      //echo '<pre>' ; print_r($priceslog); echo '</pre>' ; die();
      return $this->render('product/show.html.twig', array(
          'id'      => $product->getId(),
          'product' => $product,
          'priceslog' => $priceslog,
      ));
    }

    /**
     * Displays a form to edit an existing product entity.
     *
     * @Route("/{id}/edit", name="product_edit", options={"expose"=true})
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, Product $product)
    {
        $productlog = new ProductLog();
        $em = $this->getDoctrine()->getEntityManager();
        $categories = $em->getRepository('CategoryBundle:Category')->getAllRootCat();

        $deleteForm = $this->createDeleteForm($product);
        $editForm = $this->createForm('ProductBundle\Form\ProductType', $product);
        $editForm->handleRequest($request);
        $prod_cat=array();
        foreach ($product->getCategories() as $cat) {
            $prod_cat[]=$cat->getId();
        }
        if(!empty($prod_cat[1])){
          $sub_cat_selected=$prod_cat[1];
        }else{
          $sub_cat_selected=0;
        }

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $cat_id=$request->request->get('categories');
            $sub_cat_id= $request->request->get('s_categories');
            $Category=$em->getRepository('CategoryBundle:Category')->findById( array($cat_id, $sub_cat_id));

            if(!empty($cat_id)){
              $query=$em->createQuery('SELECT c.code FROM CategoryBundle:Category c
              WHERE c.id = '.$cat_id);
              $catCode = $query->getSingleScalarResult();
              $getcatcode = $catCode;
            }

            if(!empty($sub_cat_id)){
              $query1=$em->createQuery('SELECT c.code FROM CategoryBundle:Category c
                WHERE c.id = '.$sub_cat_id);
              $subcatCode = $query1->getSingleScalarResult();
              if($subcatCode != null){
                $getsubcatCode = $subcatCode;
              }else{
                $getsubcatCode = "000";
              }
            }else{
              $getsubcatCode = "000";
            }
            //var_dump($subcatCode); die();
            $countryCode="6";

            $prodCodeQuery = $em->createQuery("SELECT p.codeBar FROM
                            ProductBundle:Product p where p.id =".$product->getId());
            $productCode = $prodCodeQuery->getSingleScalarResult();
            if(empty($productCode)){
              $productCount = $product->getId();
              if($productCount < 10){
                $prodCode = '000000'.$productCount;
              }elseif($productCount < 100){
                $prodCode = '00000'.$productCount;
              }elseif($productCount < 1000){
                $prodCode = '0000'.$productCount;
              }elseif($productCount < 10000){
                $prodCode = '000'.$productCount;
              }elseif($productCount < 100000){
                $prodCode = '00'.$productCount;
              }elseif($productCount < 1000000){
                $prodCode = '0'.$productCount;
              }else{
                $prodCode = $productCount;
              }
            }else{
              $prodCode = substr($productCode, -7);
            }

            $serialNumber=$prodCode;

            $files = $product->getImages();
            $images = array();
            if($files != null) {
                $key = 0;
                foreach ($files as $file){
                    $fileName = $file->getClientOriginalName();
                    $file->move($this->getParameter('images_directory'),$fileName);
                    $imageProduct  = new ImageProduct();
                    $imageProduct->setProduct($product);
                    $imageProduct->setPath($fileName);
                    $images[] = $imageProduct;
                }
            }
            if($getcatcode != null ){
              $productCodeBar=$countryCode.$getcatcode.$getsubcatCode.$serialNumber;
            }else{
              $productCodeBar=$countryCode.'00'.$getsubcatCode.$serialNumber;
            }
            $product->setCodeBar($productCodeBar);
            $product->setImages($images);
            $product->setCategories($Category);

            $productlog->setProduct($product);
            $productlog->setUser($this->getUser());
            $productlog->setAction("Edit");

            $productlog->setUnitPrice($product->getUnitPrice());
            $productlog->setWholesalePrice($product->getWholesalePrice());
            $productlog->setSpecialPrice($product->getSpecialPrice());
            $productlog->setInternetPrice($product->getInternetPrice());

            $em->persist($product);
            $em->persist($productlog);
            $em->flush();
            $url = $this->generateUrl('product_show', [ 'id' => $product->getId() ]);
            $this->get('session')->getFlashBag()->add(
                'editProduct',
                array(
                    'alert' => 'success',
                    'title' => 'success.title',
                    'message' => 'product.edit.flush.success',
                    'url' => $url
                )
            );
            return $this->redirectToRoute('product_index');

        }
    		$prd = null;
            if($prod_cat && $prod_cat[0]){
    			$prd = $prod_cat[0];
    		}

        return $this->render('product/edit.html.twig', array(
            'product' => $product,
            'categories' => $categories,
            //'s_categories' => $categories,
            'cat_selected' => $prd,
            'sub_cat_selected' => $sub_cat_selected ,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a product entity.
     *
     * @Route("/{id}/desactivate", options={"expose"=true}, name="product_desactivate")
     * @Method("PUT")
     */
    public function desactivateAction(Request $request, Product $product)
    {
        $productlog = new ProductLog();
        $em = $this->getDoctrine()->getEntityManager();

        $productlog->setProduct($product);
        $productlog->setUser($this->getUser());
        $productlog->setAction("Desactivate");
        $productlog->setDeletedAt(new \DateTime());
        $em->persist($productlog);
        $this->getDoctrine()->getManager()->flush();
        return $this->redirectToRoute('product_index');
    }

    /**
     * Deletes a product entity.
     *
     * @Route("/{id}/delete", options={"expose"=true}, name="product_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, Product $product)
    {
        $em = $this->getDoctrine()->getManager();
        $em->remove($product);
        $em->flush();
        return $this->redirectToRoute('product_desactiveted');
    }

    /**
     * Finds and displays a removed product entity.
     *
     * @Route("/trash", name="product_desactiveted" ,options={"expose"=true})
     * @Method("GET")
     */
    public function trashAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $products = $em->getRepository('ProductBundle:Product')->getAllTrashedProducts();
        return $this->render('product/trash.html.twig', array(
            'products' => $products,
        ));
    }

    /**
     * Deletes a product entity.
     *
     * @Route("/{id}/revert", options={"expose"=true}, name="product_revert")
     * @Method("PUT")
     */
    public function revertAction(Request $request, Product $product)
    {
        $productlog = new ProductLog();
        $em = $this->getDoctrine()->getEntityManager();

        $productlog->setProduct($product);
        $productlog->setUser($this->getUser());
        $productlog->setAction("revert");
        $productlog->setDeletedAt(NULL);
        $em->persist($productlog);
        $this->getDoctrine()->getManager()->flush();
        return $this->redirectToRoute('product_index');
    }

    /**
     * Creates a form to delete a product entity.
     *
     * @param Product $product The product entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(Product $product)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('product_delete', array('id' => $product->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }

    /**
     * Lists searched entities.
     *
     * @Route("/cat/{category_id}", name="filter-by-cat" ,options={"expose"=true})
     * @Method("GET")
     */
    public function FilterByCatAction($category_id)
    {
            $em = $this->getDoctrine()->getManager();
            $categories = $em->getRepository('CategoryBundle:Category')->findAll();
            $category = $this->getDoctrine()
            ->getRepository('CategoryBundle:Category')
            ->find($category_id);
            $products = $category->getProduct();
                return $this->render('product/results.html.twig', array(
                'products' => $products,
            ));
    }

    /**
     * Lists searched entities.
     *
     * @Route("/subcat/{sub_category_id}", name="filter-by-sub-cat" ,options={"expose"=true})
     * @Method("GET")
     */
    public function FilterBySubCatAction($sub_category_id)
    {
        $em = $this->getDoctrine()->getManager();
        $categories = $em->getRepository('CategoryBundle:Category')->getAllSubCat();
        $sub_category = $this->getDoctrine()
        ->getRepository('CategoryBundle:Category')
        ->find($sub_category_id);
        $products = $sub_category->getProduct();
        return $this->render('product/results.html.twig', array(
            'products' => $products,
        ));
    }

    /**
     * Lists searched entities.
     *
     * @Route("/prov/{provider_id}", name="filter-by-prov" ,options={"expose"=true})
     * @Method("GET")
     */
    public function FilterByProvAction($provider_id)
    {
        $em = $this->getDoctrine()->getManager();
        $categories = $em->getRepository('CategoryBundle:Category')->findAll();
        $providers = $em->getRepository('ProviderBundle:Provider')->findAll();
        $provider = $this->getDoctrine()
        ->getRepository('ProviderBundle:Provider')
        ->find($provider_id);
        $products = $provider->getProduct();
        return $this->render('product/results.html.twig', array(
              'products' => $products,
        ));

    }

    /**
     * @Route("/new/subcategories", name="ajax_subcategories", options={"expose"=true})
     * @Method("GET")
     */
    public function ajaxSubCategoriesAction(Request $request)
    {
      $id = $request->get('id');
      $em = $this->getDoctrine()->getManager();
      $entities = $em->getRepository('CategoryBundle:Category')->findBy(array('parent' => $id));
      $output = array();
        foreach ($entities as $member) {
          $output[] = array(
              'id' => $member->getId(),
              'name' => $member->getName(),
          );
        }
      $response = new Response();
      $response->headers->set('Content-Type', 'application/json');
      $response->setContent(json_encode($output));
      return $response;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<template name="messageListTemplate">

      {{> loginButtons}}

      {{#each channel in channels}}

{{channel.name}}

      {{/each}}

      {{#each message in messages}}

{{message.user}} said: {{message.message}} (@{{message.time}})

      {{/each}}

</template>


text:
function centroids = kMeansInitCentroids(X, K)
%KMEANSINITCENTROIDS This function initializes K centroids that are to be
%used in K-Means on the dataset X
%   centroids = KMEANSINITCENTROIDS(X, K) returns K initial centroids to be
%   used with the K-Means on the dataset X
%

% You should return this values correctly
centroids = zeros(K, size(X, 2));

% ====================== YOUR CODE HERE ======================
% Instructions: You should set centroids to randomly chosen examples from
%               the dataset X
%
randidx = randperm(size(X, 1));
centroids = X(randidx(1:K), :);
% =============================================================

end


text:
scala-js-react
============
[![Build Status](https://travis-ci.org/xored/scala-js-react.svg?branch=master)](https://travis-ci.org/xored/scala-js-react)
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/xored/scala-js-react?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

Scala-js-react provides nice statically typed interface to [Facebook's React](http://facebook.github.io/react/).

# Quickstart

For detailed sbt configuration please refer to [scala.js documentation](http://www.scala-js.org/doc/).

`build.sbt`
```scala
enablePlugins(ScalaJSPlugin)

scalaVersion := "2.11.5"

libraryDependencies ++= Seq(
  "com.xored.scalajs" %%% "scalajs-react" % "0.3.3",
  compilerPlugin("org.scalamacros" % "paradise" % "2.0.1" cross CrossVersion.full)
)
```

`project/plugins.sbt`
```scala
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.0")
```

`project/build.properties`
```
sbt.version=0.13.7
```

# Features

`scala-js-react` aims to support all [Facebook React](http://facebook.github.io/react/) features.

## `scalax` annotation

While [Facebook React](http://facebook.github.io/react/) uses JSX, `scala-js-react` offers `scalax` support.
Basically `scalax` allows to use Scala XML literals to build React DOM.

React DOM allows to put objects into attribute values, while `scala.xml.UnprefixedAttribute` constructor takes `Seq[Node]` or `String`.
So we have to transform methods before it typechecks. That is why `scalax` `scalax` uses macro annotations and requires macro paradise compiler plugin.

```scala
object HelloMessage extends TypedReactSpec {

  case class State()
  case class Props(name: String)

  def getInitialState(self: This) = State()

  @scalax
  def render(self: This) = {
    <div>Hello {self.props.name}</div>
  }
}

React.renderComponent(
  HelloMessage(HelloMessage.Props(name = "John")),
  mountNode
)
```

## Internal State

A component can maintain internal state.

```scala
object Timer extends TypedReactSpec with TypedEventListeners {

  case class Props()
  case class State(secondsElapsed: Int, interval: Option[Int])

  def getInitialState(self: This) = State(secondsElapsed = 0, interval = None)

  implicit class Closure(self: This) {
    import self._

    val tick = () => {
      setState(state.copy(secondsElapsed = state.secondsElapsed + 1))
    }
  }

  override def componentDidMount(self: This) = {
    val interval = window.setInterval(self.tick, 1000)

    self.setState(self.state.copy(interval = Some(interval)))
  }

  override def componentWillUnmount(self: This) = {
    self.state.interval.foreach(window.clearInterval)
  }

  @scalax
  def render(self: This) = {
    <div>Seconds Elapsed: {self.state.secondsElapsed}</div>
  }
}
```

## Typed listeners and closures

```scala
object Say extends TypedReactSpec with TypedEventListeners {

  case class Props()
  case class State(text: String)

  implicit class Closure(self: This) {
    import self._

    val onChange = input.onChange(e => {
      setState(state.copy(text = e.target.value))
    })

    val onClick = button.onClick(e => {
      alert(state.text)
    })
  }

  def getInitialState(self: This) = State(text = "")

  @scalax
  def render(self: This) = {
    <div>
      <input type="text" value={self.state.text} onChange={self.onChange}></input>
      <button type="text" onClick={self.onClick}>Say</button>
    </div>
  }
}
```

# How to run examples

    $ sbt "project scalajs-react-examples" fastOptJS
    $ open scalajs-react-examples/index.html

# Copyright

Copyright © 2014 Xored Software, Inc.

Licensed under the Apache License, Version 2.0.


text:
import t from 'tcomb'
import { oneLine } from 'common-tags'
import invariant from 'invariant'
import { hasOwnProperty, values } from './Object'

export default function initialize(Model, select) {
	const ModelType = Model.getModelType()

	const isModelInstance = (possibleInstance) => (
		t.Nil.is(possibleInstance) === false &&
		t.Function.is(possibleInstance.getModelType) &&
		ModelType === possibleInstance.getModelType()
	)

	const emptyCollection = Object.freeze({})
	const getCollection = () => select() || emptyCollection

	return {
		create(modelData, ...args) {
			return Model.create(modelData, ...args)
		},
		destroy(modelIdentity) {
			Model.destroy(modelIdentity)
		},
		get(modelIdentity) {
			if (isModelInstance(modelIdentity)) {
				return modelIdentity
			}

			const collection = getCollection()
			if (hasOwnProperty(collection, modelIdentity)) {
				return Model(modelIdentity)
			}
			return null
		},
		has(byValue, byPropertyName) {
			return this.get(byValue, byPropertyName) !== null
		},
		filter(byValue, byPropertyName) {
			const PropertyType = ModelType.meta.props[byPropertyName]

			invariant(PropertyType, oneLine`
				The model %s is missing requested property %s.
			`, Model, byPropertyName)

			invariant(PropertyType.is(byValue), oneLine`
				Value for property %s is expected to be of type %s.
			`, byPropertyName, PropertyType)

			return values(getCollection())
				.filter((item) => item[byPropertyName] === byValue)
				.map((item) => Model(item.id))
		},
		find(predicate) {
			const found = values(getCollection()).find((item) => predicate(Model(item.id)))
			if (found === undefined) {
				return null
			}
			return Model(found.id)
		},
		getAll() {
			return Object.keys(getCollection()).map((identity) => Model(identity))
		},
		attachCountProperty(target, propertyName) {
			Reflect.defineProperty(target, propertyName, {
				get: () => Object.keys(getCollection()).length,
			})
		},
	}
}


text:
/*
 * MokituSolver - PPC
 *
 * Alexis LE GOADEC
 * M1 Informatique - DECIM
 *
 */

#ifndef TEXTENTRYWORD_HH_
#define TEXTENTRYWORD_HH_

#include <wx/wx.h>

namespace MokituSolver { namespace view {

class TextEntryWord : public wxTextCtrl {

protected:

	/**
	 * Coordonnée.
	 */
	int _x;

	/**
	 * Coordonnée.
	 */
	int _y;

public:

	/**
	 * Constructeur.
	 */
	TextEntryWord(wxFrame& wxf, int x, int y);

	std::string lireMot() const;

};

}}

#endif /* TEXTENTRYWORD_HH_ */


text:
class CUIOptionsItem;

class CUIOptionsManager{
	friend class CUIOptionsItem;
public:
	CUIOptionsManager();

	void SeveBackupValues(const char* group);
	void SetCurrentValues(const char* group);
	void SaveValues(const char* group);
	bool IsGroupChanged(const char* group);
	void UndoGroup(const char* group);

	void OptionsPostAccept();
	void DoVidRestart();
	void DoSndRestart();

	void SendMessage2Group(const char* group, const char* message);

protected:
	void RegisterItem(CUIOptionsItem* item, const char* group);
	void UnRegisterGroup(const char* group);
	void UnRegisterItem(CUIOptionsItem* item);

	typedef	xr_string									group_name;
	typedef xr_vector<CUIOptionsItem*>					items_list;
    typedef xr_map<group_name, items_list>				groups;
	typedef xr_map<group_name, items_list>::iterator	groups_it;

	groups	m_groups;

	bool	m_b_vid_restart;
	bool	m_b_snd_restart;
};


text:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Microsoft.Xbox.Services.UserStatistics
{
    public class UserStatisticsService
    {

        //public event EventHandler<StatisticChangeEventArgs> StatisticChanged;

        public Task<UserStatisticsResult> GetSingleUserStatisticsAsync(string xboxUserId, string serviceConfigurationId, string[] statisticNames)
        {
            throw new NotImplementedException();
        }

        public Task<UserStatisticsResult> GetSingleUserStatisticsAsync(string xboxUserId, string serviceConfigurationId, string statisticName)
        {
            throw new NotImplementedException();
        }

        public Task<global::System.Collections.ObjectModel.ReadOnlyCollection<UserStatisticsResult>> GetMultipleUserStatisticsAsync(string[] xboxUserIds, string serviceConfigurationId, string[] statisticNames)
        {
            throw new NotImplementedException();
        }

        public Task<global::System.Collections.ObjectModel.ReadOnlyCollection<UserStatisticsResult>> GetMultipleUserStatisticsForMultipleServiceConfigurationsAsync(string[] xboxUserIds, Microsoft.Xbox.Services.UserStatistics.RequestedStatistics[] requestedServiceConfigurationStatisticsCollection)
        {
            throw new NotImplementedException();
        }

        public StatisticChangeSubscription SubscribeToStatisticChange(string xboxUserId, string serviceConfigurationId, string statisticName)
        {
            throw new NotImplementedException();
        }

        public void UnsubscribeFromStatisticChange(StatisticChangeSubscription subscription)
        {
            throw new NotImplementedException();
        }

    }
}


text:
🚿 Shower Thoughts on your Command Line 🖥. Data pulled from Reddit's API, specifically [/r/showerthoughts](http://reddit.com/r/showerthoughts).

![screenshot-cli](https://cloud.githubusercontent.com/assets/4316355/15307867/2bfb459a-1ba5-11e6-8c28-31bb4a4c6e7e.jpg)

## Installation & Usage

1. Make sure you have [Node and NPM](https://nodejs.org/) installed.

1. Install the package:
    ```bash
    $ npm install -g showerthoughts-cli
    ```

1. Run the command:
    ```bash
   $ showerthoughts
   ```

Enjoy!

Be sure to also check out the [web version](https://github.com/drehimself/showerthoughts).


text:
// @todo: remove the following line when part imports has been removed from this file
///<reference types="@sanity/types/parts" />

import classNames from 'classnames'
import styles from 'part:@sanity/components/buttons/default-style'
import Spinner from 'part:@sanity/components/loading/spinner'
import React from 'react'
import {ButtonComponent, ButtonProps} from './types'

interface ButtonComponentOpts {
  displayName: string
  defaultProps?: Record<string, unknown>
}

export interface ButtonState {
  focusSetFromOutside: boolean
}

export default function createButtonLike(
  as: ButtonComponent | 'button' | 'a',
  {displayName, defaultProps = {}}: ButtonComponentOpts
) {
  const Component = as as ButtonComponent

  // @todo: refactor to functional component
  return class ButtonLike extends React.Component<ButtonProps, ButtonState> {
    static displayName =
      displayName ||
      `ButtonLike(${
        typeof Component === 'string' ? Component : Component.displayName || Component.name
      })`

    static defaultProps = defaultProps

    _element: HTMLButtonElement | null = null

    state = {
      focusSetFromOutside: false,
    }

    focus() {
      if (this._element) {
        this.setState({focusSetFromOutside: true})
        this._element.focus()
      }
    }

    setRootElement = (el: HTMLButtonElement | null) => {
      this._element = el
    }

    handleBlur = (event: React.FocusEvent<HTMLButtonElement>) => {
      if (this.props.onBlur) {
        this.props.onBlur(event)
      }
    }

    handleInnerBlur = () => {
      this.setState({focusSetFromOutside: false})
    }

    // eslint-disable-next-line complexity
    render() {
      const {
        kind,
        inverted,
        color,
        icon: Icon,
        iconStatus,
        loading,
        className: classNameProp,
        children,
        disabled,
        padding = 'medium',
        bleed,
        selected,
        size,
        tone,
        ...restProps
      } = this.props

      const className = classNames(
        classNameProp,
        styles.root,
        kind && styles[kind],
        styles[`padding_${padding}`],
        inverted && styles.inverted,
        color && styles[`color__${color}`],
        size && styles[`size__${size}`],
        bleed && styles.bleed,
        disabled && styles.disabled,
        selected && styles.selected,
        loading && styles.loading
      )

      return (
        <Component
          {...restProps}
          className={className}
          data-icon-status={iconStatus}
          data-tone={tone}
          disabled={disabled || loading}
          ref={this.setRootElement}
          tabIndex={0}
          onBlur={this.handleBlur}
        >
          {/*
            To avoid visually annoying "tab-focus-styling" when clicking,
            we catch the focus styling with tabIndex -1.
            However, to avoid onBlur being called on an focused button (when focues from outside),
            we need to check that the focus is not set from outside. (with .focus() )
          */}

              {loading && (

                  <Spinner inline />

              )}

              {Icon && (

                  <Icon />
                  {iconStatus && }

              )}

              {children && {children}}

        </Component>
      )
    }
  }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: sz
 * Date: 02.02.16
 * Time: 11:31
 */

namespace backend\models\search;

use common\models\Lang;
use yii\data\ActiveDataProvider;

class LangSearch extends Lang
{

    public function rules(){
        return [
            [['name', 'default', 'created_at', 'updated_at'], 'safe'],
        ];
    }

    public function search($params = null)
    {
        $query = self::find();
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere(['LIKE', 'lang.name', $this->name]);
        $query->andFilterWhere(
            [
                'FROM_UNIXTIME(created_at, "%d.%m.%Y")' => $this->created_at,
                'FROM_UNIXTIME(updated_at, "%d.%m.%Y")' => $this->updated_at
            ]
        );

        return $dataProvider;
    }

    public function attributeLabels()
    {
        return array_merge(parent::attributeLabels(), [
                'name' => 'Название',
            ]
        );
    }
}


text:
namespace WebAPI.Controllers
{
    using MovieDb.Data;
    using System.Linq;
    using System.Web.Http;
    using System.Web.Http.Cors;
    using SqlLiteData.Models;
    using System.Collections.Generic;
    using Models.Actors;
    using Models.Movies;
    using PostgreData.Models;
    using Models.Cinema;
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class CinemaController : ApiController
    {
        private IRepository<Cinema> cinemas;
        private IRepository<CinemaCity> cities;
        public CinemaController(IRepository<Cinema> cinemas, IRepository<CinemaCity> cities)

        {
            this.cinemas = cinemas;
            this.cities = cities;
        }

        [HttpGet]
        public IHttpActionResult All()
        {
            var cinemas = this.cinemas.All.ToList().Select(x=>x.Name);

            return this.Ok(cinemas);
        }

        [HttpGet]
        public IHttpActionResult AllCinemasInCIty(string id)
        {
            var name = id;
            var cinemas = this.cities.All.Where(x => x.Name == name).SelectMany(x => x.Cinemas).Select(z => z.Name).ToList();

            return this.Ok(cinemas);
        }

        [HttpPost]
        public IHttpActionResult AddCinema(CinemaToAddModel cinema)
        {
            var collectionOfCities = new List<CinemaCity>();
            foreach (var city in cinema.CinemaCities)
            {
                var alreadyExists = this.cities.All.Where(x => x.Name == city.CityName).FirstOrDefault();
                if (alreadyExists != null)
                {
                    collectionOfCities.Add(alreadyExists);
                    continue;
                }
                else
                {
                    try
                    {   var cityToAdd = new CinemaCity() { Name = city.CityName };
                        this.cities.Add(cityToAdd);
                        this.cities.SaveChanges();
                        collectionOfCities.Add(cityToAdd);
                    }
                    catch
                    {
                        return this.BadRequest("Ups couldn`t save Cinema cities something went wrong");
                    }

                }
            }

            var alreadyExistsCinema = this.cinemas.All.Where(x => x.Name == cinema.Name).FirstOrDefault();
            if (alreadyExistsCinema != null)
            {
                return this.BadRequest("Cinema already exists but cities are added if not existing");
            }
            else
            {
                var cinemaNew = new Cinema()
                {
                    Name = cinema.Name
                };

                foreach (var cityToAdd in collectionOfCities)
                {
                    cinemaNew.Cities.Add(cityToAdd);
                }
                try
                {
                    this.cinemas.Add(cinemaNew);
                    this.cinemas.SaveChanges();
                    return this.Ok("Cinema added successfully !");
                }
                catch
                {
                    return this.BadRequest("Ups couldn`t save Cinema cities something went wrong");
                }
            }
        }

        [HttpPost]
        public IHttpActionResult Delete(CinemaToDeleteModel cinema)
        {
            var cinemaToDel = this.cinemas.All.Where(x => x.Name == cinema.CinemaName).FirstOrDefault();
            if (cinemaToDel == null)
            {
                return this.BadRequest("No such cinema");
            }
            try
            {
                this.cinemas.Delete(cinemaToDel);
                this.cinemas.SaveChanges();
            }
            catch
            {
                return this.BadRequest("Ups something went wrong");
            }

            return this.Ok("Cinema Deleted successfully");

        }

        [HttpGet]
        public IHttpActionResult GetAllCitiesForCinema(string id)
        {
            var cinemaName = id;
            var cities = this.cinemas.All.Where(x => x.Name == cinemaName).SelectMany(x => x.Cities).Select(z => z.Name).ToList();

            if (cities == null)
            {
                return this.BadRequest("No such Cinema Name");
            }

            return this.Ok(cities);
        }

        [HttpPost]
        public IHttpActionResult ConnectCinemaToCity(CinemaToCityModel data)
        {
            var cinema = this.cinemas.All.Where(x => x.Name==data.CinemaName).FirstOrDefault();
            var city = this.cities.All.Where(x => x.Name == data.CityName).FirstOrDefault();

            if (cinema == null)
            {
                return this.BadRequest("Cinema doesn`t exist");
            }
            else if (city == null)
            {
                return this.BadRequest("City doesn`t exist");
            }
            else
            {
                //first check if exists connection
                var alreadyExists = cinema.Cities.Select(x => x.Name).Where(y => y==data.CityName).FirstOrDefault();

                if (alreadyExists != null)
                {
                    return this.BadRequest("Already this Cinema is connected to this City");
                }
                else
                {
                    try
                    {
                        cinema.Cities.Add(city);
                        this.cinemas.SaveChanges();
                        return this.Ok("City added successfully to Cinema");
                    }
                    catch
                    {
                        return this.BadRequest("Ups something went wrong coudn`t add Cinema to City");
                    }
                }
            }
        }

    }
}


text:
// ==++==
//
//   Copyright (c) Microsoft Corporation.  All rights reserved.
//
// ==--==

//
// mansign.cs
//

// From https://github.com/Microsoft/referencesource/blob/7de0d30c7c5ef56ab60fee41fcdb50005d24979a/inc/mansign2.cs

using System.Collections;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Xml;
using Microsoft.Win32;

using RSAKeyVaultProvider;

#pragma warning disable IDE0016
#pragma warning disable IDE0017
#pragma warning disable IDE0018
#pragma warning disable IDE0019
#pragma warning disable IDE0029
#pragma warning disable IDE0032
#pragma warning disable IDE0049
#pragma warning disable IDE0060
#pragma warning disable IDE0003
#pragma warning disable IDE0051
#pragma warning disable IDE1006 // Naming Styles

namespace System.Deployment.Internal.CodeSigning
{
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct BLOBHEADER
    {
        internal byte bType;
        internal byte bVersion;
        internal short reserved;
        internal uint aiKeyAlg;
    };

    class ManifestSignedXml2 : SignedXml
    {
        const string Sha256SignatureMethodUri = @"http://www.w3.org/2000/09/xmldsig#rsa-sha256";
        const string Sha256DigestMethod = @"http://www.w3.org/2000/09/xmldsig#sha256";

        internal ManifestSignedXml2()
            : base()
        {
            init();
        }
        internal ManifestSignedXml2(XmlElement elem)
            : base(elem)
        {
            init();
        }
        internal ManifestSignedXml2(XmlDocument document)
            : base(document)
        {
            init();
        }

        void init()
        {
            CryptoConfig.AddAlgorithm(typeof(RSAPKCS1SHA256SignatureDescription),
                               Sha256SignatureMethodUri);

#pragma warning disable SYSLIB0021
            CryptoConfig.AddAlgorithm(typeof(System.Security.Cryptography.SHA256Managed),
                               Sha256DigestMethod);
#pragma warning restore SYSLIB0021
        }
    }

    class SignedCmiManifest2
    {
        readonly XmlDocument m_manifestDom = null;
        readonly bool m_useSha256;

        const string Sha256SignatureMethodUri = @"http://www.w3.org/2000/09/xmldsig#rsa-sha256";
        const string Sha256DigestMethod = @"http://www.w3.org/2000/09/xmldsig#sha256";

        const string wintrustPolicyFlagsRegPath = "Software\\Microsoft\\Windows\\CurrentVersion\\WinTrust\\Trust Providers\\Software Publishing";
        const string wintrustPolicyFlagsRegName = "State";

        SignedCmiManifest2() { }

        internal SignedCmiManifest2(XmlDocument manifestDom, bool useSha256)
        {
            if (manifestDom == null)
            {
                throw new ArgumentNullException("manifestDom");
            }

            m_manifestDom = manifestDom;
            m_useSha256 = useSha256;
        }

        internal void Sign(CmiManifestSigner2 signer)
        {
            Sign(signer, null);
        }

        internal void Sign(CmiManifestSigner2 signer, string timeStampUrl)
        {
            // Signer cannot be null.
            if (signer == null || signer.StrongNameKey == null)
            {
                throw new ArgumentNullException("signer");
            }

            // Remove existing SN signature.
            RemoveExistingSignature(m_manifestDom);

            // Replace public key token in assemblyIdentity if requested.
            if ((signer.Flag & CmiManifestSignerFlag.DontReplacePublicKeyToken) == 0)
            {
                ReplacePublicKeyToken(m_manifestDom, signer.StrongNameKey, m_useSha256);
            }

            // No cert means don't Authenticode sign and timestamp.
            XmlDocument licenseDom = null;
            if (signer.Certificate != null)
            {
                // Yes. We will Authenticode sign, so first insert <publisherIdentity />
                // element, if necessary.
                InsertPublisherIdentity(m_manifestDom, signer.Certificate);

                // Now create the license DOM, and then sign it.
                licenseDom = CreateLicenseDom(signer, ExtractPrincipalFromManifest(), ComputeHashFromManifest(m_manifestDom, m_useSha256));
                AuthenticodeSignLicenseDom(licenseDom, signer, timeStampUrl, m_useSha256);
            }
            StrongNameSignManifestDom(m_manifestDom, licenseDom, signer, m_useSha256);
        }

        XmlElement ExtractPrincipalFromManifest()
        {
            var nsm = new XmlNamespaceManager(m_manifestDom.NameTable);
            nsm.AddNamespace("asm", AssemblyNamespaceUri);
            var assemblyIdentityNode = m_manifestDom.SelectSingleNode("asm:assembly/asm:assemblyIdentity", nsm);
            if (assemblyIdentityNode == null)
            {
                throw new CryptographicException(Win32.TRUST_E_SUBJECT_FORM_UNKNOWN);
            }

            return assemblyIdentityNode as XmlElement;
        }

        //
        // Statics.
        //
        static void InsertPublisherIdentity(XmlDocument manifestDom, X509Certificate2 signerCert)
        {
            var nsm = new XmlNamespaceManager(manifestDom.NameTable);
            nsm.AddNamespace("asm", AssemblyNamespaceUri);
            nsm.AddNamespace("asm2", AssemblyV2NamespaceUri);
            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            var assembly = manifestDom.SelectSingleNode("asm:assembly", nsm) as XmlElement;
            var assemblyIdentity = manifestDom.SelectSingleNode("asm:assembly/asm:assemblyIdentity", nsm) as XmlElement;
            if (assemblyIdentity == null)
            {
                throw new CryptographicException(Win32.TRUST_E_SUBJECT_FORM_UNKNOWN);
            }

            // Reuse existing node if exists
            var publisherIdentity = manifestDom.SelectSingleNode("asm:assembly/asm2:publisherIdentity", nsm) as XmlElement;
            if (publisherIdentity == null)
            {
                // create new if not exist
                publisherIdentity = manifestDom.CreateElement("publisherIdentity", AssemblyV2NamespaceUri);
            }
            // Get the issuer's public key blob hash.
            var pIssuerKeyHash = new IntPtr();
            var hr = Win32._AxlGetIssuerPublicKeyHash(signerCert.Handle, ref pIssuerKeyHash);
            if (hr != Win32.S_OK)
            {
                throw new CryptographicException(hr);
            }

            var issuerKeyHash = Marshal.PtrToStringUni(pIssuerKeyHash);
            Win32.HeapFree(Win32.GetProcessHeap(), 0, pIssuerKeyHash);

            publisherIdentity.SetAttribute("name", signerCert.SubjectName.Name);
            publisherIdentity.SetAttribute("issuerKeyHash", issuerKeyHash);

            var signature = manifestDom.SelectSingleNode("asm:assembly/ds:Signature", nsm) as XmlElement;
            if (signature != null)
            {
                assembly.InsertBefore(publisherIdentity, signature);
            }
            else
            {
                assembly.AppendChild(publisherIdentity);
            }
        }

        static void RemoveExistingSignature(XmlDocument manifestDom)
        {
            var nsm = new XmlNamespaceManager(manifestDom.NameTable);
            nsm.AddNamespace("asm", AssemblyNamespaceUri);
            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
            var signatureNode = manifestDom.SelectSingleNode("asm:assembly/ds:Signature", nsm);
            if (signatureNode != null)
            {
                signatureNode.ParentNode.RemoveChild(signatureNode);
            }
        }

        /// <summary>
        /// The reason you need provider type 24, is because that's the only RSA provider type that supports SHA-2 operations.   (For instance, PROV_RSA_FULL does not support SHA-2).
        /// As for official guidance – I'm not sure of any.    For workarounds though, if you're using the Microsoft software CSPs, they share the underlying key store.  You can get the key container name from your RSA object, then open up a new RSA object with the same key container name but with PROV_RSA_AES.   At that point, you should be able to use SHA-2 algorithms.
        /// </summary>
        /// <param name="oldCsp"></param>
        /// <returns></returns>
        internal static RSACryptoServiceProvider GetFixedRSACryptoServiceProvider(RSACryptoServiceProvider oldCsp, bool useSha256)
        {
            if (!useSha256)
            {
                return oldCsp;
            }

            // 3rd party crypto providers in general don't need to be forcefully upgraded.
            // This is not an ideal way to check for that but is the best we have available.
            if (!oldCsp.CspKeyContainerInfo.ProviderName.StartsWith("Microsoft", StringComparison.Ordinal))
            {
                return oldCsp;
            }

            const int PROV_RSA_AES = 24;    // CryptoApi provider type for an RSA provider supporting sha-256 digital signatures
            var csp = new CspParameters();
            csp.ProviderType = PROV_RSA_AES;
            csp.KeyContainerName = oldCsp.CspKeyContainerInfo.KeyContainerName;
            csp.KeyNumber = (int)oldCsp.CspKeyContainerInfo.KeyNumber;
            if (oldCsp.CspKeyContainerInfo.MachineKeyStore)
            {
                csp.Flags = CspProviderFlags.UseMachineKeyStore;
            }
            var fixedRsa = new RSACryptoServiceProvider(csp);

            return fixedRsa;

        }

        static void ReplacePublicKeyToken(XmlDocument manifestDom, AsymmetricAlgorithm snKey, bool useSha256)
        {
            // Make sure we can find the publicKeyToken attribute.
            var nsm = new XmlNamespaceManager(manifestDom.NameTable);
            nsm.AddNamespace("asm", AssemblyNamespaceUri);
            var assemblyIdentity = manifestDom.SelectSingleNode("asm:assembly/asm:assemblyIdentity", nsm) as XmlElement;
            if (assemblyIdentity == null)
            {
                throw new CryptographicException(Win32.TRUST_E_SUBJECT_FORM_UNKNOWN);
            }

            if (!assemblyIdentity.HasAttribute("publicKeyToken"))
            {
                throw new CryptographicException(Win32.TRUST_E_SUBJECT_FORM_UNKNOWN);
            }

            byte[] cspPublicKeyBlob;

            if (snKey is RSACryptoServiceProvider)
            {
                cspPublicKeyBlob = (GetFixedRSACryptoServiceProvider((RSACryptoServiceProvider)snKey, useSha256)).ExportCspBlob(false);
                if (cspPublicKeyBlob == null || cspPublicKeyBlob.Length == 0)
                {
                    throw new CryptographicException(Win32.NTE_BAD_KEY);
                }
            }
            else
            {
                using var rsaCsp = new RSACryptoServiceProvider();
                rsaCsp.ImportParameters(((RSA)snKey).ExportParameters(false));
                cspPublicKeyBlob = rsaCsp.ExportCspBlob(false);
            }

            // Now compute the public key token.
            unsafe
            {
                fixed (byte* pbPublicKeyBlob = cspPublicKeyBlob)
                {
                    var publicKeyBlob = new Win32.CRYPT_DATA_BLOB();
                    publicKeyBlob.cbData = (uint)cspPublicKeyBlob.Length;
                    publicKeyBlob.pbData = new IntPtr(pbPublicKeyBlob);
                    var pPublicKeyToken = new IntPtr();

                    var hr = Win32._AxlPublicKeyBlobToPublicKeyToken(ref publicKeyBlob, ref pPublicKeyToken);
                    if (hr != Win32.S_OK)
                    {
                        throw new CryptographicException(hr);
                    }

                    var publicKeyToken = Marshal.PtrToStringUni(pPublicKeyToken);
                    Win32.HeapFree(Win32.GetProcessHeap(), 0, pPublicKeyToken);

                    assemblyIdentity.SetAttribute("publicKeyToken", publicKeyToken);
                }
            }
        }

        static string GetPublicKeyToken(XmlDocument manifestDom)
        {
            var nsm = new XmlNamespaceManager(manifestDom.NameTable);
            nsm.AddNamespace("asm", AssemblyNamespaceUri);
            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            var assemblyIdentity = manifestDom.SelectSingleNode("asm:assembly/asm:assemblyIdentity", nsm) as XmlElement;

            if (assemblyIdentity == null || !assemblyIdentity.HasAttribute("publicKeyToken"))
            {
                throw new CryptographicException(Win32.TRUST_E_SUBJECT_FORM_UNKNOWN);
            }

            return assemblyIdentity.GetAttribute("publicKeyToken");
        }

        static byte[] ComputeHashFromManifest(XmlDocument manifestDom, bool useSha256)
        {
#if (true) //
            return ComputeHashFromManifest(manifestDom, false, useSha256);
        }

        static byte[] ComputeHashFromManifest(XmlDocument manifestDom, bool oldFormat, bool useSha256)
        {
            if (oldFormat)
            {
                var exc = new XmlDsigExcC14NTransform();
                exc.LoadInput(manifestDom);

                if (useSha256)
                {
                    using var sha2 = SHA256.Create();
                    var hash = sha2.ComputeHash(exc.GetOutput() as MemoryStream);
                    if (hash == null)
                    {
                        throw new CryptographicException(Win32.TRUST_E_BAD_DIGEST);
                    }

                    return hash;
                }
                else
                {
                    using var sha1 = SHA1.Create();
                    var hash = sha1.ComputeHash(exc.GetOutput() as MemoryStream);
                    if (hash == null)
                    {
                        throw new CryptographicException(Win32.TRUST_E_BAD_DIGEST);
                    }

                    return hash;
                }
            }
            else
            {
#endif
                // Since the DOM given to us is not guaranteed to be normalized,
                // we need to normalize it ourselves. Also, we always preserve
                // white space as Fusion XML engine always preserve white space.
                var normalizedDom = new XmlDocument();
                normalizedDom.PreserveWhitespace = true;

                // Normalize the document
                using (TextReader stringReader = new StringReader(manifestDom.OuterXml))
                {
                    var settings = new XmlReaderSettings();
                    settings.DtdProcessing = DtdProcessing.Parse;
                    var reader = XmlReader.Create(stringReader, settings, manifestDom.BaseURI);
                    normalizedDom.Load(reader);
                }

                var exc = new XmlDsigExcC14NTransform();
                exc.LoadInput(normalizedDom);

                if (useSha256)
                {
                    using var sha2 = SHA256.Create();
                    var hash = sha2.ComputeHash(exc.GetOutput() as MemoryStream);
                    if (hash == null)
                    {
                        throw new CryptographicException(Win32.TRUST_E_BAD_DIGEST);
                    }

                    return hash;
                }
                else
                {
                    using var sha1 = SHA1.Create();
                    var hash = sha1.ComputeHash(exc.GetOutput() as MemoryStream);
                    if (hash == null)
                    {
                        throw new CryptographicException(Win32.TRUST_E_BAD_DIGEST);
                    }

                    return hash;
                }

#if (true) //
            }
#endif
        }

        const string AssemblyNamespaceUri = "urn:schemas-microsoft-com:asm.v1";
        const string AssemblyV2NamespaceUri = "urn:schemas-microsoft-com:asm.v2";
        const string MSRelNamespaceUri = "http://schemas.microsoft.com/windows/rel/2005/reldata";
        const string LicenseNamespaceUri = "urn:mpeg:mpeg21:2003:01-REL-R-NS";
        const string AuthenticodeNamespaceUri = "http://schemas.microsoft.com/windows/pki/2005/Authenticode";
        const string licenseTemplate = "<r:license xmlns:r=\"" + LicenseNamespaceUri + "\" xmlns:as=\"" + AuthenticodeNamespaceUri + "\">" +
                                                    @"<r:grant>" +
                                                    @"<as:ManifestInformation>" +
                                                    @"<as:assemblyIdentity />" +
                                                    @"</as:ManifestInformation>" +
                                                    @"<as:SignedBy/>" +
                                                    @"<as:AuthenticodePublisher>" +
                                                    @"<as:X509SubjectName>CN=dummy</as:X509SubjectName>" +
                                                    @"</as:AuthenticodePublisher>" +
                                                    @"</r:grant><r:issuer></r:issuer></r:license>";

        static XmlDocument CreateLicenseDom(CmiManifestSigner2 signer, XmlElement principal, byte[] hash)
        {
            var licenseDom = new XmlDocument();
            licenseDom.PreserveWhitespace = true;
            licenseDom.LoadXml(licenseTemplate);
            var nsm = new XmlNamespaceManager(licenseDom.NameTable);
            nsm.AddNamespace("r", LicenseNamespaceUri);
            nsm.AddNamespace("as", AuthenticodeNamespaceUri);
            var assemblyIdentityNode = licenseDom.SelectSingleNode("r:license/r:grant/as:ManifestInformation/as:assemblyIdentity", nsm) as XmlElement;
            assemblyIdentityNode.RemoveAllAttributes();
            foreach (XmlAttribute attribute in principal.Attributes)
            {
                assemblyIdentityNode.SetAttribute(attribute.Name, attribute.Value);
            }

            var manifestInformationNode = licenseDom.SelectSingleNode("r:license/r:grant/as:ManifestInformation", nsm) as XmlElement;

            manifestInformationNode.SetAttribute("Hash", hash.Length == 0 ? "" : BytesToHexString(hash, 0, hash.Length));
            manifestInformationNode.SetAttribute("Description", signer.Description == null ? "" : signer.Description);
            manifestInformationNode.SetAttribute("Url", signer.DescriptionUrl == null ? "" : signer.DescriptionUrl);

            var authenticodePublisherNode = licenseDom.SelectSingleNode("r:license/r:grant/as:AuthenticodePublisher/as:X509SubjectName", nsm) as XmlElement;
            authenticodePublisherNode.InnerText = signer.Certificate.SubjectName.Name;

            return licenseDom;
        }

        static void AuthenticodeSignLicenseDom(XmlDocument licenseDom, CmiManifestSigner2 signer, string timeStampUrl, bool useSha256)
        {
            // Make sure it is RSA, as this is the only one Fusion will support.
            // HACK: do this in a better way
            RSA rsaPrivateKey = null;
            if (signer.Certificate.HasPrivateKey)
            {
                rsaPrivateKey = signer.Certificate.GetRSAPrivateKey();
            }
            else if (signer.StrongNameKey is RSAKeyVault provider)
            {
                rsaPrivateKey = provider;
            }
            try
            {
                if (rsaPrivateKey == null)
                {
                    throw new NotSupportedException();
                }

                // Setup up XMLDSIG engine.
                var signedXml = new ManifestSignedXml2(licenseDom);
                signedXml.SigningKey = rsaPrivateKey;
                signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
                if (signer.UseSha256)
                {
                    signedXml.SignedInfo.SignatureMethod = Sha256SignatureMethodUri;
                }

                // Add the key information.
                signedXml.KeyInfo.AddClause(new RSAKeyValue(rsaPrivateKey));
                signedXml.KeyInfo.AddClause(new KeyInfoX509Data(signer.Certificate, signer.IncludeOption));

                // Add the enveloped reference.
                var reference = new Reference();
                reference.Uri = "";
                if (signer.UseSha256)
                {
                    reference.DigestMethod = Sha256DigestMethod;
                }

                // Add an enveloped and an Exc-C14N transform.
                reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
#if (false) //
            reference.AddTransform(new XmlLicenseTransform());
#endif
                reference.AddTransform(new XmlDsigExcC14NTransform());

                // Add the reference.
                signedXml.AddReference(reference);

                // Compute the signature.
                signedXml.ComputeSignature();

                // Get the XML representation
                var xmlDigitalSignature = signedXml.GetXml();
                xmlDigitalSignature.SetAttribute("Id", "AuthenticodeSignature");

                // Insert the signature node under the issuer element.
                var nsm = new XmlNamespaceManager(licenseDom.NameTable);
                nsm.AddNamespace("r", LicenseNamespaceUri);
                var issuerNode = licenseDom.SelectSingleNode("r:license/r:issuer", nsm) as XmlElement;
                issuerNode.AppendChild(licenseDom.ImportNode(xmlDigitalSignature, true));

                // Time stamp it if requested.
                if (timeStampUrl != null && timeStampUrl.Length != 0)
                {
                    TimestampSignedLicenseDom(licenseDom, timeStampUrl);
                }

                // Wrap it inside a RelData element.
                licenseDom.DocumentElement.ParentNode.InnerXml = "<msrel:RelData xmlns:msrel=\"" +
                                                                 MSRelNamespaceUri + "\">" +
                                                                 licenseDom.OuterXml + "</msrel:RelData>";
            }
            finally
            {
                if (rsaPrivateKey != signer.StrongNameKey)
                {
                    rsaPrivateKey.Dispose();
                }
            }
        }

        static void TimestampSignedLicenseDom(XmlDocument licenseDom, string timeStampUrl)
        {
            var timestampBlob = new Win32.CRYPT_DATA_BLOB();

            var nsm = new XmlNamespaceManager(licenseDom.NameTable);
            nsm.AddNamespace("r", LicenseNamespaceUri);
            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
            nsm.AddNamespace("as", AuthenticodeNamespaceUri);

            var licenseXml = Encoding.UTF8.GetBytes(licenseDom.OuterXml);

            unsafe
            {
                fixed (byte* pbLicense = licenseXml)
                {
                    var licenseBlob = new Win32.CRYPT_DATA_BLOB();
                    var pvLicense = new IntPtr(pbLicense);
                    licenseBlob.cbData = (uint)licenseXml.Length;
                    licenseBlob.pbData = pvLicense;

                    var hr = Win32.CertTimestampAuthenticodeLicense(ref licenseBlob, timeStampUrl, ref timestampBlob);
                    if (hr != Win32.S_OK)
                    {
                        throw new CryptographicException(hr);
                    }
                }
            }

            var timestampSignature = new byte[timestampBlob.cbData];
            Marshal.Copy(timestampBlob.pbData, timestampSignature, 0, timestampSignature.Length);
            Win32.HeapFree(Win32.GetProcessHeap(), 0, timestampBlob.pbData);

            var asTimestamp = licenseDom.CreateElement("as", "Timestamp", AuthenticodeNamespaceUri);
            asTimestamp.InnerText = Encoding.UTF8.GetString(timestampSignature);

            var dsObject = licenseDom.CreateElement("Object", SignedXml.XmlDsigNamespaceUrl);
            dsObject.AppendChild(asTimestamp);

            var signatureNode = licenseDom.SelectSingleNode("r:license/r:issuer/ds:Signature", nsm) as XmlElement;
            signatureNode.AppendChild(dsObject);
        }

        static void StrongNameSignManifestDom(XmlDocument manifestDom, XmlDocument licenseDom, CmiManifestSigner2 signer, bool useSha256)
        {
            var snKey = signer.StrongNameKey as RSA;

            // Make sure it is RSA, as this is the only one Fusion will support.
            if (snKey == null)
            {
                throw new NotSupportedException();
            }

            // Setup namespace manager.
            var nsm = new XmlNamespaceManager(manifestDom.NameTable);
            nsm.AddNamespace("asm", AssemblyNamespaceUri);

            // Get to root element.
            var signatureParent = manifestDom.SelectSingleNode("asm:assembly", nsm) as XmlElement;
            if (signatureParent == null)
            {
                throw new CryptographicException(Win32.TRUST_E_SUBJECT_FORM_UNKNOWN);
            }

            if (!(signer.StrongNameKey is RSA))
            {
                throw new NotSupportedException();
            }

            // Setup up XMLDSIG engine.
            var signedXml = new ManifestSignedXml2(signatureParent);
            if (signer.StrongNameKey is RSACryptoServiceProvider)
            {
                signedXml.SigningKey = GetFixedRSACryptoServiceProvider(signer.StrongNameKey as RSACryptoServiceProvider, useSha256);
            }
            else
            {
                signedXml.SigningKey = signer.StrongNameKey;
            }
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            if (signer.UseSha256)
            {
                signedXml.SignedInfo.SignatureMethod = Sha256SignatureMethodUri;
            }

            // Add the key information.
            signedXml.KeyInfo.AddClause(new RSAKeyValue(snKey));
            if (licenseDom != null)
            {
                signedXml.KeyInfo.AddClause(new KeyInfoNode(licenseDom.DocumentElement));
            }
            signedXml.KeyInfo.Id = "StrongNameKeyInfo";

            // Add the enveloped reference.
            var enveloped = new Reference();
            enveloped.Uri = "";
            if (signer.UseSha256)
            {
                enveloped.DigestMethod = Sha256DigestMethod;
            }

            // Add an enveloped then Exc-C14N transform.
            enveloped.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            enveloped.AddTransform(new XmlDsigExcC14NTransform());
            signedXml.AddReference(enveloped);

#if (false) // DSIE: New format does not sign KeyInfo.
            // Add the key info reference.
            Reference strongNameKeyInfo = new Reference();
            strongNameKeyInfo.Uri = "#StrongNameKeyInfo";
            strongNameKeyInfo.AddTransform(new XmlDsigExcC14NTransform());
            signedXml.AddReference(strongNameKeyInfo);
#endif
            // Compute the signature.
            signedXml.ComputeSignature();

            // Get the XML representation
            var xmlDigitalSignature = signedXml.GetXml();
            xmlDigitalSignature.SetAttribute("Id", "StrongNameSignature");

            // Insert the signature now.
            signatureParent.AppendChild(xmlDigitalSignature);
        }
        static readonly char[] hexValues = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

        static string BytesToHexString(byte[] array, int start, int end)
        {
            string result = null;
            if (array != null)
            {
                var hexOrder = new char[(end - start) * 2];
                var i = end;
                int digit, j = 0;
                while (i-- > start)
                {
                    digit = (array[i] & 0xf0) >> 4;
                    hexOrder[j++] = hexValues[digit];
                    digit = (array[i] & 0x0f);
                    hexOrder[j++] = hexValues[digit];
                }
                result = new String(hexOrder);
            }
            return result;
        }

    }

    class CmiManifestSigner2
    {
        readonly AsymmetricAlgorithm m_strongNameKey;
        readonly X509Certificate2 m_certificate;
        string m_description;
        string m_url;
        readonly X509Certificate2Collection m_certificates;
        X509IncludeOption m_includeOption;
        CmiManifestSignerFlag m_signerFlag;
        readonly bool m_useSha256;

        CmiManifestSigner2() { }

        internal CmiManifestSigner2(AsymmetricAlgorithm strongNameKey) :
            this(strongNameKey, null, false)
        { }

        internal CmiManifestSigner2(AsymmetricAlgorithm strongNameKey, X509Certificate2 certificate, bool useSha256)
        {
            if (strongNameKey == null)
            {
                throw new ArgumentNullException("strongNameKey");
            }

#if (true) //
            var rsa = strongNameKey as RSA;
            if (rsa == null)
            {
                throw new ArgumentNullException("strongNameKey");
            }
#endif
            m_strongNameKey = strongNameKey;
            m_certificate = certificate;
            m_certificates = new X509Certificate2Collection();
            m_includeOption = X509IncludeOption.ExcludeRoot;
            m_signerFlag = CmiManifestSignerFlag.None;
            m_useSha256 = useSha256;
        }

        internal bool UseSha256
        {
            get
            {
                return m_useSha256;
            }
        }

        internal AsymmetricAlgorithm StrongNameKey
        {
            get
            {
                return m_strongNameKey;
            }
        }

        internal X509Certificate2 Certificate
        {
            get
            {
                return m_certificate;
            }
        }

        internal string Description
        {
            get
            {
                return m_description;
            }
            set
            {
                m_description = value;
            }
        }

        internal string DescriptionUrl
        {
            get
            {
                return m_url;
            }
            set
            {
                m_url = value;
            }
        }

        internal X509Certificate2Collection ExtraStore
        {
            get
            {
                return m_certificates;
            }
        }

        internal X509IncludeOption IncludeOption
        {
            get
            {
                return m_includeOption;
            }
            set
            {
                if (value < X509IncludeOption.None || value > X509IncludeOption.WholeChain)
                {
                    throw new ArgumentException("value");
                }

                if (m_includeOption == X509IncludeOption.None)
                {
                    throw new NotSupportedException();
                }

                m_includeOption = value;
            }
        }

        internal CmiManifestSignerFlag Flag
        {
            get
            {
                return m_signerFlag;
            }
            set
            {
                unchecked
                {
                    if ((value & ((CmiManifestSignerFlag)~CimManifestSignerFlagMask)) != 0)
                    {
                        throw new ArgumentException("value");
                    }
                }
                m_signerFlag = value;
            }
        }

        internal const uint CimManifestSignerFlagMask = 0x00000001;
    }

}
#pragma warning restore IDE1006 // Naming Styles
#pragma warning restore IDE0032
#pragma warning restore IDE0049
#pragma warning restore IDE0016
#pragma warning restore IDE0017
#pragma warning restore IDE0018
#pragma warning restore IDE0019
#pragma warning restore IDE0029
#pragma warning restore IDE0003
#pragma warning restore IDE0051
#pragma warning restore IDE0060


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Diagnostics;

namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
    /// <summary>
    /// Substitutes all occurrences of dynamic type with Object type.
    /// </summary>
    internal sealed class DynamicTypeEraser : AbstractTypeMap
    {
        private readonly TypeSymbol _objectType;

        public DynamicTypeEraser(TypeSymbol objectType)
        {
            Debug.Assert((object)objectType != null);
            _objectType = objectType;
        }

        public TypeSymbol EraseDynamic(TypeSymbol type)
        {
            return SubstituteType(type).AsTypeSymbolOnly();
        }

        protected override TypeSymbol SubstituteDynamicType()
        {
            return _objectType;
        }
    }
}


text:
'use strict';

const _ = require('lodash');
const prependHttp = require('prepend-http');
const debug = require('_/log').debugger('middleware:normalize');
const DEFAULTS = require('_/common/defaults');

module.exports = normalize;

/* Normalize */
function normalize(req, res, next) {
  merge(req);
  normalizeUrls(req);

  if (_.has(req.data, 'items')) {
    normalizeMulti(req, res, next);
  } else {
    normalizeSingle(req, res, next);
  }
}

/* Single */
function normalizeSingle(req, res, next) {
  // apply spectre defaults
  _.defaultsDeep(req.data, DEFAULTS);

  debug('Normalization success!');
  next();
}

/* Multi */
function normalizeMulti(req, res, next) {
  let results = getItemsAndDefaults(req.data);

  if (results.error) return next(new Error(results.error));

  let items = applyDefaultsToItems(results.items, results.defaults);

  req.data = items.length === 1 ? items[0] : items;

  debug('Normalization success!');
  next();
}

/* Helpers */
function getItemsAndDefaults(data) {
  let results = {
    error: null,
    defaults: {},
    items: []
  };

  if (_.isArray(data)) {
    results.items = data;
  } else {

    if (!_.has(data, 'items')) {
      results.error = 'Invalid multi request. Items missing.';
      return results;
    }

    if (!_.isArray(data.items)) {
      results.error = 'Invalid multi request. Items must be an array.';
      return results;
    }

    results.items = data.items;
    results.defaults = _.omit(data, 'items');
  }

  return results;
}

function applyDefaultsToItems(items, defaults) {
  _.forEach(items, function (item, key) {
    let sources = _.filter(items, function (i, k) {
      return k !== key;
    });

    sources.unshift(defaults);

    applyDefaultsDeep(item, sources);
  });

  // apply spectre defaults
  _.forEach(items, function (item) {
    _.defaultsDeep(item, DEFAULTS);
  });

  return items;
}

function merge(req) {
  let body = req.body || {};
  let query = req.query || {};

  req.data = _.defaultsDeep(body, query);
}

function normalizeUrls(req) {
  // single
  if (req.data.url)
    req.data.url = prependHttp(req.data.url);

  // multi
  if (req.data.items) {
    _.forEach(req.data.items, (item, key) => {
      req.data.items[key].url = prependHttp(item.url);
    });
  }
}

function applyDefaultsDeep(item, sources) {
  sources.unshift(item);
  _.defaultsDeep.apply(this, sources); // jshint ignore:line
}


text:
'use strict';

const HtmlWebpack = require('html-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const ChunkWebpack = webpack.optimize.CommonsChunkPlugin;
const ProvidePlugin = webpack.ProvidePlugin;
const DefinePlugin = webpack.DefinePlugin;

module.exports = {
    entry: {
        app: [path.resolve('src', 'boot') ],
	vendor: [path.resolve('src', 'vendor') ]
    },
    module: {
        loaders: [
            { loader: 'html-loader', test: /\.html$/ },
            { test: /\.css$/, loader: "style-loader!css-loader" },
            {
                test: /\.(jpg|png|svg|eot|otf|ttf|woff(2)?)(\?[^]*)?$/,
                loader: 'file-loader'
            },
            { exclude: /node_modules/, loaders: ['awesome-typescript-loader', 'angular2-template-loader'], test: /\.ts$/ }
        ]
    },
    output: {
        filename: '[name].bundle.js',
        path: path.resolve('build')
    },
    plugins: [
        new ChunkWebpack({
            filename: 'vendor.bundle.js',
            minChunks: Infinity,
            name: 'vendor'
        }),
        new ProvidePlugin({
            jQuery: 'jquery',
            $: 'jquery',
            jquery: 'jquery'
        }),
        new HtmlWebpack({
            filename: 'index.html',
            inject: 'body',
            template: path.resolve('src', 'index.html')
        }),
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false,
                screw_ie8: true,
                conditionals: true,
                unused: true,
                comparisons: true,
                sequences: true,
                dead_code: true,
                evaluate: true,
                if_return: true,
                join_vars: true
            },
            output: {
                comments: false
            }
        }),
        new DefinePlugin({
            'ENV': JSON.stringify('development'),
            'API_URL': JSON.stringify('https://dorfner.congrue.xyz/api/')
            //TODO: The above domain name will need to be changed to the machine hosting this
        })
    ],
    resolve: {
        extensions: [ '.js', '.ts' ]
    }
};


text:
package com.config.loader;

public class InvalidConfigFormatException extends Exception {
    private final String config;
    InvalidConfigFormatException(String config) {
        this.config = config;
    }

    public String getJsonString() {
        return config;
    }
}


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


text:
Applying patch to version {{targetVersion}}...

Upload one or more patch files to apply to this fabric

Enter a name for the new version, or leave blank to use the next available version:

      <input type="text" ng-model="newVersionName">

Enter administrator credentials for fabric:

        User Name:

          <input type="text" ng-model="proxyUser">

        Password:

          <input type="password" ng-model="proxyPassword">

            <input type="checkbox" ng-model="saveJmxCredentials">  Save these credentials as the default

        <button class="btn btn-danger" ng-click="cancel()"> Cancel</button>
        <button class="btn btn-success" ng-disabled="!valid()" ng-click="go()"> Apply</button>


text:
<?php

$this->breadcrumbs=array(
	$this->module->id,"request availability"
);

?>

<?php
$form = $this->beginWidget('CActiveForm', array(
    'id'=>"filterRequest",
));

$values = VStudies::model()->findAll("STUDY_ID NOT IN (1,2)");
$data = CHtml::listData($values,'STUDY_ID','STUDY');

echo "
";
    echo CHtml::label ("STUDY", "STUDY_ID");
    echo CHtml::dropDownList ("STUDY_ID", "",MyUtils::addEmpty($data),array("class"=>"span2"));
echo "
";

echo "
";
    echo CHtml::label ("COUNTRY", "COUNTRY_ID");
    echo CHtml::dropDownList ("COUNTRY_ID", "",array(), array(
            'ajax' => array (
                    'type' => 'POST',
                    'url' =>CController::createUrl('translational/dynamicCentre'),
                    'update' =>'#CENTRE_ID',
            ),
            'class' =>'tagsinput span2',
    ));
echo "
";

echo "
";
    echo CHtml::label ("CENTRE", "CENTRE_ID");
    echo CHtml::dropDownList ("CENTRE_ID", "",array(), array(
            'ajax' => array (
                    'type' => 'POST',
                    'url' =>CController::createUrl('translational/dynamicVisit'),
                    'update' =>'#VISIT_ID',
            ),
            "class"=>"span2"
    ));
echo "
";

echo "
";
    echo CHtml::label ("VISIT", "VISIT_ID");
    echo CHtml::dropDownList ("VISIT_ID", "",array(), array(
            'ajax' => array (
                    'type' => 'POST',
                    'url' =>CController::createUrl('translational/dynamicPatient'),
                    'update' =>'#PATIENT_ID',
            ),
            "class"=>"span2"
    ));
echo "
";

echo "
";
    echo CHtml::label ("PATIENT", "PATIENT_ID");
    echo CHtml::dropDownList ("PATIENT_ID", "",array(),array("class"=>"span2"));
echo "
";

$url = Yii::app()->createUrl('shipment/translational/materialToShip');

echo "
";
    echo CHtml::ajaxButton("FILTER",$url,
        array(
               'type'=>'POST',
               'data'=> 'js:$("#filterRequest").serialize()',
               'before'=>'js:$("#QUERY-PROGRESS").dialog("open")',
               'success'=>'js: function(data){$("#QUERY-PROGRESS").dialog("close"); $("#tableMaterialToShip").html(data);}',
        ),
        array(
                'id'=>'findMaterialToShip',
                'class'=>'button btn btn-primary',
        ));

echo "
";

$this->endWidget();

?>


text:
import jsonschema
from .raml import named_params_to_json_schema

class RAMLValidator(object):
    def __init__(self, response, raml):
        self.response = response
        self.raml = raml
        self.raml_response = raml.responses.get(response.status_code)

    def validate(self, validate=["headers", "body"]):
        if self.raml is None:
            raise ValueError("Trying to validate with no RAML ResourceNode")
        if validate == True or "headers" in validate:
            self.validate_headers()
        if validate == True or "body" in validate:
            self.validate_body()

    def validate_body(self):
        try:
            schema = self.raml_response.body['application/json'].schema
        except (AttributeError, KeyError):
            return # RAML response bodies are optional

        jsonschema.validate(self.response.json, schema)

    def validate_headers(self):
        try:
            raml_headers_node = self.raml_response.headers
        except AttributeError:
            return # RAML headers are optional
        else:
            raml_headers_raw = list(self.raml_response.headers.values())

        raml_headers = {header.name: dict(header.raw[header.name])
                        for header in raml_headers_raw}
        http_headers = dict(self.response.headers)

        for name, data in raml_headers.items():
            self._validate_header(data, http_headers.get(name))

    def _validate_header(self, header_props, header_val):
        try:
            prop_schema = named_params_to_json_schema(header_props)
        except KeyError as ex:
            raise RAMLValidationError('Missing required RAML named parameter: '
                                      '{}'.format(ex))
        try:
            header_val = _convert_type(prop_schema['type'], header_val)
        except ValueError:
            raise RAMLValidationError('Header value is not of type '
                                      '`{}`'.format(prop_schema['type']))

        required = prop_schema.pop('required', False)
        json_schema = {
            '$schema': 'http://json-schema.org/draft-04/schema',
            'type': 'object',
            'properties': {
                'header': prop_schema
            },
        }
        if required:
            json_schema['required'] = ['header']
        header = {} if header_val is None else {'header': header_val}
        jsonschema.validate(header, json_schema)

def _convert_type(type_, value):
    booleans = {'true': True, 'false': False}
    if type_ == 'number':
        return float(value)
    elif type_ == 'integer':
        return int(value)
    elif type_ == 'boolean':
        return booleans.get(value, value)
    return value

class RAMLValidationError(object): pass


text:
package io.cattle.platform.simple.allocator.dao.impl;

import io.cattle.platform.core.model.Port;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class CandidateHostInfo {
    private Long hostId;
    private String hostUuid;
    private Set<Long> poolIds = new HashSet<>();
    private List<Port> usedPorts = new ArrayList<>();
    private Map<String, Set<String>> containerLabels = new HashMap<>();

    public CandidateHostInfo(Long hostId, String hostUuid) {
        this.hostId = hostId;
        this.hostUuid = hostUuid;
    }

    public CandidateHostInfo(Long hostId, String hostUuid, Set<Long> poolIds, List<Port> usedPorts, Map<String, Set<String>> containerLabels) {
        this.hostId = hostId;
        this.hostUuid = hostUuid;
        this.poolIds = poolIds;
        this.usedPorts = usedPorts;
        this.containerLabels = containerLabels;
    }

    public Long getHostId() {
        return hostId;
    }
    public void setHostId(Long hostId) {
        this.hostId = hostId;
    }
    public Set<Long> getPoolIds() {
        return poolIds;
    }
    public void setPoolIds(Set<Long> poolIds) {
        this.poolIds = poolIds;
    }
    public String getHostUuid() {
        return hostUuid;
    }
    public void setHostUuid(String hostUuid) {
        this.hostUuid = hostUuid;
    }
    public List<Port> getUsedPorts() {
        return usedPorts;
    }
    public void setUsedPorts(List<Port> usedPorts) {
        this.usedPorts = usedPorts;
    }
    public Map<String, Set<String>> getContainerLabels() {
        return containerLabels;
    }
    public void setContainerLabels(Map<String, Set<String>> containerLabels) {
        this.containerLabels = containerLabels;
    }

}