text:
/*
******************************************************************
* HISTORY
* 15-Oct-94  Jeff Shufelt (js), Carnegie Mellon University
*	Prepared for 15-681, Fall 1994.
* Modified by Shuai Che
******************************************************************
*/

/*
  Copyright (c)2008-2011 University of Virginia
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted without royalty fees or other restrictions, provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the University of Virginia, the Dept. of Computer Science, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF VIRGINIA OR THE SOFTWARE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "common_rand.h"
#include "backprop.h"
#define OPEN

#define ABS(x)          (((x) > 0.0) ? (x) : (-(x)))

#define fastcopy(to,from,len)                           \
    {                                                   \
	register char *_to,*_from;                      \
	register int _i,_l;                             \
	_to = (char *)(to);                             \
	_from = (char *)(from);                         \
	_l = (len);                                     \
	for (_i = 0; _i < _l; _i++) *_to++ = *_from++;  \
    }

/*** The squashing function.  Currently, it's a sigmoid. ***/

float squash(x)
float x;
{
    float m;
    return (1.0 / (1.0 + exp(-x)));
}

/*** Allocate 1d array of floats ***/

float *alloc_1d_dbl(n)
int n;
{
    float *new;

    new = (float *) malloc ((unsigned) (n * sizeof (float)));
    if (new == NULL) {
        fprintf(stderr, "ALLOC_1D_DBL: Couldn't allocate array of floats\n");
        return (NULL);
    }
    return (new);
}

/*** Allocate 2d array of floats ***/

float **alloc_2d_dbl(m, n)
int m, n;
{
    int i;
    float **new;

    new = (float **) malloc ((unsigned) (m * sizeof (float *)));
    if (new == NULL) {
        fprintf(stderr, "ALLOC_2D_DBL: Couldn't allocate array of dbl ptrs\n");
        return (NULL);
    }

    for (i = 0; i < m; i++) {
        new[i] = alloc_1d_dbl(n);
    }

    return (new);
}

void bpnn_randomize_weights(w, m, n)
float **w;
int m, n;
{
    int i, j;

    for (i = 0; i <= m; i++) {
        for (j = 0; j <= n; j++) {
            w[i][j] = common_randJS();
        }
    }
}

void bpnn_randomize_row(w, m)
float *w;
int m;
{
    int i;
    for (i = 0; i <= m; i++) {
        w[i] = 0.1;
    }
}

void bpnn_zero_weights(w, m, n)
float **w;
int m, n;
{
    int i, j;

    for (i = 0; i <= m; i++) {
        for (j = 0; j <= n; j++) {
            w[i][j] = 0.0;
        }
    }
}

BPNN *bpnn_internal_create(n_in, n_hidden, n_out)
int n_in, n_hidden, n_out;
{
    BPNN *newnet;

    newnet = (BPNN *) malloc (sizeof (BPNN));
    if (newnet == NULL) {
        fprintf(stderr, "BPNN_CREATE: Couldn't allocate neural network\n");
        return (NULL);
    }

    newnet->input_n = n_in;
    newnet->hidden_n = n_hidden;
    newnet->output_n = n_out;
    newnet->input_units = alloc_1d_dbl(n_in + 1);
    newnet->hidden_units = alloc_1d_dbl(n_hidden + 1);
    newnet->output_units = alloc_1d_dbl(n_out + 1);

    newnet->hidden_delta = alloc_1d_dbl(n_hidden + 1);
    newnet->output_delta = alloc_1d_dbl(n_out + 1);
    newnet->target = alloc_1d_dbl(n_out + 1);

    newnet->input_weights = alloc_2d_dbl(n_in + 1, n_hidden + 1);
    newnet->hidden_weights = alloc_2d_dbl(n_hidden + 1, n_out + 1);

    newnet->input_prev_weights = alloc_2d_dbl(n_in + 1, n_hidden + 1);
    newnet->hidden_prev_weights = alloc_2d_dbl(n_hidden + 1, n_out + 1);

    return (newnet);
}

void bpnn_free(net)
BPNN *net;
{
    int n1, n2, i;

    n1 = net->input_n;
    n2 = net->hidden_n;

    free((char *) net->input_units);
    free((char *) net->hidden_units);
    free((char *) net->output_units);

    free((char *) net->hidden_delta);
    free((char *) net->output_delta);
    free((char *) net->target);

    for (i = 0; i <= n1; i++) {
        free((char *) net->input_weights[i]);
        free((char *) net->input_prev_weights[i]);
    }
    free((char *) net->input_weights);
    free((char *) net->input_prev_weights);

    for (i = 0; i <= n2; i++) {
        free((char *) net->hidden_weights[i]);
        free((char *) net->hidden_prev_weights[i]);
    }
    free((char *) net->hidden_weights);
    free((char *) net->hidden_prev_weights);

    free((char *) net);
}

/*** Creates a new fully-connected network from scratch,
     with the given numbers of input, hidden, and output units.
     Threshold units are automatically included.  All weights are
     randomly initialized.

     Space is also allocated for temporary storage (momentum weights,
     error computations, etc).
***/

BPNN *bpnn_create(n_in, n_hidden, n_out)
int n_in, n_hidden, n_out;
{

    BPNN *newnet;

    newnet = bpnn_internal_create(n_in, n_hidden, n_out);

    bpnn_randomize_weights(newnet->input_weights, n_in, n_hidden);
    bpnn_randomize_weights(newnet->hidden_weights, n_hidden, n_out);
    bpnn_zero_weights(newnet->input_prev_weights, n_in, n_hidden);
    bpnn_zero_weights(newnet->hidden_prev_weights, n_hidden, n_out);
    bpnn_randomize_row(newnet->target, n_out);
    return (newnet);
}

void bpnn_layerforward(l1, l2, conn, n1, n2)
float *l1, *l2, **conn;
int n1, n2;
{
    float sum;
    int j, k;

    /*** Set up thresholding unit ***/
    l1[0] = 1.0;
    /*** For each unit in second layer ***/
    for (j = 1; j <= n2; j++) {

        /*** Compute weighted sum of its inputs ***/
        sum = 0.0;
        for (k = 0; k <= n1; k++) {
            sum += conn[k][j] * l1[k];
        }
        l2[j] = squash(sum);
    }
}

//extern "C"
void bpnn_output_error(delta, target, output, nj, err)
float *delta, *target, *output, *err;
int nj;
{
    int j;
    float o, t, errsum;
    errsum = 0.0;
    for (j = 1; j <= nj; j++) {
        o = output[j];
        t = target[j];
        delta[j] = o * (1.0 - o) * (t - o);
        errsum += ABS(delta[j]);
    }
    *err = errsum;
}

void bpnn_hidden_error(delta_h,
                       nh,
                       delta_o,
                       no,
                       who,
                       hidden,
                       err)
float *delta_h, *delta_o, *hidden, **who, *err;
int nh, no;
{
    int j, k;
    float h, sum, errsum;

    errsum = 0.0;
    for (j = 1; j <= nh; j++) {
        h = hidden[j];
        sum = 0.0;
        for (k = 1; k <= no; k++) {
            sum += delta_o[k] * who[j][k];
        }
        delta_h[j] = h * (1.0 - h) * sum;
        errsum += ABS(delta_h[j]);
    }
    *err = errsum;
}

void bpnn_adjust_weights(delta, ndelta, ly, nly, w, oldw)
float *delta, *ly, **w, **oldw;
{
    float new_dw;
    int k, j;
    ly[0] = 1.0;

    for (j = 1; j <= ndelta; j++) {
        for (k = 0; k <= nly; k++) {
            new_dw = ((ETA * delta[j] * ly[k]) + (MOMENTUM * oldw[k][j]));
            w[k][j] += new_dw;
            oldw[k][j] = new_dw;
        }
    }
}

void bpnn_feedforward(net)
BPNN *net;
{
    int in, hid, out;

    in = net->input_n;
    hid = net->hidden_n;
    out = net->output_n;

    /*** Feed forward input activations. ***/
    bpnn_layerforward(net->input_units, net->hidden_units,
                      net->input_weights, in, hid);
    bpnn_layerforward(net->hidden_units, net->output_units,
                      net->hidden_weights, hid, out);

}

void bpnn_train(net, eo, eh)
BPNN *net;
float *eo, *eh;
{
    int in, hid, out;
    float out_err, hid_err;

    in = net->input_n;
    hid = net->hidden_n;
    out = net->output_n;

    /*** Feed forward input activations. ***/
    bpnn_layerforward(net->input_units, net->hidden_units,
                      net->input_weights, in, hid);
    bpnn_layerforward(net->hidden_units, net->output_units,
                      net->hidden_weights, hid, out);

    /*** Compute error on output and hidden units. ***/
    bpnn_output_error(net->output_delta, net->target, net->output_units,
                      out, &out_err);
    bpnn_hidden_error(net->hidden_delta, hid, net->output_delta, out,
                      net->hidden_weights, net->hidden_units, &hid_err);
    *eo = out_err;
    *eh = hid_err;

    /*** Adjust input and hidden weights. ***/
    bpnn_adjust_weights(net->output_delta, out, net->hidden_units, hid,
			net->hidden_weights, net->hidden_prev_weights);
    bpnn_adjust_weights(net->hidden_delta, hid, net->input_units, in,
			net->input_weights, net->input_prev_weights);

}


