text:
<?php
class Chart
{
	protected $strSQL;

	protected $header;
	protected $footer;

	protected $y_axis_label;

	protected $strLabel;

	protected $arrDataLabels = array();
	protected $arrDataSeries = array();

	protected $chrt_array = array();
	public $webchart;
	protected $cname;

	protected $gstrOrderBy;

	protected $table_type;

	protected $cipherer = null;
	protected $pSet = null;
	protected $searchClauseObj = null;

	protected $sessionPrefix = "";

	protected $detailTablesData = array();

	protected $pageId;

	/**
	 * A flag helping to detect if to apply
	 * 'details' functionality to the chart
	 */
	protected $showDetails = true;

	protected $chartPreview = false;

	/**
	 * It indicates if chart is shown on a dashboard
	 */
	protected $dashChart = false;

	/**
	 * It indicates if first point selected
	 */
	protected $dashChartFirstPointSelected = false;

	protected $detailMasterKeys = "";

	/**
	 * Dashboard table name
	 * It's set up if chart is shown on a dashboard only
	 */
	protected $dashTName = "";

	/**
	 * Dashboard element name
	 * It's set up if chart is shown on a dashboard only
	 */
	protected $dashElementName = "";

	/**
	 * @type Connection
	 */
	protected $connection;

	/**
	 *
	 */
	protected $_2d;

	/**
	 *
	 */
	protected $noRecordsFound = false;

	/**
	 *
	 */
	protected $singleSeries = false;

	function __construct( &$ch_array, $param )
	{
		global $strTableName;

		$this->webchart = $param["webchart"];

		if( $this->webchart )
			$this->chrt_array = Convert_Old_Chart($ch_array);
		else
			$this->chrt_array = $ch_array;

		// #10461, $this->setConnection(); needs to be called after value is assigned to $this->webchart
		$this->setConnection();

		$this->pSet = new ProjectSettings( $this->chrt_array['tables'][0] );
		$this->showDetails = $param['showDetails'];
		if( $this->showDetails )
		{
			$this->detailTablesData = $this->pSet->getDetailTablesArr();
			for($i = 0; $i < count($this->detailTablesData); $i ++)
			{
				$strPerm = GetUserPermissions($this->detailTablesData[$i]['dDataSourceTable']);
				if ( strpos($strPerm, "S") === false )
					unset($this->detailTablesData[$i]);
			}
		}

		$this->pageId = $param["pageId"];
		$this->chrt_array["appearance"]["autoupdate"] = false; //?

		$this->table_type = $this->chrt_array["table_type"];
		if( !$this->table_type )
			$this->table_type = "project";

		$this->cname = $param["cname"];

		$this->sessionPrefix = $this->chrt_array['tables'][0];

		$this->chartPreview = $param["chartPreview"];
		$this->dashChart = $param["dashChart"];

		if( $this->dashChart )
		{
			$this->dashTName = $param["dashTName"];
			$this->dashElementName = $param["dashElementName"];
			$this->sessionPrefix = $this->dashTName."_".$this->sessionPrefix;
		}

		$this->gstrOrderBy = $param["gstrOrderBy"];

		if( !$this->webchart && !$this->chartPreview && isset( $_SESSION[ $this->sessionPrefix.'_advsearch' ] ) )
			$this->searchClauseObj = SearchClause::UnserializeObject( $_SESSION[ $this->sessionPrefix.'_advsearch' ] );

		if( $this->isProjectDB() )
			$this->cipherer = new RunnerCipherer( $this->chrt_array['tables'][0] );

		$this->setBasicChartProp();

		$this->strSQL = $this->getSQL();

		if( tableEventExists("UpdateChartSettings", $strTableName) )
		{
			$eventObj = getEventObject( $strTableName );
			$eventObj->UpdateChartSettings( $this );
		}
	}

	/**
	 * @param Array params
	 */
	protected function setSpecParams( $params )
	{
		if( $params['name'] == "" )
			return;

		if( $this->table_type != "db" )
			$this->arrDataSeries[] = $params['agr_func'] ? $params['label'] : $params['name'];
		else
			$this->arrDataSeries[] = $params['agr_func'] ? $params['agr_func']."_".$params['table']."_".$params['name'] : $params['table']."_".$params['name'];
	}

	/**
	 * @param Array params
	 * @param String gTableName
	 */
	protected function setDataLabels( $params, $gTableName )
	{
		$chartType = $this->chrt_array["chart_type"]["type"];
		if( $this->table_type == "project" && !$this->webchart )
		{
			if( $chartType != "candlestick" && $chartType != "ohlc" )
				$this->arrDataLabels[] = $this->chart_xmlencode( GetFieldLabel( $gTableName, GoodFieldName($params['name']) ) );
			else
				$this->arrDataLabels[] = $this->chart_xmlencode( GetFieldLabel( $gTableName, GoodFieldName($params['ohlcOpen']) ) );
		}
		else
		{
			if( !$this->chart_xmlencode($params['label']) )
			{
				if( $chartType != "candlestick" && $chartType != "ohlc" )
					$this->arrDataLabels[] = $this->chart_xmlencode( $params['name'] );
				else
					$this->arrDataLabels[] = $this->chart_xmlencode( $params['ohlcOpen'] );
			}
			else
				$this->arrDataLabels[] = $this->chart_xmlencode( $params['label'] );
		}
	}

	/**
	 *
	 */
	protected function setBasicChartProp()
	{
		$this->header = $this->chrt_array['appearance']['head'];
		$this->footer = $this->chrt_array['appearance']['foot'];

		for ( $i = 0; $i<count($this->chrt_array['parameters']) - 1; $i++)
		{
			$this->setSpecParams( $this->chrt_array['parameters'][$i] );
			$this->setDataLabels( $this->chrt_array['parameters'][$i], GoodFieldName( $this->chrt_array['tables'][0] ) );
		}

		if( $this->chrt_array["chart_type"]["type"] != "gauge" )
		{
			$chartParams = $this->chrt_array['parameters'];
			$params = $chartParams[ count($chartParams) - 1 ];

			if( $this->table_type != "db" )
				$this->strLabel = $params['name'];
			else
				$this->strLabel = $params['agr_func'] ? $params['agr_func']."_".$params['table']."_".$params['name']: $params['table']."_".$params['name'];
		}

		if( count( $this->arrDataLabels ) == 1 )
			$this->y_axis_label = $this->arrDataLabels[0];
		else
			$this->y_axis_label = $this->chrt_array['appearance']['y_axis_label'];
	}

	/**
	 * @return String
	 */
	protected function getMasterWhere()
	{
		if( $this->dashChart )
			return "";

		$masterTable = $_SESSION[ $this->sessionPrefix."_mastertable" ];
		$detailKeysByM = $this->pSet->getDetailKeysByMasterTable( $masterTable );
		$masterWhereParts = array();

		for($i = 0; $i < count($detailKeysByM); $i++)
		{
			if( $this->cipherer && $this->cipherer->isEncryptionByPHPEnabled() )
				$mValue = $this->cipherer->MakeDBValue( $detailKeysByM[$i], $_SESSION[ $this->sessionPrefix."_masterkey".($i + 1) ] );
			else
				$mValue = make_db_value( $detailKeysByM[$i], $_SESSION[ $this->sessionPrefix."_masterkey".($i + 1) ] );

			if( strlen($mValue) != 0 )
				$masterWhereParts[] = RunnerPage::_getFieldSQLDecrypt( $detailKeysByM[$i], $this->connection, $this->pSet, $this->cipherer )."=".$mValue;
			else
				$masterWhereParts[] = "1=0";
		}

		return implode( " and ", $masterWhereParts );
	}

	/**
	 * @return String
	 */
	protected function getSQL()
	{
		global $strTableName;

		// prepare search params
		$gQuery = $this->pSet->getSQLQuery();

		$masterWhere = $this->getMasterWhere();
		$strWhereClause = "";
		$searchHavingClause = "";
		$strSearchCriteria = "and";

		// search where for basic charts
		if( !$this->webchart )
		{
			if( !$this->chartPreview && $this->searchClauseObj )
			{
				include_once getabspath('classes/controls/EditControlsContainer.php');
				$editControls = new EditControlsContainer( null, $this->pSet, PAGE_SEARCH, $this->cipherer );

				$whereComponents = RunnerPage::sGetWhereComponents( $gQuery, $this->pSet, $this->searchClauseObj, $editControls, $this->connection );
				$strWhereClause = $whereComponents["searchWhere"];
				foreach($whereComponents["filterWhere"] as $fWhere)
				{
					$strWhereClause = whereAdd($strWhereClause, $fWhere);
				}

				$searchHavingClause = $whereComponents["searchHaving"];
				foreach($whereComponents["filterHaving"] as $fHaving)
				{
					$searchHavingClause = whereAdd($searchHavingClause, $fHaving);
				}

				$strSearchCriteria = $whereComponents["searchUnionRequired"] ? "or" : "and";
			}
		}
		else
		{
			if($this->table_type != "project")
				$strTableName = "webchart".$this->cname;

			$strWhereClause = CalcSearchParam($this->table_type != "project");
		}

		if ($strWhereClause)
		{
			$this->chrt_array['where'] .= ($this->chrt_array['where']) ?
				" AND (" . $strWhereClause . ")" :
				" WHERE (" . $strWhereClause . ")";
		}

		if($this->table_type == "project")
		{
			if(SecuritySQL("Search", $this->chrt_array['tables'][0]))
			{
				$strWhereClause = whereAdd($strWhereClause, SecuritySQL("Search", $strTableName ));
			}
			$strSQL = $gQuery->gSQLWhere($strWhereClause,$searchHavingClause, $strSearchCriteria);

			$strOrderBy = $this->gstrOrderBy;
			$strSQL.= " ".$strOrderBy;

			if( $masterWhere )
				$strWhereClause = whereAdd($strWhereClause, $masterWhere);

			$strSQLbak = $strSQL;
			if(tableEventExists("BeforeQueryChart",$strTableName))
			{
				$tstrSQL = $strSQL;
				$eventObj = getEventObject($strTableName);
				$eventObj->BeforeQueryChart($tstrSQL,$strWhereClause,$strOrderBy);
				$strSQL = $tstrSQL;
			}
			if($strSQLbak == $strSQL)
			{
				$strSQL = $gQuery->gSQLWhere($strWhereClause, $searchHavingClause, $strSearchCriteria);
				$strSQL.= " ".$strOrderBy;
			}
		}

		if ($this->cname && $this->table_type == "db")
			$strSQL = $this->chrt_array['sql'] . $this->chrt_array['where'] . $this->chrt_array['group_by'] . $this->chrt_array['order_by'];
		elseif ($this->cname && $this->table_type == "custom")
		{
			if(!IsStoredProcedure($this->chrt_array['sql']))
			{
				$sql_query=$this->chrt_array['sql'];

				if( $this->connection->dbType == nDATABASE_MSSQLServer )
				{
					$pos=strrpos(strtoupper($sql_query),"ORDER BY");
					if($pos)
						$sql_query=substr($sql_query,0,$pos);
				}

				if( $this->connection->dbType != nDATABASE_Oracle )
					$strSQL = "select * from (".$sql_query.") as ".$this->connection->addFieldWrappers("custom_query").$this->chrt_array['where'];
				else
					$strSQL = "select * from (".$sql_query.")". $this->chrt_array['where'];
			}
			else
			{
				$strSQL = $this->chrt_array['sql'];
			}
		}

		return $strSQL;
	}

	/**
	 * Check for a web chart if it's based on the project table
	 * @return Boolean
	 */
	protected function isProjectDB()
	{
		if( !$this->webchart )
			return true;

		if("transactions" == $this->chrt_array['tables'][0])
			return true;
		if("accounts" == $this->chrt_array['tables'][0])
			return true;
		if("users" == $this->chrt_array['tables'][0])
			return true;
		if("LookUps" == $this->chrt_array['tables'][0])
			return true;
		if("users" == $this->chrt_array['tables'][0])
			return true;
		if("accounts" == $this->chrt_array['tables'][0])
			return true;
		if("accounts" == $this->chrt_array['tables'][0])
			return true;
		if("transactions" == $this->chrt_array['tables'][0])
			return true;
		if("transactions" == $this->chrt_array['tables'][0])
			return true;
		if("transactions" == $this->chrt_array['tables'][0])
			return true;
		if("transactions" == $this->chrt_array['tables'][0])
			return true;
		if("transactions" == $this->chrt_array['tables'][0])
			return true;
		if("transactions" == $this->chrt_array['tables'][0])
			return true;
		if("transactions" == $this->chrt_array['tables'][0])
			return true;
		if("accounts" == $this->chrt_array['tables'][0])
			return true;
		if("transactions" == $this->chrt_array['tables'][0])
			return true;
		if("recordidcounter" == $this->chrt_array['tables'][0])
			return true;
		if("transactions" == $this->chrt_array['tables'][0])
			return true;
		if("transactions" == $this->chrt_array['tables'][0])
			return true;
		if("transactions" == $this->chrt_array['tables'][0])
			return true;
		if("transactions" == $this->chrt_array['tables'][0])
			return true;
		if("accounts" == $this->chrt_array['tables'][0])
			return true;
		if("accounts" == $this->chrt_array['tables'][0])
			return true;
		if("accounts" == $this->chrt_array['tables'][0])
			return true;
		if("transactions" == $this->chrt_array['tables'][0])
			return true;
		if("transactions" == $this->chrt_array['tables'][0])
			return true;
		if("users" == $this->chrt_array['tables'][0])
			return true;
		if("accounts" == $this->chrt_array['tables'][0])
			return true;
		if("finance_ugrights" == $this->chrt_array['tables'][0])
			return true;
		if("users" == $this->chrt_array['tables'][0])
			return true;
		if("users" == $this->chrt_array['tables'][0])
			return true;
		if("users" == $this->chrt_array['tables'][0])
			return true;
		if("schedule" == $this->chrt_array['tables'][0])
			return true;
		if("loan" == $this->chrt_array['tables'][0])
			return true;
		return false;
	}

