text:
package cogx

import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FunSuite
import scala.collection.mutable.ArrayBuffer

/** Unit tests for the Random operator. Note that only functionality for 1 bit
  * of precision is enabled.
  *
  * @author Matthew Pickett
  */
@RunWith(classOf[JUnitRunner])
class RandomSpec extends FunSuite {

  val maxDimSize = 20
  val minPoints = 64

  def gen(bits:Int, numRandoms:Int) = {
    val rng = new java.util.Random
    val fieldDims = rng.nextInt(4)

    val fieldShape = Shape(Array.tabulate(fieldDims){
      (i) => rng.nextInt(maxDimSize) + 1
    })

    val tensorPoints = rng.nextInt(maxDimSize) + minPoints/fieldShape.points + 1
    val tensorShape = Shape(tensorPoints)
    val points = fieldShape.points*tensorShape.points

    val graph = new ComputeGraph{
      val rand = VectorField.random(fieldShape,tensorShape)
      rand <== random(rand, bits)
      val flat = reshape(rand, Shape(), Shape(points))
      probe(flat, "")
    }

    val buff = new ArrayBuffer[Float]()
    val vec = Vector(points, (i)=>0f)
    val steps = numRandoms/points + 1
    println(s"FieldShape: $fieldShape")
    println(s"TensorShape: $tensorShape")
    import graph._
    withRelease {
      step
      for(i <- 0 until steps){
        step
        val reader = read(flat).asInstanceOf[VectorFieldReader]
        reader.read(vec)
        buff ++= vec.getData
      }
    }
    buff.toVector
  }

  //ensure that the values of the output are consistent with the number of bits
  // i.e. (0f, 1f) for 1 bit.  (0f, 0.333f, 0.666f, 1f) for 2 bits.
  def valuesTest(bits:Int, numValues:Int):Boolean = {
    val values = gen(bits, numValues)
    val possibleVals =math.pow(2,bits).toInt
    val step = 1f/(possibleVals.toFloat-1f)
    val okVals = IndexedSeq.tabulate(possibleVals){(i)=>i*step}
    val remaining = values.filterNot((x)=> okVals.contains(x))
    remaining.length == 0
  }

  test("1 bit values") { require(valuesTest(1, 100000)) }
  /*test("2 bit values") { require(valuesTest(2, 100000)) }
  test("3 bit values") { require(valuesTest(3, 100000)) }
  test("4 bit values") { require(valuesTest(4, 100000)) }
  test("5 bit values") { require(valuesTest(5, 100000)) }
  test("6 bit values") { require(valuesTest(6, 100000)) }
  test("7 bit values") { require(valuesTest(7, 100000)) }
  test("8 bit values") { require(valuesTest(8, 100000)) }*/

  def frequencyTest(bits:Int, numValues:Int) = {
    val values = gen(bits, numValues)
    val points = values.length
    val possibleVals =math.pow(2,bits).toInt
    val step = 1f/(possibleVals.toFloat-1f)
    val bins = Array.tabulate(possibleVals){(i)=>0}
    val okVals = IndexedSeq.tabulate(possibleVals){(i)=>i*step}
    values.foreach(x=> bins(okVals.indexOf(x))+=1)
    val freq = bins.map(_.toFloat/points)
    val total = freq.reduce(_+_)
    val max = freq.reduce((x,y) =>math.max(x,y))
    val min = freq.reduce((x,y) =>math.min(x,y))
    bins.foreach{println}
    println(s"Max: $max")
    println(s"Min: $min")
    println(s"Total: $total")
    val maxMinDiff = (max - min)/min
    require(maxMinDiff < 0.3f,
      "Percent difference between max and min frequency should be less than 30%")
  }

//  test("1 bit freq") { frequencyTest(1, 100000) }
/*  test("2 bit freq") { frequencyTest(2, 100000) }
  test("3 bit freq") { frequencyTest(3, 100000) }
  test("4 bit freq") { frequencyTest(4, 100000) }
  test("5 bit freq") { frequencyTest(5, 100000) }
  test("6 bit freq") { frequencyTest(6, 1000000) }
  test("7 bit freq") { frequencyTest(7, 1000000) }
  test("8 bit freq") { frequencyTest(8, 1000000) }*/

}


text:
<?php

	define("API_URL","http://localhost:8080/wwwroot/api");
	$APP = "spikademo";

	//------------------------ low level functions

	function HU_getRequest($url,$requestHeader = array()){

    	$headers = array();
    	foreach($requestHeader as $key => $value){
        	$headers[] = "{$key}: {$value}";
    	}

		$curl = curl_init();

		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

		$response = curl_exec($curl);

		return $response;

	}

	function HU_postRequest($url, $reqBody,$requestHeader = array()){

    	$headers = array();
    	foreach($requestHeader as $key => $value){
        	$headers[] = "{$key}: {$value}";
    	}

		$curl = curl_init();

		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_POST, true);
		curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

		$response = curl_exec($curl);

		return $response;

	}

	function HU_putRequest($url, $reqBody,$requestHeader = array()){

    	$headers = array();
    	foreach($requestHeader as $key => $value){
        	$headers[] = "{$key}: {$value}";
    	}

		$curl = curl_init();

		curl_setopt($curl, CURLOPT_URL, $url);
		curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
		curl_setopt($curl, CURLOPT_POSTFIELDS, $reqBody);
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

		$response = curl_exec($curl);

		return $response;

	}

	function HU_checkAndMakeRequestHeader(){

		global $HU_USERID,$HU_USERTOKEN,$APP;

		if(empty($HU_USERID) || empty($HU_USERTOKEN)){
			return;
		}

		$requestHeader = array(
			"user_id: {$HU_USERID}",
			"token: {$HU_USERTOKEN}",
			"database: {$APP}",
		);

		return $requestHeader;
	}

	function HU_dbGetDocument($documentId){

		$requestHeader = HU_checkAndMakeRequestHeader();
		if($requestHeader == null)
			return;

    	$result = HU_getRequest(API_URL . $documentId,$requestHeader);

		$resultDic = json_decode($result,true);
		return $resultDic;
	}

	function HU_dbFindByKey($view,$key){

		$requestHeader = HU_checkAndMakeRequestHeader();
		if($requestHeader == null)
			return;

		$key = urlencode($key);

    	$url = "_design/app/_view/{$view}?key=\"{$key}\"";

    	$result = HU_getRequest(API_URL . $url,$requestHeader);

		$resultDic = json_decode($result,true);

		return $resultDic['rows'][0]['value'];
	}

	function HU_dbFindAll($view){

		$requestHeader = HU_checkAndMakeRequestHeader();
		if($requestHeader == null)
			return;

		$key = urlencode($key);

    	$url = "_design/app/_view/{$view}";

    	$result = HU_getRequest(API_URL . $url,$requestHeader);

		$resultDic = json_decode($result,true);

		return $resultDic['rows'];
	}

	function HU_dbInsert($data){

		$requestHeader = HU_checkAndMakeRequestHeader();
		if($requestHeader == null)
			return;

		return HU_postRequest(API_URL . "",json_encode($data),$requestHeader);

	}

	function HU_dbUpdate($id,$data){

		$requestHeader = HU_checkAndMakeRequestHeader();
		if($requestHeader == null)
			return;

		return HU_putRequest(API_URL . $id,json_encode($data),$requestHeader);

	}

	function HU_sendFile($file){

		global $APP;

		$requestHeader = HU_checkAndMakeRequestHeader();
		if($requestHeader == null)
			return;

		$post = array('file'=>'@'.$file);

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,API_URL."fileuploader.php?db=" . $APP);
		curl_setopt($ch, CURLOPT_POST,1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

		$result = curl_exec ($ch);

		curl_close ($ch);

		return $result;

	}

	//------------------------ high level functions

	function HU_createUser($name,$email,$password){

		global $APP;

		$userData = array();

		$userData['name'] = $name;
		$userData['email'] = $email;
		$userData['password'] = $password;
		$userData['type'] = "user";
		$userData['online_status'] = "online";
		$userData['max_contact_count'] = 20;
		$userData['max_favorite_count'] = 10;

		$requestHeader = array(
			'user_id: create_user',
			"database: {$APP}"
		);

		return HU_postRequest(API_URL . "",json_encode($userData),$requestHeader);

	}

	function HU_login($email,$password){

		global $APP;

		$requestHeader = array(
			"database: {$APP}",
		);

		$params = array(
			"email" => $email,
			"password" => $password
		);

		$result = HU_postRequest(API_URL . "hookup-auth.php",json_encode($params),$requestHeader);

		$resultDic = json_decode($result,true);

		return $resultDic['rows'][0]['value'];

	}

	function HU_findUserByName($name){
		return HU_dbFindByKey("find_user_by_name",$name);
	}

	function HU_findGroupByName($name){
		return HU_dbFindByKey("find_group_by_name",$name);
	}

	function HU_sendTextMessageToUser($from,$to,$message){

		$postData = array();

		$postData['type'] = "message";
		$postData['message_type'] = "text";
		$postData['body'] = $message;
		$postData['from_user_id'] = $from['_id'];
		$postData['from_user_name'] = $from['name'];
		$postData['created'] = time();
		$postData['modified'] = time();
		$postData['valid'] = true;
		$postData['to_user_name'] = $to['name'];
		$postData['to_user_id'] = $to['_id'];
		$postData['message_target_type'] = 'user';

		return HU_dbInsert($postData);

	}

	function HU_sendImageMessageToUser($from,$to,$bigImagePath,$smallImagePath){

		$bigImageId = HU_sendFile($bigImagePath);
		$smallImageId = HU_sendFile($smallImagePath);

		if(empty($bigImageId) || empty($smallImageId)){
			return;
		}

		$postData = array();

		$postData['type'] = "message";
		$postData['message_type'] = "image";
		$postData['body'] = "";
		$postData['from_user_id'] = $from['_id'];
		$postData['from_user_name'] = $from['name'];
		$postData['created'] = time();
		$postData['modified'] = time();
		$postData['valid'] = true;
		$postData['to_user_name'] = $to['name'];
		$postData['to_user_id'] = $to['_id'];
		$postData['message_target_type'] = 'user';

		$postData['picture_file_id'] = $bigImageId;
		$postData['picture_thumb_file_id'] = $smallImageId;

		return HU_dbInsert($postData);

	}

	function HU_subscribeGrupe($group,$user){

		$postData = array();

		$postData['type'] = "user_group";
		$postData['group_id'] = $group['_id'];
		$postData['user_id'] = $user['_id'];
		$postData['user_name'] = $user['name'];

		if(!isset($user['favorite_groups'])){
			$user['favorite_groups'] = array();
		}

		$user['favorite_groups'][] = $group['_id'];

		$result = HU_dbInsert($postData);

		return HU_dbUpdate($user['_id'],$user);

	}

	function HU_sendTextMessageToGroup($from,$to,$message){

		$postData = array();

		$postData['type'] = "message";
		$postData['message_type'] = "text";
		$postData['body'] = $message;
		$postData['from_user_id'] = $from['_id'];
		$postData['from_user_name'] = $from['name'];
		$postData['created'] = time();
		$postData['modified'] = time();
		$postData['valid'] = true;
		$postData['to_group_name'] = $to['name'];
		$postData['to_group_id'] = $to['_id'];
		$postData['message_target_type'] = 'group';

		return HU_dbInsert($postData);

	}

	function HU_sendNewsMessageToGroup($from,$to,$message,$url){

		$postData = array();

		$postData['type'] = "message";
		$postData['message_type'] = "news";
		$postData['body'] = $message;
		$postData['from_user_id'] = $from['_id'];
		$postData['from_user_name'] = $from['name'];
		$postData['created'] = time();
		$postData['modified'] = time();
		$postData['valid'] = true;
		$postData['to_group_name'] = $to['name'];
		$postData['to_group_id'] = $to['_id'];
		$postData['message_target_type'] = 'group';
		$postData['message_url'] = $url;

		return HU_dbInsert($postData);

	}

	function HU_createGroup($owner,$groupName,$password,$groupCategory,$description,$avatar,$thumbnail){

		$avatarFileId = HU_sendFile($avatar);
		$thumbnailFileId = HU_sendFile($thumbnail);

		$postData = array();

		$postData['type'] = "group";
		$postData['user_id'] = $owner['_id'];
		$postData['description'] = $description;
		$postData['name'] = $groupName;
		$postData['password'] = $password;
		$postData['category_id'] = $groupCategory['_id'];
		$postData['category_name'] = $groupCategory['title'];
		$postData['is_favourite'] = false;

		if(!empty($avatarFileId)){
			$postData['avatar_file_id'] = $avatarFileId;
		}

		if(!empty($thumbnailFileId)){
			$postData['avatar_thumb_file_id'] = $thumbnailFileId;
		}

		return HU_dbInsert($postData);

	}

	function HU_getGroupCategories(){
		return HU_dbFindAll("find_group_categories");
	}
	//--------------------------------------------------------------

