text:
package gensource

import (
	"encoding/json"
	"fmt"
	"io"
	"os"
	"sort"
	"strings"
	"unicode"

	"gopkg.in/yaml.v2"

	"github.com/elastic/go-elasticsearch/v8/internal/build/utils"
)

var (
	apiDescriptions map[interface{}]interface{}
)

func init() {
	err := yaml.NewDecoder(strings.NewReader(apiDescriptionsYAML)).Decode(&apiDescriptions)
	if err != nil {
		panic(fmt.Sprintf("ERROR: %v", err))
	}
}

// NewEndpoint creates a new API endpoint.
//
func NewEndpoint(f io.Reader) (*Endpoint, error) {
	var endpoint Endpoint
	var spec map[string]Endpoint

	var xpackNamespaces = []string{
		"async_search",
		"autoscaling",
		"cat.ml_data_frame_analytics",
		"cat.ml_datafeeds",
		"cat.ml_jobs",
		"cat.ml_trained_models",
		"cat.transforms",
		"ccr",
		"close_point_in_time",
		"data_frame_transform_deprecated",
		"enrich",
		"eql",
		"graph",
		"ilm",
		"indices.create_data_stream",
		"indices.data_streams_stats",
		"indices.delete_data_stream",
		"indices.freeze",
		"indices.get_data_stream",
		"indices.migrate_to_data_stream",
		"indices.promote_data_stream",
		"indices.reload_search_analyzers",
		"indices.unfreeze",
		"license",
		"logstash",
		"migration",
		"ml",
		"monitoring",
		"open_point_in_time",
		"rollup",
		"searchable_snapshots",
		"security",
		"slm",
		"sql",
		"ssl",
		"text_structure",
		"transform",
		"watcher",
		"xpack.info",
		"xpack.usage",
	}

	if err := json.NewDecoder(f).Decode(&spec); err != nil {
		return nil, err
	}

	for name, e := range spec {
		endpoint = e
		endpoint.Name = name
		endpoint.URL.Params = endpoint.Params
	}

	if fpath, ok := f.(*os.File); ok {
		if strings.Contains(fpath.Name(), "x-pack") {
			endpoint.Type = "xpack"
		}
		for _, namespace := range xpackNamespaces {
			if strings.Contains(fpath.Name(), namespace) {
				endpoint.Type = "xpack"
			}
		}
	}
	if endpoint.Type == "" {
		endpoint.Type = "core"
	}

	endpoint.URL.AllParts = make(map[string]*Part)

	for _, path := range endpoint.URL.Paths {
		for partName, part := range path.Parts {
			part.Endpoint = &endpoint
			part.Name = partName
		}
	}

	var params [][]string
	for _, path := range endpoint.URL.Paths {
		var parts []string
		for partName, part := range path.Parts {
			// Skip type only for selected APIs at this point
			if part.Name == "type" && part.Deprecated {
				if endpoint.Name == "bulk" ||
					endpoint.Name == "create" ||
					endpoint.Name == "delete" ||
					endpoint.Name == "get" ||
					endpoint.Name == "index" ||
					endpoint.Name == "update" {
					continue
				}
			}
			parts = append(parts, partName)
		}
		params = append(params, parts)
	}

	var paramsCounter = make(map[string]int)
	for _, pp := range params {
		for _, p := range pp {
			paramsCounter[p] += 1
		}
	}

	// Update the required field of path parts
	for _, path := range endpoint.URL.Paths {
		for partName, part := range path.Parts {
			if p, ok := paramsCounter[partName]; ok {
				if p == len(params) {
					part.Required = true
				}
			}
		}
	}

	for paramName, p := range endpoint.URL.Params {
		p.Endpoint = &endpoint
		p.Name = paramName
	}

	// Update the AllParts field
	var partSeen = make(map[string]bool)
	for _, path := range endpoint.URL.Paths {
		for partName, part := range path.Parts {
			if !partSeen[partName] {
				endpoint.URL.AllParts[partName] = part
			}
			partSeen[partName] = true
		}
	}

	// Fix up the documentation property (X-Pack spec related); TODO: PR
	if !strings.HasPrefix(endpoint.Documentation.URL, "http") {
		if endpoint.Type == "xpack" && endpoint.Documentation.Description == "" && endpoint.Documentation.URL != "" {
			endpoint.Documentation.Description = endpoint.Documentation.URL

			if endpoint.Documentation.URL == "TODO" {
				endpoint.Documentation.URL = ""
			}
			if endpoint.Documentation.Description == "TODO" {
				endpoint.Documentation.Description = ""
			}
		}
		endpoint.Documentation.URL = ""
	}

	var partNames []string
	for param := range paramsCounter {
		partNames = append(partNames, param)
	}
	sort.Slice(partNames, func(i, j int) bool {
		return strings.Replace(partNames[i], "_", "", 1) < strings.Replace(partNames[j], "_", "", 1)
	})
	endpoint.URL.PartNamesSorted = partNames

	var paramNames []string
	for _, param := range endpoint.URL.Params {
		paramNames = append(paramNames, param.Name)
	}
	sort.Slice(paramNames, func(i, j int) bool {
		return strings.Replace(paramNames[i], "_", "", 1) < strings.Replace(paramNames[j], "_", "", 1)
	})
	endpoint.URL.ParamNamesSorted = paramNames

	// if info, ok := apiDescriptions[endpoint.Name]; ok {
	// 	if desc, ok := info.(map[interface{}]interface{})["description"].(string); ok {
	// 		endpoint.Documentation.Description = desc
	// 	}
	// }

	return &endpoint, nil
}

// Endpoint represents an API endpoint.
//
type Endpoint struct {
	Name string `json:"-"`
	Type string `json:"-"`

	Documentation struct {
		URL         string `json:"url"`
		Description string `json:"description"`
	} `json:"documentation"`

	Stability string `json:"stability"`

	URL    *URL              `json:"url"`
	Params map[string]*Param `json:"params"`
	Body   *Body             `json:"body"`
}

// URL represents API endpoint URL.
//
type URL struct {
	Endpoint *Endpoint `json:"-"`

	Paths           []Path `json:"paths"`
	DeprecatedPaths []struct {
		Path        string `json:"path"`
		Version     string `json:"version"`
		Description string `json:"description"`
	} `json:"deprecated_paths"`
	Params map[string]*Param `json:"params"`

	AllParts         map[string]*Part
	PartNamesSorted  []string
	ParamNamesSorted []string
}

// Path represents URL path
type Path struct {
	Path       string           `json:"path"`
	Methods    []string         `json:"methods"`
	Parts      map[string]*Part `json:"parts"`
	Deprecated struct {
		Version     string `json:"version"`
		Description string `json:"description"`
	}
}

// Part represents part of the API endpoint URL.
//
type Part struct {
	Endpoint *Endpoint `json:"-"`

	Name    string      `json:"-"`
	Default interface{} `json:"-"`

	Type        string `json:"type"`
	Description string `json:"description"`
	Required    bool   `json:"required"`

	Deprecated bool `json:"deprecated"`
}

// Param represents API endpoint parameter.
//
type Param struct {
	Endpoint *Endpoint `json:"-"`

	Name string `json:"-"`

	Type        string      `json:"type"`
	Description string      `json:"description"`
	Options     []string    `json:"options"`
	Default     interface{} `json:"default"`
	Required    bool        `json:"required"`
}

// Body represents API endpoint body.
//
type Body struct {
	Endpoint *Endpoint `json:"-"`

	Description string `json:"description"`
	Required    bool   `json:"required"`
	ContentType string `json:"serialize"`
}

// MethodArgument represents a method argument for API endpoint.
//
type MethodArgument struct {
	Endpoint *Endpoint

	Name        string
	Type        string
	Description string
	Options     []string
	Default     interface{}
	Required    bool
}

// Namespace returns the API endpoint namespace.
//
func (e *Endpoint) Namespace() string {
	ep := strings.Split(e.Name, ".")
	return utils.NameToGo(ep[0])
}

// MethodName returns the API endpoint method name.
//
func (e *Endpoint) MethodName() string {
	ep := strings.Split(e.Name, ".")
	ep = append(ep[:0], ep[1:]...)
	ns := make([]string, len(ep))
	for _, v := range ep {
		m := strings.Split(v, "_")
		mn := make([]string, len(m))
		for _, vv := range m {
			mn = append(mn, strings.Title(vv))
		}
		ns = append(ns, strings.Join(mn, ""))
	}
	return strings.Join(ns, "")
}

// MethodWithNamespace returns the API endpoint method name with namespace.
//
func (e *Endpoint) MethodWithNamespace() string {
	return utils.APIToGo(e.Name)
}

// HumanMethodWithNamespace returns the API endpoint method name in humanized form.
//
func (e *Endpoint) HumanMethodWithNamespace() string {
	var (
		src = e.MethodWithNamespace()
		out string
	)
	for i, l := range src {
		if unicode.IsUpper(l) && i > 0 {
			if i+2 <= len(src) && unicode.IsUpper([]rune(src[i+1 : i+2])[0]) {
				out += string(l)
			} else {
				out += " " + string(l)
			}
		} else {
			out += string(l)
		}
	}
	return out
}

