text:
<?php

defined('COT_CODE') or die('Wrong URL');

/**
 * Cotonti Database Connection class.
 * A compact extension to standard PHP PDO class with slight Cotonti-specific needs,
 * handy functions and query builder.
 *
 * @see http://www.php.net/manual/en/class.pdo.php
 *
 * @property-read int $affectedRows Number of rows affected by the most recent query
 * @property-read int $count Total query count
 * @property-read int $timeCount Total query execution time
 */
class CotDB extends PDO {
	/**
	 * Number of rows affected by the most recent query
	 * @var int
	 */
	private $_affected_rows = 0;

	/**
	 * Total query count
	 * @var int
	 */
	private $_count = 0;

	/**
	 * Prepare statements by itself. Used with MySQL client API versions prior to 5.1
	 * @var bool
	 */
	private $_prepare_itself = false;

	/**
	 * Total query execution time
	 * @var int
	 */
	private $_tcount = 0;

	/**
	 * Timer start microtime
	 * @var string
	 */
	private $_xtime = 0;

	/**
	 * Creates a PDO instance to represent a connection to the requested database.
	 *
	 * @param string $dsn The Data Source Name, or DSN, contains the information required to connect to the database.
	 * @param string $username The user name for the DSN string.
	 * @param string $passwd The password for the DSN string.
	 * @param array $options A key=>value array of driver-specific connection options.
	 * @see http://www.php.net/manual/en/pdo.construct.php
	 */
	public function  __construct($dsn, $username, $passwd, $options = array())
	{
		global $cfg;
		if (!empty($cfg['mysqlcharset']) && version_compare(PHP_VERSION, '5.3.0', '!='))
		{
			$collation_query = "SET NAMES '{$cfg['mysqlcharset']}'";
			if (!empty($cfg['mysqlcollate']) )
			{
				$collation_query .= " COLLATE '{$cfg['mysqlcollate']}'";
			}
			$options[PDO::MYSQL_ATTR_INIT_COMMAND] = $collation_query;
		}
		parent::__construct($dsn, $username, $passwd, $options);
		$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

		if (version_compare($this->getAttribute(PDO::ATTR_CLIENT_VERSION), '5.1.0', '<'))
		{
			$this->_prepare_itself = true;
		}
	}

	/**
	 * Provides access to properties
	 * @param string $name Property name
	 * @return mixed Property value
	 */
	public function __get($name)
	{
		switch ($name)
		{
			case 'affectedRows':
				return $this->_affected_rows;
				break;
			case 'count':
				return $this->_count;
				break;
			case 'timeCount':
				return $this->_tcount;
				break;
			default:
				return null;
		}
	}

	/**
	 * Binds parameters to a statement
	 *
	 * @param PDOStatement $statement PDO statement
	 * @param array $parameters Array of parameters, numeric or associative
	 */
	private function _bindParams($statement, $parameters)
	{
		$is_numeric = is_int(key($parameters));
		foreach ($parameters as $key => $val)
		{
			$type = is_int($val) ? PDO::PARAM_INT : PDO::PARAM_STR;
			$is_numeric ? $statement->bindValue($key + 1, $val, $type) : $statement->bindValue($key, $val, $type);
		}
	}

	/**
	 * Parses PDO exception message and returns its components and status
	 *
	 * @param PDOException $e PDO Exception
	 * @param string $err_code Output error code parameter
	 * @param string $err_message Output error message parameter
	 * @return bool TRUE for error cases, FALSE for notifications and warnings
	 */
	private function _parseError(PDOException $e, &$err_code, &$err_message)
	{
		$pdo_message = $e->getMessage();
		if (preg_match('#SQLSTATE\[(\w+)\].*?: (.*)#', $pdo_message, $matches))
		{
            $err_code = $matches[1];
            $err_message = $matches[2];
        }
		else
		{
			$err_code = $e->getCode();
			$err_message = $pdo_message;
		}
		return $err_code > '02';
	}

	/**
	 * Prepares a parametrized query on client side
	 *
	 * @param string $query Query being prepared
	 * @param array $parameters Associative or numeric array of parameters
	 * @return string Array with placeholders substituted
	 */
	private function _prepare($query, $parameters = array())
	{
		if (count($parameters) > 0)
		{
			foreach ($parameters as $key => $val)
			{
				$placeholder = is_int($key) ? '?' : ':' . $key;
				$value = is_int($val) ? $val : $this->quote($val);
				$query = preg_replace('`' . preg_quote($placeholder) . '`', $value, $query, 1);
			}
		}
		return $query;
	}

	/**
	 * Starts query execution timer
	 */
	private function _startTimer()
	{
		global $cfg;
		$this->_count++;
		if ($cfg['showsqlstats'] || $cfg['debug_mode'])
		{
			$this->_xtime = microtime();
		}
	}

	/**
	 * Stops query execution timer
	 */
	private function _stopTimer($query)
	{
		global $cfg, $usr, $sys;
		if ($cfg['showsqlstats'] || $cfg['debug_mode'])
		{
			$ytime = microtime();
			$xtime = explode(' ',$this->_xtime);
			$ytime = explode(' ',$ytime);
			$this->_tcount += $ytime[1] + $ytime[0] - $xtime[1] - $xtime[0];
			if ($cfg['devmode'] || $cfg['debug_mode'])
			{
				$calls = '';
				$bt = debug_backtrace();
				for ($i = sizeof($bt)-1; $i > 0; $i--)
				{
					$call = (($bt[$i]['object'] && $bt[$i]['class']) ? $bt[$i]['class'].$bt[$i]['type'] : '').$bt[$i]['function'].'();';
					$calls .= (empty($calls)?'':"\n → ").basename($bt[$i]['file']).' ['.$bt[$i]['line'].']: '.$call;
				}
				$sys['devmode']['queries'][] = array ($this->_count, $ytime[1] + $ytime[0] - $xtime[1] - $xtime[0], $query, $calls);
				$sys['devmode']['timeline'][] = $xtime[1] + $xtime[0] - $sys['starttime'];
			}
		}
	}

	/**
	 * Returns total number of records contained in a table
	 * @param string $table_name Table name
	 * @return int
	 */
	public function countRows($table_name)
	{
		return $this->query("SELECT COUNT(*) FROM `$table_name`")->fetchColumn();
	}

	/**
	 * Performs simple SQL DELETE query and returns number of removed items.
	 *
	 * @param string $table_name Table name
	 * @param string $condition Body of WHERE clause
	 * @param array $parameters Array of statement input parameters, see http://www.php.net/manual/en/pdostatement.execute.php
	 * @return int Number of records removed on success or FALSE on error
	 */
	public function delete($table_name, $condition = '', $parameters = array())
	{
		$query = empty($condition) ? "DELETE FROM `$table_name`" : "DELETE FROM `$table_name` WHERE $condition";
		if (!is_array($parameters))
		{
			$parameters = array($parameters);
		}
		$this->_startTimer();
		try
		{
			if (count($parameters) > 0)
			{
				if ($this->_prepare_itself)
				{
					$res = $this->exec($this->_prepare($query, $parameters));
				}
				else
				{
					$stmt = $this->prepare($query);
					$this->_bindParams($stmt, $parameters);
					$stmt->execute();
					$res = $stmt->rowCount();
				}
			}
			else
			{
				$res = $this->exec($query);
			}
		}
		catch (PDOException $err)
		{
			if ($this->_parseError($err, $err_code, $err_message))
			{
				cot_diefatal('SQL error ' . $err_code . ': ' . $err_message);
			}
		}
		$this->_stopTimer($query);
		return $res;
	}

	/**
	 * Checks if a field exists in a table
	 *
	 * @param string $table_name Table name
	 * @param string $field_name Field name
	 * @return bool TRUE if the field exists, FALSE otherwise
	 */
	function fieldExists($table_name, $field_name)
	{
		return $this->query("SHOW COLUMNS FROM `$table_name` WHERE Field = " . $this->quote($field_name))->rowCount() == 1;
	}

	/**
	 * Performs SQL INSERT on simple data array. Array keys must match table keys, optionally you can specify
	 * key prefix as third parameter. Strings get quoted and escaped automatically.
	 * Ints and floats must be typecasted.
	 * You can use special values in the array:
	 * - PHP NULL => SQL NULL
	 * - 'NOW()' => SQL NOW()
	 * Performs single row INSERT if $data is an associative array,
	 * performs multi-row INSERT if $data is a 2D array (numeric => assoc)
	 *
	 * @param string $table_name Table name
	 * @param array $data Associative or 2D array containing data for insertion.
	 * @param bool $insert_null Insert SQL NULL for empty values rather than ignoring them.
	 * @return int The number of affected records
	 */
	public function insert($table_name, $data, $insert_null = false)
	{
		if (!is_array($data))
		{
			return 0;
		}
		$keys = '';
		$vals = '';
		// Check the array type
		$arr_keys = array_keys($data);
		$multiline = is_numeric($arr_keys[0]);
		// Build the query
		if ($multiline)
		{
			$rowset = &$data;
		}
		else
		{
			$rowset = array($data);
		}
		$keys_built = false;
		$cnt = count($rowset);
		for ($i = 0; $i < $cnt; $i++)
		{
			$vals .= ($i > 0) ? ',(' : '(';
			$j = 0;
			if (is_array($rowset[$i]))
			{
				foreach ($rowset[$i] as $key => $val)
				{
					if ($j > 0) $vals .= ',';
					if (!$keys_built)
					{
						if ($j > 0) $keys .= ',';
						$keys .= "`$key`";
					}
					if (is_null($val) && $insert_null)
					{
						$vals .= 'NULL';
					}
					elseif ($val === 'NOW()')
					{
						$vals .= 'NOW()';
					}
					elseif (is_int($val) || is_float($val))
					{
						$vals .= $val;
					}
					else
					{
						$vals .= $this->quote($val);
					}
					$j++;
				}
			}
			$vals .= ')';
			$keys_built = true;
		}
		if (!empty($keys) && !empty($vals))
		{
			$query = "INSERT INTO `$table_name` ($keys) VALUES $vals";
			$this->_startTimer();
			try
			{
				$res = $this->exec($query);
			}
			catch (PDOException $err)
			{
				if ($this->_parseError($err, $err_code, $err_message))
				{
					cot_diefatal('SQL error ' . $err_code . ': ' . $err_message);
				}
			}
			$this->_stopTimer($query);
			return $res;
		}
		return 0;
	}

	public function prep($str)
	{
		return preg_replace("#^'(.*)'\$#", '$1', $this->quote($str));
	}

