text:
SCC is a collection of services which allow you to easily deploy and scale SocketCluster to any number of machines.
SCC is designed to scale linearly and is optimized for running on Kubernetes but it can be setup without using an orchestrator.

SCC is made up of the following services:

- scc-worker (SocketCluster) https://github.com/SocketCluster/socketcluster
- scc-broker https://github.com/SocketCluster/scc-broker
- scc-state https://github.com/SocketCluster/scc-state
- scc-ingress (Kubernetes only)

## How it works

The **scc-worker** service can be made up of any number of regular SocketCluster instances - The main difference between running SocketCluster as a single instance vs running it as a cluster is that in cluster mode, you need to point each **scc-worker** instance to a working `scc-state` (state server) instance.

The **scc-broker** service can be made up of any number of **scc-broker** instances - This is a special backend-only service which is designed to broker
messages between multiple frontend-facing **scc-worker** instances. All the pub/sub channels in your entire system will be sharded evenly across available **scc-broker** instances.
Just like with the **scc-worker** instances above, each **scc-broker** instance needs to point to a state server in order to work.

The **scc-state** service is made up of a single instance - Its job is to dispatch the state of the cluster to all interested services to allow them to reshard themselves. The **scc-state** instance will notify all frontend **scc-worker** instances whenever a new backend **scc-broker** joins the cluster. This allows **scc-worker** instances to rebalance their pub/sub channels evenly across available brokers whenever a new **scc-broker** instance joins the cluster.
Note that SCC can continue to operate without any disruption of service while the **scc-state** instance is down/unavailable (see notes at the bottom of this page).

## Running on Kubernetes (recommended)

