text:
Plugin Signing
==============
# Security
By default, the Snap daemon (snapd) has plugin signing verification enabled. To disable it or turn it to warning, the flag `--plugin-trust, -t` can be set to 0 or 2 respectively.

##How it works
![How it works](https://cloud.githubusercontent.com/assets/12282848/10112575/19bec0f4-6391-11e5-8f27-7a1a057122fd.png)
Private/public keys and keyrings are generated by GPG. The plugin is signed with the private key and the public key needs to be added to the user's keyring. The signing is an armored detached signature in the form of a `.asc` file.

The Snap daemon uses the [Golang OpenPGP library](https://godoc.org/golang.org/x/crypto/openpgp)'s `CheckArmoredDetachedSignature` function to validate the signature using the keyring, plugin, and signature file before loading the plugin. It checks the issuer key ID, hash, and signature type.
```go
openpgp.CheckArmoredDetachedSignature(keyring, signed, signature)
```

##Usage
```
snapd
  --plugin-trust, -t '1'		0-2 (Disabled, Enabled, Warning) [$SNAP_TRUST_LEVEL]
  --keyring-paths, -k 			Keyring files for signing verification separated by colons [$SNAP_KEYRING_FILES]
```
One keyring (-t flag is not needed for signing enabled)
```
$ $SNAP_PATH/bin/snapd -k <keyringFileOrDirectory>
$ $SNAP_PATH/bin/snapd -t <trustLevel> -k <keyringFileOrDirectory>
$ $SNAP_PATH/bin/snapd -t <trustLevel> -k someDirectory/someFile.gpg
$ $SNAP_PATH/bin/snapd -t <trustLevel> -k someDirectory/
```
Multiple keyrings (may need full path, not ~)
```
$ $SNAP_PATH/bin/snapd -t <trustLevel> -k <keyringFile1>:<keyringFile2>
```
By default, plugin-trust is 1 (enabled), so the flag is only needed for 0 (disabled) and 2 (warning)
You can make an export to avoid needing the `-k` flag:
```
$ export SNAP_KEYRING_FILE=<keyringFile>
$ $SNAP_PATH/bin/snapd -t <trustLevel>
```

Loading a single plugin using $SNAP_PATH/bin/snapctl
```
$ $SNAP_PATH/bin/snapctl plugin load <pluginFile> -a <pluginFile>.asc
```

####Examples
#####No keyring, trust enabled/warning
```
$ $SNAP_PATH/bin/snapd -l 1

INFO[0000] setting plugin trust level to: enabled
FATA[0000] need keyring file when trust is on (--keyring-file or -k)  _module=snapd block=main
```
#####Invalid Keyring
Keyring doesn't exist
```
$ $SNAP_PATH/bin/snapd -l 1 -k /Users/tiffany/.gnupg/pubring.gpg:/Users/tiffany/.gnupg/stuff.gpg
INFO[0000] adding keyring file /Users/tiffany/.gnupg/pubring.gpg
FATA[0000] bad keyring file                              _module=snapd block=main error=stat /Users/tiffany/.gnupg/stuff.gpg: no such file or directory keyringPath=/Users/tiffany/.gnupg/stuff.gpg
```
#####Correct Keyring, trust enabled
Valid signature
```
$ $SNAP_PATH/bin/snapd -l 1 -k /Users/tiffany/.gnupg/

INFO[0000] setting plugin trust level to: enabled
INFO[0000] Adding keyrings from: /Users/tiffany/.gnupg
INFO[0000] adding keyring file: /Users/tiffany/.gnupg/pubkeys.gpg
INFO[0000] adding keyring file: /Users/tiffany/.gnupg/pubkeys2.gpg
INFO[0000] adding keyring file: /Users/tiffany/.gnupg/pubring.gpg
INFO[0000] adding keyring file: /Users/tiffany/.gnupg/snap.pubring
INFO[0000] adding keyring file: /Users/tiffany/.gnupg/secring.gpg
INFO[0000] adding keyring file: /Users/tiffany/.gnupg/trustdb.gpg
```
```
$ $SNAP_PATH/bin/snapctl plugin load build/plugin/snap-collector-mock1 -a build/plugin/snap-collector-mock1.asc
Plugin loaded
Name: mock
Version: 1
Type: collector
Signed: true
Loaded Time: Thu, 12 Nov 2015 13:53:58 PST
```
```
INFO[0036] API request                                   _module=_mgmt-rest index=3 method=POST url=/v1/plugins
DEBU[0037] wrote 7332032 to /var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/485061199/snap-collector-mock1
DEBU[0037] wrote 473 to /var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/784063842/snap-collector-mock1.asc
INFO[0037] Loading plugin: /var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/485061199/snap-collector-mock1  _module=_mgmt-rest
Signature made Thu, 12 Nov 2015 13:53:58 PST using RSA key ID 43F744A0
Good signature from Tiffany Jernigan (Main signing key) <my.email@intel.com>
```
No signature
```
$ $SNAP_PATH/bin/snapctl plugin load build/plugin/snap-collector-mock2
Error loading plugin:
Signature file (.asc) not found:
open : no such file or directory
```
```
DEBU[0033] wrote 7327840 to /var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/180549107/snap-collector-mock2
INFO[0033] Loading plugin: /var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/180549107/snap-collector-mock2  _module=_mgmt-rest
ERRO[0033] Signature file (.asc) not found:
open : no such file or directory  _module=_mgmt-rest
DEBU[0033] Removing file (/var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/180549107/snap-collector-mock2) after failure to load plugin (/var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/180549107/snap-collector-mock2)  _module=_mgmt-rest
```
Invalid signature
```
$SNAP_PATH/bin/snapctl plugin load build/plugin/snap-collector-mock2 -a build/plugin/snap-collector-mock1.asc
Error loading plugin:
Error checking signature
openpgp: invalid signature: hash tag doesn't match
```
```
DEBU[0003] wrote 7327840 to /var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/719702627/snap-collector-mock2
DEBU[0003] wrote 473 to /var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/700509798/snap-collector-mock1.asc
INFO[0003] Loading plugin: /var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/719702627/snap-collector-mock2  _module=_mgmt-rest
ERRO[0003] Error checking signature
openpgp: invalid signature: hash tag doesn't match  _module=_mgmt-rest
DEBU[0003] Removing file (/var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/719702627/snap-collector-mock2) after failure to load plugin (/var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/719702627/snap-collector-mock2)  _module=_mgmt-rest
DEBU[0003] Removing file (/var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/700509798/snap-collector-mock1.asc) after failure to load plugin (/var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/719702627/snap-collector-mock2)  _module=_mgmt-rest
```
Wrong keyring
```
$ $SNAP_PATH/bin/snapctl plugin load build/plugin/snap-collector-mock1 -a build/plugin/snap-collector-mock1.asc
Error loading plugin:
Error checking signature
openpgp: signature made by unknown entity
```
```
INFO[0002] Loading plugin: /var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/057449871/snap-collector-mock1  _module=_mgmt-rest
ERRO[0002] Error checking signature
openpgp: signature made by unknown entity  _module=_mgmt-rest
```
#####Correct keyring, trust warning
```
$ $SNAP_PATH/bin/snapd -l 1 -k ~/.gnupg/pubring.gpg -t 2
INFO[0000] setting plugin trust level to: warning
INFO[0000] adding keyring file /Users/tiffany/.gnupg/pubring.gpg
```
```
$ $SNAP_PATH/bin/snapctl plugin load build/plugin/snap-collector-mock1 -a build/plugin/snap-collector-mock1.asc

Plugin loaded
Name: mock
Version: 1
Type: collector
Signed: true
Loaded Time: Thu, 12 Nov 2015 14:08:32 PST

$ $SNAP_PATH/bin/snapctl plugin load build/plugin/snap-collector-mock2

Plugin loaded
Name: mock
Version: 2
Type: collector
Signed: false
Loaded Time: Thu, 12 Nov 2015 14:08:49 PST
```
```
INFO[0338] Loading plugin: /var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/276797457/snap-collector-mock1  _module=_mgmt-rest
Signature made Thu, 12 Nov 2015 14:08:32 PST using RSA key ID 43F744A0
Good signature from Tiffany Jernigan (ACI signing key) <my.email@intel.com>
WARN[0355] Loading unsigned plugin /var/folders/kh/v2qy5_zx3zlgbc0gll7fzjnm0000gp/T/205904491/snap-collector-mock2  _block=load _module=control
```

##Creating Signing Files and Validating Signature
###Creating a key for plugin signing
The following is leveraged from the [CoreOS RKT Signing and Verification Guide](https://coreos.com/rkt/docs/0.5.4/signing-and-verification-guide.html)

Create a file named `gpg-batch` with the following
```
%echo Generating a default key
Key-Type: RSA
Key-Length: 2048
Subkey-Type: RSA
Subkey-Length: 2048
Name-Real: Tiffany Jernigan
Name-Comment: Plugin signing key
Name-Email: my.email@intel.com
Expire-Date: 0
Passphrase: snap
%pubring snap.pubring
%secring snap.secring
%commit
%echo done
```
#####Generate the key using batch mode
```
$ gpg --batch --gen-key gpg-batch
```

#####List the keys
```
$ gpg --no-default-keyring --secret-keyring ./snap.secring --keyring ./snap.pubring \
--list-keys
```
```
./snap.pubring
-----------
pub   2048R/FE9B5E28 2015-11-04
uid                  Tiffany Jernigan (Plugin signing key) <my.email@intel.com>
sub   2048R/0BC6D4D7 2015-11-04
```

Since we know exactly where this key came from let's trust it:
```
$ gpg --no-default-keyring --secret-keyring ./snap.secring --keyring ./snap.pubring \
--edit-key FE9B5E28 trust
```
```
gpg (GnuPG) 1.4.19; Copyright (C) 2015 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Secret key is available.

pub  2048R/FE9B5E28  created: 2015-11-04  expires: never       usage: SCEA
                     trust: unknown       validity: unknown
sub  2048R/0BC6D4D7  created: 2015-11-04  expires: never       usage: SEA
[ unknown] (1). Tiffany Jernigan (Plugin signing key) <my.email@intel.com>

pub  2048R/FE9B5E28  created: 2015-11-04  expires: never       usage: SCEA
                     trust: unknown       validity: unknown
sub  2048R/0BC6D4D7  created: 2015-11-04  expires: never       usage: SEA
[ unknown] (1). Tiffany Jernigan (Plugin signing key) <my.email@intel.com>

Please decide how far you trust this user to correctly verify other users' keys
(by looking at passports, checking fingerprints from different sources, etc.)

  1 = I don't know or won't say
  2 = I do NOT trust
  3 = I trust marginally
  4 = I trust fully
  5 = I trust ultimately
  m = back to the main menu

Your decision? 5
Do you really want to set this key to ultimate trust? (y/N) y

pub  2048R/FE9B5E28  created: 2015-11-04  expires: never       usage: SCEA
                     trust: ultimate      validity: unknown
sub  2048R/0BC6D4D7  created: 2015-11-04  expires: never       usage: SEA
[ unknown] (1). Tiffany Jernigan (Plugin signing key) <my.email@intel.com>
Please note that the shown key validity is not necessarily correct
unless you restart the program.

gpg> quit
```
#####Export the public key
```
$ gpg --no-default-keyring --armor \
--secret-keyring ./snap.secring --keyring ./snap.pubring \
--export my.email@intel.com > pubkeys.gpg
```

###Signing the plugin/plugin package using generated keyrings
#####Sign file
```
$ gpg --no-default-keyring --armor \
--secret-keyring ./snap.secring --keyring ./snap.pubring \
--output <pluginFile>.asc \
--detach-sig <pluginFile>
```
#####Verify the image using gpg
```
$ gpg --no-default-keyring \
--secret-keyring ./snap.secring --keyring ./snap.pubring \
--verify <pluginFile>.asc <pluginFile>
```
```
gpg: Signature made Wed Nov  4 14:24:18 2015 PST using RSA key ID 0BC6D4D7
gpg: Good signature from "Tiffany Jernigan (Plugin signing key) <my.email@intel.com>
```

###Signing file using key in your default keyring
If you already have a key, you can use that. Otherwise you can create a key and directly add to your keyring
Create a file named `gpg-batch` with the following
```
%echo Generating a default key
Key-Type: RSA
Key-Length: 2048
Subkey-Type: RSA
Subkey-Length: 2048
Name-Real: Tiffany Jernigan
Name-Comment: Main signing key
Name-Email: my.email@intel.com
Expire-Date: 0
Passphrase: snap
%commit
%echo done
```
#####Generate the key using batch mode
```
$ gpg --batch --gen-key gpg-batch
```
```
$ gpg --list-keys
```
```
/Users/tiffany/.gnupg/pubring.gpg
----------------------------------
pub   2048R/43F744A0 2015-08-22
uid                  Tiffany Jernigan (Main signing key) <my.email@intel.com>
sub   2048R/2ED40FB2 2015-08-22
```

#####Sign file
```
$ gpg --armor --output <pluginFile>.asc --detach-sig <pluginFile>
```
#####Verify the image using gpg
```
$ gpg --verify <pluginFile>.asc <pluginFile>
```

###Keyring
####Adding to your keyring
If you only have one key, you can use the `snap.pubring` you just made as your `<keyringFile>`. For multiple you can just separate them by a colon (e.g. <keyringFile1>:<keyringFile2> ) . If you want to add future pubkeys.gpg files to an existing keyring you can do:
```
$ gpg --no-default-keyring --keyring <keyringFile> --import pubkeys.gpg
```
If you just want to add to your gnupg default keyring (e.g. `~/.gnupg/pubring.gpg`) you can just do
```
$ gpg --import pubkeys.gpg
```
####Validating a public key from someone else
From the [GPG Handbook](https://www.gnupg.org/gph/en/manual/x56.html):
Once a key is imported it should be validated. GnuPG uses a powerful and flexible trust model that does not require you to personally validate each key you import. Some keys may need to be personally validated, however. A key is validated by verifying the key's fingerprint and then signing the key to certify it as a valid key. A key's fingerprint can be quickly viewed with the --fingerprint command-line option, but in order to certify the key you must edit it.

Add --no-default-keyring --keyring <keyringFile> to all commands below if you are editing a specific keyring that isn't your gnupg default one.
```
$ gpg --list-keys
```
```
/Users/tiffany/.gnupg/pubring.gpg
----------------------------------
pub   2048R/43F744A0 2015-08-22
uid                  Tiffany Jernigan (Main signing key) <my.email@intel.com>
sub   2048R/2ED40FB2 2015-08-22

pub   2048R/FE9B5E28 2015-11-04
uid                  Tiffany Jernigan (Plugin signing key) <my.email@intel.com>
sub   2048R/0BC6D4D7 2015-11-04
```
```
$ gpg --edit-key FE9B5E28
```
```
gpg (GnuPG) 1.4.19; Copyright (C) 2015 Free Software Foundation, Inc.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

pub  2048R/FE9B5E28  created: 2015-11-04  expires: never       usage: SCEA
                     trust: unknown       validity: ultimate
sub  2048R/0BC6D4D7  created: 2015-11-04  expires: never       usage: SEA
[ultimate] (1). Tiffany Jernigan (Plugin signing key) <my.email@intel.com>

gpg> sign

pub  2048R/FE9B5E28  created: 2015-11-04  expires: never       usage: SCEA
                     trust: unknown       validity: ultimate
 Primary key fingerprint: 60BF B0AD 3CDB 5188 CE27  EBD5 F7D3 7AF8 FE9B 5E28

     Tiffany Jernigan (Plugin signing key) <my.email@intel.com>

Are you sure that you want to sign this key with your
key "Tiffany Jernigan (Main signing key) <my.email@intel.com>" (43F744A0)

Really sign? (y/N) y

You need a passphrase to unlock the secret key for
user: "Tiffany Jernigan (Main signing key) <my.email@intel.com>"
2048-bit RSA key, ID 43F744A0, created 2015-08-22

gpg> check
uid  Tiffany Jernigan (Plugin signing key) <my.email@intel.com>
sig!3        FE9B5E28 2015-11-04  [self-signature]
sig!         43F744A0 2015-11-05  Tiffany Jernigan (Main signing key) <my.email@intel.com>

gpg> quit
Save changes? (y/N) y
```


text:
<?php
$_pluginInfo=array(
	'name'=>'FastMail',
	'version'=>'1.0.9',
	'description'=>"Get the contacts from a FastMail account",
	'base_version'=>'1.6.3',
	'type'=>'email',
	'check_url'=>'http://www.fastmail.fm',
	'requirement'=>'email',
	'allowed_domains'=>array('/(fastmail.fm)/i'),
	'imported_details'=>array('first_name','middle_name','last_name','nickname','email_1','email_2','email_3','organization','phone_mobile','phone_home','phone_work','fax','pager','address_home','address_work','website','address_city','address_state','address_country','postcode_home','isq_messenger','skype_messenger','yahoo_messenger','msn_messenger','aol_messenger','other_messenger'),
	);
/**
 * FastMail Plugin
 *
 * Imports user's contacts from FastMail's AddressBook
 *
 * @author OpenInviter
 * @version 1.0.0
 */
class fastmail extends openinviter_base
	{
	private $login_ok=false;
	public $showContacts=true;
	public $internalError=false;
	protected $timeout=30;

	public $debug_array=array(
				'initial_get'=>'FLN-LoginMode',
				'post_login'=>'redirected',
				'url_webinterface'=>'kbshortcut',
				'url_get_webinterface'=>'kbshortcut',
				'contacts_page'=>'MC-From',
				'contacts_file'=>'Title',
				);

	/**
	 * Login function
	 *
	 * Makes all the necessary requests to authenticate
	 * the current user to the server.
	 *
	 * @param string $user The current user.
	 * @param string $pass The password for the current user.
	 * @return bool TRUE if the current user was authenticated successfully, FALSE otherwise.
	 */
	public function login($user,$pass)
		{
		$this->resetDebugger();
		$this->service='fastmail';
		$this->service_user=$user;
		$this->service_password=$pass;
		if (!$this->init()) return false;

		$res=$this->get("http://www.fastmail.fm/");

		if ($this->checkResponse('initial_get',$res))
			$this->updateDebugBuffer('initial_get',"http://www.fastmail.fm/",'GET');
		else
			{
			$this->updateDebugBuffer('initial_get',"http://www.fastmail.fm/",'GET',false);
			$this->debugRequest();
			$this->stopPlugin();
			return false;
			}

		$form_action=$this->getElementString($res,'action="','"');
		$post_elements=array('MLS'=>'=LN-*',
							 'FLN-LoginMode'=>0,
							 'FLN-UserName'=>$user,
							 'FLN-Password'=>$pass,
							 'MSignal_LN-AU*'=>'Login',
							 'FLN-Security'=>0,
							 'FLN-ScreenSize'=>3,
							 'FLN-SessionTime'=>1800,
							 'FLN-NoCache'=>'on'

							);
		$res=$this->post($form_action,$post_elements,TRUE);
		if ($this->checkResponse('post_login',$res))
			$this->updateDebugBuffer('post_login',"{$form_action}",'POST',true,$post_elements);
		else
			{
			$this->updateDebugBuffer('post_login',"{$form_action}",'POST',false,$post_elements);
			$this->debugRequest();
			$this->stopPlugin();
			return false;
			}

		if (strpos($res,'ChooseWeb-*')!==false)
			{
			$form_action=$this->getElementString($res,'post" action="','"');
			$post_elements=$this->getHiddenElements($res);$post_elements['FChooseWeb-WebInterface']=2;
			$res=$this->post($form_action,$post_elements,true);
			if ($this->checkResponse('url_webinterface',$res))
				$this->updateDebugBuffer('url_webinterface',"{$form_action}",'POST',true,$post_elements);
			else
				{
				$this->updateDebugBuffer('url_webinterface',"{$form_action}",'POST',false,$post_elements);
				$this->debugRequest();
				$this->stopPlugin();
				return false;
				}
			}
		else
			{
			$url_redirect=$this->getElementString($res,'href="','"');
			$res=$this->get($url_redirect,true);
			if ($this->checkResponse('url_get_webinterface',$res))
					$this->updateDebugBuffer('url_get_webinterface',"{$url_redirect}","GET",'GET');
				else
					{
					$this->updateDebugBuffer('url_get_webinterface',"{$url_redirect}","GET",'GET',false);
					$this->debugRequest();
					$this->stopPlugin();
					return false;
					}
			}

		$url_adress_book=$this->getElementDOM($res,"//a[@kbshortcut='b']",'href');
		$url_adress="http://www.fastmail.fm".$url_adress_book[0];
		file_put_contents($this->getLogoutPath(),$url_adress);
		$this->login_ok=$url_adress;
		return true;
		}

	/**
	 * Get the current user's contacts
	 *
	 * Makes all the necesarry requests to import
	 * the current user's contacts
	 *
	 * @return mixed The array if contacts if importing was successful, FALSE otherwise.
	 */
	public function getMyContacts()
		{
		if (!$this->login_ok)
			{
			$this->debugRequest();
			$this->stopPlugin();
			return false;
			}
		else $url=$this->login_ok;
		$res=$this->get($url,true);
		$form_action=$this->getElementString($res,'action="','"');
		$post_elements=$this->getHiddenElements($res);
		$post_elements["_charset"]="UTF-8";
		$post_elements['FAD-ST']=false;
		$post_elements['FAD-AL-SortBy']='SNM';
		$post_elements['nojs']=false;
		$post_elements['MSignal_UA-*U-1']=false;
		print_r($post_elements);
		echo $res=$this->post($form_action,$post_elements,true);
		exit;
		if ($this->checkResponse('contacts_page',$res))
			$this->updateDebugBuffer('contacts_page',"{$form_action}",'POST',true,$post_elements);
		else
			{
			$this->updateDebugBuffer('contacts_page',"{$form_action}",'POST',false,$post_elements);
			$this->debugRequest();
			$this->stopPlugin();
			return false;
			}

		$post_elements=array();
		$form_action=$this->getElementString($res,'action="','"');
		$post_elements['nojs']=0;
		$post_elements['_charset_']='ISO-8859-1';
		$post_elements['MLS']='UA-*';
		$post_elements['MSS']='!AD-*';
		$post_elements['SAD-AL-DR']=0;
		$post_elements['FUA-DownloadFormat']='OL';
		$post_elements['FUA-Group']=0;
		$post_elements['MSignal_UA-Download*']='';
		$res=$this->post($form_action,$post_elements);
		if ($this->checkResponse('contacts_file',$res))
			$this->updateDebugBuffer('contacts_file',"{$form_action}",'POST',true,$post_elements);
		else
			{
			$this->updateDebugBuffer('contacts_file',"{$form_action}",'POST',false,$post_elements);
			$this->debugRequest();
			$this->stopPlugin();
			return false;
			}

		$temp=$this->parseCSV($res);
		$contacts=array();$descriptionArray=array();
		foreach ($temp as $values)
			{
			if (!empty($values[34]))
				$contacts[$values[34]]=array('first_name'=>(!empty($values[1])?$values[1]:false),
												'middle_name'=>false,
												'last_name'=>(!empty($values[2])?$values[2]:false),
												'nickname'=>(!empty($values[3])?$values[3]:false),
												'email_1'=>(!empty($values[34])?$values[34]:false),
												'email_2'=>(!empty($values[35])?$values[35]:false),
												'email_3'=>(!empty($values[36])?$values[36]:false),
												'organization'=>false,
												'phone_mobile'=>(!empty($values[30])?$values[30]:false),
												'phone_home'=>(!empty($values[28])?$values[28]:false),
												'pager'=>(!empty($values[32])?$values[32]:false),
												'address_home'=>false,
												'address_city'=>(!empty($values[15])?$values[15]:false),
												'address_state'=>(!empty($values[16])?$values[16]:false),
												'address_country'=>(!empty($values[18])?$values[18]:false),
												'postcode_home'=>(!empty($values[17])?$values[17]:false),
												'company_work'=>(!empty($values[4])?$values[4]:false),
												'address_work'=>false,
												'address_work_city'=>(!empty($values[9])?$values[9]:false),
												'address_work_country'=>(!empty($values[12])?$values[12]:false),
												'address_work_state'=>(!empty($values[10])?$values[10]:false),
												'address_work_postcode'=>(!empty($values[11])?$values[11]:false),
												'fax_work'=>false,
												'phone_work'=>(!empty($values[20])?$values[20]:false),
												'website'=>(!empty($values[38])?$values[38]:false),
												'isq_messenger'=>false,
												'skype_essenger'=>false,
												'yahoo_essenger'=>false,
												'msn_messenger'=>false,
												'aol_messenger'=>false,
												'other_messenger'=>false,
											   );
			}
		foreach ($contacts as $email=>$name) if (!$this->isEmail($email)) unset($contacts[$email]);
		return $this->returnContacts($contacts);
		}

	/**
	 * Terminate session
	 *
	 * Terminates the current user's session,
	 * debugs the request and reset's the internal
	 * debudder.
	 *
	 * @return bool TRUE if the session was terminated successfully, FALSE otherwise.
	 */
	public function logout()
		{
		if (!$this->checkSession()) return false;
		if (file_exists($this->getLogoutPath()))
			{
			$url=file_get_contents($this->getLogoutPath());
			//go to url adress book  url in order to make the logout
			$res=$this->get($url,true);
			$form_action=$this->getElementString($res,'action="','"');
			$post_elements=$this->getHiddenElements($res);
			$post_elements['MSignal_AD-LGO*C-1.N-1']='Logout';

			//get the post elements and make de logout
			$res=$this->post($form_action,$post_elements,true);
			}
		$this->debugRequest();
		$this->resetDebugger();
		$this->stopPlugin();
		return true;
		}

	}
?>

redpajama_set_name: RedPajamaGithub


text:
package ru.nyrk.gisgmp.database.entity;

import javax.persistence.*;

@javax.persistence.Table(name = "tb_mess_addinfo", schema = "", catalog = "gisgmp")
@Entity
public class MessAddinfoEntity {
    private long messAddinfoId;
    private Long mesId;
    private String fldNm;
    private String fieldVl;

    @javax.persistence.Column(name = "mess_addinfo_id")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public long getMessAddinfoId() {
        return messAddinfoId;
    }

    public void setMessAddinfoId(long messAddinfoId) {
        this.messAddinfoId = messAddinfoId;
    }

    @javax.persistence.Column(name = "mes_id")
    @Basic
    public Long getMesId() {
        return mesId;
    }

    public void setMesId(Long mesId) {
        this.mesId = mesId;
    }

    @javax.persistence.Column(name = "fld_nm")
    @Basic
    public String getFldNm() {
        return fldNm;
    }

    public void setFldNm(String fldNm) {
        this.fldNm = fldNm;
    }

    @javax.persistence.Column(name = "field_vl")
    @Basic
    public String getFieldVl() {
        return fieldVl;
    }

    public void setFieldVl(String fieldVl) {
        this.fieldVl = fieldVl;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        MessAddinfoEntity that = (MessAddinfoEntity) o;

        if (messAddinfoId != that.messAddinfoId) return false;
        if (fieldVl != null ? !fieldVl.equals(that.fieldVl) : that.fieldVl != null) return false;
        if (fldNm != null ? !fldNm.equals(that.fldNm) : that.fldNm != null) return false;
        if (mesId != null ? !mesId.equals(that.mesId) : that.mesId != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = (int) (messAddinfoId ^ (messAddinfoId >>> 32));
        result = 31 * result + (mesId != null ? mesId.hashCode() : 0);
        result = 31 * result + (fldNm != null ? fldNm.hashCode() : 0);
        result = 31 * result + (fieldVl != null ? fieldVl.hashCode() : 0);
        return result;
    }
}


text:
from sanpera import geometry

from libweasyl import ratings

from weasyl.error import WeasylError
from weasyl import define as d
from weasyl import image, media, orm

def avatar_source(userid):
    media_items = media.get_user_media(userid)
    if media_items.get('avatar-source'):
        return media_items['avatar-source'][0]
    else:
        raise WeasylError('noImageSource')

def upload(userid, filedata):
    """
    Creates a preview-size copy of an uploaded image file for a new avatar
    selection file.
    """
    if filedata:
        media_item = media.make_resized_media_item(filedata, (600, 500), 'FileType')
        orm.UserMediaLink.make_or_replace_link(
            userid, 'avatar-source', media_item, rating=ratings.GENERAL.code)
    else:
        orm.UserMediaLink.clear_link(userid, 'avatar')

    return bool(filedata)

# TODO: Make this function respect new geometry.
def create(userid, x1, y1, x2, y2, auto=False, config=None):
    x1, y1, x2, y2 = d.get_int(x1), d.get_int(y1), d.get_int(x2), d.get_int(y2)
    db = d.connect()
    im = db.query(orm.MediaItem).get(avatar_source(userid)['mediaid']).as_image()
    file_type = image.image_file_type(im)
    bounds = None
    size = im.size.width, im.size.height
    if not auto and image.check_crop(size, x1, y1, x2, y2):
        bounds = geometry.Rectangle(x1, y1, x2, y2)
    thumb = image.shrinkcrop(im, geometry.Size(100, 100), bounds)
    media_item = orm.fetch_or_create_media_item(
        thumb.to_buffer(format=file_type), file_type=file_type, im=thumb)
    orm.UserMediaLink.make_or_replace_link(
        userid, 'avatar', media_item, rating=ratings.GENERAL.code)
    orm.UserMediaLink.clear_link(userid, 'avatar-source')


text:
module PolymerPlatinumRails
  VERSION = "1.0.0-rc.1"
end


text:
#ifndef GCC_TILEGX_MULTIPLY_H
#define GCC_TILEGX_MULTIPLY_H

/* A node of a tilegx_multiply_insn_seq, corresponding to a single
   machine instruction such as 'add', 's1a', or an shl by a constant.  */
struct tilegx_multiply_insn_seq_entry
{
  /* Which operation this node performs (e.g. an add or sub).
     Don't use this directly, call get_opcode() table to get a insn_code.  */
  unsigned char compressed_opcode;

  /* The left-hand side of this expression tree.
     If equal to 0, it refers to 'zero'.
     If equal to 1, it refers to the original input to the multiply operation.
     Otherwise, subtract two and it is an index into the containing
     tilegx_multiply_insn_seq's 'op' array. Since it can only point to some
     value that has already been computed it will always point to an
     earlier entry in the array.  */
  unsigned char lhs;

  /* This is like lhs, but for the right-hand side. However, for shift
     opcodes this is a shift count rather than an operand index.  */
  unsigned char rhs;
};

/* Maximum size of op array.  */
#define tilegx_multiply_insn_seq_MAX_OPERATIONS 4

/* This defines a DAG describing how to multiply by a constant in
   terms of one or more machine instructions.  */
struct tilegx_multiply_insn_seq
{
  /* The constant factor by which this expression tree multiplies its input.  */
  long long multiplier;

  /* The nodes of the parse tree. These are ordered so that instructions
     can be emitted in the same order that they appear in this array.
     Entry entry in this array can only refer to earlier entries in
     the array.  */
  struct tilegx_multiply_insn_seq_entry
    op[tilegx_multiply_insn_seq_MAX_OPERATIONS];

};

/* A mapping from the compressed opcode to the corresponding enum
   insn_code.  */
extern const enum insn_code tilegx_multiply_insn_seq_decode_opcode[];

/* Table mapping constant int multipliers to an expression
   tree that efficiently performs that multiplication.
   This is sorted by its 'multiplier' field so a binary search
   can look for matches.  */
extern const struct tilegx_multiply_insn_seq tilegx_multiply_insn_seq_table[];

/* The number of elements in multiply_insn_seq_table.  */
extern const int tilegx_multiply_insn_seq_table_size;

#endif /* !GCC_TILEGX_MULTIPLY_H */


text:
Irvine High School Website 2004
================

**This was a PHP/Perl website built by the IHS Web Tech Staff Team around 2004. In the early 2000's to 2007, Irvine High School was one of the very few schools with a tech program.** This program was administered by school officials but managed by Tech Students. In this Tech Program, there were several tiers of different techs. These techs often passed down their knowledge of programming languages and system administration.

The primary author of this version of the site was by Daniel Hawton.

For privacy concerns and the right to be forgotten, we have removed all the media data associated with the web application.

Why do some files have .adm and the PHP has <% ?

An earlier version of the website was in ASP and built by earlier IHS Web Tech Staff. At the time, it was in question if we could run the website in PHP. We made it appear as if the site were still written in ASP.

Here is a version of the website from the time. [https://web.archive.org/web/20051107210950/http://www.irvinehigh.org/](https://web.archive.org/web/20051107210950/http://www.irvinehigh.org/)

***A special thanks to Daniel for teaching me PHP.*** - Peter

##Here's to wishing IHS re-established and reaffirm such a prosperous environment for students interested in technology and programming. Many individuals whom were involved found themselves with a job in the tech arena after high school


text:
#include "fuseLib.h"
#include "myFS.h"

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

MyFileSystem myFileSystem;

#define USAGE		"Usage: %s -t diskSize -a backupFileName -f 'fuse options'\n"
#define EXAMPLE		"Example:\n%s -t 2097152 -a virtual-disk -f '-d -s mount-point'\n"
#define EXAMPLE2 	"Example:\n%s -m -a <virtual-disk> -f '-d -s mount-point'\n"

int main(int argc, char **argv) {
	myFileSystem.numFreeNodes = MAX_NODES;

	int ret; // Resulting code of the functions call

	fprintf(stderr, "\n\tNumero de nodos libres = %d\n\n", myFileSystem.numFreeNodes);

	int opt, diskSize = -1;
	char *backupFileName = NULL;
	char *argsFUSE = NULL;

	char *argvNew[MAX_FUSE_NARGS];
	char *pTmp;
	int mount=0;

	while((opt = getopt(argc, argv, "t:a:f:m")) != -1) {
		switch(opt) {
			case 't':
				diskSize = atoi(optarg);
				break;
			case 'a':
				backupFileName = optarg;
				break;
			case 'f':
				argsFUSE = optarg;
				break;
			case 'm':
				mount=1;
				break;
			default: /* '?' */
				fprintf(stderr, USAGE, argv[0]);
				fprintf(stderr, EXAMPLE, argv[0]);
				exit(-1);
		}
	}

	if (!mount) {
		// Any parameter missing?
		if(diskSize == -1 || backupFileName == NULL || argsFUSE == NULL) {
			fprintf(stderr, USAGE, argv[0]);
			fprintf(stderr, EXAMPLE, argv[0]);
			exit(-1);
		}

		fprintf(stderr, "\t Disk SIze: %d\n", diskSize);
		fprintf(stderr, "\t Backup filename: %s\n", backupFileName);
		fprintf(stderr, "\n\t Desde MyFileSystem.c llamamos a myFkfs() para 'formatear' el sistema\n\n");

		// Format file without format?
		ret = myMkfs(&myFileSystem, diskSize, backupFileName);
	} else {
		// Any parameter missing?
		if(backupFileName == NULL || argsFUSE == NULL) {
			fprintf(stderr, USAGE, argv[0]);
			fprintf(stderr, EXAMPLE2, argv[0]);
			exit(-1);
		}
		//Mount the file system
		ret = myMount(&myFileSystem, backupFileName);
	}

	if(ret) {
		fprintf(stderr, "Unable to format or mount, error code: %d\n", ret);
		exit(-1);
	}
	fprintf(stderr, "File system available\n");

	// Parse the arguments for FUSE
	argc = 1;
	argvNew[0] = argv[0];

	pTmp = strtok(argsFUSE, " ");
	while(pTmp && argc < MAX_FUSE_NARGS) {
		argvNew[argc++] = pTmp;
		pTmp = strtok(0, " ");
	}

	// We mount the FS, exit with Control-C
	if((ret = fuse_main(argc, argvNew, &myFS_operations, NULL))) {
		fprintf(stderr, "Error when mounting the FUSE file system\n");
		return(ret);
	}

	myFree(&myFileSystem);

	return(0);
}


text:
using UnityEngine;
using System;

namespace CoreEngine.Math
{
	public abstract class BaseVector<TImpl,T> where T:struct, System.IConvertible where TImpl:BaseVector<TImpl,T>,new()
	{
		protected static Func<T,T,T> OperatorAdd;
		protected static Func<T,T,T> OperatorSubstract;
		protected static Func<T,T,T> OperatorMultiply;
		protected static Func<T,T,T> OperatorDivision;

		protected static int Dimensions{get;set;}
		public abstract T this[int i]
		{
			get;
			set;
		}

		public static TImpl operator +( BaseVector<TImpl,T>  a, BaseVector<TImpl,T>  b )
		{
			var impl = new TImpl();
			for ( int i = 0; i< Dimensions; ++i )
				impl[i] = OperatorAdd(a[i], b[i]);
			return impl;
		}
		public static TImpl operator -( BaseVector<TImpl,T>  a, BaseVector<TImpl,T>  b )
		{
			var impl = new TImpl();
			for ( int i = 0; i< Dimensions; ++i )
				impl[i] = OperatorSubstract(a[i], b[i]);
			return impl;
		}
		public static TImpl operator *( BaseVector<TImpl,T>  a, BaseVector<TImpl,T>  b )
		{
			var impl = new TImpl();
			for ( int i = 0; i< Dimensions; ++i )
				impl[i] = OperatorMultiply(a[i], b[i]);
			return impl;
		}
		public static TImpl operator /( BaseVector<TImpl,T>  a, BaseVector<TImpl,T>  b )
		{
			var impl = new TImpl();
			for ( int i = 0; i< Dimensions; ++i )
				impl[i] = OperatorDivision(a[i], b[i]);
			return impl;
		}
		public static bool operator ==( BaseVector<TImpl,T>  a, BaseVector<TImpl,T>  b )
		{
			for ( int i = 0; i< Dimensions; ++i )
				if ( a[i].Equals( b[i] ) == false )
					return false;
			return true;
		}
		public static bool operator !=( BaseVector<TImpl,T>  a, BaseVector<TImpl,T>  b )
		{
			for ( int i = 0; i< Dimensions; ++i )
				if ( a[i].Equals( b[i] ) == false )
					return true;
			return false;
		}
		public override bool Equals (object obj)
		{
			if ( obj.GetType() != obj.GetType() )
				return false;
			for ( int i = 0; i< Dimensions; ++i )
				if ( this[i].Equals( ((TImpl)obj)[i] ) == false )
					return false;
			return true;
		}
		public override int GetHashCode ()
		{
			int hash = 0;
			for ( int i = 0; i< Dimensions; ++i )
				hash ^= this[i].GetHashCode();
			return hash;
		}

		public static explicit operator Vector2( BaseVector<TImpl,T> v )
		{
			return new Vector2( (float)Convert.ChangeType(v[0],typeof(float)), (float)Convert.ChangeType(v[1],typeof(float)) );
		}
		public static explicit operator Vector3( BaseVector<TImpl,T> v )
		{
			return new Vector3( (float)Convert.ChangeType(v[0],typeof(float)), (float)Convert.ChangeType(v[1],typeof(float)), (Dimensions>2)?(float)Convert.ChangeType(v[2],typeof(float)):0 );
		}
	}
}


text:
{% extends '../base.html' %}

{% block content %}

Bienvenido a DevAsk!!

Bienvenido al Sistema de Discusiones para Programadores.

Haz tu Pregunta !!

                <button type="button" class="btn btn-default">Todas </button>
                <button type="button" class="btn btn-default">Top 5</button>
                <button type="button" class="btn btn-default">Favoritos</button>

            {% for data in questions %}

                            {{ data.user.username }}

                                {{ data.created | date('d / m / y') }}

                                {{ data.content }}

                                 Favoritos

                                 Like

            {% endfor %}

        <button type="button" class="close" data-dismiss="modal">×Close</button>

Formulario de Pregunta

        <form class="form-horizontal" role="form" method="post" action="/guardar-pregunta">

            Título:

              <input type="text" class="form-control" id="inputtitulo" placeholder="Título" name="title">

            Contenido:

              <textarea name="content" class="form-control" id="inputcontenido" rows="3"></textarea>

        <button type="button" class="btn btn-btn" data-dismiss="modal">Atrás</button>
        <input type="submit" class="btn btn-btn btn-warning" value="Preguntar">

      </form>

{% endblock %}

{% block js %}

{% endblock %}


text:
#ifndef __INC_SYS_APIC_H
#define __INC_SYS_APIC_H

#include <drivers/ioapic.h>
#include <drivers/loapic.h>

#define _IRQ_TRIGGER_EDGE	IOAPIC_EDGE
#define _IRQ_TRIGGER_LEVEL	IOAPIC_LEVEL

#define _IRQ_POLARITY_HIGH	IOAPIC_HIGH
#define _IRQ_POLARITY_LOW	IOAPIC_LOW

#ifndef _ASMLANGUAGE

#define LOAPIC_IRQ_BASE  CONFIG_IOAPIC_NUM_RTES
#define LOAPIC_IRQ_COUNT 6  /* Default to LOAPIC_TIMER to LOAPIC_ERROR */

/* irq_controller.h interface */
void __irq_controller_irq_config(unsigned int vector, unsigned int irq,
				 uint32_t flags);

int __irq_controller_isr_vector_get(void);

static inline void __irq_controller_eoi(void)
{
#if CONFIG_EOI_FORWARDING_BUG
	_lakemont_eoi();
#else
	*(volatile int *)(CONFIG_LOAPIC_BASE_ADDRESS + LOAPIC_EOI) = 0;
#endif
}

#else /* _ASMLANGUAGE */

#if CONFIG_EOI_FORWARDING_BUG
.macro __irq_controller_eoi_macro
	call	_lakemont_eoi
.endm
#else
.macro __irq_controller_eoi_macro
	xorl %eax, %eax			/* zeroes eax */
	loapic_eoi_reg = (CONFIG_LOAPIC_BASE_ADDRESS + LOAPIC_EOI)
	movl %eax, loapic_eoi_reg	/* tell LOAPIC the IRQ is handled */
.endm
#endif /* CONFIG_EOI_FORWARDING_BUG */

#endif /* _ASMLANGUAGE */

#endif /* __INC_SYS_APIC_H */


text:
tubularjs
=========

JavaScript Single-Page HTML5 Application framework for Connected-TVs, Smart TVs and Set-top Boxes


text:
package com.github.msemys.esjc.projection;

import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;

/**
 * Exception thrown if a projection operation fails with status code {@code 404} (Not Found).
 */
public class ProjectionNotFoundException extends ProjectionException {

    /**
     * Creates a new instance with the specified status code and error message.
     *
     * @param httpStatusCode HTTP status code.
     * @param message        error message.
     */
    public ProjectionNotFoundException(int httpStatusCode, String message) {
        super(httpStatusCode, message);
    }

    /**
     * Creates a new instance from the specified HTTP request and response.
     *
     * @param request  HTTP request.
     * @param response HTTP response.
     */
    public ProjectionNotFoundException(HttpRequest request, FullHttpResponse response) {
        super(request, response);
    }

}


text:
import { createTransformer } from "../src/mobx-utils"
import * as m from "mobx"

test("transform1", () => {
    let todoCalc = 0
    let stateCalc = 0
    let state = m.observable({
        todos: [
            {
                title: "coffee",
            },
        ],
        name: "michel",
    })

    let mapped
    let unloaded = []

    let transformState = createTransformer(function (state: any) {
        stateCalc++
        return state.name + state.todos.map(transformTodo).join(",")
    })

    let transformTodo = createTransformer(
        function (todo: any) {
            todoCalc++
            return todo.title.toUpperCase()
        },
        function cleanup(text, todo) {
            unloaded.push([todo, text])
        }
    )

    m.autorun(function () {
        mapped = transformState(state)
    })

    expect(mapped).toBe("michelCOFFEE")
    expect(stateCalc).toBe(1)
    expect(todoCalc).toBe(1)

    state.name = "john"
    expect(mapped).toBe("johnCOFFEE")
    expect(stateCalc).toBe(2)
    expect(todoCalc).toBe(1)

    state.todos[0].title = "TEA"
    expect(mapped).toBe("johnTEA")
    expect(stateCalc).toBe(3)
    expect(todoCalc).toBe(2)

    state.todos.push({ title: "BISCUIT" })
    expect(mapped).toBe("johnTEA,BISCUIT")
    expect(stateCalc).toBe(4)
    expect(todoCalc).toBe(3)

    let tea = state.todos.shift()
    expect(mapped).toBe("johnBISCUIT")
    expect(stateCalc).toBe(5)
    expect(todoCalc).toBe(3)

    expect(unloaded.length).toBe(1)
    expect(unloaded[0][0]).toBe(tea)
    expect(unloaded[0][1]).toBe("TEA")
    expect(m.getObserverTree(tea, "title")).toMatchInlineSnapshot(`
        Object {
          "name": "ObservableObject@1.todos[..].title",
        }
    `)
    expect(m.getObserverTree(state.todos[0], "title")).toMatchInlineSnapshot(`
        Object {
          "name": "ObservableObject@1.todos[..].title",
          "observers": Array [
            Object {
              "name": "Transformer--memoizationId:3",
              "observers": Array [
                Object {
                  "name": "Transformer--memoizationId:1",
                  "observers": Array [
                    Object {
                      "name": "Autorun@2",
                    },
                  ],
                },
              ],
            },
          ],
        }
    `)

    tea.title = "mint"
    expect(mapped).toBe("johnBISCUIT")
    expect(stateCalc).toBe(5)
    expect(todoCalc).toBe(3)

    expect(Object.keys(state.todos[0])).toEqual(["title"])
})

test("createTransformer as off-instance computed", () => {
    let runs = 0

    // observable in closure
    let capitalize = m.observable.box(false)

    let _computeDisplayName = (person) => {
        runs++ // count the runs
        let res = person.firstName + " " + person.lastName
        if (capitalize.get()) return res.toUpperCase()
        return res
    }

    // transformer creates a computed but reuses it for every time the same object is passed in
    let displayName = createTransformer(_computeDisplayName)

    let person1 = m.observable({
        firstName: "Mickey",
        lastName: "Mouse",
    })

    let person2 = m.observable({
        firstName: "Donald",
        lastName: "Duck",
    })

    let persons = m.observable([])
    let displayNames = []

    let disposer = m.autorun(() => {
        displayNames = persons.map((p) => displayName(p))
    })

    expect(runs).toBe(0)
    expect(displayNames).toEqual([])

    persons.push(person1)
    expect(runs).toBe(1)
    expect(displayNames).toEqual(["Mickey Mouse"])

    expect(displayName(person1)).toBe("Mickey Mouse")
    expect(runs).toBe(1)

    persons.push(person2)
    expect(runs).toBe(2)
    expect(displayNames).toEqual(["Mickey Mouse", "Donald Duck"])

    persons.push(person1)
    expect(runs).toBe(2)
    expect(displayNames).toEqual(["Mickey Mouse", "Donald Duck", "Mickey Mouse"])

    person1.firstName = "Minnie"
    expect(runs).toBe(3)
    expect(displayNames).toEqual(["Minnie Mouse", "Donald Duck", "Minnie Mouse"])

    capitalize.set(true)
    expect(runs).toBe(5)
    expect(displayNames).toEqual(["MINNIE MOUSE", "DONALD DUCK", "MINNIE MOUSE"])

    persons.splice(1, 1)
    expect(displayNames).toEqual(["MINNIE MOUSE", "MINNIE MOUSE"])

    person2.firstName = "Dagobert"
    expect(runs).toBe(5)

    disposer()
    person1.lastName = "Maxi"
    expect(runs).toBe(5)

    expect(displayName(person1)).toBe("MINNIE MAXI")
    expect(runs).toBe(6)
})

test("transform into reactive graph", () => {
    function Folder(name) {
        m.extendObservable(this, {
            name: name,
            children: [],
        })
    }

    let _childrenRecalc = 0
    function DerivedFolder(state, baseFolder) {
        this.state = state
        this.baseFolder = baseFolder
        m.extendObservable(this, {
            get name() {
                return this.baseFolder.name
            },
            get isVisible() {
                return (
                    !this.state.filter ||
                    this.name.indexOf(this.state.filter) !== -1 ||
                    this.children.length > 0
                )
            },
            get children() {
                _childrenRecalc++
                return this.baseFolder.children.map(transformFolder).filter(function (folder) {
                    return folder.isVisible === true
                })
            },
        })
    }

    let state: any = m.observable({
        filter: null,
    })

    let _transformCount = 0
    let transformFolder = createTransformer(function (folder) {
        _transformCount++
        // console.log("Transform", folder.name)
        return new DerivedFolder(state, folder)
    })

    state.root = new Folder("/")
    m.autorun(function () {
        state.derived = transformFolder(state.root)
        state.derived.children
    })

    /** test convience */
    function childrenRecalcs() {
        let a = _childrenRecalc
        _childrenRecalc = 0
        return a
    }

    function transformCount() {
        let a = _transformCount
        _transformCount = 0
        return a
    }

    expect(state.derived.name).toBe("/")
    expect(state.derived.children.length).toBe(0)
    expect(transformCount()).toBe(1)
    expect(childrenRecalcs()).toBe(1)

    state.root.children.push(new Folder("hoi"))
    expect(state.derived.name).toBe("/")
    expect(state.derived.children.length).toBe(1)
    expect(state.derived.children[0].name).toBe("hoi")
    expect(transformCount()).toBe(1)
    expect(childrenRecalcs()).toBe(1)

    state.filter = "boe"
    expect(state.derived.name).toBe("/")
    expect(state.derived.isVisible).toBe(false)
    expect(state.derived.children.length).toBe(0)
    expect(transformCount()).toBe(0)
    expect(childrenRecalcs()).toBe(2)

    state.filter = "oi"
    expect(state.derived.name).toBe("/")
    expect(state.derived.isVisible).toBe(true)
    expect(state.derived.children.length).toBe(1)
    expect(state.derived.children[0].name).toBe("hoi")
    expect(transformCount()).toBe(0)
    expect(childrenRecalcs()).toBe(1)
})

// testing: https://github.com/mobxjs/mobx/issues/67
test("transform tree (modifying tree incrementally)", () => {
    const testSet = createTestSet()
    let state = testSet.state
    let stats = testSet.stats
    let TreeNode = testSet.TreeNode
    let DisplayNode = testSet.DisplayNode

    let nodeCreateCount = 0
    let renderCount = 0
    let renderNodeCount = 0

    let transformNode = createTransformer(
        function (node) {
            nodeCreateCount++
            return new DisplayNode(node)
        },
        function cleanup(displayNode, node) {
            displayNode.destroy()
        }
    )

    // transform nodes to renderedNodes
    m.autorun(function () {
        // KM: ideally, I would like to do an assignment here, but it creates a cycle and would need to preserve ms.modifiers.structure:
        //
        // state.renderedNodes = state.root ? state.root.map(transformNode) : [];
        //

        let renderedNodes = state.root ? state.root.map(transformNode) : []
        state.renderedNodes.replace(renderedNodes)
    })

    // render
    m.autorun(function () {
        renderCount++
        renderNodeCount += state.renderedNodes.length
    })

    expect(nodeCreateCount).toBe(0)
    expect(stats.refCount).toBe(0)
    expect(renderCount).toBe(1)
    expect(renderNodeCount).toBe(0)
    expect(state.renderedNodes.length).toBe(0)

    ////////////////////////////////////
    // Incremental Tree
    ////////////////////////////////////

    // initialize root
    let node = new TreeNode("root")
    state.root = node
    expect(nodeCreateCount).toBe(1)
    expect(stats.refCount).toBe(1)
    expect(renderCount).toBe(2)
    expect(renderNodeCount).toBe(1)
    expect(state.renderedNodes.length).toBe(1)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual(["root"])

    // add first child
    state.root.addChild(new TreeNode("root-child-1"))
    expect(nodeCreateCount).toBe(1 + 1)
    expect(stats.refCount).toBe(1 + 1)
    expect(renderCount).toBe(2 + 1)
    expect(renderNodeCount).toBe(1 + 2)
    expect(state.renderedNodes.length).toBe(2)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual(["root", "root-child-1"])

    // add second child
    state.root.addChild(new TreeNode("root-child-2"))
    expect(nodeCreateCount).toBe(1 + 1 + 1)
    expect(stats.refCount).toBe(1 + 1 + 1)
    expect(renderCount).toBe(2 + 1 + 1)
    expect(renderNodeCount).toBe(1 + 2 + 3)
    expect(state.renderedNodes.length).toEqual(3)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-2",
    ])

    // add first child to second child
    node = state.root.find(function (node) {
        return node.name === "root-child-2"
    })
    node.addChild(new TreeNode("root-child-2-child-1"))
    expect(nodeCreateCount).toBe(1 + 1 + 1 + 1)
    expect(stats.refCount).toBe(1 + 1 + 1 + 1)
    expect(renderCount).toBe(2 + 1 + 1 + 1)
    expect(renderNodeCount).toBe(1 + 2 + 3 + 4)
    expect(state.renderedNodes.length).toEqual(4)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    // add first child to first child
    node = state.root.find(function (node) {
        return node.name === "root-child-1"
    })
    node.addChild(new TreeNode("root-child-1-child-1"))
    expect(nodeCreateCount).toBe(1 + 1 + 1 + 1 + 1)
    expect(stats.refCount).toBe(1 + 1 + 1 + 1 + 1)
    expect(renderCount).toBe(2 + 1 + 1 + 1 + 1)
    expect(renderNodeCount).toBe(1 + 2 + 3 + 4 + 5)
    expect(state.renderedNodes.length).toEqual(5)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-1-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    // remove children from first child
    node = state.root.find(function (node) {
        return node.name === "root-child-1"
    })
    node.children.splice(0)
    expect(nodeCreateCount).toBe(1 + 1 + 1 + 1 + 1 + 0)
    expect(stats.refCount).toBe(1 + 1 + 1 + 1 + 1 - 1)
    expect(renderCount).toBe(2 + 1 + 1 + 1 + 1 + 1)
    expect(renderNodeCount).toBe(1 + 2 + 3 + 4 + 5 + 4)
    expect(state.renderedNodes.length).toEqual(4)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    // remove children from first child with no children should be a no-op
    node = state.root.find(function (node) {
        return node.name === "root-child-1"
    })
    node.children.splice(0)
    expect(nodeCreateCount).toBe(1 + 1 + 1 + 1 + 1 + 0 + 0)
    expect(stats.refCount).toBe(1 + 1 + 1 + 1 + 1 - 1 + 0)
    expect(renderCount).toBe(2 + 1 + 1 + 1 + 1 + 1 + 0)
    expect(renderNodeCount).toBe(1 + 2 + 3 + 4 + 5 + 4 + 0)
    expect(state.renderedNodes.length).toEqual(4)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    // remove children from root
    state.root.children.splice(0)
    expect(nodeCreateCount).toBe(1 + 1 + 1 + 1 + 1 + 0 + 0 + 0)
    expect(stats.refCount).toBe(1 + 1 + 1 + 1 + 1 - 1 + 0 - 3)
    expect(renderCount).toBe(2 + 1 + 1 + 1 + 1 + 1 + 0 + 1)
    expect(renderNodeCount).toBe(1 + 2 + 3 + 4 + 5 + 4 + 0 + 1)
    expect(state.renderedNodes.length).toEqual(1)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual(["root"])

    // teardown
    state.root = null
    expect(nodeCreateCount).toBe(1 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + 0)
    expect(stats.refCount).toBe(0)
    expect(renderCount).toBe(2 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1)
    expect(renderNodeCount).toBe(1 + 2 + 3 + 4 + 5 + 4 + 0 + 1 + 0)
    expect(state.renderedNodes.length).toEqual(0)
})

test("transform tree (modifying tree incrementally)", () => {
    const testSet = createTestSet()
    let state = testSet.state
    let stats = testSet.stats
    let TreeNode = testSet.TreeNode
    let DisplayNode = testSet.DisplayNode

    let nodeCreateCount = 0
    let renderCount = 0
    let renderNodeCount = 0

    let transformNode = createTransformer(
        function (node) {
            nodeCreateCount++
            return new DisplayNode(node)
        },
        function cleanup(displayNode, node) {
            displayNode.destroy()
        }
    )

    // transform nodes to renderedNodes
    m.autorun(function () {
        let renderedNodes = state.root ? state.root.map(transformNode) : []
        state.renderedNodes.replace(renderedNodes)
    })

    // render
    m.autorun(function () {
        renderCount++
        renderNodeCount += state.renderedNodes.length
    })

    // setup
    let node = new TreeNode("root-1")
    state.root = node
    expect(nodeCreateCount).toBe(1)
    expect(stats.refCount).toBe(1)
    expect(renderCount).toBe(2)
    expect(renderNodeCount).toBe(1)
    expect(state.renderedNodes.length).toEqual(1)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual(["root-1"])

    ////////////////////////////////////
    // Batch Tree (Partial)
    ////////////////////////////////////

    // add partial tree as a batch
    let children = []
    children.push(new TreeNode("root-1-child-1b"))
    children[0].addChild(new TreeNode("root-1-child-1b-child-1"))
    children.push(new TreeNode("root-1-child-2b"))
    children[1].addChild(new TreeNode("root-1-child-2b-child-1"))
    state.root.addChildren(children)
    expect(nodeCreateCount).toBe(1 + 4)
    expect(stats.refCount).toBe(1 + 4)
    expect(renderCount).toBe(2 + 1)
    expect(renderNodeCount).toBe(1 + 5)
    expect(state.renderedNodes.length).toEqual(5)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root-1",
        "root-1-child-1b",
        "root-1-child-1b-child-1",
        "root-1-child-2b",
        "root-1-child-2b-child-1",
    ])

    // remove root-1
    state.root = null
    expect(nodeCreateCount).toBe(1 + 4 + 0)
    expect(stats.refCount).toBe(1 + 4 - 5)
    expect(renderCount).toBe(2 + 1 + 1)
    expect(renderNodeCount).toBe(1 + 5 + 0)
    expect(state.renderedNodes.length).toEqual(0)

    ////////////////////////////////////
    // Batch Tree (Full)
    ////////////////////////////////////

    // add full tree as a batch
    node = new TreeNode("root-2")
    node.addChild(new TreeNode("root-2-child-1"))
    node.children[0].addChild(new TreeNode("root-2-child-1-child-1"))
    node.addChild(new TreeNode("root-2-child-2"))
    node.children[1].addChild(new TreeNode("root-2-child-2-child-1"))
    state.root = node
    expect(nodeCreateCount).toBe(1 + 4 + 0 + 5)
    expect(stats.refCount).toBe(1 + 4 - 5 + 5)
    expect(renderCount).toBe(2 + 1 + 1 + 1)
    expect(renderNodeCount).toBe(1 + 5 + 0 + 5)
    expect(state.renderedNodes.length).toEqual(5)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root-2",
        "root-2-child-1",
        "root-2-child-1-child-1",
        "root-2-child-2",
        "root-2-child-2-child-1",
    ])

    // teardown
    state.root = null
    expect(nodeCreateCount).toBe(1 + 4 + 0 + 5 + 0)
    expect(stats.refCount).toBe(0)
    expect(renderCount).toBe(2 + 1 + 1 + 1 + 1)
    expect(renderNodeCount).toBe(1 + 5 + 0 + 5 + 0)
    expect(state.renderedNodes.length).toEqual(0)
})