text:
angular.module("solo.table", [])

	.controller("SoloTableCtrl", ['$scope', function ($scope){

		$scope.original = [];

		$scope.bindData = function(data)
		{
			$scope.original = data;
		};

		/**
		 * По этой коллекции нужно выполнять ng-repeat
		 *
		 * @type Array
		 */
		$scope.filtered = [];

		$scope.order = {
			header: null,
			direction: false
		};

		$scope.tableHeaders = {};

		/**
		 * Проверка переданного параметра на принадлежность к promise-объекту
		 *
		 * @param variableToCheck
		 * @returns {*|boolean}
		 */
		$scope.isPromise = function(variableToCheck) {
			return (variableToCheck && angular.isFunction(variableToCheck.then));
		};

		/**
		 * Описание пейджера
		 *
		 * @type onPage: number, currentPage: number, found: number, total: Number, foundPages: number
		 */
		$scope.pager = {
			onPage: 10, // сколько записей на странице
			currentPage: 1, // номер текущей страницы
			found: 0, // найдено записей
			foundPages: 0, // количество страниц в таблице

			/**
			 * Устанавливает количество записей на странице
			 * @param num int Количество записей на странице
			 */
			setOnPage: function(num)
			{
				this.onPage = parseInt(num);
				this.update($scope.filtered.length);
			},

			/**
			 * Возвращает количество записей на странице
			 * @returns int
			 */
			getOnPage: function()
			{
				return this.onPage;
			},

			/**
			 * Обновляет данные пейджера
			 * @param len int Количество записей в таблице (после применения фильтра)
			 */
			update: function(len)
			{
				this.found = len;
				this.foundPages = Math.ceil(len / this.onPage);
				this.currentPage = 1;
			}
		};

		/**
		 * Режим сортировки:
		 * 2 - только ASC и DESC
		 * 3 - default, ASC и DESC
		 *
		 * @type {number}
		 */
		$scope.sortMode = 2;

		/**
		 * Установка режима сортировки
		 * @param mode
		 */
		$scope.setSortMode = function(mode)
		{
			if (mode == "" || mode == null)
				$scope.sortMode = 2;
			else
				$scope.sortMode = parseInt(mode);
		};

		/**
		 * Переход на следующую страницу
		 */
		$scope.gotoNextPage = function()
		{
			if ($scope.pager.foundPages == $scope.pager.currentPage)
				return true;

			$scope.pager.currentPage++;
		};

		/**
		 * Переход на первую страницу
		 */
		$scope.gotoFirstPage = function ()
		{
			$scope.pager.currentPage = 1;
		};

		/**
		 * Переход на последнюю страницу
		 */
		$scope.gotoLastPage = function ()
		{
			$scope.pager.currentPage = $scope.pager.foundPages;
		};

		/**
		 * Переход на предыдущую страницу
		 */
		$scope.gotoPrevPage = function()
		{
			if ($scope.pager.currentPage == 1)
				return true;
			$scope.pager.currentPage--;
		};

		// следим за коллекцией отфильтрованных элементов
		$scope.$watchCollection("filtered", function (list){
			$scope.pager.update(list.length);
		});

		/**
		 * Сортировка по колонкам
		 * @param header
		 */
		$scope.orderTableBy = function(header){

			if ($scope.sortMode == 2)
			{
				// это для работы в 2-х режимах ASC и DESC
				if ($scope.order.header == header && $scope.order.direction == false)
				{
					$scope.order.direction = true;
				}
				else
				{
					$scope.order.header = header;
					$scope.order.direction = false;
				}
			}
			if ($scope.sortMode == 3)
			{
				if ($scope.order.header == header && $scope.order.direction == true)
				{
					$scope.order.header = null; // очистка сортировки.
				}
				else if ( $scope.order.header == header )
				{
					$scope.order.direction = true;
				}
				else
				{
					$scope.order.header = header;
					$scope.order.direction = false;
				}
			}

		};
	}])

	.filter("pager", function(){
		return function(items, page, onPage)
		{
			if (items.length <= onPage)
				return items;

			var offset = (page - 1) * onPage;
			return items.slice(offset, offset + onPage);
		};
	})
	/**
	 * Эта директива добавляет данные в таблицу
	 *
	 * Пример:
	 *

	 * [{"id":0,"prefix":"Miss","name":"Alvah Gleason","address":"58707 Ophelia Field\nEast Lorena, LA 89754-9301"}]
	 *

	 */
	.directive("soloTableData", function(){
		return {
			require: "?ngModel",
			restrict: "A",
			link: function (scope, elm, attrs, ngm)
			{
				//elm.hide();
				elm.css({"display" : "none"});

				if (!!attrs.soloTableData) {
					scope.$watch(attrs.soloTableData, function (value){
						if (!scope.isPromise(value)) {
							scope.bindData(value);
						}
					});
				} else {
					var json = angular.fromJson(elm.html());
					scope.bindData(json);
				}
			}
		};
	})
	/**
	 * Эта директива добавляет возможность сортировки колонки
	 * и добавляет в разметку стрелки, указывающие направление сортировки
	 *
	 * Пример:
	 *

	 *   Id
	 *

	 */
	.directive("sortBy", function($compile){
		return {
			require: "?ngModel",
			restrict: "A",
			replace: false,
			template: function(tElement, tAttrs)
			{
				return "" + tElement.html()+ "";

			},
			link: function (scope, elm, attrs, ngm)
			{
				if (attrs.sortBy)
				{
					elm.append("");
					scope.tableHeaders[attrs.sortBy] = elm;
				}
			}
		};
	})

	/**
	 * Можно также указать направление сортировки по-умолчанию, возможные значения asc и desc.
	 * Указать можно только у одной колонки.
	 * Пример:
	 * Name
	 */
	.directive("defaultSort", function(){
		return {
			restrict: "A",
			link: function (scope, elm, attrs, ngm)
			{
				if (attrs.sortBy)
				{
					if ("asc" == attrs.defaultSort)
						scope.order.direction = false;

					if ("desc" == attrs.defaultSort)
						scope.order.direction = true;

					scope.order.header = attrs.sortBy;
				}
			}
		}
	})

	/**
	 * Базовая директива
	 *
	 * <solo-table [items-on-page = "15"] [make-sortable]>
	 *     ...
	 * </solo-table>
	 */
	.directive("soloTable", function(){
		return {
			require: "?ngModel",
			restrict: "E",
			controller: "SoloTableCtrl",
			compile: function (elm, attr)
			{
				var tr = null;
				if (attr.hasOwnProperty("listId"))
				{
					tr = angular.element(document.getElementById(attr.listId));
				}
				else
				{
					tr = angular.element( elm.find('tbody').children('tr')[0]);
				}

				if (tr.length == 0)
					throw Error("Can't find element to repeat");

				var repeat = tr.attr("ng-repeat");

				if (attr.hasOwnProperty("makeSortable"))
				{
					repeat = repeat + " | orderBy:order.header:order.direction";
					tr.attr("ng-repeat", repeat);
				}

				if (attr.hasOwnProperty("itemsOnPage") && attr.itemsOnPage !== 0)
				{
					repeat = repeat + " | pager:pager.currentPage:pager.getOnPage()";
					tr.attr("ng-repeat", repeat);
				}
				return {
					pre: function preLink(scope, element, attr)
					{
						// обработка настройки make-sortable
						if (attr.hasOwnProperty("makeSortable"))
						{
							scope.setSortMode(attr.makeSortable);

							scope.$watchCollection("order", function(){

								var resetClasses = function()
								{
									for (var i in scope.tableHeaders)
									{
										scope.tableHeaders[i].removeClass("solo-table-sort-asc");
										scope.tableHeaders[i].removeClass("solo-table-sort-desc");
									}
								};

								if (scope.order.header == null && scope.order.direction == true)
								{
									resetClasses();
								}
								else if (scope.order.header)
								{
									var el = scope.tableHeaders[scope.order.header];
									if (!el)
										return;
									if (scope.order.direction)
									{
										resetClasses();
										el.addClass("solo-table-sort-asc");
									}
									else
									{
										resetClasses();
										el.addClass("solo-table-sort-desc");
									}
								}

							});
						}

						// обработка настройки items-on-page
						if (attr.hasOwnProperty("itemsOnPage"))
							scope.pager.setOnPage(attr.itemsOnPage);
							//scope.pager.onPage = parseInt(attr.itemsOnPage);
					}
				};
			}
		};
	})

	/**
	 * Фильтрация только по указанным полям
	 *
	 * @example

	 */
	.filter("filterByFields", function(){

		/**
		 * @param items - Список фильтруемых записей
		 * @param search - Искомая подстрока
		 * @param items - список имен полей, по которым идет поиск
		 */
		return function (items, search, fields)
		{
			if (!search)
				return items;

			if (fields.length == 0)
				throw Error("You have to define list of fields");

			search = (''+search).toLowerCase();

			var test = function(el, idx, array)
			{
				var compare = function(val, search)
				{
                    // null hasn't method toString()
                    if ( val == null )
                        return false;
					return val.toString().toLowerCase().indexOf(search) !== -1;
				};

				var result = false;
				var len = fields.length;
				for (var i = 0; i < len; i++)
				{
					if (compare(el[fields[i]], search))
					{
						result = true;
						break;
					}
				}
				return result;
			};

			return items.filter(test);
		};
	});

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Polydesk</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <link href="js/jquery.js" rel="application/javascript">

    <link href="css/full-width-pics.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Polydesk

                        New Desktop

                        Running Desktops

                      <form id="signin" class="navbar-form navbar-right" role="form">

                            <input id="email" type="email" class="form-control" name="email" value="" placeholder="Email Address">

                            <input id="password" type="password" class="form-control" name="password" value="" placeholder="Password">

                        <button type="submit" class="btn btn-primary">Login</button>
                   </form>

        <form method="post" action="new/desktop">

Choose your configuration

<input name="desktop" type="radio" id="base">Common desktop

<input name="desktop" type="radio" id="web">WEB Developer

<input name="desktop" type="radio" id="lowlvl">Developer desktop

 <input name="desktop" type="radio" id="tor">Incognito desktop

<input name="desktop"  type="radio" id="office">Office suite desktop

            Desktop name

            <input  class="form-control" id="name" placeholder="Please enter the name for your virtual desktop">

            Password

            <input type="password" class="form-control" id="password" placeholder="Password">

        <button type="submit" class="btn btn-primary">Create Desktop</button>

    </form>

Copyright © Polydesk 2015


text:
title: App Lab Docs
embedded_layout: simple_embedded
---

[name]

## getImageURL(id)

[/name]

[category]

Category: UI Controls

[/category]

[description]

[short_description]

Gets the URL for the provided image element id.

[/short_description]

The images in apps are not always static, they sometimes change based on user or other events. getImage() can be used to access the URL if the image displayed for an image element ID.

[/description]

### Examples
____________________________________________________

[example]

```
// Display the URL of the Code.org logo.
image("logo", "http://code.org/images/logo.png");
write(getImageURL("logo"));
```

[/example]

____________________________________________________

[example]

**Example: Image Swap** Click the button to change the character image from the dog to the bee and back again.

```
// Click the button to change the character image from the dog to the bee and back again.
var imageId = "character";
var dogImageURL = "http://studio.code.org/blockly/media/skins/applab/static_avatar.png";
var beeImageURL = "http://studio.code.org/blockly/media/skins/bee/static_avatar.png";
image(imageId, dogImageURL);
button("changeButton", "Change Character");
onEvent("changeButton", "click", function() {
  if (getImageURL(imageId).includes("bee")) {
    setImageURL(imageId, dogImageURL);
  } else {
    setImageURL(imageId, beeImageURL);
  }
});
```

[/example]

____________________________________________________

[syntax]

### Syntax

```
getImageURL(id);
```

[/syntax]

[parameters]

### Parameters

| Name  | Type | Required? | Description |
|-----------------|------|-----------|-------------|
| id | string | Yes | The unique identifier for the screen element. Must begin with a letter, contain no spaces, and may contain letters, digits, - and _. |

[/parameters]

[returns]

### Returns
Returns a string containing image url for the provided id.

[/returns]

[tips]

### Tips
- The string returned contains the image URL. For example  http://code.org/images/logo.png is returned as https://studio.code.org/media?u=http%3A%2F%2Fcode.org%2Fimages%2Flogo.png

[/tips]

[bug]

Found a bug in the documentation? Let us know at documentation@code.org

[/bug]

<%= view :applab_docs_common %>


text:
<!doctype html>

	<meta charset="UTF-8">
	<title>prueba html </title>

formulario Web

standarthtml5.01 para input y atributos

new input types forms in html5

			<form action="pruebas.php" method="POST" name="foo">