	/**
	 * Runs an SQL script containing multiple queries.
	 *
	 * @param string $script SQL script body, containing formatted queries separated by semicolons and newlines
	 * @param resource $conn Custom connection handle
	 * @return string Error message if an error occurs or empty string on success
	 */
	public function runScript($script)
	{
		global $db_x;
		$error = '';
		// Remove comments
		$script = preg_replace('#^/\*.*?\*/#m', '', $script);
		$script = preg_replace('#^--.*?$#m', '', $script);
		// Run queries separated by ; at the end of line
		$queries =  preg_split('#;\r?\n#', $script);
		foreach ($queries as $query)
		{
			$query = trim($query);
			if (!empty($query))
			{
				if ($db_x != 'cot_')
				{
					$query = str_replace('`cot_', '`'.$db_x, $query);
				}
				$result = $this->query($query);
				if (!$result)
				{
					return $this->error . '
' . htmlspecialchars($query) . '
';
				}
				elseif ($result instanceof PDOStatement)
				{
					$result->closeCursor();
				}
			}
		}
		return '';
	}

	/**
	 * 1) If called with one parameter:
	 * Works like PDO::query()
	 * Executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.
	 * 2) If called with second parameter as array of input parameter bindings:
	 * Works like PDO::prepare()->execute()
	 * Prepares an SQL statement and executes it.
	 * @see http://www.php.net/manual/en/pdo.query.php
	 * @see http://www.php.net/manual/en/pdo.prepare.php
	 * @param string $query The SQL statement to prepare and execute.
	 * @param array $parameters An array of values to be binded as input parameters to the query. PHP int parameters will beconsidered as PDO::PARAM_INT, others as PDO::PARAM_STR.
	 * @return PDOStatement
	 */
	public function query($query, $parameters = array())
	{
		if (!is_array($parameters))
		{
			$parameters = array($parameters);
		}
		$this->_startTimer();
		try
		{
			if (count($parameters) > 0)
			{
				if ($this->_prepare_itself)
				{
					$result = parent::query($this->_prepare($query, $parameters));
				}
				else
				{
					$result = parent::prepare($query);
					$this->_bindParams($result, $parameters);
					$result->execute();
				}
			}
			else
			{
				$result = parent::query($query);
			}
		}
		catch (PDOException $err)
		{
			if ($this->_parseError($err, $err_code, $err_message))
			{
				cot_diefatal('SQL error ' . $err_code . ': ' . $err_message);
			}
		}
		$this->_stopTimer($query);
		// In Cotonti we use PDO::FETCH_ASSOC by default to save memory
		$result->setFetchMode(PDO::FETCH_ASSOC);
		$this->_affected_rows = $result->rowCount();
		return $result;
	}

	/**
	 * Performs SQL UPDATE with simple data array. Array keys must match table keys, optionally you can specify
	 * key prefix as fourth parameter. Strings get quoted and escaped automatically.
	 * Ints and floats must be typecasted.
	 * You can use special values in the array:
	 * - PHP NULL => SQL NULL
	 * - 'NOW()' => SQL NOW()
	 *
	 * @param string $table_name Table name
	 * @param array $data Associative array containing data for update
	 * @param string $condition Body of SQL WHERE clause
	 * @param array $parameters Array of statement input parameters, see http://www.php.net/manual/en/pdostatement.execute.php
	 * @param bool $update_null Nullify cells which have null values in the array. By default they are skipped
	 * @return int The number of affected records or FALSE on error
	 */
	public function update($table_name, $data, $condition ='', $parameters = array(), $update_null = false)
	{
		if(!is_array($data))
		{
			return 0;
		}
		$upd = '';
		if (!is_array($parameters))
		{
			$parameters = array($parameters);
		}
		if ($this->_prepare_itself && !empty($condition) && count($parameters) > 0)
		{
			$condition = $this->_prepare($condition, $parameters);
			$parameters = array();
		}
		$condition = empty($condition) ? '' : 'WHERE '.$condition;
		foreach ($data as $key => $val)
		{
			if (is_null($val) && !$update_null)
			{
				continue;
			}
			$upd .= "`$key`=";
			if (is_null($val))
			{
				$upd .= 'NULL,';
			}
			elseif ($val === 'NOW()')
			{
				$upd .= 'NOW(),';
			}
			elseif (is_int($val) || is_float($val))
			{
				$upd .= $val.',';
			}
			else
			{
				$upd .= $this->quote($val) . ',';
			}

		}
		if (!empty($upd))
		{
			$upd = mb_substr($upd, 0, -1);
			$query = "UPDATE `$table_name` SET $upd $condition";
			$this->_startTimer();
			try
			{
				if (count($parameters) > 0)
				{
					$stmt = $this->prepare($query);
					$this->_bindParams($stmt, $parameters);
					$stmt->execute();
					$res = $stmt->rowCount();
				}
				else
				{
					$res = $this->exec($query);
				}
			}
			catch (PDOException $err)
			{
				if ($this->_parseError($err, $err_code, $err_message))
				{
					cot_diefatal('SQL error ' . $err_code . ': ' . $err_message);
				}
			}
			$this->_stopTimer($query);
			return $res;
		}
		return 0;
	}
}

?>