	/**
	 * Set the 'connection' property #9875
	 */
	protected function setConnection()
	{
		global $cman;

		if($this->isProjectDB())
			$this->connection = $cman->byTable( $this->chrt_array['tables'][0] );
		else
			$this->connection = $cman->getDefault();
	}

	public function setFooter($name)
	{
		$this->footer = $name;
	}

	public function getFooter()
	{
		return $this->footer;
	}

	public function setHeader($name)
	{
		$this->header = $name;
	}

	public function getHeader()
	{
		return $this->header;
	}

	public function setLabelField($name)
	{
		$this->strLabel = $name;
	}

	public function getLabelField()
	{
		return $this->strLabel;
	}

	/**
	 * @return String
	 */
	protected function getDetailedToolipMessage()
	{
		if( !$this->showDetails || !count( $this->detailTablesData ) )
			return "";

		$showClickHere = true;

		if( $this->dashChart )
		{
			$showClickHere = false;

			$pDSet = new ProjectSettings( $this->dashTName );
			$arrDElem = $pDSet->getDashboardElements();
			foreach($arrDElem as $elem)
			{
				if( $elem["table"] == $this->chrt_array['tables'][0] && count( $elem["details"] ) )
					$showClickHere = true;
			}
		}

		if( $showClickHere )
		{
			$tableCaption = GetTableCaption( $this->detailTablesData[0]['dDataSourceTable'] );
			$tableCaption = $tableCaption ? $tableCaption : $this->detailTablesData[0]['dDataSourceTable'];

			 return "\nClick here to see ".$tableCaption." details";
		}

		return "";
	}

	/**
	 * @return String
	 */
	protected function getNoDataMessage()
	{
		if( !$this->noRecordsFound )
			return "";

		if( !$this->searchClauseObj )
			return "No data yet.";

		if( $this->searchClauseObj->isSearchFunctionalityActivated() )
			return "No results found.";

		return "No data yet.";
	}

	/**
	 *
	 */
	public function write()
	{
		$data = array();
		$chart = array();

		$this->setTypeSpecChartSettings( $chart );

		if( $this->noRecordsFound )
		{
			$data["noDataMessage"] = $this->getNoDataMessage();
			echo my_json_encode( $data );
			return;
		}

		// animation
		if( $this->chrt_array["appearance"]["sanim"] == "true" && $this->chrt_array["appearance"]["autoupdate"] != "true" ) // update?
			$chart["animation"] = array("enabled" => "true", "duration" => 1000);

		// legend
		if( $this->chrt_array['appearance']['slegend'] == "true" && !$this->chartPreview )
			$chart["legend"] = array("enabled"=> "true");
		else
			$chart["legend"] = array("enabled"=> false);

		// title/header
		$chart["title"]	= array("enabled" => "true", "text" => $this->header);

		// assign and display
		$data["chart"] = $chart;
		echo my_json_encode( $data );
	}

	/**
	 * A stub
	 * @param &Array chart
	 */
	protected function setTypeSpecChartSettings( &$chart )
	{
	}

	/**
	 * @return Array
	 */
	protected function getGrids()
	{
		$grids = array();

		if($this->chrt_array["appearance"]["sgrid"] == "true")
		{
			$grids[] = array(
				"enabled" => true,
				"drawLastLine" => false,
				"stroke" => "#ddd",
				"scale" => 0,
				"axis" => 0
			);

			$grids[] = array(
				"enabled"=> true,
				"drawLastLine" => false,
				"stroke" => "#ddd",
				"axis" => 1
			);
		}

		return $grids;
	}

	/**
	 * @param String fieldName
	 * @param Array data
	 * @return String
	 */
	protected function labelFormat($fieldName, $data, $truncated = true)
	{
		if( $this->table_type == "db" && count( $this->chrt_array['customLabels'] ) )
			$fieldName = $this->chrt_array['customLabels'][ $fieldName ];

		include_once getabspath('classes/controls/ViewControlsContainer.php');
		$viewControls = new ViewControlsContainer($this->pSet, PAGE_CHART);
		$value = html_special_decode( $viewControls->showDBValue( $fieldName, $data ) );

		if( $truncated && strlen($value) > 50 )
			$value = substr($value, 0, 47)."...";

		return $this->chart_xmlencode( $value );
	}

	/**
	 * @return Array
	 */
	public function get_data()
	{
		$data = array();
		$clickdata = array();
		for ( $i = 0; $i < count($this->arrDataSeries); $i++ )
		{
			$data[$i] = array();
			$clickdata[$i] = array();
		}

		$qResult = $this->connection->query( $this->strSQL );

		if( $this->cipherer != null )
			$row = $this->cipherer->DecryptFetchedArray( $qResult->fetchAssoc() );
		else
			$row = $qResult->fetchAssoc();

		if( !$row )
			$this->noRecordsFound = true;

		while ($row)
		{
			for ( $i = 0; $i < count($this->arrDataSeries); $i++ )
			{
				$data[$i][] = $this->getPoint($i, $row);

				$strLabelFormat = $this->labelFormat( $this->strLabel, $row );
				$clickdata[$i][] = $this->getActions( $row , $this->arrDataSeries[$i], $strLabelFormat );
			}

			if( $this->cipherer != null )
				$row = $this->cipherer->DecryptFetchedArray( $qResult->fetchAssoc() );
			else
				$row = $qResult->fetchAssoc();
		}

		$this->connection->close();

		$series = array();
		for ( $i = 0; $i < count($this->arrDataSeries); $i++ )
		{
			$series[] = $this->getSeriesData( $this->arrDataLabels[$i], $data[$i], $clickdata[$i], $i);
		}

		return $series;
	}

	/**
	 * @param Number seriesNumber
	 * @param Array row
	 * @return Array
	 */
	protected function getPoint($seriesNumber, $row)
	{
		$strLabelFormat = $this->labelFormat( $this->strLabel, $row );

		if( $this->table_type != "db" || !count( $this->chrt_array['customLabels'] ) )
			$strDataSeries = $row[ $this->arrDataSeries[ $seriesNumber ] ];
		else
			$strDataSeries = $row[ $this->chrt_array['customLabels'][ $this->arrDataSeries[ $seriesNumber ] ] ];

		return array( "x" => $strLabelFormat , "value" => $this->chart_xmlencode( str_replace(",", ".", $strDataSeries) + 0 ) );
	}

	/**
	 * @param String name
	 * @param Array pointsData
	 * @param Array clickData
	 * @param Number seriesNumber
	 * @return Array
	 */
	protected function getSeriesData( $name, $pointsData, $clickData, $seriesNumber )
	{
		$data = array(
			"name" => $name,
			"data" => $pointsData,
			"xScale" => "0",
			"yScale" => "1",
			"seriesType" => $this->getSeriesType()
		);

		$data["labels"] = array( "enabled" => $this->chrt_array["appearance"]["sval"] );
		if( $data["seriesType"] == "area" )
			$data["labels"] = array( "enabled" => true );

		if( $clickData )
			$data["clickData"] = $clickData;

		if( $this->showDetails )
		{
			$data["tooltip"] = array(
				"enabled" => true,
				"title" => array(
					"enabled" => true,
					"text" => $name . $this->getDetailedToolipMessage()
				)
			);
		}

		return $data;
	}

	/**
	 * @return String
	 */
	protected function getSeriesType()
	{
		return "column";
	}