test("transform tree (modifying expanded)", () => {
    const testSet = createTestSet()
    let state = testSet.state
    let stats = testSet.stats
    let TreeNode = testSet.TreeNode
    let DisplayNode = testSet.DisplayNode

    let nodeCreateCount = 0
    let renderCount = 0
    let renderNodeCount = 0

    let transformNode = createTransformer(
        function (node) {
            nodeCreateCount++
            return new DisplayNode(node)
        },
        function cleanup(displayNode, node) {
            displayNode.destroy()
        }
    )

    // transform nodes to renderedNodes
    m.autorun(function () {
        let renderedNodes = state.root ? state.root.transform(transformNode) : []
        state.renderedNodes.replace(renderedNodes)
    })

    // render
    m.autorun(function () {
        renderCount++
        renderNodeCount += state.renderedNodes.length
    })

    // patch for collapsed
    TreeNode.prototype.transform = function (iteratee, results) {
        if (this.parent && state.collapsed.has(this.parent.path())) return results || [] // not visible

        results = results || []
        results.push(iteratee(this))
        this.children.forEach(function (child) {
            child.transform(iteratee, results)
        })
        return results
    }

    // setup
    let node = new TreeNode("root")
    node.addChild(new TreeNode("root-child-1"))
    node.children[0].addChild(new TreeNode("root-child-1-child-1"))
    node.addChild(new TreeNode("root-child-2"))
    node.children[1].addChild(new TreeNode("root-child-2-child-1"))
    state.root = node
    expect(nodeCreateCount).toBe(5)
    expect(stats.refCount).toBe(5)
    expect(renderCount).toBe(2)
    expect(renderNodeCount).toBe(5)
    expect(state.renderedNodes.length).toEqual(5)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-1-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    ////////////////////////////////////
    // Expanded
    ////////////////////////////////////

    // toggle root to collapsed
    state.renderedNodes[0].toggleCollapsed()
    expect(nodeCreateCount).toBe(5 + 0)
    expect(stats.refCount).toBe(5 - 4)
    expect(renderCount).toBe(2 + 1)
    expect(renderNodeCount).toBe(5 + 1)
    expect(state.renderedNodes.length).toEqual(1)
    expect(state.renderedNodes.map(pluckFn("node"))).not.toEqual(state.root.map(identity)) // not a direct map of the tree nodes
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual(["root"])

    // toggle root to expanded
    state.renderedNodes[0].toggleCollapsed()
    expect(nodeCreateCount).toBe(5 + 0 + 4)
    expect(stats.refCount).toBe(5 - 4 + 4)
    expect(renderCount).toBe(2 + 1 + 1)
    expect(renderNodeCount).toBe(5 + 1 + 5)
    expect(state.renderedNodes.length).toEqual(5)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-1-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    // toggle child-1 collapsed
    state.renderedNodes[1].toggleCollapsed()
    expect(nodeCreateCount).toBe(5 + 0 + 4 + 0)
    expect(stats.refCount).toBe(5 - 4 + 4 - 1)
    expect(renderCount).toBe(2 + 1 + 1 + 1)
    expect(renderNodeCount).toBe(5 + 1 + 5 + 4)
    expect(state.renderedNodes.length).toEqual(4)
    expect(state.renderedNodes.map(pluckFn("node"))).not.toEqual(state.root.map(identity)) // not a direct map of the tree nodes
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    // toggle child-2-child-1 collapsed should be a no-op
    state.renderedNodes[state.renderedNodes.length - 1].toggleCollapsed()
    expect(nodeCreateCount).toBe(5 + 0 + 4 + 0 + 0)
    expect(stats.refCount).toBe(5 - 4 + 4 - 1 + 0)
    expect(renderCount).toBe(2 + 1 + 1 + 1 + 0)
    expect(renderNodeCount).toBe(5 + 1 + 5 + 4 + 0)
    expect(state.renderedNodes.length).toEqual(4)
    expect(state.renderedNodes.map(pluckFn("node"))).not.toEqual(state.root.map(identity)) // not a direct map of the tree nodes
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    // teardown
    state.root = null
    expect(nodeCreateCount).toBe(5 + 0 + 4 + 0 + 0 + 0)
    expect(stats.refCount).toBe(0)
    expect(renderCount).toBe(2 + 1 + 1 + 1 + 0 + 1)
    expect(renderNodeCount).toBe(5 + 1 + 5 + 4 + 0 + 0)
    expect(state.renderedNodes.length).toEqual(0)
})