text:
 [](#skip-navbar_top "Skip navigation links")

<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>

Overview
Package
 Class
Use
Tree
Deprecated
Index
Help

 PREV CLASS   NEXT CLASS
FRAMES    NO FRAMES
All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

------------------------------------------------------------------------

org.apache.struts.tiles.taglib
 Class DefinitionTagSupport
------------------------------

    java.lang.Object
      javax.servlet.jsp.tagext.TagSupport
          org.apache.struts.tiles.taglib.DefinitionTagSupport

**All Implemented Interfaces:**
[Serializable](http://java.sun.com/j2se/1.4.2/docs/api/java/io/Serializable.html.md?is-external=true "class or interface in java.io"), [IterationTag](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/tagext/IterationTag.html?is-external=true "class or interface in javax.servlet.jsp.tagext"), [Tag](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/tagext/Tag.html?is-external=true "class or interface in javax.servlet.jsp.tagext")

**Direct Known Subclasses:**
[DefinitionTag](../../../../../org/apache/struts/tiles/taglib/DefinitionTag.html.md "class in org.apache.struts.tiles.taglib"), [InsertTag](../../../../../org/apache/struts/tiles/taglib/InsertTag.html "class in org.apache.struts.tiles.taglib")

------------------------------------------------------------------------

    public class DefinitionTagSupport

extends [TagSupport](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/tagext/TagSupport.html.md?is-external=true "class or interface in javax.servlet.jsp.tagext")

implements [Serializable](http://java.sun.com/j2se/1.4.2/docs/api/java/io/Serializable.html.md?is-external=true "class or interface in java.io")

Common base class for tags dealing with Tiles definitions. This class defines properties used in Definition Tags. It also extends TagSupport.

**See Also:**
[Serialized Form](../../../../../serialized-form.html.md#org.apache.struts.tiles.taglib.DefinitionTagSupport)

------------------------------------------------------------------------

**Field Summary**

`protected  String`

` controllerName`
           Associated Controller name (classname or url)

`protected  String`

` controllerType`
           Associated Controller type

`protected  String`

` page`
           Uri of page assoicated to this definition.

`protected  String`

` role`
           Role associated to definition.

| **Fields inherited from class javax.servlet.jsp.tagext.[TagSupport](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/tagext/TagSupport.html.md?is-external=true "class or interface in javax.servlet.jsp.tagext")** |
|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `id, pageContext`                                                                                |

| **Fields inherited from interface javax.servlet.jsp.tagext.[IterationTag](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/tagext/IterationTag.html.md?is-external=true "class or interface in javax.servlet.jsp.tagext")** |
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `EVAL_BODY_AGAIN`                                                                                |

| **Fields inherited from interface javax.servlet.jsp.tagext.[Tag](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/tagext/Tag.html.md?is-external=true "class or interface in javax.servlet.jsp.tagext")** |
|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `EVAL_BODY_INCLUDE, EVAL_PAGE, SKIP_BODY, SKIP_PAGE`                                                                                |

| **Constructor Summary**   |
|---------------------------|
| ` DefinitionTagSupport()`
                            |

**Method Summary**

` String`

` getControllerName()`
           Get controller name.

` String`

` getControllerType()`
           Get controller type.

` String`

` getPage()`
           Get the page.

` String`

` getRole()`
           Get associated role.

` String`

` getTemplate()`
           Get the template.

` void`

` release()`
           Release class properties.

` void`

` setController(String controller)`
           Set associated controller name.

` void`

` setControllerClass(String controller)`
           Set associated controller name as a classtype and controller type as "classname".

` void`

` setControllerName(String controller)`
           Set associated controller name.

` void`

` setControllerType(String controllerType)`
           Set associated controller type.

` void`

` setControllerUrl(String controller)`
           Set associated controller name as an url, and controller type as "url".

` void`

` setPage(String page)`
           Set the page.

` void`

` setRole(String role)`
           Set associated role.

` void`

` setTemplate(String template)`
           Set the template.

| **Methods inherited from class javax.servlet.jsp.tagext.[TagSupport](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/tagext/TagSupport.html.md?is-external=true "class or interface in javax.servlet.jsp.tagext")** |
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `doAfterBody, doEndTag, doStartTag, findAncestorWithClass, getId, getParent, getValue, getValues, removeValue, setId, setPageContext, setParent, setValue`                                                               |

| **Methods inherited from class java.lang.[Object](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html.md?is-external=true "class or interface in java.lang")** |
|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`                                                                          |

**Field Detail**

### controllerType

    protected String controllerType

Associated Controller type

------------------------------------------------------------------------

### controllerName

    protected String controllerName

Associated Controller name (classname or url)

------------------------------------------------------------------------

### role

    protected String role

Role associated to definition.

------------------------------------------------------------------------

### page

    protected String page

Uri of page assoicated to this definition.

**Constructor Detail**

### DefinitionTagSupport

    public DefinitionTagSupport()

**Method Detail**

### release

    public void release()

Release class properties.

**Specified by:**
`release` in interface `Tag`

**Overrides:**
`release` in class `TagSupport`

------------------------------------------------------------------------

### getControllerType

    public String getControllerType()

Get controller type. Type can be 'classname', 'url'.

**Returns:**
Controller type.

------------------------------------------------------------------------

### getControllerName

    public String getControllerName()

Get controller name. Name denotes a fully qualified classname, or an url. Exact type can be specified with [`setControllerType(java.lang.String)`](../../../../../org/apache/struts/tiles/taglib/DefinitionTagSupport.html.md#setControllerType(java.lang.String)).

**Returns:**
Controller name.

------------------------------------------------------------------------

### setControllerType

    public void setControllerType(String controllerType)

Set associated controller type. Type denotes a fully qualified classname.

**Parameters:**
`controllerType` - Type of associated controller.

------------------------------------------------------------------------

### setController

    public void setController(String controller)

Set associated controller name. Name denotes a fully qualified classname, or an url. Exact type can be specified with [`setControllerType(java.lang.String)`](../../../../../org/apache/struts/tiles/taglib/DefinitionTagSupport.html.md#setControllerType(java.lang.String)).

**Parameters:**
`controller` - Controller classname or url.

------------------------------------------------------------------------

### setControllerName

    public void setControllerName(String controller)

Set associated controller name. Name denote a fully qualified classname, or an url. Exact type can be specified with setControllerType.

**Parameters:**
`controller` - Controller classname or url

------------------------------------------------------------------------

### setControllerUrl

    public void setControllerUrl(String controller)

Set associated controller name as an url, and controller type as "url". Name must be an url (not checked). Convenience method.

**Parameters:**
`controller` - Controller url

------------------------------------------------------------------------

### setControllerClass

    public void setControllerClass(String controller)

Set associated controller name as a classtype and controller type as "classname". Name denotes a fully qualified classname. Convenience method.

**Parameters:**
`controller` - Controller classname.

------------------------------------------------------------------------

### getRole

    public String getRole()

Get associated role.

**Returns:**
Associated role.

------------------------------------------------------------------------

### setRole

    public void setRole(String role)

Set associated role.

**Parameters:**
`role` - Associated role.

------------------------------------------------------------------------

### setPage

    public void setPage(String page)

Set the page.

**Parameters:**
`page` - Page.

------------------------------------------------------------------------

### getPage

    public String getPage()

Get the page.

**Returns:**
Page.

------------------------------------------------------------------------

### getTemplate

    public String getTemplate()

Get the template. Same as getPage().

**Returns:**
Template.

------------------------------------------------------------------------

### setTemplate

    public void setTemplate(String template)

Set the template. Same as setPage().

**Parameters:**
`template` - Template.

------------------------------------------------------------------------

 [](#skip-navbar_bottom "Skip navigation links")

<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>

Overview
Package
 Class
Use
Tree
Deprecated
Index
Help

 PREV CLASS   NEXT CLASS
FRAMES    NO FRAMES
All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD
DETAIL: FIELD | CONSTR | METHOD

------------------------------------------------------------------------

Copyright © 2000-2008 [Apache Software Foundation](http://www.apache.org/). All Rights Reserved.

redpajama_set_name: RedPajamaGithub


text:
package cn.dmdl.toolkit;

import cn.dmdl.kernel.GenericInvoke;

public class SchedulerCallScript implements GenericInvoke {

	@Override
	public Object invoke(String[] args) {
		String resultMessage = "调用成功";
		if (args != null && args.length == 2) {
			dispose(args[0], Integer.parseInt(args[1]));
		} else {
			resultMessage = "参数无效";
		}
		return resultMessage;
	}

	public static void dispose(String vbs, int intervalSecond) {
		try {
			long lastRunTime = System.currentTimeMillis();
			while (true) {
				Thread.yield();
				if (System.currentTimeMillis() - lastRunTime > 1000 * intervalSecond) {
					lastRunTime = System.currentTimeMillis();
					Runtime.getRuntime().exec(new String[] { "wscript", vbs });
				}
				Thread.sleep(1000);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


text:
"""

Simulated annealing fitting routine.

Complete rebuild of the original SA fitting module written by Mark A. Zentile, now using lmfit

Last updated 2018-07-12 MAZ
"""
# py 2.7 compatibility
from __future__ import (division, print_function, absolute_import)

import numpy as np
import matplotlib.pyplot as plt
import warnings
import sys
import copy
import time

import pickle as pickle

import psutil
from multiprocessing import Pool

from . import MLFittingRoutine as ML
import lmfit as lm

from .spectra import get_spectra

p_dict_bounds_default = {'lcell':1e-3,'Bfield':100., 'T':20.,
							'GammaBuf':20., 'shift':100.,
							# Polarisation of light
							'theta0':10., 'E_x':0.05, 'E_y':0.05, 'E_phase':0.01,
							# B-field angle w.r.t. light k-vector
							'Btheta':10*3.14/180, 'Bphi':10*3.14/180,
							'DoppTemp':20.,
							'rb85frac':1, 'K40frac':1, 'K41frac':1,
							}

def chisq(yo,ye,err=None):
	"""
	Evaluate the chi-squared value of a given data/theory combination

	Inputs:
		yo : observed data
		ye : expected (theory) data
		err : Optional, error bars - array of length(x)

	Returns:
		float of chi-squared value
	"""
	if err is None:
		err = np.ones_like(yo)
	return (((yo-ye)/err)**2).sum()

def evaluate(args):
	""" Evaluate chi-squared value for a given set of parameters """

	warnings.simplefilter("ignore")
	data = args[0]

	p_dict = args[2]
	E_in = np.array([p_dict['E_x'],p_dict['E_y']*np.exp(1.j*p_dict['E_phase']),0.])
	p_dict_bools = args[3]
	data_type = args[4]
	theory_vals = get_spectra(data[0],E_in,p_dict,outputs=[data_type])[0].real
	chisq_val = chisq(data[1],theory_vals)

	return chisq_val, p_dict

def SA_fit(data,E_in,p_dict,p_dict_bools,p_dict_bounds=None,no_evals=None,data_type='S0',verbose=False):
	"""
	Simulated annealing fitting method.

	Before simulated annealing starts, the parameter space is randomly sampled to find good starting conditions for the SA fit.

	data:					an Nx2 iterable for the x and y data to be fitted
	E_in:					the initial electric field input. See docstring for the spectra.py module for details.

	no_evals:			The number of randomly-selected start points for downhill fitting. Defaults to 2**(3+2*nFitParams) where nFitParams is
									the number of varying fit parameters

	p_dict:					dictionary containing all the calculation (initial) parameters
	p_dict_bools:		dictionary with the same keys as p_dict, with Boolean values representing each parameter that is to be varied in the fitting
	p_dict_bounds:	dictionary with the same keys as p_dict, with values that represent the deviation each parameter can take in the initial parameter search
									NOTE: this works slightly differently to p_dict_bounds in the ML fitting methods. In RR and SA fitting, the bounds
									select the range in parameter space that is randomly explored to find good starting parameters for the
									SA routine, rather than being strict bounds on the fit parameters.

	data_type:			Data type to fit experimental data to. Can be one of:
									'S0', 'S1', 'S2', 'S3', 'Ix', 'Iy', ...
	verbose:				Boolean - more print statements provided as the program progresses

	"""

	if p_dict_bounds is None:
		p_dict_bounds = p_dict_bounds_default

	print('Starting Simulated Annealing Fitting Routine')
	x = np.array(data[0])
	y = np.array(data[1])

	p_dict['E_x'] = E_in[0]
	p_dict['E_y'] = E_in[1][0]
	p_dict['E_phase'] = E_in[1][1]
	E_in_vector = np.array([p_dict['E_x'],p_dict['E_y']*np.exp(1.j*p_dict['E_phase']),0.])

	# count number of fit parameters
	nFitParams = 0
	for key in p_dict_bools:
		if p_dict_bools[key]: nFitParams += 1

	# default number of iterations based on number of fit parameters
	if no_evals == None:
		no_evals = 2**(8+2*nFitParams)

	# Create random array of starting parameters based on parameter ranges given in p_dict_bounds dictionary
	# Scattered uniformly over the parameter space

	#clone the parameter dictionary
	p_dict_list = []
	for i in range(no_evals):
		p_dict_list.append(copy.deepcopy(p_dict))

	for key in p_dict_bools:
		if p_dict_bools[key]==True:
			start_vals = p_dict[key]
			#print start_vals
			for i in range(len(p_dict_list)):
				p_dict_list[i][key] = start_vals + np.random.uniform(-1,1) * p_dict_bounds[key]

	if verbose:
		print('List of initial parameter dictionaries:')
		for pd in p_dict_list:
			print(pd)
		#print p_dict_list
		print('\n\n')

	#Do parallel ML fitting by utilising multiple cores
	po = Pool() # Pool() uses all cores, Pool(3) uses 3 cores for example.

	## use lower process priority so computer is still responsive while calculating!!
	parent = psutil.Process()
	parent.nice(psutil.BELOW_NORMAL_PRIORITY_CLASS)
	for child in parent.children():
		child.nice(psutil.IDLE_PRIORITY_CLASS)

	args_list = [(data, E_in, p_dict_list[k], p_dict_bools, data_type) for k in range(no_evals)]

	Res = po.map_async(evaluate,args_list)
	result = Res.get()
	po.close()
	po.join()

	result = np.array(result)
	lineMin = np.argmin(result[:,0]) # position of lowest chi-squared value from initial guesses
	SA_params = result[lineMin][1] # parameter dictionary associated with lowest chi-squared
	best_chi_sq = result[lineMin][0] # lowest chi-squared value
	current_chi_sq = best_chi_sq
	current_params = copy.deepcopy(SA_params)

	print('\n\n Initial parameter space evaluations completed...')

	# Measure of how much the chi-squared values change over the parameter space
	spread = np.std(result[:,0])

	# Initial 'temperature' for the annealing
	T = 1500.
	# Cold temperature extreme where the algorithm will stop searching
	minimum_T = 50.

	# sets the effective range of a given temperature
	range_scaling = 3
	k = abs(spread)/T / range_scaling

	# Cooling rate - how much the temperature decreases on each run.
	cooling_rate = 7e-6

	# Number of times a jump uphill is rejected before switching to ML fit.
	uphill_escape_chance = 0
	uphill_escape_threshold = 300

	# Number of iterations to investigate a plateau in parameter space (i.e. chi-squared does not change)
	plateau_escape_chance = 0
	plateau_escape_threshold = 300

	trial_params = copy.deepcopy(current_params)
	best_params = copy.deepcopy(current_params)
	best_chi_sq = current_chi_sq
	#print trial_params

	## testing - log algorithm path
	chi_sq_log = [current_chi_sq]
	T_log = [trial_params['T']]
	B_log = [trial_params['Bfield']]

	hot_iterations = 250
	iteration = 0

	while T > minimum_T:
		# Generate a new set of parameters that are close to the last evaluated parameters
		for key in p_dict_bools:
			if p_dict_bools[key]==True: # (extra check)
				## parameters varied over 10% of range specified before...
				trial_params[key] = copy.deepcopy(current_params[key]) + np.random.normal(0,p_dict_bounds[key]) # * p_dict_bounds[key]	#* 0.1

		print('Before calculation:')
		print(('Trial: ', trial_params['T'], trial_params['Bfield']))
		print(('Current: ', current_params['T'], current_params['Bfield']))

		trial_theory = get_spectra(x,E_in_vector,trial_params,outputs=[data_type])[0].real
		trial_chi_sq = chisq(data[1],trial_theory)

		# log best chi_squared values and parameters
		if trial_chi_sq < best_chi_sq:
			best_chi_sq = trial_chi_sq
			best_params = copy.deepcopy(trial_params)

		# Calculate energy difference
		delta_chi_sq = trial_chi_sq - current_chi_sq

		# and convert to probability of acceptance
		if delta_chi_sq < 1e-5:
			# if there's no change in chi-squared (i.e. parameter space is locally flat), accept with small (5%) probability
			print('WARNING - no change in chi-squared - probably due to plateau in parameter space!')
			prob = 0.05
			plateau_escape_chance += 1
		else:
			prob = np.exp(-delta_chi_sq/(k*T))

		if verbose:
			print(('\n\tBest chi-squared so far:', best_chi_sq))
			print(('\tBest Parameters so far (T, B): ', best_params['T'], best_params['Bfield']))

			print(('\tCurrent Parameters (T, B): ', current_params['T'], current_params['Bfield']))
			print(('\tTrial Parameters (T, B): ', trial_params['T'], trial_params['Bfield']))
			print(('\n\tCurrent chi-squared:', current_chi_sq))
			print(('\tTrial chi-squared:', trial_chi_sq))
			print(('\tChange in chi-squared from previous:', delta_chi_sq))
			print(('\tTemperature parameter: ', T))
			print(('\tProbability that new parameters will be accepted (>1 == 1):', prob))

		if (delta_chi_sq < 0) or (prob > np.random.random()):
			# accept downhill movement, or uphill movement with probability prob - update chi_squared and parameters
			current_chi_sq = trial_chi_sq
			current_params = copy.deepcopy(trial_params)

			chi_sq_log.append(trial_chi_sq) ## keep log of chi-squared values (on succesful iterations only)
			T_log.append(trial_params['T'])
			B_log.append(trial_params['Bfield'])

			print('\t...Values accepted. Current parameters updated.')
			print('\n')

			# reset escape chance
			uphill_escape_chance = 0
		else:
			print(('\t...Values rejected. Escape threshold:', uphill_escape_chance, ' / ', uphill_escape_threshold))
			print('\n')
			uphill_escape_chance += 1

		# Cool system
		# Hold T constant for first N iterations
		if iteration > hot_iterations:
			T = T/(1 + (cooling_rate*T)) #Lundy's Method (http://link.springer.com/article/10.1007/BF01582166)

		iteration += 1

		# Exit annealing loop if conditions are correct
		if (uphill_escape_chance > uphill_escape_threshold):
			print(('Simulated annealing completed ( No improvement found after {:d} iterations)'.format(uphill_escape_threshold)))
			print('Switching to downhill fit using best found parameters...\n')
			break

		if (T < minimum_T): #No jumps up hill for a while, or minimum temperature reached
			print('Simulated annealing completed ( Temperature reached minimum threshold )')
			print('Switching to downhill fit using best found parameters...\n')
			break

		if (plateau_escape_chance > plateau_escape_threshold):
			print('!!!\n\tCAUTION :: Annealing has not converged.')
			print('\tAnnealing algorithm found plateau in parameter space')
			print('\tSwitching to downhill fit using best found parameters...\n!!!')
			break

	#### Marquardt-Levenberg fit #####

	try:
		print(('Downhill fit with initial parameters: (T,B) ', best_params['T'], best_params['Bfield']))
		ML_best_params, result = ML.ML_fit(data, E_in, best_params, p_dict_bools, data_type)
		MLchi_sq = result.chisqr
		if MLchi_sq <= best_chi_sq:
			best_params = ML_best_params
			final_result = result
			success = True
			print('Downhill fit converged successfully.\n')
		else:
			print('Downhill fit did not find further improvement. Continuing with simulated annealing result.\n')
			success = False
			final_result = 1
	except:
		print('Downhill fit failed to converge. Continuing with simulated annealing result.\n')
		success = False
		final_result = 1

	return best_params, final_result #, chi_sq_log, T_log, B_log, success

def test_fit(calc=False):
	p_dict = {'elem':'Rb','Dline':'D2','T':80.,'lcell':2e-3,'Bfield':600.,'Btheta':0.,
		'Bphi':0.,'GammaBuf':0.,'shift':0.}

	# only need to specify parameters that are varied
	p_dict_bools = {'T':True,'Bfield':True}
	p_dict_bounds = {'T':20,'Bfield':200}

	E_in = np.array([0.7,0.7,0])
	E_in_angle = [E_in[0].real,[abs(E_in[1]),np.angle(E_in[1])]]

	print(E_in_angle)

	x = np.linspace(-10000,10000,200)
	if calc:
		[y] = get_spectra(x,E_in,p_dict,outputs=['S1']) + np.random.randn(len(x))*0.01
		pickle.dump([x,y],open('pickle_xydata.pkl','wb'))
	else:
		x,y = pickle.load(open('pickle_xydata.pkl','rb'))

	data = [x,y.real]

	# Map chi-squared surface:
	Tvals = np.linspace(60,100,200)
	Bvals = np.linspace(400,800,220)

	T2D, B2D = np.meshgrid(Tvals,Bvals)

	CSQ_map = np.zeros((len(Tvals),len(Bvals)))

	if calc:
		for i,TT in enumerate(Tvals):
			print((i, len(Tvals)))
			for j, BB in enumerate(Bvals):
				p_dict['T'] = TT
				p_dict['Bfield'] = BB
				[ye] = get_spectra(x,E_in,p_dict,outputs=['S1'])
				CSQ_map[i,j] = chisq(y,ye)
		pickle.dump([T2D,B2D,CSQ_map],open('pickle_CSQmap.pkl','wb'))
	else:
		T2D, B2D, CSQ_map = pickle.load(open('pickle_CSQmap.pkl','rb'))

	fig_map = plt.figure()
	ax = fig_map.add_subplot(111)
	ax.imshow(CSQ_map.T,origin='lower',aspect='auto',
					extent=(Tvals[0],Tvals[-1],Bvals[0],Bvals[-1]),
					cmap=plt.cm.jet,alpha=0.7)
	ax.contour(T2D, B2D, CSQ_map.T,7,lw=2,color='k')

	#plt.show()

	## Do SA fitting
	best_params, result, chi_sq_log, T_log, B_log = SA_fit(data, E_in_angle, p_dict, p_dict_bools,
																					p_dict_bounds, no_evals = 4, data_type='S1')
	report = result.fit_report()
	fit = result.best_fit

	fig_data = plt.figure()
	print(report)
	plt.plot(x,y,'ko')
	plt.plot(x,fit,'r-',lw=2)

	# Chi-squared log with iteration number
	fig_chisqlog = plt.figure()
	plt.plot(chi_sq_log)
	plt.ylabel('Chi_squared value')
	plt.xlabel('Iteration')

	#plt.show()

	ax.plot(T_log, B_log, 'ko', ms=1)

	plt.show()

def test_fit2(calc=False):
	""" Alternate data set to test """

	p_dict = {'elem':'Rb','Dline':'D2','T':80.,'lcell':2e-3,'Bfield':250.,'Btheta':0.,
		'Bphi':0.,'GammaBuf':0.,'shift':0.}

	# only need to specify parameters that are varied
	p_dict_bools = {'T':True,'Bfield':True}
	p_dict_bounds = {'T':15,'Bfield':100}

	E_in = np.array([1.0,0.0,0.0])
	E_in_angle = [E_in[0].real,[abs(E_in[1]),np.angle(E_in[1])]]

	print(E_in_angle)

	x = np.linspace(-7000,8000,200)
	if calc:
		[y] = get_spectra(x,E_in,p_dict,outputs=['S0']) + np.random.randn(len(x))*0.02
		pickle.dump([x,y],open('pickle_xydata.pkl','wb'))
	else:
		x,y = pickle.load(open('pickle_xydata.pkl','rb'))

	data = [x,y.real]

	# Map chi-squared surface:
	Tvals = np.linspace(40,120,300)
	Bvals = np.linspace(0,500,250)

	T2D, B2D = np.meshgrid(Tvals,Bvals)
	CSQ_map = np.zeros((len(Tvals),len(Bvals)))

	if calc:
		for i,TT in enumerate(Tvals):
			print((i, len(Tvals)))
			for j, BB in enumerate(Bvals):
				p_dict['T'] = TT
				p_dict['Bfield'] = BB
				[ye] = get_spectra(x,E_in,p_dict,outputs=['S0'])
				CSQ_map[i,j] = chisq(y,ye)
		pickle.dump([T2D,B2D,CSQ_map],open('pickle_CSQmap.pkl','wb'))
	else:
		T2D, B2D, CSQ_map = pickle.load(open('pickle_CSQmap.pkl','rb'))

	fig_map = plt.figure()
	ax = plt.subplot2grid((1,14),(0,0),colspan=13)
	ax_cb = plt.subplot2grid((1,14),(0,13),colspan=1)
	im = ax.imshow(CSQ_map.T,origin='lower',aspect='auto',
					extent=(Tvals[0],Tvals[-1],Bvals[0],Bvals[-1]),
					cmap=plt.cm.jet,alpha=0.7)
	ax.contour(T2D, B2D, CSQ_map.T,7,lw=2,color='k')

	cb = fig_map.colorbar(im,cax=ax_cb)

	#plt.show()

	## Do SA fitting
	best_params, result, chi_sq_log, T_log, B_log = SA_fit(data, E_in_angle, p_dict, p_dict_bools,
																					p_dict_bounds, no_evals = 2, data_type='S0')
	report = result.fit_report()
	fit = result.best_fit

	fig_data = plt.figure()
	print(report)
	plt.plot(x,y,'ko')
	plt.plot(x,fit,'r-',lw=2)

	# Chi-squared log with iteration number
	fig_chisqlog = plt.figure()
	plt.plot(chi_sq_log)
	plt.ylabel('Chi_squared value')
	plt.xlabel('Iteration')

	#plt.show()

	ax.plot(T_log, B_log, 'ko', ms=1)
	ax.plot(T_log[0], B_log[0], 'rs', ms=6)
	ax.plot(T_log[-1], B_log[-1], 'bs', ms=6)

	plt.show()

def test_fit3(calc=False):
	""" Alternate data set to test """

	p_dict = {'elem':'Rb','Dline':'D2','T':155.,'lcell':5e-3,'Bfield':1100.,'Btheta':0.,
		'Bphi':0.,'GammaBuf':0.,'shift':0.}

	# only need to specify parameters that are varied
	p_dict_bools = {'T':True,'Bfield':True}
	p_dict_bounds = {'T':25,'Bfield':300}

	E_in = np.array([1.0,0.0,0.0])
	E_in_angle = [E_in[0].real,[abs(E_in[1]),np.angle(E_in[1])]]

	print(E_in_angle)

	x = np.linspace(-13000,-6000,150)
	if calc:
		[y] = get_spectra(x,E_in,p_dict,outputs=['S1']) + np.random.randn(len(x))*0.02
		pickle.dump([x,y],open('pickle_xydata.pkl','wb'))
	else:
		x,y = pickle.load(open('pickle_xydata.pkl','rb'))

	data = [x,y.real]

	# Map chi-squared surface:
	#Tvals = np.linspace(p_dict['T']-p_dict_bounds['T'],p_dict['T']+p_dict_bounds['T'],150)
	#Bvals = np.linspace(p_dict['Bfield']-p_dict_bounds['Bfield'],p_dict['Bfield']+p_dict_bounds['Bfield'],125)

	Tvals = np.linspace(80,250,450)
	Bvals = np.linspace(0,2500,300)

	T2D, B2D = np.meshgrid(Tvals,Bvals)
	CSQ_map = np.zeros((len(Tvals),len(Bvals)))

	if calc:
		for i,TT in enumerate(Tvals):
			print((i, len(Tvals)))
			for j, BB in enumerate(Bvals):
				p_dict['T'] = TT
				p_dict['Bfield'] = BB
				[ye] = get_spectra(x,E_in,p_dict,outputs=['S1'])
				CSQ_map[i,j] = chisq(y,ye)
		pickle.dump([T2D,B2D,CSQ_map],open('pickle_CSQmap.pkl','wb'))
	else:
		T2D, B2D, CSQ_map = pickle.load(open('pickle_CSQmap.pkl','rb'))

	print(T2D)
	print(B2D)
	fig_map = plt.figure()
	ax = plt.subplot2grid((1,14),(0,0),colspan=13)
	ax_cb = plt.subplot2grid((1,14),(0,13),colspan=1)
	im = ax.imshow(CSQ_map.T,origin='lower',aspect='auto',
					extent=(T2D[0][0],T2D[-1][-1],B2D[0][0],B2D[-1][-1]),
					cmap=plt.cm.jet,alpha=0.7)
	ax.contour(T2D, B2D, CSQ_map.T,9,lw=2,color='k')

	cb = fig_map.colorbar(im,cax=ax_cb)

	#plt.show()

	## Do SA fitting
	best_params, result, chi_sq_log, T_log, B_log, success = SA_fit(data, E_in_angle, p_dict, p_dict_bools,
																					p_dict_bounds, no_evals = 32, data_type='S1')
	if success:
		report = result.fit_report()
		fit = result.best_fit
		print(report)

	fig_data = plt.figure()
	plt.plot(x,y,'ko')
	if success:
		plt.plot(x,fit,'r-',lw=2)

	# Chi-squared log with iteration number
	fig_chisqlog = plt.figure()
	plt.plot(chi_sq_log)
	plt.ylabel('Chi_squared value')
	plt.xlabel('Iteration')

	#plt.show()

	ax.plot(T_log, B_log, 'ko', ms=1)
	ax.plot(T_log, B_log, 'k--', lw=1.5)
	ax.plot(T_log[0], B_log[0], 'rs', ms=6)
	ax.plot(T_log[-1], B_log[-1], 'bs', ms=6)

	plt.show()

def test_fit4(calc=False):
	""" Alternate data set to test """

	#actual params 110 / 7000

	p_dict = {'elem':'Rb','Dline':'D2','T':100.,'lcell':5e-3,'Bfield':6100.,'Btheta':0.,
		'Bphi':0.,'GammaBuf':0.,'shift':0.,'rb85frac':1.0}

	# only need to specify parameters that are varied
	p_dict_bools = {'T':True,'Bfield':True}
	p_dict_bounds = {'T':5,'Bfield':400}

	E_in = np.array([1.0,0.0,0.0])
	E_in_angle = [E_in[0].real,[abs(E_in[1]),np.angle(E_in[1])]]

	print(E_in_angle)

	x = np.linspace(-21000,-13000,150)
	if calc:
		[y] = get_spectra(x,E_in,p_dict,outputs=['S0']) + np.random.randn(len(x))*0.02
		pickle.dump([x,y],open('pickle_xydata.pkl','wb'))
	else:
		x,y = pickle.load(open('pickle_xydata.pkl','rb'))

	data = [x,y.real]

	# Map chi-squared surface:
	#Tvals = np.linspace(p_dict['T']-p_dict_bounds['T'],p_dict['T']+p_dict_bounds['T'],150)
	#Bvals = np.linspace(p_dict['Bfield']-p_dict_bounds['Bfield'],p_dict['Bfield']+p_dict_bounds['Bfield'],125)

	Tvals = np.linspace(70,150,350)
	Bvals = np.linspace(5000,10000,300)

	T2D, B2D = np.meshgrid(Tvals,Bvals)
	CSQ_map = np.zeros((len(Tvals),len(Bvals)))

	if calc:
		for i,TT in enumerate(Tvals):
			print((i, len(Tvals)))
			for j, BB in enumerate(Bvals):
				p_dict['T'] = TT
				p_dict['Bfield'] = BB
				[ye] = get_spectra(x,E_in,p_dict,outputs=['S0'])
				CSQ_map[i,j] = chisq(y,ye)
		pickle.dump([T2D,B2D,CSQ_map],open('pickle_CSQmap.pkl','wb'))
	else:
		T2D, B2D, CSQ_map = pickle.load(open('pickle_CSQmap.pkl','rb'))

	print(T2D)
	print(B2D)
	fig_map = plt.figure()
	ax = plt.subplot2grid((1,14),(0,0),colspan=13)
	ax_cb = plt.subplot2grid((1,14),(0,13),colspan=1)
	im = ax.imshow(CSQ_map.T,origin='lower',aspect='auto',
					extent=(T2D[0][0],T2D[-1][-1],B2D[0][0],B2D[-1][-1]),
					cmap=plt.cm.jet,alpha=0.7)
	ax.contour(T2D, B2D, CSQ_map.T,9,lw=2,color='k')

	cb = fig_map.colorbar(im,cax=ax_cb)

	#plt.show()

	## Do SA fitting
	best_params, result, chi_sq_log, T_log, B_log, success = SA_fit(data, E_in_angle, p_dict, p_dict_bools,
																					p_dict_bounds, no_evals = 32, data_type='S0')

	fig_data = plt.figure()
	plt.plot(x,y,'ko')
	if success:
		report = result.fit_report()
		fit = result.best_fit
		print(report)
	else:
		print(best_params)
		fit = get_spectra(x,E_in,best_params,outputs=['S0'])[0].real

	plt.plot(x,fit,'r-',lw=2)

	# Chi-squared log with iteration number
	fig_chisqlog = plt.figure()
	plt.plot(chi_sq_log)
	plt.ylabel('Chi_squared value')
	plt.xlabel('Iteration')

	#plt.show()

	ax.plot(T_log, B_log, 'ko', ms=1)
	ax.plot(T_log, B_log, 'k--', lw=1.5)
	ax.plot(T_log[0], B_log[0], 'rs', ms=6)
	ax.plot(T_log[-1], B_log[-1], 'bs', ms=6)

	plt.show()

if __name__ == '__main__':
	test_fit4(False)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="mobile-web-app-capable" content="yes">
    <link rel="icon" sizes="240x240" href="icon.png">
    <title>d.light</title>
    <link rel="stylesheet" href="./css/bootstrap.css">
    <link rel="stylesheet" href="./css/bootstrap-theme.css">
    <link rel="stylesheet" href="./css/style.css">

d.light

        <input id="dimmer" type="range" name="dimmer" min="0" max="100" value="0" />

        <input class="btn btn-lg btn-danger" id="btnoff" type="button" value="Light Off" style="display:none" />
        <input class="btn btn-lg btn-success" id="btnon" type="button" value="Light On" style="display:none" />

        <input class="btn btn-lg btn-warning" id="btnsnooze" type="button" value="Snooze" style="display:none" />

        <input class="btn btn-lg btn-danger" id="btnalarmoff" type="button" value="Alarm Off" style="display:none" />

        <form class="form-inline" onsubmit="return false">
          Alarm:
          <input type="time" class="form-control" id="inalarmtime" style="width:125px">
        </form>

        <form class="form-inline" onsubmit="return false">
          Snooze:
          <input type="number" min="1" max="15" class="form-control" id="insnoozetime" style="width:70px">
        </form>

        <form class="form-inline" onsubmit="return false">
          Brighten:
          <input type="number" min="1" max="30" class="form-control" id="inbrightentime" style="width:70px">
        </form>

        <input class="btn btn-success" id="btnalarmenable" type="button" value="Enable Alarm" style="display:none" />
        <input class="btn btn-danger" id="btnalarmdisable" type="button" value="Disable Alarm" style="display:none" />


text:
@implementation ShroudNonactivatingView

- (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)theEvent;
{
    return !([theEvent modifierFlags] & NSAlternateKeyMask);
}

- (void)mouseDown:(NSEvent *)theEvent;
{
    if ([self shouldDelayWindowOrderingForEvent:theEvent])
	[NSApp preventWindowOrdering];
    else
        [NSApp activateIgnoringOtherApps:YES]; // only necessary the first time
}

@end


text:
require 'spec_helper'

RSpec.describe Idnow do
  after do
    Idnow.instance_variable_set(:@env, nil)
    Idnow.instance_variable_set(:@company_id, nil)
    Idnow.instance_variable_set(:@api_key, nil)
    Idnow.instance_variable_set(:@custom_environments, nil)
    Idnow.instance_variable_set(:@client, nil)
  end

  describe '.env=' do
    subject { Idnow.env = env }

    let(:env) { :test }

    it 'resets client' do
      Idnow.instance_variable_set(:@client, 'dummy')
      expect { subject }.to change { Idnow.instance_variable_get(:@client) }.to(nil)
    end

    it 'sets env' do
      expect { subject }.to change { Idnow.instance_variable_get(:@env) }.to(env)
    end

    context 'when invalid env is given' do
      let(:env) { :invalid }
      it { expect { subject }.to raise_error(ArgumentError) }
    end
  end

  describe '.company_id=' do
    subject { Idnow.company_id = company_id }

    let(:company_id) { 'somecompany' }

    it 'resets client' do
      Idnow.instance_variable_set(:@client, 'dummy')
      expect { subject }.to change { Idnow.instance_variable_get(:@client) }.to(nil)
    end

    it 'sets company_id' do
      expect { subject }.to change { Idnow.instance_variable_get(:@company_id) }.to(company_id)
    end
  end

  describe '.api_key=' do
    subject { Idnow.api_key = api_key }

    let(:api_key) { 'api_key' }

    it 'resets client' do
      Idnow.instance_variable_set(:@client, 'dummy')
      expect { subject }.to change { Idnow.instance_variable_get(:@client) }.to(nil)
    end

    it 'sets api_key' do
      expect { subject }.to change { Idnow.instance_variable_get(:@api_key) }.to(api_key)
    end
  end

  describe '.custom_environments=' do
    subject { Idnow.custom_environments = custom_environments }

    let(:custom_environments) { { test: {}, live: {} } }

    it 'resets client' do
      Idnow.instance_variable_set(:@client, 'dummy')
      expect { subject }.to change { Idnow.instance_variable_get(:@client) }.to(nil)
    end

    it 'sets custom_environments' do
      expect { subject }.to change { Idnow.instance_variable_get(:@custom_environments) }.to(custom_environments)
    end
  end

  describe '.client' do
    subject { Idnow.client }

    context 'if company_id is not set' do
      before do
        Idnow.env = :test
        Idnow.api_key = 'some key'
      end
      it { expect { subject }.to raise_error(RuntimeError, 'Please set your company_id') }
    end

    context 'if api_key is not set' do
      before do
        Idnow.env = :test
        Idnow.company_id = 'somecompany'
      end
      it { expect { subject }.to raise_error(RuntimeError, 'Please set your api_key') }
    end

    context 'if env is not set' do
      before do
        Idnow.company_id = 'somecompany'
        Idnow.api_key = 'some key'
      end
      it { expect { subject }.to raise_error(RuntimeError, 'Please set env to :test or :live') }
    end

    context 'if env, api_key and company_id are set' do
      before do
        Idnow.env = :test
        Idnow.company_id = 'somecompany'
        Idnow.api_key = 'some key'
      end

      it { is_expected.to be_a(Idnow::Client) }

      it 'memoizes the client' do
        expect(Idnow::Client).to receive(:new).once.and_call_original
        2.times { Idnow.client }
      end
    end
  end
end


text:
//  The MIT License (MIT)
//
//  Copyright (c) 2013 Levi Nunnink
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to
//  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//  the Software, and to permit persons to whom the Software is furnished to do so,
//  subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

//
//  Created by Levi Nunnink (@a_band) http://culturezoo.com
//  Copyright (C) Droplr Inc. All Rights Reserved
//

#import "SmoothLineView.h"
#import <QuartzCore/QuartzCore.h>

#define DEFAULT_COLOR               [UIColor blackColor]
#define DEFAULT_WIDTH               5.0f
#define DEFAULT_BACKGROUND_COLOR    [UIColor whiteColor]

#define USE_SYNCHRONIZED 1

//static const CGFloat kPointMinDistance = 5.0f;
//static const CGFloat kPointMinDistanceSquared = kPointMinDistance * kPointMinDistance;

@interface SmoothLineView ()
@property (nonatomic,assign) CGPoint currentPoint;
@property (nonatomic,assign) CGPoint previousPoint;
@property (nonatomic,assign) CGPoint previousPreviousPoint;

@property (nonatomic, strong) UIBezierPath* bzPath;
@property (nonatomic, strong) NSMutableArray* pathSnapshots;

@property (nonatomic, strong) UIColor *bgColor;

#pragma mark Private Helper function
CGPoint midPoint(CGPoint p1, CGPoint p2);
@end

@implementation SmoothLineView {
@private
    CGMutablePathRef _fullPath;
    CGMutablePathRef _drawnPath;
}

#pragma mark UIView lifecycle methods

+ (Class) layerClass
{
    return [CATiledLayer class];
}

- (id) initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];

    if (self)
    {
        // NOTE: do not change the backgroundColor here, so it can be set in IB.
        _fullPath = CGPathCreateMutable();
        _drawnPath = CGPathCreateMutable();
        _lineWidth = DEFAULT_WIDTH;
        _lineColor = DEFAULT_COLOR;
        _empty = YES;
        _pathSnapshots = [NSMutableArray new];
    }

    return self;
}

- (id) initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if (self)
    {
        self.backgroundColor = DEFAULT_BACKGROUND_COLOR;
        _fullPath = CGPathCreateMutable();
        _drawnPath = CGPathCreateMutable();
        _lineWidth = DEFAULT_WIDTH;
        _lineColor = DEFAULT_COLOR;
        _empty = YES;
        _pathSnapshots = [NSMutableArray new];
        self.multipleTouchEnabled = YES;
        self.bzPath = [UIBezierPath bezierPathWithCGPath:_fullPath];
    }

    return self;
}

-(void) dealloc
{
    CGPathRelease(_fullPath);
    CGPathRelease(_drawnPath);
}

- (void) updateWithTransform:(CGAffineTransform)transform
{
#if USE_SYNCHRONIZED
    @synchronized (self)
#endif
    {
    UIBezierPath* path = [self path];
    [path applyTransform:transform];
    [self setPath:path];
    [self setNeedsDisplay];

    for (UIBezierPath* path in self.pathSnapshots)
    {
        [path applyTransform:transform];
    }
    }
}

- (void) setBackgroundColor:(UIColor *)backgroundColor
{
    [super setBackgroundColor:backgroundColor];

    _bgColor = backgroundColor;
}

- (void) drawRect:(CGRect)rect
{
    // Empty drawRect for drawLayer
}

- (void) drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
#if USE_SYNCHRONIZED
    @synchronized (self)
#endif
    {
    CGContextSaveGState(context);
    CGRect rect = CGContextGetClipBoundingBox(context);
    // we use an internal property because drawRect is called from a background thread
    // and throws a warning if you try to access [UIView backgroundColor] while
    // not on the main thread.
    CGContextSetFillColorWithColor(context, self.bgColor.CGColor);
    CGContextFillRect(context, rect);
    CGContextAddPath(context, _fullPath);
    CGContextAddPath(context, _drawnPath);
    CGContextSetLineCap(context, kCGLineCapRound);
    CGContextSetLineWidth(context, self.lineWidth);
    CGContextSetStrokeColorWithColor(context, self.lineColor.CGColor);

    CGContextStrokePath(context);

    if (self.renderAsArea)
    {
        CGContextAddPath(context, _fullPath);
        CGContextAddPath(context, _drawnPath);
        CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
        CGContextSetAlpha(context, 0.2);
        CGContextFillPath(context);
    }
    CGContextRestoreGState(context);

    self.empty = NO;

    }
}

#pragma mark private Helper function

CGPoint midPoint(CGPoint p1, CGPoint p2) {
    return CGPointMake((p1.x + p2.x) * 0.5, (p1.y + p2.y) * 0.5);
}

#pragma mark Touch event handlers

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (event.allTouches.count == 1)
    {
        UITouch *touch = [touches anyObject];

        // initializes our point records to current location
        self.previousPoint = [touch previousLocationInView:self];
        self.previousPreviousPoint = [touch previousLocationInView:self];
        self.currentPoint = [touch locationInView:self];

#if USE_SYNCHRONIZED
        @synchronized (self)
#endif
        {
        CGPathMoveToPoint(_drawnPath, NULL, self.currentPoint.x, self.currentPoint.y);
        }
        LogMessage(INFO, @"Move to Point: (%@, %@)", @(self.currentPoint.x), @(self.currentPoint.y));
    }
}

- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (event.allTouches.count == 1)
    {
        UITouch *touch = [touches anyObject];

        /*
         CGPoint point = [touch locationInView:self];

         // if the finger has moved less than the min dist ...
         CGFloat dx = point.x - self.currentPoint.x;
         CGFloat dy = point.y - self.currentPoint.y;

         if ((dx * dx + dy * dy) < kPointMinDistanceSquared) {
         // ... then ignore this movement
         return;
         }
         */

        // update points: previousPrevious -> mid1 -> previous -> mid2 -> current
        self.previousPreviousPoint = self.previousPoint;
        self.previousPoint = [touch previousLocationInView:self];
        self.currentPoint = [touch locationInView:self];

        CGPoint mid2 = midPoint(self.currentPoint, self.previousPoint);

        // to represent the finger movement, add a quadratic bezier path
        // from current point to mid2, using previous as a control point
#if USE_SYNCHRONIZED
        @synchronized (self)
#endif
        {
        CGPathAddQuadCurveToPoint(_drawnPath, NULL,
                                  self.previousPoint.x, self.previousPoint.y,
                                  mid2.x, mid2.y);
        }
        LogMessage(INFO, @"Quad Curve to Point: (%@, %@), CP (%@, %@)", @(mid2.x), @(mid2.y), @(self.previousPoint.x), @(self.previousPoint.y));
    }

    [self setNeedsDisplayInRect:CGPathGetBoundingBox(_drawnPath)];
}

- (void) touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
#if USE_SYNCHRONIZED
    @synchronized (self)
#endif
    {
        if (event.allTouches.count == 1)
        {
            UIBezierPath* drawnPath = [UIBezierPath bezierPathWithCGPath:_drawnPath];
            UIBezierPath* fullPath = [UIBezierPath bezierPathWithCGPath:_fullPath];
            LogMessage(INFO, @"Touch Ended - Path: %@", drawnPath);
            if (!drawnPath.empty && (drawnPath.bounds.size.width != 0 && drawnPath.bounds.size.height != 0))
            {
                [fullPath appendPath:drawnPath];
                CGMutablePathRef oldPath = _fullPath;
                CGPathRelease(oldPath);
                _fullPath = CGPathCreateMutableCopy(fullPath.CGPath);
                self.bzPath = fullPath;
                [self.pathSnapshots addObject:self.bzPath];
            }

            CGMutablePathRef oldPath = _drawnPath;
            CGPathRelease(oldPath);
            _drawnPath = CGPathCreateMutable();
        }
    }
}

- (void) replaceCGPathsWithNewPath:(UIBezierPath*)path
{
#if USE_SYNCHRONIZED
    @synchronized (self)
#endif
    {
    CGMutablePathRef oldPath = _fullPath;
    CGPathRelease(oldPath);
    _fullPath = path == nil ? CGPathCreateMutable() : CGPathCreateMutableCopy(path.CGPath);

    oldPath = _drawnPath;
    CGPathRelease(oldPath);
    _drawnPath = CGPathCreateMutable();
    }
}

#pragma mark interface

- (void) clearDrawing
{
    [self replaceCGPathsWithNewPath:nil];

    [self setNeedsDisplay];
}

-(void) clear
{
    [self clearPath];

    self.pathSnapshots = [NSMutableArray new];
    [self setNeedsDisplay];
}

- (void) clearPath
{
#if USE_SYNCHRONIZED
    @synchronized (self)
#endif
    {
        [self replaceCGPathsWithNewPath:nil];
        self.bzPath = [UIBezierPath bezierPathWithCGPath:_fullPath];
    }
}

- (UIBezierPath*) path
{
    return self.bzPath;
}

- (void) setPath:(UIBezierPath*) bezierPath
{
    NSAssert(bezierPath != nil, @"Bezier path should not be nil");
#if USE_SYNCHRONIZED
    @synchronized (self)
#endif
    {
        [self replaceCGPathsWithNewPath:bezierPath];
        self.bzPath = [bezierPath copy];
    }
}

- (BOOL) didChange
{
    return !self.path.isEmpty
    && (self.path.bounds.size.width > 0 || self.path.bounds.size.height > 0);
}

- (void) closeSubpath
{
    //
    // According to documentation, when a path is filled, all inner subpaths
    // are implicitly closed so the the fill rule can be applied.
    //
    // https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIBezierPath_class/#//apple_ref/occ/instm/UIBezierPath/fill
    //  | This method fills the path using the current fill color and drawing properties. If the path contains any open subpaths, this method implicitly closes them before painting the fill region.
    //
#if USE_SYNCHRONIZED
    @synchronized (self)
#endif
    {
    CGPathCloseSubpath(_fullPath);
    }
    [self setNeedsDisplay];
}

- (void) undo
{
    [self.pathSnapshots removeLastObject];
    if (self.pathSnapshots.count > 0)
    {
        UIBezierPath* path = [self.pathSnapshots lastObject];
        [self setPath:path];
    }
    else
    {
        [self clearPath];
    }

    [self setNeedsDisplay];
}

@end


text:
"""
Tests for database migrations. The test case runs a series of test cases to
ensure that migrations work properly both upgrading and downgrading, and that
no data loss occurs if possible.
"""

import os
import unittest2 as unittest
import urlparse

from migrate.versioning.repository import Repository
from sqlalchemy import *
from sqlalchemy.pool import NullPool

import keystone.backends.sqlalchemy.migration as migration_api
from keystone.logic.types import fault

class TestMigrations(unittest.TestCase):

    """Test sqlalchemy-migrate migrations"""

    TEST_DATABASES = {'sqlite': 'sqlite:///migration.db'}

    REPOSITORY_PATH = os.path.abspath(os.path.join(os.path.abspath(__file__),
                                os.pardir, os.pardir, os.pardir, 'backends',
                                'sqlalchemy', 'migrate_repo'))
    REPOSITORY = Repository(REPOSITORY_PATH)

    def __init__(self, *args, **kwargs):
        super(TestMigrations, self).__init__(*args, **kwargs)

    def setUp(self):
        # Load test databases
        self.engines = {}
        for key, value in TestMigrations.TEST_DATABASES.items():
            self.engines[key] = create_engine(value, poolclass=NullPool)

        # We start each test case with a completely blank slate.
        self._reset_databases()

    def tearDown(self):
        # We destroy the test data store between each test case,
        # and recreate it, which ensures that we have no side-effects
        # from the tests
        self._reset_databases()

    def _reset_databases(self):
        for key, engine in self.engines.items():
            conn_string = TestMigrations.TEST_DATABASES[key]
            conn_pieces = urlparse.urlparse(conn_string)
            if conn_string.startswith('sqlite'):
                # We can just delete the SQLite database, which is
                # the easiest and cleanest solution
                db_path = conn_pieces.path.strip('/')
                if os.path.exists(db_path):
                    os.unlink(db_path)
                # No need to recreate the SQLite DB. SQLite will
                # create it for us if it's not there...
            elif conn_string.startswith('mysql'):
                # We can execute the MySQL client to destroy and re-create
                # the MYSQL database, which is easier and less error-prone
                # than using SQLAlchemy to do this via MetaData...trust me.
                database = conn_pieces.path.strip('/')
                loc_pieces = conn_pieces.netloc.split('@')
                host = loc_pieces[1]
                auth_pieces = loc_pieces[0].split(':')
                user = auth_pieces[0]
                password = ""
                if len(auth_pieces) > 1:
                    if auth_pieces[1].strip():
                        password = "-p%s" % auth_pieces[1]
                sql = ("drop database if exists %(database)s; "
                       "create database %(database)s;") % locals()
                cmd = ("mysql -u%(user)s %(password)s -h%(host)s "
                       "-e\"%(sql)s\"") % locals()
                exitcode, out, err = execute(cmd)
                self.assertEqual(0, exitcode)

    def test_walk_versions(self):
        """
        Walks all version scripts for each tested database, ensuring
        that there are no errors in the version scripts for each engine
        """
        for key, engine in self.engines.items():
            self._walk_versions(TestMigrations.TEST_DATABASES[key])

    def _walk_versions(self, sql_connection):
        # Determine latest version script from the repo, then
        # upgrade from 1 through to the latest, with no data
        # in the databases. This just checks that the schema itself
        # upgrades successfully.

        # Assert we are not under version control...
        self.assertRaises(fault.DatabaseMigrationError,
                          migration_api.db_version,
                          sql_connection)
        # Place the database under version control
        print migration_api.version_control(sql_connection)

        cur_version = migration_api.db_version(sql_connection)
        self.assertEqual(0, cur_version)

        for version in xrange(1, TestMigrations.REPOSITORY.latest + 1):
            migration_api.upgrade(sql_connection, version)
            cur_version = migration_api.db_version(sql_connection)
            self.assertEqual(cur_version, version)

        # Now walk it back down to 0 from the latest, testing
        # the downgrade paths.
        for version in reversed(
            xrange(0, TestMigrations.REPOSITORY.latest)):
            migration_api.downgrade(sql_connection, version)
            cur_version = migration_api.db_version(sql_connection)
            self.assertEqual(cur_version, version)

if __name__ == '__main__':
    unittest.main()


text:
:orphan:

Jinja2 Documentation
====================

.. include:: contents.rst.inc


text:
package namesys

import (
	"fmt"
	"time"

	lru "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/hashicorp/golang-lru"
	mh "gx/ipfs/QmYf7ng2hG5XBtJA3tN34DQ2GUN5HNksEw1rLDkmr6vGku/go-multihash"
	proto "gx/ipfs/QmZ4Qi3GaRbjcx28Sme5eMH7RQjGkt8wHxt2a65oLaeFEV/gogo-protobuf/proto"
	"gx/ipfs/QmZy2y8t9zQH2a1b8q2ZSLKp17ATuJoCNxxyMFG5qFExpt/go-net/context"

	key "github.com/ipfs/go-ipfs/blocks/key"
	pb "github.com/ipfs/go-ipfs/namesys/pb"
	path "github.com/ipfs/go-ipfs/path"
	routing "github.com/ipfs/go-ipfs/routing"
	ci "gx/ipfs/QmNefBbWHR9JEiP3KDVqZsBLQVRmH3GBG2D2Ke24SsFqfW/go-libp2p/p2p/crypto"
	u "gx/ipfs/QmZNVWh8LLjAavuQ2JXuFmuYH3C11xo988vSgp7UQrTRj1/go-ipfs-util"
	logging "gx/ipfs/Qmazh5oNUVsDZTs2g59rq8aYQqwpss8tcUWQzor5sCCEuH/go-log"
)

var log = logging.Logger("namesys")

// routingResolver implements NSResolver for the main IPFS SFS-like naming
type routingResolver struct {
	routing routing.IpfsRouting

	cache *lru.Cache
}

func (r *routingResolver) cacheGet(name string) (path.Path, bool) {
	if r.cache == nil {
		return "", false
	}

	ientry, ok := r.cache.Get(name)
	if !ok {
		return "", false
	}

	entry, ok := ientry.(cacheEntry)
	if !ok {
		// should never happen, purely for sanity
		log.Panicf("unexpected type %T in cache for %q.", ientry, name)
	}

	if time.Now().Before(entry.eol) {
		return entry.val, true
	}

	r.cache.Remove(name)

	return "", false
}

func (r *routingResolver) cacheSet(name string, val path.Path, rec *pb.IpnsEntry) {
	if r.cache == nil {
		return
	}

	// if completely unspecified, just use one minute
	ttl := DefaultResolverCacheTTL
	if rec.Ttl != nil {
		recttl := time.Duration(rec.GetTtl())
		if recttl >= 0 {
			ttl = recttl
		}
	}

	cacheTil := time.Now().Add(ttl)
	eol, ok := checkEOL(rec)
	if ok && eol.Before(cacheTil) {
		cacheTil = eol
	}

	r.cache.Add(name, cacheEntry{
		val: val,
		eol: cacheTil,
	})
}

type cacheEntry struct {
	val path.Path
	eol time.Time
}

// NewRoutingResolver constructs a name resolver using the IPFS Routing system
// to implement SFS-like naming on top.
// cachesize is the limit of the number of entries in the lru cache. Setting it
// to '0' will disable caching.
func NewRoutingResolver(route routing.IpfsRouting, cachesize int) *routingResolver {
	if route == nil {
		panic("attempt to create resolver with nil routing system")
	}

	var cache *lru.Cache
	if cachesize > 0 {
		cache, _ = lru.New(cachesize)
	}

	return &routingResolver{
		routing: route,
		cache:   cache,
	}
}

// Resolve implements Resolver.
func (r *routingResolver) Resolve(ctx context.Context, name string) (path.Path, error) {
	return r.ResolveN(ctx, name, DefaultDepthLimit)
}

// ResolveN implements Resolver.
func (r *routingResolver) ResolveN(ctx context.Context, name string, depth int) (path.Path, error) {
	return resolve(ctx, r, name, depth, "/ipns/")
}

// resolveOnce implements resolver. Uses the IPFS routing system to
// resolve SFS-like names.
func (r *routingResolver) resolveOnce(ctx context.Context, name string) (path.Path, error) {
	log.Debugf("RoutingResolve: '%s'", name)
	cached, ok := r.cacheGet(name)
	if ok {
		return cached, nil
	}

	hash, err := mh.FromB58String(name)
	if err != nil {
		// name should be a multihash. if it isn't, error out here.
		log.Warningf("RoutingResolve: bad input hash: [%s]\n", name)
		return "", err
	}

	// use the routing system to get the name.
	// /ipns/<name>
	h := []byte("/ipns/" + string(hash))

	var entry *pb.IpnsEntry
	var pubkey ci.PubKey

	resp := make(chan error, 2)
	go func() {
		ipnsKey := key.Key(h)
		val, err := r.routing.GetValue(ctx, ipnsKey)
		if err != nil {
			log.Warning("RoutingResolve get failed.")
			resp <- err
		}

		entry = new(pb.IpnsEntry)
		err = proto.Unmarshal(val, entry)
		if err != nil {
			resp <- err
		}
		resp <- nil
	}()

	go func() {
		// name should be a public key retrievable from ipfs
		pubk, err := routing.GetPublicKey(r.routing, ctx, hash)
		if err != nil {
			resp <- err
		}
		pubkey = pubk
		resp <- nil
	}()

	for i := 0; i < 2; i++ {
		err = <-resp
		if err != nil {
			return "", err
		}
	}

	hsh, _ := pubkey.Hash()
	log.Debugf("pk hash = %s", key.Key(hsh))

	// check sig with pk
	if ok, err := pubkey.Verify(ipnsEntryDataForSig(entry), entry.GetSignature()); err != nil || !ok {
		return "", fmt.Errorf("Invalid value. Not signed by PrivateKey corresponding to %v", pubkey)
	}

	// ok sig checks out. this is a valid name.

	// check for old style record:
	valh, err := mh.Cast(entry.GetValue())
	if err != nil {
		// Not a multihash, probably a new record
		p, err := path.ParsePath(string(entry.GetValue()))
		if err != nil {
			return "", err
		}

		r.cacheSet(name, p, entry)
		return p, nil
	} else {
		// Its an old style multihash record
		log.Warning("Detected old style multihash record")
		p := path.FromKey(key.Key(valh))
		r.cacheSet(name, p, entry)
		return p, nil
	}
}

func checkEOL(e *pb.IpnsEntry) (time.Time, bool) {
	if e.GetValidityType() == pb.IpnsEntry_EOL {
		eol, err := u.ParseRFC3339(string(e.GetValidity()))
		if err != nil {
			return time.Time{}, false
		}
		return eol, true
	}
	return time.Time{}, false
}


text:
$:.unshift File.join(File.dirname(__FILE__))
require 'cli'
require 'git/commands'
require 'git/release_notes'
require 'git/tagger'
require 'git/wiki'
require 'qa_release_tasks/version'

if defined?(Rails)
  require 'qa_release_tasks/railtie'
else
  require 'qa_release_tasks/tasks/qa_release'
end

module QaReleaseTasks
  def self.version
    VERSION
  end
end


text:
namespace base {
class DictionaryValue;
class SingleThreadTaskRunner;
}

namespace net {
class HttpServerRequestInfo;
class HttpServerResponseInfo;
}

class Adb;
class DeviceManager;
class PortManager;
class PortServer;
class URLRequestContextGetter;

enum HttpMethod {
  kGet,
  kPost,
  kDelete,
};

struct CommandMapping {
  CommandMapping(HttpMethod method,
                 const std::string& path_pattern,
                 const Command& command);
  ~CommandMapping();

  HttpMethod method;
  std::string path_pattern;
  Command command;
};

typedef base::Callback<void(scoped_ptr<net::HttpServerResponseInfo>)>
    HttpResponseSenderFunc;

class HttpHandler {
 public:
  explicit HttpHandler(const std::string& url_base);
  HttpHandler(const base::Closure& quit_func,
              const scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
              const std::string& url_base,
              int adb_port,
              scoped_ptr<PortServer> port_server);
  ~HttpHandler();

  void Handle(const net::HttpServerRequestInfo& request,
              const HttpResponseSenderFunc& send_response_func);

 private:
  FRIEND_TEST_ALL_PREFIXES(HttpHandlerTest, HandleUnknownCommand);
  FRIEND_TEST_ALL_PREFIXES(HttpHandlerTest, HandleNewSession);
  FRIEND_TEST_ALL_PREFIXES(HttpHandlerTest, HandleInvalidPost);
  FRIEND_TEST_ALL_PREFIXES(HttpHandlerTest, HandleUnimplementedCommand);
  FRIEND_TEST_ALL_PREFIXES(HttpHandlerTest, HandleCommand);
  typedef std::vector<CommandMapping> CommandMap;

  Command WrapToCommand(const char* name,
                        const SessionCommand& session_command);
  Command WrapToCommand(const char* name, const WindowCommand& window_command);
  Command WrapToCommand(const char* name,
                        const ElementCommand& element_command);
  void HandleCommand(const net::HttpServerRequestInfo& request,
                     const std::string& trimmed_path,
                     const HttpResponseSenderFunc& send_response_func);
  void PrepareResponse(const std::string& trimmed_path,
                       const HttpResponseSenderFunc& send_response_func,
                       const Status& status,
                       scoped_ptr<base::Value> value,
                       const std::string& session_id);
  scoped_ptr<net::HttpServerResponseInfo> PrepareResponseHelper(
      const std::string& trimmed_path,
      const Status& status,
      scoped_ptr<base::Value> value,
      const std::string& session_id);

  base::ThreadChecker thread_checker_;
  base::Closure quit_func_;
  std::string url_base_;
  bool received_shutdown_;
  scoped_refptr<URLRequestContextGetter> context_getter_;
  SyncWebSocketFactory socket_factory_;
  SessionThreadMap session_thread_map_;
  scoped_ptr<CommandMap> command_map_;
  scoped_ptr<Adb> adb_;
  scoped_ptr<DeviceManager> device_manager_;
  scoped_ptr<PortServer> port_server_;
  scoped_ptr<PortManager> port_manager_;

  base::WeakPtrFactory<HttpHandler> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(HttpHandler);
};

namespace internal {

extern const char kNewSessionPathPattern[];

bool MatchesCommand(const std::string& method,
                    const std::string& path,
                    const CommandMapping& command,
                    std::string* session_id,
                    base::DictionaryValue* out_params);

}  // namespace internal

#endif  // CHROME_TEST_CHROMEDRIVER_SERVER_HTTP_HANDLER_H_


text:
package x7c1.linen.database.struct

import android.database.Cursor
import x7c1.linen.repository.date.Date
import x7c1.wheat.macros.database.TypedFields.toArgs
import x7c1.wheat.macros.database.{TypedCursor, TypedFields}
import x7c1.wheat.modern.database.selector.presets.{CanFindRecord, DefaultProvidable}
import x7c1.wheat.modern.database.selector.{IdEndo, Identifiable, RecordReifiable}
import x7c1.wheat.modern.database.{HasTable, Insertable, Updatable}

trait ChannelStatusRecord extends TypedFields {
  def channel_id: Long
  def account_id: Long
  def channel_rank: Double
  def subscribed: Int --> Boolean
  def created_at: Int --> Date
  def updated_at: Int --> Date
}

object ChannelStatusRecord {
  def table: String = "channel_statuses"

  def column = TypedFields.expose[ChannelStatusRecord]

  implicit object hasTable extends HasTable.Where[ChannelStatusRecord](table)

  implicit object providable
    extends DefaultProvidable[HasChannelStatusKey, ChannelStatusRecord]

  implicit object reifiable extends RecordReifiable[ChannelStatusRecord]{
    override def reify(cursor: Cursor) = TypedCursor[ChannelStatusRecord](cursor)
  }
  implicit object findable extends CanFindRecord.Where[HasChannelStatusKey, ChannelStatusRecord]{
    override def where[X](key: ChannelStatusKey) = toArgs(
      column.account_id -> key.accountId,
      column.channel_id -> key.channelId
    )
  }
}

case class ChannelStatusKey (
  channelId: Long,
  accountId: Long
)
object ChannelStatusKey {
  implicit object id
    extends HasChannelStatusKey[ChannelStatusKey]
      with IdEndo[ChannelStatusKey]

  implicit def key[A: HasAccountId, B: HasChannelId]: HasChannelStatusKey[(A, B)] =
    new HasChannelStatusKey[(A, B)]{
      override def toId = {
        case (account, channel) => ChannelStatusKey(
          channelId = implicitly[HasChannelId[B]] toId channel,
          accountId = implicitly[HasAccountId[A]] toId account
        )
      }
    }
}

trait HasChannelStatusKey[A] extends Identifiable[A, ChannelStatusKey]

case class ChannelStatusRecordParts(
  channelId: Long,
  accountId: Long,
  channelRank: Double,
  subscribed: Boolean
)
object ChannelStatusRecordParts {
  import ChannelStatusRecord.column

  implicit object updatable extends Updatable[ChannelStatusRecordParts]{
    override def tableName = ChannelStatusRecord.table
    override def toContentValues(target: ChannelStatusRecordParts) = {
      TypedFields toContentValues (
        column.account_id -> target.accountId,
        column.channel_id -> target.channelId,
        column.channel_rank -> target.channelRank,
        column.updated_at -> Date.current(),
        column.subscribed -> target.subscribed
      )
    }
    override def where(target: ChannelStatusRecordParts) = toArgs(
      column.channel_id -> target.channelId,
      column.account_id -> target.accountId
    )
  }
  implicit object insertable extends Insertable[ChannelStatusRecordParts]{
    override def tableName = ChannelStatusRecord.table
    override def toContentValues(target: ChannelStatusRecordParts) = {
      TypedFields toContentValues (
        column.account_id -> target.accountId,
        column.channel_id -> target.channelId,
        column.channel_rank -> target.channelRank,
        column.subscribed -> target.subscribed,
        column.updated_at -> Date.current(),
        column.created_at -> Date.current()
      )
    }
  }
}

case class ChannelRankParts(
  accountId: Long,
  channelId: Long,
  channelRank: Double
)
object ChannelRankParts {
  import ChannelStatusRecord.column

  implicit object updatable extends Updatable[ChannelRankParts]{
    override def tableName = ChannelStatusRecord.table
    override def toContentValues(target: ChannelRankParts) = {
      TypedFields toContentValues (
        column.account_id -> target.accountId,
        column.channel_id -> target.channelId,
        column.channel_rank -> target.channelRank,
        column.updated_at -> Date.current()
      )
    }
    override def where(target: ChannelRankParts) = toArgs(
      column.channel_id -> target.channelId,
      column.account_id -> target.accountId
    )
  }

  def apply[A: HasChannelStatusKey](origin: A, channelRank: Double): ChannelRankParts = {
    val key = implicitly[HasChannelStatusKey[A]] toId origin
    new ChannelRankParts(
      accountId = key.accountId,
      channelId = key.channelId,
      channelRank = channelRank
    )
  }
}