	/**
	 * ?
	 * @param String str
	 * @return String
	 */
	protected function chart_xmlencode($str)
	{
		return str_replace(array("&","<",">","\""),array("&","<",">","""),$str);
	}

	/**
	 * Get a 'point click' action data
	 * @param Array data
	 * @param Number seriesId
	 * @param Number pointId
	 * @return Array
	 */
	protected function getActions( $data, $seriesId, $pointId )
	{
		global $strTableName;

		if( !count($this->detailTablesData) )
			return null;

		if ( $this->dashChart )
		{
			$masterKeysArr = array();
			foreach ( $this->detailTablesData as $detailId => $detail )
			{
				foreach( $detail['masterKeys'] as $idx => $mk )
				{
					$masterKeysArr[ $detail['dDataSourceTable'] ] = array( 'masterkey'.($idx + 1) => $data[ $mk ] );
				}
			}

			if (!$this->dashChartFirstPointSelected)
			{
				$this->dashChartFirstPointSelected = true;
				$this->detailMasterKeys = my_json_encode( $masterKeysArr );
			}

			return array( "masterKeys" => $masterKeysArr, "seriesId" => $seriesId, "pointId" => $pointId );
		}

		// The one detail table is allowed for a chart page only
		$detailTableData = $this->detailTablesData[0];
		$masterquery = "mastertable=".rawurlencode( $strTableName );
		foreach( $detailTableData['masterKeys'] as $idx => $mk )
		{
			$masterquery.= "&masterkey".($idx + 1)."=".rawurlencode( $data[ $mk ] );
		}

		return array( "url" => GetTableLink( $detailTableData['dShortTable'], $detailTableData['dType'], $masterquery ) );
	}
}

class Chart_Bar extends Chart
{
	protected $stacked;
	protected $bar;

	function __construct( &$ch_array, $param )
	{
		parent::__construct( $ch_array, $param );

		$this->stacked = $param["stacked"];
		$this->_2d = $param["2d"];
		$this->bar = $param["bar"];
	}

	/**
	 * @return String
	 */
	protected function getSeriesType()
	{
		if($this->bar)
			return "bar";
		else
			return "column";
	}

	/**
	 * @param &Array chart
	 */
	protected function setTypeSpecChartSettings( &$chart )
	{
		$chart["series"] = $this->get_data();

		$chart["scales"] = $this->getScales();

		if( $this->bar )
			$chart["type"] = "bar";
		else
			$chart["type"] = "column";

		if( !$this->_2d )
			$chart["type"] .= "3d";

		$chart["xScale"] = 0;
		$chart["yScale"] = 1;

		// grid
		$chart["grids"] = $this->getGrids();

		// Y-axis label
		$chart["yAxes"]	= array(array("enabled"=>"true",
				"title" => $this->y_axis_label));

		// X-axis label
		$chart["xAxes"]	= array(array("enabled"=>"true",
				"title" => $this->footer,
				"labels" => array("enabled" => $this->chrt_array["appearance"]["sname"])
				));
	}

	/**
	 * "scales"
	 * @return Array
	 */
	protected function getScales()
	{
		if($this->stacked || $this->chrt_array["appearance"]["slog"] == "true")
		{
			$arr = array();
			if( $this->stacked )
				$arr["stackMode"] = "value";

			if( $this->chrt_array["appearance"]["slog"] == "true" )
			{
				$arr["logBase"] = 10;
				$arr["type"] = "log";
			};

			return array(
				array("names"=> array()),
				$arr);
		}

		return array();
	}
}

class Chart_Line extends Chart
{
	protected $type_line;

	function __construct( &$ch_array, $param )
	{
		parent::__construct( $ch_array, $param );

		$this->type_line = $param["type_line"];
	}

	/**
	 * @param &Array chart
	 */
	protected function setTypeSpecChartSettings( &$chart )
	{
		$chart["series"] = $this->get_data();
		$chart["type"] = "line";

		$chart["xScale"] = 0;
		$chart["yScale"] = 1;
		$chart["grids"] = $this->getGrids();

		$chart["yAxes"]	= array(
			array( "enabled" => "true", "title" => $this->y_axis_label )
		);

		$chart["xAxes"]	= array(
			array(
				"enabled" => "true",
				"title" => $this->footer,
				"labels" => array( "enabled" => $this->chrt_array["appearance"]["sname"] )
			));
	}

	/**
	 * @return String
	 */
	protected function getSeriesType()
	{
		switch( $this->type_line )
		{
			case "line":
				return "line";
			case "spline":
				return "spline";
			case "step_line":
				return "stepLine";
			default:
				return "line";
		}
	}
}

class Chart_Area extends Chart
{
	protected $stacked;

	function __construct( &$ch_array, $param )
	{
		parent::__construct( $ch_array, $param );

		$this->stacked = $param["stacked"];
	}

	/**
	 * @param &Array chart
	 */
	protected function setTypeSpecChartSettings( &$chart )
	{
		$chart["series"] = $this->get_data();

		if( $this->stacked )
			$chart["scales"] = $this->getScales();

		$chart["type"] = "area";
		$chart["xScale"] = 0;
		$chart["yScale"] = 1;

		$chart["grids"] = $this->getGrids();

		$chart["yAxes"]	= array(
			array( "enabled" => "true", "title" => $this->y_axis_label )
		);

		$chart["xAxes"]	= array(
			array(
				"enabled" => "true",
				"title" => $this->footer,
				"labels" => array( "enabled" => $this->chrt_array["appearance"]["sname"] )
			));
	}

	/**
	 * @return String
	 */
	protected function getSeriesType()
	{
		return "area";
	}

	/**
	 * "scales"
	 * @return Array
	 */
	protected function getScales()
	{
		if( $this->stacked )
		{
			$arr = array();
			$arr["stackMode"] = "value";

			if( $this->chrt_array["appearance"]["sstacked"] == "true" )
			{
				$arr["stackMode"] = "percent";
				$arr["maximumGap"] = "10";
				$arr["maximum"] = "100";
			};

			return array(
				array( "names"=> array() ),
				$arr
			);
		}

		return array();
	}
}

/**
 * A single series chart
 */
class Chart_Pie extends Chart
{
	protected $pie;

	function __construct( &$ch_array, $param )
	{
		parent::__construct( $ch_array, $param );

		$this->pie = $param["pie"];
		$this->_2d = $param["2d"];
		$this->singleSeries = true;
	}

	/**
	 * @param &Array chart
	 */
	protected function setTypeSpecChartSettings( &$chart )
	{
		$series = $this->get_data();

		$chart["data"] = $series[0]["data"];
		$chart["clickData"] = $series[0]["clickData"];
		$chart["singleSeries"] = true;

		$chart["tooltip"] = $series[0]["tooltip"];
		if( $this->showDetails )
			$chart["tooltipExtra"] = $this->getDetailedToolipMessage(); // single series fix

		if( $this->_2d )
			$chart["type"] = "pie";
		else
			$chart["type"] = "pie3d";

		if( !$this->pie )
			$chart["innerRadius"] = "30%";

		if( $this->chrt_array['appearance']['slegend'] == "true" && !$this->chartPreview )
		{
			$chart["legend"]["title"] = array(
				"enabled" => true,
				"text" => $this->footer,
			);
		}

		$chart["labels"] = array( "enabled" => $this->chrt_array["appearance"]["sval"] == "true" || $this->chrt_array["appearance"]["sname"] == "true" );
	}
}

class Chart_Combined extends Chart
{
	function __construct( &$ch_array, $param )
	{
		parent::__construct( $ch_array, $param );
	}

	/**
	 * @param &Array chart
	 */
	protected function setTypeSpecChartSettings( &$chart )
	{
		$chart["series"] = $this->get_data();
		$chart["type"] = "column";

		$chart["xScale"] = 0;
		$chart["yScale"] = 1;
		$chart["grids"] = $this->getGrids();

		$chart["yAxes"]	= array(
			array( "enabled" => "true", "title" => $this->y_axis_label )
		);

		$chart["xAxes"]	= array(
			array(
				"enabled" => "true",
				"title" => $this->footer,
				"labels" => array( "enabled" => $this->chrt_array["appearance"]["sname"] )
			));
	}

	/**
	 * @return String
	 */
	protected function getSeriesType()
	{
		if( $seriesNumber == 0 )
			return "line";

		return "column";
	}
}

/**
 * A single series chart
 */
class Chart_Funnel extends Chart
{
	protected $inver;

	function __construct( &$ch_array, $param )
	{
		parent::__construct( $ch_array, $param );

		$this->inver = $param["funnel_inv"];
		$this->singleSeries = true;
	}

	/**
	 * @param &Array chart
	 */
	protected function setTypeSpecChartSettings( &$chart )
	{
		$series = $this->get_data();
		$chart["type"] = "pyramid";

		$chart["data"] = $series[0]["data"];
		$chart["clickData"] = $series[0]["clickData"];
		$chart["singleSeries"] = true;

		$chart["tooltip"] = $series[0]["tooltip"];
		if( $this->showDetails )
			$chart["tooltipExtra"] = $this->getDetailedToolipMessage(); // single series fix

		if( $this->inver )
			$chart["reversed"] = true;
	}
}

class Chart_Bubble extends Chart
{
	protected $arrDataSize = array();

	function __construct( &$ch_array, $param )
	{
		parent::__construct( $ch_array, $param );

		$this->_2d = $param["2d"];
	}

	/**
	 * @param Array params
	 */
	protected function setSpecParams( $params )
	{
		parent::setSpecParams( $params );

		if( $params['name'] != "" )
		{
			if( $this->table_type != "db" )
				$this->arrDataSize[] = $params['size'];
			else
				$this->arrDataSize[] = $params['table']."_".$params['size'];
		}
	}

	/**
	 * @param &Array chart
	 */
	protected function setTypeSpecChartSettings( &$chart )
	{
		$chart["series"] = $this->get_data();
		$chart["type"] = "scatter";
		$chart["grids"] = $this->getGrids();

		$chart["yAxes"]	= array(
			array(
				"enabled" => true,
				"title" => $this->y_axis_label,
				"labels" => array( "enabled" => $this->chrt_array["appearance"]["sval"] )
			));

		$chart["xAxes"]	= array(
			array(
				"enabled" => "true",
				"title" => $this->footer,
				"labels" => array( "enabled" => $this->chrt_array["appearance"]["sname"] )
			));
	}

	/**
	 * @return String
	 */
	protected function getSeriesType()
	{
		return "bubble";
	}

	/**
	 * @param Number seriesNumber
	 * @param Array row
	 * @return Array
	 */
	protected function getPoint( $seriesNumber, $row )
	{
		$pointData = parent::getPoint( $seriesNumber, $row );
		$pointData["size"] = $this->chart_xmlencode( str_replace(",", ".", $row[ $this->arrDataSize[ $seriesNumber ] ]) + 0 );

		return $pointData;
	}
}

class Chart_Gauge extends Chart
{
	protected $arrGaugeColor = array();
	protected $gaugeType = "";
	protected $layout = "";

	function __construct( &$ch_array, $param )
	{
		parent::__construct( $ch_array, $param );

		$this->gaugeType = $param["gaugeType"];
		$this->layout = $param["layout"];
	}

	/**
	 * @param Array params
	 */
	protected function setSpecParams( $params )
	{
		parent::setSpecParams( $params );

		if ( $params['name'] != "" )
		{
			for ($k = 0; is_array( $params["gaugeColorZone"] ) && $k < count( $params["gaugeColorZone"] ); $k++ )
			{
				$beginColor = (float)@$params["gaugeColorZone"][ $k ]["gaugeBeginColor"];
				$endColor = (float)@$params["gaugeColorZone"][ $k ]["gaugeEndColor"];
				$gColor = "#".@$params["gaugeColorZone"][ $k ]["gaugeColor"];

				$this->arrGaugeColor[ count($this->arrDataSeries) - 1 ][] = array($beginColor, $endColor, $gColor);
			}
		}
	}

	/**
	 *
	 */
	public function write()
	{
		$data = array();

		for($i = 0; $i < count($this->arrDataSeries); $i++)
		{
			$chart = array();

			if( $this->chrt_array["appearance"]["sanim"] == "true" )
				$chart["animation"] = array("enabled" => "true", "duration" => 1000);

			$this->setGaugeSpecChartSettings( $chart, $i );
			if( $this->noRecordsFound )
			{
				$data["noDataMessage"] = $this->getNoDataMessage();
				echo my_json_encode( $data );
				return;
			}

			$data[] = array( "gauge" => $chart );
		}

		echo my_json_encode( array( "gauge" => $data ) );
	}

	/**
	 * @param &Array chart
	 * @param Number seriesNumber
	 */
	protected function setGaugeSpecChartSettings( &$chart, $seriesNumber )
	{
		$series = $this->get_data();
		$chart["data"] = $series[ $seriesNumber ]["data"];

		$chart["type"] = $this->gaugeType;
		$chart["layout"] = $this->layout;
		$chart["axes"] = array( $this->getAxesSettings( $seriesNumber ) );
		$chart["chartLabels"] = $this->getCircularGaugeLabel( $seriesNumber, $chart["data"][0] );

		if( $this->gaugeType == "circular" )
		{
			$chart["needles"] = array( array("enabled" => true) );
			$chart["ranges"] = $this->getColorRanges( $seriesNumber );
		}
		else
		{
			$hasColorZones = count( $this->arrGaugeColor ) > 0 && array_key_exists($seriesNumber, $this->arrGaugeColor );

			$chart["pointers"] = array(
				array(
					"enabled" => true,
					"pointerType" => "marker",
					"type" => $this->layout == "horizontal" ? "triangleUp" : "triangleLeft",
					"name" => "",
					"offset" => $hasColorZones ? "20%" : "10%",
					"dataIndex" => 0,
				)
			);

			if( $hasColorZones )
			{
				foreach( $this->arrGaugeColor[ $seriesNumber ] as $ind => $val )
				{
					$chart["pointers"][] = array(
						"enabled" => true,
						"pointerType" => "rangeBar",
						"name" => "",
						"offset" => "10%",
						"dataIndex" => $ind + 1, // 0 is an index of the db point then range bars coords go
						"color" => $val[2]
					);
				}
			}

			$scalesData = $this->getGaugeScales( $seriesNumber );

			$chart["scale"] = 0;
			$chart["scales"] = array(
				array(
					"maximum" => $scalesData["max"],
					"minimum" => $scalesData["min"],
					"ticks" => array( "interval"=> $scalesData["interval"] ),
					"minorTicks" => array( "interval"=> $scalesData["interval"] / 2 )
				)
			);
		}
	}

	/**
	 * @param Number seriesNumber
	 * @param Array pointData
	 * @return Array
	 */
	protected function getCircularGaugeLabel( $seriesNumber, $pointData )
	{
		$label = array(
			"enabled" => true,
			"vAlign" => "center",
			"hAlign" => "center",
			"text" =>  $this->getChartLabelText( $seriesNumber, $pointData["value"] )
		);

		if( $this->gaugeType == "circular" )
		{
			$label["offsetY"] = -150; //fix it
			$label["anchor"] = "center";

			$label["background"] = array(
				"enabled" => true,
				"fill" => "#fff",
				"cornerType" => "round",
				"corner" => 0
			);

			$label["padding"] = array(
				"top" => 15,
				"right" => 20,
				"bottom" => 15,
				"left" => 20
			);
		}

		return array( $label );
	}

	/**
	 * @param Number seriesNumber
	 * @return Array
	 */
	protected function getColorRanges( $seriesNumber )
	{
		$ranges = array();
		if( count( $this->arrGaugeColor ) > 0 && array_key_exists($seriesNumber, $this->arrGaugeColor ) )
		{
			foreach( $this->arrGaugeColor[ $seriesNumber ] as $ind => $val )
			{
				$ranges[] = array(
					"radius" => 70,
					"from" => $val[0],
					"to" => $val[1],
					"fill" => $val[2],
					"endSize" => "10%",
					"startSize" => "10%"
				);
			}
		}

		return $ranges;
	}

	/**
	 * @param Number seriesNumber
	 * @return Array
	 */
	protected function getAxesSettings( $seriesNumber )
	{
		$axes = array();

		if( $this->gaugeType == "circular" )
		{
			$axes["startAngle"] = -150;
			$axes["sweepAngle"] = 300;

			$scalesData = $this->getGaugeScales( $seriesNumber );

			$axes["scale"] = array(
				"maximum" => $scalesData["max"],
				"minimum" => $scalesData["min"],
				"ticks" => array( "interval"=> $scalesData["interval"] ),
				"minorTicks" => array( "interval"=> $scalesData["interval"] / 2 )
			);

			$axes["ticks"] = array(
				"type" => "trapezoid",
				"interval" => $scalesData["interval"]
			);

			$axes["minorTicks"] = array(
				"enabled" => true,
				"length" => 2
			 );
		}

		$axes["enabled"] = true;
		$axes["labels"] = array( "enabled" => $this->chrt_array["appearance"]["sval"] );

		return $axes;
	}

	/**
	 * @param Number seriesNumber
	 * @return Array
	 */
	protected function getGaugeScales( $seriesNumber )
	{
		$min = $this->chrt_array["parameters"][ $seriesNumber ]["gaugeMinValue"];
		$max = $this->chrt_array["parameters"][ $seriesNumber ]["gaugeMaxValue"];

		if( !is_numeric( $min ) )
			$min = 0;

		if( !is_numeric( $max ) )
			$max = 100;

		$diff = $max - $min;
		$slog = floor( log10( $diff ) );
		$interval = pow(10, $slog - 2);
		$muls = array(1,2,3,5,10);

		while(true)
		{
			foreach($muls as $m)
			{
				if( $diff / ($interval * $m) <= 10 )
				{
					$interval*= $m;
					break;
				}
			}
			if( $diff / ($interval) <= 10 )
				break;

			$interval*= 10;
		}

		return array(
			"min" => $min,
			"max" => $max,
			"interval" => $interval
		);
	}

	/**
	 * @return String
	 */
	protected function getSQL()
	{
		global $gSettings;

		$strSQL = parent::getSQL();

		if( $this->table_type == "project" )
		{
			$g_orderindexes = $gSettings->GetTableData(".orderindexes");
			$p = strpos( strtolower( $strSQL ), "order by");

			if( $p > 0 && count( $g_orderindexes ) )
			{
				$ob = "ORDER BY";
				foreach( $g_orderindexes as $ind => $val )
				{
					$ob.=" ".$val[0]." ";
					if( $val[1] == "ASC")
						$ob.= "DESC";
					else
						$ob.= "ASC";

					if( $ind + 1 != count( $g_orderindexes ) )
						$ob.=",";
				}

				$strSQL = substr($strSQL, 0, $p).$ob;
			}
		}

		return $strSQL;
	}

	/**
	 *
	 */
	public function get_data()
	{
		$data = array();

		$qResult = $this->connection->query( $this->strSQL );

		if( $this->cipherer != null )
			$row = $this->cipherer->DecryptFetchedArray( $qResult->fetchAssoc() );
		else
			$row = $qResult->fetchAssoc();

		if( !$row )
			$this->noRecordsFound = true;

		for($i = 0; $i < count($this->arrDataSeries); $i++)
		{
			if( $row )
			{
				$data[$i] = array();
				$data[$i][] = $this->getPoint($i, $row);
			}
		}

		$series = array();
		for ( $i = 0; $i < count($this->arrDataSeries); $i++ )
		{
			$series[] = $this->getSeriesData( $this->arrDataLabels[$i], $data[$i], $clickdata[$i], $i);
		}

		return $series;
	}

	/**
	 * @param String name
	 * @param Array pointsData
	 * @param Array clickData
	 * @param Number seriesNumber
	 * @return Array
	 */
	protected function getSeriesData( $name, $pointsData, $clickData, $seriesNumber )
	{
		if( $this->gaugeType == "linearGauge" && count( $this->arrGaugeColor ) > 0 && array_key_exists( $seriesNumber, $this->arrGaugeColor ) )
		{
			foreach( $this->arrGaugeColor[ $seriesNumber ] as $ind => $val )
			{
				$pointsData[] = array(
					"low" => $val[0],
					"high" => $val[1]
				);
			}
		}

		return array(
			"data" => $pointsData,
			"labelText" => $this->getChartLabelText( $seriesNumber, $pointsData[0]["value"] )
		);
	}

	/**
	 * @param Number seriesNumber
	 * @param String value
	 * @return String
	 */
	protected function getChartLabelText( $seriesNumber, $value )
	{
		if( $this->table_type == "project" && !$this->webchart )
		{
			$fieldName = $this->arrDataSeries[ $seriesNumber ];

			include_once getabspath('classes/controls/ViewControlsContainer.php');
			$viewControls = new ViewControlsContainer($this->pSet, PAGE_CHART);

			$data = array( $fieldName => $value );
			$viewValue = html_special_decode( $viewControls->showDBValue( $fieldName, $data ) );

			return $this->arrDataLabels[ $seriesNumber ].": ". $viewValue;
		}

		return $this->arrDataLabels[ $seriesNumber ].": ". $value;
	}
}

class Chart_Ohlc extends Chart
{
	protected $ohcl_type;

	protected $arrOHLC_high = array();
	protected $arrOHLC_low = array();
	protected $arrOHLC_open = array();
	protected $arrOHLC_close = array();

	function __construct( &$ch_array, $param )
	{
		parent::__construct( $ch_array, $param );

		$this->ohcl_type = $param["ohcl_type"];
	}

	/**
	 * @param Array params
	 */
	protected function setSpecParams( $params )
	{
		if($this->table_type != "db")
		{
			$this->arrOHLC_open[] = $params['ohlcOpen'];
			$this->arrOHLC_high[] = $params['ohlcHigh'];
			$this->arrOHLC_low[] = $params['ohlcLow'];
			$this->arrOHLC_close[] = $params['ohlcClose'];
			return;
		}

		if( $params['agr_func'] )
		{
			$this->arrOHLC_open[] = $params['agr_func']."_".$params['table']."_".$params['ohlcOpen'];
			$this->arrOHLC_high[] = $params['agr_func']."_".$params['table']."_".$params['ohlcHigh'];
			$this->arrOHLC_low[] = $params['agr_func']."_".$params['table']."_".$params['ohlcLow'];
			$this->arrOHLC_close[] = $params['agr_func']."_".$params['table']."_".$params['ohlcClose'];
		}
		else
		{
			$this->arrOHLC_open[] = $params['table']."_".$params['ohlcOpen'];
			$this->arrOHLC_high[] = $params['table']."_".$params['ohlcHigh'];
			$this->arrOHLC_low[] = $params['table']."_".$params['ohlcLow'];
			$this->arrOHLC_close[] = $params['table']."_".$params['ohlcClose'];
		}
	}

	/**
	 *
	 */
	public function write()
	{
		$data = array();
		$chart = array();

		$this->setTypeSpecChartSettings( $chart );

		$chart["title"]	= array("enabled" => "true", "text" => $this->header);

		if( $this->chrt_array['appearance']['slegend'] == "true" && !$this->chartPreview )
			$chart["legend"] = array("enabled" => "true");

		$data["chart"] = $chart;
		echo my_json_encode( $data );
	}

	/**
	 * @param &Array chart
	 */
	protected function setTypeSpecChartSettings( &$chart )
	{
		$chart["series"] = $this->get_data();
		$chart["grids"] = $this->getGrids();

		$chart["type"] = "financial";
		$chart["xScale"] = 0;
		$chart["yScale"] = 1;

		$chart["yAxes"]	= array(
			array(
				"enabled" => "true",
				"title" => $this->y_axis_label,
				"labels" => array("enabled" => $this->chrt_array["appearance"]["sval"])
			));

		$chart["xAxes"]	= array(
			array(
				"enabled" => "true",
				"title" => $this->footer,
				"labels" => array("enabled" => $this->chrt_array["appearance"]["sname"])
			));

		if( $this->chrt_array["appearance"]["slog"] == "true" )
		{
			$chart["scales"] = array(
				array( "names" => array() ),
				array( "logBase" => 10, "type" => "log" )
			);
		}
	}

	/**
	 * @return Array
	 */
	public function get_data()
	{
		$data = array();
		$clickdata = array();

		for ( $i = 0; $i < count($this->arrOHLC_open); $i++ )
		{
			$data[$i] = array();
			$clickdata[$i] = array();
		}

		$qResult = $this->connection->query( $this->strSQL );

		if( $this->cipherer != null )
			$row = $this->cipherer->DecryptFetchedArray( $qResult->fetchAssoc() );
		else
			$row = $qResult->fetchAssoc();

		if( !$row )
			$this->noRecordsFound = true;

		while($row)
		{
			for ( $i = 0; $i < count($this->arrOHLC_open); $i++ )
			{
				$data[$i][] = $this->getPoint($i, $row);

				$strLabelFormat = $this->labelFormat( $this->strLabel, $row );
				$clickdata[$i][] = $this->getActions( $row , $this->arrDataSeries[$i], $strLabelFormat );
			}

			if( $this->cipherer != null )
				$row = $this->cipherer->DecryptFetchedArray( $qResult->fetchAssoc() );
			else
				$row = $qResult->fetchAssoc();
		}

		$this->connection->close();

		$series = array();
		for ( $i = 0; $i < count($this->arrOHLC_open); $i++ )
		{
			$series[] = $this->getSeriesData( $this->arrDataLabels[$i], $data[$i], $clickdata[$i], $i );
		}

		return $series;
	}

	/**
	 * @return String
	 */
	protected function getSeriesType()
	{
		if( $this->ohcl_type == "ohcl" )
			return "ohlc";

		return "candlestick";
	}

	/**
	 * @param Number seriesNumber
	 * @param Array row
	 * @return Array
	 */
	protected function getPoint( $seriesNumber, $row )
	{
		if( $this->table_type!="db" || !count($this->chrt_array['customLabels']) )
		{
			$high = $row[ $this->arrOHLC_high[ $seriesNumber ] ];
			$low = $row[ $this->arrOHLC_low[ $seriesNumber ] ];
			$open = $row[ $this->arrOHLC_open[ $seriesNumber ] ];
			$close = $row[ $this->arrOHLC_close[ $seriesNumber ] ];
		}
		else
		{
			$high = $row[ $this->chrt_array['customLabels'][ $this->arrOHLC_high[ $seriesNumber ] ] ];
			$low = $row[ $this->chrt_array['customLabels'][ $this->arrOHLC_low[ $seriesNumber ] ] ];
			$open = $row[ $this->chrt_array['customLabels'][ $this->arrOHLC_open[ $seriesNumber ] ] ];
			$close = $row[ $this->chrt_array['customLabels'][ $this->arrOHLC_close[ $seriesNumber ] ] ];
		}

		return array(
			"x" => $this->labelFormat( $this->strLabel, $row ),
			"open" => $this->chart_xmlencode( $open + 0 ),
			"high" => $this->chart_xmlencode( $high + 0 ),
			"low" => $this->chart_xmlencode( $low + 0 ),
			"close" => $this->chart_xmlencode( str_replace(",", ".", $close) + 0 )
		);
	}
}
?>


text:
"""
    sphinx.environment.collectors.toctree
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Toctree collector for sphinx.environment.

    :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

from typing import cast

from docutils import nodes

from sphinx import addnodes
from sphinx.environment.adapters.toctree import TocTree
from sphinx.environment.collectors import EnvironmentCollector
from sphinx.locale import __
from sphinx.transforms import SphinxContentsFilter
from sphinx.util import url_re, logging

if False:
    # For type annotation
    from typing import Dict, List, Set, Tuple, Type, TypeVar  # NOQA
    from sphinx.application import Sphinx  # NOQA
    from sphinx.environment import BuildEnvironment  # NOQA

    N = TypeVar('N')

logger = logging.getLogger(__name__)

class TocTreeCollector(EnvironmentCollector):
    def clear_doc(self, app, env, docname):
        # type: (Sphinx, BuildEnvironment, str) -> None
        env.tocs.pop(docname, None)
        env.toc_secnumbers.pop(docname, None)
        env.toc_fignumbers.pop(docname, None)
        env.toc_num_entries.pop(docname, None)
        env.toctree_includes.pop(docname, None)
        env.glob_toctrees.discard(docname)
        env.numbered_toctrees.discard(docname)

        for subfn, fnset in list(env.files_to_rebuild.items()):
            fnset.discard(docname)
            if not fnset:
                del env.files_to_rebuild[subfn]

    def merge_other(self, app, env, docnames, other):
        # type: (Sphinx, BuildEnvironment, Set[str], BuildEnvironment) -> None
        for docname in docnames:
            env.tocs[docname] = other.tocs[docname]
            env.toc_num_entries[docname] = other.toc_num_entries[docname]
            if docname in other.toctree_includes:
                env.toctree_includes[docname] = other.toctree_includes[docname]
            if docname in other.glob_toctrees:
                env.glob_toctrees.add(docname)
            if docname in other.numbered_toctrees:
                env.numbered_toctrees.add(docname)

        for subfn, fnset in other.files_to_rebuild.items():
            env.files_to_rebuild.setdefault(subfn, set()).update(fnset & set(docnames))

    def process_doc(self, app, doctree):
        # type: (Sphinx, nodes.document) -> None
        """Build a TOC from the doctree and store it in the inventory."""
        docname = app.env.docname
        numentries = [0]  # nonlocal again...

        def traverse_in_section(node, cls):
            # type: (nodes.Element, Type[N]) -> List[N]
            """Like traverse(), but stay within the same section."""
            result = []  # type: List[N]
            if isinstance(node, cls):
                result.append(node)
            for child in node.children:
                if isinstance(child, nodes.section):
                    continue
                elif isinstance(child, nodes.Element):
                    result.extend(traverse_in_section(child, cls))
            return result

        def build_toc(node, depth=1):
            # type: (nodes.Element, int) -> nodes.bullet_list
            entries = []  # type: List[nodes.Element]
            for sectionnode in node:
                # find all toctree nodes in this section and add them
                # to the toc (just copying the toctree node which is then
                # resolved in self.get_and_resolve_doctree)
                if isinstance(sectionnode, nodes.section):
                    title = sectionnode[0]
                    # copy the contents of the section title, but without references
                    # and unnecessary stuff
                    visitor = SphinxContentsFilter(doctree)
                    title.walkabout(visitor)
                    nodetext = visitor.get_entry_text()
                    if not numentries[0]:
                        # for the very first toc entry, don't add an anchor
                        # as it is the file's title anyway
                        anchorname = ''
                    else:
                        anchorname = '#' + sectionnode['ids'][0]
                    numentries[0] += 1
                    # make these nodes:
                    # list_item -> compact_paragraph -> reference
                    reference = nodes.reference(
                        '', '', internal=True, refuri=docname,
                        anchorname=anchorname, *nodetext)
                    para = addnodes.compact_paragraph('', '', reference)
                    item = nodes.list_item('', para)  # type: nodes.Element
                    sub_item = build_toc(sectionnode, depth + 1)
                    if sub_item:
                        item += sub_item
                    entries.append(item)
                elif isinstance(sectionnode, addnodes.only):
                    onlynode = addnodes.only(expr=sectionnode['expr'])
                    blist = build_toc(sectionnode, depth)
                    if blist:
                        onlynode += blist.children
                        entries.append(onlynode)
                elif isinstance(sectionnode, nodes.Element):
                    for toctreenode in traverse_in_section(sectionnode,
                                                           addnodes.toctree):
                        item = toctreenode.copy()
                        entries.append(item)
                        # important: do the inventory stuff
                        TocTree(app.env).note(docname, toctreenode)
            if entries:
                return nodes.bullet_list('', *entries)
            return None
        toc = build_toc(doctree)
        if toc:
            app.env.tocs[docname] = toc
        else:
            app.env.tocs[docname] = nodes.bullet_list('')
        app.env.toc_num_entries[docname] = numentries[0]

    def get_updated_docs(self, app, env):
        # type: (Sphinx, BuildEnvironment) -> List[str]
        return self.assign_section_numbers(env) + self.assign_figure_numbers(env)

    def assign_section_numbers(self, env):
        # type: (BuildEnvironment) -> List[str]
        """Assign a section number to each heading under a numbered toctree."""
        # a list of all docnames whose section numbers changed
        rewrite_needed = []

        assigned = set()  # type: Set[str]
        old_secnumbers = env.toc_secnumbers
        env.toc_secnumbers = {}

        def _walk_toc(node, secnums, depth, titlenode=None):
            # type: (nodes.Element, Dict, int, nodes.title) -> None
            # titlenode is the title of the document, it will get assigned a
            # secnumber too, so that it shows up in next/prev/parent rellinks
            for subnode in node.children:
                if isinstance(subnode, nodes.bullet_list):
                    numstack.append(0)
                    _walk_toc(subnode, secnums, depth - 1, titlenode)
                    numstack.pop()
                    titlenode = None
                elif isinstance(subnode, nodes.list_item):
                    _walk_toc(subnode, secnums, depth, titlenode)
                    titlenode = None
                elif isinstance(subnode, addnodes.only):
                    # at this stage we don't know yet which sections are going
                    # to be included; just include all of them, even if it leads
                    # to gaps in the numbering
                    _walk_toc(subnode, secnums, depth, titlenode)
                    titlenode = None
                elif isinstance(subnode, addnodes.compact_paragraph):
                    numstack[-1] += 1
                    reference = cast(nodes.reference, subnode[0])
                    if depth > 0:
                        number = list(numstack)
                        secnums[reference['anchorname']] = tuple(numstack)
                    else:
                        number = None
                        secnums[reference['anchorname']] = None
                    reference['secnumber'] = number
                    if titlenode:
                        titlenode['secnumber'] = number
                        titlenode = None
                elif isinstance(subnode, addnodes.toctree):
                    _walk_toctree(subnode, depth)

        def _walk_toctree(toctreenode, depth):
            # type: (addnodes.toctree, int) -> None
            if depth == 0:
                return
            for (title, ref) in toctreenode['entries']:
                if url_re.match(ref) or ref == 'self':
                    # don't mess with those
                    continue
                elif ref in assigned:
                    logger.warning(__('%s is already assigned section numbers '
                                      '(nested numbered toctree?)'), ref,
                                   location=toctreenode, type='toc', subtype='secnum')
                elif ref in env.tocs:
                    secnums = {}  # type: Dict[str, Tuple[int, ...]]
                    env.toc_secnumbers[ref] = secnums
                    assigned.add(ref)
                    _walk_toc(env.tocs[ref], secnums, depth, env.titles.get(ref))
                    if secnums != old_secnumbers.get(ref):
                        rewrite_needed.append(ref)

        for docname in env.numbered_toctrees:
            assigned.add(docname)
            doctree = env.get_doctree(docname)
            for toctreenode in doctree.traverse(addnodes.toctree):
                depth = toctreenode.get('numbered', 0)
                if depth:
                    # every numbered toctree gets new numbering
                    numstack = [0]
                    _walk_toctree(toctreenode, depth)

        return rewrite_needed

    def assign_figure_numbers(self, env):
        # type: (BuildEnvironment) -> List[str]
        """Assign a figure number to each figure under a numbered toctree."""

        rewrite_needed = []

        assigned = set()  # type: Set[str]
        old_fignumbers = env.toc_fignumbers
        env.toc_fignumbers = {}
        fignum_counter = {}  # type: Dict[str, Dict[Tuple[int, ...], int]]

        def get_figtype(node):
            # type: (nodes.Node) -> str
            for domain in env.domains.values():
                figtype = domain.get_enumerable_node_type(node)
                if figtype:
                    return figtype

            return None

        def get_section_number(docname, section):
            # type: (str, nodes.section) -> Tuple[int, ...]
            anchorname = '#' + section['ids'][0]
            secnumbers = env.toc_secnumbers.get(docname, {})
            if anchorname in secnumbers:
                secnum = secnumbers.get(anchorname)
            else:
                secnum = secnumbers.get('')

            return secnum or tuple()

        def get_next_fignumber(figtype, secnum):
            # type: (str, Tuple[int, ...]) -> Tuple[int, ...]
            counter = fignum_counter.setdefault(figtype, {})

            secnum = secnum[:env.config.numfig_secnum_depth]
            counter[secnum] = counter.get(secnum, 0) + 1
            return secnum + (counter[secnum],)

        def register_fignumber(docname, secnum, figtype, fignode):
            # type: (str, Tuple[int, ...], str, nodes.Element) -> None
            env.toc_fignumbers.setdefault(docname, {})
            fignumbers = env.toc_fignumbers[docname].setdefault(figtype, {})
            figure_id = fignode['ids'][0]

            fignumbers[figure_id] = get_next_fignumber(figtype, secnum)

        def _walk_doctree(docname, doctree, secnum):
            # type: (str, nodes.Element, Tuple[int, ...]) -> None
            for subnode in doctree.children:
                if isinstance(subnode, nodes.section):
                    next_secnum = get_section_number(docname, subnode)
                    if next_secnum:
                        _walk_doctree(docname, subnode, next_secnum)
                    else:
                        _walk_doctree(docname, subnode, secnum)
                elif isinstance(subnode, addnodes.toctree):
                    for title, subdocname in subnode['entries']:
                        if url_re.match(subdocname) or subdocname == 'self':
                            # don't mess with those
                            continue

                        _walk_doc(subdocname, secnum)
                elif isinstance(subnode, nodes.Element):
                    figtype = get_figtype(subnode)
                    if figtype and subnode['ids']:
                        register_fignumber(docname, secnum, figtype, subnode)

                    _walk_doctree(docname, subnode, secnum)

        def _walk_doc(docname, secnum):
            # type: (str, Tuple[int, ...]) -> None
            if docname not in assigned:
                assigned.add(docname)
                doctree = env.get_doctree(docname)
                _walk_doctree(docname, doctree, secnum)

        if env.config.numfig:
            _walk_doc(env.config.master_doc, tuple())
            for docname, fignums in env.toc_fignumbers.items():
                if fignums != old_fignumbers.get(docname):
                    rewrite_needed.append(docname)

        return rewrite_needed

def setup(app):
    # type: (Sphinx) -> Dict
    app.add_env_collector(TocTreeCollector)

    return {
        'version': 'builtin',
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }

redpajama_set_name: RedPajamaGithub


text:
import { NgModule } from '@angular/core'
import { Routes, RouterModule } from '@angular/router'
import { SharedModule } from '../Shared'

import AppDownloadsComponent  from './appdownloads.component'

@NgModule({
  imports: [ SharedModule,RouterModule ],
  declarations: [ AppDownloadsComponent ]
})
export class AppDownloadsModule {}


text:
module Bruise
  class Engine < ::Rails::Engine
    isolate_namespace Bruise
    config.assets.paths << "#{Rails}/vendor/assets/fonts/*"
  end
end


text:
List::ListElement::ListElement(string const &word)
    : word(word), frequency(1), next(nullptr)
{
}

List::ListElement::~ListElement()
{
}

void List::ListElement::addChild(string const &word)
{
    ListElement * newElement = new ListElement(word);
    next = newElement;
}

void List::ListElement::addFrequency()
{
    ++frequency;
}

string List::ListElement::getWord() const
{
    return word;
}

long long List::ListElement::getFrequency() const
{
    return frequency;
}

List::ListElement * List::ListElement::getNext() const
{
    return next;
}

List::List()
{
    first = nullptr;
    last = nullptr;
}

List::~List()
{
    ListElement * currentElement = first;
    ListElement * deletedElement = nullptr;
    while (currentElement != nullptr)
    {
        deletedElement = currentElement;
        currentElement = currentElement->getNext();
        delete deletedElement;
    }
    deletedElement = nullptr;
    first = nullptr;
    last = nullptr;
}

void List::add(string const &word)
{
    if (first == nullptr)
    {
        ListElement * newElement = new ListElement(word);
        first = newElement;
        last = newElement;
    }
    else
    {
        if (!check(word))
        {
            last->addChild(word);
            last = last->getNext();
        }
        else
        {
            ListElement * currentElement = first;
            while (currentElement->getWord() != word)
            {
                currentElement = currentElement->getNext();
            }
            currentElement->addFrequency();
        }
    }
}

bool List::check(string const &word)
{
    ListElement * currentElement = first;
    while (currentElement != nullptr && currentElement->getWord() != word)
    {
        currentElement = currentElement->getNext();
    }
    return currentElement != nullptr;
}

void List::print()
{
    ListElement * currentElement = first;
    while (currentElement != nullptr)
    {
        cout << currentElement->getWord() << " - " << currentElement->getFrequency() << endl;
        currentElement = currentElement->getNext();
    }
}

bool List::doExist() const
{
    return first != nullptr;
}

int List::size() const
{
    int size = 0;
    ListElement * currentElement = first;
    while (currentElement != nullptr)
    {
        ++size;
        currentElement = currentElement->getNext();
    }
    return size;
}


text:
using System;
using nyom.domain;
using nyom.infra.CrossCutting.Services;

namespace nyom.pushsender
{
	public class Sender
	{
		private readonly IAtualizarStatus _atualizarStatus;
		private readonly IEnviarMensagensPush _enviarMensagensPush;

		public Sender(IAtualizarStatus atualizarStatus, IEnviarMensagensPush enviarMensagensPush)
		{
			_atualizarStatus = atualizarStatus;
			_enviarMensagensPush = enviarMensagensPush;
		}

		public void Start()
		{
			PushMessages(Guid.Parse("4063DEBE-6EA0-4C54-B36E-2C65D0D6D060"));
		}
		public void PushMessages(Guid campanha)
		{
			var enviar = _enviarMensagensPush.Envia(campanha.ToString());

			if(enviar)
			_atualizarStatus.AtualizarStatusApi(campanha, (int) WorkflowStatus.PushSenderCompleted);
		}
	}
}


text:
#ifndef VIEWSCRIPT_H
#define VIEWSCRIPT_H
/**
 * Run a viewscript.
 *
 * @param script Script to run.
 * @return 0 on success, err number on error
 */
int run_viewscript(char *script);

#endif


text:
package org.wisdom.monitor.extensions.jcr.script.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import javax.jcr.RepositoryException;
import javax.jcr.observation.Event;
import java.io.IOException;

/**
 * Created by KEVIN on 26/01/2016.
 */
public class JcrEventSerializer extends JsonSerializer<Event> {
    @Override
    public void serialize(Event value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeStartObject();
        try {
            gen.writeStringField("path", value.getPath());
            gen.writeNumberField("type", value.getType());
            gen.writeNumberField("date", value.getDate());
            gen.writeStringField("userID", value.getUserID());
        } catch (RepositoryException e) {
            throw new IOException(e);
        }
        gen.writeEndObject();
    }
}


text:
sap.ui.define(["./BaseContentRenderer"], function (BaseContentRenderer) {
	"use strict";

	/**
	 * ComponentContentRenderer renderer.
	 * @author SAP SE
	 * @namespace
	 */
	var ComponentContentRenderer = BaseContentRenderer.extend("sap.ui.integration.cards.ComponentContentRenderer", {
		apiVersion: 2
	});

	/**
	 * @override
	 */
	ComponentContentRenderer.getMinHeight = function (oConfiguration, oContent) {
		if (oConfiguration.minHeight) {
			return oConfiguration.minHeight;
		}

		return BaseContentRenderer.getMinHeight.apply(this, arguments);
	};

	return ComponentContentRenderer;
});


text:
require 'test_helper'

class FacebookConnectTest < ActiveSupport::TestCase
  test "truth" do
    assert_kind_of Module, FacebookConnect
  end
end


text:
package org.lib4j.test;

import java.util.HashMap;
import java.util.Map;

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.junit.Assert;
import org.junit.ComparisonFailure;
import org.lib4j.xml.dom.DOMStyle;
import org.lib4j.xml.dom.DOMs;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xmlunit.builder.Input;
import org.xmlunit.diff.Comparison;
import org.xmlunit.diff.ComparisonListener;
import org.xmlunit.diff.ComparisonResult;
import org.xmlunit.diff.DOMDifferenceEngine;
import org.xmlunit.diff.DifferenceEngine;

public class AssertXml {
  private XPath newXPath() {
    final XPath xPath = XPathFactory.newInstance().newXPath();
    xPath.setNamespaceContext(new SimpleNamespaceContext(prefixToNamespaceURI));
    return xPath;
  }

  public static AssertXml compare(final Element controlElement, final Element testElement) {
    final Map<String,String> prefixToNamespaceURI = new HashMap<>();
    prefixToNamespaceURI.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");
    final NamedNodeMap attributes = controlElement.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
       final Attr attribute = (Attr)attributes.item(i);
       if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(attribute.getNamespaceURI()) && "xmlns".equals(attribute.getPrefix()))
         prefixToNamespaceURI.put(attribute.getLocalName(), attribute.getNodeValue());
    }

    return new AssertXml(prefixToNamespaceURI, controlElement, testElement);
  }

  private final Map<String,String> prefixToNamespaceURI;
  private final Element controlElement;
  private final Element testElement;

  private AssertXml(final Map<String,String> prefixToNamespaceURI, final Element controlElement, final Element testElement) {
    if (!controlElement.getPrefix().equals(testElement.getPrefix()))
      throw new IllegalArgumentException("Prefixes of control and test elements must be the same: " + controlElement.getPrefix() + " != " + testElement.getPrefix());

    this.prefixToNamespaceURI = prefixToNamespaceURI;
    this.controlElement = controlElement;
    this.testElement = testElement;
  }

  public void addAttribute(final Element element, final String xpath, final String name, final String value) throws XPathExpressionException {
    final XPathExpression expression = newXPath().compile(xpath);
    final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); ++i) {
      final Node node = nodes.item(i);
      if (!(node instanceof Element))
        throw new UnsupportedOperationException("Only support addition of attributes to elements");

      final Element target = (Element)node;
      final int colon = name.indexOf(':');
      final String namespaceURI = colon == -1 ? node.getNamespaceURI() : node.getOwnerDocument().lookupNamespaceURI(name.substring(0, colon));
      target.setAttributeNS(namespaceURI, name, value);
    }
  }