test("transform tree (modifying render observable)", () => {
    const testSet = createTestSet()
    let state = testSet.state
    let stats = testSet.stats
    let TreeNode = testSet.TreeNode
    let DisplayNode = testSet.DisplayNode

    let nodeCreateCount = 0
    let renderCount = 0
    let renderNodeCount = 0
    let renderIconCalc = 0

    let transformNode = createTransformer(
        function (node) {
            nodeCreateCount++
            return new DisplayNode(node)
        },
        function cleanup(displayNode, node) {
            displayNode.destroy()
        }
    )

    // transform nodes to renderedNodes
    m.autorun(function () {
        let renderedNodes = state.root ? state.root.transform(transformNode) : []
        state.renderedNodes.replace(renderedNodes)
    })

    // render
    m.autorun(function () {
        renderCount++
        renderNodeCount += state.renderedNodes.length
    })

    // custom transform
    TreeNode.prototype.transform = function (iteratee, results) {
        node.icon.get() // icon dependency

        results = results || []
        results.push(iteratee(this))
        this.children.forEach(function (child) {
            child.transform(iteratee, results)
        })
        return results
    }

    // setup
    let node = new TreeNode("root")
    node.addChild(new TreeNode("root-child-1"))
    node.children[0].addChild(new TreeNode("root-child-1-child-1"))
    node.addChild(new TreeNode("root-child-2"))
    node.children[1].addChild(new TreeNode("root-child-2-child-1"))
    state.root = node
    expect(nodeCreateCount).toBe(5)
    expect(stats.refCount).toBe(5)
    expect(renderCount).toBe(2)
    expect(renderNodeCount).toBe(5)
    expect(state.renderedNodes.length).toEqual(5)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-1-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    ////////////////////////////////////
    // Icon
    ////////////////////////////////////

    // update root icon
    state.root.icon.set("file")
    expect(nodeCreateCount).toBe(5 + 0)
    expect(stats.refCount).toBe(5 + 0)
    expect(renderCount).toBe(2 + 1)
    expect(renderNodeCount).toBe(5 + 5)
    expect(state.renderedNodes.length).toEqual(5)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-1-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    // teardown
    state.root = null
    expect(nodeCreateCount).toBe(5 + 0 + 0)
    expect(stats.refCount).toBe(0)
    expect(renderCount).toBe(2 + 1 + 1)
    expect(renderNodeCount).toBe(5 + 5 + 0)
    expect(state.renderedNodes.length).toEqual(0)
})