el input de search es aquel se utiliza para buscar informacion dentro de nuestros directorios del server

SEARCH<input type="search" name="search"/>

se valida si lleva @' y NO lleva espacios en blanco

EMAIL<input type="email" name="email" required>

requiere del protocolo, el tipo de servidor y el dominio

URL<input type="url" name="url" required>

telefono

TELEFONO<input type="tel" name="tel"/>

casilla numerica, poddemos sustituir patrones con los atributos, min, max, step

NUMBER<input type="number" name="number" min="10" max="100" step="5">

rango [0, 100]

RANGE<input type="range" value="50" name="range">

fechas, podemos usar un rango de fechas [YYYY-MM-DD]

				los estilos de las fechas no se pueden manipular, y los valores tienen que definirse tal cual el standart

DATE<input type="date"
				name="date" min="1985-12-11" max="2013-09-27"/>

meses, no tiene rangos, formato: value="1956-02"

MES<input type="month" id="month"
					name="month" value="1956-02">

semanas, no tiene rangos, formato: value="1956-W02", es la semana del año

SEMANA<input type="week" id="week"
					name="week" value="1956-W02">

horas, formato 24H: value="23:59"

<input type="time" id="time" name="time" value="23:59"/>

evitar la validacion nativa de los formularios: attr:'formnovalidate'

submit NO necesita 'name'

<input type="submit" value="server">

			</form>

new form atributes in hyml5

placeholder

autofocus

autocomplete

required

pattern

list

multiple

novalidate

formnovalidate

form

formaction

formenctype

formmethod

formtarget

placeholder

es una descripcion corta del valor que debe tomar el input

title: atributo que extiende el sgnificado de placeholder

el texto de e ste atributo desaparece una vez el foco toma el contro e el input

los navegadores que no lo soportan,  ignoran su contenido

No se puede dar estil a l texto del placeholder

autofocus

cuando la pagina web se carga en el navegador, el input que lleve el atributo autofocus, toma el foco de la interaccion con el usuario

los navegadores que no lo soportan,  ignoran su contenido

autocomplete

carga entradas antiguas que el usuario halla introducdo e el input anteriormente

es un atrributo booleano y esta activado por defecto

desactivarlo: autocomplete="off"

required

el formulario exige relenar el campo e n el input antes de que se envie la pagina

es un atributo booleano y esta deactivado por defecto

activarlo: required

falta de compatibilidad en navegadores: IE9 - navegadores moviles (opera mini, IOSsafari - android)

para estos casos hay que cargar javascriprt de validadcion  de campos incmpletos del lado del cliente

datalist

permite seleccionar una serie de valores para los inputs de tipo text

NO es un menu SELECT, no hay que elegir obligatoriamente un valor

solo es una ayuda que te permite completar los campos del ,formulario

			<form action="pruebas_php.php">

					<datalist id="fruits">
					  <select name="fruits">
					    <option value="mora">Blackberry</option>
					    <option value="grosella negra">Blackcurrant</option>
					    <option value="arandano">Blueberry</option>
					  </select>
					  If other, please specify:
					</datalist>
					Your favorite fruit:
					<input type="text" name="fruit" id="frutas_bosque" list="fruits">

			</form>

form

permite asociar el input al que se asopcia, un formulario desplazado a otro lugar de la pagina

se asocia con el <form id="">

de esta manera el input NO debe ser descendiente del  formulario

min, max

 The max and min attributes works with the following input types:

number

range

date

time

datetime

month

week


text:
$().insertAfter(element) Inserts a collection after the element in the dom.

Let's say we want to move all paragraphs after an element with id ="insertBeforeTest"

```html
<p>This is p1</p>
<p>This is p2</p>
<div id="insertAfterTest">P's will go after me</div>
<div>Some stuff</div>
```

We can find all the p tags, then insert after #insertAfterTest
```js
$("p").insertAfter("#insertAfterTest");
```


text:
package cluster

import (
	"bufio"
	"fmt"
	"reflect"
	"regexp"
	"strings"

	kerrs "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	kapi "k8s.io/kubernetes/pkg/api"
	kclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"

	authorizationapi "github.com/openshift/origin/pkg/authorization/api"
	osclient "github.com/openshift/origin/pkg/client"
	"github.com/openshift/origin/pkg/diagnostics/types"
	osapi "github.com/openshift/origin/pkg/image/api"
)

// ClusterRegistry is a Diagnostic to check that there is a working Docker registry.
type ClusterRegistry struct {
	KubeClient          kclientset.Interface
	OsClient            *osclient.Client
	PreventModification bool
}

const (
	ClusterRegistryName = "ClusterRegistry"

	registryName   = "docker-registry"
	registryVolume = "registry-storage"
	clGetRegNone   = `
There is no "%s" service in project "%s". This is not strictly required to
be present; however, it is required for builds, and its absence probably
indicates an incomplete installation.

Please consult the documentation and use the 'oadm registry' command
to create a Docker registry.`

	clGetRegFailed = `
Client error while retrieving registry service. Client retrieved records
during discovery, so this is likely to be a transient error. Try running
diagnostics again. If this message persists, there may be a permissions
problem with getting records. The error was:

(%T) %[1]v `

	clRegNoPods = `
The "%s" service exists but has no associated pods, so it
is not available. Builds and deployments that use the registry will fail.`

	clRegNoRunningPods = `
The "%s" service exists but no pods currently running, so it
is not available. Builds and deployments that use the registry will fail.`

	clRegMultiPods = `
The "%s" service has multiple associated pods each using
ephemeral storage. These are likely to have inconsistent stores of
images. Builds and deployments that use images from the registry may
fail sporadically. Use a single registry or add a shared storage volume
to the registries.`

	clRegMultiCustomCfg = `
The "%s" service has multiple associated pods each mounted with
ephemeral storage, but also has a custom config %s
mounted; assuming storage config is as desired.`

	clRegPodDown = `
The "%s" pod for the "%s" service is not running.
This may be transient, a scheduling error, or something else.`
	clRegPodLog = `
Failed to read the logs for the "%s" pod belonging to
the "%s" service. This is not a problem by itself but
prevents diagnostics from looking for errors in those logs. The
error encountered was:
%s`

	clRegPodConn = `
The pod logs for the "%s" pod belonging to
the "%s" service indicated a problem connecting to the
master to notify it about a new image. This typically results in builds
succeeding but not triggering deployments (as they wait on notifications
to the ImageStream from the build).

There are many reasons for this step to fail, including invalid
credentials, master outages, DNS failures, network errors, and so on. It
can be temporary or ongoing. Check the most recent error message from the
registry pod logs to determine the nature of the problem:

%s`

	clRegPodErr = `
The pod logs for the "%s" pod belonging to
the "%s" service indicated unknown errors.
This could result in problems with builds or deployments.
Please examine the log entries to determine if there might be
any related problems:
%s`

	clRegSelinuxErr = `
The pod logs for the "%s" pod belonging to
the "%s" service indicated the registry is unable to write to disk.
This may indicate an SELinux denial, or problems with volume
ownership/permissions.

For volume permission problems please consult the Persistent Storage section
of the Administrator's Guide.

In the case of SELinux this may be resolved on the node by running:

    sudo chcon -R -t svirt_sandbox_file_t [PATH_TO]/openshift.local.volumes

%s`

	clRegNoEP = `
The "%[1]s" service exists with %d associated pod(s), but there
are %d endpoints in the "%[1]s" service.
This mismatch likely indicates a system bug, and builds and
deployments that require the registry may fail sporadically.`

	clRegISDelFail = `
The diagnostics created an ImageStream named "%[1]s"
for test purposes and then attempted to delete it, which failed. This
should be an unusual, transient occurrence. The error encountered in
deleting it was:

%s

This message is just to notify you that this object exists.
You ought to be able to delete this object with:

oc delete imagestream/%[1]s -n default
`

	clRegISMismatch = `
Diagnostics created a test ImageStream and compared the registry IP
it received to the registry IP available via the %[1]s service.

%[1]s      : %[2]s
ImageStream registry : %[3]s

They do not match, which probably means that an administrator re-created
the %[1]s service but the master has cached the old service
IP address. Builds or deployments that use ImageStreams with the wrong
%[1]s IP will fail under this condition.

To resolve this issue, restarting the master (to clear the cache) should
be sufficient. Existing ImageStreams may need to be re-created.`
)

func (d *ClusterRegistry) Name() string {
	return ClusterRegistryName
}

func (d *ClusterRegistry) Description() string {
	return "Check that there is a working Docker registry"
}

func (d *ClusterRegistry) CanRun() (bool, error) {
	if d.OsClient == nil || d.KubeClient == nil {
		return false, fmt.Errorf("must have kube and os clients")
	}
	return userCan(d.OsClient, authorizationapi.Action{
		Namespace:    metav1.NamespaceDefault,
		Verb:         "get",
		Group:        kapi.GroupName,
		Resource:     "services",
		ResourceName: registryName,
	})
}

func (d *ClusterRegistry) Check() types.DiagnosticResult {
	r := types.NewDiagnosticResult(ClusterRegistryName)
	if service := d.getRegistryService(r); service != nil {
		// Check that it actually has pod(s) selected and running
		if runningPods := d.getRegistryPods(service, r); len(runningPods) == 0 {
			// not reporting an error here, if there are no running pods an error
			// is reported by getRegistryPods
			return r
		} else if d.checkRegistryEndpoints(runningPods, r) { // Check that matching endpoint exists on the service
			// attempt to create an imagestream and see if it gets the same registry service IP from the service cache
			d.verifyRegistryImageStream(service, r)
		}
	}
	return r
}

func (d *ClusterRegistry) getRegistryService(r types.DiagnosticResult) *kapi.Service {
	service, err := d.KubeClient.Core().Services(metav1.NamespaceDefault).Get(registryName, metav1.GetOptions{})
	if err != nil && reflect.TypeOf(err) == reflect.TypeOf(&kerrs.StatusError{}) {
		r.Warn("DClu1002", err, fmt.Sprintf(clGetRegNone, registryName, metav1.NamespaceDefault))
		return nil
	} else if err != nil {
		r.Error("DClu1003", err, fmt.Sprintf(clGetRegFailed, err))
		return nil
	}
	r.Debug("DClu1004", fmt.Sprintf("Found %s service with ports %v", registryName, service.Spec.Ports))
	return service
}