?>

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Act. Inst. bot. Univ. Athèn. 1: 38 (1940)

#### Original name
Eutypa lata f. platani Maire

### Remarks
null


text:
title: Config & Registry
teaser: Function registry and configuration system
next: /docs/api-types
---

|                           |                                                                                |
| ------------------------- | ------------------------------------------------------------------------------- |
| [**Config**](#config)     | `Config` class used to load and create INI-style [configs](/docs/usage-config). |
| [**Registry**](#registry) | Function registry for layers, optimizers etc.                                   |

## Config {#config tag="class"}

This class holds the model and training [configuration](/docs/usage-config) and
can load and save the INI-style configuration format from/to a string, file or
bytes. The `Config` class is a subclass of `dict` and uses Python's
`ConfigParser` under the hood.

### Config.\_\_init\_\_ {#config-init tag="method"}

Initialize a new `Config` object with optional data.

```python
### Example
from thinc.api import Config

config = Config({"training": {"patience": 10, "dropout": 0.2}})
```

| Argument          | Type                                             | Description                                                                                |
| ----------------- | ------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data`            | <tt>Optional[Union[Dict[str, Any], Config]]</tt> | Optional data to initialize the config with.                                                                                |
| _keyword-only_    |                                                  |                                                                                |
| `section_order`   | <tt>Optional[List[str]]</tt>                     | Top-level section names, in order, used to sort the saved and loaded config. All other sections will be sorted alphabetically.                              |
| `is_interpolated` | <tt>Optional[bool]</tt>                          | Whether the config is interpolated or whether it contains variables. Read from the `data` if it's an instance of `Config` and otherwise defaults to `True`. |

### Config.from_str {#config-from_str tag="method"}

Load the config from a string.

```python
### Example
from thinc.api import Config

config_str = """
[training]
patience = 10
dropout = 0.2
"""
config = Config().from_str(config_str)
print(config["training"])  # {'patience': 10, 'dropout': 0.2}}
```

| Argument       | Type                    | Description                                                                                |
| -------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `text`         | <tt>str</tt>            | The string config to load.                                                                                |
| _keyword-only_ |                         |                                                                                |
| `interpolate`  | <tt>bool</tt>           | Whether to interpolate variables like `${section.key}`. Defaults to `True`.                                          |
| `overrides`    | <tt>Dict[str, Any]</tt> | Overrides for values and sections. Keys are provided in dot notation, e.g. `"training.dropout"` mapped to the value. |
| **RETURNS**    | <tt>Config</tt>         | The loaded config.                                                                                |

### Config.to_str {#config-to_str tag="method"}

Write the config to a string.

```python
### Example
from thinc.api import Config

config = Config({"training": {"patience": 10, "dropout": 0.2}})
print(config.to_str()) # '[training]\npatience = 10\n\ndropout = 0.2'
```

| Argument      | Type          | Description                                                                 |
| ------------- | ------------- | --------------------------------------------------------------------------- |
| `interpolate` | <tt>bool</tt> | Whether to interpolate variables like `${section.key}`. Defaults to `True`. |
| **RETURNS**   | <tt>str</tt>  | The string config.                                                          |

### Config.to_bytes {#config-to_bytes tag="method"}

Serialize the config to a byte string.

```python
### Example
from thinc.api import Config

config = Config({"training": {"patience": 10, "dropout": 0.2}})
config_bytes = config.to_bytes()
print(config_bytes)  # b'[training]\npatience = 10\n\ndropout = 0.2'
```

| Argument       | Type                    | Description                                                                                |
| -------------- | ----------------------- | -------------------------------------------------------------------------------------------------------------------- |
| _keyword-only_ |                         |                                                                                |
| `interpolate`  | <tt>bool</tt>           | Whether to interpolate variables like `${section.key}`. Defaults to `True`.                                          |
| `overrides`    | <tt>Dict[str, Any]</tt> | Overrides for values and sections. Keys are provided in dot notation, e.g. `"training.dropout"` mapped to the value. |
| **RETURNS**    | <tt>bytes</tt>          | The serialized config.                                                                                |

### Config.from_bytes {#config-from_bytes tag="method"}

Load the config from a byte string.

```python
### Example
from thinc.api import Config

config = Config({"training": {"patience": 10, "dropout": 0.2}})
config_bytes = config.to_bytes()
new_config = Config().from_bytes(config_bytes)
```

| Argument       | Type            | Description                                                                 |
| -------------- | --------------- | --------------------------------------------------------------------------- |
| `bytes_data`   | <tt>bytes</tt>  | The data to load.                                                           |
| _keyword-only_ |                 |                                                                             |
| `interpolate`  | <tt>bool</tt>   | Whether to interpolate variables like `${section.key}`. Defaults to `True`. |
| **RETURNS**    | <tt>Config</tt> | The loaded config.                                                          |

### Config.to_disk {#config-to_disk tag="method"}

Serialize the config to a file.

```python
### Example
from thinc.api import Config

config = Config({"training": {"patience": 10, "dropout": 0.2}})
config.to_disk("./config.cfg")
```

| Argument       | Type                      | Description                                                                 |
| -------------- | ------------------------- | --------------------------------------------------------------------------- |
| `path`         | <tt>Union[Path, str]</tt> | The file path.                                                              |
| _keyword-only_ |                           |                                                                             |
| `interpolate`  | <tt>bool</tt>             | Whether to interpolate variables like `${section.key}`. Defaults to `True`. |

### Config.from_disk {#config-from_disk tag="method"}

Load the config from a file.

```python
### Example
from thinc.api import Config

config = Config({"training": {"patience": 10, "dropout": 0.2}})
config.to_disk("./config.cfg")
new_config = Config().from_disk("./config.cfg")
```

| Argument       | Type                      | Description                                                                                |
| -------------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `path`         | <tt>Union[Path, str]</tt> | The file path.                                                                                |
| _keyword-only_ |                           |                                                                                |
| `interpolate`  | <tt>bool</tt>             | Whether to interpolate variables like `${section.key}`. Defaults to `True`.                                          |
| `overrides`    | <tt>Dict[str, Any]</tt>   | Overrides for values and sections. Keys are provided in dot notation, e.g. `"training.dropout"` mapped to the value. |
| **RETURNS**    | <tt>Config</tt>           | The loaded config.                                                                                |

### Config.copy {#config-copy tag="method"}

Deep-copy the config.

| Argument    | Type            | Description        |
| ----------- | --------------- | ------------------ |
| **RETURNS** | <tt>Config</tt> | The copied config. |

### Config.interpolate {#config-interpolate tag="method"}

Interpolate [variables](/docs/usage-config#config-interpolation) like
`${section.value}` or `${section.subsection}` and return a copy of the config
with interpolated values. Can be used if a config is loaded with
`interpolate=False`, e.g. via [`Config.from_str`](#config-from_str).

```python
### Example
from thinc.api import Config

config_str = """
[hyper_params]
dropout = 0.2

[training]
dropout = ${hyper_params.dropout}
"""
config = Config().from_str(config_str, interpolate=False)
print(config["training"])  # {'dropout': '${hyper_params.dropout}'}}
config = config.interpolate()
print(config["training"])  # {'dropout': 0.2}}
```

| Argument    | Type            | Description                                    |
| ----------- | --------------- | ---------------------------------------------- |
| **RETURNS** | <tt>Config</tt> | A copy of the config with interpolated values. |

### Config.merge {#config-merge tag="method"}

Deep-merge two config objects, using the current config as the default. Only
merges sections and dictionaries and not other values like lists. Values that
are provided in the updates are overwritten in the base config, and any new
values or sections are added. If a config value is a variable like
`${section.key}` (e.g. if the config was loaded with `interpolate=False`), the
**variable is preferred**, even if the updates provide a different value. This
ensures that variable references aren't destroyed by a merge.

<infobox variant="warning">

Note that blocks that refer to
[registered functions](/docs/usage-config#registry) using the `@` syntax are
only merged if they are referring to the same functions. Otherwise, merging
could easily produce invalid configs, since different functions can take
different arguments. If a block refers to a different function, it's
overwritten.

</infobox>

```python
### Example
from thinc.api import Config

base_config_str = """
[training]
patience = 10
dropout = 0.2
"""
update_config_str = """
[training]
dropout = 0.1
max_epochs = 2000
"""

base_config = Config().from_str(base_config_str)
update_config = Config().from_str(update_config_str)
merged = Config(base_config).merge(update_config)
print(merged["training"])  # {'patience': 10, 'dropout': 1.0, 'max_epochs': 2000}
```

| Argument    | Type                                   | Description                                         |
| ----------- | -------------------------------------- | --------------------------------------------------- |
| `updates`   | <tt>Union[Dict[str, Any], Config]</tt> | The updates to merge into the config.               |
| **RETURNS** | <tt>Config</tt>                        | A new config instance containing the merged config. |

### Config Attributes

| Name              | Type          | Description                                                                                |
| ----------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `is_interpolated` | <tt>bool</tt> | Whether the config values have been interpolated. Defaults to `True` and is set to `False` if a config is loaded with `interpolate=False`, e.g. using [`Config.from_str`](#config-from_str). |

---

## Registry {#registry tag="class"}

Thinc's registry system lets you **map string keys to functions**. You can
register functions to create [optimizers](/docs/api-optimizers),
[schedules](/docs/api-schedules), [layers](/docs/api-layers) and more, and then
refer to them and set their arguments in your [config file](/docs/usage-config).
Python type hints are used to validate the inputs.

```python
### Example
import thinc

@thinc.registry.optimizers.register("my_cool_optimizer.v1")
def make_my_optimizer(learn_rate: float, gamma: float):
    return MyCoolOptimizer(learn_rate, gamma)
```

<grid>

```ini
### Valid Config {small="true"}
[optimizer]
@optimizers = "my_cool_optimizer.v1"
learn_rate = 0.001
gamma = 1e-8
```

```ini
### Invalid Config {small="true"}
[optimizer]
@optimizers = "my_cool_optimizer.v1"
learn_rate = 1  # not a float
schedules = null  # unknown argument
```

</grid>

### Attributes {#registry-attributes}

| Registry name  | Description                                                                |
| -------------- | -------------------------------------------------------------------------- |
| `optimizers`   | Registry for functions that create [optimizers](/docs/api-optimizers).     |
| `schedules`    | Registry for functions that create [schedules](/docs/api-schedules).       |
| `layers`       | Registry for functions that create [layers](/docs/api-layers).             |
| `losses`       | Registry for functions that create [losses](/docs/api-loss).               |
| `initializers` | Registry for functions that create [initializers](/docs/api-initializers). |

### registry.get {#registry-get tag="classmethod"}

Get a registered function from a given registry using string names. Will raise
an error if the registry or function doesn't exist. All individual registries
also have a `get` method to get a registered function.

```python
### Example
import thinc

registered_func = thinc.registry.get("optimizers", "my_cool_optimizer.v1")
# The above is the same as:
registered_func = thinc.registry.optimizers.get("my_cool_optimizer.v1")
```

| Argument        | Type              | Description                                    |
| --------------- | ----------------- | ---------------------------------------------- |
| `registry_name` | <tt>str</tt>      | The name of the registry, e.g. `"optimizers"`. |
| `func_name`     | <tt>str</tt>      | The name of the function.                      |
| **RETURNS**     | <tt>Callable</tt> | The registered function.                       |

### registry.create {#registry-create tag="classmethod"}

Create a new function registry that will become available as an attribute to
`registry`. Will raise an error if a registry of the name already exists. Under
the hood, this calls into
[`catalogue.create`](https://github.com/explosion/catalogue#function-cataloguecreate)
using the `"thinc"` namespace.

```python
### Example
import thinc

thinc.registry.create("visualizers")

@thinc.registry.visualizers("my_cool_visualizer.v1")
def my_cool_visualizer(format: str = "jpg") -> "MyCoolVisualizer":
    return MyCoolVisualizer(format)
```

| Argument        | Type          | Description                                                                                |
| --------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `registry_name` | <tt>str</tt>  | The name of the registry to create, e.g. `"visualizers"`.                                                                                |
| `entry_points`  | <tt>bool</tt> | Allow the registry to be populated with entry points advertised by other packages (e.g. via the `"thinc_visualizers"` entry point group). Defaults to `False`. |

<infobox variant="warning">

Registry names can be _any string_ – however, if you want to use your registry
as an attribute of `thinc.registry`, e.g. `@thinc.registry.visualizers`, they
should be valid Python attribute names and only contain alphanumeric characters
and underscores.

</infobox>

### registry.fill {#fill tag="classmethod"}

Unpack a config dictionary, but leave all references to registry functions
intact and don't resolve them. Only use the type annotations and optional base
schema to fill in all arguments and their default values. This method is
especially useful for getting an existing config up to date with changes in the
schema and/or function arguments. If the config is incomplete and contains
missing values for required arguments, you can set `validate=False` to skip
validation and only update it. The updated schema should then pass validation.

If the provided [`Config`](#config) still includes references to variables, e.g.
if it was loaded with `interpolate=False` using a method like
[`Config.from_str`](#config-from_str), a copy of the config is interpolated so
it can be filled, and a filled version with the variables intact is returned.
This means you can auto-fill partial config, without destroying the variables.

```python
### Example
from thinc.api import Config, registry

cfg = Config().from_disk("./my_config.cfg")
filled_cfg = registry.fill(cfg)
```

| Argument       | Type                                   | Description                                                                                |
| -------------- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `config`       | <tt>Union[Config, Dict[str, Any]]</tt> | The config dict to load.                                                                                |
| _keyword-only_ |                                        |                                                                                |
| `validate`     | <tt>bool</tt>                          | Whether to validate the config against a base schema and/or type annotations defined on the registered functions. Defaults to `True`.                                                                                |
| `schema`       | <tt>pydantic.BaseModel</tt>            | Optional [`pydantic` model](https://pydantic-docs.helpmanual.io/usage/models/) to validate the config against. See the docs on [base schemas](/docs/api-config#advanced-types-base-schema) for details. Defaults to an `EmptySchema` with extra properties and arbitrary types allowed. |
| `overrides`    | <tt>Dict[str, Any]</tt>                | Optional overrides for config values. Should be a dictionary keyed by config properties with dot notation, e.g. `{"training.batch_size": 128}`.                                                                                |
| **RETURNS**    | <tt>Config</tt>                        | The filled config.                                                                                |

### registry.resolve {#registry-resolve tag="classmethod"}

Unpack a config dictionary, creating objects from the registry recursively. If a
section contains a key beginning with `@`, the rest of that key will be
interpreted as the name of the registry. For instance,
`"@optimizers": "my_cool_optimizer.v1"` will load the function from the
optimizers registry and pass in the specified arguments. For more details and
examples, see the [docs on Thinc's config system](/docs/usage-config).

```python
### Example
from thinc.api import Config, registry

cfg = Config().from_disk("./my_config.cfg")
resolved = registry.resolve(cfg)
```

| Argument       | Type                                   | Description                                                                                |
| -------------- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `config`       | <tt>Union[Config, Dict[str, Any]]</tt> | The config dict to load.                                                                                |
| _keyword-only_ |                                        |                                                                                |
| `validate`     | <tt>bool</tt>                          | Whether to validate the config against a base schema and/or type annotations defined on the registered functions. Defaults to `True`.                                                                                |
| `schema`       | <tt>pydantic.BaseModel</tt>            | Optional [`pydantic` model](https://pydantic-docs.helpmanual.io/usage/models/) to validate the config against. See the docs on [base schemas](/docs/api-config#advanced-types-base-schema) for details. Defaults to an `EmptySchema` with extra properties and arbitrary types allowed. |
| `overrides`    | <tt>Dict[str, Any]</tt>                | Optional overrides for config values. Should be a dictionary keyed by config properties with dot notation, e.g. `{"training.batch_size": 128}`.                                                                                |
| **RETURNS**    | <tt>Dict[str, Any]</tt>                | The resolved config.                                                                                |


text:
<!DOCTYPE HTML>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta content='width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0'
          name='viewport'/>
    <title>responsiveCarousel Example - 4</title>

    <link type="text/css" rel="stylesheet" href="example.css"/>

Example 4

Infinitely scrolling slide show. Something that might be on a product landing page.

    [ Github ]
    [ Example 1 ]
    [ Example 2 ]
    [ Example 3 ]
    [ Example 4 ]
    [ Example 5 ]

One

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

Toggle Slide Show


text:
<?php
echo "Select an image to be your new user profile image";
?>

<?php
echo 'inner_path($app->user->getProfileImage($app->user->get_user_id())).'" width="235" height="170" />';
?>

<form id="formImageProfile" id="formImageProfile" action="addProfileImage" method="POST" enctype="multipart/form-data">
 	Upload an Image
 	<input type="file" name="file" id="file">

 <button type="submit" name = "submit" value="Submit" style="margin-top:15px;">Submit</button>
</form>


text: export * from '../types/index';


text:
// This file is automatically generated.

package adila.db;

/*
 * Archos alba 10
 *
 * DEVICE: ac101cplv2
 * MODEL: Alba 10"
 */
final class ac101cplv2_alba201022 {
    public static final String DATA = "Archos|alba 10|";
}


text:
#include <ets_sys.h>
#include <osapi.h>
#include <mem.h>
#include <os_type.h>
#include <gpio.h>
#include <user_interface.h>
#include "uart.h"

extern int ets_uart_printf(const char *fmt, ...);

#define INTERVAL 1000 // scan interval in ms
static ETSTimer scan_timer;

static void ICACHE_FLASH_ATTR i2c_scan();

void user_rf_pre_init(void) {}

void ICACHE_FLASH_ATTR init()
{
	// initialise i2c driver
	i2c_init();

	// setup timer to scan every second
	os_timer_disarm(&scan_timer);
	os_timer_setfn(&scan_timer, (os_timer_func_t*)i2c_scan, NULL);
	os_timer_arm(&scan_timer, INTERVAL, 1);
}

void ICACHE_FLASH_ATTR user_init(void)
{
	// initialise system
	gpio_init();
	uart_init(BIT_RATE_115200, BIT_RATE_115200);
	os_delay_us(2000);

	ets_uart_printf("ESP8266 STARTUP\n");

	// setup callback to start program
	system_init_done_cb(init);

}

// Scans all i2c addresses [0,127] and writes a list of responding
// devices to UART
//
static void ICACHE_FLASH_ATTR i2c_scan() {

	ets_uart_printf("i2c Scan \n");
	uint8_t i;
	for (i=1; i<127; i++) {
		i2c_start();
		i2c_writeByte(i << 1);
		if (i2c_check_ack()) {
			ets_uart_printf("Found device at: 0x%2x\n", i);
		}
		i2c_stop();
	}
	ets_uart_printf("done\n");
}


text:
import numpy as np

from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_warns
from sklearn.utils.testing import ignore_warnings
from sklearn.utils.testing import check_skip_travis

from sklearn.linear_model import (orthogonal_mp, orthogonal_mp_gram,
                                  OrthogonalMatchingPursuit,
                                  OrthogonalMatchingPursuitCV,
                                  LinearRegression)
from sklearn.utils import check_random_state
from sklearn.datasets import make_sparse_coded_signal

n_samples, n_features, n_nonzero_coefs, n_targets = 20, 30, 5, 3
y, X, gamma = make_sparse_coded_signal(n_targets, n_features, n_samples,
                                       n_nonzero_coefs, random_state=0)
G, Xy = np.dot(X.T, X), np.dot(X.T, y)
# this makes X (n_samples, n_features)
# and y (n_samples, 3)

def test_correct_shapes():
    assert_equal(orthogonal_mp(X, y[:, 0], n_nonzero_coefs=5).shape,
                 (n_features,))
    assert_equal(orthogonal_mp(X, y, n_nonzero_coefs=5).shape,
                 (n_features, 3))

def test_correct_shapes_gram():
    assert_equal(orthogonal_mp_gram(G, Xy[:, 0], n_nonzero_coefs=5).shape,
                 (n_features,))
    assert_equal(orthogonal_mp_gram(G, Xy, n_nonzero_coefs=5).shape,
                 (n_features, 3))

def test_n_nonzero_coefs():
    assert_true(np.count_nonzero(orthogonal_mp(X, y[:, 0],
                                 n_nonzero_coefs=5)) <= 5)
    assert_true(np.count_nonzero(orthogonal_mp(X, y[:, 0], n_nonzero_coefs=5,
                                               precompute=True)) <= 5)

def test_tol():
    tol = 0.5
    gamma = orthogonal_mp(X, y[:, 0], tol=tol)
    gamma_gram = orthogonal_mp(X, y[:, 0], tol=tol, precompute=True)
    assert_true(np.sum((y[:, 0] - np.dot(X, gamma)) ** 2) <= tol)
    assert_true(np.sum((y[:, 0] - np.dot(X, gamma_gram)) ** 2) <= tol)

def test_with_without_gram():
    assert_array_almost_equal(
        orthogonal_mp(X, y, n_nonzero_coefs=5),
        orthogonal_mp(X, y, n_nonzero_coefs=5, precompute=True))

def test_with_without_gram_tol():
    assert_array_almost_equal(
        orthogonal_mp(X, y, tol=1.),
        orthogonal_mp(X, y, tol=1., precompute=True))

def test_unreachable_accuracy():
    assert_array_almost_equal(
        orthogonal_mp(X, y, tol=0),
        orthogonal_mp(X, y, n_nonzero_coefs=n_features))

    assert_array_almost_equal(
        assert_warns(RuntimeWarning, orthogonal_mp, X, y, tol=0,
                     precompute=True),
        orthogonal_mp(X, y, precompute=True,
                      n_nonzero_coefs=n_features))

def test_bad_input():
    assert_raises(ValueError, orthogonal_mp, X, y, tol=-1)
    assert_raises(ValueError, orthogonal_mp, X, y, n_nonzero_coefs=-1)
    assert_raises(ValueError, orthogonal_mp, X, y,
                  n_nonzero_coefs=n_features + 1)
    assert_raises(ValueError, orthogonal_mp_gram, G, Xy, tol=-1)
    assert_raises(ValueError, orthogonal_mp_gram, G, Xy, n_nonzero_coefs=-1)
    assert_raises(ValueError, orthogonal_mp_gram, G, Xy,
                  n_nonzero_coefs=n_features + 1)

def test_perfect_signal_recovery():
    idx, = gamma[:, 0].nonzero()
    gamma_rec = orthogonal_mp(X, y[:, 0], 5)
    gamma_gram = orthogonal_mp_gram(G, Xy[:, 0], 5)
    assert_array_equal(idx, np.flatnonzero(gamma_rec))
    assert_array_equal(idx, np.flatnonzero(gamma_gram))
    assert_array_almost_equal(gamma[:, 0], gamma_rec, decimal=2)
    assert_array_almost_equal(gamma[:, 0], gamma_gram, decimal=2)

def test_estimator():
    omp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_nonzero_coefs)
    omp.fit(X, y[:, 0])
    assert_equal(omp.coef_.shape, (n_features,))
    assert_equal(omp.intercept_.shape, ())
    assert_true(np.count_nonzero(omp.coef_) <= n_nonzero_coefs)

    omp.fit(X, y)
    assert_equal(omp.coef_.shape, (n_targets, n_features))
    assert_equal(omp.intercept_.shape, (n_targets,))
    assert_true(np.count_nonzero(omp.coef_) <= n_targets * n_nonzero_coefs)

    omp.set_params(fit_intercept=False, normalize=False)

    omp.fit(X, y[:, 0])
    assert_equal(omp.coef_.shape, (n_features,))
    assert_equal(omp.intercept_, 0)
    assert_true(np.count_nonzero(omp.coef_) <= n_nonzero_coefs)

    omp.fit(X, y)
    assert_equal(omp.coef_.shape, (n_targets, n_features))
    assert_equal(omp.intercept_, 0)
    assert_true(np.count_nonzero(omp.coef_) <= n_targets * n_nonzero_coefs)

def test_identical_regressors():
    newX = X.copy()
    newX[:, 1] = newX[:, 0]
    gamma = np.zeros(n_features)
    gamma[0] = gamma[1] = 1.
    newy = np.dot(newX, gamma)
    assert_warns(RuntimeWarning, orthogonal_mp, newX, newy, 2)

def test_swapped_regressors():
    gamma = np.zeros(n_features)
    # X[:, 21] should be selected first, then X[:, 0] selected second,
    # which will take X[:, 21]'s place in case the algorithm does
    # column swapping for optimization (which is the case at the moment)
    gamma[21] = 1.0
    gamma[0] = 0.5
    new_y = np.dot(X, gamma)
    new_Xy = np.dot(X.T, new_y)
    gamma_hat = orthogonal_mp(X, new_y, 2)
    gamma_hat_gram = orthogonal_mp_gram(G, new_Xy, 2)
    assert_array_equal(np.flatnonzero(gamma_hat), [0, 21])
    assert_array_equal(np.flatnonzero(gamma_hat_gram), [0, 21])

def test_no_atoms():
    y_empty = np.zeros_like(y)
    Xy_empty = np.dot(X.T, y_empty)
    gamma_empty = ignore_warnings(orthogonal_mp)(X, y_empty, 1)
    gamma_empty_gram = ignore_warnings(orthogonal_mp)(G, Xy_empty, 1)
    assert_equal(np.all(gamma_empty == 0), True)
    assert_equal(np.all(gamma_empty_gram == 0), True)

def test_omp_path():
    path = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=True)
    last = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=False)
    assert_equal(path.shape, (n_features, n_targets, 5))
    assert_array_almost_equal(path[:, :, -1], last)
    path = orthogonal_mp_gram(G, Xy, n_nonzero_coefs=5, return_path=True)
    last = orthogonal_mp_gram(G, Xy, n_nonzero_coefs=5, return_path=False)
    assert_equal(path.shape, (n_features, n_targets, 5))
    assert_array_almost_equal(path[:, :, -1], last)

def test_omp_cv():
    # FIXME: This test is unstable on Travis, see issue #3190 for more detail.
    check_skip_travis()
    y_ = y[:, 0]
    gamma_ = gamma[:, 0]
    ompcv = OrthogonalMatchingPursuitCV(normalize=True, fit_intercept=False,
                                        max_iter=10, cv=5)
    ompcv.fit(X, y_)
    assert_equal(ompcv.n_nonzero_coefs_, n_nonzero_coefs)
    assert_array_almost_equal(ompcv.coef_, gamma_)
    omp = OrthogonalMatchingPursuit(normalize=True, fit_intercept=False,
                                    n_nonzero_coefs=ompcv.n_nonzero_coefs_)
    omp.fit(X, y_)
    assert_array_almost_equal(ompcv.coef_, omp.coef_)

def test_omp_reaches_least_squares():
    # Use small simple data; it's a sanity check but OMP can stop early
    rng = check_random_state(0)
    n_samples, n_features = (10, 8)
    n_targets = 3
    X = rng.randn(n_samples, n_features)
    Y = rng.randn(n_samples, n_targets)
    omp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_features)
    lstsq = LinearRegression()
    omp.fit(X, Y)
    lstsq.fit(X, Y)
    assert_array_almost_equal(omp.coef_, lstsq.coef_)


text:
export function expectToFail(fn: () => Promise<any>, errorMessage?: string): Promise<void> {
  return fn()
    .then(() => {
      const functionSource = fn.name || (<any>fn).source || fn.toString();
      const errorDetails = errorMessage ? `\n\tDetails:\n\t${errorMessage}` : '';
      throw new Error(
        `Function ${functionSource} was expected to fail, but succeeded.${errorDetails}`);
    }, () => { });
}

export function wait(msecs: number) {
  return new Promise((resolve) => {
    setTimeout(resolve, msecs);
  });
}


text:
			Text
			(selection)

			{{stat.value}} {{stat.name}}

			HTML
			(selection)

			{{stat.value}} {{stat.name}}


text:
#include <grpc/support/port_platform.h>

#include "src/core/tsi/alts/handshaker/alts_tsi_handshaker.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/sync.h>
#include <grpc/support/thd_id.h>

#include "src/core/lib/gpr/host_port.h"
#include "src/core/lib/gprpp/thd.h"
#include "src/core/tsi/alts/frame_protector/alts_frame_protector.h"
#include "src/core/tsi/alts/handshaker/alts_handshaker_client.h"
#include "src/core/tsi/alts/handshaker/alts_tsi_utils.h"
#include "src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.h"
#include "src/core/tsi/alts_transport_security.h"

#define TSI_ALTS_INITIAL_BUFFER_SIZE 256

static alts_shared_resource* kSharedResource = alts_get_shared_resource();

/* Main struct for ALTS TSI handshaker. */
typedef struct alts_tsi_handshaker {
  tsi_handshaker base;
  alts_handshaker_client* client;
  grpc_slice recv_bytes;
  grpc_slice target_name;
  unsigned char* buffer;
  size_t buffer_size;
  bool is_client;
  bool has_sent_start_message;
  grpc_alts_credentials_options* options;
} alts_tsi_handshaker;

/* Main struct for ALTS TSI handshaker result. */
typedef struct alts_tsi_handshaker_result {
  tsi_handshaker_result base;
  char* peer_identity;
  char* key_data;
  unsigned char* unused_bytes;
  size_t unused_bytes_size;
  grpc_slice rpc_versions;
  bool is_client;
} alts_tsi_handshaker_result;

static tsi_result handshaker_result_extract_peer(
    const tsi_handshaker_result* self, tsi_peer* peer) {
  if (self == nullptr || peer == nullptr) {
    gpr_log(GPR_ERROR, "Invalid argument to handshaker_result_extract_peer()");
    return TSI_INVALID_ARGUMENT;
  }
  alts_tsi_handshaker_result* result =
      reinterpret_cast<alts_tsi_handshaker_result*>(
          const_cast<tsi_handshaker_result*>(self));
  GPR_ASSERT(kTsiAltsNumOfPeerProperties == 3);
  tsi_result ok = tsi_construct_peer(kTsiAltsNumOfPeerProperties, peer);
  int index = 0;
  if (ok != TSI_OK) {
    gpr_log(GPR_ERROR, "Failed to construct tsi peer");
    return ok;
  }
  GPR_ASSERT(&peer->properties[index] != nullptr);
  ok = tsi_construct_string_peer_property_from_cstring(
      TSI_CERTIFICATE_TYPE_PEER_PROPERTY, TSI_ALTS_CERTIFICATE_TYPE,
      &peer->properties[index]);
  if (ok != TSI_OK) {
    tsi_peer_destruct(peer);
    gpr_log(GPR_ERROR, "Failed to set tsi peer property");
    return ok;
  }
  index++;
  GPR_ASSERT(&peer->properties[index] != nullptr);
  ok = tsi_construct_string_peer_property_from_cstring(
      TSI_ALTS_SERVICE_ACCOUNT_PEER_PROPERTY, result->peer_identity,
      &peer->properties[index]);
  if (ok != TSI_OK) {
    tsi_peer_destruct(peer);
    gpr_log(GPR_ERROR, "Failed to set tsi peer property");
  }
  index++;
  GPR_ASSERT(&peer->properties[index] != nullptr);
  ok = tsi_construct_string_peer_property(
      TSI_ALTS_RPC_VERSIONS,
      reinterpret_cast<char*>(GRPC_SLICE_START_PTR(result->rpc_versions)),
      GRPC_SLICE_LENGTH(result->rpc_versions), &peer->properties[2]);
  if (ok != TSI_OK) {
    tsi_peer_destruct(peer);
    gpr_log(GPR_ERROR, "Failed to set tsi peer property");
  }
  GPR_ASSERT(++index == kTsiAltsNumOfPeerProperties);
  return ok;
}

static tsi_result handshaker_result_create_zero_copy_grpc_protector(
    const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
    tsi_zero_copy_grpc_protector** protector) {
  if (self == nullptr || protector == nullptr) {
    gpr_log(GPR_ERROR,
            "Invalid arguments to create_zero_copy_grpc_protector()");
    return TSI_INVALID_ARGUMENT;
  }
  alts_tsi_handshaker_result* result =
      reinterpret_cast<alts_tsi_handshaker_result*>(
          const_cast<tsi_handshaker_result*>(self));
  tsi_result ok = alts_zero_copy_grpc_protector_create(
      reinterpret_cast<const uint8_t*>(result->key_data),
      kAltsAes128GcmRekeyKeyLength, /*is_rekey=*/true, result->is_client,
      /*is_integrity_only=*/false, /*enable_extra_copy=*/false,
      max_output_protected_frame_size, protector);
  if (ok != TSI_OK) {
    gpr_log(GPR_ERROR, "Failed to create zero-copy grpc protector");
  }
  return ok;
}

static tsi_result handshaker_result_create_frame_protector(
    const tsi_handshaker_result* self, size_t* max_output_protected_frame_size,
    tsi_frame_protector** protector) {
  if (self == nullptr || protector == nullptr) {
    gpr_log(GPR_ERROR,
            "Invalid arguments to handshaker_result_create_frame_protector()");
    return TSI_INVALID_ARGUMENT;
  }
  alts_tsi_handshaker_result* result =
      reinterpret_cast<alts_tsi_handshaker_result*>(
          const_cast<tsi_handshaker_result*>(self));
  tsi_result ok = alts_create_frame_protector(
      reinterpret_cast<const uint8_t*>(result->key_data),
      kAltsAes128GcmRekeyKeyLength, result->is_client, /*is_rekey=*/true,
      max_output_protected_frame_size, protector);
  if (ok != TSI_OK) {
    gpr_log(GPR_ERROR, "Failed to create frame protector");
  }
  return ok;
}

static tsi_result handshaker_result_get_unused_bytes(
    const tsi_handshaker_result* self, const unsigned char** bytes,
    size_t* bytes_size) {
  if (self == nullptr || bytes == nullptr || bytes_size == nullptr) {
    gpr_log(GPR_ERROR,
            "Invalid arguments to handshaker_result_get_unused_bytes()");
    return TSI_INVALID_ARGUMENT;
  }
  alts_tsi_handshaker_result* result =
      reinterpret_cast<alts_tsi_handshaker_result*>(
          const_cast<tsi_handshaker_result*>(self));
  *bytes = result->unused_bytes;
  *bytes_size = result->unused_bytes_size;
  return TSI_OK;
}

static void handshaker_result_destroy(tsi_handshaker_result* self) {
  if (self == nullptr) {
    return;
  }
  alts_tsi_handshaker_result* result =
      reinterpret_cast<alts_tsi_handshaker_result*>(
          const_cast<tsi_handshaker_result*>(self));
  gpr_free(result->peer_identity);
  gpr_free(result->key_data);
  gpr_free(result->unused_bytes);
  grpc_slice_unref(result->rpc_versions);
  gpr_free(result);
}

static const tsi_handshaker_result_vtable result_vtable = {
    handshaker_result_extract_peer,
    handshaker_result_create_zero_copy_grpc_protector,
    handshaker_result_create_frame_protector,
    handshaker_result_get_unused_bytes, handshaker_result_destroy};

static tsi_result create_handshaker_result(grpc_gcp_handshaker_resp* resp,
                                           bool is_client,
                                           tsi_handshaker_result** self) {
  if (self == nullptr || resp == nullptr) {
    gpr_log(GPR_ERROR, "Invalid arguments to create_handshaker_result()");
    return TSI_INVALID_ARGUMENT;
  }
  grpc_slice* key = static_cast<grpc_slice*>(resp->result.key_data.arg);
  GPR_ASSERT(key != nullptr);
  grpc_slice* identity =
      static_cast<grpc_slice*>(resp->result.peer_identity.service_account.arg);
  if (identity == nullptr) {
    gpr_log(GPR_ERROR, "Invalid service account");
    return TSI_FAILED_PRECONDITION;
  }
  if (GRPC_SLICE_LENGTH(*key) < kAltsAes128GcmRekeyKeyLength) {
    gpr_log(GPR_ERROR, "Bad key length");
    return TSI_FAILED_PRECONDITION;
  }
  alts_tsi_handshaker_result* result =
      static_cast<alts_tsi_handshaker_result*>(gpr_zalloc(sizeof(*result)));
  result->key_data =
      static_cast<char*>(gpr_zalloc(kAltsAes128GcmRekeyKeyLength));
  memcpy(result->key_data, GRPC_SLICE_START_PTR(*key),
         kAltsAes128GcmRekeyKeyLength);
  result->peer_identity = grpc_slice_to_c_string(*identity);
  if (!resp->result.has_peer_rpc_versions) {
    gpr_log(GPR_ERROR, "Peer does not set RPC protocol versions.");
    return TSI_FAILED_PRECONDITION;
  }
  if (!grpc_gcp_rpc_protocol_versions_encode(&resp->result.peer_rpc_versions,
                                             &result->rpc_versions)) {
    gpr_log(GPR_ERROR, "Failed to serialize peer's RPC protocol versions.");
    return TSI_FAILED_PRECONDITION;
  }
  result->is_client = is_client;
  result->base.vtable = &result_vtable;
  *self = &result->base;
  return TSI_OK;
}

static tsi_result handshaker_next(
    tsi_handshaker* self, const unsigned char* received_bytes,
    size_t received_bytes_size, const unsigned char** bytes_to_send,
    size_t* bytes_to_send_size, tsi_handshaker_result** result,
    tsi_handshaker_on_next_done_cb cb, void* user_data) {
  if (self == nullptr || cb == nullptr) {
    gpr_log(GPR_ERROR, "Invalid arguments to handshaker_next()");
    return TSI_INVALID_ARGUMENT;
  }
  if (self->handshake_shutdown) {
    gpr_log(GPR_ERROR, "TSI handshake shutdown");
    return TSI_HANDSHAKE_SHUTDOWN;
  }
  alts_tsi_handshaker* handshaker =
      reinterpret_cast<alts_tsi_handshaker*>(self);
  tsi_result ok = TSI_OK;
  alts_tsi_event* event = nullptr;
  ok = alts_tsi_event_create(handshaker, cb, user_data, handshaker->options,
                             handshaker->target_name, &event);
  if (ok != TSI_OK) {
    gpr_log(GPR_ERROR, "Failed to create ALTS TSI event");
    return ok;
  }
  grpc_slice slice = (received_bytes == nullptr || received_bytes_size == 0)
                         ? grpc_empty_slice()
                         : grpc_slice_from_copied_buffer(
                               reinterpret_cast<const char*>(received_bytes),
                               received_bytes_size);
  if (!handshaker->has_sent_start_message) {
    ok = handshaker->is_client
             ? alts_handshaker_client_start_client(handshaker->client, event)
             : alts_handshaker_client_start_server(handshaker->client, event,
                                                   &slice);
    handshaker->has_sent_start_message = true;
  } else {
    if (!GRPC_SLICE_IS_EMPTY(handshaker->recv_bytes)) {
      grpc_slice_unref(handshaker->recv_bytes);
    }
    handshaker->recv_bytes = grpc_slice_ref(slice);
    ok = alts_handshaker_client_next(handshaker->client, event, &slice);
  }
  grpc_slice_unref(slice);
  if (ok != TSI_OK) {
    gpr_log(GPR_ERROR, "Failed to schedule ALTS handshaker requests");
    return ok;
  }
  return TSI_ASYNC;
}

static void handshaker_shutdown(tsi_handshaker* self) {
  GPR_ASSERT(self != nullptr);
  if (self->handshake_shutdown) {
    return;
  }
  alts_tsi_handshaker* handshaker =
      reinterpret_cast<alts_tsi_handshaker*>(self);
  alts_handshaker_client_shutdown(handshaker->client);
}

static void handshaker_destroy(tsi_handshaker* self) {
  if (self == nullptr) {
    return;
  }
  alts_tsi_handshaker* handshaker =
      reinterpret_cast<alts_tsi_handshaker*>(self);
  alts_handshaker_client_destroy(handshaker->client);
  grpc_slice_unref(handshaker->recv_bytes);
  grpc_slice_unref(handshaker->target_name);
  grpc_alts_credentials_options_destroy(handshaker->options);
  gpr_free(handshaker->buffer);
  gpr_free(handshaker);
}

static const tsi_handshaker_vtable handshaker_vtable = {
    nullptr,         nullptr,
    nullptr,         nullptr,
    nullptr,         handshaker_destroy,
    handshaker_next, handshaker_shutdown};

static void thread_worker(void* arg) {
  while (true) {
    grpc_event event = grpc_completion_queue_next(
        kSharedResource->cq, gpr_inf_future(GPR_CLOCK_REALTIME), nullptr);
    GPR_ASSERT(event.type != GRPC_QUEUE_TIMEOUT);
    if (event.type == GRPC_QUEUE_SHUTDOWN) {
      /* signal alts_tsi_shutdown() to destroy completion queue. */
      grpc_tsi_alts_signal_for_cq_destroy();
      break;
    }
    /* event.type == GRPC_OP_COMPLETE. */
    alts_tsi_event* alts_event = static_cast<alts_tsi_event*>(event.tag);
    alts_tsi_event_dispatch_to_handshaker(alts_event, event.success);
    alts_tsi_event_destroy(alts_event);
  }
}

static void init_shared_resources(const char* handshaker_service_url) {
  GPR_ASSERT(handshaker_service_url != nullptr);
  gpr_mu_lock(&kSharedResource->mu);
  if (kSharedResource->channel == nullptr) {
    gpr_cv_init(&kSharedResource->cv);
    kSharedResource->channel =
        grpc_insecure_channel_create(handshaker_service_url, nullptr, nullptr);
    kSharedResource->cq = grpc_completion_queue_create_for_next(nullptr);
    kSharedResource->thread =
        grpc_core::Thread("alts_tsi_handshaker", &thread_worker, nullptr);
    kSharedResource->thread.Start();
  }
  gpr_mu_unlock(&kSharedResource->mu);
}

tsi_result alts_tsi_handshaker_create(
    const grpc_alts_credentials_options* options, const char* target_name,
    const char* handshaker_service_url, bool is_client, tsi_handshaker** self) {
  if (handshaker_service_url == nullptr || self == nullptr ||
      options == nullptr || (is_client && target_name == nullptr)) {
    gpr_log(GPR_ERROR, "Invalid arguments to alts_tsi_handshaker_create()");
    return TSI_INVALID_ARGUMENT;
  }
  init_shared_resources(handshaker_service_url);
  alts_handshaker_client* client = alts_grpc_handshaker_client_create(
      kSharedResource->channel, kSharedResource->cq, handshaker_service_url);
  if (client == nullptr) {
    gpr_log(GPR_ERROR, "Failed to create ALTS handshaker client");
    return TSI_FAILED_PRECONDITION;
  }
  alts_tsi_handshaker* handshaker =
      static_cast<alts_tsi_handshaker*>(gpr_zalloc(sizeof(*handshaker)));
  handshaker->client = client;
  handshaker->buffer_size = TSI_ALTS_INITIAL_BUFFER_SIZE;
  handshaker->buffer =
      static_cast<unsigned char*>(gpr_zalloc(handshaker->buffer_size));
  handshaker->is_client = is_client;
  handshaker->has_sent_start_message = false;
  handshaker->target_name = target_name == nullptr
                                ? grpc_empty_slice()
                                : grpc_slice_from_static_string(target_name);
  handshaker->options = grpc_alts_credentials_options_copy(options);
  handshaker->base.vtable = &handshaker_vtable;
  *self = &handshaker->base;
  return TSI_OK;
}

static bool is_handshake_finished_properly(grpc_gcp_handshaker_resp* resp) {
  GPR_ASSERT(resp != nullptr);
  if (resp->has_result) {
    return true;
  }
  return false;
}

static void set_unused_bytes(tsi_handshaker_result* self,
                             grpc_slice* recv_bytes, size_t bytes_consumed) {
  GPR_ASSERT(recv_bytes != nullptr && self != nullptr);
  if (GRPC_SLICE_LENGTH(*recv_bytes) == bytes_consumed) {
    return;
  }
  alts_tsi_handshaker_result* result =
      reinterpret_cast<alts_tsi_handshaker_result*>(self);
  result->unused_bytes_size = GRPC_SLICE_LENGTH(*recv_bytes) - bytes_consumed;
  result->unused_bytes =
      static_cast<unsigned char*>(gpr_zalloc(result->unused_bytes_size));
  memcpy(result->unused_bytes,
         GRPC_SLICE_START_PTR(*recv_bytes) + bytes_consumed,
         result->unused_bytes_size);
}

void alts_tsi_handshaker_handle_response(alts_tsi_handshaker* handshaker,
                                         grpc_byte_buffer* recv_buffer,
                                         grpc_status_code status,
                                         grpc_slice* details,
                                         tsi_handshaker_on_next_done_cb cb,
                                         void* user_data, bool is_ok) {
  /* Invalid input check. */
  if (cb == nullptr) {
    gpr_log(GPR_ERROR,
            "cb is nullptr in alts_tsi_handshaker_handle_response()");
    return;
  }
  if (handshaker == nullptr || recv_buffer == nullptr) {
    gpr_log(GPR_ERROR,
            "Invalid arguments to alts_tsi_handshaker_handle_response()");
    cb(TSI_INTERNAL_ERROR, user_data, nullptr, 0, nullptr);
    return;
  }
  if (handshaker->base.handshake_shutdown) {
    gpr_log(GPR_ERROR, "TSI handshake shutdown");
    cb(TSI_HANDSHAKE_SHUTDOWN, user_data, nullptr, 0, nullptr);
    return;
  }
  /* Failed grpc call check. */
  if (!is_ok || status != GRPC_STATUS_OK) {
    gpr_log(GPR_ERROR, "grpc call made to handshaker service failed");
    if (details != nullptr) {
      char* error_details = grpc_slice_to_c_string(*details);
      gpr_log(GPR_ERROR, "error details:%s", error_details);
      gpr_free(error_details);
    }
    cb(TSI_INTERNAL_ERROR, user_data, nullptr, 0, nullptr);
    return;
  }
  grpc_gcp_handshaker_resp* resp =
      alts_tsi_utils_deserialize_response(recv_buffer);
  /* Invalid handshaker response check. */
  if (resp == nullptr) {
    gpr_log(GPR_ERROR, "alts_tsi_utils_deserialize_response() failed");
    cb(TSI_DATA_CORRUPTED, user_data, nullptr, 0, nullptr);
    return;
  }
  grpc_slice* slice = static_cast<grpc_slice*>(resp->out_frames.arg);
  unsigned char* bytes_to_send = nullptr;
  size_t bytes_to_send_size = 0;
  if (slice != nullptr) {
    bytes_to_send_size = GRPC_SLICE_LENGTH(*slice);
    while (bytes_to_send_size > handshaker->buffer_size) {
      handshaker->buffer_size *= 2;
      handshaker->buffer = static_cast<unsigned char*>(
          gpr_realloc(handshaker->buffer, handshaker->buffer_size));
    }
    memcpy(handshaker->buffer, GRPC_SLICE_START_PTR(*slice),
           bytes_to_send_size);
    bytes_to_send = handshaker->buffer;
  }
  tsi_handshaker_result* result = nullptr;
  if (is_handshake_finished_properly(resp)) {
    create_handshaker_result(resp, handshaker->is_client, &result);
    set_unused_bytes(result, &handshaker->recv_bytes, resp->bytes_consumed);
  }
  grpc_status_code code = static_cast<grpc_status_code>(resp->status.code);
  grpc_gcp_handshaker_resp_destroy(resp);
  cb(alts_tsi_utils_convert_to_tsi_result(code), user_data, bytes_to_send,
     bytes_to_send_size, result);
}

namespace grpc_core {
namespace internal {

bool alts_tsi_handshaker_get_has_sent_start_message_for_testing(
    alts_tsi_handshaker* handshaker) {
  GPR_ASSERT(handshaker != nullptr);
  return handshaker->has_sent_start_message;
}

bool alts_tsi_handshaker_get_is_client_for_testing(
    alts_tsi_handshaker* handshaker) {
  GPR_ASSERT(handshaker != nullptr);
  return handshaker->is_client;
}

void alts_tsi_handshaker_set_recv_bytes_for_testing(
    alts_tsi_handshaker* handshaker, grpc_slice* slice) {
  GPR_ASSERT(handshaker != nullptr && slice != nullptr);
  handshaker->recv_bytes = grpc_slice_ref(*slice);
}

grpc_slice alts_tsi_handshaker_get_recv_bytes_for_testing(
    alts_tsi_handshaker* handshaker) {
  GPR_ASSERT(handshaker != nullptr);
  return handshaker->recv_bytes;
}

void alts_tsi_handshaker_set_client_for_testing(
    alts_tsi_handshaker* handshaker, alts_handshaker_client* client) {
  GPR_ASSERT(handshaker != nullptr && client != nullptr);
  alts_handshaker_client_destroy(handshaker->client);
  handshaker->client = client;
}

alts_handshaker_client* alts_tsi_handshaker_get_client_for_testing(
    alts_tsi_handshaker* handshaker) {
  return handshaker->client;
}

}  // namespace internal
}  // namespace grpc_core


text:
<resources>
    <string name="app_name">ModelViewRecyclerViewDemo</string>
    <string name="action_settings">Settings</string>

</resources>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycol. Writ. 7: 1231 (1923)

#### Original name
Polyporus elongatus Berk., 1842

### Remarks
null


text:
package com.google.template.soy.basicfunctions;

import com.google.template.soy.data.SoyValue;
import com.google.template.soy.plugin.java.restricted.JavaPluginContext;
import com.google.template.soy.plugin.java.restricted.JavaValue;
import com.google.template.soy.plugin.java.restricted.JavaValueFactory;
import com.google.template.soy.plugin.java.restricted.SoyJavaSourceFunction;
import com.google.template.soy.plugin.javascript.restricted.JavaScriptPluginContext;
import com.google.template.soy.plugin.javascript.restricted.JavaScriptValue;
import com.google.template.soy.plugin.javascript.restricted.JavaScriptValueFactory;
import com.google.template.soy.plugin.javascript.restricted.SoyJavaScriptSourceFunction;
import com.google.template.soy.plugin.python.restricted.PythonPluginContext;
import com.google.template.soy.plugin.python.restricted.PythonValue;
import com.google.template.soy.plugin.python.restricted.PythonValueFactory;
import com.google.template.soy.plugin.python.restricted.SoyPythonSourceFunction;
import com.google.template.soy.shared.restricted.Signature;
import com.google.template.soy.shared.restricted.SoyMethodSignature;
import com.google.template.soy.shared.restricted.SoyPureFunction;
import java.lang.reflect.Method;
import java.util.List;

/**
 * A function that determines the length of a string.
 *
 *
strLen(expr1) requires expr1 to be of type string or {@link
 * com.google.template.soy.data.SanitizedContent}.
 *
 *
TODO(lukes,dcphillips): This function has inconsistent behavior between the backends when it
 * comes to astral plane codepoints. Python is the only backend doing it right.
 */
@SoyMethodSignature(name = "length", baseType = "string", value = @Signature(returnType = "int"))
@SoyPureFunction
final class StrLenFunction
    implements SoyJavaSourceFunction, SoyJavaScriptSourceFunction, SoyPythonSourceFunction {

  @Override
  public JavaScriptValue applyForJavaScriptSource(
      JavaScriptValueFactory factory, List<JavaScriptValue> args, JavaScriptPluginContext context) {
    return args.get(0).coerceToString().accessProperty("length");
  }

  @Override
  public PythonValue applyForPythonSource(
      PythonValueFactory factory, List<PythonValue> args, PythonPluginContext context) {
    return factory.global("len").call(args.get(0));
  }

  // lazy singleton pattern, allows other backends to avoid the work.
  private static final class Methods {
    static final Method STR_LEN =
        JavaValueFactory.createMethod(BasicFunctionsRuntime.class, "strLen", SoyValue.class);
  }

  @Override
  public JavaValue applyForJavaSource(
      JavaValueFactory factory, List<JavaValue> args, JavaPluginContext context) {
    return factory.callStaticMethod(Methods.STR_LEN, args.get(0));
  }
}


text:
Todos.EditTodoView = Ember.TextField.extend({
    didInsertElement: function(){
        this.$().focus();
    }
});

// Regester newly created view with handlebars
Ember.Handlebars.helper('edit-todo', Todos.EditTodoView);


text:
DROP TABLE IF EXISTS users;

CREATE TABLE users (
  id INTEGER PRIMARY KEY,
  fname VARCHAR(255) NOT NULL,
  lname VARCHAR(255) NOT NULL
);

DROP TABLE IF EXISTS questions;

CREATE TABLE questions (
  id INTEGER PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  body TEXT NOT NULL,
  user_id INTEGER NOT NULL
);

DROP TABLE IF EXISTS question_follows;

CREATE TABLE questions_follows (
  id INTEGER PRIMARY KEY,
  user_id INTEGER NOT NULL,
  question_id INTEGER NOT NULL
);

DROP TABLE IF EXISTS replies;

CREATE TABLE replies (
  id INTEGER PRIMARY KEY,
  question_id INTEGER NOT NULL,
  parent_id INTEGER,
  user_id INTEGER NOT NULL,
  body TEXT NOT NULL
);

DROP TABLE IF EXISTS question_likes;

CREATE TABLE question_likes (
  id INTEGER PRIMARY KEY,
  user_id INTEGER NOT NULL,
  question_id INTEGER NOT NULL
);

INSERT INTO
  users (fname, lname)
VALUES
    ('John', 'Smith'),
    ('Andrew', 'Liu'),
    ('Akansh', 'Murthy');


text:
require "spec_helper"

describe Thor::ZshCompletion::Generator do
  let(:thor) {
    nest2 = Class.new(Thor) do
      desc "baz", "Description of baz"
      def baz
        p options
        puts "baz"
      end
      map "ben" => "baz"
    end

    nest1 = Class.new(Thor) do
      desc "bar", "Description of bar"
      def bar
        p options
        puts "bar"
      end

      desc "nest2", "Description of nest2"
      subcommand "nest2", nest2
    end

    Class.new(Thor) do
      class_option :global, desc: "Global option"

      desc "foo", "Description of foo"
      option :verbose, aliases: :v, desc: "Write more logs"
      def foo
        p options
        puts "foo"
      end

      desc "nest1", "Description of nest1"
      subcommand "nest1", nest1
    end
  }

  let(:expected) { File.read("#{File.dirname(__FILE__)}/generator_spec.zsh") }

  subject { Thor::ZshCompletion::Generator.new(thor, "generator_spec").generate }

  it { should eq expected }
end


text:
package com.yohomall.dao;

import java.util.List;

import org.apache.ibatis.annotations.Insert;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.core.annotation.Order;

import com.yohomall.pojo.Orderitem;
import com.yohomall.pojo.Orders;
import com.yohomall.pojo.OrdersVo;
import com.yohomall.pojo.Product;

public interface OrdersMapper {

	Integer getAdminTotalRecord(@Param(value="status")Integer status);

	List<Orders> findAllOrder(@Param(value="status")Integer status, @Param("StartIndex")Integer StartIndex,
			@Param("pageSize")Integer pageSize);

	@Insert("insert into Orders(uid,addr,aname,phone,total,time,status) values(#{uid},#{addr},#{aname},#{phone},#{total},#{time},#{status})")
	int add(Orders order);

	@Insert("insert into orders(oid,uid,addr,aname,phone,total,time,status) values(#{oid},#{user.uid},#{addr},#{aname},#{phone},#{total},#{time},#{status})")
	void save(Orders order);

	@Insert("insert into orderitem(itemid,pid,oid,quantity,subtotal) values(#{itemid},#{product.pid},#{order.oid},#{quantity},#{subtotal})")
	void saveOrderItem(Orderitem orderitem);

	int getTotalRecord(@Param(value="uid") Integer uid);

	List<Orders> getMyOrdersByPage(@Param("uid") Integer uid,@Param("StartIndex")Integer StartIndex,
			@Param("pageSize")Integer pageSize);

	List<OrdersVo> getMyOrderItem(@Param("oid") String oid);

	Orders getByID(@Param("oid") String oid);

	@Update("update orders set addr=#{addr},aname=#{aname},phone=#{phone},status=#{status} where oid=#{oid}")
	void update(Orders order);

	List<Orders> findOrderDetails();

}


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

<TITLE>
All Classes (RabbIT/4)
</TITLE>

<META NAME="date" CONTENT="2012-02-16">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

All Classes

AccessFilter

Address

AdFilter

AsyncListener

Authenticator

AuthUserInfo

BackgroundFilter

BadHttpHeaderException

Base64

BaseHandler

BaseMetaHandler

BaseMetaHandler.PageCompletion

BaseSocketHandler

BlinkFilter

BlockFilter

BlockListener

BlockSender

BlockSentListener

BodyFilter

BoundBinder

BufferHandle

Cache

CacheBufferHandle

CacheConfiguration

CacheConfigurationBase

CacheEntry

CacheException

CacheResourceSource

CacheStatus

CacheUtils

ChunkDataFeeder

ChunkEnder

ChunkHandler

ClearCache

ClientBase

ClientListener

ClientListenerAdapter

ClientResourceHandler

ClientResourceListener

ClientResourceTransferredListener

ClientTrafficLogger

Config

Connection

Connection

ConnectionHandler

ConnectionId

ConnectionLogger

Connections

ContentRangeParser

Counter

CountingClientBaseStopper

DataSourceHelper

DefaultBinder

DNSHandler

DNSJavaHandler

DNSSunHandler

DontCacheFilter

DontFilterFilter

ETagUtils

ExternalProcessConverter

FileHandler

FileHelper

FileResourceSource

FileSaver

FileSender

FileTemplateHttpGeneratorFactory

FilterHandler

GeneralHeader

GZipHandler

GZipListener

GZipPacker

GZipPackListener

GZipUnpacker

GZipUnpackListener

Handler

HandlerFactory

Head

Header

HeadResponseListener

HierContext

HtmlBlock

HtmlEscapeUtils

HtmlFilter

HtmlFilterFactory

HtmlPage

HtmlParseException

HtmlParser

HttpBaseFilter

HttpDateParser

HttpFilter

HttpGenerator

HttpGeneratorFactory

HttpHeader

HttpHeaderFileHandler

HttpHeaderListener

HttpHeaderParser

HttpHeaderReader

HttpHeaderSender

HttpHeaderSentListener

HttpHeaderWithContent

HttpProxy

HttpResponseListener

HttpResponseReader

HttpSnoop

ImageConverter

ImageHandler

InetAddressListener

InitCtxFactory

InOutProxyChain

InOutProxyChainFactory

IPAccess

IPAccessFilter

JavaImageConverter

Kill

LineListener

LineReader

LogHeadToSystemOut

LowresImageFilter

MetaHandler

MimeTypeMapper

MultiPartHandler

MultipartHeader

MultiPartPipe

NCache

NoGZipEncoding

PartialCacher

PatternHelper

PlainFileAuthenticator

ProxiedProxyChain

ProxyAuth

ProxyChain

ProxyChainFactory

ProxyConnectionAcceptor

ProxyLogger

ProxyResolver

ProxyStarter

RandomCacheResourceSource

Range

RequestLineTooLongException

Resolver

ResolvRunner

ResourceLoader

ResourceSource

RevalidateFilter

ReverseProxy

SCC

SelectorStatus

SetHeaderFilter

SimpleBufferHandle

SimpleProxyChain

SimpleResolver

SimpleTagFilter

SimpleTrafficLogger

SimpleUserHandler

SimpleWebServer

SocketAccessController

SocketBinder

SProperties

SQLAuthenticator

SQLBlockFilter

SSLHandler

StackTrace

StackTraceUtil

StandardHttpGeneratorFactory

StandardOutTrafficLogger

Status

StatusCode

Storable

StringCache

SWC

Tag

Tag.Pair

TagType

TaskTimings

TestHttpHeaderReader

Token

TokenType

TrafficLogger

TrafficLoggerHandler

Transferable

TransferHandler

TransferListener

Tunnel

WebConnection

WebConnectionListener

WebConnectionResourceSource

WGet


text:
(function ($) {
    $(function () {

        $('.button-collapse').sideNav();

        $('.parallax').parallax();

        $('.slider').slider();

        $('.carousel.carousel-slider').carousel({
            fullWidth: true
        });

        //la bare de recherche annimation d'apparition
        $(".search").click(function () {
            if ($(this).text() == "search") {
                $(this).text("close")
            } else {
                $(this).text("search")
            }
            $(".grey").slideToggle(255)
        });

        //annimation dropdown du nav
        $('.dropdown-button').dropdown({
            inDuration: 300,
            outDuration: 225,
            constrainWidth: true, // Does not change width of dropdown to that of the activator
            hover: true, // Activate on hover
            gutter: 0, // Spacing from edge
            belowOrigin: false, // Displays dropdown below the button
            alignment: 'left', // Displays dropdown with edge aligned to the left of button
            stopPropagation: false // Stops event propagation
        });

        $('.collapsible').collapsible();

        $('.modal').modal({
                dismissible: true, // Modal can be dismissed by clicking outside of the modal
                opacity: .5, // Opacity of modal background
                inDuration: 300, // Transition in duration
                outDuration: 200, // Transition out duration
                startingTop: '10%', // Starting top style attribute
                endingTop: '10%' // Ending top style attribute
            }
        );

    }); // end of document ready
})(jQuery); // end of jQuery name space


text:
package urlshortener.common.web.fixture;

import urlshortener.common.domain.ShortURL;

public class ShortURLFixture {

	public static ShortURL someUrl() {
		return new ShortURL("someKey", "http://example.com/", null, null, null,
				null, 307, true, null, null, null, false);
	}
}


text:
<?php
/**
 * Event class.
 * @version    1.0
 * @author     Housseyn Guettaf <ghoucine@gmail.com>
 * @package    Phiber
 */
namespace Phiber\Event;

class event
{
    protected $authority;
    protected $name;
    protected $type;
    protected $payload;
    protected $vars = array();

    public function __construct($eventName, $issuer, $payload = null, $type = 'notification')
    {
        $this->name = $eventName;
        $this->authority = $issuer;
        $this->type = $type;
        $this->payload = $payload;

    }

    /**
     * @return null
     */
    public function getPayload()
    {
        return $this->payload;
    }
    /**
     * @return mixed
     */
    public function getAuthority()
    {
        return $this->authority;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }
    public function __toString()
    {
        return __CLASS__;
    }

    public function __set($var, $value)
    {
        $this->vars[$var] = $value;
    }

    public function __get($var)
    {
        if (isset($this->vars[$var])) {
            return $this->vars[$var];
        }
    }
}

?>


text:
var co = require('co');
var Hackathon = require('../models/hackathon');

module.exports = {
	create: function(event) {
		return function(done) {
			co(function *() {
				var _hackathon = new Hackathon({
					name: event.name,
					desc: event.desc,
					geo: event.geo,
					loc: event.loc,
					address: event.address,
					start: event.start,
					end: event.end,
					registration: event.registration,
					website: event.website
				});

				_hackathon.save(function(err) {

					done(err, _hackathon);
				});
			});

		};
	},
	getEvent: function(id) {
		return function(done) {
			Hackathon.findOne({ _id: id }, function(err, event) {
				if (err)
					return done(err);

				if (!event)
					return done();

				return done(null, event);
			});
		};
	},
	list: function() {

		var conditions = {};
		var columns;
		var opts = {};
		if (arguments.length == 3) {
			conditions = arguments[0];
			columns = arguments[1];
			opts = arguments[2];
		} else if (arguments.length == 2) {
			if (arguments[0] instanceof Array) {
				columns = arguments[0];
				opts = arguments[1];
			} else if (arguments[1] instanceof Array) {
				conditions = arguments[0];
				columns = arguments[1];
			} else {
				conditions = arguments[0];
				opts = arguments[1];
			}
		} else if (arguments.length == 1) {
			columns = null;
			opts = arguments[0];
		}

		return function(done) {

			var cols = null;
			if (columns)
				cols = columns.join(' ');

			Hackathon.count(conditions, function(err, count) {
				if (err) {
					done(err);
					return;
				}

				if (!count) {
					done(err, { count: 0 });
					return;
				}

				Hackathon.find(conditions, cols, opts, function(err, results) {

					done(err, {
						count: count,
						results: results
					});
				});
			});
		};
	}
};