test("transform tree (modifying render-only observable)", () => {
    const testSet = createTestSet()
    let state = testSet.state
    let stats = testSet.stats
    let TreeNode = testSet.TreeNode
    let DisplayNode = testSet.DisplayNode

    let nodeCreateCount = 0
    let renderCount = 0
    let renderNodeCount = 0
    let renderIconCalc = 0

    let transformNode = createTransformer(
        function (node) {
            nodeCreateCount++
            return new DisplayNode(node)
        },
        function cleanup(displayNode, node) {
            displayNode.destroy()
        }
    )

    // transform nodes to renderedNodes
    m.autorun(function () {
        let renderedNodes = state.root ? state.root.map(transformNode) : []
        state.renderedNodes.replace(renderedNodes)
    })

    // render
    m.autorun(function () {
        renderCount++
        renderNodeCount += state.renderedNodes.length

        state.renderedNodes.forEach(function (renderedNode) {
            m.autorun(function () {
                renderIconCalc++
                renderedNode.node.icon.get() // icon dependency
            })
        })
    })

    // setup
    let node = new TreeNode("root")
    node.addChild(new TreeNode("root-child-1"))
    node.children[0].addChild(new TreeNode("root-child-1-child-1"))
    node.addChild(new TreeNode("root-child-2"))
    node.children[1].addChild(new TreeNode("root-child-2-child-1"))
    state.root = node
    expect(nodeCreateCount).toBe(5)
    expect(stats.refCount).toBe(5)
    expect(renderCount).toBe(2)
    expect(renderNodeCount).toBe(5)
    expect(renderIconCalc).toBe(5)
    expect(state.renderedNodes.length).toEqual(5)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-1-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    ////////////////////////////////////
    // Icon
    ////////////////////////////////////

    // update root icon
    state.root.icon.set("file")
    expect(nodeCreateCount).toBe(5 + 0)
    expect(stats.refCount).toBe(5 + 0)
    expect(renderCount).toBe(2 + 0)
    expect(renderNodeCount).toBe(5 + 0)
    expect(renderIconCalc).toBe(5 + 1)
    expect(state.renderedNodes.length).toEqual(5)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-1-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    // teardown
    state.root = null
    expect(nodeCreateCount).toBe(5 + 0 + 0)
    expect(stats.refCount).toBe(0)
    expect(renderCount).toBe(2 + 0 + 1)
    expect(renderNodeCount).toBe(5 + 0 + 0)
    expect(renderIconCalc).toBe(5 + 1 + 0)
    expect(state.renderedNodes.length).toEqual(0)
})