Running on Kubernetes (K8s) is easy; you just need to run all the `.yaml` files from the `kubernetes/` directory from the SocketCluster repo (https://github.com/SocketCluster/socketcluster/tree/master/kubernetes) using the `kubectl` command (one at a time):

```
kubectl create -f <service-deployment-or-ingress-definition.yaml>
```

By default, you should also add a TLS/SSL key and cert pair to your provider (Rancher has a page were you can just paste them in).
Or if you don't want to use a certificate (not recommended), you can just delete these lines from `scc-ingress.yaml` before you create it with `kubectl`:

```
  tls:
  - secretName: scc-tls-credentials
```

Note that the step above is crucial if you don't want to use TLS/SSL - Otherwise the ingress load balancer service will not show up on your Rancher control panel until you add some credentials with the name `scc-tls-credentials` to your Rancher control panel (See Infrastructure > Certificates page).

## Running using Node.js directly

You can also run SCC using only Node.js version >= 10.x.x.
For simplicity, we will show you how to run everything on your localhost (`127.0.0.1`), but in practice, you will need to change `127.0.0.1` to an appropriate IP, host name or domain name.

First, you need to download each of these repositories to your machine(s):

- `git clone https://github.com/SocketCluster/scc-broker`
- `git clone https://github.com/SocketCluster/scc-state`

Then inside each repo, you should run `npm install` without any arguments to install dependencies.

Then you need to setup a new SocketCluster project to use as your user-facing instance.

Once you have the two repos mentioned earlier and your SocketCluster project setup, you should launch the state server first by
going inside your local **scc-state** repo and then running the command:

```
node server
```

Next, to launch a broker, you should navigate to your **scc-broker** repo and run the command:

```
SCC_STATE_SERVER_HOST='127.0.0.1' SCC_BROKER_SERVER_PORT='8888' node server
```

Finally, to run a frontend-facing SocketCluster instance, you can navigate to your project directory and run:

```
SCC_STATE_SERVER_HOST='127.0.0.1' SOCKETCLUSTER_PORT='8000' node server
```

You can add a second frontend-facing server by running (this time running on port 8001):

```
SCC_STATE_SERVER_HOST='127.0.0.1' SOCKETCLUSTER_PORT='8001' node server
```
Now if you navigate to either `localhost:8000` or `localhost:8001` in your browser, you should see that your pub/sub channels are shared between the two **scc-worker** instances.

Note that you can provide additional environment variables to various instances to set custom port numbers, passwords etc...
For more info, you can look inside the code in the `server.js` file in each repo and see what `process.env` vars are used.

When running multiples instances of any service on the same machine, make sure that the ports don't clash - Modify the `SCC_BROKER_SERVER_PORT` or `SOCKETCLUSTER_PORT` environment variable for each instance to make sure that they are unique.

## CAP theorem

User-facing instances in SCC are highly available (this was done to ensure that SCC is resilient against DDoS attacks).
Back end instances, on the other hand, are optimized for consistency and efficiency. SCC is designed to quickly recover from failure of back end instances (a few seconds of partial missed messages at worst). Note that it's still possible to implement guaranteed delivery of messages by assigning a unique ID to each published message and resending messages which have not been acknowledged.

## Notes

You should only ever run a single **scc-state** per cluster - Note that the cluster can continue to operate without any disruption while **scc-state** is down.
**scc-state** only needs to be available for a few seconds while SCC is in the process of scaling itself up or down. Even if **scc-state** crashes while in the middle of scaling up, SCC will wait for **scc-state** to become available again (still without disruptions to the existing service) and will resume the scaling operation as soon as the **scc-state** instance becomes available again.
In the event of a crash, K8s will respawn **scc-state** within a few seconds so a failure of **scc-state** will only delay your scale up/down operation at worst.
Nevertheless, it is recommended that you run the **scc-state** instance inside your datacenter/AWS availability zone and do not expose it to the public internet.

The **scc-state** instance does not handle any pub/sub messages and so it is not a bottleneck with regards to the scalability of your cluster (SCC scales linearly).

Note that you can launch the services in any order you like but if your state server is not available, you may get harmless `Socket hung up` warnings on other instances (while they keep trying to reconnect) until **scc-state** becomes available again.


text:
package org.json4s

import org.json4s.prefs.EmptyValueStrategy

trait JsonMethods[T] {

  def parse[A: AsJsonInput](in: A, useBigDecimalForDouble: Boolean = false, useBigIntForLong: Boolean = true): JValue
  def parseOpt[A: AsJsonInput](
    in: A,
    useBigDecimalForDouble: Boolean = false,
    useBigIntForLong: Boolean = true
  ): Option[JValue]

  def render(
    value: JValue,
    alwaysEscapeUnicode: Boolean = false,
    emptyValueStrategy: EmptyValueStrategy = EmptyValueStrategy.default
  ): T
  def compact(d: T): String
  def pretty(d: T): String
}

redpajama_set_name: RedPajamaGithub


text:
function abstractSpec() { }
abstractSpec.prototype = {
    $isSatisfiedBy: function(v) { },
    isSatisfiedBy: function(v) {return this.$isSatisfiedBy(v);},
    and: function(spec) { return new andSpec(this, spec); },
    or: function(spec) { return new orSpec(this, spec); },
    xor: function(spec) { return new xorSpec(this, spec); },
    not: function() { return new notSpec(this); }
};
function andSpec (a, b) {
    andSpec.base.call(this);
    this.$1 = a;
    this.$2 = b;
}
andSpec.prototype.$isSatisfiedBy = function(c) {
    return this.$1.isSatisfiedBy(c) &&
            this.$2.isSatisfiedBy(c);
};
$.Class.extend(andSpec, abstractSpec);

function orSpec(a, b) {
    orSpec.base.call(this);
    this.$1 = a;
    this.$2 = b;
}
orSpec.prototype.$isSatisfiedBy = function(candidate) {
    return this.$1.isSatisfiedBy(candidate) ||
            this.$2.isSatisfiedBy(candidate);
};

$.Class.extend(orSpec, abstractSpec);

function xorSpec(a, b) {
    xorSpec.base.call(this);
    this.$1 = a;
    this.$2 = b;
}
xorSpec.prototype.$isSatisfiedBy = function(candidate) {
    return $.xor(this.$1.isSatisfiedBy(candidate),
                 this.$2.isSatisfiedBy(candidate));
};
$.Class.extend(xorSpec, abstractSpec);

function trueSpec() { trueSpec.base.call(this); }
trueSpec.prototype.$isSatisfiedBy = function(candidate) { return true; };
$.Class.extend(trueSpec, abstractSpec);

function falseSpec() { falseSpec.base.call(this); }
falseSpec.prototype.$isSatisfiedBy = function(candidate) { return false; };
$.Class.extend(falseSpec, abstractSpec);

function notSpec(s) {
    notSpec.base.call(this);
    this._s = s;
}
notSpec.prototype.$isSatisfiedBy = function(candidate) {
    return !this._s.isSatisfiedBy(candidate);
};
$.Class.extend(notSpec, abstractSpec);

function spec(func){
    spec.base.call(this);
    this.$isSatisfiedBy = func;
}
$.Class.extend(spec, abstractSpec);

$.spec = function(func){
    return new spec(func);
};


text:
<?php

class SimplePie_First_Item_Category_Label_Test_RSS_092_Category extends SimplePie_First_Item_Category_Label_Test
{
	function data()
	{
		$this->data =
'<rss version="0.92">
	<channel>
		<item>
			<category>Item Category</category>
		</item>
	</channel>
</rss>';
	}

	function expected()
	{
		$this->expected = 'Item Category';
	}
}

?>


text:
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace AllReady.Areas.Admin.ViewModels.Event
{
    /// <summary>
    /// User that can be assigned to the given task
    /// </summary>
    public class VolunteerCandidatesViewModel
    {
        public List<SelectListItem> Volunteers { get; set; }

        /// <summary>
        /// Amount of users that may be selected (total number - already assigned count)
        /// </summary>
        public int MaxSelectableCount { get; set; }
    }
}


text:
pill: gradle_baseline
subtitle: 'gradle flywayBaseline'
---
# Gradle Task: flywayBaseline

Baselines an existing database, excluding all migrations up to and including baselineVersion.

## Usage

> gradle flywayBaseline

## Configuration

See [configuration](Configuration/parameters) for a full list of supported configuration parameters.

## Sample configuration

```groovy
flyway {
    driver = 'org.hsqldb.jdbcDriver'
    url = 'jdbc:hsqldb:file:/db/flyway_sample;shutdown=true'
    user = 'SA'
    password = 'mySecretPwd'
    connectRetries = 10
    initSql = 'SET ROLE \'myuser\''
    schemas = ['schema1', 'schema2', 'schema3']
    createSchemas=true
    table = 'schema_history'
    tablespace = 'my_tablespace'
    callbacks = ['com.mycompany.proj.CustomCallback', 'com.mycompany.proj.AnotherCallback']
    skipDefaultCallbacks = false
    baselineVersion = 5
    baselineDescription = "Let's go!"
    workingDirectory = 'C:/myproject'
    jdbcProperties = [
      'someProperty' : 'someValue',
      'someOtherProperty' : 'someOtherValue'
    ]
}
```

## Sample output

> gradle flywayBaseline -i

Creating schema history table: "PUBLIC"."flyway_schema_history"
Schema baselined with version: 1


text:
author: napbuf
comments: true
date: 2012-06-10 07:09:29+00:00
layout: post
slug: summits-of-mylife
title: Summits of my life
wordpress_id: 1527
categories:
- Blog
- Inspiració
- Media
- Vídeos
---

Avui,
per la inspiració;
per la que ens empeny a tirar endavant, a ser millors;
per la que ens motiva a buscar-nos, a lluitar-nos i a trobar-nos.

Per ella, perquè a ella li dec el meu present.
Gràcies Inspiració!!

<blockquote>

>
> _ _Pots continuar per acabar la carrera
i les cames et faran mal una setmana,
o pots renunciar
i la teva ment et farà mal tota la vida
>
>

>
> **Qui vol una vida millor - Marcel Zamora**
>
>
</blockquote>

[vimeo http://www.vimeo.com/42964218 w=600&h=338]

[Summits of My Life - Trailer](http://vimeo.com/42964218) from [sebastien montaz-rosset](http://vimeo.com/chamonix) on [Vimeo](http://vimeo.com).


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="">

    <title>Zach's Website</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">

    <link href="css/grayscale.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
                    Menu
                </button>

                    Zach Miller [Home]

                        About Me

                        Contact

                        Instrumentals

Welcome!

Read on to find out more about me, how to get in touch, or take a listen to a few instrumentals that I've produced.

About Me

In May of 2017, I graduated from Penn State Behrend with BA in Computer Engineering. I am currently working for GE while being enrolled in their software Edison Leadership program. Take a look at my complete resume below. Feel free to email me any questions!

                  <button class="download btn btn-default btn-sm" type="submit">Download Resume PDF</button>

                  <button class="toggle btn btn-default btn-sm">Toggle PDF Preview</button>

Contact Me

                    <button class="btn btn-default btn-lg" id="subCap">Show Contact Information</button>

                    <button class="btn btn-default btn-sm" id="copCap">Copy Email</button>

Instrumentals

For free downloads send me an email using the above section!

                <audio id="track1Audio">
                  <source src="res/Techi.mp3" type="audio/mpeg">
                </audio>
                <audio id="track2Audio">
                  <source src="res/Flawedv4.mp3" type="audio/mpeg">
                </audio>
                <audio id="track3Audio">
                  <source src="res/Star.mp3" type="audio/mpeg">
                </audio>
                <audio id="track4Audio">
                  <source src="res/Chill.mp3" type="audio/mpeg">
                </audio>
                <button class="btn btn-default btn-lg" id="track1" onClick="audioClick(this.id)">Play Track  1</button>
                <button class="btn btn-default btn-lg" id="track2" onClick="audioClick(this.id)">Play Track 2</button>

                <button class="btn btn-default btn-lg" id="track3" onClick="audioClick(this.id)">Play Track 3</button>
                <button class="btn btn-default btn-lg" id="track4" onClick="audioClick(this.id)">Play Track 4</button>

2017

            Grayscale Bootstrap Template


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "php.h"
#include "php_phalcon.h"
#include "phalcon.h"

#include "Zend/zend_operators.h"
#include "Zend/zend_exceptions.h"
#include "Zend/zend_interfaces.h"

#include "kernel/main.h"
#include "kernel/memory.h"

#include "kernel/exception.h"
#include "kernel/object.h"
#include "kernel/fcall.h"
#include "kernel/filter.h"
#include "kernel/framework/url.h"

/**
 * Phalcon\Escaper
 *
 * Escapes different kinds of text securing them. By using this component you may
 * prevent XSS attacks.
 *
 * This component only works with UTF-8. The PREG extension needs to be compiled with UTF-8 support.
 *
 *
 *	$escaper = new Phalcon\Escaper();
 *	$escaped = $escaper->escapeCss("font-family: <Verdana>");
 *	echo $escaped; // font\2D family\3A \20 \3C Verdana\3E
 *
 */

/**
 * Phalcon\Escaper initializer
 */
PHALCON_INIT_CLASS(Phalcon_Escaper){

	PHALCON_REGISTER_CLASS(Phalcon, Escaper, escaper, phalcon_escaper_method_entry, 0);

	zend_declare_property_string(phalcon_escaper_ce, SL("_encoding"), "utf-8", ZEND_ACC_PROTECTED TSRMLS_CC);
	zend_declare_property_null(phalcon_escaper_ce, SL("_htmlEscapeMap"), ZEND_ACC_PROTECTED TSRMLS_CC);
	zend_declare_property_long(phalcon_escaper_ce, SL("_htmlQuoteType"), 3, ZEND_ACC_PROTECTED TSRMLS_CC);

	zend_class_implements(phalcon_escaper_ce TSRMLS_CC, 1, phalcon_escaperinterface_ce);

	return SUCCESS;
}

/**
 * Sets the encoding to be used by the escaper
 *
 *
 * $escaper->setEncoding('utf-8');
 *
 *
 * @param string $encoding
 */
PHP_METHOD(Phalcon_Escaper, setEncoding){

	zval *encoding;

	phalcon_fetch_params(0, 1, 0, &encoding);

	if (unlikely(Z_TYPE_P(encoding) != IS_STRING)) {
		PHALCON_THROW_EXCEPTION_STRW(phalcon_escaper_exception_ce, "The character set must be string");
		return;
	}
	phalcon_update_property_this(this_ptr, SL("_encoding"), encoding TSRMLS_CC);

}

/**
 * Returns the internal encoding used by the escaper
 *
 * @return string
 */
PHP_METHOD(Phalcon_Escaper, getEncoding){

	RETURN_MEMBER(this_ptr, "_encoding");
}

/**
 * Sets the HTML quoting type for htmlspecialchars
 *
 *
 * $escaper->setHtmlQuoteType(ENT_XHTML);
 *
 *
 * @param int $quoteType
 */
PHP_METHOD(Phalcon_Escaper, setHtmlQuoteType){

	zval *quote_type;

	phalcon_fetch_params(0, 1, 0, &quote_type);

	if (Z_TYPE_P(quote_type) != IS_LONG) {
		PHALCON_THROW_EXCEPTION_STRW(phalcon_escaper_exception_ce, "The quoting type is not valid");
		return;
	}
	phalcon_update_property_this(this_ptr, SL("_htmlQuoteType"), quote_type TSRMLS_CC);

}

/**
 * Detect the character encoding of a string to be handled by an encoder
 * Special-handling for chr(172) and chr(128) to chr(159) which fail to be detected by mb_detect_encoding()
 *
 * @param string $str
 * @param string $charset
 * @return string
 */
PHP_METHOD(Phalcon_Escaper, detectEncoding){

	zval *str, *charset = NULL, *strict_check, *detected = NULL;

	PHALCON_MM_GROW();

	phalcon_fetch_params(1, 1, 0, &str);

	/**
	 * Check if charset is ASCII or ISO-8859-1
	 */
	PHALCON_INIT_VAR(charset);
	phalcon_is_basic_charset(charset, str);
	if (Z_TYPE_P(charset) == IS_STRING) {
		RETURN_CTOR(charset);
	}

	/**
	 * We require mbstring extension here
	 */
	if (phalcon_function_exists_ex(SS("mb_detect_encoding") TSRMLS_CC) == FAILURE) {
		RETURN_MM_NULL();
	}

	/**
	 * Strict encoding detection with fallback to non-strict detection.
	 */
	PHALCON_INIT_VAR(strict_check);
	ZVAL_BOOL(strict_check, 1);

	PHALCON_INIT_NVAR(charset);
	ZVAL_STRING(charset, "UTF-32", 1);

	/**
	 * Check for UTF-32 encoding
	 */
	PHALCON_INIT_VAR(detected);
	phalcon_call_func_p3(detected, "mb_detect_encoding", str, charset, strict_check);
	if (zend_is_true(detected)) {
		RETURN_CTOR(charset);
	}

	PHALCON_INIT_NVAR(charset);
	ZVAL_STRING(charset, "UTF-16", 1);

	/**
	 * Check for UTF-16 encoding
	 */
	PHALCON_INIT_NVAR(detected);
	phalcon_call_func_p3(detected, "mb_detect_encoding", str, charset, strict_check);
	if (zend_is_true(detected)) {
		RETURN_CTOR(charset);
	}

	PHALCON_INIT_NVAR(charset);
	ZVAL_STRING(charset, "UTF-8", 1);

	/**
	 * Check for UTF-8 encoding
	 */
	PHALCON_INIT_NVAR(detected);
	phalcon_call_func_p3(detected, "mb_detect_encoding", str, charset, strict_check);
	if (zend_is_true(detected)) {
		RETURN_CTOR(charset);
	}

	PHALCON_INIT_NVAR(charset);
	ZVAL_STRING(charset, "ISO-8859-1", 1);

	/**
	 * Check for ISO-8859-1 encoding
	 */
	PHALCON_INIT_NVAR(detected);
	phalcon_call_func_p3(detected, "mb_detect_encoding", str, charset, strict_check);
	if (zend_is_true(detected)) {
		RETURN_CTOR(charset);
	}

	PHALCON_INIT_NVAR(charset);
	ZVAL_STRING(charset, "ASCII", 1);

	/**
	 * Check for ASCII encoding
	 */
	PHALCON_INIT_NVAR(detected);
	phalcon_call_func_p3(detected, "mb_detect_encoding", str, charset, strict_check);
	if (zend_is_true(detected)) {
		RETURN_CTOR(charset);
	}

	/**
	 * Fallback to global detection
	 */
	phalcon_call_func_p1(return_value, "mb_detect_encoding", str);
	RETURN_MM();
}

/**
 * Utility to normalize a string's encoding to UTF-32.
 *
 * @param string $str
 * @return string
 */
PHP_METHOD(Phalcon_Escaper, normalizeEncoding){

	zval *str, *encoding, *charset;

	PHALCON_MM_GROW();

	phalcon_fetch_params(1, 1, 0, &str);

	/**
	 * mbstring is required here
	 */
	if (phalcon_function_exists_ex(SS("mb_convert_encoding") TSRMLS_CC) == FAILURE) {
		PHALCON_THROW_EXCEPTION_STR(phalcon_escaper_exception_ce, "Extension 'mbstring' is required");
		return;
	}

	PHALCON_INIT_VAR(encoding);
	phalcon_call_method_p1(encoding, this_ptr, "detectencoding", str);

	PHALCON_INIT_VAR(charset);
	ZVAL_STRING(charset, "UTF-32", 1);

	/**
	 * Convert to UTF-32 (4 byte characters, regardless of actual number of bytes in
	 * the character).
	 */
	phalcon_call_func_p3(return_value, "mb_convert_encoding", str, charset, encoding);
	RETURN_MM();
}

/**
 * Escapes a HTML string. Internally uses htmlspeciarchars
 *
 * @param string $text
 * @return string
 */
PHP_METHOD(Phalcon_Escaper, escapeHtml){

	zval *text, *html_quote_type, *encoding;

	PHALCON_MM_GROW();

	phalcon_fetch_params(1, 1, 0, &text);

	if (Z_TYPE_P(text) == IS_STRING) {
		PHALCON_OBS_VAR(html_quote_type);
		phalcon_read_property_this(&html_quote_type, this_ptr, SL("_htmlQuoteType"), PH_NOISY_CC);

		PHALCON_OBS_VAR(encoding);
		phalcon_read_property_this(&encoding, this_ptr, SL("_encoding"), PH_NOISY_CC);
		phalcon_call_func_p3(return_value, "htmlspecialchars", text, html_quote_type, encoding);
		RETURN_MM();
	}

	RETURN_CCTOR(text);
}

/**
 * Escapes a HTML attribute string
 *
 * @param string $attribute
 * @return string
 */
PHP_METHOD(Phalcon_Escaper, escapeHtmlAttr){

	zval *attribute, *normalized;

	PHALCON_MM_GROW();

	phalcon_fetch_params(1, 1, 0, &attribute);

	if (Z_TYPE_P(attribute) == IS_STRING) {
		if (zend_is_true(attribute)) {

			/**
			 * Normalize encoding to UTF-32
			 */
			PHALCON_INIT_VAR(normalized);
			phalcon_call_method_p1(normalized, this_ptr, "normalizeencoding", attribute);

			/**
			 * Escape the string
			 */
			phalcon_escape_htmlattr(return_value, normalized);
			RETURN_MM();
		}
	}

	RETURN_CCTOR(attribute);
}

/**
 * Escape CSS strings by replacing non-alphanumeric chars by their hexadecimal escaped representation
 *
 * @param string $css
 * @return string
 */
PHP_METHOD(Phalcon_Escaper, escapeCss){

	zval *css, *normalized;

	PHALCON_MM_GROW();

	phalcon_fetch_params(1, 1, 0, &css);

	if (Z_TYPE_P(css) == IS_STRING) {
		if (zend_is_true(css)) {

			/**
			 * Normalize encoding to UTF-32
			 */
			PHALCON_INIT_VAR(normalized);
			phalcon_call_method_p1(normalized, this_ptr, "normalizeencoding", css);

			/**
			 * Escape the string
			 */
			phalcon_escape_css(return_value, normalized);
			RETURN_MM();
		}
	}

	RETURN_CCTOR(css);
}

/**
 * Escape javascript strings by replacing non-alphanumeric chars by their hexadecimal escaped representation
 *
 * @param string $js
 * @return string
 */
PHP_METHOD(Phalcon_Escaper, escapeJs){

	zval *js, *normalized;

	PHALCON_MM_GROW();

	phalcon_fetch_params(1, 1, 0, &js);

	if (Z_TYPE_P(js) == IS_STRING) {
		if (zend_is_true(js)) {

			/**
			 * Normalize encoding to UTF-32
			 */
			PHALCON_INIT_VAR(normalized);
			phalcon_call_method_p1(normalized, this_ptr, "normalizeencoding", js);

			/**
			 * Escape the string
			 */
			phalcon_escape_js(return_value, normalized);
			RETURN_MM();
		}
	}

	RETURN_CCTOR(js);
}

/**
 * Escapes a URL. Internally uses rawurlencode
 *
 * @param string $url
 * @return string
 */
PHP_METHOD(Phalcon_Escaper, escapeUrl){

	zval *url;

	phalcon_fetch_params(0, 1, 0, &url);

	phalcon_raw_url_encode(return_value, url);
	return;
}


text:
APP_PATH = "/var/www" # install location
worker_processes 4    # amount of unicorn workers to spin up
timeout 30            # restarts workers that hang for 30 seconds

# Speed things up
preload_app true
GC.respond_to?(:copy_on_write_friendly=) and
  GC.copy_on_write_friendly = true

# Run unpriviliged
user "www-data", "www-data"

# Set our working directory
working_directory APP_PATH

# Set what we're listening on
listen APP_PATH + "/.unicorn.sock", :backlog => 64
#listen 8080, :tcp_nopush => true

# PIDs are nice
pid APP_PATH + "/unicorn.pid"

# stderr/stdout logs
stderr_path APP_PATH + "/logs/unicorn.stderr.log"
stdout_path APP_PATH + "/logs/unicorn.stdout.log"


text:
package stsc.general.simulator.multistarter.genetic;

import stsc.common.algorithms.EodExecutionInstance;
import stsc.common.algorithms.MutableAlgorithmConfiguration;
import stsc.common.algorithms.StockExecutionInstance;
import stsc.general.simulator.Execution;

public final class GeneticExecutionInitializer {

	private final String executionName;
	public String algorithmName;
	public AlgorithmConfigurationSetGeneticGenerator geneticAlgorithmSettings;

	public GeneticExecutionInitializer(String eName, String algorithmName, AlgorithmConfigurationSetGeneticGenerator algorithmSettings) {
		super();
		this.executionName = eName;
		this.algorithmName = algorithmName;
		this.geneticAlgorithmSettings = algorithmSettings;
	}

	public String getExecutionName() {
		return executionName;
	}

	public String getAlgorithmName() {
		return algorithmName;
	}

	@Override
	public String toString() {
		return executionName + "(" + algorithmName + ")\n" + geneticAlgorithmSettings + "\n";
	}

	public MutableAlgorithmConfiguration generateRandom() {
		return geneticAlgorithmSettings.generateRandom();
	}

	public void mutateStock(int mutateSettingIndex, Execution copy) {
		final StockExecutionInstance execution = copy.getInit().getExecutionsStorage().getStockExecutions().get(mutateSettingIndex);
		final MutableAlgorithmConfiguration algorithmSettings = execution.getSettings();
		mutateAlgorithmSettings(algorithmSettings);
	}

	public void mutateEod(int eodIndex, Execution copy) {
		final EodExecutionInstance execution = copy.getInit().getExecutionsStorage().getEodExecutions().get(eodIndex);
		final MutableAlgorithmConfiguration algorithmSettings = execution.getSettings();
		mutateAlgorithmSettings(algorithmSettings);
	}

	private void mutateAlgorithmSettings(final MutableAlgorithmConfiguration algorithmSettings) {
		geneticAlgorithmSettings.mutate(algorithmSettings);
	}

	public MutableAlgorithmConfiguration mergeStock(StockExecutionInstance leftSe, StockExecutionInstance rightSe) {
		return geneticAlgorithmSettings.merge(leftSe.getSettings(), rightSe.getSettings());
	}

	public MutableAlgorithmConfiguration mergeEod(EodExecutionInstance leftSe, EodExecutionInstance rightSe) {
		return geneticAlgorithmSettings.merge(leftSe.getSettings(), rightSe.getSettings());
	}

	public long size() {
		return geneticAlgorithmSettings.size();
	}

}


text:
copyright:
  years: 2015, 2016
lastupdated: "2016-11-01"
---

{:shortdesc: .shortdesc}
{:new_window: target="_blank"}
{:codeblock: .codeblock}

# Introdução ao IBM WebSphere Application Server for {{site.data.keyword.Bluemix_notm}}
{: #getting_started}

{{site.data.keyword.IBM}} WebSphere Application Server for {{site.data.keyword.Bluemix}} é um serviço que facilita a rápida configuração em uma instância pré-configurada do WebSphere Application Server Liberty, do Traditional Network Deployment ou do Traditional WebSphere Java EE em um ambiente de nuvem hospedado no {{site.data.keyword.Bluemix_notm}}.
{: shortdesc}

## Visão geral do WebSphere Application Server for {{site.data.keyword.Bluemix_notm}}
{: #overview}

O WebSphere Application Server for {{site.data.keyword.Bluemix_notm}} fornece aos consumidores os servidores pré-configurados Traditional WebSphere e perfil Liberty. Ele é hospedado em convidados da máquina
virtual com acesso raiz para o sistema operacional guest. Quando você estiver criando seu serviço, escolha entre *Liberty*, *Traditional ND* ou *Traditional WebSphere*.

**Nota:** os consumidores são agora capazes de escolher entre a V8.5 e a V9.0 quando você cria uma nova instância do *Traditional ND* ou do *Traditional WebSphere*.

Você recebe uma experiência de administração do WebSphere familiar e tem acesso completo
ao sistema operacional subjacente. É possível reutilizar seus scripts existentes e fazer pequenos ajustes de sistema
necessários para trabalhar com suas estruturas próprias ou de terceiros. O Centro do administrador e os Consoles do administrador são fornecidos para administrar o serviço WebSphere Application Server Liberty, ND ou Traditional, assim como suas configurações do WebSphere no local.

O Plano do WebSphere Application Server for {{site.data.keyword.Bluemix_notm}} Network Deployment consiste em um ambiente de célula do WebSphere Application Server Network Deployment com duas ou mais máquinas virtuais. A primeira máquina virtual contém o Deployment Manager e o IBM HTTP Server e as máquinas virtuais restantes contêm nós customizados (agentes de nó) federados para o Deployment Manager. Use seus scripts wsadmin existentes para criar sua configuração do WebSphere ou use
o Console administrativo do WebSphere para configurar manualmente o ambiente. Esses novos recursos permitem que os usuários configurem um ambiente em cluster, o que é um aspecto crítico de qualquer aplicativo corporativo de middleware. Os
clientes agora podem optar por agrupar uma topologia para balancear a carga de solicitações entre duas ou mais Instâncias.

O Plano do WebSphere Application Server for {{site.data.keyword.Bluemix_notm}} Liberty Core inclui o uso de um Liberty Collective. O Liberty Collective é um domínio administrativo para um grupo de perfis Liberty (servidores) e consiste em duas ou mais máquinas virtuais. A
primeira máquina virtual contém o servidor Collective Controller liberty, que é um ponto de controle
para o Liberty Collective. Além do liberty collective, essa máquina virtual também
contém o IBM HTTP Server, que permite acesso aos aplicativos a partir de um navegador da web. As
máquinas virtuais restantes são os hosts coletivos nos quais os membros coletivos residem (servidores
do perfil liberty). O recurso Liberty Admin Center também é ativado no servidor liberty controller.

A figura a seguir mostra a arquitetura dos ambientes do WebSphere Application Server for {{site.data.keyword.Bluemix_notm}} Network Deployment Cell e Liberty Collective.

Figura 1. Célula de implementação de rede e arquitetura Liberty Collective

![Figura1. Arquitetura da célula de implementação de rede e Liberty Collective](images/CellCollectiveDiagram.gif)

**Nota**: na *Figura 1* acima, o padrão que descreve a disposição do Gerenciador de Implementação ou do Controlador Coletivo com o IBM HTTP Server se
destina para propósitos de desenvolvimento e de testes. O WebSphere Application Server for {{site.data.keyword.Bluemix_notm}} também lhe dá a liberdade de reconfigurar o software pré-instalado para atender às suas necessidades operacionais e do aplicativo de produção; tal como você faria no local. Além disso, para os requisitos de produção mais estritos, entre em contato com seu representante de vendas IBM que pode falar sobre nossa oferta do IBM WebSphere Application Server for {{site.data.keyword.Bluemix_notm}} de locatário único, que oferece recursos de cálculo e de rede isolados.

## Ambiente Operacional
{: #operational_environment}

O IBM WebSphere Application Server for {{site.data.keyword.Bluemix_notm}} é um serviço que retorna guests
(máquinas virtuais) em um ambiente compartilhado para que os consumidores implementem aplicativos. Um VPN protege o serviço público de varreduras de portas genéricas e outros
ataques baseados em rede não solicitados. No entanto, é importante observar que a VPN de serviço que você usa para acessar
a sua instância de serviço pode ser compartilhada entre múltiplas organizações e usuários do
{{site.data.keyword.Bluemix_notm}}. As máquinas virtuais fornecem recursos de cálculo, de memória e de Entrada/Saída, os quais são provenientes de um conjunto compartilhado de recursos IaaS.

Como os recursos específicos de cálculo, de memória e de E/S são executados
por máquinas virtuais em um ambiente compartilhado, as configurações de serviço podem variar. As configurações para cada instância de serviço específica
podem ser visualizadas por meio dos portais e painéis de serviço do
IBM WebSphere Application Server for {{site.data.keyword.Bluemix_notm}}.

O IBM WebSphere Application Server for {{site.data.keyword.Bluemix_notm}} fornece instâncias da máquina virtual. Com essas instâncias, os clientes usam um portal simples para criar e gerenciar implementações corporativas do WebSphere Application Server de uma forma consistente e repetida com flexibilidade significativa para ajustar seus aplicativos. Os usuários podem começar a trabalhar em máquinas virtuais pré-configuradas do WebSphere Application Server Liberty, ND ou Traditional em um ambiente de nuvem hospedado. Os usuários podem migrar aplicativos existentes do WebSphere Application Server para o {{site.data.keyword.Bluemix_notm}} e assumir o controle total do sistema operacional e do middleware subjacentes.

## Estratégia de precificação
{: #pricing_strategy}

O IBM WebSphere Application Server for
{{site.data.keyword.Bluemix_notm}} fornece instâncias
dimensionadas para Camiseta para clientes com aplicativos de uso
intensivo de memória para dimensionar corretamente seu ambiente com máquinas virtuais maiores. Os clientes podem selecionar o tamanho do recurso específico de um componente provisionado do WebSphere Application Server ou de um único sistema com máquinas virtuais de até 32 GB de RAM.

As tabelas a seguir representam os preços dos planos do IBM
WebSphere Application Server for {{site.data.keyword.Bluemix_notm}} a partir de 1 de abril de 2016 e são representados em dólares americanos (USD).

*Tabela 1. Plano do Liberty Core*

| **Camiseta** | **vCPU** | **RAM (GB)** | **HD (GB)** | **Preço/H** |
|:-------------:|:----------:|:--------------:|:-------------:|:--------------:|
| P | 1 | 2 | 12 | US$ 0,21 |
| M | 2 | 4 | 25 | US$ 0,42 |
| G | 4 | 8 | 50 | US$ 0,84 |
| EG | 8 | 16 | 100 | US$ 1,68 |
| EEG | 16 | 32 | 200 | US$ 3,36 |

*Tabela 2. Plano base do WebSphere Application Server*

| **Camiseta** | **vCPU** | **RAM (GB)** | **HD (GB)** | **Preço/H** |
|:-------------:|:----------:|:--------------:|:-------------:|:--------------:|
| P | 1 | 2 | 12 | US$ 0,30 |
| M | 2 | 4 | 25 | US$ 0,60 |
| G | 4 | 8 | 50 | US$ 1,20 |
| EG | 8 | 16 | 100 | US$ 2,40 |
| EEG | 16 | 32 | 200 | US$ 4,80 |

*Tabela 3. Plano do WebSphere Application Server ND*

| **Camiseta** | **vCPU** | **RAM (GB)** | **HD (GB)** | **Preço/H** |
|:-------------:|:----------:|:--------------:|:-------------:|:--------------:|
| P | 1 | 2 | 12 | US$ 0,70 |
| M | 2 | 4 | 25 | US$ 1,40 |
| G | 4 | 8 | 50 | US$ 2,80 |
| EG | 8 | 16 | 100 | US$ 5,60 |
| EEG | 16 | 32 | 200 | US$ 11,20 |

O IBM WebSphere Application Server for {{site.data.keyword.Bluemix_notm}} é oferecido de acordo com a métrica de encargo a seguir:

*  *Hora por instância*: uma Instância é definida como acesso a uma configuração específica do serviço do IBM WebSphere Application Server for {{site.data.keyword.Bluemix_notm}}. Os clientes são cobrados por cada hora integral ou parcial de cada Instância do Serviço que é implementado durante o período de faturamento. Cada Hora da instância é faturada mensalmente e se uma instância for usada somente uma parte do mês, a taxa de uso será rateada.

Por exemplo, se você usar o Plano ND, uma Instância será equiparada a 1vCPU com 2 GB de RAM e 12 GB de HD. Portanto, se você escolher configurar sua Célula com um nó de Controle e oito nós Customizados, será cobrado por nove nós (instâncias).

**Nota**: o faturamento mínimo é configurado como 0,25 a hora da instância por nó Customizado ou host Liberty. No exemplo acima, um nó de Controle e um nó Customizado que esteja configurado para pelo menos 15 minutos seria equiparado a um encargo mínimo de (0,25 * n.º de instâncias).

**Nota**: em razão de uma quantia específica de recursos de cálculo, de memória e de E/S, os clientes são cobrados por instâncias acumuladas no estado INTERROMPIDO a uma taxa reduzida de 5%. Os clientes são gerenciados para um número fixo de instâncias INTERROMPIDAS com não mais de 10 endereços IP ou 64 GB de memória.

# rellinks
{: #rellinks}
## gerais
{: #general}
* [WASdev](https://developer.ibm.com/wasdev/){: new_window}
* [Documentação do WebSphere Application Server V9](http://www.ibm.com/support/knowledgecenter/SSEQTP_9.0.0/as_ditamaps/was900_welcome_base.html){: new_window}


text:
function [C, sigma] = dataset3Params(X, y, Xval, yval)
%EX6PARAMS returns your choice of C and sigma for Part 3 of the exercise
%where you select the optimal (C, sigma) learning parameters to use for SVM
%with RBF kernel
%   [C, sigma] = EX6PARAMS(X, y, Xval, yval) returns your choice of C and
%   sigma. You should complete this function to return the optimal C and
%   sigma based on a cross-validation set.
%

% You need to return the following variables correctly.
C = 1;
sigma = 0.3;

% ====================== YOUR CODE HERE ======================
% Instructions: Fill in this function to return the optimal C and sigma
%               learning parameters found using the cross validation set.
%               You can use svmPredict to predict the labels on the cross
%               validation set. For example,
%                   predictions = svmPredict(model, Xval);
%               will return the predictions on the cross validation set.
%
%  Note: You can compute the prediction error using
%        mean(double(predictions ~= yval))
%

% =========================================================================
C_values = [0.01 0.03 0.1 0.3 1 3 10 30];
sigma_values = [0.01 0.03 0.1 0.3 1 3 10 30];

for i=1:length(C_values)
	    for j=1:length(sigma_values)
		            C = C_values(i);
			            sigma = sigma_values(j);
				            model = svmTrain(X, y, C, @(x1, x2) gaussianKernel(x1, x2, sigma));
					            predictions = svmPredict(model, Xval);
						            predictions_error(i,j) = mean(double(predictions ~= yval));
							        end
							end

							mm = min(min(predictions_error));
							[i j] = find(predictions_error == mm);
							C = C_values(i)
							sigma = sigma_values(j)
% Answer is C = 1 and sigma = 0.1
% ============================================================================
end


text:
require File.expand_path('../../../../spec_helper', __FILE__)
require 'set'

describe "SortedSet#each" do
  before(:each) do
    @set = SortedSet[1, 2, 3]
  end

  it "yields each Object in self in sorted order" do
    ret = []
    SortedSet["one", "two", "three"].each { |x| ret << x }
    ret.should == ["one", "two", "three"].sort
  end

  ruby_bug "http://redmine.ruby-lang.org/issues/show/116", "1.8.7.7" do
    it "returns self" do
      @set.each { |x| x }.should equal(@set)
    end
  end

  ruby_version_is "1.8.7" do
    it "returns an Enumerator when not passed a block" do
      enum = @set.each

      ret = []
      enum.each { |x| ret << x }
      ret.sort.should == [1, 2, 3]
    end
  end

  ruby_version_is "" ... "1.8.7" do
    it "raises a LocalJumpError when not passed a block" do
      lambda { @set.each }.should raise_error(LocalJumpError)
    end
  end
end


text:
import unittest

import numpy

import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition

@testing.parameterize(
    {'dtype': numpy.float16},
    {'dtype': numpy.float32},
    {'dtype': numpy.float64},
)
class TestLogSumExp(unittest.TestCase):

    def setUp(self):
        self.x = numpy.random.uniform(-1, 1, (3, 2, 4)).astype(self.dtype)
        self.gy = numpy.random.uniform(-1, 1, ()).astype(self.dtype)
        self.check_forward_option = {}
        self.check_backward_option = {
            'eps': 2.0 ** -5, 'rtol': 1.0e-4, 'atol': 1.0e-4}
        if self.dtype == numpy.float16:
            self.check_forward_option = {'rtol': 1.0e-2, 'atol': 1.0e-2}
            self.check_backward_option = {
                'eps': 2.0 ** -3, 'rtol': 1.0e-2, 'atol': 1.0e-2}

    def check_forward(self, x_data, axis=None):
        x = chainer.Variable(x_data)
        y = functions.logsumexp(x, axis=axis)
        self.assertEqual(y.data.dtype, self.dtype)
        y_expect = numpy.log(numpy.exp(self.x).sum(axis=axis))
        testing.assert_allclose(
            y_expect, y.data, **self.check_forward_option)

    @condition.retry(3)
    def test_forward_cpu(self):
        self.check_forward(self.x)

    @condition.retry(3)
    def test_forward_axis_cpu(self):
        for i in range(self.x.ndim):
            self.check_forward(self.x, axis=i)

    @condition.retry(3)
    def test_forward_negative_axis_cpu(self):
        self.check_forward(self.x, axis=-1)

    @condition.retry(3)
    def test_forward_multi_axis_cpu(self):
        self.check_forward(self.x, axis=(0, 1))

    @condition.retry(3)
    def test_forward_multi_axis_invert_cpu(self):
        self.check_forward(self.x, axis=(1, 0))

    @condition.retry(3)
    def test_forward_negative_multi_axis_cpu(self):
        self.check_forward(self.x, axis=(0, -1))

    @condition.retry(3)
    def test_forward_negative_multi_axis_invert_cpu(self):
        self.check_forward(self.x, axis=(-2, 0))

    @attr.gpu
    @condition.retry(3)
    def test_forward_gpu(self):
        self.check_forward(cuda.to_gpu(self.x))

    @attr.gpu
    @condition.retry(3)
    def test_forward_axis_gpu(self):
        for i in range(self.x.ndim):
            self.check_forward(cuda.to_gpu(self.x), axis=i)

    @attr.gpu
    @condition.retry(3)
    def test_forward_negative_axis_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), axis=-1)

    @attr.gpu
    @condition.retry(3)
    def test_forward_multi_axis_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), axis=(0, 1))

    @attr.gpu
    @condition.retry(3)
    def test_forward_multi_axis_invert_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), axis=(1, 0))

    @attr.gpu
    @condition.retry(3)
    def test_forward_negative_multi_axis_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), axis=(0, -1))

    @attr.gpu
    @condition.retry(3)
    def test_forward_negative_multi_axis_invert_gpu(self):
        self.check_forward(cuda.to_gpu(self.x), axis=(-2, 0))

    def check_backward(self, x_data, y_grad, axis=None):
        gradient_check.check_backward(
            functions.LogSumExp(axis), x_data, y_grad,
            **self.check_backward_option)

    @condition.retry(3)
    def test_backward_cpu(self):
        self.check_backward(self.x, self.gy)

    @condition.retry(3)
    def test_backward_axis_cpu(self):
        for i in range(self.x.ndim):
            gy = numpy.ones_like(self.x.sum(axis=i)) * self.gy
            self.check_backward(self.x, gy, axis=i)

    @condition.retry(3)
    def test_backward_negative_axis_cpu(self):
        gy = numpy.ones_like(self.x.sum(axis=-1)) * self.gy
        self.check_backward(self.x, gy, axis=-1)

    @condition.retry(3)
    def test_backward_multi_axis_cpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(0, 1))) * self.gy
        self.check_backward(self.x, gy, axis=(0, 1))

    @condition.retry(3)
    def test_backward_multi_axis_invert_cpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(1, 0))) * self.gy
        self.check_backward(self.x, gy, axis=(1, 0))

    @condition.retry(3)
    def test_backward_negative_multi_axis_cpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(0, -1))) * self.gy
        self.check_backward(self.x, gy, axis=(0, -1))

    @condition.retry(3)
    def test_backward_negative_multi_axis_invert_cpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(-2, 0))) * self.gy
        self.check_backward(self.x, gy, axis=(-2, 0))

    @attr.gpu
    @condition.retry(3)
    def test_backward_gpu(self):
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(self.gy))

    @attr.gpu
    @condition.retry(3)
    def test_backward_axis_gpu(self):
        for i in range(self.x.ndim):
            gy = numpy.ones_like(self.x.sum(axis=i)) * self.gy
            self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=i)

    @attr.gpu
    @condition.retry(3)
    def test_backward_negative_axis_gpu(self):
        for i in range(self.x.ndim):
            gy = numpy.ones_like(self.x.sum(axis=-1)) * self.gy
            self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=-1)

    @attr.gpu
    @condition.retry(3)
    def test_backward_multi_axis_gpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(0, 1))) * self.gy
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=(0, 1))

    @attr.gpu
    @condition.retry(3)
    def test_backward_multi_axis_invert_gpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(1, 0))) * self.gy
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=(1, 0))

    @attr.gpu
    @condition.retry(3)
    def test_backward_negative_multi_axis_gpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(0, -1))) * self.gy
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=(0, -1))

    @attr.gpu
    @condition.retry(3)
    def test_backward_negative_multi_axis_invert_gpu(self):
        gy = numpy.ones_like(self.x.sum(axis=(-2, 0))) * self.gy
        self.check_backward(cuda.to_gpu(self.x), cuda.to_gpu(gy), axis=(-2, 0))

    def test_invalid_axis_type(self):
        with self.assertRaises(TypeError):
            functions.Sum([0])

    def test_invalid_axis_type_in_tuple(self):
        with self.assertRaises(TypeError):
            functions.Sum((1, 'x'))

    def test_duplicate_axis(self):
        with self.assertRaises(ValueError):
            functions.Sum((0, 0))

    def test_pos_neg_duplicate_axis(self):
        with self.assertRaises(ValueError):
            self.x.sum(axis=(1, -2))