  public void remove(final Element element, final String ... xpaths) throws XPathExpressionException {
    for (final String xpath : xpaths) {
      final XPathExpression expression = newXPath().compile(xpath);
      final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET);
      for (int i = 0; i < nodes.getLength(); ++i) {
        final Node node = nodes.item(i);
        if (node instanceof Attr) {
          final Attr attribute = (Attr)node;
          attribute.getOwnerElement().removeAttributeNode(attribute);
        }
        else {
          node.getParentNode().removeChild(node);
        }
      }
    }
  }

  public void replace(final Element element, final String xpath, final String name, final String value) throws XPathExpressionException {
    final XPathExpression expression = newXPath().compile(xpath);
    final NodeList nodes = (NodeList)expression.evaluate(element, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); ++i) {
      final Node node = nodes.item(i);
      if (node instanceof Attr) {
        final Attr attribute = (Attr)node;
        if (name == null) {
          attribute.setValue(value);
        }
        else {
          final int colon = name.indexOf(':');
          final String namespaceURI = colon == -1 ? attribute.getNamespaceURI() : attribute.getOwnerDocument().lookupNamespaceURI(name.substring(0, colon));
          final Element owner = attribute.getOwnerElement();
          owner.removeAttributeNode(attribute);
          owner.setAttributeNS(namespaceURI, name, value);
        }
      }
      else {
        throw new UnsupportedOperationException("Only support replacement of attribute values");
      }
    }
  }

  public void replace(final Element element, final String xpath, final String value) throws XPathExpressionException {
    replace(element, xpath, null, value);
  }

  public void assertEqual() {
    final String prefix = controlElement.getPrefix();
    final String controlXml = DOMs.domToString(controlElement, DOMStyle.INDENT, DOMStyle.INDENT_ATTRS);
    final String testXml = DOMs.domToString(testElement, DOMStyle.INDENT, DOMStyle.INDENT_ATTRS);

    final Source controlSource = Input.fromString(controlXml).build();
    final Source testSource = Input.fromString(testXml).build();

    final DifferenceEngine diffEngine = new DOMDifferenceEngine();
    diffEngine.addDifferenceListener(new ComparisonListener() {
      @Override
      public void comparisonPerformed(final Comparison comparison, final ComparisonResult result) {
        final String controlXPath = comparison.getControlDetails().getXPath() == null ? null : comparison.getControlDetails().getXPath().replaceAll("/([^@])", "/" + prefix + ":$1");
        if (controlXPath == null || controlXPath.matches("^.*\\/@[:a-z]+$") || controlXPath.contains("text()"))
          return;

        try {
          Assert.assertEquals(controlXml, testXml);
        }
        catch (final ComparisonFailure e) {
          final StackTraceElement[] stackTrace = e.getStackTrace();
          int i;
          for (i = 3; i < stackTrace.length; i++)
            if (!stackTrace[i].getClassName().startsWith("org.xmlunit.diff"))
              break;

          final StackTraceElement[] filtered = new StackTraceElement[stackTrace.length - ++i];
          System.arraycopy(stackTrace, i, filtered, 0, stackTrace.length - i);
          e.setStackTrace(filtered);
          throw e;
        }

        Assert.fail(comparison.toString());
      }
    });

    diffEngine.compare(controlSource, testSource);
  }
}