test("transform tree (static tags / global filter only)", () => {
    const testSet = createTestSet()
    let state = testSet.state
    let stats = testSet.stats
    let TreeNode = testSet.TreeNode
    let DisplayNode = testSet.DisplayNode

    let nodeCreateCount = 0
    let renderCount = 0
    let renderNodeCount = 0

    let transformNode = createTransformer(
        function (node) {
            nodeCreateCount++
            return new DisplayNode(node)
        },
        function cleanup(displayNode, node) {
            displayNode.destroy()
        }
    )

    // transform nodes to renderedNodes
    m.autorun(function () {
        let renderedNodes = state.root ? state.root.transform(transformNode) : []
        state.renderedNodes.replace(renderedNodes)
    })

    // render
    m.autorun(function () {
        renderCount++
        renderNodeCount += state.renderedNodes.length
    })

    // no tags
    state.tags = m.observable.array([])

    // custom transform
    TreeNode.prototype.transform = function (iteratee, results) {
        results = results || []
        if (!state.tags.length || intersection(state.tags, this.tags).length)
            results.push(iteratee(this))
        this.children.forEach(function (child) {
            child.transform(iteratee, results)
        })
        return results
    }

    // setup
    let node = new TreeNode("root", { tags: [1] })
    node.addChild(new TreeNode("root-child-1", { tags: [2] }))
    node.children[0].addChild(new TreeNode("root-child-1-child-1", { tags: [3] }))
    node.addChild(new TreeNode("root-child-2", { tags: [2] }))
    node.children[1].addChild(new TreeNode("root-child-2-child-1", { tags: [3] }))
    state.root = node
    expect(nodeCreateCount).toBe(5)
    expect(stats.refCount).toBe(5)
    expect(renderCount).toBe(2)
    expect(renderNodeCount).toBe(5)
    expect(state.renderedNodes.length).toEqual(5)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-1-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    ////////////////////////////////////
    // Tags
    ////////////////////////////////////

    // add search tag
    state.tags.push(2)
    expect(nodeCreateCount).toBe(5 + 0)
    expect(stats.refCount).toBe(5 - 3)
    expect(renderCount).toBe(2 + 1)
    expect(renderNodeCount).toBe(5 + 2)
    expect(state.renderedNodes.length).toEqual(2)
    expect(state.renderedNodes.map(pluckFn("node"))).not.toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual(["root-child-1", "root-child-2"])

    // add search tag
    state.tags.push(3)
    expect(nodeCreateCount).toBe(5 + 0 + 2)
    expect(stats.refCount).toBe(5 - 3 + 2)
    expect(renderCount).toBe(2 + 1 + 1)
    expect(renderNodeCount).toBe(5 + 2 + 4)
    expect(state.renderedNodes.length).toEqual(4)
    expect(state.renderedNodes.map(pluckFn("node"))).not.toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root-child-1",
        "root-child-1-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    // add search tag
    state.tags.push(1)
    expect(nodeCreateCount).toBe(5 + 0 + 2 + 1)
    expect(stats.refCount).toBe(5 - 3 + 2 + 1)
    expect(renderCount).toBe(2 + 1 + 1 + 1)
    expect(renderNodeCount).toBe(5 + 2 + 4 + 5)
    expect(state.renderedNodes.length).toEqual(5)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-1-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    // remove search tags
    state.tags.splice(0, 2)
    expect(nodeCreateCount).toBe(5 + 0 + 2 + 1 + 0)
    expect(stats.refCount).toBe(5 - 3 + 2 + 1 - 4)
    expect(renderCount).toBe(2 + 1 + 1 + 1 + 1)
    expect(renderNodeCount).toBe(5 + 2 + 4 + 5 + 1)
    expect(state.renderedNodes.length).toEqual(1)
    expect(state.renderedNodes.map(pluckFn("node"))).not.toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual(["root"])

    // teardown
    state.root = null
    expect(nodeCreateCount).toBe(5 + 0 + 2 + 1 + 0 + 0)
    expect(stats.refCount).toBe(0)
    expect(renderCount).toBe(2 + 1 + 1 + 1 + 1 + 1)
    expect(renderNodeCount).toBe(5 + 2 + 4 + 5 + 1 + 0)
    expect(state.renderedNodes.length).toEqual(0)
})