testing.run_module(__name__, __file__)


text:
class AddRevisionComment < ActiveRecord::Migration
  def self.up
    add_column 'revisions', 'comment', :string
  end

  def self.down
    remove_column 'revisions', 'comment'
  end
end


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/pubsub/v1/pubsub.proto

package com.google.pubsub.v1;

public interface ListTopicsResponseOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.pubsub.v1.ListTopicsResponse)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * The resulting topics.
   *

   *
   * repeated .google.pubsub.v1.Topic topics = 1;
   */
  java.util.List<com.google.pubsub.v1.Topic> getTopicsList();
  /**
   *
   *
   *

   * The resulting topics.
   *

   *
   * repeated .google.pubsub.v1.Topic topics = 1;
   */
  com.google.pubsub.v1.Topic getTopics(int index);
  /**
   *
   *
   *

   * The resulting topics.
   *

   *
   * repeated .google.pubsub.v1.Topic topics = 1;
   */
  int getTopicsCount();
  /**
   *
   *
   *

   * The resulting topics.
   *

   *
   * repeated .google.pubsub.v1.Topic topics = 1;
   */
  java.util.List<? extends com.google.pubsub.v1.TopicOrBuilder> getTopicsOrBuilderList();
  /**
   *
   *
   *

   * The resulting topics.
   *

   *
   * repeated .google.pubsub.v1.Topic topics = 1;
   */
  com.google.pubsub.v1.TopicOrBuilder getTopicsOrBuilder(int index);

  /**
   *
   *
   *

   * If not empty, indicates that there may be more topics that match the
   * request; this value should be passed in a new `ListTopicsRequest`.
   *

   *
   * string next_page_token = 2;
   */
  java.lang.String getNextPageToken();
  /**
   *
   *
   *

   * If not empty, indicates that there may be more topics that match the
   * request; this value should be passed in a new `ListTopicsRequest`.
   *

   *
   * string next_page_token = 2;
   */
  com.google.protobuf.ByteString getNextPageTokenBytes();
}