func (d *ClusterRegistry) getRegistryPods(service *kapi.Service, r types.DiagnosticResult) []*kapi.Pod {
	runningPods := []*kapi.Pod{}
	pods, err := d.KubeClient.Core().Pods(metav1.NamespaceDefault).List(metav1.ListOptions{LabelSelector: labels.SelectorFromSet(service.Spec.Selector).String()})
	if err != nil {
		r.Error("DClu1005", err, fmt.Sprintf("Finding pods for '%s' service failed. This should never happen. Error: (%T) %[2]v", registryName, err))
		return runningPods
	} else if len(pods.Items) < 1 {
		r.Error("DClu1006", nil, fmt.Sprintf(clRegNoPods, registryName))
		return runningPods
	} else if len(pods.Items) > 1 {
		emptyDir := false     // multiple registry pods using EmptyDir will be inconsistent
		customConfig := false // ... unless the user has configured them for e.g. S3
		configPath := "/config.yml"
		// look through the pod volumes to see if that might be a problem
		podSpec := pods.Items[0].Spec
		container := podSpec.Containers[0]
		for _, volume := range podSpec.Volumes {
			if volume.Name == registryVolume && volume.EmptyDir != nil {
				emptyDir = true
			}
		}
		for _, env := range container.Env {
			if env.Name == "REGISTRY_CONFIGURATION_PATH" {
				configPath = env.Value // look for custom config here
			}
		}
		for _, vmount := range container.VolumeMounts {
			if strings.HasPrefix(configPath, vmount.MountPath) {
				customConfig = true // if something's mounted there, assume custom config.
			}
		}
		if emptyDir {
			if customConfig { // assume they know what they're doing
				r.Info("DClu1020", fmt.Sprintf(clRegMultiCustomCfg, registryName, configPath))
			} else { // assume they scaled up with ephemeral storage
				r.Error("DClu1007", nil, fmt.Sprintf(clRegMultiPods, registryName))
			}
		}
	}
	for _, pod := range pods.Items {
		r.Debug("DClu1008", fmt.Sprintf("Found %s pod with name %s", registryName, pod.ObjectMeta.Name))
		if pod.Status.Phase != kapi.PodRunning {
			r.Warn("DClu1009", nil, fmt.Sprintf(clRegPodDown, pod.ObjectMeta.Name, registryName))
		} else {
			runningPods = append(runningPods, &pod)
			// Check the logs for that pod for common issues (credentials, DNS resolution failure)
			d.checkRegistryLogs(&pod, r)
		}
	}
	return runningPods
}

func (d *ClusterRegistry) checkRegistryLogs(pod *kapi.Pod, r types.DiagnosticResult) {
	// pull out logs from the pod
	readCloser, err := d.KubeClient.Core().RESTClient().Get().
		Namespace("default").Name(pod.ObjectMeta.Name).
		Resource("pods").SubResource("log").
		Param("follow", "false").
		Param("container", pod.Spec.Containers[0].Name).
		Stream()
	if err != nil {
		r.Warn("DClu1010", nil, fmt.Sprintf(clRegPodLog, pod.ObjectMeta.Name, registryName, fmt.Sprintf("(%T) %[1]v", err)))
		return
	}
	defer readCloser.Close()

	// Indicator that selinux is blocking the registry from writing to disk:
	selinuxErrorRegex, _ := regexp.Compile(".*level=error.*mkdir.*permission denied.*")
	// If seen after the above error regex, we know the problem has since been fixed:
	selinuxSuccessRegex, _ := regexp.Compile(".*level=info.*response completed.*http.request.method=PUT.*")

	clientError := ""
	registryError := ""
	selinuxError := ""

	scanner := bufio.NewScanner(readCloser)
	for scanner.Scan() {
		logLine := scanner.Text()
		// TODO: once the logging API gets "since" and "tail" and "limit", limit to more recent log entries
		// https://github.com/kubernetes/kubernetes/issues/12447
		if strings.Contains(logLine, `level=error msg="client error:`) {
			clientError = logLine // end up showing only the most recent client error
		} else if selinuxErrorRegex.MatchString(logLine) {
			selinuxError = logLine
		} else if selinuxSuccessRegex.MatchString(logLine) {
			// Check for a successful registry push, if this occurs after a selinux error
			// we can safely clear it, the problem has already been fixed.
			selinuxError = ""
		} else if strings.Contains(logLine, "level=error msg=") {
			registryError += "\n" + logLine // gather generic errors
		}
	}
	if clientError != "" {
		r.Error("DClu1011", nil, fmt.Sprintf(clRegPodConn, pod.ObjectMeta.Name, registryName, clientError))
	}
	if selinuxError != "" {
		r.Error("DClu1020", nil, fmt.Sprintf(clRegSelinuxErr, pod.ObjectMeta.Name, registryName, selinuxError))
	}
	if registryError != "" {
		r.Warn("DClu1012", nil, fmt.Sprintf(clRegPodErr, pod.ObjectMeta.Name, registryName, registryError))
	}
}

func (d *ClusterRegistry) checkRegistryEndpoints(pods []*kapi.Pod, r types.DiagnosticResult) bool {
	endPoint, err := d.KubeClient.Core().Endpoints(metav1.NamespaceDefault).Get(registryName, metav1.GetOptions{})
	if err != nil {
		r.Error("DClu1013", err, fmt.Sprintf(`Finding endpoints for "%s" service failed. This should never happen. Error: (%[2]T) %[2]v`, registryName, err))
		return false
	}
	numEP := 0
	for _, subs := range endPoint.Subsets {
		numEP += len(subs.Addresses)
	}
	if numEP != len(pods) {
		r.Warn("DClu1014", nil, fmt.Sprintf(clRegNoEP, registryName, len(pods), numEP))
		return false
	}
	return true
}

func (d *ClusterRegistry) verifyRegistryImageStream(service *kapi.Service, r types.DiagnosticResult) {
	if d.PreventModification {
		r.Info("DClu1021", "Skipping creating an ImageStream to test registry service address, because you requested no API modifications.")
		return
	}
	imgStream, err := d.OsClient.ImageStreams(metav1.NamespaceDefault).Create(&osapi.ImageStream{ObjectMeta: metav1.ObjectMeta{GenerateName: "diagnostic-test"}})
	if err != nil {
		r.Error("DClu1015", err, fmt.Sprintf("Creating test ImageStream failed. Error: (%T) %[1]v", err))
		return
	}
	defer func() { // delete what we created, or notify that we couldn't
		if err := d.OsClient.ImageStreams(metav1.NamespaceDefault).Delete(imgStream.ObjectMeta.Name); err != nil {
			r.Warn("DClu1016", err, fmt.Sprintf(clRegISDelFail, imgStream.ObjectMeta.Name, fmt.Sprintf("(%T) %[1]s", err)))
		}
	}()
	imgStream, err = d.OsClient.ImageStreams(metav1.NamespaceDefault).Get(imgStream.ObjectMeta.Name, metav1.GetOptions{}) // status is filled in post-create
	if err != nil {
		r.Error("DClu1017", err, fmt.Sprintf("Getting created test ImageStream failed. Error: (%T) %[1]v", err))
		return
	}
	r.Debug("DClu1018", fmt.Sprintf("Created test ImageStream: %[1]v", imgStream))
	cacheHost := strings.SplitN(imgStream.Status.DockerImageRepository, "/", 2)[0]
	serviceHost := fmt.Sprintf("%s:%d", service.Spec.ClusterIP, service.Spec.Ports[0].Port)
	if cacheHost != serviceHost {
		r.Error("DClu1019", nil, fmt.Sprintf(clRegISMismatch, registryName, serviceHost, cacheHost))
	}
}


text:
define(['angular','feed-mgr/feeds/edit-feed/module-name'], function (angular,moduleName) {

    var directive = function () {
        return {
            restrict: "EA",
            bindToController: {
                processingdttm:'=',
                rowsPerPage:'='
            },
            controllerAs: 'vm',
            scope: {},
            templateUrl: 'js/feed-mgr/feeds/edit-feed/profile-history/profile-invalid-results.html',
            controller: "FeedProfileInvalidResultsController",
            link: function ($scope, element, attrs, controller) {

            }

        };
    };

    var controller =  function($scope,$http,FeedService, RestUrlService, HiveService, Utils,BroadcastService) {

        var self = this;

        this.model = FeedService.editFeedModel;
        this.data = [];
        this.loadingFilterOptions = false;
        this.loadingData = false;
        this.limitOptions = [10, 50, 100, 500, 1000];
        this.limit = this.limitOptions[2];

        this.filterOptions = [
            {name: 'None', objectShortClassType: ''},
            {name: 'Type Conversion', objectShortClassType: 'Not convertible to'}
        ];
        this.filter = self.filterOptions[0];

        //noinspection JSUnusedGlobalSymbols
        this.onLimitChange = function() {
            getProfileValidation();
        };

        //noinspection JSUnusedGlobalSymbols
        this.onFilterChange = function() {
            getProfileValidation();
        };

        $scope.gridOptions = {
            columnDefs: [],
            rowHeight: 70,
            data: null,
            enableColumnResizing: true,
            enableGridMenu: true,
            useExternalSorting: false
        };

        var transformFn = function(row,columns,displayColumns){
            var invalidFields = [];
            var invalidFieldMap = {};
            row.invalidFields = invalidFields;
            row.invalidFieldMap = invalidFieldMap;
            row.invalidField = function(column){
                return this.invalidFieldMap[column];
            };
            var _index = _.indexOf(displayColumns,'dlp_reject_reason');
            var rejectReasons = row[columns[_index]];
            if(rejectReasons != null){
                rejectReasons = angular.fromJson(rejectReasons);
            }
            if(rejectReasons != null){
                angular.forEach(rejectReasons,function(rejectReason){
                    if(rejectReason.scope =='field'){
                        var field = rejectReason.field;
                        var copy = angular.copy(rejectReason);
                        _index = _.indexOf(displayColumns,field);
                        copy.fieldValue = row[columns[_index]];
                        invalidFields.push(copy);
                        invalidFieldMap[columns[_index]] = copy;
                    }
                });
            }

        };

        var addCellTemplate = function(columns) {
            var cellTemplate =
                '
' +
                '
' +
                '            {{row.entity[col.colDef.name]}}' +
                '
' +
                '
' +
                '                {{row.entity.invalidField(col.colDef.name).rule}}' +
                '
' +
                '                {{row.entity.invalidField(col.colDef.name).reason}}' +
                '
' +
                '
';

            angular.forEach(columns, function(column) {
                column.cellTemplate = cellTemplate;
            });

            return columns;
        };

        var errorFn = function (err) {
            self.loadingData = false;
        };
        function getProfileValidation(){
            self.loadingData = true;

            var successFn = function (response) {
                var result = self.queryResults = HiveService.transformResultsToUiGridModel(response, [], transformFn);
                $scope.gridOptions.columnDefs = addCellTemplate(result.columns);
                $scope.gridOptions.columnDefs = _.reject($scope.gridOptions.columnDefs, function(col) {
                    return col.name == 'dlp_reject_reason'
                });
                $scope.gridOptions.data = result.rows;

                self.loadingData = false;
                BroadcastService.notify('PROFILE_TAB_DATA_LOADED','invalid');
            };

            var promise = $http.get(
                RestUrlService.FEED_PROFILE_INVALID_RESULTS_URL(self.model.id),
                { params:
                    {
                        'processingdttm': self.processingdttm,
                        'limit': self.limit,
                        'filter': _.isUndefined(self.filter) ? '' : self.filter.objectShortClassType
                    }
                });
            promise.then(successFn, errorFn);
            return promise;
        }

        function getFilterOptions() {
            self.loadingFilterOptions = true;
            var filterOptionsOk = function(response) {
                self.filterOptions = _.union(self.filterOptions, response.data);
                self.loadingFilterOptions = false;
            };
            var promise = $http.get(RestUrlService.AVAILABLE_VALIDATION_POLICIES, {cache:true});
            promise.then(filterOptionsOk, errorFn);
            return promise;
        }

        getFilterOptions();
        getProfileValidation();
    };

    angular.module(moduleName).controller('FeedProfileInvalidResultsController', ["$scope","$http","FeedService","RestUrlService","HiveService","Utils","BroadcastService",controller]);

    angular.module(moduleName)
        .directive('thinkbigFeedProfileInvalid', directive);

});