test("transform tree (dynamic tags - peek / rebuild)", () => {
    const testSet = createTestSet()
    let state = testSet.state
    let stats = testSet.stats
    let TreeNode = testSet.TreeNode
    let DisplayNode = testSet.DisplayNode

    let nodeCreateCount = 0
    let renderCount = 0
    let renderNodeCount = 0

    let transformNode = createTransformer(
        function (node) {
            nodeCreateCount++
            return new DisplayNode(node)
        },
        function cleanup(displayNode, node) {
            displayNode.destroy()
        }
    )

    // transform nodes to renderedNodes
    m.autorun(function () {
        let renderedNodes = state.root ? state.root.transform(transformNode) : []
        state.renderedNodes.replace(renderedNodes)
    })

    // render
    m.autorun(function () {
        renderCount++
        renderNodeCount += state.renderedNodes.length
    })

    // no tags
    state.tags = m.observable.array([])

    // custom transform
    TreeNode.prototype.transform = function (iteratee, results) {
        results = results || []
        if (!state.tags.length || intersection(state.tags, this.tags).length)
            results.push(iteratee(this))
        this.children.forEach(function (child) {
            child.transform(iteratee, results)
        })
        return results
    }

    // setup
    let node = new TreeNode("root", { tags: m.observable.array([1]) })
    node.addChild(new TreeNode("root-child-1", { tags: m.observable.array([2]) }))
    node.children[0].addChild(
        new TreeNode("root-child-1-child-1", { tags: m.observable.array([3]) })
    )
    node.addChild(new TreeNode("root-child-2", { tags: m.observable.array([2]) }))
    node.children[1].addChild(
        new TreeNode("root-child-2-child-1", { tags: m.observable.array([3]) })
    )
    state.root = node
    expect(nodeCreateCount).toBe(5)
    expect(stats.refCount).toBe(5)
    expect(renderCount).toBe(2)
    expect(renderNodeCount).toBe(5)
    expect(state.renderedNodes.length).toEqual(5)
    expect(state.renderedNodes.map(pluckFn("node"))).toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-1-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    ////////////////////////////////////
    // Tags
    ////////////////////////////////////

    // add search tag
    state.tags.push(2)
    expect(nodeCreateCount).toBe(5 + 0)
    expect(stats.refCount).toBe(5 - 3)
    expect(renderCount).toBe(2 + 1)
    expect(renderNodeCount).toBe(5 + 2)
    expect(state.renderedNodes.length).toEqual(2)
    expect(state.renderedNodes.map(pluckFn("node"))).not.toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual(["root-child-1", "root-child-2"])

    // modify search tag
    state.root.tags.push(2)
    expect(nodeCreateCount).toBe(5 + 0 + 1)
    expect(stats.refCount).toBe(5 - 3 + 1)
    expect(renderCount).toBe(2 + 1 + 1)
    expect(renderNodeCount).toBe(5 + 2 + 3)
    expect(state.renderedNodes.length).toEqual(3)
    expect(state.renderedNodes.map(pluckFn("node"))).not.toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1",
        "root-child-2",
    ])

    // perform multiple search tag operations
    m.transaction(function () {
        state.root.tags.shift() // no-op
        state.root
            .find(function (node) {
                return node.name === "root-child-1"
            })
            .tags.splice(0)
        state.root
            .find(function (node) {
                return node.name === "root-child-1-child-1"
            })
            .tags.push(2)
        state.root
            .find(function (node) {
                return node.name === "root-child-2-child-1"
            })
            .tags.push(2)
    })
    expect(nodeCreateCount).toBe(5 + 0 + 1 + 2)
    expect(stats.refCount).toBe(5 - 3 + 1 + 1)
    expect(renderCount).toBe(2 + 1 + 1 + 1)
    expect(renderNodeCount).toBe(5 + 2 + 3 + 4)
    expect(state.renderedNodes.length).toEqual(4)
    expect(state.renderedNodes.map(pluckFn("node"))).not.toEqual(state.root.map(identity))
    expect(state.renderedNodes.map(pluckFn("node.name"))).toEqual([
        "root",
        "root-child-1-child-1",
        "root-child-2",
        "root-child-2-child-1",
    ])

    // teardown
    state.root = null
    expect(nodeCreateCount).toBe(5 + 0 + 1 + 2 + 0)
    expect(stats.refCount).toBe(0)
    expect(renderCount).toBe(2 + 1 + 1 + 1 + 1)
    expect(renderNodeCount).toBe(5 + 2 + 3 + 4 + 0)
    expect(state.renderedNodes.length).toEqual(0)
})