// RequiredArguments return the list of required method arguments.
//
func (e *Endpoint) RequiredArguments() []MethodArgument {
	var args = make([]MethodArgument, 0)
	var prominentArgs = []string{
		"index",
		"id",
		"repository",
		"snapshot",
		"snapshot_id",
		"calendar_id",
		"job_id",
		"username",
		"name",
	}

	var contains = func(s string) bool {
		for _, v := range args {
			if v.Name == s {
				return true
			}
		}
		return false
	}

	var keys []string
	for k := range e.URL.Paths[0].Parts {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	// Return the prominent arguments first
	for _, d := range prominentArgs {
		for _, k := range keys {
			p := e.URL.Paths[0].Parts[k]
			if p.Name != d {
				continue
			}
			if p.Required {
				args = append(args, MethodArgument{
					Endpoint:    e,
					Name:        p.Name,
					Type:        p.Type,
					Description: p.Description,
					Required:    true,
				})
			}
		}
	}

	// Return the body after prominent arguments
	if e.Body != nil && e.Body.Required {
		args = append(args, MethodArgument{
			Endpoint:    e,
			Name:        "body",
			Description: e.Body.Description,
		})
	}

	// Return rest of the URL parts
	for _, k := range keys {
		p := e.URL.Paths[0].Parts[k]
		if contains(p.Name) {
			continue
		}
		if p.Required {
			args = append(args, MethodArgument{
				Endpoint:    e,
				Name:        p.Name,
				Type:        p.Type,
				Description: p.Description,
				Required:    true,
			})
		}
	}

	// Return URL params
	for _, p := range e.URL.Params {
		if contains(p.Name) {
			continue
		}
		if p.Required {
			args = append(args, MethodArgument{
				Endpoint:    e,
				Name:        p.Name,
				Type:        p.Type,
				Description: p.Description,
				Options:     p.Options,
				Default:     p.Default,
				Required:    p.Required,
			})
		}
	}

	return args
}

// GoName returns a Go name for part.
//
func (p *Part) GoName() string {
	switch {
	case p.Name == "context":
		return "ScriptContext"
	default:
		return utils.NameToGo(p.Name, p.Endpoint.MethodWithNamespace())
	}
}

// GoType returns a Go type for part.
//
func (p *Part) GoType(comment ...bool) string {
	return utils.TypeToGo(p.Type)
}

// GoName returns a Go name for parameter.
//
func (p *Param) GoName() string {
	switch {
	case p.Name == "context":
		return "ScriptContext"
	case p.Name == "q":
		return "Query"
	default:
		return utils.NameToGo(p.Name, p.Endpoint.MethodWithNamespace())
	}
}

// GoType returns a Go type for parameter.
//
func (p *Param) GoType(comment ...bool) string {
	if f := (&Generator{Endpoint: p.Endpoint}).GetOverride("polymorphic-param", p.Endpoint.Name); f != nil {
		if out := f(p.Endpoint, p.Name); out != "" {
			return out
		}
	}
	return utils.TypeToGo(p.Type)
}

// GoName returns a Go name for method argument.
//
func (p *MethodArgument) GoName() string {
	return utils.NameToGo(p.Name, p.Endpoint.MethodWithNamespace())
}

// GoType returns a Go type for method argument.
//
func (p *MethodArgument) GoType(comment ...bool) string {
	return utils.TypeToGo(p.Type)
}

// ContainsMethods return true if every method passed in argument is present in every Path
func (u *URL) ContainsMethods(methods ...string) bool {
	for _, path := range u.Paths {
		// Fast exit if both collections are not the same size
		if len(methods) != len(path.Methods) {
			return false
		}

		// We iterate over every items
		items := make(map[string]struct{})
		for _, v := range path.Methods {
			items[v] = struct{}{}
		}

		for _, method := range methods {
			if _, ok := items[method]; ok {
				continue
			}
			return false
		}
		continue
	}
	return true
}


text:
<?php

declare(strict_types=1);

namespace spec\Sylius\Component\Promotion\Model;

use PhpSpec\ObjectBehavior;
use Sylius\Component\Promotion\Model\CatalogPromotionInterface;
use Sylius\Component\Promotion\Model\CatalogPromotionScopeInterface;

final class CatalogPromotionScopeSpec extends ObjectBehavior
{
    function it_is_a_catalog_promotion_scope(): void
    {
        $this->shouldImplement(CatalogPromotionScopeInterface::class);
    }

    function it_does_not_have_id_by_default(): void
    {
        $this->getId()->shouldReturn(null);
    }

    function its_type_is_mutable(): void
    {
        $this->getType()->shouldReturn(null);
        $this->setType('type');
        $this->getType()->shouldReturn('type');
    }

    function its_configuration_is_mutable(): void
    {
        $this->getConfiguration()->shouldReturn([]);
        $this->setConfiguration(['value' => 500]);
        $this->getConfiguration()->shouldReturn(['value' => 500]);
    }

    function its_catalog_promotion_is_mutable(CatalogPromotionInterface $catalogPromotion): void
    {
        $this->getCatalogPromotion()->shouldReturn(null);
        $this->setCatalogPromotion($catalogPromotion);
        $this->getCatalogPromotion()->shouldReturn($catalogPromotion);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.spark.sql.execution.streaming

import java.util
import java.util.Collections

import org.apache.spark.sql._
import org.apache.spark.sql.execution.streaming.sources.ConsoleWrite
import org.apache.spark.sql.sources.{BaseRelation, CreatableRelationProvider, DataSourceRegister}
import org.apache.spark.sql.sources.v2._
import org.apache.spark.sql.sources.v2.writer.{SupportsTruncate, WriteBuilder}
import org.apache.spark.sql.sources.v2.writer.streaming.StreamingWrite
import org.apache.spark.sql.types.StructType
import org.apache.spark.sql.util.CaseInsensitiveStringMap

case class ConsoleRelation(override val sqlContext: SQLContext, data: DataFrame)
  extends BaseRelation {
  override def schema: StructType = data.schema
}

class ConsoleSinkProvider extends TableProvider
  with DataSourceRegister
  with CreatableRelationProvider {

  override def getTable(options: CaseInsensitiveStringMap): Table = {
    ConsoleTable
  }

  def createRelation(
      sqlContext: SQLContext,
      mode: SaveMode,
      parameters: Map[String, String],
      data: DataFrame): BaseRelation = {
    // Number of rows to display, by default 20 rows
    val numRowsToShow = parameters.get("numRows").map(_.toInt).getOrElse(20)

    // Truncate the displayed data if it is too long, by default it is true
    val isTruncated = parameters.get("truncate").map(_.toBoolean).getOrElse(true)
    data.show(numRowsToShow, isTruncated)

    ConsoleRelation(sqlContext, data)
  }

  def shortName(): String = "console"
}

object ConsoleTable extends Table with SupportsStreamingWrite {

  override def name(): String = "console"

  override def schema(): StructType = StructType(Nil)

  override def capabilities(): util.Set[TableCapability] = Collections.emptySet()

  override def newWriteBuilder(options: CaseInsensitiveStringMap): WriteBuilder = {
    new WriteBuilder with SupportsTruncate {
      private var inputSchema: StructType = _

      override def withInputDataSchema(schema: StructType): WriteBuilder = {
        this.inputSchema = schema
        this
      }

      // Do nothing for truncate. Console sink is special that it just prints all the records.
      override def truncate(): WriteBuilder = this

      override def buildForStreaming(): StreamingWrite = {
        assert(inputSchema != null)
        new ConsoleWrite(inputSchema, options)
      }
    }
  }
}


text:
from migrate import ForeignKeyConstraint
from sqlalchemy import Integer
from sqlalchemy import MetaData, String, Table

from migrate import ForeignKeyConstraint
from nova.openstack.common import log as logging

LOG = logging.getLogger(__name__)

def upgrade(migrate_engine):
    """Convert volume and snapshot id columns from int to varchar."""
    meta = MetaData()
    meta.bind = migrate_engine

    volumes = Table('volumes', meta, autoload=True)
    snapshots = Table('snapshots', meta, autoload=True)
    iscsi_targets = Table('iscsi_targets', meta, autoload=True)
    volume_metadata = Table('volume_metadata', meta, autoload=True)
    sm_volume = Table('sm_volume', meta, autoload=True)
    block_device_mapping = Table('block_device_mapping', meta, autoload=True)

    try:
        fkeys = list(snapshots.c.volume_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[snapshots.c.volume_id],
                    refcolumns=[volumes.c.id],
                    name=fkey_name).drop()

        fkeys = list(iscsi_targets.c.volume_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[iscsi_targets.c.volume_id],
                                 refcolumns=[volumes.c.id],
                                 name=fkey_name).drop()

        fkeys = list(volume_metadata.c.volume_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[volume_metadata.c.volume_id],
                                 refcolumns=[volumes.c.id],
                                 name=fkey_name).drop()

        fkeys = list(sm_volume.c.id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[sm_volume.c.id],
                                 refcolumns=[volumes.c.id],
                                 name=fkey_name).drop()

        fkeys = list(block_device_mapping.c.volume_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[block_device_mapping.c.volume_id],
                                 refcolumns=[volumes.c.id],
                                 name=fkey_name).drop()

        fkeys = list(block_device_mapping.c.snapshot_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[block_device_mapping.c.snapshot_id],
                                 refcolumns=[snapshots.c.id],
                                 name=fkey_name).drop()

    except Exception:
        LOG.error(_("Foreign Key constraint couldn't be removed"))
        raise

    volumes.c.id.alter(String(36), primary_key=True)
    volumes.c.snapshot_id.alter(String(36))
    volume_metadata.c.volume_id.alter(String(36), nullable=False)
    snapshots.c.id.alter(String(36), primary_key=True)
    snapshots.c.volume_id.alter(String(36))
    sm_volume.c.id.alter(String(36))
    block_device_mapping.c.volume_id.alter(String(36))
    block_device_mapping.c.snapshot_id.alter(String(36))
    iscsi_targets.c.volume_id.alter(String(36), nullable=True)

    try:
        fkeys = list(snapshots.c.volume_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[snapshots.c.volume_id],
                    refcolumns=[volumes.c.id],
                    name=fkey_name).create()

        fkeys = list(iscsi_targets.c.volume_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[iscsi_targets.c.volume_id],
                                 refcolumns=[volumes.c.id],
                                 name=fkey_name).create()

        fkeys = list(volume_metadata.c.volume_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[volume_metadata.c.volume_id],
                                 refcolumns=[volumes.c.id],
                                 name=fkey_name).create()

        fkeys = list(sm_volume.c.id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[sm_volume.c.id],
                                 refcolumns=[volumes.c.id],
                                 name=fkey_name).create()
        # NOTE(jdg) We're intentionally leaving off FK's on BDM

    except Exception:
        LOG.error(_("Foreign Key constraint couldn't be removed"))
        raise

def downgrade(migrate_engine):
    """Convert volume and snapshot id columns back to int."""
    meta = MetaData()
    meta.bind = migrate_engine
    dialect = migrate_engine.url.get_dialect().name

    if dialect.startswith('sqlite'):
        return

    volumes = Table('volumes', meta, autoload=True)
    snapshots = Table('snapshots', meta, autoload=True)
    iscsi_targets = Table('iscsi_targets', meta, autoload=True)
    volume_metadata = Table('volume_metadata', meta, autoload=True)
    sm_volume = Table('sm_volume', meta, autoload=True)
    block_device_mapping = Table('block_device_mapping', meta, autoload=True)

    try:
        fkeys = list(snapshots.c.volume_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[snapshots.c.volume_id],
                    refcolumns=[volumes.c.id],
                    name=fkey_name).drop()

        fkeys = list(iscsi_targets.c.volume_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[iscsi_targets.c.volume_id],
                                 refcolumns=[volumes.c.id],
                                 name=fkey_name).drop()

        fkeys = list(volume_metadata.c.volume_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[volume_metadata.c.volume_id],
                                 refcolumns=[volumes.c.id],
                                 name=fkey_name).drop()

        fkeys = list(sm_volume.c.id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[sm_volume.c.id],
                                 refcolumns=[volumes.c.id],
                                 name=fkey_name).drop()

    except Exception:
        LOG.error(_("Foreign Key constraint couldn't be removed"))
        raise

    volumes.c.id.alter(Integer, primary_key=True, autoincrement=True)
    volumes.c.snapshot_id.alter(Integer)
    volume_metadata.c.volume_id.alter(Integer, nullable=False)
    snapshots.c.id.alter(Integer, primary_key=True, autoincrement=True)
    snapshots.c.volume_id.alter(Integer)
    sm_volume.c.id.alter(Integer)
    block_device_mapping.c.volume_id.alter(Integer)
    block_device_mapping.c.snapshot_id.alter(Integer)
    iscsi_targets.c.volume_id.alter(Integer, nullable=True)

    try:
        fkeys = list(snapshots.c.volume_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[snapshots.c.volume_id],
                    refcolumns=[volumes.c.id],
                    name=fkey_name).create()

        fkeys = list(iscsi_targets.c.volume_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[iscsi_targets.c.volume_id],
                                 refcolumns=[volumes.c.id],
                                 name=fkey_name).create()

        fkeys = list(volume_metadata.c.volume_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[volume_metadata.c.volume_id],
                                 refcolumns=[volumes.c.id],
                                 name=fkey_name).create()

        fkeys = list(sm_volume.c.id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[sm_volume.c.id],
                                 refcolumns=[volumes.c.id],
                                 name=fkey_name).create()

        # NOTE(jdg) Put the BDM foreign keys back in place
        fkeys = list(block_device_mapping.c.volume_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[block_device_mapping.c.volume_id],
                                 refcolumns=[volumes.c.id],
                                 name=fkey_name).drop()

        fkeys = list(block_device_mapping.c.snapshot_id.foreign_keys)
        if fkeys:
            fkey_name = fkeys[0].constraint.name
            ForeignKeyConstraint(columns=[block_device_mapping.c.snapshot_id],
                                 refcolumns=[snapshots.c.id],
                                 name=fkey_name).drop()

    except Exception:
        LOG.error(_("Foreign Key constraint couldn't be removed"))
        raise


text:
'use strict';

// Our modules
const app = require('../server');
const createJWT = require('../app/utils/createJWT.server.utils');
const config = require('../config/config');

// External modules
const should = require('should');
const request = require('supertest');
const mongoose = require('mongoose');
const jwt = require('jwt-simple');
const moment = require('moment');

const agent = request.agent(app);

// Models
const Template = mongoose.model('Template');
const Email = mongoose.model('Email');

let template, field, email, token;

// Email routes tests
describe('Email CRUD tests:', () => {

    beforeEach((done) => {

        token = createJWT('abc@ft.com');

        field = {
            label: 'Body',
            name: 'body',
            type: 'wysiwyg',
            options: []
        };

        template = new Template({
            name: 'Editorial',
            path: './templates/example.html',
            from: {
                address: 'email@email.ft.com',
                name: "Financial Times"
            },
            list: 'abcdefg',
            fields: [field]
        });

        template.save(() => {

            email = new Email({
                subject: 'Email subject',
                template: template._id,
                parts:[{
                    name: 'body',
                    value: '
Some body
'
                }],
                createdOn: Date.now()
            });

            done();

        });

    });

    /** POST /eme-emails **/

    it('should be able to save an email', (done) => {
        agent
            .post('/eme-emails')
            .set('Authorization', 'Bearer ' + token)
            .send(email)
            .expect(201)
            .end((emailSaveErr, emailSaveRes) => {

                if (emailSaveErr) {
                    return done(emailSaveErr);
                }

                (emailSaveRes.headers['cache-control']).should.equal('no-cache, no-store');

                Email.find({})
                    .exec((emailFindErr, emailFindRes) => {

                        // Handle emails get error
                        if (emailFindErr) {
                            return done(emailFindErr);
                        }

                        // Set assertions
                        (emailFindRes[0].template).should.match(email.template);

                        done();

                    });

            });

    });

    it('should be able to save an email that has to be sent now', (done) => {

        email = email.toObject();

        email.sendTime = 'now';

        agent
            .post('/eme-emails')
            .set('Authorization', 'Bearer ' + token)
            .send(email)
            .expect(201)
            .end((emailSaveErr, emailSaveRes) => {

                if (emailSaveErr) {
                    return done(emailSaveErr);
                }

                (emailSaveRes.headers['cache-control']).should.equal('no-cache, no-store');

                Email.find({})
                    .exec((emailFindErr, emailFindRes) => {

                        // Handle emails get error
                        if (emailFindErr) {
                            return done(emailFindErr);
                        }

                        // Set assertions
                        (emailFindRes[0].sendTime).should.be.an.instanceOf(Date);

                        done();

                    });

            });

    });

    it('should not be able to save an email if no name is provided', (done) => {
        // Invalidate template field
        email = email.toObject();
        email.template = '';

        agent.post('/eme-emails')
            .set('Authorization', 'Bearer ' + token)
            .send(email)
            .expect(400)
            .end(done);
    });

    it('should not be able to save an email if no auth token is provided', (done) => {

        agent.post('/eme-emails')
            .send(email)
            .expect(401)
            .end((emailSaveErr, emailSaveRes) => {

                should.exist(emailSaveRes);
                (emailSaveRes.body.message).should.equal('Please make sure your request has an Authorization header');

                done(emailSaveErr);

            });
    });

    it('should return an error if the plain text is serialized when saving an email', (done) => {

        email.body = {
            plain: "Some body"
        };

        agent
            .post('/eme-emails')
            .set('Authorization', 'Bearer ' + token)
            .send(email)
            .expect(400)
            .end((emailSaveErr, emailSaveRes) => {

                should.exist(emailSaveRes);
                (emailSaveRes.body.message).should.equal('The plain text body is read-only, it cannot be overridden');

                done(emailSaveErr);

            });

    });

    it('should be able to add the plain text when saving if the email contains an html body', (done) => {

        email.body = {
            html: "
Some body
"
        };

        agent
            .post('/eme-emails')
            .set('Authorization', 'Bearer ' + token)
            .send(email)
            .expect(201)
            .end((emailSaveErr) => {

                if (emailSaveErr) {
                    return done(emailSaveErr);
                }

                Email.find({})
                    .exec((emailFindErr, emailFindRes) => {

                        // Handle emails get error
                        if (emailFindErr) {
                            return done(emailFindErr);
                        }

                        // Set assertions
                        (emailFindRes[0].template).should.match(email.template);
                        (emailFindRes[0].body.plain).should.match('Some body');

                        done();

                    });

            });

    });

    /** GET /eme-emails **/

    it('should be able to get a list of emails', (done) => {

        email.save(() => {

            agent
                .get('/eme-emails')
                .set('Authorization', 'Bearer ' + token)
                .end((emailsGetErr, emailsGetRes) => {

                    // Set assertion
                    (emailsGetRes.headers['cache-control']).should.equal('no-cache, no-store');
                    emailsGetRes.body.should.have.a.lengthOf(1);

                    done(emailsGetErr);
                });

        });
    });

    it('should not be able to get a list of emails if no auth token is provided', (done) => {

        email.save(() => {

            agent
                .get('/eme-emails')
                .expect(401)
                .end((emailsGetErr, emailsGetRes) => {

                    should.exist(emailsGetRes);
                    (emailsGetRes.body.message).should.equal('Please make sure your request has an Authorization header');

                    done(emailsGetErr);

                });

        });
    });

    /** GET /eme-emails/:emailId **/

    it('should be able to get a single email', (done) => {

        email.save(() => {

            agent
                .get('/eme-emails/' + email._id)
                .set('Authorization', 'Bearer ' + token)
                .end((emailGetErr, emailGetRes) => {

                    // Set assertion
                    (emailGetRes.headers['cache-control']).should.equal('no-cache, no-store');
                    emailGetRes.body.should.have.a.property('template');

                    done(emailGetErr);

                });
        });
    });

    it('should not be able to get a single email if no auth token is provided', (done) => {

        email.save(() => {

            agent
                .get('/eme-emails/' + email._id)
                .expect(401)
                .end((emailGetErr, emailGetRes) => {

                    // Set message assertion
                    should.exist(emailGetRes);
                    (emailGetRes.body.message).should.equal('Please make sure your request has an Authorization header');

                    done(emailGetErr);

                });

        });
    });

    /** PATCH /eme-emails/:emailId **/

    it('should be able to patch an email', (done) => {

        email.save(() => {

            let patchEmail = { template: template._id };

            agent
                .patch('/eme-emails/' + email._id)
                .set('Authorization', 'Bearer ' + token)
                .send(patchEmail)
                .expect(200)
                .end((emailPatchErr, emailPatchRes) => {

                    if (emailPatchErr) {
                        done(emailPatchErr);
                    }

                    // Set assertions
                    (emailPatchRes.headers['cache-control']).should.equal('no-cache, no-store');
                    (emailPatchRes.body._id).should.equal(email._id.toString());
                    (emailPatchRes.body.dirty).should.equal(true);

                    // Call the assertion callback
                    done(emailPatchErr);
                });

        });
    });

    it('should be able to patch an email to be sent now', (done) => {

        email.save(() => {

            let patchEmail = { sendTime: 'now' };

            agent
                .patch('/eme-emails/' + email._id)
                .set('Authorization', 'Bearer ' + token)
                .send(patchEmail)
                .expect(200)
                .end((emailPatchErr, emailPatchRes) => {

                    if (emailPatchErr) {
                        done(emailPatchErr);
                    }

                    // Set assertions
                    (emailPatchRes.headers['cache-control']).should.equal('no-cache, no-store');
                    (emailPatchRes.body._id).should.equal(email._id.toString());
                    (new Date(emailPatchRes.body.sendTime)).should.be.an.instanceOf(Date);

                    // Call the assertion callback
                    done(emailPatchErr);
                });

        });
    });

    it('should be able to update the plain text body when receiving a patch with an HTML body', (done) => {

        email.save(() => {

            let patchEmail = { body: { html: '
Some other text
' } };

            agent
                .patch('/eme-emails/' + email._id)
                .set('Authorization', 'Bearer ' + token)
                .send(patchEmail)
                .expect(200)
                .end((emailPatchErr, emailPatchRes) => {

                    if (emailPatchErr) {
                        done(emailPatchErr);
                    }

                    // Set assertions
                    (emailPatchRes.body.body.plain).should.match('Some other text');

                    // Call the assertion callback
                    done(emailPatchErr);
                });

        });
    });

    it('should be able to set an email as not dirty', (done) => {

        email.save(() => {

            let patchEmail = { dirty: false };

            agent
                .patch('/eme-emails/' + email._id)
                .set('Authorization', 'Bearer ' + token)
                .send(patchEmail)
                .expect(200)
                .end((emailPatchErr, emailPatchRes) => {

                    if (emailPatchErr) {
                        done(emailPatchErr);
                    }

                    // Set assertions
                    (emailPatchRes.body.dirty).should.equal(false);

                    // Call the assertion callback
                    done(emailPatchErr);
                });

        });
    });

    it('should return an error if the plain text is serialized when patching an email', (done) => {

        email.save(() => {

            let patchEmail = { body: { plain: 'Some other text' } };

            agent
                .patch('/eme-emails/' + email._id)
                .set('Authorization', 'Bearer ' + token)
                .send(patchEmail)
                .expect(400)
                .end((emailPatchErr, emailPatchRes) => {

                    if (emailPatchErr) {
                        done(emailPatchErr);
                    }

                    // Set assertions
                    (emailPatchRes.body.message).should.match('The plain text body is read-only, it cannot be overridden');

                    // Call the assertion callback
                    done(emailPatchErr);
                });

        });

    });

    it('should not be able to  patch an email if an empty name is provided', (done) => {

        email.save(() => {

            let patchEmail = { template: '' };

            agent
                .patch('/eme-emails/' + email._id)
                .set('Authorization', 'Bearer ' + token)
                .send(patchEmail)
                .expect(400)
                .end((emailPatchErr, emailPatchRes) => {

                    // Set message assertion
                    should.exist(emailPatchRes);
                    (emailPatchRes.body.message).should.equal('Cast to ObjectId failed for value "" at path "template"');

                    // Handle list save error
                    done(emailPatchErr);

                });

        });
    });

    it('should not be able to patch an email if no auth token is provided', (done) => {

        email.save(() => {

            agent
                .patch('/eme-emails/' + email._id)
                .expect(401)
                .end((emailPatchErr, emailPatchRes) => {

                    // Set message assertion
                    should.exist(emailPatchRes);
                    (emailPatchRes.body.message).should.equal('Please make sure your request has an Authorization header');

                    // Handle list save error
                    done(emailPatchErr);

                });

        });
    });

    it('should not be able to patch the content of an email if it has been already scheduled', (done) => {

        email.sendTime = Date.now();

        email.save(() => {

            let patchEmail = { template: '' };

            agent
                .patch('/eme-emails/' + email._id)
                .set('Authorization', 'Bearer ' + token)
                .send(patchEmail)
                .expect(400)
                .end((emailPatchErr, emailPatchRes) => {

                    // Set message assertion
                    should.exist(emailPatchRes);
                    (emailPatchRes.body.message).should.equal('The email is already scheduled, the required property cannot be edited');

                    // Handle list save error
                    done(emailPatchErr);

                });

        });
    });

    it('should not be able to patch the content of an email if it has been already scheduled', (done) => {

        email.sendTime = Date.now();
        email.sent = true;

        email.save(() => {

            let patchEmail = { subject: 'Some subject' };

            agent
                .patch('/eme-emails/' + email._id)
                .set('Authorization', 'Bearer ' + token)
                .send(patchEmail)
                .expect(400)
                .end((emailPatchErr, emailPatchRes) => {

                    // Set message assertion
                    should.exist(emailPatchRes);
                    (emailPatchRes.body.message).should.equal('Cannot patch. The email has already been sent');

                    // Handle list save error
                    done(emailPatchErr);

                });

        });
    });

    /** DELETE /eme-emails/:emailId **/

    it('should be able to delete a email', (done) => {

        email.save(() => {

            agent
                .delete('/eme-emails/' + email._id)
                .set('Authorization', 'Bearer ' + token)
                .send(email)
                .expect(200)
                .end((emailDelErr, emailDelRes) => {

                    if (emailDelErr) {
                        return done(emailDelErr);
                    }

                    (emailDelRes.headers['cache-control']).should.equal('no-cache, no-store');

                    Email.find({})
                        .exec((emailFindErr, emailFindRes) => {

                            // Handle emails get error
                            if (emailFindErr) {
                                return done(emailFindErr);
                            }

                            // Set assertions
                            emailFindRes.should.have.a.lengthOf(0);
                            done();

                        });

                });
        });
    });

    it('should not be able to delete an email if no auth token is provided', (done) => {

        email.save(() => {

            agent
                .delete('/eme-emails/' + email._id)
                .expect(401)
                .end((emailDeleteErr, emailDeleteRes) => {

                    // Set message assertion
                    should.exist(emailDeleteRes);
                    (emailDeleteRes.body.message).should.equal('Please make sure your request has an Authorization header');

                    // Handle list save error
                    done(emailDeleteErr);

                });

        });
    });

    it('returns an error if an invalid _id is provided', (done) => {
        email.save(() => {
            agent
                .get('/eme-emails/' + 'invalidId')
                .set('Authorization', 'Bearer ' + token)
                .expect(400)
                .end((emailGetErr, emailGetRes) => {

                    // Set message assertion
                    should.exist(emailGetRes);
                    (emailGetRes.body.message).should.equal('Email ID is invalid');

                    done(emailGetErr);

                });

        });
    });

    it('returns an error if an invalid _id is provided', (done) => {

        let randomId = '55c8861dfdf6f00300b9f89a';

        email.save(() => {
            agent
                .get('/eme-emails/' + randomId)
                .set('Authorization', 'Bearer ' + token)
                .expect(404)
                .end((emailGetErr, emailGetRes) => {

                    // Set message assertion
                    should.exist(emailGetRes);
                    (emailGetRes.body.message).should.equal('Email not found');

                    done(emailGetErr);

                });

        });
    });

    it('returns an error if an invalid jwt is provided', (done) => {

        let randomJWT = 'abcdefghijklmnopqrstuvwxyz';

        email.save(() => {
            agent
                .get('/eme-emails/')
                .set('Authorization', 'Bearer ' + randomJWT)
                .expect(401)
                .end((emailGetErr, emailGetRes) => {

                    // Set message assertion
                    should.exist(emailGetRes);
                    (emailGetRes.body.message).should.equal('Invalid Token');

                    done(emailGetErr);

                });

        });
    });

    it('returns an error if an expired jwt is provided', (done) => {

        let payload = {
            email: 'abc@ft.com',
            expire: moment().subtract(3, 'hours').unix()
        };

        let expiredJWT = jwt.encode(payload, config.tokenSecret);

        email.save(() => {
            agent
                .get('/eme-emails/')
                .set('Authorization', 'Bearer ' + expiredJWT)
                .expect(401)
                .end((emailGetErr, emailGetRes) => {

                    // Set message assertion
                    should.exist(emailGetRes);
                    (emailGetRes.body.message).should.equal('Token has expired');

                    done(emailGetErr);

                });

        });
    });

    it('allows to specify the a specific pagination returned', (done) => {

        // Create a new email
        let email2 = new Email({
            subject: 'Another Email',
            template: template._id,
            parts:[{
                name: 'body',
                value: '
Some other body
'
            }]
        });

        // Save the user
        email.save(() => {

            email2.save(() => {

                // Request the second email
                agent.get('/eme-emails?pp=1&p=2')
                    .set('Authorization', 'Bearer ' + token)
                    .end((gerEmailErr, getEmailRes) => {

                        // Set assertion
                        getEmailRes.body.should.have.a.lengthOf(1);
                        (getEmailRes.headers['x-page']).should.equal('2');
                        (getEmailRes.headers['x-per-page']).should.equal('1');
                        (getEmailRes.headers['x-total-count']).should.equal('2');

                        // Call the assertion callback
                        done();
                    });
            });

        });

    });

    it('allows to filter emails by template', (done) => {

        // Create another template
        let template2 = new Template({
            name: 'Breaking news',
            path: './templates/example.html',
            from: {
                address: 'email@email.ft.com',
                name: "Financial Times"
            },
            list: 'abcdefg',
            fields: [field]
        });

        template2.save(() => {

            let email2 = new Email({
                subject: 'Another Email',
                template: template2._id,
                parts: [{
                    name: 'body',
                    value: '
Some other body
'
                }]
            });

            // Save the user
            email.save(() => {

                email2.save(() => {

                    // Request the second email
                    agent.get('/eme-emails?t=' + template2._id)
                        .set('Authorization', 'Bearer ' + token)
                        .end((gerEmailErr, getEmailRes) => {

                            // Set assertion
                            getEmailRes.body.should.have.a.lengthOf(1);
                            (getEmailRes.body[0].template._id).should.match(template2._id.toString());

                            // Call the assertion callback
                            done();
                        });
                });

            });

        });

    });

    it('allows to filter emails by the "dirty" property', (done) => {

        let email2 = new Email({
            subject: 'Another Email',
            template: template._id,
            parts: [{
                name: 'body',
                value: '
Some other body
'
            }],
            dirty: true
        });

        // Save the user
        email.save(() => {

            email2.save(() => {

                // Request for the dirty emails
                agent.get('/eme-emails?dirty')
                    .set('Authorization', 'Bearer ' + token)
                    .end((gerEmailErr, getEmailRes) => {

                        // Set assertion
                        getEmailRes.body.should.have.a.lengthOf(1);
                        (getEmailRes.body[0]._id).should.match(email2._id.toString());

                        // Request for the not-dirty emails
                        agent.get('/eme-emails?dirty=false')
                            .set('Authorization', 'Bearer ' + token)
                            .end((gerEmailErr, getEmailRes) => {

                                // Set assertion
                                getEmailRes.body.should.have.a.lengthOf(1);
                                (getEmailRes.body[0]._id).should.match(email._id.toString());

                                // Call the assertion callback
                                done();
                            });
                    });
            });

        });

    });

    it('allows to filter emails by the "sent" property', (done) => {

        let email2 = new Email({
            subject: 'Another Email',
            template: template._id,
            parts: [{
                name: 'body',
                value: '
Some other body
'
            }],
            sent: true
        });

        // Save the user
        email.save(() => {

            email2.save(() => {

                // Request for the sent emails
                agent.get('/eme-emails?sent')
                    .set('Authorization', 'Bearer ' + token)
                    .end((gerEmailErr, getEmailRes) => {

                        // Set assertion
                        getEmailRes.body.should.have.a.lengthOf(1);
                        (getEmailRes.body[0]._id).should.match(email2._id.toString());

                        // Request for the not-sent emails
                        agent.get('/eme-emails?sent=false')
                            .set('Authorization', 'Bearer ' + token)
                            .end((gerEmailErr, getEmailRes) => {

                                // Set assertion
                                getEmailRes.body.should.have.a.lengthOf(1);
                                (getEmailRes.body[0]._id).should.match(email._id.toString());

                                // Call the assertion callback
                                done();
                            });
                    });
            });

        });

    });

    it('allows to filter emails by the "toSubEdit" property', (done) => {

        let email2 = new Email({
            subject: 'Another Email',
            template: template._id,
            parts: [{
                name: 'body',
                value: '
Some other body
'
            }],
            toSubEdit: true
        });

        // Save the user
        email.save(() => {

            email2.save(() => {

                // Request for the toSubEdit emails
                agent.get('/eme-emails?toSubEdit')
                    .set('Authorization', 'Bearer ' + token)
                    .end((gerEmailErr, getEmailRes) => {

                        // Set assertion
                        getEmailRes.body.should.have.a.lengthOf(1);
                        (getEmailRes.body[0]._id).should.match(email2._id.toString());

                        // Request for the not-toSubEdit emails
                        agent.get('/eme-emails?toSubEdit=false')
                            .set('Authorization', 'Bearer ' + token)
                            .end((gerEmailErr, getEmailRes) => {

                                // Set assertion
                                getEmailRes.body.should.have.a.lengthOf(1);
                                (getEmailRes.body[0]._id).should.match(email._id.toString());

                                // Call the assertion callback
                                done();
                            });
                    });
            });

        });

    });

    it('allows to filter emails by the "subEdited" property', (done) => {

        let email2 = new Email({
            subject: 'Another Email',
            template: template._id,
            parts: [{
                name: 'body',
                value: '
Some other body
'
            }],
            subEdited: true
        });

        // Save the user
        email.save(() => {

            email2.save(() => {

                // Request for the subEdited emails
                agent.get('/eme-emails?subEdited')
                    .set('Authorization', 'Bearer ' + token)
                    .end((gerEmailErr, getEmailRes) => {

                        // Set assertion
                        getEmailRes.body.should.have.a.lengthOf(1);
                        (getEmailRes.body[0]._id).should.match(email2._id.toString());

                        // Request for the not-subEdited emails
                        agent.get('/eme-emails?subEdited=false')
                            .set('Authorization', 'Bearer ' + token)
                            .end((gerEmailErr, getEmailRes) => {

                                // Set assertion
                                getEmailRes.body.should.have.a.lengthOf(1);
                                (getEmailRes.body[0]._id).should.match(email._id.toString());

                                // Call the assertion callback
                                done();
                            });
                    });
            });

        });

    });

    it('allows to filter emails that need to be sent now', (done) => {

        let email2 = new Email({
            subject: 'Another Email',
            template: template._id,
            parts: [{
                name: 'body',
                value: '
Some other body
'
            }],
            sendTime: Date.now()
        });

        // Save the user
        email.save(() => {

            email2.save(() => {

                // Request for the emails toSend
                agent.get('/eme-emails?toSend')
                    .set('Authorization', 'Bearer ' + token)
                    .end((gerEmailErr, getEmailRes) => {

                        // Set assertion
                        getEmailRes.body.should.have.a.lengthOf(1);
                        (getEmailRes.body[0]._id).should.match(email2._id.toString());

                        done(gerEmailErr);

                    });
            });

        });

    });

    afterEach((done) => {
        Email.remove()
            .exec(() => Template.remove().exec(done));
    });

});


text:
import DocumentTitle from 'react-document-title';
import Html from './html';
import Promise from 'bluebird';
import React from 'react';
import Router from 'react-router';
import config from './config';
import initialState from './initialstate';
import routes from '../client/routes';
import {state} from '../client/state';

export default function render(req, res, locale) {
  const path = req.path;
  return loadData(path, locale)
    .then((appState) => renderPage(res, appState, path));
}

function loadData(path, locale) {
  // TODO: Preload and merge user specific state.
  const appState = initialState;
  return new Promise((resolve, reject) => {
    resolve(appState);
  });
}

// TODO: Refactor.
function renderPage(res, appState, path) {
  return new Promise((resolve, reject) => {
    const router = Router.create({
      routes,
      location: path,
      onError: reject,
      onAbort: (abortReason) => {
        if (abortReason.constructor.name === 'Redirect') {
          const {to, params, query} = abortReason;
          const path = router.makePath(to, params, query);
          res.redirect(path);
          resolve();
          return;
        }
        reject(abortReason);
      }
    });
    router.run((Handler, routerState) => {
      state.load(appState);
      const html = getPageHtml(Handler, appState);
      const notFound = routerState.routes.some(route => route.name === 'not-found');
      const status = notFound ? 404 : 200;
      res.status(status).send(html);
      resolve();
    });
  });
}

function getPageHtml(Handler, appState) {
  const appHtml = `<div id="app">${React.renderToString(<Handler />)}</div>`;
  const appScriptSrc = config.isProduction
    ? '/build/app.js?v=' + config.version
    : '//localhost:8888/build/app.js';

  let scriptHtml = `
    <script>
      (function() {
        window._appState = ${JSON.stringify(appState)};
        var app = document.createElement('script'); app.type = 'text/javascript'; app.async = true;
        var src = '${appScriptSrc}';
        // IE<11 and Safari need Intl polyfill.
        if (!window.Intl) src = src.replace('.js', 'intl.js');
        app.src = src;
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(app, s);
      })();
    </script>`;

  if (config.isProduction && config.googleAnalyticsId !== 'UA-XXXXXXX-X')
    scriptHtml += `
      <script>
        (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
        function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
        e=o.createElement(i);r=o.getElementsByTagName(i)[0];
        e.src='//www.google-analytics.com/analytics.js';
        r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
        ga('create','${config.googleAnalyticsId}');ga('send','pageview');
      </script>`;

  const title = DocumentTitle.rewind();

  return '<!DOCTYPE html>' + React.renderToStaticMarkup(
    <Html
      bodyHtml={appHtml + scriptHtml}
      isProduction={config.isProduction}
      title={title}
      version={config.version}
    />
  );
}


text:
<!DOCTYPE html>

		<meta charset="utf8"></meta>
		<meta name="generator" content="JsDoc Toolkit"></meta>
		<title>nclosure.examples.animals.CatLike | JsDoc Reference</title>

		<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;"></meta>
		<meta name="mobileoptimized" content="0"></meta>

		<link rel="stylesheet" href="../css/all.css" media="all"></link>
		<link rel="stylesheet" href="../css/handheld.css" media="only screen and (max-width: 660px)"></link>
		<link rel="stylesheet" href="../css/handheld.css" media="handheld"></link>
		<link rel="stylesheet" href="../css/screen.css" media="screen and (min-width: 661px)"></link>

			Classes
			Files

Classes

		<input type="text" name="classFilter" class="classFilter" id="ClassFilter" placeholder="Filter"></input>

nclosure . examples . animals . Cat

nclosure . examples . animals . CatLike

nclosure . examples . animals . Dog

nclosure . examples . animals . Example

nclosure . examples . animals . Monkey

nclosure . examples . animals . Tiger

		Documentation generator: JsDoc Toolkit 2.4.0

		Template: Codeview 1.2

		Generated on: 2011-1-14 23:43

			Class nclosure.examples.animals.CatLike

Defined in: catlike.js

Class Summary

							Constructor Attributes
							Constructor Name and Description

									nclosure.examples.animals.CatLike()

Method Summary

								Method Attributes
								Method Name and Description

talk()

This is a default implementaion of talk for cat like animals, special cats
may want to override this.

						Class Detail

						nclosure.examples.animals.CatLike()

						Method Detail

									talk()

									This is a default implementaion of talk for cat like animals, special cats
may want to override this.


text:
/* eslint-disable no-unused-vars, no-unused-expressions */
/* @flow */
import React from "react";
import { compose, withProps, defaultProps } from "recompose";

import type { HOC } from "recompose";

type EnhancedCompProps = { eA: 1 };

const Comp = ({ hello, eA }) => (
  <div>
    {(hello: string)}
    {(eA: number)}
    {
      // $ExpectError eA nor any nor string
      (eA: string)
    }
    {
      // $ExpectError hello nor any nor number
      (hello: number)
    }
  </div>
);

const enhacer: HOC<*, EnhancedCompProps> = compose(
  defaultProps({
    hello: "world"
  }),
  withProps(props => ({
    hello: (props.hello: string),
    eA: (props.eA: number),
    // $ExpectError hello nor any nor number
    helloErr: (props.hello: number),
    // $ExpectError eA nor any nor string
    eAErr: (props.eA: string)
  })),
  withProps(props => ({
    // $ExpectError property not found
    err: props.iMNotExists
  }))
);

const EnhancedComponent = enhacer(Comp);


text:
@extends('admin.layouts.app')

@section('content')
    @include('admin.errors._messages')

    {!! Form::open(['method'=>'POST', 'action'=>'Admin\ImageCategoryController@store']) !!}
        @include('admin.image_category._form', ['submitButtonText'=>'Add category of images'])
    {!! Form::close() !!}
@stop


text:
package org.frontcache.tests;

public class TestConfig {

	// is used to cleanup generaged fallbacks in FRONTCACHE_HOME_XXX folders
	public static final String FRONTCACHE_TEST_PROJECT_DIR_KEY = "frontcache-tests.home";

	public static final String TEST_DOMAIN_FC1 = "fc1-test.org";

	public static final String TEST_DOMAIN_FC2 = "fc2-test.org";

	public static final String FRONTCACHE_STANDALONE_TEST_BASE_URI_LOCALHOST = "http://localhost:9080/";

	public static final String FRONTCACHE_FILTER_TEST_BASE_URI_LOCALHOST = "http://localhost:8080/";

	public static final String FRONTCACHE_STANDALONE_TEST_BASE_URI_FC1 = "http://www.fc1-test.org:9080/";

	public static final String FRONTCACHE_FILTER_TEST_BASE_URI_FC1 = "http://www.fc1-test.org:8080/";

	public static final String FRONTCACHE_STANDALONE_TEST_BASE_URI_FC2 = "http://www.fc2-test.org:9080/";

	public static final String FRONTCACHE_FILTER_TEST_BASE_URI_FC2 = "http://www.fc2-test.org:8080/";

}


text:
using System;
using Xamarin.Forms;
using Etherify.LightWallet.Helpers;

namespace Etherify.LightWallet.Behaviors
{
	public class PasswordValidationBehavior: Behavior<Entry>
	{
		static readonly BindablePropertyKey IsValidPropertyKey =
			BindableProperty.CreateReadOnly("IsValid", typeof(bool), typeof(RequiredFieldBehavior), false);
		static readonly BindableProperty IsValidProperty = IsValidPropertyKey.BindableProperty;

		public bool IsValid
		{
			get { return (bool)base.GetValue(IsValidProperty); }
			private set { base.SetValue(IsValidPropertyKey, value); }
		}

		static readonly BindablePropertyKey ValidationErrorPropertyKey =
			BindableProperty.CreateReadOnly( "ValidationError", typeof(string), typeof(RequiredFieldBehavior), "");
		static readonly BindableProperty ValidationErrorProperty = ValidationErrorPropertyKey.BindableProperty;

		public string ValidationError
		{
			get { return (string)base.GetValue(ValidationErrorProperty); }
			private set { base.SetValue(ValidationErrorPropertyKey, value); }
		}

		protected override void OnAttachedTo(Entry bindable)
		{
			bindable.TextChanged +=	HandleTextChanged;
			bindable.Unfocused += HandleFocusChanged;
			base.OnAttachedTo(bindable);
		}
		protected override void OnDetachingFrom(Entry bindable)
		{
			bindable.Unfocused -= HandleFocusChanged;
			base.OnDetachingFrom(bindable);
		}

		void HandleTextChanged(object sender, EventArgs e) {
			Validate (((Entry)sender).Text);
		}

		void HandleFocusChanged(object sender, FocusEventArgs e)
		{
			Validate (((Entry)sender).Text);
		}

		void Validate(string password) {
			var helper = new PasswordValidationHelper ();

			this.IsValid = helper.IsValid (password);
			this.ValidationError = helper.ValidationError;
		}
	}
}


text:
h1 {
  font-family: sans-serif;
  font-size: 20px;
}

.unicorn {
  width: 100px;
  height: 100px;
  border: 3px solid purple;
  background-image: url('unicorn1.jpg');
  background-size: cover;
  background-repeat: no-repeat;
}


text:
<!doctype html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/common/get-host-info.sub.js"></script>
<body>

<script>
async_test(t => {
  const iframeURL = new URL("resources/cross-origin-iframe-helper.html", location.href);
  iframeURL.hostname = get_host_info().REMOTE_HOST;
  const iframe = document.createElement("iframe");
  iframe.src = iframeURL;
  iframe.name = "windowname";
  document.body.append(iframe);

  window.onmessage = t.step_func_done(e => {
    // If we hit onnavigate in the target window, we'll get a different message, and fail.
    assert_equals(e.data, "DONE");
  });

  navigation.onnavigate = t.unreached_func("onnavigate must not fire in the source window");
  window.onload = t.step_func(() => window.open(iframeURL + "?postMessage-top-when-done", "windowname"));
}, "using window.open() to navigate cross-document targeting a cross-origin window");
</script>


text:
import netaddr

from fuelmenu.common.errors import BadIPException

def inSameSubnet(ip1, ip2, netmask_or_cidr):
    try:
        cidr1 = netaddr.IPNetwork("%s/%s" % (ip1, netmask_or_cidr))
        cidr2 = netaddr.IPNetwork("%s/%s" % (ip2, netmask_or_cidr))
        return cidr1 == cidr2
    except netaddr.AddrFormatError:
        return False

def getCidr(ip, netmask):
    try:
        ipn = netaddr.IPNetwork("%s/%s" % (ip, netmask))
        return str(ipn.cidr)
    except netaddr.AddrFormatError:
        return False

def getCidrSize(cidr):
    try:
        ipn = netaddr.IPNetwork(cidr)
        return ipn.size
    except netaddr.AddrFormatError:
        return False

def getNetwork(ip, netmask, additionalip=None):
    #Return a list excluding ip and broadcast IPs
    try:
        ipn = netaddr.IPNetwork("%s/%s" % (ip, netmask))
        ipn_list = list(ipn)
        #Drop broadcast and network ip
        ipn_list = ipn_list[1:-1]
        #Drop ip
        ipn_list[:] = [value for value in ipn_list if str(value) != ip]
        #Drop additionalip
        if additionalip:
            ipn_list[:] = [value for value in ipn_list if
                           str(value) != additionalip]

        return ipn_list
    except netaddr.AddrFormatError:
        return False

def range(startip, endip):
    #Return a list of IPs between startip and endip
    try:
        return set(netaddr.iter_iprange(startip, endip))
    except netaddr.AddrFormatError:
        raise BadIPException("Invalid IP address(es) specified.")

def intersects(range1, range2):
    #Returns true if any IPs in range1 exist in range2
    return range1 & range2


text:
package org.apache.bigtop.bigpetstore.datagenerator.generators.store;

import static org.junit.Assert.assertTrue;

import java.util.Arrays;
import java.util.List;

import org.apache.bigtop.bigpetstore.datagenerator.datamodels.Pair;
import org.apache.bigtop.bigpetstore.datagenerator.datamodels.inputs.ZipcodeRecord;
import org.apache.bigtop.bigpetstore.datagenerator.generators.store.StoreLocationIncomePDF;
import org.junit.Test;

public class TestStoreLocationIncomePDF
{

	@Test
	public void testProbability() throws Exception
	{
		List<ZipcodeRecord> zipcodes = Arrays.asList(new ZipcodeRecord[] {
				new ZipcodeRecord("11111", Pair.create(1.0, 1.0), "AZ", "Tempte", 30000.0, 100),
				new ZipcodeRecord("22222", Pair.create(2.0, 2.0), "AZ", "Phoenix", 45000.0, 200),
				new ZipcodeRecord("33333", Pair.create(3.0, 3.0), "AZ", "Flagstaff", 60000.0, 300)
				});

		StoreLocationIncomePDF pdf = new StoreLocationIncomePDF(zipcodes, 100.0);

		for(ZipcodeRecord record : zipcodes)
		{
			assertTrue(pdf.probability(record) > 0.0);
		}

	}

}


text:
import math

def adam(opfunc, x, config, state=None):
    """ An implementation of Adam http://arxiv.org/pdf/1412.6980.pdf

    ARGS:

    - 'opfunc' : a function that takes a single input (X), the point
                of a evaluation, and returns f(X) and df/dX
    - 'x'      : the initial point
    - 'config` : a table with configuration parameters for the optimizer
    - 'config.learningRate'      : learning rate
    - 'config.beta1'             : first moment coefficient
    - 'config.beta2'             : second moment coefficient
    - 'config.epsilon'           : for numerical stability
    - 'config.weightDecay'       : weight decay
    - 'state'                    : a table describing the state of the optimizer; after each
                                call the state is modified

    RETURN:
    - `x`     : the new x vector
    - `f(x)`  : the value of optimized function, evaluated before the update

    """
    # (0) get/update state
    if config is None and state is None:
        raise ValueError("adam requires a dictionary to retain state between iterations")
    state = state if state is not None else config
    lr = config.get('learningRate', 0.001)
    beta1 = config.get('beta1', 0.9)
    beta2 = config.get('beta2', 0.999)
    epsilon = config.get('epsilon', 1e-8)
    wd = config.get('weightDecay', 0)

    # (1) evaluate f(x) and df/dx
    fx, dfdx = opfunc(x)

    # (2) weight decay
    if wd != 0:
        dfdx.add_(wd, x)

    # Initialization
    if 't' not in state:
        state['t'] = 0
        # Exponential moving average of gradient values
        state['m'] = x.new().resize_as_(dfdx).zero_()
        # Exponential moving average of squared gradient values
        state['v'] = x.new().resize_as_(dfdx).zero_()
        # A tmp tensor to hold the sqrt(v) + epsilon
        state['denom'] = x.new().resize_as_(dfdx).zero_()

    state['t'] += 1

    # Decay the first and second moment running average coefficient
    state['m'].mul_(beta1).add_(1 - beta1, dfdx)
    state['v'].mul_(beta2).addcmul_(1 - beta2, dfdx, dfdx)

    state['denom'].copy_(state['v']).sqrt_().add_(epsilon)

    biasCorrection1 = 1 - beta1 ** state['t']
    biasCorrection2 = 1 - beta2 ** state['t']
    stepSize = lr * math.sqrt(biasCorrection2) / biasCorrection1
    # (3) update x
    x.addcdiv_(-stepSize, state['m'], state['denom'])

    # return x*, f(x) before optimization
    return x, fx


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
     Copyright (C) 2011 The Android Open Source Project

     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.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/list_item"
    android:layout_width="match_parent"
    android:layout_height="@dimen/sv__preferred_dropdown_item_height"
    android:minWidth="196dp"
    android:orientation="vertical"
    android:paddingLeft="16dp"
    android:paddingRight="16dp" >

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:drawablePadding="8dp"
        android:duplicateParentState="true"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal"
        android:gravity="center_vertical"
        android:singleLine="true"
        android:textSize="18sp" />

</LinearLayout>


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;

namespace Sharp.Utils.Transactions
{
    /// <summary>
    /// Represents a change to a collection.
    /// </summary>
    /// <typeparam name="T">The type of elements in the collection.</typeparam>
    public class CollectionChange<T> : ICollectionChange<T>
    {
		/// <summary>
        /// Creates a new CollectionChange instance.
		/// </summary>
		/// <param name="inserted">A value that indicates whether the items were added to the list or removed from the list.</param>
		/// <param name="startIndex">The index in the list where the listItems were added or removed.</param>
		/// <param name="items">The list of items that were added or removed.</param>
        public CollectionChange(bool inserted, int startIndex, IReadOnlyCollection<T> items)
		{
            if (items == null)
                throw new ArgumentNullException("listItems");
			Inserted = inserted;
			StartIndex = startIndex;
			Items = items;
		}

		/// <summary>
		/// Gets whether the items were added to the list.
		/// </summary>
        public bool Inserted { get; private set; }

		/// <summary>
		/// Gets whether the items were removed from the list.
		/// </summary>
		public bool Removed
		{
			get { return !Inserted; }
		}

		/// <summary>
        /// Gets the list of items that were added or removed.
		/// </summary>
        public IReadOnlyCollection<T> Items { get; private set; }

		/// <summary>
		/// Gets the start index of the range of items that were added or removed.
		/// </summary>
        public int StartIndex { get; private set; }

        /// <summary>
        /// Gets the end index of the range of items after they were added, or before they were removed.
        /// </summary>
        public int EndIndex
        {
            get { return StartIndex + Items.Count; }
        }
    }
}


text:
Renovate uses the term "presets" to refer to shareable config snippets, similar to ESLint.
Unlike ESLint though:

- Presets may be as small as a list of package names, or as large as a full config
- Shared config files can contain many presets

Presets can be defined using either npm packages, or with GitHub/GitLab repositories.
Only the JSON format is supported.
Bitbucket-hosted presets are yet to be implemented.

## Preset config URIs

In human-understandable form, the rules are:

- A full preset URI consists of package name, preset name, and preset parameters, such as `package:preset(param)`
- If a package scope is specified and no package exists, then the package name is assumed to be `renovate-config`, e.g. `@rarkins:webapp` is expanded to `@rarkins/renovate-config:webapp`
- If a non-scoped package is specified then it is assumed to have the prefix `renovate-config-`. e.g. `rarkins:webapp` is expanded to `renovate-config-rarkins:webapp`
- If a package name is specified and has no preset name, then `default` is assumed, e.g. `@rarkins` expands in full to `@rarkins/renovate-config:default` and `rarkins` expands in full to `renovate-config-rarkins:default`
- There is a special "default" namespace where no package name is necessary. e.g. `:webapp` (not the leading `:`) expands to `renovate-config-default:webapp`

## Supported config syntax

### Scoped

| name                                               | example use                                 | preset    | npm package resolves as      | parameters |
| -------------------------------------------------- | ------------------------------------------- | --------- | ---------------------------- | ---------- |
| scoped                                             | `@somescope`                                | `default` | `@somescope/renovate-config` |            |
| scoped with package name                           | `@somescope/somepackagename`                | `default` | `@somescope/somepackagename` |            |
| scoped with preset name                            | `@somescope:webapp`                         | `webapp`  | `@somescope/renovate-config` |            |
| scoped with param                                  | `@somescope(eslint)`                        | `default` | `@somescope/renovate-config` | `eslint`   |
| scoped with preset name and param                  | `@somescope:webapp(eslint)`                 | `webapp`  | `@somescope/renovate-config` | `eslint`   |
| scoped with package name and preset name           | `@somescope/somepackagename:webapp`         | `webapp`  | `@somescope/somepackagename` |            |
| scoped with package name and preset name and param | `@somescope/somepackagename:webapp(eslint)` | `webapp`  | `@somescope/somepackagename` | `eslint`   |

### Non-scoped

If you use a non-scoped config, you must use a preset name!

| name                                        | example use                                       | preset    | npm package resolves as           | parameters |
| ------------------------------------------- | ------------------------------------------------- | --------- | --------------------------------- | ---------- |
| non-scoped short with preset name           | `somepackagename:default`                         | `default` | `renovate-config-somepackagename` |            |
| non-scoped short with preset name and param | `somepackagename:default(eslint)`                 | `default` | `renovate-config-somepackagename` | `eslint`   |
| non-scoped full with preset name            | `renovate-config-somepackagename:default`         | `default` | `renovate-config-somepackagename` |            |
| non-scoped full with preset name and param  | `renovate-config-somepackagename:default(eslint)` | `default` | `renovate-config-somepackagename` | `eslint`   |

### Git based

In general, GitHub, GitLab or Gitea-based preset hosting is easier than npm because you avoid the "publish" step - simply commit preset code to the default branch and it will be picked up by Renovate the next time it runs.
An additional benefit of using source code hosting is that the same token/authentication can be reused by Renovate in case you want to make your config private.

| name                    | example use          | preset    | resolves as                          | filename                          |
| ----------------------- | -------------------- | --------- | ------------------------------------ | --------------------------------- |
| GitHub default          | `github>abc/foo`     | `default` | `https://github.com/abc/foo`         | `default.json` or `renovate.json` |
| GitHub with preset name | `github>abc/foo:xyz` | `xyz`     | `https://github.com/abc/foo`         | `xyz.json`                        |
| GitLab default          | `gitlab>abc/foo`     | `default` | `https://gitlab.com/abc/foo`         | `default.json` or `renovate.json` |
| GitLab with preset name | `gitlab>abc/foo:xyz` | `xyz`     | `https://gitlab.com/abc/foo`         | `xyz.json`                        |
| Gitea default           | `gitea>abc/foo`      | `default` | `https://gitea.com/abc/foo`          | `default.json` or `renovate.json` |
| Gitea with preset name  | `gitea>abc/foo:xyz`  | `xyz`     | `https://gitea.com/abc/foo`          | `xyz.json`                        |
| Local default           | `local>abc/foo`      | `default` | `https://github.company.com/abc/foo` | `default.json` or `renovate.json` |


text:
Meteor.startup(function() {
  process.env.MAIL_URL = 'smtp://sorpaasemail:email718281@smtp.sendgrid.net:587';
});

Meteor.methods({
  emailTicketChange: function(title, content) {
    Meteor.users.find().forEach(function(user) {
      Email.send({
        from: "info@ticketboard.ns.mg",
        to: user.emails[0].address,
        subject: "[Ticketboard] " + title,
        text: content
      });
      console.log("Email of " + title + " sent to " + user.emails[0].address + ".");
    });
  }
});


text:
/* Client-side router settings */

Router.configure({
  layoutTemplate:"layout",
  notFoundTemplate:"page_not_found",
  loadingTemplate:"loading"
});

Router.route("/", {
  name:"home",
  template:"home"
});

Router.route("/profile", {
  name:"profile",
  template:"profile"
});

Router.route("/admin", {
  name:"admin",
  template:"admin"
});

Router.route("/user/:_id", {
  name:"user",
  template:"user",
  data: function(){
     return Meteor.users.findOne({_id: this.params._id});
  }
});


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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Utilities;
using System.IO;

namespace Microsoft.CodeAnalysis
{
    public static class CommonDiagnosticAnalyzers
    {
        [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
        public class AnalyzerForErrorLogTest : DiagnosticAnalyzer
        {
            public static readonly DiagnosticDescriptor Descriptor1 = new DiagnosticDescriptor(
                "ID1",
                "Title1",
                "Message1",
                "Category1",
                defaultSeverity: DiagnosticSeverity.Warning,
                isEnabledByDefault: true,
                description: "Description1",
                helpLinkUri: "HelpLink1",
                customTags: new[] { "1_CustomTag1", "1_CustomTag2" });

            public static readonly DiagnosticDescriptor Descriptor2 = new DiagnosticDescriptor(
                "ID2",
                "Title2",
                "Message2",
                "Category2",
                defaultSeverity: DiagnosticSeverity.Error,
                isEnabledByDefault: true,
                description: "Description2",
                helpLinkUri: "HelpLink2",
                customTags: new[] { "2_CustomTag1", "2_CustomTag2" });

            private static readonly ImmutableDictionary<string, string> s_properties =
                new Dictionary<string, string> { { "Key1", "Value1" }, { "Key2", "Value2" } }.ToImmutableDictionary();

            public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
            {
                get
                {
                    return ImmutableArray.Create(Descriptor1, Descriptor2);
                }
            }

            public override void Initialize(AnalysisContext context)
            {
                context.RegisterCompilationAction(compilationContext =>
                {
                    // With location diagnostic.
                    var location = compilationContext.Compilation.SyntaxTrees.First().GetRoot().GetLocation();
                    compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor1, location, s_properties));

                    // No location diagnostic.
                    compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor2, Location.None, s_properties));
                });
            }

            private static string GetExpectedPropertiesMapText()
            {
                var isFirst = true;
                var expectedText = @",
        ""customProperties"": {";

                foreach (var kvp in s_properties.OrderBy(kvp => kvp.Key))
                {
                    if (!isFirst)
                    {
                        expectedText += ",";
                    }

                    expectedText += string.Format(@"
          ""{0}"": ""{1}""", kvp.Key, kvp.Value);

                    isFirst = false;
                }

                expectedText += @"
        }";
                return expectedText;
            }

            public static string GetExpectedErrorLogIssuesText(Compilation compilation)
            {
                var tree = compilation.SyntaxTrees.First();
                var root = tree.GetRoot();
                var expectedLineSpan = root.GetLocation().GetLineSpan();
                var filePath = EscapeDirectorySeparatorChar(tree.FilePath);

                return @"
  ""issues"": [
    {
      ""ruleId"": """ + Descriptor1.Id + @""",
      ""locations"": [
        {
          ""analysisTarget"": [
            {
              ""uri"": """ + filePath + @""",
              ""region"": {
                ""startLine"": " + expectedLineSpan.StartLinePosition.Line + @",
                ""startColumn"": " + expectedLineSpan.StartLinePosition.Character + @",
                ""endLine"": " + expectedLineSpan.EndLinePosition.Line + @",
                ""endColumn"": " + expectedLineSpan.EndLinePosition.Character + @"
              }
            }
          ]
        }
      ],
      ""shortMessage"": """ + Descriptor1.MessageFormat + @""",
      ""fullMessage"": """ + Descriptor1.Description + @""",
      ""properties"": {
        ""severity"": """ + Descriptor1.DefaultSeverity + @""",
        ""warningLevel"": ""1"",
        ""defaultSeverity"": """ + Descriptor1.DefaultSeverity + @""",
        ""title"": """ + Descriptor1.Title + @""",
        ""category"": """ + Descriptor1.Category + @""",
        ""helpLink"": """ + Descriptor1.HelpLinkUri + @""",
        ""isEnabledByDefault"": """ + Descriptor1.IsEnabledByDefault + @""",
        ""customTags"": """ + Descriptor1.CustomTags.Join(";") + @"""" +
        GetExpectedPropertiesMapText() + @"
      }
    },
    {
      ""ruleId"": """ + Descriptor2.Id + @""",
      ""locations"": [
      ],
      ""shortMessage"": """ + Descriptor2.MessageFormat + @""",
      ""fullMessage"": """ + Descriptor2.Description + @""",
      ""properties"": {
        ""severity"": """ + Descriptor2.DefaultSeverity + @""",
        ""defaultSeverity"": """ + Descriptor2.DefaultSeverity + @""",
        ""title"": """ + Descriptor2.Title + @""",
        ""category"": """ + Descriptor2.Category + @""",
        ""helpLink"": """ + Descriptor2.HelpLinkUri + @""",
        ""isEnabledByDefault"": """ + Descriptor2.IsEnabledByDefault + @""",
        ""customTags"": """ + Descriptor2.CustomTags.Join(";") + @"""" +
        GetExpectedPropertiesMapText() + @"
      }
    }
  ]
}";
            }

            public static string EscapeDirectorySeparatorChar(string input)
            {
                return input.Replace(Path.DirectorySeparatorChar.ToString(), @"\" + Path.DirectorySeparatorChar);
            }
        }

        [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
        public class NotConfigurableDiagnosticAnalyzer : DiagnosticAnalyzer
        {
            public static readonly DiagnosticDescriptor EnabledRule = new DiagnosticDescriptor(
                "ID1",
                "Title1",
                "Message1",
                "Category1",
                defaultSeverity: DiagnosticSeverity.Warning,
                isEnabledByDefault: true,
                customTags: WellKnownDiagnosticTags.NotConfigurable);

            public static readonly DiagnosticDescriptor DisabledRule = new DiagnosticDescriptor(
                "ID2",
                "Title2",
                "Message2",
                "Category2",
                defaultSeverity: DiagnosticSeverity.Warning,
                isEnabledByDefault: false,
                customTags: WellKnownDiagnosticTags.NotConfigurable);

            public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
            {
                get
                {
                    return ImmutableArray.Create(EnabledRule, DisabledRule);
                }
            }

            public override void Initialize(AnalysisContext context)
            {
                context.RegisterCompilationAction(compilationContext =>
                {
                    // Report enabled diagnostic.
                    compilationContext.ReportDiagnostic(Diagnostic.Create(EnabledRule, Location.None));

                    // Try to report disabled diagnostic.
                    compilationContext.ReportDiagnostic(Diagnostic.Create(DisabledRule, Location.None));
                });
            }
        }

        [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
        public class CodeBlockActionAnalyzer : DiagnosticAnalyzer
        {
            private readonly bool _onlyStatelessAction;

            public CodeBlockActionAnalyzer(bool onlyStatelessAction = false)
            {
                _onlyStatelessAction = onlyStatelessAction;
            }

            public static readonly DiagnosticDescriptor CodeBlockTopLevelRule = new DiagnosticDescriptor(
                "CodeBlockTopLevelRuleId",
                "CodeBlockTopLevelRuleTitle",
                "CodeBlock : {0}",
                "Category",
                defaultSeverity: DiagnosticSeverity.Warning,
                isEnabledByDefault: true);

            public static readonly DiagnosticDescriptor CodeBlockPerCompilationRule = new DiagnosticDescriptor(
                "CodeBlockPerCompilationRuleId",
                "CodeBlockPerCompilationRuleTitle",
                "CodeBlock : {0}",
                "Category",
                defaultSeverity: DiagnosticSeverity.Warning,
                isEnabledByDefault: true);

            public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
            {
                get
                {
                    return ImmutableArray.Create(CodeBlockTopLevelRule, CodeBlockPerCompilationRule);
                }
            }

            public override void Initialize(AnalysisContext context)
            {
                context.RegisterCodeBlockAction(codeBlockContext =>
                {
                    codeBlockContext.ReportDiagnostic(Diagnostic.Create(CodeBlockTopLevelRule, codeBlockContext.OwningSymbol.Locations[0], codeBlockContext.OwningSymbol.Name));
                });

                if (!_onlyStatelessAction)
                {
                    context.RegisterCompilationStartAction(compilationStartContext =>
                    {
                        compilationStartContext.RegisterCodeBlockAction(codeBlockContext =>
                        {
                            codeBlockContext.ReportDiagnostic(Diagnostic.Create(CodeBlockPerCompilationRule, codeBlockContext.OwningSymbol.Locations[0], codeBlockContext.OwningSymbol.Name));
                        });
                    });
                }
            }
        }

        [DiagnosticAnalyzer(LanguageNames.CSharp)]
        public class CSharpGenericNameAnalyzer : DiagnosticAnalyzer
        {
            public const string DiagnosticId = "DiagnosticId";
            public const string Title = "Title";
            public const string Message = "Message";
            public const string Category = "Category";
            public const DiagnosticSeverity Severity = DiagnosticSeverity.Warning;

            internal static DiagnosticDescriptor Rule =
                new DiagnosticDescriptor(DiagnosticId, Title, Message,
                                         Category, Severity, isEnabledByDefault: true);

            public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics =>
                 ImmutableArray.Create(Rule);

            public override void Initialize(AnalysisContext context)
            {
                context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.GenericName);
            }

            private void AnalyzeNode(SyntaxNodeAnalysisContext context)
            {
                context.ReportDiagnostic(Diagnostic.Create(Rule, context.Node.GetLocation()));
            }
        }

        [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
        public sealed class AnalyzerWithNoActions : DiagnosticAnalyzer
        {
            public static readonly DiagnosticDescriptor DummyRule = new DiagnosticDescriptor(
                "ID1",
                "Title1",
                "Message1",
                "Category1",
                defaultSeverity: DiagnosticSeverity.Warning,
                isEnabledByDefault: true);

            public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DummyRule);
            public override void Initialize(AnalysisContext context) { }
        }

        [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
        public sealed class AnalyzerWithNoSupportedDiagnostics : DiagnosticAnalyzer
        {
            public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }
            public override void Initialize(AnalysisContext context) { }
        }

        [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
        public sealed class AnalyzerWithInvalidDiagnosticId : DiagnosticAnalyzer
        {
            public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
                "Invalid ID",
                "Title1",
                "Message1",
                "Category1",
                defaultSeverity: DiagnosticSeverity.Warning,
                isEnabledByDefault: true);

            public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);
            public override void Initialize(AnalysisContext context)
            {
                context.RegisterCompilationAction(compilationContext =>
                    compilationContext.ReportDiagnostic(Diagnostic.Create(Descriptor, Location.None)));
            }
        }

        [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
        public sealed class AnalyzerThatThrowsInGetMessage : DiagnosticAnalyzer
        {
            public static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(
                "ID1",
                "Title1",
                new MyLocalizableStringThatThrows(),
                "Category1",
                defaultSeverity: DiagnosticSeverity.Warning,
                isEnabledByDefault: true);

            public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
            public override void Initialize(AnalysisContext context)
            {
                context.RegisterSymbolAction(symbolContext =>
                {
                    symbolContext.ReportDiagnostic(Diagnostic.Create(Rule, symbolContext.Symbol.Locations[0]));
                }, SymbolKind.NamedType);
            }

            private sealed class MyLocalizableStringThatThrows : LocalizableString
            {
                protected override bool AreEqual(object other)
                {
                    return ReferenceEquals(this, other);
                }

                protected override int GetHash()
                {
                    return 0;
                }

                protected override string GetText(IFormatProvider formatProvider)
                {
                    throw new NotImplementedException();
                }
            }
        }

        [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
        public class HiddenDiagnosticsCompilationAnalyzer : DiagnosticAnalyzer
        {
            public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(
                "ID1000",
                "Description1",
                string.Empty,
                "Analysis",
                DiagnosticSeverity.Hidden,
                true,
                customTags: WellKnownDiagnosticTags.NotConfigurable);

            public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor);

            public override void Initialize(AnalysisContext context)
            {
                context.RegisterCompilationAction(this.OnCompilation);
            }

            private void OnCompilation(CompilationAnalysisContext context)
            {
                // Report the hidden diagnostic on all trees in compilation.
                foreach (var tree in context.Compilation.SyntaxTrees)
                {
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, tree.GetRoot().GetLocation()));
                }
            }
        }
    }
}


text:
angular.module('Test').config(function ($stateProvider, $urlRouterProvider, T_TEST) {
	'use strict';

	$urlRouterProvider
		.otherwise("/");

	$stateProvider
		.state('root', {
			url: "/",
			templateUrl: T_TEST.TEST_TEMPL,
			controller: 'IntegrationTestCtrl'
		})
	;

});


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

  angular.module('PDRClient')
      .controller('AnalysisModalCtrl', AnalysisModalCtrl);

  AnalysisModalCtrl.$inject = [
    '$scope',
    '$state',
    '$timeout',
    '$modal',
    '$modalInstance',
    'RecommendationTextService',
    'SessionService',
    'Analysis',
    'Inventory',
    'preSelectedInventory'
  ];

  function AnalysisModalCtrl($scope, $state, $timeout, $modal, $modalInstance, RecommendationTextService, SessionService, Analysis, Inventory, preSelectedInventory) {
    var vm = this;
    vm.analysis = {};
    vm.alerts = [];
    vm.preSelectedInventory = preSelectedInventory;
    if (vm.preSelectedInventory) {
      vm.analysis.inventory_id = vm.preSelectedInventory.id;
    }

    vm.inventories = [];
    vm.hasFetchedInventories = false;

    vm.userIsNetworkPartner = function() {
      return SessionService.isNetworkPartner();
    };

    vm.titleText = function() {
      return RecommendationTextService.analysisText();
    };

    vm.inventoryText = function() {
      return RecommendationTextService.inventoryText();
    };

    vm.closeModal = function() {
      $modalInstance.close('cancel');
    };

    vm.openInventoryModal = function() {
      vm.closeModal('cancel');
      vm.inventoryModal = $modal.open({
        templateUrl: 'client/home/inventory_modal.html',
        controller: 'InventoryModalCtrl',
        controllerAs: 'inventoryModal'
      });
    };

    vm.gotoAnalyses = function() {
      vm.closeModal();
      $state.go('analyses');
    };

    vm.updateData = function() {
      return vm.updateInventories();
    };

    vm.updateInventories = function() {
      return Inventory.query().$promise.then(function(response) {
        vm.inventories = response;

        // ensure an inventory is always selected unless it was pre-selected
        if (!vm.analysis.inventory_id && vm.inventories.length > 0) {
          vm.analysis.inventory_id = vm.inventories[0].id;
        }

        vm.hasFetchedInventories = true;
      });
    };

    vm.addAlert = function(message) {
      vm.alerts.push({type: 'danger', msg: message});
    };

    vm.closeAlert = function(index) {
      vm.alerts.splice(index, 1);
    };

    vm.hasInventories = function() {
      return vm.hasFetchedInventories && _.any(vm.inventories);
    };

    vm.hasNoInventories = function() {
      return vm.hasFetchedInventories && _.isEmpty(vm.inventories);
    };

    vm.save = function() {
      var deadlineFromDOM = $('#analysis-deadline').val();
      vm.analysis.deadline = moment(deadlineFromDOM, 'MM/DD/YYYY', true).toISOString();
      Analysis.create(null, vm.analysis)
          .$promise
          .then(function(productEntry) {
            vm.closeModal();
            $state.go('inventory_analysis_assign', {inventory_id: productEntry.inventory_id, analysis_id: productEntry.id});
          }, function(response) {
            var errors = response.data.errors;
            angular.forEach(errors, function(error, field) {
              vm.addAlert(field + " : " + error);
            });
          });
    };

    $timeout(function() {
      vm.datetime = $('.datetime').datetimepicker({
        pickTime: false
      });

      vm.datetime.on('dp.change', function() {
        vm.datetime.find('input').trigger('change');
      });

      vm.updateData();
    });

    vm.defaultDate = function(model) {
      if (typeof(model) !== 'undefined') {
        return moment(model.due_date || model.deadline).format('MM/DD/YYYY');
      }
    };

    $scope.$watch('vm.analysis', function(val) {
      vm.date = vm.defaultDate(val);
    }).bind(vm);
  }
})();


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System.Web.Http;
using Microsoft.OData.Edm;

namespace System.Web.OData.Extensions
{
    internal static class HttpConfigurationExtensions
    {
        public static void MapODataServiceRoute(this HttpConfiguration configuration, IEdmModel model)
        {
            configuration.MapODataServiceRoute("IgnoredRouteName", null, model);
        }
    }
}