text:
"""The Coolmaster integration."""
import logging

from pycoolmasternet_async import CoolMasterNet

from homeassistant.components.climate import SCAN_INTERVAL
from homeassistant.const import CONF_HOST, CONF_PORT
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import DATA_COORDINATOR, DATA_INFO, DOMAIN

_LOGGER = logging.getLogger(__name__)

PLATFORMS = ["climate"]

async def async_setup_entry(hass, entry):
    """Set up Coolmaster from a config entry."""
    host = entry.data[CONF_HOST]
    port = entry.data[CONF_PORT]
    coolmaster = CoolMasterNet(host, port)
    try:
        info = await coolmaster.info()
        if not info:
            raise ConfigEntryNotReady
    except OSError as error:
        raise ConfigEntryNotReady() from error
    coordinator = CoolmasterDataUpdateCoordinator(hass, coolmaster)
    hass.data.setdefault(DOMAIN, {})
    await coordinator.async_config_entry_first_refresh()
    hass.data[DOMAIN][entry.entry_id] = {
        DATA_INFO: info,
        DATA_COORDINATOR: coordinator,
    }
    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True

async def async_unload_entry(hass, entry):
    """Unload a Coolmaster config entry."""
    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
    if unload_ok:
        hass.data[DOMAIN].pop(entry.entry_id)
    return unload_ok

class CoolmasterDataUpdateCoordinator(DataUpdateCoordinator):
    """Class to manage fetching Coolmaster data."""

    def __init__(self, hass, coolmaster):
        """Initialize global Coolmaster data updater."""
        self._coolmaster = coolmaster

        super().__init__(
            hass,
            _LOGGER,
            name=DOMAIN,
            update_interval=SCAN_INTERVAL,
        )

    async def _async_update_data(self):
        """Fetch data from Coolmaster."""
        try:
            return await self._coolmaster.status()
        except OSError as error:
            raise UpdateFailed from error


text:
class AddDissolvedMessageFieldsToParliament < ActiveRecord::Migration
  def up
    add_column :parliaments, :dissolved_heading, :string, limit: 100
    add_column :parliaments, :dissolved_message, :text
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>