// https://github.com/mobxjs/mobx/issues/886
test("transform with primitive key", () => {
    function Bob() {
        this.num = Math.floor(Math.random() * 1000)
        m.extendObservable(this, {
            get name() {
                return "Bob" + this.num
            },
        })
    }

    let observableBobs = m.observable([])
    let bobs = []

    let bobFactory = createTransformer(function (key) {
        return new Bob()
    })

    m.autorun(function () {
        bobs = observableBobs.map(function (bob) {
            return bobFactory(bob)
        })
    })

    observableBobs.push("Bob1")
    observableBobs.push("Bob1")
    expect(bobs[0].name).toBe(bobs[1].name)

    observableBobs.clear()
    observableBobs.push("Bob1")
    observableBobs.push("Bob2")
    expect(bobs[0].name).not.toEqual(bobs[1].name)

    observableBobs.clear()
    observableBobs.push(1)
    observableBobs.push(1)
    expect(bobs[0].name).toEqual(bobs[1].name)

    observableBobs.clear()
    observableBobs.push(1)
    observableBobs.push(2)
    expect(bobs[0].name).not.toEqual(bobs[1].name)
})

// https://github.com/mobxjs/mobx-utils/issues/134
test("transform with mixed key types", () => {
    const identityTransformer = createTransformer((a) => a)

    let transformedStringKey
    let transformedNumberKey
    m.autorun(() => {
        transformedStringKey = identityTransformer("1")
        transformedNumberKey = identityTransformer(1)
    })

    expect(transformedStringKey).not.toEqual(transformedNumberKey)
})

import * as intersection from "lodash.intersection"

function pluckFn(key) {
    return function (obj) {
        let keys = key.split("."),
            value = obj
        for (let i = 0, l = keys.length; i < l; i++) {
            if (!value) return
            value = value[keys[i]]
        }
        return value
    }
}

function identity(value) {
    return value
}

function createTestSet(): any {
    let testSet: any = {}

    let state = (testSet.state = m.observable({
        root: null,
        renderedNodes: m.observable.array(),
        collapsed: m.observable.map(), // KM: ideally, I would like to use a set
    }))

    let stats = (testSet.stats = {
        refCount: 0,
    })

    let TreeNode = (testSet.TreeNode = function (name, extensions) {
        this.children = m.observable.array()
        this.icon = m.observable.box("folder")

        this.parent = null // not observed
        this.name = name // not observed

        // optional extensions
        if (extensions) {
            for (let key in extensions) {
                this[key] = extensions[key]
            }
        }
    })
    TreeNode.prototype.addChild = function (node) {
        node.parent = this
        this.children.push(node)
    }
    TreeNode.prototype.addChildren = function (nodes) {
        let _this = this
        nodes.map(function (node) {
            node.parent = _this
        })
        this.children.splice.apply(this.children, [this.children.length, 0].concat(nodes))
    }

    TreeNode.prototype.path = function () {
        let node = this,
            parts = []
        while (node) {
            parts.push(node.name)
            node = node.parent
        }
        return parts.join("/")
    }

    TreeNode.prototype.map = function (iteratee, results) {
        results = results || []
        results.push(iteratee(this))
        this.children.forEach(function (child) {
            child.map(iteratee, results)
        })
        return results
    }

    TreeNode.prototype.find = function (predicate) {
        if (predicate(this)) return this

        let result
        for (let i = 0, l = this.children.length; i < l; i++) {
            result = this.children[i].find(predicate)
            if (result) return result
        }
        return null
    }

    let DisplayNode = (testSet.DisplayNode = function (node) {
        stats.refCount++
        this.node = node
    })
    DisplayNode.prototype.destroy = function () {
        stats.refCount--
    }

    DisplayNode.prototype.toggleCollapsed = function () {
        let path = this.node.path()
        state.collapsed.has(path) ? state.collapsed.delete(path) : state.collapsed.set(path, true) // KM: ideally, I would like to use a set
    }

    return testSet
}

it("should throw error when passed invalid param type", () => {
    const transformedFn = createTransformer((obj: any) => obj)
    const validParams = [[], {}, jest.fn(), 1, "string"]
    const invalidParams = [null, undefined, Symbol("A"), true]

    validParams.forEach((obj) => {
        expect(() => {
            transformedFn(obj)
        }).not.toThrowError()
    })

    invalidParams.forEach((obj) => {
        expect(() => {
            transformedFn(obj)
        }).toThrowErrorMatchingSnapshot()
    })
})
test("should respect onCleanup argument", () => {
    let state = m.observable({
        todos: [{ title: "coffee" }],
        name: "michel",
    })
    let mapped
    let unloaded = []
    let objectName
    let transformState = createTransformer(function (state: any) {
        return state.name + state.todos.map(transformTodo).join(",")
    })
    let transformTodo = createTransformer(
        function (todo: any) {
            return todo.title.toUpperCase()
        },
        {
            onCleanup: function (text, value) {
                unloaded.push([text, value])
            },
            debugNameGenerator: function (todo) {
                return todo.title.toUpperCase() + "-DEBUG"
            },
        }
    )
    m.autorun(function () {
        mapped = transformState(state)
    })
    state.todos.shift()
    expect(unloaded.length).toBe(1)
})

test("should respect debugNameGenerator argument", () => {
    let state = m.observable.map({
        title: "coffee",
        name: "michel",
    })
    let mapped
    let objectName
    let transformTodo = createTransformer(
        function (state: any) {
            return state.get("title").toUpperCase()
        },
        {
            debugNameGenerator: function (state) {
                return state.get("title").toUpperCase() + "-DEBUG"
            },
        }
    )
    m.autorun(function () {
        mapped = transformTodo(state)
    })
    state.set("name", "BISCUIT")
    objectName = m.getObserverTree(state, "title").observers[0].name
    expect(objectName).toBe("COFFEE-DEBUG")
})

test("supports computed value options", () => {
    const events: number[][] = []
    const xs = m.observable([1, 2, 3])
    const xsLessThan = createTransformer((n) => xs.filter((x) => x < n), {
        equals: m.comparer.structural,
    })

    m.autorun(() => events.push(xsLessThan(3)))
    expect(events).toEqual([[1, 2]])

    events.length = 0
    xs.push(4)
    expect(events).toEqual([])
})

test("should not memorize outside reactive context", () => {
    let transformer = jest.fn((input: string) => input.toLowerCase())
    let onCleanup = jest.fn()
    let stubTransformer = createTransformer(transformer, onCleanup)

    stubTransformer("HELLO")
    expect(transformer).toHaveBeenCalledWith("HELLO")
    expect(onCleanup).toHaveBeenCalledWith("hello", "HELLO")
    transformer.mockClear()
    onCleanup.mockClear()

    stubTransformer("HELLO")
    expect(transformer).toHaveBeenCalledWith("HELLO")
    expect(onCleanup).toHaveBeenCalledWith("hello", "HELLO")
    transformer.mockClear()
    onCleanup.mockClear()
})


text:
namespace WinApiNet.Shell.Console
{
    using System.Runtime.InteropServices;

    /// <summary>
    /// Contains information about the console history.
    /// </summary>
    [StructLayout(LayoutKind.Sequential)]
    public class ConsoleHistoryInfo
    {
        /// <summary>
        /// The size of the structure, in bytes.
        /// </summary>
        public uint cbSize = (ushort)Marshal.SizeOf(typeof(ConsoleHistoryInfo));

        /// <summary>
        /// The number of commands kept in each history buffer.
        /// </summary>
        public uint HistoryBufferSize;

        /// <summary>
        /// The number of history buffers kept for this console process.
        /// </summary>
        public uint NumberOfHistoryBuffers;

        /// <summary>
        /// This parameter can be zero or values from the <see cref="ConsoleHistoryInfoFlags"/> enumeration.
        /// </summary>
        public ConsoleHistoryInfoFlags dwFlags;
    }
}


text:
<? session_start();
if ($_SESSION['nis'])
{
?>
<?php error_reporting(E_ALL ^ (E_NOTICE | E_WARNING)); ?>

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

    <title>Selamat Tinggal</title>
	<link href='images/osis.png' rel='shortcut icon'>

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

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

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

                </button>

                	PILKOSIS

                        Home

                        Tutorial Pemilihan

                        Contact Us!

                        Tentang Aplikasi

						Akun

logout

Aplikasi Pilkosis

Aplikasi Pemilihan Ketua & Wakil Ketua Osis Online

SMK Negeri 1 Kebumen

Khususnya bagi Siswa SMK Negeri 1 Kebumen

Tujuan

Agar lebih efisien dalam pemiliihan

					Previous

					Next

Komentar Pemilih

						Terimakasih..!!

						Anda Telah Berpartisipasi,  Dan Telah Menggunakan Hak Suara Dengan Sebaik-Baiknya Dalam Pemilihan Calon Ketua Dan Wakil Ketua OSIS SMK N 1 Kebumen

						Periode 2016/2017
						Untuk Logout Silahkan Klik Tulisan "Account", Lalu Klik Tulisan  "Logout"

Terms & Conditions | Privacy Policy | Contact

Copyright © OSIS_TEAM 2016/2017

 <?
}else{
	?>
	<?
}
?>