text: export const getIsPending = (state) => state.progress.isPending


text:
Implement the `keep` and `discard` operation on collections. Given a collection and a predicate on the collection's elements, `keep` returns a new collection containing those elements where the predicate is true, while `discard` returns a new collection containing those elements where the predicate is false.

Write two functions that each take a function and a list.  One of them will
return the list of items for which the passed in function is true, and the
other will return the items for which it is false.

For example, given the collection of numbers:

- 1, 2, 3, 4, 5

And the predicate:

- is the number even?

Then your keep operation should produce:

- 2, 4

While your discard operation should produce:

- 1, 3, 5

Note that the union of keep and discard is all the elements.

The functions may be called `keep` and `discard`, or they may need different
names in order to not clash with existing functions or concepts in your
language.

## Restrictions

Keep your hands off that filter/reject/whatchamacallit functionality
provided by your standard library!  Solve this one yourself using other
basic tools instead.

## Setup

Go through the setup instructions for ECMAScript to
install the necessary dependencies:

http://exercism.io/languages/ecmascript

## Requirements

Install assignment dependencies:

```bash
$ npm install
```

## Making the test suite pass

Execute the tests with:

```bash
$ npm test
```

In many test suites all but the first test have been skipped.

Once you get a test passing, you can unskip the next one by
changing `xit` to `it`.