text:
'use strict'

const getEnvVar = require('./getEnvVar')

const DEFAULT_VERSIONS = {
  'remap': '1.2',
  'phone': '1.0',
  'posap': '1.0',
  'moysklad/loyalty': '1.0'
}

const ENV_KEY = {
  'remap': 'REMAP',
  'phone': 'PHONE',
  'posap': 'POSAP',
  'moysklad/loyalty': 'LOYALTY'
}

function getApiDefaultVersion(api) {
  const apiVersion = DEFAULT_VERSIONS[api]
  const envKey = ENV_KEY[api] || api.replace(/\W/g, '_').toUpperCase()
  const envName = `MOYSKLAD_${envKey}_API_VERSION`

  return getEnvVar(envName) || apiVersion
}

module.exports = getApiDefaultVersion


text:
package apple.webkit;

import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;
import apple.uikit.*;

/**
 * @since Available in iOS 8.0 and later.
 */
@Library("WebKit/WebKit.h")
@Mapping("WKNavigationActionPolicy")
public final class WKNavigationActionPolicy extends ObjCEnum {

    @GlobalConstant("WKNavigationActionPolicyCancel")
    public static final long Cancel = 0L;
    @GlobalConstant("WKNavigationActionPolicyAllow")
    public static final long Allow = 1L;

}