<udhr iso639-3='lue' xml:lang='lue' key='lue' n='Luvale' xmlns="http://www.unhchr.ch/udhr">
  <title>KUZANGA CHA KAYE HALUSESA LWA MUTU</title>
  <preamble>
    <title>KUPUTUKA</title>
    <para>Chakutamo hakwitavila wulemu wa Lusesa lwa Mutu wosena mu chiyoyelo chenyi, Nakupwa nakuliyoyela chakuhona kupwa nawoma, kaha atela kupwa nachiyoyelo chakuwunda mu Kaye.</para>
    <para>Chapwa chakutamo kuhasa kukanyisa jijila jize jakuyanjisilamo Mutu, kaha makuwana nawa jijila jeka Mutu nahase kuyoyelamo muno mu Kaye mwahasa kupwa na Lusesa lwakuhasa kulihanjikila, kupwa nachinyingi chakutanga mazu akalunga mwazanga chakuhona kupwa nawoma.</para>
    <para>Chapwa chakutamo Mutu kuhona kumushinjila kulinga vyuma vyavipi navihasa kumuwanyisa kukaluhwa mu chiyoyelo chenyi kupwa nge jila yakukumishilako, Lushimbi lwakufwana ngana lwatela kupwako.</para>
    <para>Chapwa chakutamo kuneha chivwashano nawusepa mukachi kamafuchi.</para>
    <para>Chapwa nawa chakutamo Vatu vamu Liwuka lya United Nations kweseka nakuzanga chavo kumona nge kuli kweseka hamwe muchiyoyelo chavo chamalunga na mapwevo mangana vahase kupwa vakweseka hamwe muchiyoyelo chavo.</para>
    <para>Chakutamo nawa mafuchi amuchikungulwilo kana chazango ya Lushimbi yakulivwashana vanalishiki mukachi kavo kuhasa kulivwashana na Mafuchi amu United Nations kuhasa kutwala kulutwe chivwashano kana kaha nakukavangiza nawa jingolo ja Lusesa lwa Mutu jakupwa wakulizachila nakulitambukila mukuyoya chenyi.</para>
    <para>Chapwa nawa chakutamo nakumona nge kuli chivwashano cha jishimbi ja Lusesa kana ja Mutu kwesekesa nalushiko lwa chivwashano echi.</para>
    <para>Chivwashano kana echi cha Lusesa lwajingolo ja Mutu chatela kuchitachikiza nakuchikavangiza kuvatu vosena vamu vamuchivulu muchiyoyelo chavo, nakulama nawa lushiko lwa chivwashano kana mukachi ka Vatu vosena hamwe na Mafuchi atwama mu Chikungulwilo kana chazango eyi ya Chivwashano.</para>
  </preamble>

    <title>Chihanda 1</title>
    <para>Vatu vosena vasemuka yapwa hohamwe nakweseka mukuyoya chavo. Vatwama nachiyoyelo chalusesa chajingolo chakuzanga kulivwashana muchiyoyelo chavo.</para>

    <title>Chihanda 2</title>
    <para>Mutu wosena atwama nalusesa lwajingolo josena eji vetavila mukaye jakuhona kulihandununa chakufwana nge kulitala havikova, miyachi, kulihandununa chavatu vamukaye mukusemuka chavo hamwe namukutwama chavo hano hakaye.</para>
    <para>Kakwechi kupwa kukalihandununa mwomwo wajishimbi, jizango chipwe kulihandununa chamafuchi mujishimbi namuchiyulo chipwe lifuchi kuze afuma mutu, chipwe lifuchi lyakulimanyina, lyalifwelela muchiyulo chalyo, kalyaliyula liveneko, chipwe lyapwa kanda lilimanyine muchiyulo.</para>

    <title>Chihanda 3</title>
    <para>Mutu wosena analusesa lwachiyoyelo chenyi, kupwa wakusokoka kaha mutu vanahase kukinga.</para>

    <title>Chihanda 4</title>
    <para>Kakwechi kukapwa mutu mwakapwa muwundungoko, kuzata milimo yakushinjila yawana, nawundungo wakukwata vatu navakawukanyisa mujijila josena.</para>

    <title>Chihanda 5</title>
    <para>Kakwechi kukapwa mutu navakayanjisa mujijila josena jajipiko chipwe kumuhombwanyisa numba kumuzangamisako.</para>

    <title>Chihanda 6</title>
    <para>Mutu wosena atela kupwa nalusesa lwajingolo jakulisolola kwosena kupwa nge mutu shimbu kanda jishimbi.</para>

    <title>Chihanda 7</title>
    <para>Vatu vosena vaneseka hamwe shimbu kanda jijishimbi kaha vanalusesa lwakuvakinga kujishimbi. Vosena vaneseka hamwe kaha kakwechi kupwa wumwe mwahambakana mukwavokoko kwesekesa nalushiko kuhona kuyanjisa chipwe kumuhandununa kuvakwavo.</para>

    <title>Chihanda 8</title>
    <para>Mutu wosena analusesa lwakumukinga kuvikungulwilo vyosena navipwangako vyakutala hakuyanjisa chamutu halushimbi vahana mutu lwakupwa wakulimanyina muchiyoyela chenyi kwesekesa nalushimbi.</para>

    <title>Chihanda 9</title>
    <para>Kakwechi kukakpwa kulikwachila chamutuko, kumutumbika mutolongo chipwe kuchinyina kweka.</para>

    <title>Chihanda 10</title>
    <para>Mutu wosena analusesa lwakwivwilila chihande chenyi ku zango yayinene yakaye yakulimanyina, nge vanawane mutu kana anamulonga wunapandama kuchiyoyelo chenyi.</para>

    <title>Chihanda 11</title>
    <orderedlist>
      <listitem>
	<para>Wosena navawana namulonga wawunene anajingolo jakuvangila kumuwana nge anamulonga shimbu kanda vamusopese, kaha atela kulihakwila yavene.</para>
      </listitem>
      <listitem>
	<para>Kakwechi kukapwa kuwanyina mulonga mutuko mwomwo hakuhona kumuwanyina chihande chamulonga wawunene, kwesekesa najishimbi jamuze mulifuchi chipwe kaye, halwola kana alvulumwine wuze mulonga. Chipwe kakwechi kukahana mulonga wawunene wuze mutuko kuhambakana wuze mulonga avulumine halwola kana lwakavanga.</para>
      </listitem>
    </orderedlist>

    <title>Chihanda 12</title>
    <para>Kakwechi kukapwa kuyanjisa mutu kwasekesa namukutwama chenyiko, tanga yenyi, limbo lyenyi, chipwe mukusonejeka chipwe kumusawula. Mutu wosena analusesa lwajingolo lwakumukinga lwalushimbi lwakuhona kumwivwisa woma.</para>

    <title>Chihanda 13</title>
    <orderedlist>
      <listitem>
	<para>Mutu wosena analusesa lwakulitambukila nakutwama kala kungalila mukachi kalifuchi lyenyi.</para>
      </listitem>
      <listitem>
	<para>Mutu analusesa lwakufuma mulifuchi lyosena nazange chipwe mulifuchi lyenyi nakukinduluka cheka muze mulifuchi lyenyi atwama.</para>
      </listitem>
    </orderedlist>

    <title>Chihanda 14</title>
    <orderedlist>
      <listitem>
	<para>Kala mutu analusesa lwakuzanga kuwahilila muchiyoyelo chenyi mumafuchi eka kuchina kuhona kumusopesa.</para>
      </listitem>
      <listitem>
	<para>Lusesa kana kalwechi kupwa nge mujila yize nayijila kwesekesa najijila jajipi javihande vyamafuchi chipwe kavetavila kwesekesa navishinganyeka vyakava United Nations.</para>
      </listitem>
    </orderedlist>

    <title>Chihanda 15</title>
    <orderedlist>
      <listitem>
	<para>Kala mutu analusesa lwakupwa mutu wamulifuchi kana.</para>
      </listitem>
      <listitem>
	<para>Kakwechi kupwa kukafumisa mutu wuze nalisonekesa nakupwa mutu wamulifuchi kana chipwe kumukanyisa kwalumuna mutu kana kupwa wamulifuchi nazange.</para>
      </listitem>
    </orderedlist>

    <title>Chihanda 16</title>
    <orderedlist>
      <listitem>
	<para>Malunga namapwevo vanamyaka yakutumo yakusemuka, chakuhona kuvakanyisa mwomwo wamiyachi navikova, mazu akalunga chipwe numba kavafuma mulifuchi kanako, vanalusesa lwakulimbata nakupwa najitanga. Vanalusesa lwakulimbata, mukutwama chavo chosena hakulimbata kaha nomu nawafwa aze malwavo.</para>
      </listitem>
      <listitem>
	<para>Kulimbata chosena navakachitavisa kwesekesa nakwitavila chavisemi jalunga napwevo vaze vanakuzanga kulimbata.</para>
      </listitem>
      <listitem>
	<para>Tanga kana navakayikinga kuvyuma vyosena mangana vapwenga vatu vakuliyoyela muchiyoyelo kana chalifuchi.</para>
      </listitem>
    </orderedlist>

    <title>Chihanda 17</title>
    <orderedlist>
      <listitem>
	<para>Kala mutu analusesa lwakupita wupite wukawenyi kaha numba nakulifutula navakwavo.</para>
      </listitem>
      <listitem>
	<para>Kakwechi kukapwa kunyanga wupite wamutuko.</para>
      </listitem>
    </orderedlist>

    <title>Chihanda 18</title>
    <para>Mutu wosena analusesa lwakulitambukila nakushinganyeka, mukutwama chenyi namumazu akalunga, lusesa kana elu lwakwitavisa wuze mutu kufuma kala muchikungulwilo chamazu akalunga eka nakwingila kweka, chipwe numba wukawenyi numba navakwavo muze mungalila, kuhasa kutwalaho namazu kana nakutangisa namuvilombelo vyenyi.</para>

    <title>Chihanda 19</title>
    <para>Mutu wosena analusesa lwavishinganyeka nakuhajika, lusesa kana lunapu lwakushinganyeka vishinganyeka vyenyi chakuhona kupwa nawoma kaha nakuzanga kutambula nakunangula mazu navishinganyeka kuhichila mukala mazu amijimbu chakuhona veka kumukinga.</para>

    <title>Chihanda 20</title>
    <orderedlist>
      <listitem>
	<para>Mutu wosena anajingolo jakuhasa kulikungulula chakuhona woma kaha namumawuka.</para>
      </listitem>
      <listitem>
	<para>Kakwechi kupwa kushinjila mutu kwingila muchikungulwiloko.</para>
      </listitem>
    </orderedlist>

    <title>Chihanda 21</title>
    <orderedlist>
      <listitem>
	<para>Mutu wosena analusesa lwakuhanjika vihande mufulumende yalifuchi lyenyi, yikiye chipwe kuhichila muli vatu vasakula navamwimanyinako.</para>
      </listitem>
      <listitem>
	<para>Kala mutu analusesa lwakupwa hamwe kutachikiza vyuma mumilimo yamulifuchi lyenyi.</para>
      </listitem>
      <listitem>
	<para>Kuzanga chavatu chikiko nachihasa kuneha jingolo jafulumende jalifuchi lyosena nachipwa chakusweka hakuvwota, chipwe kukavangiza jijila jikwavo jakuvwotelamo.</para>
      </listitem>
    </orderedlist>

    <title>Chihanda 22</title>
    <para>Mutu wosena hakupwa wamuchiyoyelo analusesa lwakupwa najijila jimwe jakuhasa kupwa wakilikinga, kupwa nalisesa lwakupwa nawupite mujila yatela lifuchi chipwe kaye yetavila muluheto, mukutwama chavatu hamwe nachisemwa kaha hawulemu nalusesa lwakulizachila lwakutwala milimo kana kulutwe kuli wuze mutu.</para>

    <title>Chihanda 23</title>
    <orderedlist>
      <listitem>
	<para>Mutu wosena ali nalusesa lwakuzata milimo kwosena nazange, kukavangiza jijila jamwaza jakuzachilamo yize milimo kaha nakumukinga wuze mutu kuchina mwahona kuwana milimo.</para>
      </listitem>
      <listitem>
	<para>Kala mutu chakuhona kulihandununa atela kutambula fweto yakutamo.</para>
      </listitem>
      <listitem>
	<para>Wosena anakuzata analusesa lwakutambula fweto yakutamo kwesekes namilimo anakuzata mwahasa kulikafwa nawo natanga yenyi kwesekesa nachiyoyelo chenyi, chipwe kuwana jijila jikwavo mwahasa kuwanyinamo mali akulikafwa nawo.</para>
      </listitem>
      <listitem>
	<para>Mutu wosena analusesa lwakuputuka chipwe kwingila muchikungulwilo nachihasa kumuhanjikilako nakumukinga mukuyoya chenyi.</para>
      </listitem>
    </orderedlist>

    <title>Chihanda 24</title>
    <para>Mutu wosena analusesa lwakupwa nalwola lwakunoka lwaviseke, kupwa nalwola lwamweseke lwakuzachilamo milimo kaha najilwola nawa jakunoka vatela wuze mutu kumuhana fweto.</para>

    <title>Chihanda 25</title>
    <orderedlist>
      <listitem>
	<para>Mutu wosela analusesa lwakupwa nachiyoyelo chakutamo kupwa mutu wamulemu hamwe natanga yenyi mukulya, mukuvwala nakulikangula kumijimba hamwe navyuma vyazangiwa kukuyoya chamutu, lusesa lwakumukafwa halwola mwapwa tuliwe, kashinakaji chipwe mwahona vyuma vyatela kupwa vyakumukafwa mukuyoya chenyi.</para>
      </listitem>
      <listitem>
	<para>Mapwevo navanyike vavandende vatela kupwa nalusesa lwakuvatala kanawa, kaha mwana wuze nasemukila kweka kechi wamuze muzuvoko vatela kumulama kanawa apwenga nachiyoyelo chamwaza.</para>
      </listitem>
    </orderedlist>

    <title>Chihanda 26</title>
    <orderedlist>
      <listitem>
	<para>Mutu wosena analusesa lwakutanga. Kutanga chosena chatela kupwa chawana, kufuma kukuputuka nakuheta kwakamwihi nakukukuma chakutanga. Kutanga chakuputukishilako chetala kupwa chawana. Kutanga chakulinangula Milimo nachipwako kaha kutanga chize chakuhambakanyisa nachipwa lika kuvat vosena kwesekesa namangana avovali nawo.</para>
      </listitem>
      <listitem>
	<para>Kutanga chosena nachipwako kwesekesa namangana amutu mangana apwenga wakulimanyina muchiyoyelo chenyi chajingolo jamutu. Nachinehesa mutu kuhasa kumutwala kulutwe, kumuwanyisa wusepa mukachi kamafuchi, vatu veka naveka mawuka eka avakakwitava, kaha nachitwala milimo yavaka United Nations kulutwe mukuneha kuwunda.</para>
      </listitem>
      <listitem>
	<para>Visemi vanalisesa lwakusakula shikola muka chipwe kutanga muka anakuzanga chawuze mwanenyi.</para>
      </listitem>
    </orderedlist>

    <title>Chihanda 27</title>
    <orderedlist>
      <listitem>
	<para>Kala mutu analisesa lwakuhasa kutwala chisemwa kulutwe changalila kana, kuwahilila chavyuma vyachisemwa kaha nakutambasana chisemwa kana nakuwana kuwaha chacho.</para>
      </listitem>
      <listitem>
	<para>Mutu wosena analusesa lwakukinga chisemwa chenyi, kwesekesa nomu navahasa veka kuhasa kuchalumuna chipwe numba kuchisoneka kwesekesa nomu nachisoneka yavene.</para>
      </listitem>
    </orderedlist>

    <title>Chihanda 28</title>
    <para>Mutu wosena wukwechi lusesa muvyuma vyachiyoyelo cheyi omu mukwechi jingolo jajishimbi vanavuluka kwesekesa nalushiko elu vanafwelela.</para>

    <title>Chihanda 29</title>
    <orderedlist>
      <listitem>
	<para>Mutu wosena anamulimo mungalila yize anakuyoyela yinakuya kulutwe.</para>
      </listitem>
      <listitem>
	<para>Mulusesa kana lwachiyulo, mutu wosena mwakapwa nalusesa lwakukavangiza lushimbu kwesekesa najishimbi jize navaketavila nakulilemesa vatu vavene nakupwa nakavumbi muchiyoyelo chavo.</para>
      </listitem>
      <listitem>
	<para>Lusesa lwajingolo kana eji jakwitavila jachiyulo kanda kala lwola kujisachisa nakuzomboka kwesekesa najishimbi javaka United Nations.</para>
      </listitem>
    </orderedlist>

    <title>Chihanda 30</title>
    <para>Kanda kuchifwelela nge echikulikasa kana chalufwelelo chinapandama kulifuchi limwe kahako, liwuka chipwe mutu kala lisesa lwa jingolo mwahasa kulilingila vyuma chipwe chuma echi nachihasa kupihisa jishimbi kana jalusesa vanasonekako.</para>

</udhr>


text:
export voltage
typealias Danavoltage Danapositive
type _voltage
	function _voltage(_::Dict{Symbol,Any})
		fields::Dict{Symbol,Any}=Dict{Symbol,Any}()
		fields[:Brief]="Electrical Voltage"
		fields[:Default]=100
		fields[:Upper]=1e9
		fields[:finalUnit]="V"
		drive!(fields,_)
		new(_positive(fields).value)
	end
	value::Dict{Symbol,Any}
end
typealias voltage Danapositive{_voltage}


text:
import unittest

from s3.s3utils import *
from s3.s3data import S3DataTable
from s3.s3datetime import S3Calendar, S3DefaultTZ

from unit_tests import run_suite