## Source

Conversation with James Edward Gray II [https://twitter.com/jeg2](https://twitter.com/jeg2)

## Submitting Incomplete Problems
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
require 'cinch'
require 'cinch/toolbox'
require 'cinch/cooldown'

module Cinch
  module Plugins
    # Cinch Plugin to looking MTG cards
    class Magic
      include Cinch::Plugin

      enforce_cooldown

      self.help = 'Use .mtg <card name> to see the info for that card.'

      match(/mtg (.*)/)

      def execute(m, term)
        m.reply get_card(term)
      end

      private

      def get_card(term)
        # Fetch the html for the search term
        data = card_data(term)

        # Catch nil responses.
        return '[Magic] Card not found, or problem fetching page.' if data.nil?

        # Build card string
        card = "#{card_name(data)} [#{card_info(data)}] - #{card_text(data)}"

        # Truncate if it's super long
        card = Cinch::Toolbox.truncate(card, 300)

        "[Magic] #{card} [#{card_link(data)}]"
      end

      def card_info(data)
        text = data[/
]*>([^<]+)<\/p>/, 1]

        # Replace Newlines, unicode lines, total mana, and large spaces.
        text = text.gsub(/\n/, '')
        text = text.gsub(/\s—/, ', ')
        text = text.gsub(/\s\(\d*\)/, '')
        text = text.gsub(/\s{2,}/, ' ')

        # Remove pesky whitespace that might have snuck in...
        text.strip!

        text
      rescue
        debug 'Error getting the card info'
        return ''
      end

      def card_name(data)
        data[/]*>([^<]+)<\/a>/, 1]
      rescue
        debug 'Error finding the card name'
        return ''
      end

      def card_link(data)
        "http://magiccards.info#{data[/]*)">[^<]+<\/a>/, 1]}"
      rescue
        debug 'Error finding the card url'
        return ''
      end

      def card_text(data)
        data[%r{
]*>(.+)
}, 1].gsub(/

/, ' ')
      rescue
        debug 'Error finding the card description'
        return ''
      end

      def card_data(term)
        # URI Encode the term and build the URL
        term = URI.escape("!#{term}",
                          Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
        url = "http://magiccards.info/query?q=#{term}"

        # Make sure the URL is legit
        url = URI.extract(url, %w(http https)).first

        # Grab the html block because magiccards.info fucking loves tables
        # and hates helpful ids and classnames
        Cinch::Toolbox.get_html_element(url, '//table[3]/tr/td[2]', :xpath_full)
      rescue
        debug "Error looking up card: #{term}"
        return
      end
    end
  end
end


text:
package org.apereo.portal.events.aggr.tabrender;

import org.apereo.portal.events.aggr.BaseGroupedAggregationDiscriminatorImpl;
import org.apereo.portal.events.aggr.groups.AggregatedGroupMapping;
import org.apereo.portal.events.aggr.tabs.AggregatedTabMapping;
import org.apereo.portal.utils.ComparableExtractingComparator;

/**
 * Basic impl of {@link org.apereo.portal.events.aggr.tabrender.TabRenderAggregationKey}
 *
 * @author James Wennmacher, jameswennmacher@gmail.com
 */
public final class TabRenderAggregationDiscriminatorImpl
        extends BaseGroupedAggregationDiscriminatorImpl
        implements TabRenderAggregationDiscriminator {
    private static final long serialVersionUID = 1L;

    private final AggregatedTabMapping tabMapping;
    private int hashCode = 0;

    public TabRenderAggregationDiscriminatorImpl(TabRenderAggregation aggregationData) {
        super(aggregationData.getAggregatedGroup());
        tabMapping = aggregationData.getTabMapping();
    }

    public TabRenderAggregationDiscriminatorImpl(
            AggregatedGroupMapping aggregatedGroupMapping, AggregatedTabMapping tabMapping) {
        super(aggregatedGroupMapping);
        this.tabMapping = tabMapping;
    }

    @Override
    public final AggregatedTabMapping getTabMapping() {
        return this.tabMapping;
    }

    @Override
    public int hashCode() {
        int h = this.hashCode;
        if (h == 0) {
            final int prime = 31;
            h = super.hashCode();
            h = prime * h + ((tabMapping == null) ? 0 : tabMapping.hashCode());
            this.hashCode = h;
        }
        return h;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!super.equals(obj)) return false;
        if (getClass() != obj.getClass()) return false;
        TabRenderAggregationDiscriminator other = (TabRenderAggregationDiscriminator) obj;
        if (tabMapping == null) {
            if (other.getTabMapping() != null) return false;
        } else if (!tabMapping.equals(other.getTabMapping())) return false;
        return true;
    }

    // Compare discriminators based on the group name and tab information
    public static class Comparator
            extends ComparableExtractingComparator<TabRenderAggregationDiscriminator, String> {

        public static Comparator INSTANCE = new Comparator();

        @Override
        protected String getComparable(TabRenderAggregationDiscriminator o) {
            return o.getAggregatedGroup().getGroupName()
                    + o.getTabMapping().getTabName()
                    + o.getTabMapping().getFragmentName();
        }
    }

    @Override
    public String toString() {
        return "TabRenderAggregationKey [" + super.toString() + ", tabMapping=" + tabMapping + "]";
    }
}


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

    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

-->
<typeSystemDescription xmlns="http://uima.apache.org/resourceSpecifier">
  <name>DiscoveryTechnique</name>
  <description/>
  <version>1.0</version>
  <vendor/>
  <types>
    <typeDescription>
      <name>org.apache.ctakes.coreference.type.DiscoveryTechnique</name>
      <description/>
      <supertypeName>uima.cas.TOP</supertypeName>
      <features>
        <featureDescription>
          <name>technique</name>
          <description/>
          <rangeTypeName>uima.cas.String</rangeTypeName>
        </featureDescription>
        <featureDescription>
          <name>confidence</name>
          <description/>
          <rangeTypeName>uima.cas.Double</rangeTypeName>
        </featureDescription>
      </features>
    </typeDescription>
  </types>