text:
<?php

class CollectionPost extends Eloquent {

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'collection_posts';

	protected $fillable = array(
				'post_id',
				'collection_id',
				'order',
				);

}


text:
MAT: 1A
HOST: http://example:8000/__api__

# API Documentation
This is a reference document explaining the API. Please note that paths are relative to the base API url (ie `http://example:8000/__api__/`)

# Group Settings
## Server Settings [/server_settings]

Get server settings

## Get Server Settings [GET]
+ Response 200 (application/json)

    + Attributes
        + version: software version (string, required)
        + build: software build (string, required)

# Group Users
Get, update, and delete users

## Users [/users]

### List all users [GET]
Get a list of all users. Optionally, you can specify a `prefix` to search for a specific user.

+ prefix (string - The prefix of a user (username, first name, or last name)

+ Response 200 (application/json)

    + Attributes (array[User])

### User Detail [/users/{user_id}]

Get detailed information on a specific user

+ Parameters
    + user_id: p401 (string, required) - The ID of a specific user in the form of a string

### Get a specific user [GET]

+ Response 200 (application/json)

    + Attributes (UserDetail)

## Data Structures

### User
+ id: 1 (number, required) - unique numerical identified
+ principal_id: 1 (number, required) - unique numerical identified across users and groups
+ provider_key: p401 (string) - unique identifier in string format
+ email: chad@test.com (string) - email address
+ email_hash: a51b767bfd8fccf9b5831a99e1f97c81 (string) - hashed email address
+ username: admin (string, required) - username of the user
+ first_name: Chad (string) - the first name of the user
+ last_name: Smith (string) - the last name of the user
+ password: password (string) the password, usually blank
+ user_role: administrator (string, required) - the role of the user
+ confirmed: true (boolean, required) - has the user been confirmed
+ locked: false (boolean, required) - is the user locked

### UserDetail (User)
+ privileges: ["add_users"] (array[string], required) - List of privileges the user has


text:
<?php

namespace kalibao\backend\modules\supplier\models\supplier\crud;

use Yii;
use yii\data\ActiveDataProvider;
use kalibao\common\components\crud\ModelFilterInterface;
use kalibao\common\models\supplier\Supplier;

/**
 * This is the model filter class for controller "Supplier".
 *
 * @property integer $id
 * @property string $name
 *
 * @package kalibao\backend\modules\supplier\models\supplier\crud
 * @version 1.0
 */
class ModelFilter extends Supplier implements ModelFilterInterface
{

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        return [
            self::SCENARIO_DEFAULT => [
                'id', 'name'
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['name'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
        ];
    }

    /**
     * @inheritdoc
     */
    public function search($requestParams, $language = null, $pageSize = 10)
    {
        $query = self::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'attributes' => [
                    'id',
                    'name',
                ],
                'defaultOrder' => [
                    'id' => SORT_DESC
                ]
            ],
            'pagination' => [
                'defaultPageSize' => $pageSize,
                'pageSize' => $pageSize,
            ]
        ]);

        $this->load($requestParams);

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

        $query
            ->andFilterWhere(['supplier.id' => $this->id])
            ->andFilterWhere(['like', 'supplier.name', $this->name]);

        return $dataProvider;
    }
}


text:
namespace content {
class BrowserContext;
}

namespace extensions {
class ExtensionRegistry;
}

// The WebUI class for the uber page (chrome://chrome). It manages the UI for
// the uber page (navigation bar and so forth) as well as WebUI objects for
// pages that appear in the uber page.
class UberUI : public content::WebUIController {
 public:
  explicit UberUI(content::WebUI* web_ui);
  ~UberUI() override;

  content::WebUI* GetSubpage(const std::string& page_url);

  // WebUIController implementation.
  bool OverrideHandleWebUIMessage(const GURL& source_url,
                                  const std::string& message,
                                  const base::ListValue& args) override;

  // We forward these to |sub_uis_|.
  void RenderViewCreated(content::RenderViewHost* render_view_host) override;
  void RenderViewReused(content::RenderViewHost* render_view_host) override;

 private:
  // A map from URL origin to WebUI instance.
  typedef std::map<std::string, content::WebUI*> SubpageMap;

  // Creates and stores a WebUI for the given URL.
  void RegisterSubpage(const std::string& page_url,
                       const std::string& page_host);

  // The WebUI*s in this map are owned.
  SubpageMap sub_uis_;

  DISALLOW_COPY_AND_ASSIGN(UberUI);
};

class UberFrameUI : public content::WebUIController,
                    public extensions::ExtensionRegistryObserver {
 public:
  explicit UberFrameUI(content::WebUI* web_ui);
  ~UberFrameUI() override;

 private:
  // extensions::ExtensionRegistryObserver implementation.
  void OnExtensionLoaded(content::BrowserContext* browser_context,
                         const extensions::Extension* extension) override;
  void OnExtensionUnloaded(
      content::BrowserContext* browser_context,
      const extensions::Extension* extension,
      extensions::UnloadedExtensionInfo::Reason reason) override;

  ScopedObserver<extensions::ExtensionRegistry,
                 extensions::ExtensionRegistryObserver>
      extension_registry_observer_;

  DISALLOW_COPY_AND_ASSIGN(UberFrameUI);
};

#endif  // CHROME_BROWSER_UI_WEBUI_UBER_UBER_UI_H_


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Fusion;
using Fusion.Mathematics;
using Fusion.Graphics;
using Fusion.Input;
using Fusion.Development;
using System.Runtime.InteropServices;

namespace InstancingDemo2D {
	class InstancingDemo : Game {

		[StructLayout(LayoutKind.Explicit, Size=80)]
		struct ConstData {
			[FieldOffset(0)]
			public Matrix Transform;
			[FieldOffset(64)]
			public float  Time;
		}

		const int InstanceCount = 1000;

		struct InstData {
			public Vector2	Offset;
			public float	Rotation;
			public float	Scale;
			public Vector4	Color;
			public float	TexId;
		}

		Ubershader			us;
		VertexBuffer		vb;
		ConstantBuffer		cb;
		InstData[]			instDataCpu;
		StructuredBuffer	instDataGpu;
		Texture2D			tex;
		ConstData			cbData;
		StateFactory		factory;

		enum UberFlags {
			NONE,
		}

		struct Vertex {
			[Vertex("POSITION")]	public Vector3	Position;
			[Vertex("TEXCOORD", 0)]	public Vector2	TexCoord;
			[Vertex("COLOR")]		public Color	Color;
		}

