text:
(function(undefined) {
	var root = this;

	// Weird IE shit, objects do not have hasOwn, but the prototype does...
	var hasOwnProp = Object.prototype.hasOwnProperty;

	// Object cloning function, uses jQuery/Underscore/Object.create depending on what's available

	var clone = function (object) {
		if (typeof Object.hasOwnProperty !== 'undefined') {
			var target = {};
			for (var i in object) {
				if (hasOwnProp.call(object, i)) {
					target[i] = object[i];
				}
			}
			return target;
		}
		if (typeof jQuery !== 'undefined') {
			return jQuery.extend({}, object);
		}
		if (typeof _ !== 'undefined') {
			return _.extend({}, object);
		}
	};

	var Dottie = function() {
		var args = Array.prototype.slice.call(arguments);

		if (args.length == 2) {
			return Dottie.find.apply(this, args);
		}
		return Dottie.transform.apply(this, args);
	};

	// Legacy syntax, changed syntax to have get/set be similar in arg order
	Dottie.find = function(path, object) {
		return Dottie.get(object, path);
	};

	// Dottie memoization flag
	Dottie.memoizePath = true;
	var memoized = {};

	// Traverse object according to path, return value if found - Return undefined if destination is unreachable
	Dottie.get = function(object, path, defaultVal) {
		if ((object === undefined) || (object === null)) return defaultVal;

		var names;

		if (typeof path === "string") {
			if (Dottie.memoizePath) {
				if (memoized[path]) {
					names = memoized[path].slice(0);
				} else {
					names = path.split('.').reverse();
					memoized[path] = names.slice(0);
				}
			} else {
				names = path.split('.').reverse();
			}
		} else if (Array.isArray(path)) {
			names = path.reverse();
		}

		while (names.length && (object = object[names.pop()]) !== undefined && object !== null);

		// Handle cases where accessing a childprop of a null value
		if (object === null && names.length) object = undefined;

		return (object === undefined ? defaultVal : object);
	};

	// Set nested value
	Dottie.set = function(object, path, value) {
		var pieces = Array.isArray(path) ? path : path.split('.'), current = object, piece, length = pieces.length;

		for (var index = 0; index < length; index++) {
			piece = pieces[index];
			if (!hasOwnProp.call(current, piece) || current[piece] === undefined) {
				current[piece] = {};
			}

			if (typeof current !== 'object') throw new Error('Target key is not suitable for a nested value (it is either not undefined or not an object)');

			if (index == (length - 1)) {
				current[piece] = value;
			} else {
				current = current[piece];
			}
		}

		current[piece] = value;
	};

	// Set default nested value
	Dottie['default'] = function(object, path, value) {
		if (Dottie.get(object, path) === undefined) {
			Dottie.set(object, path, value);
		}
	};

	// Transform unnested object with .-seperated keys into a nested object.
	Dottie.transform = function Dottie$transformfunction(object, options) {
		if (Array.isArray(object)) {
			return object.map(function(o) {
				return Dottie.transform(o, options);
			});
		}

		options = options || {};
		options.delimiter = options.delimiter || '.';

		var pieces,
			piecesLength,
			piece,
			current,
			transformed = {},
			key,
			keys = Object.keys(object),
			length = keys.length,
			i;

		for (i = 0; i < length; i++) {
			key = keys[i];

			if (key.indexOf(options.delimiter) !== -1) {
				pieces = key.split(options.delimiter);
				piecesLength = pieces.length;
				current = transformed;

				for (var index = 0; index < piecesLength; index++) {
					piece = pieces[index];
					if (index != (piecesLength - 1) && !current.hasOwnProperty(piece)) {
						current[piece] = {};
					}

					if (index == (piecesLength - 1)) {
						current[piece] = object[key];
					}

					current = current[piece];
					if (current === null) {
						break;
					}
				}
			} else {
				transformed[key] = object[key];
			}
		}

		return transformed;
	};

	Dottie.flatten = function(object, seperator) {
		if (typeof seperator === "undefined") seperator = '.';
		var flattened = {},
			current,
			nested;

		for (var key in object) {
			if (hasOwnProp.call(object, key)) {
				current = object[key];
				if (Object.prototype.toString.call(current) === "[object Object]") {
					nested = Dottie.flatten(current, seperator);

					for (var _key in nested) {
						flattened[key+seperator+_key] = nested[_key];
					}
				} else {
					flattened[key] = current;
				}
			}
		}

		return flattened;
	};

	if (typeof module !== 'undefined' && module.exports) {
		exports = module.exports = Dottie;
	} else {
		root['Dottie'] = Dottie;
		root['Dot'] = Dottie; //BC

		if (typeof define === "function") {
			define([], function () { return Dottie; });
		}
	}
})();


text:
<readable><title>3552796830_2dd2aa9c2c</title><content>
Two men in camouflage pants are running past a parking lot .
Two men in camouflage pants are running past a parking lot .
Two men run through a parking lot wearing camouflage pants .
Two men wearing army pants are running next to a fence .
Two soldiers are running down a track .
</content></readable>

redpajama_set_name: RedPajamaGithub


text:
import Resource from '../resource/Resource'

export default class Response<T> {

    /**
     * Constructor
     * @param resources collection of resources
     * @param status HTTP status code
     */
    constructor(private resources: Resource<T>[], private total: number, private status: number) {
        this.resources = resources
        this.status = status
        this.total = total
    }

    getResources(): Resource<T>[] {
        return this.resources
    }

    getStatus(): number {
        return this.status
    }