</typeSystemDescription>


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="SHCrowd">

    <insert id="addCrowd" parameterType="com.sung.hee.shcrowd.model.SHCrowd">

        INSERT INTO SHCROWD(TITLE, CONTENT, ID, GOALMONEY, LIKENUM, TAG,
        SDATE, EDATE, CATEGORY, ADDRESS, TYPE,REQ, DEL,ENDFLAG,REWARD,WDATE,LATLNG) VALUES
        (#{title},#{content},#{id},#{goalMoney},0,#{tag},
        #{sdate},#{edate},#{category},
        <if test="address != null and address!=''">
            #{address}
        </if>
        <if test="address == null or address==''">''</if>
        ,#{type},0,0,'0','0',DATE_FORMAT(NOW(), '%Y-%m-%d'),
        <if test="latlng != null and latlng!=''">
            #{latlng}

        </if>
        <if test="latlng == null or latlng==''">''</if>
        )
    </insert>

    <update id="delCrowd" parameterType="com.sung.hee.shcrowd.model.SHCrowd">

        UPDATE SHCROWD SET DEL=1 WHERE SEQ=#{seq}

    </update>

    <select id="detailCrowd" parameterType="com.sung.hee.shcrowd.model.SHCrowd"
            resultType="com.sung.hee.shcrowd.model.SHCrowd">

     SELECT PNUM, SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM, CURMONEY, TAG,
    SDATE, EDATE, CATEGORY, ADDRESS, TYPE, REQ, LATLNG, WDATE FROM (
    SELECT IFNULL(PNUM,0) AS PNUM, SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM,
    IFNULL(COUNTS.CURMONEY,0) AS CURMONEY, TAG, SDATE, EDATE, CATEGORY, ADDRESS, TYPE, REQ, LATLNG, WDATE
    FROM SHCROWD LEFT JOIN
    (SELECT COUNT(*) PNUM, PSEQ, SUM(MONEY) CURMONEY
    FROM SHFUND GROUP BY PSEQ) COUNTS ON COUNTS.PSEQ=SHCROWD.SEQ WHERE SEQ =#{seq}) A

    </select>

    <select id="reqCrowdList"
            resultType="com.sung.hee.shcrowd.model.SHCrowd">
    SELECT rnn,pnum,SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM, CURMONEY, TAG,
    SDATE, EDATE, CATEGORY, ADDRESS, TYPE,REQ,LATLNG,WDATE FROM (
    SELECT @ROWNUM := @ROWNUM + 1 as rnn,IFNULL(pnum,0) as pnum,SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM,
    IFNULL(COUNTS.CURMONEY,0) AS CURMONEY, TAG, SDATE, EDATE, CATEGORY, ADDRESS, TYPE,REQ,LATLNG,WDATE
    FROM SHCROWD left join
    (SELECT COUNT(*) PNUM,PSEQ,SUM(MONEY) CURMONEY
    FROM SHFUND GROUP BY pseq) COUNTS ON COUNTS.PSEQ=SHCROWD.seq,(SELECT @ROWNUM := 0)R WHERE REQ = 0 ORDER BY SEQ DESC) A

    </select>
    <select id="myReqCrowdList" parameterType="com.sung.hee.user.model.SHUser"
            resultType="com.sung.hee.shcrowd.model.SHCrowd">
    SELECT rnn,pnum,SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM, CURMONEY, TAG,
    SDATE, EDATE, CATEGORY, ADDRESS, TYPE,REQ,LATLNG,WDATE FROM (
    SELECT @ROWNUM := @ROWNUM + 1 as rnn,IFNULL(pnum,0) as pnum,SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM,
    IFNULL(COUNTS.CURMONEY,0) AS CURMONEY, TAG, SDATE, EDATE, CATEGORY, ADDRESS, TYPE,REQ,LATLNG,WDATE
    FROM SHCROWD left join
    (SELECT COUNT(*) PNUM,PSEQ,SUM(MONEY) CURMONEY
    FROM SHFUND GROUP BY pseq) COUNTS ON COUNTS.PSEQ=SHCROWD.seq,(SELECT @ROWNUM := 0)R WHERE ID = #{id} ORDER BY SEQ DESC) A
    </select>
    <update id="accCrowd"
            parameterType="com.sung.hee.shcrowd.model.SHCrowd">

        UPDATE SHCROWD SET REQ=1 WHERE SEQ=#{seq}

    </update>
    <update id="noCrowd"
            parameterType="com.sung.hee.shcrowd.model.SHCrowd">

        UPDATE SHCROWD SET REQ=2 WHERE SEQ=#{seq}

    </update>
    <select id="crowdListAll"
            resultType="com.sung.hee.shcrowd.model.SHCrowd">

        SELECT rnn,SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM, IFNULL(CURMONEY,0) CURMONEY, TAG,
        SDATE, EDATE, CATEGORY, ADDRESS, TYPE,REQ,LATLNG,WDATE,ENDFLAG,REWARD FROM (
        SELECT @ROWNUM := @ROWNUM + 1 as rnn,SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM, CURMONEY, TAG,
        SDATE, EDATE, CATEGORY, ADDRESS, TYPE,REQ,LATLNG,WDATE,ENDFLAG,REWARD FROM SHCROWD left join
            (SELECT COUNT(*) PNUM,PSEQ,SUM(MONEY) CURMONEY
             FROM SHFUND GROUP BY pseq) COUNTS ON COUNTS.PSEQ=SHCROWD.seq,(SELECT @ROWNUM := 0)R ORDER BY SEQ DESC) A

    </select>
    <select id="crowdListAllforCal"
            resultType="com.sung.hee.shcrowd.model.SHCrowd">

        SELECT rnn,SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM, IFNULL(CURMONEY,0) CURMONEY, TAG,
        SDATE, EDATE, CATEGORY, ADDRESS, TYPE,REQ,LATLNG,WDATE,ENDFLAG,REWARD FROM (
        SELECT @ROWNUM := @ROWNUM + 1 as rnn,SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM, CURMONEY, TAG,
        SDATE, EDATE, CATEGORY, ADDRESS, TYPE,REQ,LATLNG,WDATE,ENDFLAG,REWARD FROM SHCROWD left join
            (SELECT COUNT(*) PNUM,PSEQ,SUM(MONEY) CURMONEY
             FROM SHFUND GROUP BY pseq) COUNTS ON COUNTS.PSEQ=SHCROWD.seq,(SELECT @ROWNUM := 0)R WHERE REQ = 1 AND ENDFLAG='0' ORDER BY SEQ DESC)  A

    </select>
    <select id="crowdList" parameterType="com.sung.hee.shcrowd.model.SHCrowd"
            resultType="com.sung.hee.shcrowd.model.SHCrowd">

        SELECT RESULT.* FROM (SELECT @ROWNUM := @ROWNUM + 1 as rnn,pnum,SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM,
        CURMONEY,
        TAG,
        SDATE, EDATE, CATEGORY, ADDRESS, TYPE,REQ,LATLNG,WDATE,ENDFLAG,REWARD FROM (
        SELECT IFNULL(pnum,0) as pnum,SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM,
        IFNULL(COUNTS.CURMONEY,0)
        AS CURMONEY, TAG,
        SDATE, EDATE, CATEGORY, ADDRESS, TYPE,REQ,LATLNG,WDATE,ENDFLAG,REWARD FROM SHCROWD left join (SELECT COUNT(*)
        PNUM,PSEQ,SUM(MONEY) CURMONEY FROM
        SHFUND GROUP BY pseq) COUNTS ON COUNTS.PSEQ=SHCROWD.seq WHERE REQ = 1 AND ENDFLAG='0'
        ORDER BY SEQ DESC) A,(SELECT @ROWNUM := 0)R

        ) RESULT
        <if test="rnn == null or rnn ==''">
            WHERE 12 >= rnn
        </if>
        <if test="rnn != null and rnn !=''">
            WHERE rnn between #{rnn}+1 AND #{rnn}+12
        </if>
    </select>
    <select id="listbySearch" parameterType="com.sung.hee.shcrowd.model.SHCrowd"
            resultType="com.sung.hee.shcrowd.model.SHCrowd">
        SELECT RESULT.* FROM (SELECT @ROWNUM := @ROWNUM + 1 as rnn,pnum,SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM,
        CURMONEY, TAG,
        SDATE, EDATE, CATEGORY, ADDRESS, TYPE,REQ,LATLNG,WDATE,ENDFLAG,REWARD FROM (
        SELECT IFNULL(pnum,0) as pnum,SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM,
        IFNULL(COUNTS.CURMONEY,0)
        AS CURMONEY, TAG,
        SDATE, EDATE, CATEGORY, ADDRESS, TYPE,REQ,LATLNG,WDATE,ENDFLAG,REWARD FROM SHCROWD left join (SELECT COUNT(*)
        PNUM,PSEQ,SUM(MONEY) CURMONEY FROM
        SHFUND GROUP BY pseq) COUNTS ON COUNTS.PSEQ=SHCROWD.seq WHERE REQ = 1 AND ENDFLAG='0'
        <if test="search_type != '' and search_type != null">
            <if test="search_type == 'search'">
                AND (TAG like CONCAT('%',#{search},'%') OR TITLE like CONCAT('%',#{search},'%') OR CONTENT like
                CONCAT('%',#{search},'%'))
            </if>
            <if test="search_type == 'tag'">
                AND (TAG like CONCAT('%',#{search},'%'))
            </if>
            <if test="search_type == 'category'">

                AND (CATEGORY like CONCAT('%',#{category},'%')) AND (TAG like CONCAT('%',#{search},'%') OR TITLE like
                CONCAT('%',#{search},'%') OR CONTENT like CONCAT('%',#{search},'%'))
            </if>
        </if>
        ORDER BY SEQ DESC
        ) A,(SELECT @ROWNUM := 0)R ) RESULT
        <if test="rnn !=9999">
            <if test="rnn == null or rnn ==''">
                WHERE 12 >= rnn
            </if>
            <if test="rnn != null and rnn !=''">
                WHERE rnn between #{rnn}+1 AND #{rnn}+12
            </if>
        </if>
    </select>
    <select id="myCrowdList" parameterType="com.sung.hee.help.MyCrowd"
            resultType="com.sung.hee.help.MyCrowd">

        SELECT c.SEQ,f.SEQ as myseq, c.TITLE, c.GOALMONEY, c.CURMONEY, c.tag,
        c.SDATE, c.EDATE, c.CATEGORY, c.TYPE,c.REQ, f.MONEY,f.wdate FROM ( SELECT @ROWNUM := @ROWNUM + 1 as rnn,pnum,SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM, CURMONEY, TAG,
    SDATE, EDATE, CATEGORY, ADDRESS, TYPE,REQ,LATLNG,WDATE FROM (
    SELECT IFNULL(pnum,0) as pnum,SEQ, TITLE, CONTENT, ID, GOALMONEY, LIKENUM,
    IFNULL(COUNTS.CURMONEY,0) AS CURMONEY, TAG, SDATE, EDATE, CATEGORY, ADDRESS, TYPE,REQ,LATLNG,WDATE
    FROM SHCROWD left join
    (SELECT COUNT(*) PNUM,PSEQ,SUM(MONEY) CURMONEY
    FROM SHFUND GROUP BY pseq) COUNTS ON COUNTS.PSEQ=SHCROWD.seq ORDER BY SEQ DESC)A,(SELECT @ROWNUM := 0)R )c join SHFUND f on c.seq = f.pseq
        WHERE f.id = #{id}

    </select>

    <insert id="fundCrowd" parameterType="com.sung.hee.shcrowd.model.SHFund">
        INSERT INTO SHFUND(PSEQ, MONEY, wdate, ID) VALUES
        (#{pseq},#{money},DATE_FORMAT(NOW(), '%Y-%m-%d'),#{id})

    </insert>

    <delete id="fundCrowdCancel" parameterType="com.sung.hee.shcrowd.model.SHFund">
        DELETE FROM SHFUND WHERE SEQ = #{seq}

    </delete>

    <insert id="crowdLike" parameterType="com.sung.hee.help.CrowdLike">

        INSERT INTO SHCROWDLIKE(PSEQ, ID) VALUES (#{pseq},#{id})

    </insert>
    <delete id="crowdUnLike" parameterType="com.sung.hee.help.CrowdLike">

      DELETE FROM SHCROWDLIKE WHERE id=#{id} and pseq=#{pseq}

    </delete>
    <select id="crowdLikeChk" parameterType="com.sung.hee.help.CrowdLike"
            resultType="java.lang.Integer">

        SELECT count(*) FROM SHCROWDLIKE WHERE id=#{id} and pseq=#{pseq}

    </select>
    <select id="crowdLikeNum" parameterType="com.sung.hee.help.CrowdLike"
            resultType="java.lang.Integer">
        SELECT LIKENUM FROM SHCROWD WHERE SEQ=#{pseq}

    </select>
    <update id="likeUpdate" parameterType="com.sung.hee.help.CrowdLike">
        UPDATE SHCROWD SET LIKENUM=LIKENUM
        <if test="like==0">+1</if>
        <if test="like==-1">-1</if>
        WHERE seq = #{pseq}

    </update>

    <update id="endFlag" parameterType="com.sung.hee.shcrowd.model.SHCrowd">
        UPDATE SHCROWD SET ENDFLAG = '1' WHERE SEQ = #{seq}
    </update>
    <update id="finishReward" parameterType="com.sung.hee.shcrowd.model.SHCrowd">

        UPDATE SHCROWD SET REWARD = '1' WHERE SEQ = #{seq}

    </update>
    <update id="addReward" parameterType="com.sung.hee.shcrowd.model.SHCrowd">

        UPDATE SHUSER SET POINT = POINT + #{curMoney} WHERE ID = #{id}

    </update>

    <update id="inPoint" parameterType="com.sung.hee.user.model.SHUser">

        UPDATE SHUSER SET POINT = POINT + #{epoint} WHERE ID= #{id}

    </update>

    <update id="dePoint" parameterType="com.sung.hee.user.model.SHUser">

        UPDATE SHUSER SET POINT = POINT - #{epoint} WHERE ID= #{id}

    </update>

    <select id="findTag"
            resultType="java.lang.String">
        SELECT TAG FROM SHCROWD WHERE REQ=1 AND ENDFLAG ='0'
    </select>

    <select id="searchCategory" parameterType="com.sung.hee.shcrowd.model.SHCrowd"
            resultType="com.sung.hee.shcrowd.model.SHCrowd">
    	SELECT COUNT(*) CNT, CATEGORY FROM SHCROWD
		WHERE TAG like CONCAT('%',#{search},'%') OR TITLE like CONCAT('%',#{search},'%') OR CONTENT like CONCAT('%',#{search},'%')
		GROUP BY CATEGORY
    </select>

    <update id="updateCrowd">
        UPDATE SHCROWD SET
        TITLE = #{title}, CONTENT = #{content}, TAG = #{tag}, REQ=0
        WHERE SEQ = #{seq} AND ID = #{id}
<!--         <if test="address != null and address!=''"> -->
<!--             ADDRESS = #{address} -->
<!--         </if> -->
<!--         <if test="address == null or address==''">ADDRESS =''</if> -->
<!--         TYPE = #{type}, REQ = 0, WDATE = DATE_FORMAT(NOW(), '%Y-%m-%d'), -->
<!--         <if test="latlng != null and latlng!=''"> -->
<!--             LATLAG = #{latlng} -->
<!--         </if> -->
<!--         <if test="latlng == null or latlng==''">LATLAG = ''</if> -->
    </update>

</mapper>


text:
#include "wlcore.h"
#include "debug.h"
#include "ps.h"
#include "sysfs.h"

static ssize_t wl1271_sysfs_show_bt_coex_state(struct device *dev,
					       struct device_attribute *attr,
					       char *buf)
{
	struct wl1271 *wl = dev_get_drvdata(dev);
	ssize_t len;

	len = PAGE_SIZE;

	mutex_lock(&wl->mutex);
	len = snprintf(buf, len, "%d\n\n0 - off\n1 - on\n",
		       wl->sg_enabled);
	mutex_unlock(&wl->mutex);

	return len;

}

static ssize_t wl1271_sysfs_store_bt_coex_state(struct device *dev,
						struct device_attribute *attr,
						const char *buf, size_t count)
{
	struct wl1271 *wl = dev_get_drvdata(dev);
	unsigned long res;
	int ret;

	ret = kstrtoul(buf, 10, &res);
	if (ret < 0) {
		wl1271_warning("incorrect value written to bt_coex_mode");
		return count;
	}

	mutex_lock(&wl->mutex);

	res = !!res;

	if (res == wl->sg_enabled)
		goto out;

	wl->sg_enabled = res;

	if (unlikely(wl->state != WLCORE_STATE_ON))
		goto out;

	ret = wl1271_ps_elp_wakeup(wl);
	if (ret < 0)
		goto out;

	wl1271_acx_sg_enable(wl, wl->sg_enabled);
	wl1271_ps_elp_sleep(wl);

 out:
	mutex_unlock(&wl->mutex);
	return count;
}

static DEVICE_ATTR(bt_coex_state, S_IRUGO | S_IWUSR,
		   wl1271_sysfs_show_bt_coex_state,
		   wl1271_sysfs_store_bt_coex_state);

static ssize_t wl1271_sysfs_show_hw_pg_ver(struct device *dev,
					   struct device_attribute *attr,
					   char *buf)
{
	struct wl1271 *wl = dev_get_drvdata(dev);
	ssize_t len;

	len = PAGE_SIZE;

	mutex_lock(&wl->mutex);
	if (wl->hw_pg_ver >= 0)
		len = snprintf(buf, len, "%d\n", wl->hw_pg_ver);
	else
		len = snprintf(buf, len, "n/a\n");
	mutex_unlock(&wl->mutex);

	return len;
}

static DEVICE_ATTR(hw_pg_ver, S_IRUGO,
		   wl1271_sysfs_show_hw_pg_ver, NULL);

static ssize_t wl1271_sysfs_read_fwlog(struct file *filp, struct kobject *kobj,
				       struct bin_attribute *bin_attr,
				       char *buffer, loff_t pos, size_t count)
{
	struct device *dev = container_of(kobj, struct device, kobj);
	struct wl1271 *wl = dev_get_drvdata(dev);
	ssize_t len;
	int ret;

	ret = mutex_lock_interruptible(&wl->mutex);
	if (ret < 0)
		return -ERESTARTSYS;

	/* Let only one thread read the log at a time, blocking others */
	while (wl->fwlog_size == 0) {
		DEFINE_WAIT(wait);

		prepare_to_wait_exclusive(&wl->fwlog_waitq,
					  &wait,
					  TASK_INTERRUPTIBLE);

		if (wl->fwlog_size != 0) {
			finish_wait(&wl->fwlog_waitq, &wait);
			break;
		}

		mutex_unlock(&wl->mutex);

		schedule();
		finish_wait(&wl->fwlog_waitq, &wait);

		if (signal_pending(current))
			return -ERESTARTSYS;

		ret = mutex_lock_interruptible(&wl->mutex);
		if (ret < 0)
			return -ERESTARTSYS;
	}

	/* Check if the fwlog is still valid */
	if (wl->fwlog_size < 0) {
		mutex_unlock(&wl->mutex);
		return 0;
	}

	/* Seeking is not supported - old logs are not kept. Disregard pos. */
	len = min(count, (size_t)wl->fwlog_size);
	wl->fwlog_size -= len;
	memcpy(buffer, wl->fwlog, len);

	/* Make room for new messages */
	memmove(wl->fwlog, wl->fwlog + len, wl->fwlog_size);

	mutex_unlock(&wl->mutex);

	return len;
}

static struct bin_attribute fwlog_attr = {
	.attr = {.name = "fwlog", .mode = S_IRUSR},
	.read = wl1271_sysfs_read_fwlog,
};

int wlcore_sysfs_init(struct wl1271 *wl)
{
	int ret;

	/* Create sysfs file to control bt coex state */
	ret = device_create_file(wl->dev, &dev_attr_bt_coex_state);
	if (ret < 0) {
		wl1271_error("failed to create sysfs file bt_coex_state");
		goto out;
	}

	/* Create sysfs file to get HW PG version */
	ret = device_create_file(wl->dev, &dev_attr_hw_pg_ver);
	if (ret < 0) {
		wl1271_error("failed to create sysfs file hw_pg_ver");
		goto out_bt_coex_state;
	}

	/* Create sysfs file for the FW log */
	ret = device_create_bin_file(wl->dev, &fwlog_attr);
	if (ret < 0) {
		wl1271_error("failed to create sysfs file fwlog");
		goto out_hw_pg_ver;
	}

	goto out;

out_hw_pg_ver:
	device_remove_file(wl->dev, &dev_attr_hw_pg_ver);

out_bt_coex_state:
	device_remove_file(wl->dev, &dev_attr_bt_coex_state);

out:
	return ret;
}

void wlcore_sysfs_free(struct wl1271 *wl)
{
	device_remove_bin_file(wl->dev, &fwlog_attr);

	device_remove_file(wl->dev, &dev_attr_hw_pg_ver);

	device_remove_file(wl->dev, &dev_attr_bt_coex_state);
}


text:
class CianModifier : public search::CategoriesModifier
{
public:
  explicit CianModifier(std::string const & city);

  // CategoriesModifier overrides:
  void Modify(search::DisplayedCategories::Keys & keys) override;

private:
  std::string m_city;
};


text:
Android Fun App

Please add a file called "api_keys.xml" to res/values and insert your The Movie DB API key there:

`<resources><string name="THE_MOVIE_DB_API_KEY">YOUR_KEY_GOES_HERE</string></resources>`


text:
import React from 'react'
import { Text, View, Dimensions, Modal, TouchableHighlight, Animated, ScrollView, Easing } from 'react-native'
import * as utils from './utils'
import styles2 from './styles'

const WARN_COLOR = '#FF3B30'
const MAX_HEIGHT = Dimensions.get('window').height * 0.7

class ActionSheet extends React.Component {
  static defaultProps = {
    tintColor: '#007AFF',
    buttonUnderlayColor: '#F4F4F4',
    onPress: () => {},
    styles: {}
  }

  constructor (props) {
    super(props)
    this.scrollEnabled = false
    this.translateY = this._calculateHeight(props)
    this.state = {
      visible: false,
      sheetAnim: new Animated.Value(this.translateY)
    }
  }

  componentWillReceiveProps (nextProps) {
    this.translateY = this._calculateHeight(nextProps)
  }

  get styles () {
    const { styles } = this.props
    const obj = {}
    Object.keys(styles2).forEach((key) => {
      const arr = [styles2[key]]
      if (styles[key]) {
        arr.push(styles[key])
      }
      obj[key] = arr
    })
    return obj
  }

  show = () => {
    this.setState({visible: true}, () => {
      this._showSheet()
    })
  }

  hide = (index) => {
    this._hideSheet(() => {
      this.setState({visible: false}, () => {
        this.props.onPress(index)
      })
    })
  }

  _cancel = () => {
    const { cancelButtonIndex } = this.props
    // 保持和 ActionSheetIOS 一致,
    // 未设置 cancelButtonIndex 时,点击背景不隐藏 ActionSheet
    if (utils.isset(cancelButtonIndex)) {
      this.hide(cancelButtonIndex)
    }
  }

  _showSheet = () => {
    Animated.timing(this.state.sheetAnim, {
      toValue: 0,
      duration: 250,
      easing: Easing.out(Easing.ease)
    }).start()
  }

  _hideSheet (callback) {
    Animated.timing(this.state.sheetAnim, {
      toValue: this.translateY,
      duration: 200
    }).start(callback)
  }

  /**
   * elements: titleBox, messageBox, buttonBox, cancelButtonBox
   * box size: height, marginTop, marginBottom
   */
  _calculateHeight (props) {
    const styles = this.styles

    const getHeight = (name) => {
      const style = styles[name][styles[name].length - 1]
      let h = 0
      ;['height', 'marginTop', 'marginBottom'].forEach((attrName) => {
        if (typeof style[attrName] !== 'undefined') {
          h += style[attrName]
        }
      })
      return h
    }

    let height = 0
    if (props.title) height += getHeight('titleBox')
    if (props.message) height += getHeight('messageBox')
    if (utils.isset(props.cancelButtonIndex)) {
      height += getHeight('cancelButtonBox')
      height += (props.options.length - 1) * getHeight('buttonBox')
    } else {
      height += props.options.length * getHeight('buttonBox')
    }

    if (height > MAX_HEIGHT) {
      this.scrollEnabled = true
      height = MAX_HEIGHT
    } else {
      this.scrollEnabled = false
    }

    return height
  }

  _renderTitle () {
    const { title } = this.props
    const styles = this.styles
    if (!title) return null
    return (
      <View style={styles.titleBox}>
        {React.isValidElement(title) ? title : (
          <Text style={styles.titleText}>{title}</Text>
        )}
      </View>
    )
  }

  _renderMessage () {
    const { message } = this.props
    const styles = this.styles
    if (!message) return null
    return (
      <View style={styles.messageBox}>
        {React.isValidElement(message) ? message : (
          <Text style={styles.messageText}>{message}</Text>
        )}
      </View>
    )
  }

  _renderCancelButton () {
    const { options, cancelButtonIndex } = this.props
    if (!utils.isset(cancelButtonIndex)) return null
    return this._createButton(options[cancelButtonIndex], cancelButtonIndex)
  }

  _createButton (title, index) {
    const styles = this.styles
    const { buttonUnderlayColor, cancelButtonIndex, destructiveButtonIndex, tintColor } = this.props
    const fontColor = destructiveButtonIndex === index ? WARN_COLOR : tintColor
    const buttonBoxStyle = cancelButtonIndex === index ? styles.cancelButtonBox : styles.buttonBox
    return (
      <TouchableHighlight
        key={index}
        activeOpacity={1}
        underlayColor={buttonUnderlayColor}
        style={buttonBoxStyle}
        onPress={() => this.hide(index)}
      >
        {React.isValidElement(title) ? title : (
          <Text style={[styles.buttonText, {color: fontColor}]}>{title}</Text>
        )}
      </TouchableHighlight>
    )
  }

  _renderOptions () {
    const { cancelButtonIndex } = this.props
    return this.props.options.map((title, index) => {
      return cancelButtonIndex === index ? null : this._createButton(title, index)
    })
  }

  render () {
    const styles = this.styles
    const { visible, sheetAnim } = this.state
    return (
      <Modal visible={visible}
        animationType='none'
        transparent
        onRequestClose={this._cancel}
      >
        <View style={[styles.wrapper]}>
          <Text
            style={[styles.overlay]}
            onPress={this._cancel}
          />
          <Animated.View
            style={[
              styles.body,
              { height: this.translateY, transform: [{ translateY: sheetAnim }] }
            ]}
          >
            {this._renderTitle()}
            {this._renderMessage()}
            <ScrollView scrollEnabled={this.scrollEnabled}>{this._renderOptions()}</ScrollView>
            {this._renderCancelButton()}
          </Animated.View>
        </View>
      </Modal>
    )
  }
}

export default ActionSheet