		/// <summary>
		///	Add services and set options
		/// </summary>
		public InstancingDemo ()
		{
			//	enable object tracking :
			Parameters.TrackObjects		=	false;
			Parameters.VSyncInterval	=	1;
			Parameters.MsaaLevel		=	4;
			Parameters.StereoMode		=	StereoMode.Disabled;

			//	add services :
			AddService( new SpriteBatch( this ), false, false, 0, 0 );
			AddService( new DebugStrings( this ), true, true, 9999, 9999 );
			AddService( new DebugRender( this ), true, true, 9998, 9998 );
			AddService( new Camera( this ), true, false, 1, 1 );

			//	load configuration :
			LoadConfiguration();

			//	make configuration saved on exit
			Exiting += InstancingDemo_Exiting;

			//	handle keys
			InputDevice.KeyDown += InputDevice_KeyDown;
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		void InputDevice_KeyDown ( object sender, InputDevice.KeyEventArgs e )
		{
			if (e.Key == Keys.F1) {
				DevCon.Show(this);
			}

			if (e.Key == Keys.F2) {
				Parameters.VSyncInterval = (Parameters.VSyncInterval == 0) ? 1 : 0;
			}

			if (e.Key == Keys.F5) {
				Reload();
			}

			if (e.Key == Keys.F12) {
				GraphicsDevice.Screenshot();
			}

			if (e.Key == Keys.Escape) {
				Exit();
			}
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		void InstancingDemo_Exiting ( object sender, EventArgs e )
		{
			SaveConfiguration();
		}

		/// <summary>
		/// Load stuff here
		/// </summary>
		protected override void Initialize ()
		{
			var device	=	GraphicsDevice;

			base.Initialize();

			vb			=	new VertexBuffer(device,  typeof(Vertex), 6 );
			cb			=	new ConstantBuffer(GraphicsDevice, typeof(ConstData) );
			instDataGpu	=	new StructuredBuffer( device, typeof(InstData), InstanceCount, StructuredBufferFlags.None );
			instDataCpu	=	new InstData[ InstanceCount ];

			var rand = new Random();
			for (int i=0; i<InstanceCount; i++) {
				instDataCpu[ i ].Offset		=	rand.NextVector2( new Vector2(-2.5f,-2f), new Vector2( 2.5f,2f) );
				instDataCpu[ i ].Scale		=	rand.NextFloat( 0, 0.7f);
				instDataCpu[ i ].Rotation	=	rand.NextFloat( 0, MathUtil.TwoPi );
				instDataCpu[ i ].Color		=	rand.NextVector4( Vector4.Zero, Vector4.One * 0.7f );
				instDataCpu[ i ].TexId		=	rand.Next(4);
			}

			Reloading += InstancingDemo_Reloading;

			InstancingDemo_Reloading ( this, EventArgs.Empty );
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		void InstancingDemo_Reloading ( object sender, EventArgs e )
		{
			SafeDispose( ref factory );
			us		=	Content.Load<Ubershader>("test");
			factory	=	new StateFactory( us, typeof(UberFlags), Primitive.TriangleList, VertexInputElement.FromStructure( typeof(Vertex) ), BlendState.Additive, RasterizerState.CullNone, DepthStencilState.None );
			tex		=	Content.Load<Texture2D>("block" );
		}

		/// <summary>
		/// Kill stuff here
		/// </summary>
		protected override void Dispose ( bool disposing )
		{
			if (disposing) {
				SafeDispose( ref factory );
				SafeDispose( ref vb );
				SafeDispose( ref cb );
				SafeDispose( ref instDataGpu );
			}

			base.Dispose( disposing );
		}

		/// <summary>
		/// Update stuff here
		/// </summary>
		/// <param name="gameTime"></param>
		protected override void Update ( GameTime gameTime )
		{
			var ds = GetService<DebugStrings>();

			ds.Add( Color.Orange, "FPS {0}", gameTime.Fps );
			ds.Add( "F1   - show developer console" );
			ds.Add( "F2   - toggle vsync" );
			ds.Add( "F5   - build content and reload textures" );
			ds.Add( "F12  - make screenshot" );
			ds.Add( "ESC  - exit" );
			ds.Add("");

			base.Update( gameTime );

			var rand = new Random();
			for (int i=0; i<InstanceCount; i++) {
				instDataCpu[ i ].Scale		=	0.2f * (0.5f + 0.4f*(float)Math.Cos( 0.17*i + gameTime.Total.TotalSeconds * 2 ));
				instDataCpu[ i ].Rotation	+= (MathUtil.IsOdd(i) ? 0.01f : -0.01f);
				instDataCpu[ i ].Offset.Y	+= (MathUtil.IsOdd(i) ? 0.001f : -0.001f);

				if (instDataCpu[ i ].Offset.Y > 2) {
					instDataCpu[ i ].Offset.Y = -2;
				}
				if (instDataCpu[ i ].Offset.Y < -2) {
					instDataCpu[ i ].Offset.Y = 2;
				}
				/*float c = (1 - (instDataCpu[ i ].Offset.Y + 2)/4);
				c *= c * 0.5f;
				instDataCpu[ i ].Color = new Vector4(c,c,c,c);*/
			}

			instDataGpu.SetData( instDataCpu );
		}

		/// <summary>
		/// Draw stuff here
		/// </summary>
		/// <param name="gameTime"></param>
		/// <param name="stereoEye"></param>
		protected override void Draw ( GameTime gameTime, StereoEye stereoEye )
		{
			//	Clear back buffer :
			GraphicsDevice.ClearBackbuffer( new Color4(0,0,0,1) );

			//	Update constant buffer and bound it to pipeline:
			cbData.Transform	=	Matrix.OrthoRH( 4, 3, -2, 2 );
			cbData.Time = 0.001f * (float)gameTime.Total.TotalMilliseconds;
			cb.SetData( cbData );

			GraphicsDevice.VertexShaderConstants[0]	= cb ;
			GraphicsDevice.PixelShaderConstants[0]	= cb ;

			//	Fill vertex buffer :
			var v0	=	new Vertex{ Position = new Vector3( -1.0f, -1.0f, 0 ), Color = Color.Red,   TexCoord = new Vector2(0,1) };
			var v1	=	new Vertex{ Position = new Vector3(  1.0f,  1.0f, 0 ), Color = Color.White, TexCoord = new Vector2(1,0) };
			var v2	=	new Vertex{ Position = new Vector3( -1.0f,  1.0f, 0 ), Color = Color.Blue,  TexCoord = new Vector2(0,0) };
			var v3	=	new Vertex{ Position = new Vector3( -1.0f, -1.0f, 0 ), Color = Color.Red,   TexCoord = new Vector2(0,1) };
			var v4	=	new Vertex{ Position = new Vector3(  1.0f, -1.0f, 0 ), Color = Color.Lime,  TexCoord = new Vector2(1,1) };
			var v5	=	new Vertex{ Position = new Vector3(  1.0f,  1.0f, 0 ), Color = Color.White, TexCoord = new Vector2(1,0) };//*/

			var data = new Vertex[]{ v0, v1, v2, v3, v4, v5 };

			vb.SetData( data, 0, 6 );

			//	Set required ubershader :

			//	Set device states :
			GraphicsDevice.PipelineState		= factory[0];
			GraphicsDevice.PixelShaderSamplers[0]	= SamplerState.LinearWrap ;

			//	Setup texture :
			GraphicsDevice.PixelShaderResources[0]	= tex ;
			GraphicsDevice.VertexShaderResources[1]	= instDataGpu ;

			//	Setup vertex data and draw :
			GraphicsDevice.SetupVertexInput( vb, null );

			GraphicsDevice.DrawInstanced( 6, InstanceCount, 0, 0 );

			base.Draw( gameTime, stereoEye );
		}
	}
}


text:
package main

import (
	"context"
	"testing"

	"github.com/golang/mock/gomock"
	"github.com/pkg/errors"
	"github.com/stretchr/testify/assert"
	"github.com/uber-go/dosa"
	"github.com/uber-go/dosa/connectors/devnull"
	"github.com/uber-go/dosa/mocks"
)

type ClientTestEntity struct {
	dosa.Entity `dosa:"primaryKey=(ID)"`
	dosa.Index  `dosa:"key=Name, name=username"`
	ID          int64
	Name        string
	Email       string
}

var (
	table, _      = dosa.FindEntityByName(".", "ClientTestEntity")
	ctx           = context.TODO()
	scope         = "test"
	namePrefix    = "team.service"
	nullConnector = devnull.NewConnector()
	query1        = &queryObj{fieldName: "ID", colName: "id", op: "eq", valueStr: "10", value: dosa.FieldValue(int64(10))}
	query2        = &queryObj{fieldName: "ID", colName: "id", op: "lt", valueStr: "10", value: dosa.FieldValue(int64(10))}
	query3        = &queryObj{fieldName: "ID", colName: "id", op: "ne", valueStr: "10", value: dosa.FieldValue(int64(10))}
)

func TestNewClient(t *testing.T) {
	// initialize registrar
	reg, err := newSimpleRegistrar(scope, namePrefix, table)
	assert.NoError(t, err)
	assert.NotNil(t, reg)

	// initialize a pseudo-connected client
	client := newShellQueryClient(reg, nullConnector)
	err = client.Initialize(ctx)
	assert.NoError(t, err)
}

func TestClient_Initialize(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()
	reg, _ := newSimpleRegistrar(scope, namePrefix, table)

	// CheckSchema error
	errConn := mocks.NewMockConnector(ctrl)
	errConn.EXPECT().CheckSchema(ctx, gomock.Any(), gomock.Any(), gomock.Any()).Return(int32(-1), errors.New("CheckSchema error")).AnyTimes()
	c1 := newShellQueryClient(reg, errConn)
	assert.Error(t, c1.Initialize(ctx))

	// success case
	c2 := dosa.NewClient(reg, nullConnector)
	assert.NoError(t, c2.Initialize(ctx))
}


text:
import { CommandResult } from "./CommandResult";

/**
 * A cluster of code converted from a line of GLS syntax.
 */
export class LineResults {
    /**
     * Text contents of the result.
     */
    public commandResults: CommandResult[];

    /**
     * Whether this should have a semicolon appended.
     */
    public addSemicolon: boolean;

    /**
     * Any imports that must be in a file to use this.
     */
    public addedImports: { [i: string]: string[] };

    /**
     * Initializes a new instance of the LineResults class.
     *
     * @param commandResults   Lines of code converted fromthe GLS syntax.
     * @param addsSemicolon   Whether this should end with a semicolon.
     */
    constructor(commandResults: CommandResult[], addSemicolon: boolean) {
        this.commandResults = commandResults;
        this.addSemicolon = addSemicolon;
        this.addedImports = {};
    }

    /**
     *
     */
    public addImports(imports: { [i: string]: string[] }): void {
        if (this.addedImports === undefined) {
            this.addedImports = imports;
            return;
        }

        for (let packageName in imports) {
            this.addedImports[packageName] = imports[packageName];
        }
    }

    /**
     * Creates a new result containing a single line with a semicolon.
     *
     * @param text   The contents of the line.
     * @param addSemicolon   Whether the line should end with a semicolon.
     * @returns A new single line result.
     */
    public static newSingleLine(text: string, addSemicolon: boolean): LineResults {
        return new LineResults([new CommandResult(text, 0)], addSemicolon);
    }

    /**
     * Creates a new result containing the start or end of a block.
     *
     * @param text   The contents of the line.
     * @param indentation   How much the line changes indentation.
     * @returns A new block-changing line result.
     */
    public static newBlockLine(text: string, indentation: number): LineResults {
        return new LineResults([new CommandResult(text, indentation)], false);
    }
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.9.1: http://docutils.sourceforge.net/" />
<title>PyGreSQL future directions</title>
<link rel="stylesheet" href="docs.css" type="text/css" />

PyGreSQL future directions

This list has been closed since tasks are now managed with the PyGreSQL
tracker that can be found at http://trac.vex.net:8000/pgtracker.
(ticket numbers have been added below):

To Do

Add docs for the pgdb module (everything specific to PyGreSQL) (#5).

The large object and direct access functions need much more attention (#6).

The fetch method should use real cursors (#7).

The C module needs to be cleaned up and redundant code merged,
and should get its own unit test module (#8).

Clean up test_pg.py and merge it with TEST_PyGreSQL_classic.py (#9).

The test suite for the classic module should also check that quoted
mixed-case identifiers can be used everywhere - currently they can't.
Improve pg.py accordingly, adding quotes etc. as needed (#10).

What shall we do with the "tutorial" directory - it's rather a tutorial
for Postgres/SQL than for PyGreSQL, it's using only the query method from
the classic pg module and no other PyGreSQL functionality, it's rather
a demo than a tutorial (#11)?

Wish List

Make use of PQexecParams() and PQprepare(). This could speed up
executemany() and allow retrieving binary data directly by setting
the resultFormat parameter to one (#16).

Enhance cursor.description attribute, delivering more information
available with PQfmod() or PQftable() for instance (#17).

Support optional "errorhandler" extension (#18).

Support optional cursor and connection attribute "messages" (#19).

Users should be able to register their own types with _pg (#21).

pg has now got a new method namedresult() that returns named tuples.
pgdb should also support named tuples, maybe via a row_factory attribute
on the connection, similar to sqlite3 (see #22).

New methods in the classic module, similar to getresult() and
dictresult(), but returning dictionaries of rows instead of lists
of rows (with primary key or oids as keys) (#23).

Make PyGreSQL thread-safe on the connection level (#24).

The API documentation could be created with Epydoc or Sphinx (#4).

Write a tutorial for beginners and advanced use (#11).

More and better documented examples (#4, #5, #11).


text:
#include "../../../ScriptEnv.h"
#include "../ui/ChartsViewDlg.h"

#include "DataBuffer.h"

DWORD WINAPI DisplayMngThread(PVOID param)
{
	DataBuffer* pBuffer = (DataBuffer*)param;

	pBuffer->pChartsView_ = new CChartsViewDlg(pBuffer->name_);

	CChartsViewDlg* pChartsView = pBuffer->pChartsView_;

	SetEvent(pBuffer->event_);

	pChartsView->DoModal();

	return 0;
}


text:
namespace Sim {
	namespace Memory {
		void init();
	}
}


text:
require "codeclimate-test-reporter"
CodeClimate::TestReporter.start

require "simplecov"
require "bundler/setup"
require "rspec"

SimpleCov.start do
  add_filter do |src|
    src.lines.count < 5
  end
  add_filter "/spec/"
end

RSpec.configure do |config|
  config.expect_with :rspec do |c|
    c.syntax = :expect
  end
end


text:
"""
test_django-courses
------------

Tests for `django-courses` models module.
"""

import os
import shutil
import unittest

from courses import models

class TestCourses(unittest.TestCase):

    def setUp(self):
        pass

    def test_something(self):
        pass

    def tearDown(self):
        pass


text:
package d366.net.musicplayer;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;

// Map the songs list to the ListView
public class SongAdapter extends BaseAdapter{
    private ArrayList<Song> songs;
    // Map the title and artist strings to the TextView
    private LayoutInflater songInf;

    public SongAdapter(Context c, ArrayList<Song> theSongs){
        songs = theSongs;
        songInf = LayoutInflater.from(c);
    }

    @Override
    public int getCount() {
        return songs.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Map to song layout
        LinearLayout songLay = (LinearLayout)songInf.inflate(R.layout.song, parent, false);

        // Get title and artist views
        TextView songView = (TextView)songLay.findViewById(R.id.song_title);
        TextView artistView = (TextView)songLay.findViewById(R.id.song_artist);

        // Get song using position
        Song currSong = songs.get(position);

        // Get title and artist strings
        songView.setText(currSong.getTitle());
        artistView.setText(currSong.getArtist());

        // Set position as tag
        songLay.setTag(position);

        return songLay;
    }
}


text:
package com.si.jupiter.smart.client.config;

/**
 * This is just a concrete, usable wrapper for {@link ThriftClientDefBuilderBase}, which
 * can't be used directly even if it was not abstract, because it uses a recursive generic
 * definition.
 */
public class ThriftClientDefBuilder
        extends ThriftClientDefBuilderBase<ThriftClientDefBuilder> {}


text:
Template.tmp_ctn_list_note_item.created = function () {

};
Template.tmp_ctn_list_note_item.rendered = function () {
    var data = $(this)[0];
    console.log(data);
    $('#' + data.data._id).html(data.data.Content);
};
Template.tmp_ctn_list_note_item.events({
    'click #btnEdit': function (e) {
        e.preventDefault();
        var id = $(this)[0]._id;
    },
    'click #btnDelete': function (e) {
        e.preventDefault();
        var id = $(this)[0]._id;
    }
});


text:
<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class UserApiTableSeeder extends Seeder {

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run() {
        DB::table('user_api')->insert([
            'user_id'    => 1,
            'api_id'     => 1,
            'is_owner'   => true,
            'permission' => 'RW',
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now()
        ]);
    }
}


text: require 'refinery/photo_gallery'


text:
import React from "react";
import CodeExample from "../code-example";

import ex from "./code.example";
import desc from "./description.md";

const AlertContainerDemo = props => (
	<CodeExample
		title={AlertContainer}
		code={ex}
		description={desc}
		{...props}
	/>
);

export default AlertContainerDemo;


text:
using System;
using UnityEngine;
using Flunity.Utils;
using Flunity.Common;
using Flunity.Internal;

namespace Flunity
{
	/// <summary>
	/// Unity component in which flash scene is beind rendered.
	/// </summary>
	[ExecuteInEditMode]
	public class FlashStage: MonoBehaviour
	{
		/// <summary>
		/// Root DisplayContainer
		/// </summary>
		public DisplayContainer root { get; private set; }

		/// <summary>
		/// Global inout controller
		/// </summary>
		public InputController input { get; private set; }

		/// <summary>
		/// Scene width
		/// </summary>
		public int width = 600;

		/// <summary>
		/// Scene height
		/// </summary>
		public int height = 400;

		internal readonly EventSender drawEvent = new EventSender();
		internal readonly EventSender updateEvent = new EventSender();

		internal TouchController touchController;
		internal DrawBatch debugBatch;
		internal DrawBatch sceneBatch;
		internal bool isDrawPhase;

		#region events

		private readonly FlashStageEvents _events = new FlashStageEvents();

		public FlashStageEvents events
		{
			get { return _events; }
		}

		#endregion

		#region shader

		[SerializeField]
		private Shader _shader;

		private bool _shaderDirty;

		/// <summary>
		/// Shader used for rendering
		/// </summary>
		public Shader shader
		{
			get { return _shader; }
			set
			{
				if (_shader != value)
				{
					_shader = value;
					_shaderDirty = true;
				}
			}
		}

		#endregion

		#region resourcePath

		[SerializeField]
		private String _resourcePath = "";

		private bool _resourceDirty;

		/// <summary>
		/// Resource wich will be automatically attached to the root.
		/// </summary>
		public String resourcePath
		{
			get { return _resourcePath; }
			set
			{
				if (_resourcePath != value)
				{
					_resourcePath = value;
					_resourceDirty = true;
				}
			}
		}

		#endregion

		#region isPlaying

		[SerializeField]
		private bool _isPlaying;

		/// <summary>
		/// If resource path is set, specifies whether attached instance should by played.
		/// </summary>
		public bool isPlaying
		{
			get	{ return _isPlaying; }
			set
			{
				if (_isPlaying != value)
				{
					_isPlaying = value;
					_resourceDirty = _resourcePath.IsNotEmpty();
				}
			}
		}

		#endregion

		#region life cycle

		void Awake()
		{
			root = new DisplayRoot(this);
			input = new InputController(this);
			touchController = new TouchController(this);
			sceneBatch = new DrawBatch();
			debugBatch = new DrawBatch();

			if (shader == null)
				shader = Shader.Find("Flunity/Default");
		}

		void OnEnable()
		{
			if (root == null)
			{
				Awake();
				Start();
			}

//			Causes broblem on scene loading (possibly needed by live reloading)
//			if (Application.isEditor)
//				FlashResources.UnloadAllBundles();
		}

		void Start()
		{
			_shaderDirty = true;
			_resourceDirty = _resourcePath.IsNotEmpty();
			FlashResources.Reloaded += onReloaded;
		}

		void onReloaded()
		{
			_resourceDirty = _resourcePath.IsNotEmpty();
		}

		void OnDestroy()
		{
			if (root != null)
			{
				root.stage = null;
				root.RemoveChildren();
				root = null;

				debugBatch.Destroy();
				sceneBatch.Destroy();
			}
		}

		void FixedUpdate()
		{
			isDrawPhase = false;

			if (Application.isPlaying)
			{
				input.DoUpdate();
				touchController.DoUpdate();
				updateEvent.Dispatch();
			}
		}

		void Update()
		{
			isDrawPhase = false;

			if (FlashResources.isPlatformReloadingEnabled)
				FlashResources.reloadPendingResources();

			if (_shaderDirty)
			{
				sceneBatch.shader = shader;
				debugBatch.shader = shader;

				_shaderDirty = false;
			}

			if (_resourceDirty)
			{
				UpdateContent();
				_resourceDirty = false;
			}

			isDrawPhase = true;

			debugBatch.Begin(GetGlobalMatrix());
			root.Draw();
			drawEvent.Dispatch();
			debugBatch.renderQueue = sceneBatch.renderQueue + 1;
			debugBatch.End();

			isDrawPhase = false;
		}

		#endregion

		#region transform

		public Matrix4x4 GetGlobalMatrix()
		{
			var stageMatrix = transform != null
				? transform.localToWorldMatrix
				: Matrix4x4.identity;

			var rootScale = new Vector3(1, -1, 1);
			var rootPosition = new Vector3(-0.5f * width, 0.5f * height, 0);
			var rootMatrix = Matrix4x4.TRS(rootPosition, Quaternion.identity, rootScale);
			return stageMatrix * rootMatrix;
		}

		public Vector2 TouchToComponentPoint(Vector3 point)
		{
			var worldPos = Camera.main.ScreenToWorldPoint(point);
			return WorldToComponentPoint(worldPos);
		}

		public Vector2 WorldToComponentPoint(Vector3 point)
		{
			return GetGlobalMatrix().inverse.MultiplyPoint3x4(point);
		}

		#endregion

		#region gizmos

		void OnDrawGizmos()
		{
			var matrix = GetGlobalMatrix();
			var w = width;
			var h = height;

			if (Application.isEditor)
			{
				var lt = matrix.MultiplyPoint(new Vector3(0, 0, 0));
				var rt = matrix.MultiplyPoint(new Vector3(w, 0, 0));
				var lb = matrix.MultiplyPoint(new Vector3(0, h, 0));
				var rb = matrix.MultiplyPoint(new Vector3(w, h, 0));

				Gizmos.DrawLine(lt, rt);
				Gizmos.DrawLine(lb, rb);
				Gizmos.DrawLine(lt, lb);
				Gizmos.DrawLine(rt, rb);

				if (!Application.isPlaying && (root == null || root.numChildren == 0))
				{
					Gizmos.DrawLine(lt, rb);
					Gizmos.DrawLine(rt, lb);
				}
			}
		}

		#endregion

		#region update

		void UpdateContent()
		{
			root.RemoveChildren();

			if (resourcePath.IsNullOrEmpty())
				return;

			var bundleName = resourcePath.Split("/")[0];
			var bundle = FlashResources.GetBundleInstance(bundleName);
			if (bundle == null)
			{
				Debug.Log("Bundle not found: " + bundleName);
				return;
			}

			if (!bundle.isLoaded)
				FlashResources.LoadBundle(bundle);

			var resource = FlashResources.GetResource<IDisplayResource>(resourcePath);
			if (resource == null)
			{
				Debug.Log("Resource not found: " + resourcePath);
				return;
			}

			var instance = resource.CreateInstance();
			root.AddChild(instance);

			if (isPlaying)
			{
				if (instance.totalFrames > 1)
				{
					instance.Play();
				}
				else
				{
					var displayContainer = instance as DisplayContainer;
					if (displayContainer != null)
						displayContainer.PlayAllChildren();
				}
			}
		}

		#endregion
	}
}


text:
@interface UILabel (Extention)

+(instancetype)makeLabel:(void(^)(UILabel*label))block;

@end


text:
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'addressbook'

test = Addressbook::Person.new("Eric","856-924-8029")
puts "This is test: #{test.name}"
puts "This is the #{test.name} phone number #{test.phone_number}"


text:
package ru.stqa.mantis.appmanager;

import biz.futureware.mantis.rpc.soap.client.*;
import ru.stqa.mantis.model.Issue;
import ru.stqa.mantis.model.Project;
import ru.stqa.mantis.model.Status;

import javax.xml.rpc.ServiceException;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by User on 16.04.2017.
 */
public class SoapHelper {
    private final ApplicationManager app;

    public SoapHelper(ApplicationManager app) {
        this.app = app;
    }

    public Set<Project> getProjects() throws MalformedURLException, ServiceException, RemoteException {
        MantisConnectPortType mc = getMantisConnect();
        ProjectData[] projects = mc.mc_projects_get_user_accessible("administrator", "root");
        return Arrays.asList(projects).stream()
                .map((p) -> new Project().withId(p.getId().intValue()).withName(p.getName())).collect(Collectors.toSet());

    }

    private MantisConnectPortType getMantisConnect() throws ServiceException, MalformedURLException {
        return new MantisConnectLocator()
                .getMantisConnectPort(new URL(app.getProperty("web.soapUrl")));
    }

    public Issue addIssue(Issue issue) throws MalformedURLException, ServiceException, RemoteException {
        MantisConnectPortType mc = getMantisConnect();
        String[] categories = mc.mc_project_get_categories("administrator", "root", BigInteger.valueOf(issue.getProject().getId()));
        IssueData issueData = new IssueData();
        issueData.setSummary(issue.getSummary());
        issueData.setDescription(issue.getDescription());
        issueData.setProject(new ObjectRef(BigInteger.valueOf(issue.getId()), issue.getProject().getName()));
        issueData.setCategory(categories[0]);
        BigInteger issueId = mc.mc_issue_add("administrator", "root", issueData);
        IssueData createdIssueData = mc.mc_issue_get("administrator", "root", issueId);
        return new Issue().withId(createdIssueData.getId().intValue())
                .withSummary(createdIssueData.getSummary()).withDescription(createdIssueData.getDescription())
                .withProject(new Project().withId(createdIssueData.getProject().getId().intValue())
                        .withName(createdIssueData.getProject().getName()));

    }

    public Issue getIssueById(int id) throws MalformedURLException, ServiceException, RemoteException {
        MantisConnectPortType mc = getMantisConnect();
        IssueData issueData = mc.mc_issue_get("administrator", "root", BigInteger.valueOf(id));
        return new Issue().withId(issueData.getId().intValue())
                .withStatus(new Status().withId(issueData.getStatus().getId().intValue()).withName(issueData.getStatus().getName()))
                .withSummary(issueData.getSummary()).withDescription(issueData.getDescription())
                .withProject(new Project().withId(issueData.getProject().getId().intValue())
                        .withName(issueData.getProject().getName()));

    }
}


text:
#include <math.h>

#define weaver_debug_
#include "common/stl_serialization.h"
#include "node_prog/edge.h"
#include "node_prog/neural_net_infer.h"

using node_prog::Node_Parameters_Base;
using node_prog::Node_State_Base;
using node_prog::search_type;
using node_prog::nn_params;
using node_prog::nn_state;
using node_prog::node;
using node_prog::edge;

// params
nn_params :: nn_params()
    : order(-1)
    , act_func("sigmoid")
{ }

uint64_t
nn_params :: size(void *aux_args) const
{
    return message::size(aux_args, network_description)
         + message::size(aux_args, input)
         + message::size(aux_args, order)
         + message::size(aux_args, act_func)
         + message::size(aux_args, layer_type)
         + message::size(aux_args, layer_op);
}

void
nn_params :: pack(e::packer &packer, void *aux_args) const
{
    message::pack_buffer(packer, aux_args, network_description);
    message::pack_buffer(packer, aux_args, input);
    message::pack_buffer(packer, aux_args, order);
    message::pack_buffer(packer, aux_args, act_func);
    message::pack_buffer(packer, aux_args, layer_type);
    message::pack_buffer(packer, aux_args, layer_op);
}

void
nn_params :: unpack(e::unpacker &unpacker, void *aux_args)
{
    message::unpack_buffer(unpacker, aux_args, network_description);
    message::unpack_buffer(unpacker, aux_args, input);
    message::unpack_buffer(unpacker, aux_args, order);
    message::unpack_buffer(unpacker, aux_args, act_func);
    message::unpack_buffer(unpacker, aux_args, layer_type);
    message::unpack_buffer(unpacker, aux_args, layer_op);
}

// state
nn_state :: nn_state()
    : visited(false)
    , in_count(0)
{ }

uint64_t
nn_state :: size(void *aux_args) const
{
    return message::size(aux_args, visited)
         + message::size(aux_args, in_count)
         + message::size(aux_args, value);
}

void
nn_state :: pack(e::packer &packer, void *aux_args) const
{
    message::pack_buffer(packer, aux_args, visited);
    message::pack_buffer(packer, aux_args, in_count);
    message::pack_buffer(packer, aux_args, value);
}

void
nn_state :: unpack(e::unpacker &unpacker, void *aux_args)
{
    message::unpack_buffer(unpacker, aux_args, visited);
    message::unpack_buffer(unpacker, aux_args, in_count);
    message::unpack_buffer(unpacker, aux_args, value);
}

// forward and backward edge props
static std::pair<std::string, std::string> fwd_prop = std::make_pair("dir", "f");
static std::pair<std::string, std::string> rev_prop = std::make_pair("dir", "b");

uint32_t
calculate_in_count(node &n)
{
    uint32_t count = 0;
    for (edge &e: n.get_edges()) {
        if (e.has_property(rev_prop)) {
            count++;
        }
    }

    return count;
}

bool
to_double(const std::string &str, double &v)
{
    try {
        v = std::stod(str);
    } catch (std::invalid_argument &e) {
        WDEBUG << "invalid arg " << e.what() << std::endl;
        WDEBUG << "prop=" << str << std::endl;
        return false;
    }
    return true;
}

bool
get_edge_weight(edge &e, double &weight)
{
    return to_double(e.get_property("weight"), weight);
}

bool
get_edge_order(edge &e, int &order)
{
    try {
        order = std::stoi(e.get_property("order"));
    } catch (std::invalid_argument &ia) {
        WDEBUG << "invalid arg " << ia.what() << std::endl;
        WDEBUG << "prop=" << e.get_property("order") << std::endl;
        return false;
    }
    return true;
}

// activation functions
// f(x) = x
double
id(double x)
{
    return x;
}

// f(x) = 0 if x<0, 1 otherwise
double
step(double x)
{
    return x>=0? 1 : 0;
}

// f(x) = 1 / (1 + e^(-x))
double
sigmoid(double x)
{
    double denominator = 1 + exp(-1 * x);
    return 1 / denominator;
}

// f(x) = 0 if x<0, x otherwise
double
relu(double x)
{
    return x>=0? x : 0;
}

// f(x) = e^(-(x^2))
double
gaussian(double x)
{
    double exponent = -1 * x * x;
    return exp(exponent);
}

double
apply_activation_function(double val, const std::string &func)
{
    if (func == "id") {
        return id(val);
    } else if (func == "step") {
        return step(val);
    } else if (func == "sigmoid") {
        return sigmoid(val);
    } else if (func == "relu") {
        return relu(val);
    } else if (func == "gaussian") {
        return gaussian(val);
    } else {
        // unknown func type, apply sigmoid
        return sigmoid(val);
    }
}

extern "C" {

PROG_FUNC_DEFINE(nn);

std::pair<search_type, std::vector<std::pair<db::remote_node, std::shared_ptr<Node_Parameters_Base>>>>
node_prog :: node_program(node &n,
   db::remote_node&,
   std::shared_ptr<Node_Parameters_Base> param_ptr,
   std::function<Node_State_Base&()> state_getter)
{
    //WDEBUG << "neural net prog execing at node=" << n.get_handle() << std::endl;

    Node_State_Base &state_base = state_getter();
    nn_state& state = dynamic_cast<nn_state&>(state_base);

    Node_Parameters_Base &param_base = *param_ptr;
    nn_params &params = dynamic_cast<nn_params&>(param_base);

    std::vector<std::pair<db::remote_node, std::shared_ptr<Node_Parameters_Base>>> next;

    if (n.get_handle() == params.network_description.first) {
        // first node/layer
        state.visited = true;
        auto input = params.input;
        params.input.clear();
        params.input.emplace_back(0.0);

        for (edge &e: n.get_edges()) {
            if (e.has_property(fwd_prop)) {
                int order;
                double weight;
                if (!get_edge_weight(e, weight)
                 || !get_edge_order(e, order)) {
                    continue;
                }

                params.input[0] = weight*input[order];
                params.order = -1;
                params.layer_type = "init";
                params.layer_op = "";
                next.emplace_back(std::make_pair(e.get_neighbor(),
                                                 std::make_shared<nn_params>(params)));
            }
        }
    } else if (n.get_handle() == params.network_description.second) {
        // last node/layer
        if (!state.visited) {
            state.visited = true;
            state.in_count = calculate_in_count(n);
            state.value.assign(state.in_count, 0);
        }

        state.value[params.order] = params.input[0];

        if (--state.in_count == 0) {
            params.input = state.value;
            next.emplace_back(std::make_pair(db::coordinator,
                                             std::make_shared<nn_params>(params)));
        }
    } else {
        // middle layer
        if (!state.visited) {
            state.visited = true;
            state.in_count = calculate_in_count(n);
            //WDEBUG << "in count=" << state.in_count << std::endl;

            //double bias;
            //if (!to_double(n.get_property("bias"), bias)) {
            //    WDEBUG << "bias fail" << std::endl;
            //    state.value.emplace_back(bias);
            //} else {
            //    state.value.emplace_back(0.0);
            //}
            //WDEBUG << "value=" << state.value[0] << std::endl;
            state.value.emplace_back(0.0);
        }

        state.value[0] += params.input[0];

        if (--state.in_count == 0) {
            //WDEBUG << "in count zero" << std::endl;
            state.value[0] = apply_activation_function(state.value[0], params.act_func);
            //WDEBUG << "val=" << state.value[0]
            //       << " val sz=" << state.value.size()
            //       << std::endl;

            for (edge &e: n.get_edges()) {
                if (e.has_property(fwd_prop)) {
                    double weight;
                    if (!get_edge_weight(e, weight)
                     || !get_edge_order(e, params.order)) {
                        WDEBUG << "fail weight/order" << std::endl;
                        continue;
                    }

                    params.layer_type = e.get_property("type");
                    params.layer_op   = e.get_property("op");
                    //if (params.layer_type.empty()
                    // || params.layer_op.empty()) {
                    //    continue;
                    //}

                    params.input[0] = weight*state.value[0];
                    //WDEBUG << "params.input=" << params.input[0] << std::endl;

                    next.emplace_back(std::make_pair(e.get_neighbor(),
                                                     std::make_shared<nn_params>(params)));
                }
            }
        }
    }

    return std::make_pair(search_type::BREADTH_FIRST, next);
}

} // extern C


text:
//=============================================================================================================

#ifndef LAYOUTMAKER_H
#define LAYOUTMAKER_H

//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "utils_global.h"

//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QVector>
#include <QList>
#include <QStringList>
#include <QFile>

//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================

#include <Eigen/Core>

//=============================================================================================================
// DEFINE NAMESPACE MNELIB
//=============================================================================================================

namespace UTILSLIB
{

//=============================================================================================================
// TYPEDEFS
//=============================================================================================================

typedef struct {
  Eigen::MatrixXf rr;
  int   np;
  int   report;
} *fitUser,fitUserRec;

//=============================================================================================================
/**
 * Make layout files from given 3D points
 *
 * @brief Make layout files from given 3D points.
 */
class UTILSSHARED_EXPORT LayoutMaker
{
public:
    //=========================================================================================================
    /**
     * Constructs a LayoutMaker object.
     */
    LayoutMaker();

    //=========================================================================================================
    /**
     * Reads the specified ANT elc-layout file.
     * @param [in] inputPoints       The input points in 3D space.
     * @param [out] outputPoints     The output layout points in 2D space.
     * @param [in] names             The channel names.
     * @param [in] outFile           The outout file.
     * @param [in] do_fit            The flag whether to do a sphere fitting.
     * @param [in] prad
     * @param [in] w
     * @param [in] h
     * @param [in] writeFile         The flag whether to write to file.
     * @param [in] mirrorXAxis       Mirror points at x axis.
     * @param [in] mirrorYAxis       Mirror points at y axis.
     *
     * @return true if making layout was successful, false otherwise.
     */
    static bool makeLayout(const QList<QVector<float> > &inputPoints,
                           QList<QVector<float> > &outputPoints,
                           const QStringList &names,
                           QFile &outFile,
                           bool do_fit,
                           float prad,
                           float w,
                           float h,
                           bool writeFile = false,
                           bool mirrorXAxis = false,
                           bool mirrorYAxis = false);

private:
    static void sphere_coord(float x,
                      float y,
                      float z,
                      float *r,
                      float *theta,
                      float *phi);
};
} //NAMESPACE

#endif // LAYOUTMAKER_H


text:
package org.apache.zookeeper.recipes.lock;

/**
 * This class has two methods which are call back methods when a lock is
 * acquired and when the lock is released.
 *
 */
public interface LockListener {
	/**
	 * call back called when the lock is acquired
	 */
	public void lockAcquired();

	/**
	 * call back called when the lock is released.
	 */
	public void lockReleased();
}


text:
__author__ = 'cfiloteo'
from django.dispatch import receiver
from django_cas_ng.signals import cas_user_authenticated
from home import models as hmod

###########################################################
###   Signal handler for when users authenticate via CAS

@receiver(cas_user_authenticated)
def cas_authentication_handler(sender, **kwargs):
    user = kwargs['user']
    attributes = kwargs['attributes']

    # fill out the user account with info from BYU
    for fieldname, attrname in [
        ( 'first_name', 'preferredFirstName' ),
        ( 'last_name' , 'preferredSurname' ),
        ( 'email'     , 'emailAddress' ),
        ( 'fullname'  , 'fullName' ),
    ]:
        if attributes.get(attrname):
            setattr(user, fieldname, attributes.get(attrname))
        else:
            setattr(user, fieldname, '')

    # byu status logic
    status_list = []
    for attrname in [
        'activeParttimeEmployee',
        'activeFulltimeEmployee',
        'activeFulltimeInstructor',
        'inactiveFulltimeInstructor',
        'activeParttimeNonBYUEmployee',
        'inactiveParttimeNonBYUEmployee',
        'activeEligibletoRegisterStudent',
        'inactiveFulltimeNonBYUEmployee',
        'inactiveParttimeInstructor',
        'inactiveParttimeEmployee',
        'activeFulltimeNonBYUEmployee',
        'inactiveFulltimeEmployee',
        'activeParttimeInstructor',
        'alumni',
    ]:
        if attributes.get(attrname) == 'true':
            status_list.append(attrname)

    user.byu_status = ','.join(status_list)
    # save the user
    user.save()