# =============================================================================
class S3TypeConverterTests(unittest.TestCase):
    """ Test S3TypeConverter """

    # -------------------------------------------------------------------------
    def setUp(self):

        settings = current.deployment_settings

        # Make sure date+time formats are standard
        self.date_format = settings.get_L10n_date_format()
        self.time_format = settings.get_L10n_time_format()
        settings.L10n.date_format = "%Y-%m-%d"
        settings.L10n.time_format = "%H:%M:%S"

        # Set timezone to UTC
        self.tzinfo = current.response.s3.tzinfo
        current.response.s3.tzinfo = S3DefaultTZ(0)

        # Set calendar to Gregorian
        self.calendar = current.calendar
        current.calendar = S3Calendar("Gregorian")

    # -------------------------------------------------------------------------
    def tearDown(self):

        settings = current.deployment_settings

        # Reset date and time format settings
        settings.L10n.date_format = self.date_format
        settings.L10n.time_format = self.time_format

        # Reset time zone
        current.response.s3.tzinfo = self.tzinfo

        # Restore current calendar
        current.calendar = self.calendar

    # -------------------------------------------------------------------------
    def testDate(self):
        """ Test date conversion """

        assertEqual = self.assertEqual
        settings = current.deployment_settings
        response = current.response

        convert = S3TypeConverter._date

        # Set custom format
        settings.L10n.date_format = "%d.%m.%Y"

        # Verify that ISO format always works
        result = convert("2011-10-01")
        assertEqual(result, datetime.date(2011, 10, 1))

        # Verify that local format always works
        result = convert("01.10.2011")
        assertEqual(result, datetime.date(2011, 10, 1))

        # Verify without offset
        response.s3.tzinfo = S3DefaultTZ(0)
        result = convert("2011-10-01")
        assertEqual(result, datetime.date(2011, 10, 1))

        # Verify with offset
        # => Date without time part means 08:00 local time zone,
        #    so 2 hours East means the same day UTC, 06:00
        response.s3.tzinfo = S3DefaultTZ(+2)
        result = convert("2011-10-01")
        assertEqual(result, datetime.date(2011, 10, 1))
        result = convert("01.05.2015")
        assertEqual(result, datetime.date(2015, 5, 1))

        # Cross into the next day
        # => Date without time part means 08:00 local time zone,
        #    so 11 hours East means previous day UTC, 21:00
        response.s3.tzinfo = S3DefaultTZ(+11)
        result = convert("2011-10-01")
        assertEqual(result, datetime.date(2011, 9, 30))

        # Reset to ISO format
        settings.L10n.date_format = "%Y-%m-%d"

        # Date+Time always convert to the exact UTC date
        # => 11 hours West of 22:00 is the same day
        result = convert("2011-10-01T22:00:00")
        assertEqual(result, datetime.date(2011, 10, 1))
        # => 11 hours West of 09:00 is the previous day
        result = convert("2011-10-01T09:00:00")
        assertEqual(result, datetime.date(2011, 9, 30))

        # Explicit timezone in string overrides default offset
        # => trailing Z means UTC
        result = convert("2011-10-01T09:00:00Z")
        assertEqual(result, datetime.date(2011, 10, 1))

    # -------------------------------------------------------------------------
    def testDateTime(self):
        """ Test date/time conversion """

        assertEqual = self.assertEqual
        settings = current.deployment_settings
        response = current.response

        convert = S3TypeConverter._datetime

        # Set custom format
        settings.L10n.date_format = "%d.%m.%Y"
        settings.L10n.time_format = "%H.%M"

        # Verify that ISO format always works
        result = convert("2011-10-01T16:37:00")
        assertEqual(result, datetime.datetime(2011, 10, 1, 16, 37, 0))

        # Verify that local format always works
        result = convert("01.10.2011 16.37")
        assertEqual(result, datetime.datetime(2011, 10, 1, 16, 37, 0))

        # Reset to ISO format
        settings.L10n.date_format = "%Y-%m-%d"
        settings.L10n.time_format = "%H:%M:S"

        # Verify without offset
        response.s3.tzinfo = S3DefaultTZ(0)
        result = convert("2011-10-01 07:30:00")
        assertEqual(result, datetime.datetime(2011, 10, 1, 7, 30, 0))

        # Verify with offset
        response.s3.tzinfo = S3DefaultTZ(+11)
        result = convert("2011-10-01T22:00:00")
        assertEqual(result, datetime.datetime(2011, 10, 1, 11, 0, 0))
        result = convert("2011-10-01T09:00:00")
        assertEqual(result, datetime.datetime(2011, 9, 30, 22, 0, 0))
        # Explicit timezone in string overrides offset
        result = convert("2011-10-01T09:00:00Z")
        assertEqual(result, datetime.datetime(2011, 10, 1, 9, 0, 0))

# =============================================================================
class S3FKWrappersTests(unittest.TestCase):
    """ Test has_foreign_key and get_foreign_key """

    # -------------------------------------------------------------------------
    def testHasForeignKey(self):
        """ Test has_foreign_key """

        ptable = current.s3db.pr_person
        self.assertFalse(s3_has_foreign_key(ptable.first_name))
        self.assertTrue(s3_has_foreign_key(ptable.pe_id))

        htable = current.s3db.hrm_human_resource
        self.assertFalse(s3_has_foreign_key(htable.start_date))
        self.assertTrue(s3_has_foreign_key(htable.person_id))

        # @todo: restore with a different list:reference
        #otable = s3db.org_organisation
        #self.assertTrue(s3_has_foreign_key(otable.multi_sector_id))
        #self.assertFalse(s3_has_foreign_key(otable.multi_sector_id, m2m=False))

    # -------------------------------------------------------------------------
    def testGetForeignKey(self):

        ptable = current.s3db.pr_person
        ktablename, key, multiple = s3_get_foreign_key(ptable.pe_id)
        self.assertEqual(ktablename, "pr_pentity")
        self.assertEqual(key, "pe_id")
        self.assertFalse(multiple)

        # @todo: restore with a different list:reference
        #otable = s3db.org_organisation
        #ktablename, key, multiple = s3_get_foreign_key(otable.multi_sector_id)
        #self.assertEqual(ktablename, "org_sector")
        #self.assertEqual(key, "id")
        #self.assertTrue(multiple)

        # @todo: restore with a different list:reference
        #ktablename, key, multiple = s3_get_foreign_key(otable.multi_sector_id, m2m=False)
        #self.assertEqual(ktablename, None)
        #self.assertEqual(key, None)
        #self.assertEqual(multiple, None)

# =============================================================================
class S3MarkupStripperTests(unittest.TestCase):
    """ Test for S3MarkupStripper """

    def testConstructor(self):
        """ Verify Python-2 compatibility of constructor """

        # Base class of S3MarkupStripper is a Python-2 old-style class,
        # so super() call in constructor could raise a TypeError unless
        # multiple inheritance with object enforces a new-style class
        stripper = S3MarkupStripper()

# =============================================================================
if __name__ == "__main__":

    run_suite(
        S3TypeConverterTests,
        S3FKWrappersTests,
        S3MarkupStripperTests,
        )

# END ========================================================================


text:
package mcjty.rftools.commands;

import mcjty.varia.Logging;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;

public class CmdDebugToggle extends AbstractRfToolsCommand {
    @Override
    public String getHelp() {
        return "";
    }

    @Override
    public String getCommand() {
        return "toggle";
    }

    @Override
    public int getPermissionLevel() {
        return 1;
    }

    @Override
    public boolean isClientSide() {
        return false;
    }

    @Override
    public void execute(ICommandSender sender, String[] args) {
        Logging.debugMode = !Logging.debugMode;
        if (Logging.debugMode) {
            sender.addChatMessage(new ChatComponentText(EnumChatFormatting.YELLOW + "RFTools Debug Mode enabled!"));
        } else {
            sender.addChatMessage(new ChatComponentText(EnumChatFormatting.YELLOW + "RFTools Debug Mode disabled!"));
        }
    }
}


text:
namespace nom {
namespace repr {

/// \brief A basic block holds a reference to a subgraph
/// of the data flow graph as well as an ordering on instruction
/// execution.  Basic blocks are used for control flow analysis.
template <typename T, typename U> class BasicBlock {
public:
  using NodeRef = typename Subgraph<T, U>::NodeRef;
  BasicBlock() {}
  ~BasicBlock() {
    for (auto pair : callbacks) {
      pair.first->deleteDestructorCallback(pair.second);
    }
  }

  void trackNode(NodeRef node) {
    callbacks[node] = node->registerDestructorCallback([&](NodeRef n){
        assert(hasInstruction(n) && "Destructor callback invoked on untracked node in BasicBlock.");
        deleteInstruction(n);
    });
    Nodes.addNode(node);
  }

  void untrackNode(NodeRef node) {
    callbacks.erase(node);
    Nodes.removeNode(node);
  }

  void pushInstructionNode(NodeRef node) {
    assert(isa<Instruction>(node->data()) &&
           "Cannot push non-instruction node to basic block.");
    Instructions.emplace_back(node);
    trackNode(node);
  }
  const std::vector<NodeRef> &getInstructions() { return Instructions; }

  const bool hasInstruction(NodeRef instr) const {
    return Nodes.hasNode(instr);
  }

  void insertInstructionBefore(NodeRef newInstr, NodeRef instr) {
    auto it = std::find(std::begin(Instructions), std::end(Instructions), instr);
    Instructions.insert(it, newInstr);
    trackNode(newInstr);
  }

  void deleteInstruction(NodeRef instr) {
    assert(hasInstruction(instr) && "Instruction not in basic block.");
    Instructions.erase(std::remove(Instructions.begin(), Instructions.end(), instr),
        Instructions.end());
    untrackNode(instr);
  }

private:
  Subgraph<T, U> Nodes;
  std::vector<NodeRef> Instructions;
  // Because we reference a dataflow graph, we need to register callbacks
  // for when the dataflow graph is modified.
  std::unordered_map<NodeRef, typename Notifier<Node<T, U>>::Callback *> callbacks;
};

using Program = Graph<Value>;

template <typename G> struct ControlFlowGraphImpl {
  // Hack to help debugging in case this class is misused.
  static_assert(sizeof(ControlFlowGraphImpl), "Template parameter G in "
                                              "ControlFlowGraph<G> must be of "
                                              "type Graph<T, U>.");
};

template <typename T, typename U> struct ControlFlowGraphImpl<Graph<T, U>> {
  using type = Graph<std::unique_ptr<BasicBlock<T, U>>, int>;
  using bbType = BasicBlock<T, U>;
};

/// \brief Control flow graph is a graph of basic blocks that
/// can be used as an analysis tool.
///
/// \note G Must be of type Graph<T, U>.
template<typename G>
class ControlFlowGraph : public ControlFlowGraphImpl<G>::type {
public:
  // This is for C++11 compatibility, otherwise we could use "using"
  ControlFlowGraph() {}
  ControlFlowGraph(const ControlFlowGraph &) = delete;
  ControlFlowGraph(ControlFlowGraph &&) = default;
  ControlFlowGraph& operator=(ControlFlowGraph &&) = default;
  ~ControlFlowGraph() {
  }
};

/// \brief Helper for extracting the type of BasicBlocks given
/// a graph (probably a dataflow graph).  TODO: refactor this
/// to come from something like Graph::NodeDataType
template <typename G>
using BasicBlockType = typename ControlFlowGraphImpl<G>::bbType;

/// \brief Converts graph to SSA representation.  Modifies the graph
/// by inserting versions and phi nodes.
template <typename Phi, typename G> void addSSA(G* dfg, ControlFlowGraph<G> *cfg) {
  static_assert(std::is_base_of<Instruction, Phi>::value, "Phi type must be derived from Instruction.");
  auto dfMap = dominanceFrontierMap(cfg);
  for (auto pair : dfMap) {
    for (auto n : pair.second) {
      printf("%llu -> %llu\n", (unsigned long long)pair.first, (unsigned long long)n);
    }
  }
}

/// \brief Deletes a referenced node from the control flow graph.
template <typename G>
void deleteNode(ControlFlowGraph<G>* cfg, typename G::NodeRef node) {
  for (auto bbNode : cfg->getMutableNodes()) {
    auto bb = bbNode->data().get();
    if (bb->hasInstruction(node)) {
      bb->deleteInstruction(node);
    }
  }
}

} // namespace repr
} // namespace nom