text:
var x = null;                        // error at "x"
var x1 = undefined;		             // error at "x1"
var widenArray = [null, undefined];  // error at "widenArray"
var emptyArray = [];		         // error at "emptyArray"

// these should not be error
class AnimalObj {
      x:any;
}
var foo = 5;
var bar = "Hello World";
var foo1: any = null;
var foo2: any = undefined;
var temp: number = 5;
var c: AnimalObj = { x: null };
var array1 = ["Bob",2];
var array2: any[] = [];
var array3: any[] = [null, undefined];
var array4: number[] = [null, undefined];
var array5 = <any[]>[null, undefined];

var objLit: { new (n: number): any; };
function anyReturnFunc(): any { }
var obj0 = new objLit(1);
var obj1 = anyReturnFunc();

//// [implicitAnyWidenToAny.js]
// these should be errors
var x = null; // error at "x"
var x1 = undefined; // error at "x1"
var widenArray = [null, undefined]; // error at "widenArray"
var emptyArray = []; // error at "emptyArray"
// these should not be error
var AnimalObj = (function () {
    function AnimalObj() {
    }
    return AnimalObj;
})();
var foo = 5;
var bar = "Hello World";
var foo1 = null;
var foo2 = undefined;
var temp = 5;
var c = { x: null };
var array1 = ["Bob", 2];
var array2 = [];
var array3 = [null, undefined];
var array4 = [null, undefined];
var array5 = [null, undefined];
var objLit;
function anyReturnFunc() {
}
var obj0 = new objLit(1);
var obj1 = anyReturnFunc();


text:
package com.emitrom.ti4j.mobile.client.core.events;

import com.google.gwt.core.client.JavaScriptObject;

public class OrientationChangeEvent extends TiEvent {

    public static final String ORIENTATION_CHANGE = "orientationchange";

    protected OrientationChangeEvent(JavaScriptObject obj) {
        jsObj = obj;
    }

    /**
     * the orientation constant
     */
    public final native int getOrientation() /*-{
		var jso = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
		return jso.orientation;
    }-*/;

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Mycosphaerella trifolii f. trifolii

### Remarks
null


text:
$ErrorActionPreference = "Stop"

$result = @{
    changed = $false
}

Function Assert-Equals($actual, $expected) {
    if ($actual -cne $expected) {
        $call_stack = (Get-PSCallStack)[1]
        $error_msg = "AssertionError:`r`nActual: `"$actual`" != Expected: `"$expected`"`r`nLine: $($call_stack.ScriptLineNumber), Method: $($call_stack.Position.Text)"
        Fail-Json -obj $result -message $error_msg
    }
}

Function Get-PagefilePath() {
    $pagefile = $null
    $cs = Get-CimInstance -ClassName Win32_ComputerSystem
    if ($cs.AutomaticManagedPagefile) {
        $pagefile = "$($env:SystemRoot.Substring(0, 1)):\pagefile.sys"
    } else {
        $pf = Get-CimInstance -ClassName Win32_PageFileSetting
        if ($null -ne $pf) {
            $pagefile = $pf[0].Name
        }
    }
    return $pagefile
}

$pagefile = Get-PagefilePath
if ($pagefile) {
    # Test-AnsiblePath Hidden system file
    $actual = Test-AnsiblePath -Path $pagefile
    Assert-Equals -actual $actual -expected $true

    # Get-AnsibleItem file
    $actual = Get-AnsibleItem -Path $pagefile
    Assert-Equals -actual $actual.FullName -expected $pagefile
    Assert-Equals -actual $actual.Attributes.HasFlag([System.IO.FileAttributes]::Directory) -expected $false
    Assert-Equals -actual $actual.Exists -expected $true
}

# Test-AnsiblePath File that doesn't exist
$actual = Test-AnsiblePath -Path C:\fakefile
Assert-Equals -actual $actual -expected $false

# Test-AnsiblePath Directory that doesn't exist
$actual = Test-AnsiblePath -Path C:\fakedirectory
Assert-Equals -actual $actual -expected $false

# Test-AnsiblePath file in non-existant directory
$actual = Test-AnsiblePath -Path C:\fakedirectory\fakefile.txt
Assert-Equals -actual $actual -expected $false

# Test-AnsiblePath Normal directory
$actual = Test-AnsiblePath -Path C:\Windows
Assert-Equals -actual $actual -expected $true

# Test-AnsiblePath Normal file
$actual = Test-AnsiblePath -Path C:\Windows\System32\kernel32.dll
Assert-Equals -actual $actual -expected $true

# Test-AnsiblePath fails with wildcard
$failed = $false
try {
    Test-AnsiblePath -Path C:\Windows\*.exe
} catch {
    $failed = $true
    Assert-Equals -actual $_.Exception.Message -expected "Exception calling `"GetAttributes`" with `"1`" argument(s): `"Illegal characters in path.`""
}
Assert-Equals -actual $failed -expected $true

# Test-AnsiblePath on non file PS Provider object
$actual = Test-AnsiblePath -Path Cert:\LocalMachine\My
Assert-Equals -actual $actual -expected $true

# Test-AnsiblePath on environment variable
$actual = Test-AnsiblePath -Path env:SystemDrive
Assert-Equals -actual $actual -expected $true

# Test-AnsiblePath on environment variable that does not exist
$actual = Test-AnsiblePath -Path env:FakeEnvValue
Assert-Equals -actual $actual -expected $false

# Get-AnsibleItem doesn't exist with -ErrorAction SilentlyContinue param
$actual = Get-AnsibleItem -Path C:\fakefile -ErrorAction SilentlyContinue
Assert-Equals -actual $actual -expected $null

# Get-AnsibleItem directory
$actual = Get-AnsibleItem -Path C:\Windows
Assert-Equals -actual $actual.FullName -expected C:\Windows
Assert-Equals -actual $actual.Attributes.HasFlag([System.IO.FileAttributes]::Directory) -expected $true
Assert-Equals -actual $actual.Exists -expected $true

# ensure Get-AnsibleItem doesn't fail in a try/catch and -ErrorAction SilentlyContinue - stop's a trap from trapping it
try {
    $actual = Get-AnsibleItem -Path C:\fakepath -ErrorAction SilentlyContinue
} catch {
    Fail-Json -obj $result -message "this should not fire"
}
Assert-Equals -actual $actual -expected $null

$result.data = "success"
Exit-Json -obj $result


text:
cask "superhuman" do
  arch = Hardware::CPU.intel? ? "" : "-arm64"

  version "11.0.36"

  if Hardware::CPU.intel?
    sha256 "ccc9c8526757dad96fab06ab29e7a0b955a2f9658553212c4679262afef020e5"
  else
    sha256 "0285fcabbc6e7dafc3f94185e1be0c32804f9bea692136707cf3cfafb245d22b"
  end

  url "https://storage.googleapis.com/download.superhuman.com/supertron-update/Superhuman-#{version}#{arch}-latest-mac.zip",
      verified: "storage.googleapis.com/download.superhuman.com/"
  name "Superhuman"
  desc "Email client"
  homepage "https://superhuman.com/"

  livecheck do
    url "https://storage.googleapis.com/download.superhuman.com/supertron-update/latest-mac.yml"
    strategy :electron_builder
  end

  app "Superhuman.app"

  zap trash: [
    "~/Library/Application Support/Superhuman",
    "~/Library/Caches/com.superhuman.electron",
    "~/Library/Caches/com.superhuman.electron.helper",
    "~/Library/Caches/com.superhuman.electron.ShipIt",
    "~/Library/Caches/Superhuman",
    "~/Library/Logs/Superhuman",
    "~/Library/Preferences/com.superhuman.electron.plist",
    "~/Library/Preferences/com.superhuman.electron.helper.plist",
    "~/Library/Preferences/com.superhuman.mail.plist",
  ]
end


text:
package i2p.bote.web;

import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.JspTag;

import net.i2p.util.Log;

public class ParamTag extends BodyTagSupport {
    private static final long serialVersionUID = 4675618920560347711L;

    private Log log = new Log(ParamTag.class);
    private String value;

    @Override
    public int doEndTag() {
        JspTag parent = findAncestorWithClass(this, MessageTag.class);
        if (parent instanceof MessageTag) {
            MessageTag messageTag = (MessageTag)parent;
            if (value == null)
                messageTag.addParameter(getBodyContent().getString());
            else
                messageTag.addParameter(value);
        }
        else
            log.error("No MessageTag ancestor found. Ancestor: " + parent);

        return EVAL_PAGE;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}


text:
FactoryGirl.define do
  trait :party_member do
    site_id { cms_site.id }
    node_id 1
    name "name"
    kana "kana"
    gender "male"
    #birth_date Date.new(1980, 5, 1)
    birth_y 1980
    birth_m 5
    birth_d 1
    pref "tokushima"
    city "tokushimashi"
    block "banchi"
    building "building"
    tel "000-000-0000"
    email "member@example.jp"
  end

  factory :party_member, class: Party::Member, traits: [:party_member] do
    #
  end

  factory :party_member_male, class: Party::Member, traits: [:party_member] do
    name "male name"
    kana "mae kana"
    gender "male"
    email "male@example.jp"
  end

  factory :party_member_female, class: Party::Member, traits: [:party_member] do
    name "female name"
    kana "female kana"
    gender "female"
    email "female@example.jp"
  end

  factory :party_node_member, class: Party::Node::Member, traits: [:cms_node] do
    route "party/member"
  end
end


text:
module StyleGuide
  class JavaScript < Base
    DEFAULT_CONFIG_FILENAME = "javascript.json"

    def violations_in_file(file)
      Jshintrb.lint(file.content, config).compact.map do |violation|
        line = file.line_at(violation["line"])

        Violation.new(
          filename: file.filename,
          patch_position: line.patch_position,
          line: line,
          line_number: violation["line"],
          messages: [violation["reason"]]
        )
      end
    end

    def file_included?(file)
      !excluded_files.any? { |pattern| File.fnmatch?(pattern, file.filename) }
    end

    private

    def config
      custom_config = repo_config.for(name)
      if custom_config["predef"].present?
        custom_config["predef"] |= default_config["predef"]
      end
      default_config.merge(custom_config)
    end

    def excluded_files
      repo_config.ignored_javascript_files
    end

    def default_config
      config_file = File.read(default_config_file)
      JSON.parse(config_file)
    end

    def default_config_file
      DefaultConfigFile.new(
        DEFAULT_CONFIG_FILENAME,
        repository_owner_name
      ).path
    end
  end
end


text:
package ma.glasnost.orika.impl.generator.specification;

import static java.lang.String.format;
import static ma.glasnost.orika.impl.generator.SourceCodeContext.statement;
import ma.glasnost.orika.impl.generator.SourceCodeContext;
import ma.glasnost.orika.impl.generator.VariableRef;
import ma.glasnost.orika.metadata.FieldMap;

/**
 * StringToEnum handles the case where the source is a String
 * and the destination is an enumeration.
 *
 */
public class StringToEnum extends AbstractSpecification {

    public boolean appliesTo(FieldMap fieldMap) {
        return fieldMap.getBType().isEnum() && fieldMap.getAType().isString();
    }

    public String generateEqualityTestCode(FieldMap fieldMap, VariableRef source, VariableRef destination, SourceCodeContext code) {
        return "(Enum.valueOf(%s.class, \"\"+%s) == " + destination +")";
    }

    public String generateMappingCode(FieldMap fieldMap, VariableRef source, VariableRef destination, SourceCodeContext code) {

        if (code.isDebugEnabled()) {
            code.debugField(fieldMap, "converting String to enum " + destination.type());
        }

        String assignEnum = destination.assign("Enum.valueOf(%s.class, \"\"+%s)", destination.typeName(), source);
        String mapNull = shouldMapNulls(fieldMap, code) ? format(" else {\n %s;\n}", destination.assignIfPossible("null")): "";
        return statement("%s { %s; } %s", source.ifNotNull(), assignEnum, mapNull);
    }
}