    getTotal(): number {
        return this.total
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>org.apache.catalina.ha.authenticator (Apache Tomcat 9.0.0.M11 API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache Tomcat 9.0.0.M11

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.apache.catalina.ha.authenticator

Class Summary

Class
Description

ClusterSingleSignOn

A Valve that supports a "single sign on" user experience on
 each nodes of a cluster, where the security identity of a user who successfully
 authenticates to one web application is propagated to other web applications and
 to other nodes cluster in the same security domain.

ClusterSingleSignOnListener

Cluster extension of SingleSignOnListener that simply adds the marker
 interface ReplicatedSessionListener which allows the listener to be
 replicated across the cluster along with the session.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache Tomcat 9.0.0.M11

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2000-2016 Apache Software Foundation. All Rights Reserved.


text:
<?php

namespace AppBundle\Entity\Document;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use JMS\Serializer\Annotation as Serializer;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;

/**
 * @ORM\Entity
 * @ORM\Table(name="document")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="type", type="string", length=75)
 * @ORM\DiscriminatorMap({
 *     "document__team_logo" = "AppBundle\Entity\Document\TeamLogo",
 *     "document__region_logo" = "LeagueOfLegendsBundle\Entity\Document\RegionLogo"
 * })
 */
abstract class Document
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     *
     * @Serializer\Exclude()
     */
    protected $id;

    /**
     * @var UuidInterface
     *
     * @ORM\Column(name="uuid", type="uuid")
     *
     * @Serializer\Type("string")
     * @Serializer\Groups({
     *     "get_document",
     *     "get_team",
     *     "get_teams",
     *     "league.get_region",
     *     "league.get_regions",
     *     "league.get_players",
     *     "get_player_members",
     * })
     */
    protected $uuid;

    /**
     * @var string
     *
     * @ORM\Column(name="public_id", type="string", length=255)
     *
     * @Serializer\Type("string")
     * @Serializer\Groups({
     *     "get_document",
     *     "get_team",
     *     "get_teams",
     *     "league.get_region",
     *     "league.get_regions",
     *     "league.get_players",
     *     "league.get_search",
     *     "get_player_members",
     * })
     */
    protected $publicId;

    /**
     * @var string
     *
     * @ORM\Column(name="version", type="string", length=255)
     *
     * @Serializer\Type("string")
     * @Serializer\Groups({
     *     "get_document",
     *     "get_team",
     *     "get_teams",
     *     "league.get_region",
     *     "league.get_regions",
     *     "league.get_players",
     *     "league.get_search",
     *     "get_player_members",
     * })
     */
    protected $version;

    /**
     * @var string
     *
     * @ORM\Column(name="url", type="string", length=255)
     *
     * @Serializer\Type("string")
     * @Serializer\Groups({
     *     "get_document",
     *     "get_team",
     *     "get_teams",
     *     "league.get_region",
     *     "league.get_regions",
     *     "league.get_players",
     *     "league.get_search",
     *     "get_player_members",
     *     "get_member",
     * })
     */
    protected $url;

    /**
     * @var \DateTime
     *
     * @Gedmo\Timestampable(on="create")
     *
     * @ORM\Column(name="created_at", type="datetime")
     *
     * @Serializer\Type("DateTime")
     * @Serializer\Groups({
     *     "get_document",
     *     "get_team",
     *     "league.get_region",
     *     "league.get_regions",
     * })
     */
    protected $createdAt;

    public function __construct()
    {
        $this->uuid = Uuid::uuid4();
    }

    public function getUuid(): UuidInterface
    {
        return $this->uuid;
    }

    public function getPublicId(): string
    {
        return $this->publicId;
    }

    public function setPublicId(string $publicId): self
    {
        $this->publicId = $publicId;

        return $this;
    }

    public function getVersion(): string
    {
        return $this->version;
    }

    public function setVersion(string $version): self
    {
        $this->version = $version;

        return $this;
    }

    public function getUrl(): string
    {
        return $this->url;
    }

    public function setUrl(string $url): self
    {
        $this->url = $url;

        return $this;
    }

    public function getCreatedAt(): \DateTime
    {
        return $this->createdAt;
    }

    public function setCreatedAt(\DateTime $createdAt): self
    {
        $this->createdAt = $createdAt;

        return $this;
    }
}


text:
.eeh-menu-bs3-navbar .navbar-right {
  margin-right: 0; }

.eeh-menu-bs3-sidebar {
  border-radius: 0;
  border-top: none;
  border-right: none;
  border-left: none; }
  .eeh-menu-bs3-sidebar > .navbar-collapse {
    padding-right: 0;
    padding-left: 0; }
    .eeh-menu-bs3-sidebar > .navbar-collapse > ul.sidebar-nav {
      /* Indent second level menu items */
      /* Indent third level menu items */ }
      .eeh-menu-bs3-sidebar > .navbar-collapse > ul.sidebar-nav > li > ul > li > a {
        padding-left: 30px; }
      .eeh-menu-bs3-sidebar > .navbar-collapse > ul.sidebar-nav > li > ul > li > ul > li > a {
        padding-left: 45px; }
  .eeh-menu-bs3-sidebar .navbar-default > .active {
    background-color: #e7e7e7;
    color: #e7e7e7; }
  .eeh-menu-bs3-sidebar .sidebar-search .sidebar-search-input a {
    position: relative;
    display: block;
    padding: 10px 15px; }
  .eeh-menu-bs3-sidebar .sidebar-arrow {
    line-height: 1.5em; }
  .eeh-menu-bs3-sidebar .sidebar-nav > li a {
    color: #777; }
    .eeh-menu-bs3-sidebar .sidebar-nav > li a:hover, .eeh-menu-bs3-sidebar .sidebar-nav > li a:focus {
      color: #333;
      background-color: transparent; }
  .eeh-menu-bs3-sidebar .sidebar-nav > .active > a, .eeh-menu-bs3-sidebar .sidebar-nav > .active > a:hover, .eeh-menu-bs3-sidebar .sidebar-nav > .active > a:focus {
    color: #555;
    background-color: #e7e7e7; }
  .eeh-menu-bs3-sidebar .sidebar-nav > .disabled > a, .eeh-menu-bs3-sidebar .sidebar-nav > .disabled > a:hover, .eeh-menu-bs3-sidebar .sidebar-nav > .disabled > a:focus {
    color: #ccc;
    background-color: transparent; }

@media (min-width: 768px) {
  .eeh-menu-bs3-sidebar {
    z-index: 1;
    position: absolute;
    width: 250px; }

  .eeh-menu-bs3-sidebar.sidebar-text-collapsed {
    width: 50px; }

  #eeh-menu-bs3-page-wrapper.sidebar-text-collapsed {
    margin-left: 50px; }

  .sidebar-nav-nested.text-collapsed {
    position: absolute;
    left: 51px;
    top: 0;
    width: 250px;
    background-color: #f8f8f8; }
    .sidebar-nav-nested.text-collapsed a {
      padding-left: 15px !important; }
    .sidebar-nav-nested.text-collapsed .sidebar-nav-nested.text-collapsed {
      position: relative;
      left: 0; }
      .sidebar-nav-nested.text-collapsed .sidebar-nav-nested.text-collapsed a {
        padding-left: 30px !important; } }
#eeh-menu-bs3-page-wrapper {
  padding: 0 15px;
  min-height: 568px;
  background-color: #fff; }

#eeh-menu-bs3-page-wrapper.sidebar-invisible {
  margin-left: 0;
  border-left: none; }

@media (min-width: 768px) {
  #eeh-menu-bs3-page-wrapper {
    position: inherit;
    margin: 0 0 0 250px;
    padding: 0 30px;
    border-left: 1px solid #e7e7e7; } }
.search-input-popover .navbar-form {
  padding: 0;
  margin: 0; }

.eeh-menu-bs3 {
  margin-bottom: 0; }
  .eeh-menu-bs3 a {
    cursor: pointer; }
  .eeh-menu-bs3 .icon-fw {
    width: 1.28571429em;
    text-align: center; }
  .eeh-menu-bs3 .float-right {
    float: right !important;
    margin-right: -10px; }
    .eeh-menu-bs3 .float-right ~ .float-right {
      margin-right: 0; }

/*# sourceMappingURL=eeh-menu-bs3.css.map */


text:
const { existsSync: exists, promises: fs } = require('fs')
const path = require('path')
const c = require('chalk')
const recursiveReadDir = require('../support/fs/recursiveReadDir')

module.exports = async function write(themePath, outDir) {
  const themeName = path.basename(themePath)
  const importMsg = `🗄  Collected files`
  console.time(importMsg)
  let source
  try {
    // eslint-disable-next-line global-require
    source = await import(path.join(themePath, 'index.js'))
  } catch (error) {
    console.warn(c.red('🚫 Unable to import theme', c.bold(themeName)), '... copying instead')
    const files = await recursiveReadDir(themePath, { only: ['json'] })
    for (const file of files) {
      if (!exists(path.join(outDir, themeName))) await fs.mkdir(path.join(outDir, themeName), { recursive: true })
      await fs.copyFile(path.join(themePath, file), path.join(outDir, themeName, file))
    }
  }
  console.timeEnd(importMsg)
  if (source) {
    console.info(`✅ Successfully imported theme`, c.bold(themeName))
    let jsonString
    try {
      jsonString = JSON.stringify(source.default)
    } catch(error) {
      jsonString = JSON.stringify(source)
    }
    // WRITE OUT JSON
    console.log(
      `🏗  ${c.yellow(
        `Building - ${c.blue.bold(themeName)}`
      )}`
    )
    const buildMsg = c.green('build completed in')
    console.time(buildMsg)
    try {
      const outFile = path.join(outDir, path.basename(themePath), `${themeName}.json`)
      if (!exists(path.dirname(outFile))) await fs.mkdir(path.dirname(outFile), { recursive: true })
      await fs.writeFile(
        path.join(outDir, themeName, `${themeName}.json`),
        jsonString,
        'utf8')
    } catch (error) {
      if (error) console.error(error, 'error')
      // clear cache of all files
      await clearCache(await recursiveReadDir(themePath))
    }
    console.timeEnd(buildMsg)
  }
}


text:
package edu.utah.further.core.util.schema;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.w3c.dom.Element;

/**
 * A parser of the Spring schema "further"'s float element.
 *

 * -----------------------------------------------------------------------------------

 * (c) 2008-2013 FURTHeR Project, Health Sciences IT, University of Utah

 * Contact: {@code <further@utah.edu>}

 * Biomedical Informatics, 26 South 2000 East

 * Room 5775 HSEB, Salt Lake City, UT 84112

 * Day Phone: 1-801-581-4080

 * -----------------------------------------------------------------------------------
 *
 * @author Oren E. Livne {@code <oren.livne@utah.edu>}
 * @version Oct 12, 2009
 */
final class FloatBeanDefinitionParser extends AbstractSingleBeanDefinitionParser
{
	// ========================= IMPLEMENTATION: AbstractSingleBeanDefini. =

	/**
	 * @param element
	 * @return
	 * @see org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser#getBeanClass(org.w3c.dom.Element)
	 */
	@Override
	protected Class<?> getBeanClass(final Element element)
	{
		return Float.class;
	}

	/**
	 * @param element
	 * @param bean
	 * @see org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser#doParse(org.w3c.dom.Element,
	 *      org.springframework.beans.factory.support.BeanDefinitionBuilder)
	 */
	@Override
	protected void doParse(final Element element, final BeanDefinitionBuilder bean)
	{
		// this will never be null since the schema explicitly requires that a value be
		// supplied. Therefore we can pass it to the constructor String(String)
		final String pattern = element.getAttribute(CoreSchemaConstants.ATTRIBUTE_VALUE);
		bean.addConstructorArgValue(pattern);
	}
}


text:
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RestaurantProject
{
    public partial class Form5 : Form
    {
        Restaurant restaurant;
        Form parent;

        public Form5(Form p, Restaurant r)
        {
            InitializeComponent();
            parent = p;
            restaurant = r;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Form5_Load(object sender, EventArgs e)
        {
            //Loading dishes from the database
            MySqlCommand cmd = restaurant.callProcedure("Rest_showDishes");
            restaurant.displayGridView(cmd, dataGridView1);

            //Loading beverages from the database
            cmd = restaurant.callProcedure("Rest_showBeverages");
            restaurant.displayGridView(cmd, dataGridView2);
            textBox1.Text = "0";
        }

        private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if(e.RowIndex >= 0)
                dataGridView1.Rows[e.RowIndex].Selected = true;

        }

        private void dataGridView2_CellMouseClick_1(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex >= 0)
                dataGridView2.Rows[e.RowIndex].Selected = true;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            Boolean validInput = false;
            string msg = "Please at least select something ";
            object dishId = null;
            object bvgId = null;
            double total = 0;

            if (dataGridView1.SelectedRows.Count > 0) {
                dishId = (int)dataGridView1.SelectedRows[0].Cells[0].Value;
                total += Convert.ToDouble(dataGridView1.SelectedRows[0].Cells[3].Value);
                validInput = true;
            }

            if (dataGridView2.SelectedRows.Count > 0)
            {
                bvgId = (int)dataGridView2.SelectedRows[0].Cells[0].Value;
                total += Convert.ToDouble(dataGridView2.SelectedRows[0].Cells[3].Value);
                validInput = true;
            }

            int tableNumber;

            if (!(Int32.TryParse(textBox1.Text.Trim(), out tableNumber))&& validInput) {
                validInput = false;
                msg = "Table must be a number";
            }

            string[] parametersName = { "p_emp", "p_tb", "p_dish", "p_bevg", "p_total" };
            object[] parametersValue = { restaurant.Employee.Id, textBox1.Text, dishId, bvgId, total };
            MySqlCommand cmd = restaurant.callProcedure("Rest_NewOrder", parametersName, parametersValue);
            if (cmd.ExecuteNonQuery() != -1 ) {
                MessageBox.Show("New Order added!");
            }

            //clear selected rows
            if(dishId != null)
                dataGridView1.SelectedRows[0].Selected = false;
            if (bvgId != null)
                dataGridView2.SelectedRows[0].Selected = false;

        }

        private void Form5_FormClosed(object sender, FormClosedEventArgs e)
        {
            parent.Show();
        }

        private void buttonMenu_Click(object sender, EventArgs e)
        {
            parent.Show();
            this.Close();
        }

        private void buttonLogout_Click(object sender, EventArgs e)
        {
            this.Close();
            parent.Close();
        }

    }
}


text:
package com.ibm.watson.developer_cloud.concept_insights.v2.model;

import java.util.Date;

import com.google.gson.annotations.SerializedName;
import com.ibm.watson.developer_cloud.service.model.GenericModel;

/**
 * The Class CorpusStats.
 */
public class CorpusStats extends GenericModel {
  private String id;
  @SerializedName("last_updated")
  private Date lastUpdated;
  @SerializedName("top_tags")
  private TopTags topTags;

  /**
   * Gets the id.
   *
   * @return The id
   */
  public String getId() {
    return id;
  }

  /**
   * Gets the last updated.
   *
   * @return The lastUpdated
   */
  public Date getLastUpdated() {
    return lastUpdated;
  }

  /**
   * Gets the top tags.
   *
   * @return The topTags
   */
  public TopTags getTopTags() {
    return topTags;
  }

  /**
   * Sets the id.
   *
   * @param id The id
   */
  public void setId(String id) {
    this.id = id;
  }

  /**
   * Sets the last updated.
   *
   * @param lastUpdated The last_updated
   */
  public void setLastUpdated(Date lastUpdated) {
    this.lastUpdated = lastUpdated;
  }

  /**
   * Sets the top tags.
   *
   * @param topTags The top_tags
   */
  public void setTopTags(TopTags topTags) {
    this.topTags = topTags;
  }
}


text:
package org.wso2.carbon.datasource.ui;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.commons.datasource.DataSourceConstants;
import org.apache.synapse.commons.datasource.DataSourceInformation;
import org.wso2.securevault.secret.SecretInformation;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 *
 */
public class DataSourceManagementHelper {

    private static final Log log = LogFactory.getLog(DataSourceManagementHelper.class);

    /**
     * Factory method to create a DataSourceInformation from HttpServletResuet
     *
     * @param request HttpServletRequest instance
     * @return A DataSourceInformation
     * @throws javax.servlet.ServletException Throws for any error during DataSourceInformation creation
     */
    public static DataSourceInformation createDataSourceInformation(
            HttpServletRequest request) throws ServletException {

        ResourceBundle bundle = ResourceBundle.
                getBundle("org.wso2.carbon.datasource.ui.i18n.Resources",
                        request.getLocale());
        String alias = request.getParameter("alias");
        if (alias == null || "".equals(alias)) {
            alias = request.getParameter("alias_hidden");
            if (alias == null || "".equals(alias)) {
                handleException(bundle.getString("ds.name.cannotfound.msg"));
            }
        }

        String diver = request.getParameter("driver");
        if (diver == null || "".equals(diver)) {
            handleException(bundle.getString("ds.driver.cannotfound.msg"));
        }

        String url = request.getParameter("url");
        if (url == null || "".equals(url)) {
            handleException(bundle.getString("ds.url.cannotfound.msg"));
        }
        DataSourceInformation dataSourceInformation = new DataSourceInformation();

        dataSourceInformation.setAlias(alias.trim());
        dataSourceInformation.setDatasourceName(alias.trim());
        dataSourceInformation.setDriver(diver.trim());
        dataSourceInformation.setUrl(url.trim());

        String user = request.getParameter("user");
        if (user != null && !"".equals(user)) {
            SecretInformation secretInfo;
            if (dataSourceInformation.getSecretInformation() == null) {
                secretInfo = new SecretInformation();
            } else {
                secretInfo = dataSourceInformation.getSecretInformation();
            }
            secretInfo.setUser(user.trim());
            dataSourceInformation.setSecretInformation(secretInfo);
        }
        String password = request.getParameter("password");
        if (password != null && !"".equals(password)) {
            SecretInformation secretInfo;
            if (dataSourceInformation.getSecretInformation() == null) {
                secretInfo = new SecretInformation();
            } else {
                secretInfo = dataSourceInformation.getSecretInformation();
            }
            secretInfo.setAliasSecret(password.trim());
            dataSourceInformation.setSecretInformation(secretInfo);
        }
        String dstype = request.getParameter("dstype");
        if ("peruserds".equals(dstype)) {
            dataSourceInformation.setType("PerUserPoolDataSource");
        }
//        String dsName = request.getParameter("dsName");
//        if (dsName != null && !"".equals(dsName)) {
//            dataSourceInformation.setDatasourceName(dsName.trim());
//        }
        String dsrepotype = request.getParameter("dsrepotype");
        if ("JNDI".equals(dsrepotype)) {
            dataSourceInformation.setRepositoryType(DataSourceConstants.PROP_REGISTRY_JNDI);
            StringBuffer buffer = new StringBuffer();
            buffer.append(DataSourceConstants.PROP_SYNAPSE_PREFIX_DS);
            buffer.append(DataSourceConstants.DOT_STRING);

            buffer.append(alias.trim());
            buffer.append(DataSourceConstants.DOT_STRING);
            // The prefix for root level jndiProperties
            String rootPrefix = buffer.toString();
            // setting naming provider
            Properties jndiEvn = new Properties();

            String icFactory = request.getParameter("icFactory");
            String providerUrl = request.getParameter("providerUrl");
            String providerPort = request.getParameter("providerPort");
            String providerType = request.getParameter("providerType");
            if (icFactory != null && !"".equals(icFactory)) {
                jndiEvn.setProperty(rootPrefix + DataSourceConstants.PROP_IC_FACTORY,
                        icFactory.trim());
            }
            if ("url".equals(providerType)) {
                if (providerUrl != null && !"".equals(providerUrl)) {
                    jndiEvn.setProperty(rootPrefix +
                            DataSourceConstants.PROP_PROVIDER_URL, providerUrl.trim());
                }
            } else {
                if (providerPort != null && !"".equals(providerPort)) {
                    jndiEvn.setProperty(rootPrefix +
                            DataSourceConstants.PROP_PROVIDER_PORT, providerPort.trim());
                }
            }
            dataSourceInformation.setProperties(jndiEvn);
        }
        String autocommit = request.getParameter("autocommit");
        if (autocommit != null && !"".equals(autocommit)) {
            dataSourceInformation.setDefaultAutoCommit(Boolean.parseBoolean(autocommit.trim()));
        }
        String isolation = request.getParameter("isolation");
        if (isolation != null && !"".equals(isolation)) {
            if ("TRANSACTION_NONE".equals(isolation)) {
                dataSourceInformation.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
            } else if ("TRANSACTION_READ_COMMITTED".equals(isolation.trim())) {
                dataSourceInformation.setDefaultTransactionIsolation(
                        Connection.TRANSACTION_READ_COMMITTED);
            } else if ("TRANSACTION_READ_UNCOMMITTED".equals(isolation.trim())) {
                dataSourceInformation.setDefaultTransactionIsolation(
                        Connection.TRANSACTION_READ_UNCOMMITTED);
            } else if ("TRANSACTION_REPEATABLE_READ".equals(isolation.trim())) {
                dataSourceInformation.setDefaultTransactionIsolation(
                        Connection.TRANSACTION_REPEATABLE_READ);
            } else if ("TRANSACTION_SERIALIZABLE".equals(isolation.trim())) {
                dataSourceInformation.setDefaultTransactionIsolation(
                        Connection.TRANSACTION_SERIALIZABLE);
            }
        }
        String maxActive = request.getParameter("maxActive");
        if (maxActive != null && !"".equals(maxActive) && !maxActive.contains("int")) {
            try {
                dataSourceInformation.setMaxActive(Integer.parseInt(maxActive.trim()));
            } catch (NumberFormatException e) {
                handleException(bundle.getString("invalid.maxActive"));
            }
        }
        String maxIdle = request.getParameter("maxIdle");
        if (maxIdle != null && !"".equals(maxIdle) && !maxIdle.contains("int")) {
            try {
                dataSourceInformation.setMaxIdle(Integer.parseInt(maxIdle.trim()));
            } catch (NumberFormatException e) {
                handleException(bundle.getString("invalid.maxidle"));
            }
        }
        String maxopenstatements = request.getParameter("maxopenstatements");
        if (maxopenstatements != null && !"".equals(maxopenstatements) &&
                !maxopenstatements.contains("int")) {
            try {
                dataSourceInformation.setMaxOpenPreparedStatements(
                        Integer.parseInt(maxopenstatements.trim()));
            } catch (NumberFormatException e) {
                handleException(bundle.getString("invalid.MaxOpenStatements"));
            }
        }
        String maxWait = request.getParameter("maxWait");
        if (maxWait != null && !"".equals(maxWait) && !maxWait.contains("long")) {
            try {
                dataSourceInformation.setMaxWait(Long.parseLong(maxWait.trim()));
            } catch (NumberFormatException e) {
                handleException(bundle.getString("invalid.MaxWait"));
            }
        }
        String minIdle = request.getParameter("minIdle");
        if (minIdle != null && !"".equals(minIdle) && !minIdle.contains("int")) {
            try {
                dataSourceInformation.setMinIdle(Integer.parseInt(minIdle.trim()));
            } catch (NumberFormatException e) {
                handleException(bundle.getString("invalid.MinIdle"));
            }
        }
        String initialsize = request.getParameter("initialsize");
        if (initialsize != null && !"".equals(initialsize) && !initialsize.contains("int")) {
            try {
                dataSourceInformation.setInitialSize(Integer.parseInt(initialsize.trim()));
            } catch (NumberFormatException e) {
                handleException(bundle.getString("invalid.Initialsize"));
            }
        }
        String poolstatements = request.getParameter("poolstatements");
        if (poolstatements != null && !"".equals(poolstatements)) {
            dataSourceInformation.setPoolPreparedStatements(
                    Boolean.parseBoolean(poolstatements.trim()));
        }
        String removeAbandoned = request.getParameter("removeAbandoned");
        if (removeAbandoned != null && !"".equals(removeAbandoned)) {
            dataSourceInformation.setRemoveAbandoned(Boolean.parseBoolean(removeAbandoned));
        }
        String removeAbandonedTimeout = request.getParameter("removeAbandonedTimeout");
        if (removeAbandonedTimeout != null && !"".equals(removeAbandonedTimeout)) {
            try {
                dataSourceInformation.setRemoveAbandonedTimeout(
                        Integer.parseInt(removeAbandonedTimeout));
            } catch (NumberFormatException e) {
                handleException(bundle.getString("invalid.remove.abandoned.timeout"));
            }
        }
        String logAbandoned = request.getParameter("logAbandoned");
        if (logAbandoned != null && !"".equals(logAbandoned)) {
            dataSourceInformation.setLogAbandoned(Boolean.parseBoolean(logAbandoned));
        }
        String testonborrow = request.getParameter("testonborrow");
        if (testonborrow != null && !"".equals(testonborrow)) {
            dataSourceInformation.setTestOnBorrow(Boolean.parseBoolean(testonborrow.trim()));
        }
        String testwhileidle = request.getParameter("testwhileidle");
        if (testwhileidle != null && !"".equals(testwhileidle)) {
            dataSourceInformation.setTestWhileIdle(Boolean.parseBoolean(testwhileidle.trim()));
        }
        String validationquery = request.getParameter("validationquery");
        if (validationquery != null && !"".equals(validationquery)) {
            dataSourceInformation.setValidationQuery(validationquery.trim());
        }

        return dataSourceInformation;
    }

    public static String toStringIsolation(int isolation) {
        switch (isolation) {
            case Connection.TRANSACTION_NONE: {
                return "TRANSACTION_NONE";
            }
            case Connection.TRANSACTION_READ_COMMITTED: {
                return "TRANSACTION_READ_COMMITTED";
            }
            case Connection.TRANSACTION_READ_UNCOMMITTED: {
                return "TRANSACTION_READ_UNCOMMITTED";
            }
            case Connection.TRANSACTION_REPEATABLE_READ: {
                return "TRANSACTION_REPEATABLE_READ";
            }
            case Connection.TRANSACTION_SERIALIZABLE: {
                return "TRANSACTION_SERIALIZABLE";
            }
            default: {
                return "TRANSACTION_UNKNOWN";
            }
        }
    }

    public static String getProperty(Properties properties, String name, String defaultValue) {
        if (properties != null) {
            String value = properties.getProperty(name, defaultValue);
            if (value == null) {
                return "";
            }
            return value.trim();
        }
        return defaultValue;
    }

    private static void handleException(String msg) {
        log.error(msg);
        throw new IllegalArgumentException(msg);
    }
}


text:
/*
 * Utilities.h
 *
 *  Created on: Apr 13, 2017
 *      Author: broihier
 */

#ifndef UTILITIES_H_
#define UTILITIES_H_

#include <vector>
#include <string>

class Utilities {
public:
	Utilities();
	virtual ~Utilities();
	static std::vector<std::string> split(std::string sourceString, std::string delimiter);
	static std::string trim(std::string sourceString);
	static void dumpStack();
};

#endif /* UTILITIES_H_ */


text:
(function() {
  var mode = CodeMirror.getMode({tabSize: 4}, "markdown");
  function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
  var modeHighlightFormatting = CodeMirror.getMode({tabSize: 4}, {name: "markdown", highlightFormatting: true});
  function FT(name) { test.mode(name, modeHighlightFormatting, Array.prototype.slice.call(arguments, 1)); }
  var modeAtxNoSpace = CodeMirror.getMode({tabSize: 4}, {name: "markdown", allowAtxHeaderWithoutSpace: true});
  function AtxNoSpaceTest(name) { test.mode(name, modeAtxNoSpace, Array.prototype.slice.call(arguments, 1)); }
  var modeFenced = CodeMirror.getMode({tabSize: 4}, {name: "markdown", fencedCodeBlocks: true});
  function FencedTest(name) { test.mode(name, modeFenced, Array.prototype.slice.call(arguments, 1)); }
  var modeOverrideClasses = CodeMirror.getMode({tabsize: 4}, {
    name: "markdown",
    strikethrough: true,
    tokenTypeOverrides: {
      "header" : "override-header",
      "code" : "override-code",
      "quote" : "override-quote",
      "list1" : "override-list1",
      "list2" : "override-list2",
      "list3" : "override-list3",
      "hr" : "override-hr",
      "image" : "override-image",
      "imageAltText": "override-image-alt-text",
      "imageMarker": "override-image-marker",
      "linkInline" : "override-link-inline",
      "linkEmail" : "override-link-email",
      "linkText" : "override-link-text",
      "linkHref" : "override-link-href",
      "em" : "override-em",
      "strong" : "override-strong",
      "strikethrough" : "override-strikethrough"
  }});
  function TokenTypeOverrideTest(name) { test.mode(name, modeOverrideClasses, Array.prototype.slice.call(arguments, 1)); }
  var modeFormattingOverride = CodeMirror.getMode({tabsize: 4}, {
    name: "markdown",
    highlightFormatting: true,
    tokenTypeOverrides: {
      "formatting" : "override-formatting"
  }});
  function FormatTokenTypeOverrideTest(name) { test.mode(name, modeFormattingOverride, Array.prototype.slice.call(arguments, 1)); }

  FT("formatting_emAsterisk",
     "[em&formatting&formatting-em *][em foo][em&formatting&formatting-em *]");

  FT("formatting_emUnderscore",
     "[em&formatting&formatting-em _][em foo][em&formatting&formatting-em _]");

  FT("formatting_strongAsterisk",
     "[strong&formatting&formatting-strong **][strong foo][strong&formatting&formatting-strong **]");

  FT("formatting_strongUnderscore",
     "[strong&formatting&formatting-strong __][strong foo][strong&formatting&formatting-strong __]");

  FT("formatting_codeBackticks",
     "[comment&formatting&formatting-code `][comment foo][comment&formatting&formatting-code `]");

  FT("formatting_doubleBackticks",
     "[comment&formatting&formatting-code ``][comment foo ` bar][comment&formatting&formatting-code ``]");

  FT("formatting_atxHeader",
     "[header&header-1&formatting&formatting-header&formatting-header-1 # ][header&header-1 foo # bar ][header&header-1&formatting&formatting-header&formatting-header-1 #]");

  FT("formatting_setextHeader",
     "foo",
     "[header&header-1&formatting&formatting-header&formatting-header-1 =]");

  FT("formatting_blockquote",
     "[quote&quote-1&formatting&formatting-quote&formatting-quote-1 > ][quote&quote-1 foo]");

  FT("formatting_list",
     "[variable-2&formatting&formatting-list&formatting-list-ul - ][variable-2 foo]");
  FT("formatting_list",
     "[variable-2&formatting&formatting-list&formatting-list-ol 1. ][variable-2 foo]");

  FT("formatting_link",
     "[link&formatting&formatting-link [][link foo][link&formatting&formatting-link ]]][string&formatting&formatting-link-string&url (][string&url http://example.com/][string&formatting&formatting-link-string&url )]");

  FT("formatting_linkReference",
     "[link&formatting&formatting-link [][link foo][link&formatting&formatting-link ]]][string&formatting&formatting-link-string&url [][string&url bar][string&formatting&formatting-link-string&url ]]]",
     "[link&formatting&formatting-link [][link bar][link&formatting&formatting-link ]]:] [string&url http://example.com/]");

  FT("formatting_linkWeb",
     "[link&formatting&formatting-link <][link http://example.com/][link&formatting&formatting-link >]");

  FT("formatting_linkEmail",
     "[link&formatting&formatting-link <][link user@example.com][link&formatting&formatting-link >]");

  FT("formatting_escape",
     "[formatting-escape \\*]");

  FT("formatting_image",
     "[formatting&formatting-image&image&image-marker !][formatting&formatting-image&image&image-alt-text&link [[][image&image-alt-text&link alt text][formatting&formatting-image&image&image-alt-text&link ]]][formatting&formatting-link-string&string&url (][url&string http://link.to/image.jpg][formatting&formatting-link-string&string&url )]");

  MT("plainText",
     "foo");

  // Don't style single trailing space
  MT("trailingSpace1",
     "foo ");

  // Two or more trailing spaces should be styled with line break character
  MT("trailingSpace2",
     "foo[trailing-space-a  ][trailing-space-new-line  ]");

  MT("trailingSpace3",
     "foo[trailing-space-a  ][trailing-space-b  ][trailing-space-new-line  ]");

  MT("trailingSpace4",
     "foo[trailing-space-a  ][trailing-space-b  ][trailing-space-a  ][trailing-space-new-line  ]");

  // Code blocks using 4 spaces (regardless of CodeMirror.tabSize value)
  MT("codeBlocksUsing4Spaces",
     "    [comment foo]");

  // Code blocks using 4 spaces with internal indentation
  MT("codeBlocksUsing4SpacesIndentation",
     "    [comment bar]",
     "        [comment hello]",
     "            [comment world]",
     "    [comment foo]",
     "bar");

  // Code blocks should end even after extra indented lines
  MT("codeBlocksWithTrailingIndentedLine",
     "    [comment foo]",
     "        [comment bar]",
     "    [comment baz]",
     "    ",
     "hello");

  // Code blocks using 1 tab (regardless of CodeMirror.indentWithTabs value)
  MT("codeBlocksUsing1Tab",
     "\t[comment foo]");

  // No code blocks directly after paragraph
  // http://spec.commonmark.org/0.19/#example-65
  MT("noCodeBlocksAfterParagraph",
     "Foo",
     "    Bar");

  // Inline code using backticks
  MT("inlineCodeUsingBackticks",
     "foo [comment `bar`]");

  // Block code using single backtick (shouldn't work)
  MT("blockCodeSingleBacktick",
     "[comment `]",
     "[comment foo]",
     "[comment `]");

  // Unclosed backticks
  // Instead of simply marking as CODE, it would be nice to have an
  // incomplete flag for CODE, that is styled slightly different.
  MT("unclosedBackticks",
     "foo [comment `bar]");

  // Per documentation: "To include a literal backtick character within a
  // code span, you can use multiple backticks as the opening and closing
  // delimiters"
  MT("doubleBackticks",
     "[comment ``foo ` bar``]");

  // Tests based on Dingus
  // http://daringfireball.net/projects/markdown/dingus
  //
  // Multiple backticks within an inline code block
  MT("consecutiveBackticks",
     "[comment `foo```bar`]");

  // Multiple backticks within an inline code block with a second code block
  MT("consecutiveBackticks",
     "[comment `foo```bar`] hello [comment `world`]");

  // Unclosed with several different groups of backticks
  MT("unclosedBackticks",
     "[comment ``foo ``` bar` hello]");

  // Closed with several different groups of backticks
  MT("closedBackticks",
     "[comment ``foo ``` bar` hello``] world");

  // atx headers
  // http://daringfireball.net/projects/markdown/syntax#header

  MT("atxH1",
     "[header&header-1 # foo]");

  MT("atxH2",
     "[header&header-2 ## foo]");

  MT("atxH3",
     "[header&header-3 ### foo]");

  MT("atxH4",
     "[header&header-4 #### foo]");

  MT("atxH5",
     "[header&header-5 ##### foo]");

  MT("atxH6",
     "[header&header-6 ###### foo]");

  // http://spec.commonmark.org/0.19/#example-24
  MT("noAtxH7",
     "####### foo");

  // http://spec.commonmark.org/0.19/#example-25
  MT("noAtxH1WithoutSpace",
     "#5 bolt");

  // CommonMark requires a space after # but most parsers don't
  AtxNoSpaceTest("atxNoSpaceAllowed_H1NoSpace",
     "[header&header-1 #foo]");

  AtxNoSpaceTest("atxNoSpaceAllowed_H4NoSpace",
     "[header&header-4 ####foo]");

  AtxNoSpaceTest("atxNoSpaceAllowed_H1Space",
     "[header&header-1 # foo]");

  // Inline styles should be parsed inside headers
  MT("atxH1inline",
     "[header&header-1 # foo ][header&header-1&em *bar*]");

  // Setext headers - H1, H2
  // Per documentation, "Any number of underlining ='s or -'s will work."
  // http://daringfireball.net/projects/markdown/syntax#header
  // Ideally, the text would be marked as `header` as well, but this is
  // not really feasible at the moment. So, instead, we're testing against
  // what works today, to avoid any regressions.
  //
  // Check if single underlining = works
  MT("setextH1",
     "foo",
     "[header&header-1 =]");

  // Check if 3+ ='s work
  MT("setextH1",
     "foo",
     "[header&header-1 ===]");

  // Check if single underlining - works
  MT("setextH2",
     "foo",
     "[header&header-2 -]");

  // Check if 3+ -'s work
  MT("setextH2",
     "foo",
     "[header&header-2 ---]");

  // http://spec.commonmark.org/0.19/#example-45
  MT("setextH2AllowSpaces",
     "foo",
     "   [header&header-2 ----      ]");

  // http://spec.commonmark.org/0.19/#example-44
  MT("noSetextAfterIndentedCodeBlock",
     "     [comment foo]",
     "[hr ---]");

  // http://spec.commonmark.org/0.19/#example-51
  MT("noSetextAfterQuote",
     "[quote&quote-1 > foo]",
     "[hr ---]");

  MT("noSetextAfterList",
     "[variable-2 - foo]",
     "[hr ---]");

  // Single-line blockquote with trailing space
  MT("blockquoteSpace",
     "[quote&quote-1 > foo]");

  // Single-line blockquote
  MT("blockquoteNoSpace",
     "[quote&quote-1 >foo]");

  // No blank line before blockquote
  MT("blockquoteNoBlankLine",
     "foo",
     "[quote&quote-1 > bar]");

  // Nested blockquote
  MT("blockquoteSpace",
     "[quote&quote-1 > foo]",
     "[quote&quote-1 >][quote&quote-2 > foo]",
     "[quote&quote-1 >][quote&quote-2 >][quote&quote-3 > foo]");

  // Single-line blockquote followed by normal paragraph
  MT("blockquoteThenParagraph",
     "[quote&quote-1 >foo]",
     "",
     "bar");

  // Multi-line blockquote (lazy mode)
  MT("multiBlockquoteLazy",
     "[quote&quote-1 >foo]",
     "[quote&quote-1 bar]");

  // Multi-line blockquote followed by normal paragraph (lazy mode)
  MT("multiBlockquoteLazyThenParagraph",
     "[quote&quote-1 >foo]",
     "[quote&quote-1 bar]",
     "",
     "hello");

  // Multi-line blockquote (non-lazy mode)
  MT("multiBlockquote",
     "[quote&quote-1 >foo]",
     "[quote&quote-1 >bar]");

  // Multi-line blockquote followed by normal paragraph (non-lazy mode)
  MT("multiBlockquoteThenParagraph",
     "[quote&quote-1 >foo]",
     "[quote&quote-1 >bar]",
     "",
     "hello");

  // Header with leading space after continued blockquote (#3287, negative indentation)
  MT("headerAfterContinuedBlockquote",
     "[quote&quote-1 > foo]",
     "[quote&quote-1 bar]",
     "",
     " [header&header-1 # hello]");

  // Check list types

  MT("listAsterisk",
     "foo",
     "bar",
     "",
     "[variable-2 * foo]",
     "[variable-2 * bar]");

  MT("listPlus",
     "foo",
     "bar",
     "",
     "[variable-2 + foo]",
     "[variable-2 + bar]");

  MT("listDash",
     "foo",
     "bar",
     "",
     "[variable-2 - foo]",
     "[variable-2 - bar]");

  MT("listNumber",
     "foo",
     "bar",
     "",
     "[variable-2 1. foo]",
     "[variable-2 2. bar]");

  MT("listFromParagraph",
     "foo",
     "[variable-2 1. bar]",
     "[variable-2 2. hello]");

  // List after hr
  MT("listAfterHr",
     "[hr ---]",
     "[variable-2 - bar]");

  // List after header
  MT("listAfterHeader",
     "[header&header-1 # foo]",
     "[variable-2 - bar]");

  // hr after list
  MT("hrAfterList",
     "[variable-2 - foo]",
     "[hr -----]");

  // Formatting in lists (*)
  MT("listAsteriskFormatting",
     "[variable-2 * ][variable-2&em *foo*][variable-2  bar]",
     "[variable-2 * ][variable-2&strong **foo**][variable-2  bar]",
     "[variable-2 * ][variable-2&em&strong ***foo***][variable-2  bar]",
     "[variable-2 * ][variable-2&comment `foo`][variable-2  bar]");

  // Formatting in lists (+)
  MT("listPlusFormatting",
     "[variable-2 + ][variable-2&em *foo*][variable-2  bar]",
     "[variable-2 + ][variable-2&strong **foo**][variable-2  bar]",
     "[variable-2 + ][variable-2&em&strong ***foo***][variable-2  bar]",
     "[variable-2 + ][variable-2&comment `foo`][variable-2  bar]");

  // Formatting in lists (-)
  MT("listDashFormatting",
     "[variable-2 - ][variable-2&em *foo*][variable-2  bar]",
     "[variable-2 - ][variable-2&strong **foo**][variable-2  bar]",
     "[variable-2 - ][variable-2&em&strong ***foo***][variable-2  bar]",
     "[variable-2 - ][variable-2&comment `foo`][variable-2  bar]");

  // Formatting in lists (1.)
  MT("listNumberFormatting",
     "[variable-2 1. ][variable-2&em *foo*][variable-2  bar]",
     "[variable-2 2. ][variable-2&strong **foo**][variable-2  bar]",
     "[variable-2 3. ][variable-2&em&strong ***foo***][variable-2  bar]",
     "[variable-2 4. ][variable-2&comment `foo`][variable-2  bar]");

  // Paragraph lists
  MT("listParagraph",
     "[variable-2 * foo]",
     "",
     "[variable-2 * bar]");

  // Multi-paragraph lists
  //
  // 4 spaces
  MT("listMultiParagraph",
     "[variable-2 * foo]",
     "",
     "[variable-2 * bar]",
     "",
     "    [variable-2 hello]");

  // 4 spaces, extra blank lines (should still be list, per Dingus)
  MT("listMultiParagraphExtra",
     "[variable-2 * foo]",
     "",
     "[variable-2 * bar]",
     "",
     "",
     "    [variable-2 hello]");

  // 4 spaces, plus 1 space (should still be list, per Dingus)
  MT("listMultiParagraphExtraSpace",
     "[variable-2 * foo]",
     "",
     "[variable-2 * bar]",
     "",
     "     [variable-2 hello]",
     "",
     "    [variable-2 world]");

  // 1 tab
  MT("listTab",
     "[variable-2 * foo]",
     "",
     "[variable-2 * bar]",
     "",
     "\t[variable-2 hello]");

  // No indent
  MT("listNoIndent",
     "[variable-2 * foo]",
     "",
     "[variable-2 * bar]",
     "",
     "hello");

  MT("listCommonMarkIndentationCode",
     "[variable-2 * Code blocks also affect]",
     "  [variable-3 * The next level starts where the contents start.]",
     "   [variable-3 *    Anything less than that will keep the item on the same level.]",
     "       [variable-3 * Each list item can indent the first level further and further.]",
     "  [variable-3 * For the most part, this makes sense while writing a list.]",
     "    [keyword * This means two items with same indentation can be different levels.]",
     "     [keyword *  Each level has an indent requirement that can change between items.]",
     "       [keyword * A list item that meets this will be part of the next level.]",
     "   [variable-3 * Otherwise, it will be part of the level where it does meet this.]",
     " [variable-2 * World]");

  // Blockquote
  MT("blockquote",
     "[variable-2 * foo]",
     "",
     "[variable-2 * bar]",
     "",
     "    [variable-2&quote&quote-1 > hello]");

  // Code block
  MT("blockquoteCode",
     "[variable-2 * foo]",
     "",
     "[variable-2 * bar]",
     "",
     "        [comment > hello]",
     "",
     "    [variable-2 world]");

  // Code block followed by text
  MT("blockquoteCodeText",
     "[variable-2 * foo]",
     "",
     "    [variable-2 bar]",
     "",
     "        [comment hello]",
     "",
     "    [variable-2 world]");

  // Nested list

  MT("listAsteriskNested",
     "[variable-2 * foo]",
     "",
     "    [variable-3 * bar]");

  MT("listPlusNested",
     "[variable-2 + foo]",
     "",
     "    [variable-3 + bar]");

  MT("listDashNested",
     "[variable-2 - foo]",
     "",
     "    [variable-3 - bar]");

  MT("listNumberNested",
     "[variable-2 1. foo]",
     "",
     "    [variable-3 2. bar]");

  MT("listMixed",
     "[variable-2 * foo]",
     "",
     "    [variable-3 + bar]",
     "",
     "        [keyword - hello]",
     "",
     "            [variable-2 1. world]");

  MT("listBlockquote",
     "[variable-2 * foo]",
     "",
     "    [variable-3 + bar]",
     "",
     "        [quote&quote-1&variable-3 > hello]");

  MT("listCode",
     "[variable-2 * foo]",
     "",
     "    [variable-3 + bar]",
     "",
     "            [comment hello]");

  // Code with internal indentation
  MT("listCodeIndentation",
     "[variable-2 * foo]",
     "",
     "        [comment bar]",
     "            [comment hello]",
     "                [comment world]",
     "        [comment foo]",
     "    [variable-2 bar]");

  // List nesting edge cases
  MT("listNested",
    "[variable-2 * foo]",
    "",
    "    [variable-3 * bar]",
    "",
    "       [variable-3 hello]"
  );
  MT("listNested",
    "[variable-2 * foo]",
    "",
    "    [variable-3 * bar]",
    "",
    "      [keyword * foo]"
  );

  // Code followed by text
  MT("listCodeText",
     "[variable-2 * foo]",
     "",
     "        [comment bar]",
     "",
     "hello");

  // Following tests directly from official Markdown documentation
  // http://daringfireball.net/projects/markdown/syntax#hr

  MT("hrSpace",
     "[hr * * *]");

  MT("hr",
     "[hr ***]");

  MT("hrLong",
     "[hr *****]");

  MT("hrSpaceDash",
     "[hr - - -]");

  MT("hrDashLong",
     "[hr ---------------------------------------]");

  //Images
  MT("Images",
     "[image&image-marker !][image&image-alt-text&link [[alt text]]][string&url (http://link.to/image.jpg)]")

  //Images with highlight alt text
  MT("imageEm",
     "[image&image-marker !][image&image-alt-text&link [[][image-alt-text&em&image&link *alt text*][image&image-alt-text&link ]]][string&url (http://link.to/image.jpg)]");

  MT("imageStrong",
     "[image&image-marker !][image&image-alt-text&link [[][image-alt-text&strong&image&link **alt text**][image&image-alt-text&link ]]][string&url (http://link.to/image.jpg)]");

  MT("imageEmStrong",
     "[image&image-marker !][image&image-alt-text&link [[][image&image-alt-text&em&strong&link ***alt text***][image&image-alt-text&link ]]][string&url (http://link.to/image.jpg)]");

  // Inline link with title
  MT("linkTitle",
     "[link [[foo]]][string&url (http://example.com/ \"bar\")] hello");

  // Inline link without title
  MT("linkNoTitle",
     "[link [[foo]]][string&url (http://example.com/)] bar");

  // Inline link with image
  MT("linkImage",
     "[link [[][link&image&image-marker !][link&image&image-alt-text&link [[alt text]]][string&url (http://link.to/image.jpg)][link ]]][string&url (http://example.com/)] bar");

  // Inline link with Em
  MT("linkEm",
     "[link [[][link&em *foo*][link ]]][string&url (http://example.com/)] bar");

  // Inline link with Strong
  MT("linkStrong",
     "[link [[][link&strong **foo**][link ]]][string&url (http://example.com/)] bar");

  // Inline link with EmStrong
  MT("linkEmStrong",
     "[link [[][link&em&strong ***foo***][link ]]][string&url (http://example.com/)] bar");

  // Image with title
  MT("imageTitle",
     "[image&image-marker !][image&image-alt-text&link [[alt text]]][string&url (http://example.com/ \"bar\")] hello");

  // Image without title
  MT("imageNoTitle",
     "[image&image-marker !][image&image-alt-text&link [[alt text]]][string&url (http://example.com/)] bar");

  // Image with asterisks
  MT("imageAsterisks",
     "[image&image-marker !][image&image-alt-text&link [[ ][image&image-alt-text&em&link *alt text*][image&image-alt-text&link ]]][string&url (http://link.to/image.jpg)] bar");

  // Not a link. Should be normal text due to square brackets being used
  // regularly in text, especially in quoted material, and no space is allowed
  // between square brackets and parentheses (per Dingus).
  MT("notALink",
     "[[foo]] (bar)");

  // Reference-style links
  MT("linkReference",
     "[link [[foo]]][string&url [[bar]]] hello");

  // Reference-style links with Em
  MT("linkReferenceEm",
     "[link [[][link&em *foo*][link ]]][string&url [[bar]]] hello");

  // Reference-style links with Strong
  MT("linkReferenceStrong",
     "[link [[][link&strong **foo**][link ]]][string&url [[bar]]] hello");

  // Reference-style links with EmStrong
  MT("linkReferenceEmStrong",
     "[link [[][link&em&strong ***foo***][link ]]][string&url [[bar]]] hello");

  // Reference-style links with optional space separator (per documentation)
  // "You can optionally use a space to separate the sets of brackets"
  MT("linkReferenceSpace",
     "[link [[foo]]] [string&url [[bar]]] hello");

  // Should only allow a single space ("...use *a* space...")
  MT("linkReferenceDoubleSpace",
     "[[foo]]  [[bar]] hello");

  // Reference-style links with implicit link name
  MT("linkImplicit",
     "[link [[foo]]][string&url [[]]] hello");

  // @todo It would be nice if, at some point, the document was actually
  // checked to see if the referenced link exists

  // Link label, for reference-style links (taken from documentation)

  MT("labelNoTitle",
     "[link [[foo]]:] [string&url http://example.com/]");

  MT("labelIndented",
     "   [link [[foo]]:] [string&url http://example.com/]");

  MT("labelSpaceTitle",
     "[link [[foo bar]]:] [string&url http://example.com/ \"hello\"]");

  MT("labelDoubleTitle",
     "[link [[foo bar]]:] [string&url http://example.com/ \"hello\"] \"world\"");

  MT("labelTitleDoubleQuotes",
     "[link [[foo]]:] [string&url http://example.com/  \"bar\"]");

  MT("labelTitleSingleQuotes",
     "[link [[foo]]:] [string&url http://example.com/  'bar']");

  MT("labelTitleParentheses",
     "[link [[foo]]:] [string&url http://example.com/  (bar)]");

  MT("labelTitleInvalid",
     "[link [[foo]]:] [string&url http://example.com/] bar");

  MT("labelLinkAngleBrackets",
     "[link [[foo]]:] [string&url <http://example.com/>  \"bar\"]");

  MT("labelTitleNextDoubleQuotes",
     "[link [[foo]]:] [string&url http://example.com/]",
     "[string \"bar\"] hello");

  MT("labelTitleNextSingleQuotes",
     "[link [[foo]]:] [string&url http://example.com/]",
     "[string 'bar'] hello");

  MT("labelTitleNextParentheses",
     "[link [[foo]]:] [string&url http://example.com/]",
     "[string (bar)] hello");

  MT("labelTitleNextMixed",
     "[link [[foo]]:] [string&url http://example.com/]",
     "(bar\" hello");

  MT("labelEscape",
     "[link [[foo \\]] ]]:] [string&url http://example.com/]");

  MT("labelEscapeColon",
     "[link [[foo \\]]: bar]]:] [string&url http://example.com/]");

  MT("labelEscapeEnd",
     "[[foo\\]]: http://example.com/");

  MT("linkWeb",
     "[link <http://example.com/>] foo");

  MT("linkWebDouble",
     "[link <http://example.com/>] foo [link <http://example.com/>]");

  MT("linkEmail",
     "[link <user@example.com>] foo");

  MT("linkEmailDouble",
     "[link <user@example.com>] foo [link <user@example.com>]");

  MT("emAsterisk",
     "[em *foo*] bar");

  MT("emUnderscore",
     "[em _foo_] bar");

  MT("emInWordAsterisk",
     "foo[em *bar*]hello");

  MT("emInWordUnderscore",
     "foo_bar_hello");

  // Per documentation: "...surround an * or _ with spaces, it'll be
  // treated as a literal asterisk or underscore."

  MT("emEscapedBySpaceIn",
     "foo [em _bar _ hello_] world");

  MT("emEscapedBySpaceOut",
     "foo _ bar [em _hello_] world");

  MT("emEscapedByNewline",
     "foo",
     "_ bar [em _hello_] world");

  // Unclosed emphasis characters
  // Instead of simply marking as EM / STRONG, it would be nice to have an
  // incomplete flag for EM and STRONG, that is styled slightly different.
  MT("emIncompleteAsterisk",
     "foo [em *bar]");

  MT("emIncompleteUnderscore",
     "foo [em _bar]");

  MT("strongAsterisk",
     "[strong **foo**] bar");

  MT("strongUnderscore",
     "[strong __foo__] bar");

  MT("emStrongAsterisk",
     "[em *foo][em&strong **bar*][strong hello**] world");

  MT("emStrongUnderscore",
     "[em _foo ][em&strong __bar_][strong  hello__] world");

  // "...same character must be used to open and close an emphasis span.""
  MT("emStrongMixed",
     "[em _foo][em&strong **bar*hello__ world]");

  MT("emStrongMixed",
     "[em *foo ][em&strong __bar_hello** world]");

  MT("linkWithNestedParens",
     "[link [[foo]]][string&url (bar(baz))]")

  // These characters should be escaped:
  // \   backslash
  // `   backtick
  // *   asterisk
  // _   underscore
  // {}  curly braces
  // []  square brackets
  // ()  parentheses
  // #   hash mark
  // +   plus sign
  // -   minus sign (hyphen)
  // .   dot
  // !   exclamation mark

  MT("escapeBacktick",
     "foo \\`bar\\`");

  MT("doubleEscapeBacktick",
     "foo \\\\[comment `bar\\\\`]");

  MT("escapeAsterisk",
     "foo \\*bar\\*");

  MT("doubleEscapeAsterisk",
     "foo \\\\[em *bar\\\\*]");

  MT("escapeUnderscore",
     "foo \\_bar\\_");

  MT("doubleEscapeUnderscore",
     "foo \\\\[em _bar\\\\_]");

  MT("escapeHash",
     "\\# foo");

  MT("doubleEscapeHash",
     "\\\\# foo");

  MT("escapeNewline",
     "\\",
     "[em *foo*]");

  // Class override tests
  TokenTypeOverrideTest("overrideHeader1",
    "[override-header&override-header-1 # Foo]");

  TokenTypeOverrideTest("overrideHeader2",
    "[override-header&override-header-2 ## Foo]");

  TokenTypeOverrideTest("overrideHeader3",
    "[override-header&override-header-3 ### Foo]");

  TokenTypeOverrideTest("overrideHeader4",
    "[override-header&override-header-4 #### Foo]");

  TokenTypeOverrideTest("overrideHeader5",
    "[override-header&override-header-5 ##### Foo]");

  TokenTypeOverrideTest("overrideHeader6",
    "[override-header&override-header-6 ###### Foo]");

  TokenTypeOverrideTest("overrideCode",
    "[override-code `foo`]");

  TokenTypeOverrideTest("overrideCodeBlock",
    "[override-code ```]",
    "[override-code foo]",
    "[override-code ```]");

  TokenTypeOverrideTest("overrideQuote",
    "[override-quote&override-quote-1 > foo]",
    "[override-quote&override-quote-1 > bar]");

  TokenTypeOverrideTest("overrideQuoteNested",
    "[override-quote&override-quote-1 > foo]",
    "[override-quote&override-quote-1 >][override-quote&override-quote-2 > bar]",
    "[override-quote&override-quote-1 >][override-quote&override-quote-2 >][override-quote&override-quote-3 > baz]");

  TokenTypeOverrideTest("overrideLists",
    "[override-list1 - foo]",
    "",
    "    [override-list2 + bar]",
    "",
    "        [override-list3 * baz]",
    "",
    "            [override-list1 1. qux]",
    "",
    "                [override-list2 - quux]");

  TokenTypeOverrideTest("overrideHr",
    "[override-hr * * *]");

  TokenTypeOverrideTest("overrideImage",
    "[override-image&override-image-marker !][override-image&override-image-alt-text&link [[alt text]]][override-link-href&url (http://link.to/image.jpg)]");

  TokenTypeOverrideTest("overrideLinkText",
    "[override-link-text [[foo]]][override-link-href&url (http://example.com)]");

  TokenTypeOverrideTest("overrideLinkEmailAndInline",
    "[override-link-email <][override-link-inline foo@example.com>]");

  TokenTypeOverrideTest("overrideEm",
    "[override-em *foo*]");

  TokenTypeOverrideTest("overrideStrong",
    "[override-strong **foo**]");

  TokenTypeOverrideTest("overrideStrikethrough",
    "[override-strikethrough ~~foo~~]");

  FormatTokenTypeOverrideTest("overrideFormatting",
    "[override-formatting-escape \\*]");

  // Tests to make sure GFM-specific things aren't getting through

  MT("taskList",
     "[variable-2 * [ ]] bar]");

  MT("noFencedCodeBlocks",
     "~~~",
     "foo",
     "~~~");

  FencedTest("fencedCodeBlocks",
     "[comment ```]",
     "[comment foo]",
     "[comment ```]",
     "bar");

  FencedTest("fencedCodeBlocksMultipleChars",
     "[comment `````]",
     "[comment foo]",
     "[comment ```]",
     "[comment foo]",
     "[comment `````]",
     "bar");

  FencedTest("fencedCodeBlocksTildes",
     "[comment ~~~]",
     "[comment foo]",
     "[comment ~~~]",
     "bar");

  FencedTest("fencedCodeBlocksTildesMultipleChars",
     "[comment ~~~~~]",
     "[comment ~~~]",
     "[comment foo]",
     "[comment ~~~~~]",
     "bar");

  FencedTest("fencedCodeBlocksMultipleChars",
     "[comment `````]",
     "[comment foo]",
     "[comment ```]",
     "[comment foo]",
     "[comment `````]",
     "bar");

  FencedTest("fencedCodeBlocksMixed",
     "[comment ~~~]",
     "[comment ```]",
     "[comment foo]",
     "[comment ~~~]",
     "bar");

  // Tests that require XML mode

  MT("xmlMode",
     "[tag&bracket <][tag div][tag&bracket >]",
     "*foo*",
     "[tag&bracket <][tag http://github.com][tag&bracket />]",
     "[tag&bracket </][tag div][tag&bracket >]",
     "[link <http://github.com/>]");

  MT("xmlModeWithMarkdownInside",
     "[tag&bracket <][tag div] [attribute markdown]=[string 1][tag&bracket >]",
     "[em *foo*]",
     "[link <http://github.com/>]",
     "[tag </div>]",
     "[link <http://github.com/>]",
     "[tag&bracket <][tag div][tag&bracket >]",
     "[tag&bracket </][tag div][tag&bracket >]");

})();


text:
class PhoneFormatValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    if not value =~ /^([0-9\.+ -]+)$/i
      record.errors.add(attribute, 'should only contain digits, period, plus sign, hyphen, and spaces')
    end
    if value.gsub(/\D/, '').length > 10
      record.errors.add(attribute, 'contains more than 10 numbers.  Please fix.')
    end
    if value.gsub(/\D/, '').length < 10
      record.errors.add(attribute, 'contains fewer than 10 numbers.  Please fix.')
    end
  end
end


text:
using System;
using System.Threading;

namespace Renci.SshNet
{
    internal class ForwardedPortStatus
    {
        private readonly int _value;
        private readonly string _name;

        public static readonly ForwardedPortStatus Stopped = new ForwardedPortStatus(1, "Stopped");
        public static readonly ForwardedPortStatus Stopping = new ForwardedPortStatus(2, "Stopping");
        public static readonly ForwardedPortStatus Started = new ForwardedPortStatus(3, "Started");
        public static readonly ForwardedPortStatus Starting = new ForwardedPortStatus(4, "Starting");

        private ForwardedPortStatus(int value, string name)
        {
            _value = value;
            _name = name;
        }

        public override bool Equals(object other)
        {
            if (ReferenceEquals(other, null))
                return false;

            if (ReferenceEquals(this, other))
                return true;

            var forwardedPortStatus = other as ForwardedPortStatus;
            if (forwardedPortStatus == null)
                return false;

            return forwardedPortStatus._value == _value;
        }

        public static bool operator ==(ForwardedPortStatus left, ForwardedPortStatus right)
        {
            // check if lhs is null
            if (ReferenceEquals(left, null))
            {
                // check if both lhs and rhs are null
                return (ReferenceEquals(right, null));
            }

            return left.Equals(right);
        }

        public static bool operator !=(ForwardedPortStatus left, ForwardedPortStatus right)
        {
            return !(left==right);
        }

        public override int GetHashCode()
        {
            return _value;
        }

        public override string ToString()
        {
            return _name;
        }

        /// <summary>
        /// Returns a value indicating whether <paramref name="status"/> has been changed to <see cref="Stopping"/>.
        /// </summary>
        /// <param name="status">The status to transition from.</param>
        /// <returns>
        /// <c>true</c> if <paramref name="status"/> has been changed to <see cref="Stopping"/>; otherwise, <c>false</c>.
        /// </returns>
        /// <exception cref="InvalidOperationException">Cannot transition <paramref name="status"/> to <see cref="Stopping"/>.</exception>
        /// <remarks>
        /// While a transition from <see cref="Stopped"/> to <see cref="Stopping"/> is not possible, this method will
        /// return <c>false</c> for any such attempts.  This is related to concurrency.
        /// </remarks>
        public static bool ToStopping(ref ForwardedPortStatus status)
        {
            // attempt to transition from Started to Stopping
            var previousStatus = Interlocked.CompareExchange(ref status, Stopping, Started);
            if (previousStatus == Stopping || previousStatus == Stopped)
            {
                // status is already Stopping or Stopped, so no transition to Stopping is necessary
                return false;
            }

            // we've successfully transitioned from Started to Stopping
            if (status == Stopping)
                return true;

            // attempt to transition from Starting to Stopping
            previousStatus = Interlocked.CompareExchange(ref status, Stopping, Starting);
            if (previousStatus == Stopping || previousStatus == Stopped)
            {
                // status is already Stopping or Stopped, so no transition to Stopping is necessary
                return false;
            }

            // we've successfully transitioned from Starting to Stopping
            if (status == Stopping)
                return true;

            // there's no valid transition from status to Stopping
            throw new InvalidOperationException(string.Format("Forwarded port cannot transition from '{0}' to '{1}'.",
                                                              previousStatus,
                                                              Stopping));
        }

        /// <summary>
        /// Returns a value indicating whether <paramref name="status"/> has been changed to <see cref="Starting"/>.
        /// </summary>
        /// <param name="status">The status to transition from.</param>
        /// <returns>
        /// <c>true</c> if <paramref name="status"/> has been changed to <see cref="Starting"/>; otherwise, <c>false</c>.
        /// </returns>
        /// <exception cref="InvalidOperationException">Cannot transition <paramref name="status"/> to <see cref="Starting"/>.</exception>
        /// <remarks>
        /// While a transition from <see cref="Started"/> to <see cref="Starting"/> is not possible, this method will
        /// return <c>false</c> for any such attempts.  This is related to concurrency.
        /// </remarks>
        public static bool ToStarting(ref ForwardedPortStatus status)
        {
            // attemp to transition from Stopped to Starting
            var previousStatus = Interlocked.CompareExchange(ref status, Starting, Stopped);
            if (previousStatus == Starting || previousStatus == Started)
            {
                // port is already Starting or Started, so no transition to Starting is necessary
                return false;
            }

            // we've successfully transitioned from Stopped to Starting
            if (status == Starting)
                return true;

            // there's no valid transition from status to Starting
            throw new InvalidOperationException(string.Format("Forwarded port cannot transition from '{0}' to '{1}'.",
                                                              previousStatus,
                                                              Starting));
        }
    }
}


text:
from __future__ import print_function
from hashlib import sha1
from subprocess import Popen, PIPE, STDOUT

data = open("index.html", "r").read()

for line in open("cmds.txt", "r"):
    line = line.strip()
    p = Popen(['pup', line], stdout=PIPE, stdin=PIPE, stderr=PIPE)
    h = sha1()
    h.update(p.communicate(input=data)[0])
    print("%s %s" % (h.hexdigest(), line))


text:
<?xml version="1.0" encoding="utf-8"?>
<products xmlns:xlink="http://www.w3.org/1999/xlink">
   <latestpdf>MidoNet_Quick_Start_Guide_Ubuntu-1404_Liberty_EN_5.0-rev2-latest.pdf</latestpdf>
   <pdfoutname>MidoNet_Quick_Start_Guide_Ubuntu-1404_Liberty_EN_5.0-rev2.pdf</pdfoutname>
   <docname>MidoNet Quick Start Guide for Ubuntu 14.04 / Liberty</docname>
   <productname>MidoNet Quick Start Guide</productname>
   <webappname>quick-start-guide/ubuntu-1404_liberty_en</webappname>
   <pominfo>
      <groupid>org.midonet</groupid>
      <artifactid>midonet-docs-quick-start-guide-ubuntu-1404-liberty-en</artifactid>
      <version>5.0-rev2</version>
      <pomname>midonet-docs-quick-start-guide-ubuntu-1404-liberty-en v5.0-rev2</pomname>
   </pominfo>
</products>


text:
from xml.etree import ElementTree

import openerp
from openerp.addons.web.controllers.main import load_actions_from_ir_values

class Board(openerp.addons.web.http.Controller):
    _cp_path = '/board'

    @openerp.addons.web.http.jsonrequest
    def add_to_dashboard(self, req, menu_id, action_id, context_to_save, domain, view_mode, name=''):
        # FIXME move this method to board.board model
        dashboard_action = load_actions_from_ir_values(
            req, 'action', 'tree_but_open', [('ir.ui.menu', menu_id)], False)

        if dashboard_action:
            action = dashboard_action[0][2]
            if action['res_model'] == 'board.board' and action['views'][0][1] == 'form':
                # Maybe should check the content instead of model board.board ?
                view_id = action['views'][0][0]
                board = req.session.model(action['res_model']).fields_view_get(view_id, 'form')
                if board and 'arch' in board:
                    xml = ElementTree.fromstring(board['arch'])
                    column = xml.find('./board/column')
                    if column is not None:
                        new_action = ElementTree.Element('action', {
                            'name': str(action_id),
                            'string': name,
                            'view_mode': view_mode,
                            'context': str(context_to_save),
                            'domain': str(domain)
                        })
                        column.insert(0, new_action)
                        arch = ElementTree.tostring(xml, 'utf-8')
                        return req.session.model('ir.ui.view.custom').create({
                            'user_id': req.session._uid,
                            'ref_id': view_id,
                            'arch': arch
                        }, req.context)

        return False


text:
```none
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

https://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.
```

# How to Write a Tensorflow Probability Distribution

This document is primarily aimed at authors wishing to add one or more
Distribution classes to this directory, but it should also be useful to
people writing unofficial Distributions, especially if they wish those
classes to interoperate with TFP code (such as `Mixture` or `JointDistribution`).

Here are the steps:

1. Can your distribution be implemented as a change of variables of an
existing distribution?  If so, doing it that way can save you a lot of work.
You will just need `__init__` and `_parameter_properties` methods, and the
`__init__` should end with a `super.__init__` call that looks like

  ```python
  super(MyDistribution, self).__init__(
    distribution=OtherDistribution(param1=param1, param2=param2,
                                   validate_args=validate_args,
                                   allow_nan_stats=allow_nan_stats),
    bijector=bijector_or_invert_bijector_that_does_the_transformation,
    validate_args=validate_args,
    parameters=parameters,
    name=name
    )
  )
  ```

See [chi.py](https://github.com/tensorflow/probability/blob/main/tensorflow_probability/python/distributions/chi.py)
for an example of this technique.

1. Write a class inheriting from `tfp.distributions.Distribution` or a
sub-class of such:

    ```python
    from tensorflow_probability.python.distributions import distribution
    from tensorflow_probability.python.internal import parameter_properties

    class MyDistribution(distribution.Distribution):
    ```

1. Give your class an `__init__` method.  Besides the arguments needed to
specify the distribution, the `__init__` method should also take
`validate_args`, `allow_nan_stats`, and `name` arguments:

    ```python
    def __init__(self,
                 loc, scale, kurtosis,
                 validate_args=False,
                 allow_nan_stats=True,
                 name='MyDistribution):
      """Initialize a MyDistribution distribution.

      Longer description of MyDistribution.

      Args:
        Document each __init__ argument.

      Raises:
        Specify here if it does.
    ```

    You are strongly encouraged to use English names (`scale`, `total_count`,
    `rate`, ...) for your `__init__` parameters instead of Greek
    (`mu`, `lambda`, `alpha`, ...).

    Your `__init__` method doesn't actually need to do much work other than
    save the passed parameters and perform some static checks on their
    validity.  If `validate_args` is True, you can and should also perform
    dynamic validity checks.

1. Call your class's parent's `__init__` at the end of your `__init__`:

    ```python
    def __init__(self, ...):
      parameters=dict(locals())
      ...

      super().__init__(
        dtype=the_dtype_MyDistribution_returns_for_samples,
        reparameterization_type= # either tfd.FULLY_REPARAMETERIZED or
                                 #        tfd.NOT_REPARAMETERIZED,
        validate_args, allow_nan_stats,
        parameters=parameters
        name=name)
    ```
    Note that if you subclass from a Distribution that does not have a
    `parameters` argument in its `__init__`, you will need to set
    `self._parameters` in your own `__init__`, after calling `super().__init__`.

1. Give your class a class comment describing the distribution.  Be sure
to give some examples of creating and using the class.

1. Give your class a `_parameter_properties` classmethod:

    ```python
    @classmethod
    def _parameter_properties(cls, dtype, num_classes=None):
      return dict(
        loc=parameter_properties.ParameterProperties(),
        scale=parameter_properties.ParameterProperties(
            default_constraining_bijector_fn=(
                lambda: softplus_bijector.Softplus(low=dtype_util.eps(dtype))))),
        log_scale=parameter_properties.ParameterProperties(
            is_preferred=False)
        )
    ```
    Each value in the returned dictionary should be an instance of
    `parameter_properties.ParameterProperties`.  For real-valued parameters that
    can accept any real value, use `parameter_properties.ParameterProperties()`.
    For real-valued parameters that can accept only a certain subset of real
    values, use
    `parameter_properties.ParameterProperties(
    default_constraining_bijector_fn=lambda: PUT_BIJECTOR_HERE)` with a bijector
    that maps arbitrary real values to that subset.  For example, for the common
    case of a parameter that only accepts positive values, you could use
    `softplus_bijector.Softplus` as the bijector.  For more information on
    ParameterProperties, including non-tensor valued parameters, parameters that
    specify the shape of samples, and mutually-exclusive parameters like
    `logits` and `probs`, please see [the class documentation of
    `ParameterProperties`](https://github.com/tensorflow/probability/blob/main/tensorflow_probability/python/internal/parameter_properties.py#L45).

1. If you inherited from a concrete Distribution subclass that implements
`_sample_n` and `_log_prob`, you can skip to the last step
(unless you want and are able to
implement more efficient versions for your particular case.)

1. Define a `_sample_n` method that returns `n` samples from your distribution:

    ```python
    def _sample_n(self, n, seed=None):
    ```
    Actually, this method shouldn't exactly return `n` samples.  Rather, it
    should return `n` samples for each *batch* of the Distribution's parameters.
    The idea is that the Distribution should support [Numpy-like broadcasting](
    https://docs.scipy.org/doc/numpy-1.15.0/user/basics.broadcasting.html)
    for its arguments.  So for example, a Normal distribution could be given
    a `loc` of shape `(100, 32, 5)` and a scale of shape `(100, 32, 5)` and
    expect that a call to `_sample_n` with `n = 4` to return a value of shape
    `(4, 100, 32, 5)`.  Your `_sample_n` should do the same.  See the
    class documentation for `Distribution` in the **Broadcasting, batching,
    and shapes** section for more information.

    You will need to read the [PRNGS and seeds](
    https://github.com/tensorflow/probability/blob/main/PRNGS.md)
    document for a full understanding of how TFP handles random number
    generation, but to the first approximation you can either pass the
    given `seed` to a single routine in
    `tensorflow_probability.python.internal.samplers`, or
    you can "split" the seed using `samplers.split_seed` and use each split
    in an unique location.

1. You might be aware the TensorFlow Probability supports three different
backends:  TensorFlow, Numpy and JAX.  If you add your distribution to the
`python/distributions/` subdirectory, add it to the "distributions" target in
the BUILD file there, and build it using bazel, then your distribution will
also be usable in all three substrates.  Otherwise, it is fine to target a
single backend and to write your tensor manipulating code with just that API.

1. Define `_event_shape` and `_event_shape_tensor` methods.  These specify
the shape returned by `_sample_n` for a single batch.  They are usually

    ```python
    def _event_shape_tensor(self):
      return tf.constant([], dtype=tf.int32)

    def _event_shape(self):
      return tf.TensorShape([])
    ```

    but if your distribution is defined over `m`-dimensional space, they would
    instead be

    ```python
    def _event_shape_tensor(self):
      return tf.constant([self.m], dtype=tf.int32)

    def _event_shape(self):
      return tf.TensorShape([self.m])
    ```

1. Define either a `_log_prob` or `_prob` method:

    ```python
    def _log_prob(self, x):
    ```
    Remember that the input `x` will be batched the same way as your
    Distribution's parameters (and it is fine to raise an error if it isn't.)
    This normally is
    pretty transparent, as the tensorflow and numpy routines you were probably
    going to use to implement `_log_prob` support batching themselves.

1. Define additional statistical methods as desired, such as `_mean`,
   `_variance`, `mode`, `_cdf`, `_quantile`, `_entropy`, etc.  Remember to
   support batching; these should all return tensors of shape
   `batch_shape + event_shape`, manually broadcasting if necessary.

1. Congratulations!  You are almost done!  The last step is to write some
unittests for your distribution.  Each method should have one or more unittests
that check the shape and value of what the method returns.  All tests should
be deterministic; you can use `test_util.test_seed()` for methods like
`sample` that need a random number generator seed.  See [the TFP unit-test best
practices document](https://github.com/tensorflow/probability/blob/main/UNITTEST.md)
for more information.


text:
/*
 * This project was made in school by Thomas LEDUC.
 * To resuse it you have to get the Antoine Dumeige's permission
 * his professor in this project.
 */

package com.epita.mti.datemine.data.Business;

import com.epita.mti.datemine.data.DAO.AbstractDAO;
import com.epita.mti.datemine.data.Entity.AbstractEntity;
import com.epita.mti.datemine.tools.RESTError;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * The Abstract class which defined the Business level.
 * @author leduc_t
 * @param <D> DAO used
 * @param <T> Entity used
 */
public abstract class AbstractBusiness
<D extends AbstractDAO<T>, T extends AbstractEntity> {

    private static final Logger log =
         Logger.getLogger(AbstractBusiness.class.getName());
    /**
     * Get the DAO according to the Business class.
     * @return The DAO.
     */
    public abstract D getDao();

    /**
     * Check if the entity is OK to add in database
     * Caution it doesn't check the persist error like constrains.
     * @param entity
     * @return null if it's OK, else a rest error.
     */
    public abstract RESTError checkBeforeAdding(T entity);

    /**
     * Find all the entities managed by the instance of the business class.
     * @return all the entities managed by the instance of the business class.
     */
    public Collection<T> findAll() {
        return getDao().findAll();
    }

    /**
     * Find the entity managed by the instance of the business class,
     * according to the id.
     * @param id The id of the entity
     * @return The entity.
     */
    public T findById(final Long id) {
        return getDao().findById(id);
    }

    /**
     * Push the entity.
     * @param entity The entity to push.
     * @return If the user
     */
    public T persist(final T entity) {
        try {
            return getDao().persist(entity);
        } catch (Exception e) {
            log.log(Level.INFO, "{0} can't be persit correctly{1}Cause by :{2}",
                    new Object[]{entity.toString(),
                                 System.getProperty("line.separator"),
                                 e.getMessage()});
        }
        return null;
    }

    /**
     * @param str The string to test.
     * @param min The minimum length.
     * @param max The maximum length.
     * @return if the length of the string is between min and max parameter.
     */
    protected static Boolean lenghtBetween(final String str, int min, int max) {
        return (str.length() >= min) && (str.length() <= max);
    }
}


text:
require 'i18n'
require 'pathname'
require "juli/version"

# namespace for all of Juli library elements
module Juli
  # sentinel to search juli-repo.  Also it's a directory name to sotre config.
  REPO          = '.juli'
  LIB           = File.join(Pathname.new(File.dirname(__FILE__)).realpath, 'juli')
  TEMPLATE_PATH = File.join(LIB, 'template')

  class JuliError       < StandardError; end
    class NoConfig        < JuliError; end
    class NotImplemented  < JuliError; end

  class << self
    def init
      I18n.enforce_available_locales = false
    end
  end
end


text:
package com.hp.alm.ali.idea.model.type;

import com.hp.alm.ali.idea.translate.Translator;
import com.hp.alm.ali.idea.translate.ValueCallback;
import com.hp.alm.ali.idea.filter.ChoicesFilterFactory;
import com.hp.alm.ali.idea.filter.FilterFactory;
import com.hp.alm.ali.idea.translate.filter.FilterResolver;

import java.util.Arrays;

public class BacklogEntityType implements Type, Translator, FilterResolver {

    @Override
    public FilterFactory getFilterFactory(boolean multiple) {
        return new ChoicesFilterFactory(Arrays.asList("user story", "defect"));
    }

    @Override
    public FilterResolver getFilterResolver() {
        return this;
    }

    @Override
    public Translator getTranslator() {
        return this;
    }

    @Override
    public String translate(String value, ValueCallback callback) {
        if("requirement".equals(value))  {
            return "user story";
        } else {
            return value; // defect
        }
    }

    @Override
    public String resolveDisplayValue(String value, ValueCallback onValue) {
        onValue.value(value);
        return value;
    }

    @Override
    public String toRESTQuery(String value) {
        if("user story".equals(value)) {
            return "requirement";
        } else {
            return value; // defect
        }
    }
}