#endif // NOM_REPRESENTATIONS_CONTROLFLOW_H


text:
/**
 * @jsx React.DOM
 */

var React = require('react');
var CodeMirror = global.CodeMirror;
var JSXTransformer = global.JSXTransformer;
var TabbedArea = require('../../cjs/TabbedArea');
var TabPane = require('../../cjs/TabPane');
var Alert = require('../../cjs/Alert');
var Button = require('../../cjs/Button');
var Nav = require('../../cjs/Nav');
var NavItem = require('../../cjs/NavItem');

var IS_MOBILE = typeof navigator !== 'undefined' && (
  navigator.userAgent.match(/Android/i)
    || navigator.userAgent.match(/webOS/i)
    || navigator.userAgent.match(/iPhone/i)
    || navigator.userAgent.match(/iPad/i)
    || navigator.userAgent.match(/iPod/i)
    || navigator.userAgent.match(/BlackBerry/i)
    || navigator.userAgent.match(/Windows Phone/i)
  );

var CodeMirrorEditor = React.createClass({
  componentDidMount: function() {
    if (IS_MOBILE) return;

    this.editor = CodeMirror.fromTextArea(this.refs.editor.getDOMNode(), {
      mode: 'javascript',
      lineNumbers: false,
      lineWrapping: true,
      matchBrackets: true,
      tabSize: 2,
      theme: 'solarized-light',
      readOnly: this.props.readOnly
    });
    this.editor.on('change', this.handleChange);
  },

  componentDidUpdate: function() {
    if (this.props.readOnly) {
      this.editor.setValue(this.props.codeText);
    }
  },

  handleChange: function() {
    if (!this.props.readOnly) {
      this.props.onChange && this.props.onChange(this.editor.getValue());
    }
  },

  render: function() {
    // wrap in a div to fully contain CodeMirror
    var editor;

    if (IS_MOBILE) {
      var preStyles = {overflow: 'scroll'};
      editor =
{this.props.codeText}
;
    } else {
      editor = <textarea ref="editor" defaultValue={this.props.codeText} />;
    }

    return (

        {editor}

      );
  }
});

var selfCleaningTimeout = {
  componentDidUpdate: function() {
    clearTimeout(this.timeoutID);
  },

  setTimeout: function() {
    clearTimeout(this.timeoutID);
    this.timeoutID = setTimeout.apply(null, arguments);
  }
};

var ReactPlayground = React.createClass({
  mixins: [selfCleaningTimeout],

  MODES: {JSX: 'JSX', JS: 'JS', NONE: null},

  propTypes: {
    codeText: React.PropTypes.string.isRequired,
    transformer: React.PropTypes.func,
    renderCode: React.PropTypes.bool
  },

  getDefaultProps: function() {
    return {
      transformer: function(code) {
        return JSXTransformer.transform(code).code;
      }
    };
  },

  getInitialState: function() {
    return {
      mode: this.MODES.NONE,
      code: this.props.codeText
    };
  },

  handleCodeChange: function(value) {
    this.setState({code: value});
    this.executeCode();
  },

  handleCodeModeSwitch: function(mode) {
    this.setState({mode: mode});
  },

  handleCodeModeToggle: function(e) {
    var mode;

    e.preventDefault();

    switch (this.state.mode) {
      case this.MODES.NONE:
        mode = this.MODES.JSX;
        break;
      case this.MODES.JSX:
      default:
        mode = this.MODES.NONE;
    }

    this.setState({mode: mode});
  },

  compileCode: function() {
    return this.props.transformer(this.state.code);
  },

  render: function() {
    var editor;

    if (this.state.mode !== this.MODES.NONE) {
       editor = (
           <CodeMirrorEditor
             key="jsx"
             onChange={this.handleCodeChange}
             className="highlight"
             codeText={this.state.code}/>
        );
    }
    return (

        {editor}
        {this.state.mode === this.MODES.NONE ? 'show code' : 'hide code'}

      );
  },

  componentDidMount: function() {
    this.executeCode();
  },

  componentWillUpdate: function(nextProps, nextState) {
    // execute code only when the state's not being updated by switching tab
    // this avoids re-displaying the error, which comes after a certain delay
    if (this.state.code !== nextState.code) {
      this.executeCode();
    }
  },

  executeCode: function() {
    var mountNode = this.refs.mount.getDOMNode();

    try {
      React.unmountComponentAtNode(mountNode);
    } catch (e) { }

    try {
      var compiledCode = this.compileCode();
      if (this.props.renderCode) {
        React.renderComponent(
          <CodeMirrorEditor codeText={compiledCode} readOnly={true} />,
          mountNode
        );
      } else {
        eval(compiledCode);
      }
    } catch (err) {
      this.setTimeout(function() {
        React.renderComponent(
          <Alert bsStyle="danger">{err.toString()}</Alert>,
          mountNode
        );
      }, 500);
    }
  }
});

module.exports = ReactPlayground;


text:
class Context:
    def __init__(self, data, parent = None):
        self.data = data
        self.is_dict = isinstance(data, dict)
        self.parent = parent

    def get(self, key):
        if key == u'.':
            return self.data

        parts = key.split(u'.')
        key = parts[0]
        ctx = self
        while True:
            if ctx.is_dict:
                try:
                    value = ctx.data[key]
                    break
                except:
                    pass
            else:
                try:
                    value = getattr(ctx.data, key)
                    break
                except:
                    pass

            if ctx.parent:
                ctx = ctx.parent
            else:
                return ''

        for part in parts[1:]:
            try:
                if isinstance(value, dict):
                    value = value[part]
                else:
                    value = getattr(value, part)
            except:
                return ''
        return value


text:
import { moduleFor, test } from 'ember-qunit';

moduleFor('transform:<%= dasherizedModuleName %>', '<%= friendlyTestDescription %>', {
  // Specify the other units that are required for this test.
  // needs: ['serializer:foo']
});

// Replace this with your real tests.
test('it exists', function(assert) {
  let transform = this.subject();
  assert.ok(transform);
});


text:
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
package com.witchcraft.common.core.capability.brew;

import mcp.MethodsReturnNonnullByDefault;

import javax.annotation.ParametersAreNonnullByDefault;


text:
<?php

namespace FOS\MessageBundle\Sender;

use FOS\MessageBundle\Model\MessageInterface;

/**
 * Sends messages.
 *
 * @author Thibault Duplessis <thibault.duplessis@gmail.com>
 */
interface SenderInterface
{
    /**
     * Sends the given message.
     */
    public function send(MessageInterface $message);
}


text:
package com.gitblit.authority;

import java.math.BigInteger;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.eclipse.jgit.lib.Config;

import com.gitblit.Constants;
import com.gitblit.models.UserModel;
import com.gitblit.utils.ArrayUtils;
import com.gitblit.utils.StringUtils;
import com.gitblit.utils.TimeUtils;
import com.gitblit.utils.X509Utils.RevocationReason;

public class UserCertificateModel implements Comparable<UserCertificateModel> {
		public UserModel user;
		public Date expires;
		public List<X509Certificate> certs;
		public List<String> revoked;
		public String notes;

		public UserCertificateModel(UserModel user) {
			this.user = user;
		}

		public void update(Config config) {
			if (expires == null) {
				config.unset("user",  user.username, "expires");
			} else {
				SimpleDateFormat df = new SimpleDateFormat(Constants.ISO8601);
				config.setString("user", user.username, "expires", df.format(expires));
			}
			if (StringUtils.isEmpty(notes)) {
				config.unset("user",  user.username, "notes");
			} else {
				config.setString("user", user.username, "notes", notes);
			}
			if (ArrayUtils.isEmpty(revoked)) {
				config.unset("user",  user.username, "revoked");
			} else {
				config.setStringList("user", user.username, "revoked", revoked);
			}
		}

		@Override
		public int compareTo(UserCertificateModel o) {
			return user.compareTo(o.user);
		}

		public void revoke(BigInteger serial, RevocationReason reason) {
			if (revoked == null) {
				revoked = new ArrayList<String>();
			}
			revoked.add(serial.toString() + ":" + reason.ordinal());
			expires = null;
			for (X509Certificate cert : certs) {
				if (!isRevoked(cert.getSerialNumber())) {
					if (!isExpired(cert.getNotAfter())) {
						if (expires == null || cert.getNotAfter().after(expires)) {
							expires = cert.getNotAfter();
						}
					}
				}
			}
		}

		public boolean isRevoked(BigInteger serial) {
			return isRevoked(serial.toString());
		}

		public boolean isRevoked(String serial) {
			if (ArrayUtils.isEmpty(revoked)) {
				return false;
			}
			String sn = serial + ":";
			for (String s : revoked) {
				if (s.startsWith(sn)) {
					return true;
				}
			}
			return false;
		}

		public RevocationReason getRevocationReason(BigInteger serial) {
			try {
				String sn = serial + ":";
				for (String s : revoked) {
					if (s.startsWith(sn)) {
						String r = s.substring(sn.length());
						int i = Integer.parseInt(r);
						return RevocationReason.values()[i];
					}
				}
			} catch (Exception e) {
			}
			return RevocationReason.unspecified;
		}

		public CertificateStatus getStatus() {
			if (expires == null) {
				return CertificateStatus.unknown;
			} else if (isExpired(expires)) {
				return CertificateStatus.expired;
			} else if (isExpiring(expires)) {
				return CertificateStatus.expiring;
			}
			return CertificateStatus.ok;
		}

		public boolean hasExpired() {
			return expires != null && isExpiring(expires);
		}

		public CertificateStatus getStatus(X509Certificate cert) {
			if (isRevoked(cert.getSerialNumber())) {
				return CertificateStatus.revoked;
			} else if (isExpired(cert.getNotAfter())) {
				return CertificateStatus.expired;
			} else if (isExpiring(cert.getNotAfter())) {
				return CertificateStatus.expiring;
			}
			return CertificateStatus.ok;
		}

		private boolean isExpiring(Date date) {
			return (date.getTime() - System.currentTimeMillis()) <= TimeUtils.ONEDAY * 30;
		}

		private boolean isExpired(Date date) {
			return date.getTime() < System.currentTimeMillis();
		}
	}


text:
from setuptools import setup , find_namespace_packages

setup(name='PeriPyDIC',
      version='0.3',
      description='Peridynamics (PD) computations for state-based PD in 1D, 2D for elastic and viscoelastic materials. Also possible to import Digital Image Correlation results and compute PD forces for each pixel as a node.',
      author='Patrick Diehl, Rolland Delorme, Ilyass Tabiai',
      author_email='patrickdiehl@lsu.edu, rolland.delorme@polymtl.ca, ilyass.tabiai@polymtl.ca',
      url='https://github.com/lm2-poly/PeriPyDIC',
      keywords='material science, peridynamics, digital image correlation',
      license='GPL-3.0',
      packages=find_namespace_packages(where="./"),
      zip_safe=False)


text:
object Test {

  def main(args: Array[String]): Unit = {
    println(Index.succ["bar", "foo", ("bar", ("baz", Unit))])
  }
}