text:
package edu.psu.ist.youseer;
public class Extractor {
    public Extractor() {
    }

    public static String GenerateCustomeData(SubmitterDocument doc)
    {
        // Add your code here
        return "";
    }

    /*
         Example Code:
     public static String GenerateCustomeData(SubmitterDocument doc)
         {

     StringBuilder command = new StringBuilder();
      command.append("<field name=\"page_author\">").append("Your Name").append("</field>").
              append(ARCSubmitter.LINE_SEP);

        return command.toString();;
         }
     *
     *
     * public static String GenerateCustomeData1(SubmitterDocument doc)
  {
	StringBuilder command = new StringBuilder();
                 String url = doc.getUrl();
String date = url.substring(23, 27) + "-" + url.substring(28, 30) + "-" + url.substring(31, 33) + "T00:00:00Z";
	command.append("<field name=\"publication_date\">").append(date).append("</field>").
append(ARCSubmitter.LINE_SEP);
return command.toString();
}

     */
 public static String GenerateCustomeData1(SubmitterDocument doc)
         {

     StringBuilder command = new StringBuilder();
      command.append("<field name=\"page_author\">").append("Your Name").append("</field>").
              append(ARCSubmitter.LINE_SEP);

        return command.toString();
         }

}


text:
<?php

namespace Smalldb\Flupdo;

/**
 * Query builder base class, which provides some magic to build queries.
 */
abstract class FlupdoBuilder
{
	/**
	 * PDO driver used to execute query and escape strings.
	 */
	public $pdo;

	/**
	 * Log all queries as they are executed
	 */
	protected $log_query;

	/**
	 * Explain each query to log.
	 */
	protected $log_explain;

	/**
	 * Sphinx does not like parenthesis in WHERE
	 */
	protected $no_parenthesis_in_conditions;

	/**
	 * Is it possible to explain this query?
	 */
	protected $can_explain = false;

	/**
	 * Indentation string.
	 */
	protected $indent = "\t";

	/**
	 * Second level indentation string.
	 */
	protected $sub_indent = "\t\t";

	/**
	 * Built query
	 */
	protected $query_sql = null;

	/**
	 * Parameters for prepared statement (to be bound before query is executed).
	 */
	protected $query_params = null;

	/**
	 * List of clauses used to composed result query. Shared constant data.
	 */
	protected static $clauses = array();

	/**
	 * List of methods used to fill the $buffers. Shared constant data.
	 */
	protected static $methods = array();

	/**
	 * Buffers containing SQL fragments.
	 */
	protected $buffers = array();

	/**
	 * @name Flags for helper methods.
	 *
	 * Used by sqlList() and sqlStatementFlags().
	 * @{
	 */
	const INDENT		= 0x01;	///< List items should be indented.
	const LABEL		= 0x02;	///< SQL fragment has a label.
	const BRACKETS		= 0x04;	///< There are brackets around each item in the list.
	const NO_SEPARATOR	= 0x08;	///< No separator between list items
	const SUB_INDENT	= 0x20;	///< Indent more the first line.
	const COMMA		= 0x40;	///< Add comma after the SQL fragment.
	const EOL		= 0x80;	///< Add EOL after the SQL fragment.
	const ALL_DECORATIONS	= 0xFF;	///< Make it fancy!
	/** @} */

	/**
	 * Constructor.
	 */
	public function __construct($pdo, $log_query = false, $log_explain = false, $no_parenthesis_in_conditions = false)
	{
		$this->pdo = $pdo;
		$this->log_query = $log_query;
		$this->log_explain = $log_explain;
		$this->no_parenthesis_in_conditions = $no_parenthesis_in_conditions;
	}

	/**
	 * Call buffer-specific method to process arguments.
	 *
	 * If the first argument is null, corresponding buffer will be deleted.
	 */
	public function __call($method, $args)
	{
		//echo __CLASS__, "::", $method, " (", join(', ', array_map(function($x) { return var_export($x, true);}, $args)), ")\n";

		if (!isset(static::$methods[$method])) {
			throw new \BadMethodCallException('Undefined method "'.$method.'".');
		}

		if ($this->query_sql !== null) {
			throw new \RuntimeException('Query is already compiled.');
		}

		$method_cfg = static::$methods[$method];
		list($action, $buffer_id) = $method_cfg;
		$label = $method_cfg[2] ?? null;        // label is optional

		if (count($args) == 1 && $args[0] === null) {
			unset($this->buffers[$buffer_id]);
		} else {
			$this->$action($args, $buffer_id, $label);
		}

		$this->query_sql = null;

		return $this;
	}

	/**
	 * Quote `identifier`, preserve dot.
	 */
	public function quoteIdent($ident)
	{
		if (is_array($ident)) {
			return array_map(function($ident) { return '`' . str_replace(array('`', '.'), array('``', '`.`'), $ident) . '`'; }, $ident);
		} else {
			return '`' . str_replace(array('`', '.'), array('``', '`.`'), $ident) . '`';
		}
	}

	/**
	 * Add SQL fragment to buffer.
	 */
	protected function add($args, $buffer_id)
	{
		$this->buffers[$buffer_id][] = $args;
	}

	/**
	 * Replace buffer content with SQL fragment.
	 */
	protected function replace($args, $buffer_id)
	{
		$this->buffers[$buffer_id] = array($args);
	}

	/**
	 * Set flag. Replace buffer with new label of this flag.
	 */
	protected function setFlag($args, $buffer_id, $label)
	{
		$this->buffers[$buffer_id] = $label;
	}

	/**
	 * Add join statement to buffer.
	 */
	protected function addJoin($args, $buffer_id, $label)
	{
		array_push($args, $label);
		$this->buffers[$buffer_id][] = $args;
	}

	/**
	 * Process all buffers and build SQL query. Side product is array of
	 * parameters (stored in $this->args) to bind with query.
	 *
	 * This function is called by FlupdoBuilder, do not call it directly.
	 *
	 * Example:
	 *
	 *     $this->sqlStart();
	 *     // ...
	 *     return $this->sqlFinish();
	 *
	 */
	abstract protected function compileQuery();

	/**
	 * Call compile function in a safe way.
	 */
	public final function compile()
	{
		try {
			$q = $this->compileQuery();
			if ($this->log_query) {
				error_log(sprintf("SQL Query (compile):\n%s", $this->query_sql));
			}
			return $q;
		}
		catch (\Exception $ex) {
			// Make sure unfinished query will not make it to the output.
			ob_end_clean();
			throw $ex;
		}
	}

	/**
	 * "Uncompile" the query. This will drop compiled query and allow
	 * additional modifications. Once query is compiled additional
	 * modifications are not allowed to detect programming errors, but
	 * sometimes it is useful to execute the query and then perform
	 * additional modifications before second execution.
	 */
	public function uncompile()
	{
		$this->query_sql = null;
	}

	/**
	 * Fluently dump query to error log.
	 */
	public function debugDump()
	{
		error_log("Query:\n".$this);
		return $this;
	}

	/**
	 * Get compiled SQL query, use only for debugging.
	 */
	public function getSqlQuery()
	{
		if ($this->query_sql === null) {
			$this->compile();
		}

		return $this->query_sql;
	}

	/**
	 * Get parameters for compiled SQL query, use only for debugging.
	 */
	public function getSqlParams()
	{
		if ($this->query_sql === null) {
			$this->compile();
		}

		return $this->query_params;
	}

	/**
	 * Quotes a string for use in a query.
	 *
	 * Proxy to PDO::quote().
	 */
	public function quote($value)
	{
		// PDO::quote() does not work as it should ...
		if ($value instanceof FlupdoRawSql) {
			return $value;
		} else if (is_bool($value)) {
			return $value ? 'TRUE' : 'FALSE';
		} else if (is_null($value)) {
			return 'NULL';
		} else if (is_int($value)) {
			return (string) $value;
		} else if (is_float($value)) {
			return sprintf('%F', $value);
		} else {
			// ignore locales when converting to string
			return $this->pdo->quote(strval($value), \PDO::PARAM_STR);
		}
	}

	/**
	 * Returns object marking raw SQL statement.
	 */
	public function rawSql($sql)
	{
		return new FlupdoRawSql($sql);
	}

	/**
	 * Builds and executes an SQL statement, returning the number of affected rows.
	 *
	 * Proxy to PDO::exec().
	 */
	public function exec()
	{
		if ($this->query_sql === null) {
			$this->compile();
		}
		if ($this->log_query) {
			error_log(sprintf("SQL Query (exec):\n%s", $this->query_sql));
		}
		if (empty($this->query_params)) {
			$t = microtime(true);
			try {
				$r = $this->pdo->exec($this->query_sql);
				if ($this->log_query) {
					error_log(sprintf("SQL Query time: %F ms (exec).", (microtime(true) - $t) * 1000));
				}
			}
			catch (\PDOException $ex) {
				throw new FlupdoException($ex->getMessage(), $ex->getCode(), $ex, $this->query_sql, $this->query_params);
			}
			if ($r === FALSE) {
				throw new FlupdoException(vsprintf("SQLSTATE[%s]: Error %s: %s", $this->pdo->errorInfo()),
					$this->pdo->errorCode(), null, $this->query_sql, $this->query_params);
			}
			return $r;
		} else {
			$stmt = $this->query();
			return $stmt->rowCount();
		}
	}

	/**
	 * Builds, binds and executes an SQL statement, returning a result set
	 * as a PDOStatement object.
	 *
	 * Proxy to PDOStatement::prepare() & PDOStatement::bindValue() & PDOStatement::query().
	 * But if there is nothing to bind, PDO::query() is called instead.
	 */
	public function query()
	{
		if ($this->query_sql === null) {
			$this->compile();
		}

		if (empty($this->query_params)) {
			$t = microtime(true);
			try {
				$result = $this->pdo->query($this->query_sql);
				if ($this->log_query) {
					error_log(sprintf("SQL Query time: %F ms (query), %d rows.", (microtime(true) - $t) * 1000, $result->rowCount()));
				}
			}
			catch (\PDOException $ex) {
				throw new FlupdoException($ex->getMessage(), $ex->getCode(), $ex, $this->query_sql, $this->query_params);
			}
			if (!$result) {
				throw new FlupdoException(vsprintf("SQLSTATE[%s]: Error %s: %s", $this->pdo->errorInfo()),
					$this->pdo->errorCode(), null, $this->query_sql, $this->query_params);
			}
			return $result;
		} else {
			$t = microtime(true);
			try {
				$stmt = $this->prepare();
			}
			catch (\PDOException $ex) {
				throw new FlupdoException($ex->getMessage(), $ex->getCode(), $ex, $this->query_sql, $this->query_params);
			}
			if ($stmt === FALSE) {
				throw new FlupdoException(vsprintf("SQLSTATE[%s]: Error %s: %s", $this->pdo->errorInfo()),
					$this->pdo->errorCode(), null, $this->query_sql, $this->query_params);
			}

			$i = 1;
			foreach ($this->query_params as $param) {
				if (is_bool($param)) {
					$stmt->bindValue($i, $param, \PDO::PARAM_BOOL);
				} else if (is_null($param)) {
					$stmt->bindValue($i, $param, \PDO::PARAM_NULL);
				} else if (is_int($param)) {
					$stmt->bindValue($i, $param, \PDO::PARAM_INT);
				} else {
					// ignore locales when converting to string
					$stmt->bindValue($i, strval($param), \PDO::PARAM_STR);
				}
				$i++;
			}

			try {
				$success = $stmt->execute();
			}
			catch (\PDOException $ex) {
				throw new FlupdoException($ex->getMessage(), $ex->getCode(), $ex, $this->query_sql, $this->query_params);
			}
			if ($success === FALSE) {
				throw new FlupdoException(vsprintf("SQLSTATE[%s]: Error %s: %s", $stmt->errorInfo()),
					$stmt->errorCode(), null, $this->query_sql, $this->query_params);
			}
			if ($this->log_query) {
				error_log(sprintf("SQL Query time: %F ms (prepare + execute), %d rows.", (microtime(true) - $t) * 1000, $stmt->rowCount()));
			}
			if ($this->can_explain && $this->log_explain) {
				$this->explain();
			}
			return $stmt;
		}
	}

	/**
	 * Explain the query and dump result to log.
	 */
	protected function explain()
	{
		if ($this->query_sql === null) {
			$this->compile();
		}

		$sql = "\n    EXPLAIN\n" . $this->interpolateQuery($this->query_sql, $this->query_params);

		$explain = $this->pdo->query($sql);

		$data = $explain->fetchAll(\PDO::FETCH_ASSOC);
		$col_len = array();
		$t = "\n";

		// Calculate column widths
		foreach ($data as $row) {
			foreach ($row as $k => $v) {
				$col_len[$k] = isset($col_len[$k]) ? max($col_len[$k], strlen($v)) : strlen($v);
			}
		}
		foreach ($col_len as $k => $len) {
			$col_len[$k] = max($len, strlen($k));
		}

		// Horizontal Line
		foreach ($col_len as $k => $len) {
			$t .= '+'.str_repeat('-', $len + 2);
		}
		$t .= "+\n";

		// Table header
		foreach ($col_len as $k => $len) {
			$t .= sprintf('| %-'.$len.'s ', $k);
		}
		$t .= "+\n";

		// Horizontal Line
		foreach ($col_len as $k => $len) {
			$t .= '+'.str_repeat('-', $len + 2);
		}
		$t .= "+\n";

		// Table body
		foreach ($data as $row) {
			foreach ($row as $k => $v) {
				$t .= sprintf('| %-'.$col_len[$k].'s ', $v);
			}
			$t .= "|\n";
		}

		// Horizontal Line
		foreach ($col_len as $k => $len) {
			$t .= '+'.str_repeat('-', $len + 2);
		}
		$t .= "+\n";

		// Log the table
		if (function_exists('debug_msg')) {
			debug_msg('Explain last query:%s', $t);
		}

		// Make sure EXPLAIN query is destroyed.
		$this->uncompile();
	}

	/**
	 * Replaces any parameter placeholders in a query with the value of that
	 * parameter. Useful for debugging. Assumes anonymous parameters from
	 * $params are are in the same order as specified in $query
	 *
	 * @see http://stackoverflow.com/questions/210564/getting-raw-sql-query-string-from-pdo-prepared-statements
	 *
	 * Added `$pdo->quote()` to properly escape all values.
	 *
	 * @param string $query The sql query with parameter placeholders
	 * @param array $params The array of substitution parameters
	 * @return string The interpolated query
	 */
	private function interpolateQuery($query, $params)
	{
		$keys = array();

		# build a regular expression for each parameter
		foreach ($params as $key => $value) {
			if (is_string($key)) {
				$keys[] = '/:'.$key.'/';
			} else {
				$keys[] = '/[?]/';
			}
		}

		$pdo = $this->pdo;
		$query = preg_replace($keys, array_map(function($a) use ($pdo) { return $pdo->quote($a); }, $params), $query, 1, $count);

		#trigger_error('replaced '.$count.' keys');

		return $query;
	}

	/**
	 * Builds and prepares a statement for execution, returns a statement object.
	 *
	 * Proxy to PDO::prepare().
	 */
	public function prepare($driver_options = array())
	{
		if ($this->query_sql === null) {
			$this->compile();
		}

		return $this->pdo->prepare($this->query_sql, $driver_options);
	}

	/**
	 * Proxy to PDO::lastInsertId().
	 */
	public function lastInsertId()
	{
		return $this->pdo->lastInsertId();
	}

	/**
	 * Fetch one row from result and close cursor.
	 *
	 * Returns what PDOStatement::fetch() would return.
	 */
	public function fetchSingleRow()
	{
		$result = $this->query();
		$row = $result->fetch(\PDO::FETCH_ASSOC);
		$result->closeCursor();
		return $row;
	}

	/**
	 * Fetch one row from result and close cursor.
	 *
	 * Returns what PDOStatement::fetchColumn(0) would return.
	 */
	public function fetchSingleValue()
	{
		$result = $this->query();
		$value = $result->fetchColumn(0);
		$result->closeCursor();
		return $value;
	}

	/**
	 * Fetch everything into array
	 *
	 * Returns what PDOStatement::fetchAll(PDO::FETCH_ASSOC) would return.
	 *
	 * If $key_column is set, the specified column will be used to index
	 * array items.
	 *
	 * @note Keep in mind that this is not effective for larger data sets.
	 * 	It is better to perform the query and iterate over result
	 * 	instead of loading it all at once. However, it may not be
	 * 	possible in all cases.
	 */
	public function fetchAll($key_column = null)
	{
		$result = $this->query();
		if ($key_column === null) {
			$list = $result->fetchAll(\PDO::FETCH_ASSOC);
		} else {
			$list = array();
			while(($item = $result->fetch(\PDO::FETCH_ASSOC))) {
				$list[$item[$key_column]] = $item;
			}
			return $list;
		}
		$result->closeCursor();
		return $list;
	}

	/**
	 * Get SQL query as a string.
	 */
	public function __toString()
	{
		try {
			if ($this->query_sql === null) {
				$this->compile();
			}
		}
		catch (\Exception $ex) {
			// __toString() cannot throw an exception, so we will
			// log it and die, fatal error would be triggered anyway.
			error_log(__METHOD__.': '.$ex);
			die();
		}
		return $this->query_sql;
	}

	/**
	 * Start SQL generating. Uses output buffering to concatenate the query.
	 */
	protected function sqlStart()
	{
		$this->query_params = array();
		ob_start();
	}

	/**
	 * Finish SQL generating. Picks up the query from output buffer.
	 */
	protected function sqlFinish()
	{
		$this->query_sql = ob_get_clean();

		// Flatten parameters before bind
		if (!empty($this->query_params)) {
			$this->query_params = call_user_func_array('array_merge', $this->query_params);
		}
		return $this;
	}

	/**
	 * Add SQL with parameters. Parameters are stored in groups, merge to
	 * one array is done at the end (using single array_merge call).
	 */
	protected function sqlBuffer($buf)
	{
		if (empty($buf)) {
			return;
		}

		$sql = array_shift($buf);

		if (is_array($sql)) {
			$first = true;
			foreach ($sql as $fragment) {
				if ($first) {
					$first = false;
				} else {
					echo ' ';
				}
				if ($fragment instanceof self) {
					$fragment->indent = $this->sub_indent."\t";
					$fragment->compile();
					echo "(\n", $fragment->query_sql, $this->sub_indent, ")";
					$this->query_params[] = $fragment->query_params;
				} else {
					echo $fragment;
				}
			}
		} else if ($sql instanceof self) {
			$sql->indent = $this->sub_indent."\t";
			$sql->compile();
			echo "(\n", $sql->query_sql, $sql->sub_indent, ")";
			$this->query_params[] = $sql->query_params;
		} else {
			echo $sql;
		}

		if (!empty($buf)) {
			$this->query_params[] = $buf;
		}
	}

	/**
	 * Generate raw SQL fragment.
	 */
	protected function sqlRawBuffer($buf)
	{
		if (is_array($buf[0])) {
			echo join("\n", $buf[0]);
		} else {
			echo $buf[0];
		}
	}

	/**
	 * Generate SQL comment.
	 */
	protected function sqlComment($buffer_id)
	{
		if (isset($this->buffers[$buffer_id])) {
			foreach ($this->buffers[$buffer_id] as $buf) {
				echo $this->indent, '-- ', str_replace(array("\r", "\n"), array('', "\n".$this->indent.'-- '), $this->sqlRawBuffer($buf)), "\n";
			}
		}
	}

	/**
	 * Generate flag fragment.
	 */
	protected function sqlFlag($buffer_id)
	{
		if (isset($this->buffers[$buffer_id])) {
			if (isset($this->buffers[$flag_buf])) {
				echo ' ', $this->buffers[$flag_buf];
			}
		}
	}

	/**
	 * Generate SQL fragment made of flags.
	 */
	protected function sqlStatementFlags($buffer_id, $flag_buffer_ids, $decorations)
	{
		$first = false;

		if ($decorations & self::INDENT) {
			echo $this->indent;
			$first = true;
		}

		if ($decorations & self::LABEL) {
			if ($first) {
				$first = false;
			} else {
				echo ' ';
			}
			echo $buffer_id;
			$first = false;
		}

		foreach ($flag_buffer_ids as $flag_buf) {
			if (isset($this->buffers[$flag_buf])) {
				if ($first) {
					$first = false;
				} else {
					echo ' ';
				}
				echo $this->buffers[$flag_buf];
			}
		}

		if ($decorations & self::COMMA) {
			echo ",";
		}
		if ($decorations & self::EOL) {
			echo "\n";
		}
	}

	/**
	 * Generate SQL fragment made of list.
	 */
	protected function sqlList($buffer_id, $decorations)
	{
		$first = true;

		if (isset($this->buffers[$buffer_id])) {
			if ($decorations & (self::INDENT | self::SUB_INDENT)) {
				if ($decorations & (self::BRACKETS | self::SUB_INDENT)) {
					echo $this->sub_indent;
				} else {
					echo $this->indent;
				}
			} else if ($decorations & (self::LABEL | self::BRACKETS)) {
				echo ' ';
			}
			if ($decorations & self::LABEL) {
				echo $buffer_id;
			}
			if ($decorations & self::BRACKETS) {
				echo '(';
			}
			foreach ($this->buffers[$buffer_id] as $buf) {
				if ($decorations & self::NO_SEPARATOR) {
					if ($first) {
						$first = false;
					} else {
						echo "\n", $this->sub_indent;
					}
				} else if ($decorations & self::BRACKETS) {
					if ($first) {
						$first = false;
					} else {
						echo ", ";
					}
				} else {
					if ($first) {
						$first = false;
						echo ' ';
					} else {
						echo ",\n", $this->sub_indent;
					}
				}
				$this->sqlBuffer($buf);
			}
			if ($decorations & self::BRACKETS) {
				echo ')';
			}
			if ($decorations & self::COMMA) {
				echo ",";
			}
			if ($decorations & self::EOL) {
				echo "\n";
			}
		}
	}

	/**
	 * Generate SQL fragment made of list values.
	 */
	protected function sqlValuesList($buffer_id)
	{
		$first = true;

		if (isset($this->buffers[$buffer_id])) {
			echo $this->indent, $buffer_id, "\n";
			foreach ($this->buffers[$buffer_id] as $buf) {
				if (count($buf) == 1) {
					// One argument -- insert values from array
					foreach ($buf[0] as $row) {
						if ($first) {
							$first = false;
							echo $this->sub_indent, '(';
						} else {
							echo "),\n", $this->sub_indent, '(';
						}

						echo join(', ', array_map(array($this, 'quote'), $row)); // FIXME: bind values
					}
				} else {
					throw new \Exception('Not implemented yet.');
				}
			}
			echo ')';
			echo "\n";
		}
	}

	/**
	 * Generate SQL fragment made of joins.
	 */
	protected function sqlJoins($buffer_id)
	{
		$first = true;

		if (isset($this->buffers[$buffer_id])) {
			foreach ($this->buffers[$buffer_id] as $buf) {
				$join = array_pop($buf);
				echo $this->indent, $join, " ", $this->sqlBuffer($buf), "\n";
			}
		}
	}

	/**
	 * Generate SQL fragment made of conditions in AND statement.
	 */
	protected function sqlConditions($buffer_id)
	{
		$first = true;

		if (isset($this->buffers[$buffer_id])) {
			echo $this->indent, $buffer_id;
			if ($this->no_parenthesis_in_conditions) {
				foreach ($this->buffers[$buffer_id] as $buf) {
					if ($first) {
						$first = false;
						echo ' ';
					} else {
						echo $this->sub_indent, "AND ";
					}
					echo $this->sqlBuffer($buf), "\n";
				}
			} else {
				foreach ($this->buffers[$buffer_id] as $buf) {
					if ($first) {
						$first = false;
						echo ' (';
					} else {
						echo $this->sub_indent, "AND (";
					}
					echo $this->sqlBuffer($buf), ")\n";
				}
			}
		}
	}

	/**
	 * Generate documentation for methods defined in $methods array.
	 */
	public static function generateDoxygenDocumentation()
	{
		foreach (static::$methods as $methodName => $m) {
			@ list($realMethod, $buffer, $label) = $m;
			echo "/**\n";
			echo "@memberof ", get_called_class(), "\n";
			if ($realMethod == 'setFlag') {
				echo "@fn $methodName()\n";
			} else {
				echo "@fn $methodName(\$sql_statement, ...)\n";
				echo "@param \$sql_statement SQL statement (a fragment of SQL query) with placeholders.\n";
				echo "@param ... Values of placeholders (when positional placeholders are used).\n";
			}
			echo "@public\n";
			if ($realMethod == 'setFlag') {
				echo "@brief Sets content of buffer `$buffer` to `$label`.\n";
			} else if (substr($realMethod, 0, 3) == 'add') {
				if ($label) {
					echo "@brief Appends `\$sql_statement` prefixed with `$label` to buffer `$buffer`.\n";
				} else {
					echo "@brief Appends `\$sql_statement` to buffer `$buffer`.\n";
				}
			} else {
				if ($label) {
					echo "@brief Replaces content of buffer `$buffer` with `\$sql_statement` prefixed with `$label`.\n";
				} else {
					echo "@brief Replaces content of buffer `$buffer` with `\$sql_statement`.\n";
				}
			}
			echo "\n";
			echo "@note This method is generated from FlupdoBuilder::\$methods array. See compileQuery() method for buffer usage.\n";
			echo "*/\n";
			echo "\n";
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
#include "proton/delivery.hpp"

#include "proton/connection.hpp"
#include "proton/link.hpp"
#include "proton/session.hpp"

#include "proton/delivery.h"
#include "proton/link.h"
#include "proton/session.h"

namespace proton {

link delivery::link() const { return pn_delivery_link(pn_object()); }
session delivery::session() const { return pn_link_session(pn_delivery_link(pn_object())); }
connection delivery::connection() const { return pn_session_connection(pn_link_session(pn_delivery_link(pn_object()))); }
bool delivery::settled() const { return pn_delivery_settled(pn_object()); }

void delivery::settle() { pn_delivery_settle(pn_object()); }

void delivery::update(delivery::state state) { pn_delivery_update(pn_object(), state); }

void delivery::settle(delivery::state state) {
    update(state);
    settle();
}

bool delivery::partial()  const { return pn_delivery_partial(pn_object()); }
bool delivery::readable() const { return pn_delivery_readable(pn_object()); }
bool delivery::writable() const { return pn_delivery_writable(pn_object()); }
bool delivery::updated()  const { return pn_delivery_updated(pn_object()); }
size_t delivery::pending() const { return pn_delivery_pending(pn_object()); }

void delivery::clear()  { pn_delivery_clear(pn_object()); }
delivery::state delivery::remote_state() const { return state(pn_delivery_remote_state(pn_object())); }
}


text:
<?php

namespace mako\http\response\senders;

use Closure;
use mako\http\Request;
use mako\http\Response;

use function flush;
use function ob_end_clean;
use function ob_get_level;
use function printf;
use function strlen;

/**
 * Stream response.
 */
class Stream implements ResponseSenderInterface
{
	/**
	 * Is PHP running as a CGI program?
	 *
	 * @var bool
	 */
	protected $isCGI;

	/**
	 * Constructor.
	 *
	 * @param \Closure    $stream      Stream
	 * @param string|null $contentType Content type
	 * @param string|null $charset     Character set
	 */
	public function __construct(
		protected Closure $stream,
		protected ?string $contentType = null,
		protected ?string $charset = null
	)
	{}

	/**
	 * Sets the response content type.
	 *
	 * @param  string                             $contentType Content type
	 * @return \mako\http\response\senders\Stream
	 */
	public function setType(string $contentType): Stream
	{
		$this->contentType = $contentType;

		return $this;
	}

	/**
	 * Returns the response content type.
	 *
	 * @return string|null
	 */
	public function getType(): ?string
	{
		return $this->contentType;
	}

	/**
	 * Sets the response character set.
	 *
	 * @param  string                             $charset Character set
	 * @return \mako\http\response\senders\Stream
	 */
	public function setCharset(string $charset): Stream
	{
		$this->charset = $charset;

		return $this;
	}

	/**
	 * Returns the response character set.
	 *
	 * @return string|null
	 */
	public function getCharset(): ?string
	{
		return $this->charset;
	}

	/**
	 * Flushes a chunck of data.
	 *
	 * @param string|null $chunk      Chunck of data to flush
	 * @param bool        $flushEmpty Flush empty chunk?
	 */
	public function flush(?string $chunk, bool $flushEmpty = false): void
	{
		if($this->isCGI)
		{
			if(!empty($chunk))
			{
				echo $chunk;

				flush();
			}
		}
		else
		{
			if(!empty($chunk) || $flushEmpty === true)
			{
				printf("%x\r\n%s\r\n", strlen($chunk ?? ''), $chunk ?? '');

				flush();
			}
		}
	}

	/**
	 * Sends the stream.
	 */
	protected function flow(): void
	{
		// Erase output buffers and disable output buffering

		while(ob_get_level() > 0) ob_end_clean();

		// Send the stream

		$stream = $this->stream;

		$stream($this);

		// Send empty chunk to tell the client that we're done

		$this->flush(null, true);
	}

	/**
	 * {@inheritDoc}
	 */
	public function send(Request $request, Response $response): void
	{
		$this->isCGI = $request->isCGI();

		if(!$this->isCGI)
		{
			$response->getHeaders()->add('Content-Encoding', 'chunked');
			$response->getHeaders()->add('Transfer-Encoding', 'chunked');
		}

		if(!empty($this->contentType))
		{
			$response->setType($this->contentType);
		}

		if(!empty($this->charset))
		{
			$response->setCharset($this->charset);
		}

		$response->sendHeaders();

		$this->flow();
	}
}


text:
layout: post
status: publish
published: true
title: Just When I Thought I Was Over Zombies
author: Jeff
author_login: admin
author_email: jeff@allthingsdork.com
author_url: http://www.allthingsdork.com
wordpress_id: 662
wordpress_url: http://www.allthingsdork.com/?p=662
date: '2011-02-17 09:31:02 -0600'
date_gmt: '2011-02-17 15:31:02 -0600'
categories:
- Random
tags:
- Video Games
- zombies
- dead island
comments: []
---

It's rare that a game makes me downright emotional. The game will have a hard time living up to this trailer, but I already want to kick some zombie ass! For Jasmine!!!! Or whatever the girl's name is....

<object id="vid_4d5af1dfdad0bd219500000b" class="ign-videoplayer" width="480" height="270" data="http://media.ign.com/ev/prod/embed.swf" type="application/x-shockwave-flash"><param name="movie" value="http://media.ign.com/ev/prod/embed.swf" /><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="bgcolor" value="#000000" /><param name="flashvars" value="url=http://www.ign.com/videos/2011/02/16/dead-island-announcement-trailer"/></object>

More Dead Island Videos


text:
using testing::Return;
using testing::StrictMock;
using testing::_;

namespace net {
namespace test {

const QuicByteCount kBytesInFlight = 1024;
const int kInitialBurstPackets = 10;

class PacingSenderTest : public ::testing::Test {
 protected:
  PacingSenderTest()
      : zero_time_(QuicTime::Delta::Zero()),
        infinite_time_(QuicTime::Delta::Infinite()),
        packet_number_(1),
        mock_sender_(new StrictMock<MockSendAlgorithm>()),
        pacing_sender_(new PacingSender) {
    pacing_sender_->set_sender(mock_sender_.get());
    // Pick arbitrary time.
    clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(9));
  }

  ~PacingSenderTest() override {}

  void InitPacingRate(QuicPacketCount burst_size, QuicBandwidth bandwidth) {
    mock_sender_.reset(new StrictMock<MockSendAlgorithm>());
    pacing_sender_.reset(new PacingSender);
    pacing_sender_->set_sender(mock_sender_.get());
    EXPECT_CALL(*mock_sender_, PacingRate(_)).WillRepeatedly(Return(bandwidth));
    if (burst_size == 0) {
      EXPECT_CALL(*mock_sender_, OnCongestionEvent(_, _, _, _, _));
      SendAlgorithmInterface::CongestionVector lost_packets;
      lost_packets.push_back(std::make_pair(1, kMaxPacketSize));
      SendAlgorithmInterface::CongestionVector empty;
      pacing_sender_->OnCongestionEvent(true, 1234, clock_.Now(), empty,
                                        lost_packets);
    } else if (burst_size != kInitialBurstPackets) {
      LOG(FATAL) << "Unsupported burst_size " << burst_size
                 << " specificied, only 0 and " << kInitialBurstPackets
                 << " are supported.";
    }
  }

  void CheckPacketIsSentImmediately(HasRetransmittableData retransmittable_data,
                                    QuicByteCount bytes_in_flight,
                                    bool in_recovery) {
    // In order for the packet to be sendable, the underlying sender must
    // permit it to be sent immediately.
    for (int i = 0; i < 2; ++i) {
      EXPECT_CALL(*mock_sender_, TimeUntilSend(clock_.Now(), bytes_in_flight))
          .WillOnce(Return(zero_time_));
      // Verify that the packet can be sent immediately.
      EXPECT_EQ(zero_time_,
                pacing_sender_->TimeUntilSend(clock_.Now(), bytes_in_flight));
    }

    // Actually send the packet.
    if (bytes_in_flight == 0) {
      EXPECT_CALL(*mock_sender_, InRecovery()).WillOnce(Return(in_recovery));
    }
    EXPECT_CALL(*mock_sender_,
                OnPacketSent(clock_.Now(), bytes_in_flight, packet_number_,
                             kMaxPacketSize, retransmittable_data));
    pacing_sender_->OnPacketSent(clock_.Now(), bytes_in_flight,
                                 packet_number_++, kMaxPacketSize,
                                 retransmittable_data);
  }

  void CheckPacketIsSentImmediately() {
    CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, kBytesInFlight,
                                 false);
  }

  void CheckPacketIsDelayed(QuicTime::Delta delay) {
    // In order for the packet to be sendable, the underlying sender must
    // permit it to be sent immediately.
    for (int i = 0; i < 2; ++i) {
      EXPECT_CALL(*mock_sender_, TimeUntilSend(clock_.Now(), kBytesInFlight))
          .WillOnce(Return(zero_time_));
      // Verify that the packet is delayed.
      EXPECT_EQ(delay.ToMicroseconds(),
                pacing_sender_->TimeUntilSend(clock_.Now(), kBytesInFlight)
                    .ToMicroseconds());
    }
  }

  void UpdateRtt() {
    EXPECT_CALL(*mock_sender_,
                OnCongestionEvent(true, kBytesInFlight, _, _, _));
    SendAlgorithmInterface::CongestionVector empty_map;
    pacing_sender_->OnCongestionEvent(true, kBytesInFlight, clock_.Now(),
                                      empty_map, empty_map);
  }

  const QuicTime::Delta zero_time_;
  const QuicTime::Delta infinite_time_;
  MockClock clock_;
  QuicPacketNumber packet_number_;
  std::unique_ptr<StrictMock<MockSendAlgorithm>> mock_sender_;
  std::unique_ptr<PacingSender> pacing_sender_;
};

TEST_F(PacingSenderTest, NoSend) {
  for (int i = 0; i < 2; ++i) {
    EXPECT_CALL(*mock_sender_, TimeUntilSend(clock_.Now(), kBytesInFlight))
        .WillOnce(Return(infinite_time_));
    EXPECT_EQ(infinite_time_,
              pacing_sender_->TimeUntilSend(clock_.Now(), kBytesInFlight));
  }
}

TEST_F(PacingSenderTest, SendNow) {
  for (int i = 0; i < 2; ++i) {
    EXPECT_CALL(*mock_sender_, TimeUntilSend(clock_.Now(), kBytesInFlight))
        .WillOnce(Return(zero_time_));
    EXPECT_EQ(zero_time_,
              pacing_sender_->TimeUntilSend(clock_.Now(), kBytesInFlight));
  }
}

TEST_F(PacingSenderTest, VariousSending) {
  // Configure pacing rate of 1 packet per 1 ms, no initial burst.
  InitPacingRate(0, QuicBandwidth::FromBytesAndTimeDelta(
                        kMaxPacketSize, QuicTime::Delta::FromMilliseconds(1)));

  // Now update the RTT and verify that packets are actually paced.
  UpdateRtt();

  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();

  // The first packet was a "make up", then we sent two packets "into the
  // future", so the delay should be 2.
  CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2));

  // Wake up on time.
  clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(2));
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2));

  // Wake up late.
  clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(4));
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2));

  // Wake up really late.
  clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(8));
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2));

  // Wake up really late again, but application pause partway through.
  clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(8));
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(100));
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2));

  // Wake up too early.
  CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2));

  // Wake up early, but after enough time has passed to permit a send.
  clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
  CheckPacketIsSentImmediately();
  CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2));
}

TEST_F(PacingSenderTest, InitialBurst) {
  // Configure pacing rate of 1 packet per 1 ms.
  InitPacingRate(10, QuicBandwidth::FromBytesAndTimeDelta(
                         kMaxPacketSize, QuicTime::Delta::FromMilliseconds(1)));

  EXPECT_CALL(*mock_sender_, GetCongestionWindow())
      .WillOnce(Return(10 * kDefaultTCPMSS));
  // Update the RTT and verify that the first 10 packets aren't paced.
  UpdateRtt();

  // Send 10 packets, and verify that they are not paced.
  for (int i = 0; i < kInitialBurstPackets; ++i) {
    CheckPacketIsSentImmediately();
  }

  // The first packet was a "make up", then we sent two packets "into the
  // future", so the delay should be 2ms.
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2));

  clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
  CheckPacketIsSentImmediately();

  // Next time TimeUntilSend is called with no bytes in flight, pacing should
  // allow a packet to be sent, and when it's sent, the tokens are refilled.
  CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 0, false);
  for (int i = 0; i < kInitialBurstPackets - 1; ++i) {
    CheckPacketIsSentImmediately();
  }

  // The first packet was a "make up", then we sent two packets "into the
  // future", so the delay should be 2ms.
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2));
}

TEST_F(PacingSenderTest, InitialBurstNoRttMeasurement) {
  // Configure pacing rate of 1 packet per 1 ms.
  InitPacingRate(10, QuicBandwidth::FromBytesAndTimeDelta(
                         kMaxPacketSize, QuicTime::Delta::FromMilliseconds(1)));

  EXPECT_CALL(*mock_sender_, GetCongestionWindow())
      .WillOnce(Return(10 * kDefaultTCPMSS));
  // Send 10 packets, and verify that they are not paced.
  for (int i = 0; i < kInitialBurstPackets; ++i) {
    CheckPacketIsSentImmediately();
  }

  // The first packet was a "make up", then we sent two packets "into the
  // future", so the delay should be 2ms.
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2));

  clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
  CheckPacketIsSentImmediately();

  // Next time TimeUntilSend is called with no bytes in flight, the tokens
  // should be refilled and there should be no delay.
  CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 0, false);
  // Send 10 packets, and verify that they are not paced.
  for (int i = 0; i < kInitialBurstPackets - 1; ++i) {
    CheckPacketIsSentImmediately();
  }

  // The first packet was a "make up", then we sent two packets "into the
  // future", so the delay should be 2ms.
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2));
}

TEST_F(PacingSenderTest, FastSending) {
  // Ensure the pacing sender paces, even when the inter-packet spacing is less
  // than the pacing granularity.
  InitPacingRate(10,
                 QuicBandwidth::FromBytesAndTimeDelta(
                     2 * kMaxPacketSize, QuicTime::Delta::FromMilliseconds(1)));

  EXPECT_CALL(*mock_sender_, GetCongestionWindow())
      .WillOnce(Return(10 * kDefaultTCPMSS));
  // Update the RTT and verify that the first 10 packets aren't paced.
  UpdateRtt();

  // Send 10 packets, and verify that they are not paced.
  for (int i = 0; i < kInitialBurstPackets; ++i) {
    CheckPacketIsSentImmediately();
  }

  // The first packet was a "make up", then we sent two packets "into the
  // future", since it's 2 packets/ms, so the delay should be 1.5ms.
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsDelayed(QuicTime::Delta::FromMicroseconds(1500));

  clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
  CheckPacketIsSentImmediately();

  // Next time TimeUntilSend is called with no bytes in flight, the tokens
  // should be refilled and there should be no delay.
  CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 0, false);
  for (int i = 0; i < kInitialBurstPackets - 1; ++i) {
    CheckPacketIsSentImmediately();
  }

  // The first packet was a "make up", then we sent two packets "into the
  // future", so the delay should be 1.5ms.
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsSentImmediately();
  CheckPacketIsDelayed(QuicTime::Delta::FromMicroseconds(1500));
}

TEST_F(PacingSenderTest, NoBurstEnteringRecovery) {
  // Configure pacing rate of 1 packet per 1 ms with no burst tokens.
  InitPacingRate(0, QuicBandwidth::FromBytesAndTimeDelta(
                        kMaxPacketSize, QuicTime::Delta::FromMilliseconds(1)));
  // Sending a packet will set burst tokens.
  CheckPacketIsSentImmediately();

  // Losing a packet will set clear burst tokens.
  SendAlgorithmInterface::CongestionVector lost_packets;
  lost_packets.push_back(std::make_pair(1, kMaxPacketSize));
  SendAlgorithmInterface::CongestionVector empty;
  EXPECT_CALL(*mock_sender_,
              OnCongestionEvent(true, kMaxPacketSize, _, empty, lost_packets));
  pacing_sender_->OnCongestionEvent(true, kMaxPacketSize, clock_.Now(), empty,
                                    lost_packets);
  // One packet is sent immediately, because of 1ms pacing granularity.
  CheckPacketIsSentImmediately();
  // Ensure packets are immediately paced.
  EXPECT_CALL(*mock_sender_, TimeUntilSend(clock_.Now(), kDefaultTCPMSS))
      .WillOnce(Return(zero_time_));
  // Verify the next packet is paced and delayed 2ms due to granularity.
  EXPECT_EQ(QuicTime::Delta::FromMilliseconds(2),
            pacing_sender_->TimeUntilSend(clock_.Now(), kDefaultTCPMSS));
  CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2));
}

TEST_F(PacingSenderTest, NoBurstInRecovery) {
  // Configure pacing rate of 1 packet per 1 ms with no burst tokens.
  InitPacingRate(0, QuicBandwidth::FromBytesAndTimeDelta(
                        kMaxPacketSize, QuicTime::Delta::FromMilliseconds(1)));

  UpdateRtt();

  // Ensure only one packet is sent immediately and the rest are paced.
  CheckPacketIsSentImmediately(HAS_RETRANSMITTABLE_DATA, 0, true);
  CheckPacketIsSentImmediately();
  CheckPacketIsDelayed(QuicTime::Delta::FromMilliseconds(2));
}

}  // namespace test
}  // namespace net


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Nest
{
	public class FieldsDescriptor<T> : DescriptorPromiseBase<FieldsDescriptor<T>, Fields>
		where T : class
	{
		public FieldsDescriptor() : base(new Fields()) { }

		public FieldsDescriptor<T> Fields(params Expression<Func<T, object>>[] fields) => Assign(f => f.And(fields));
		public FieldsDescriptor<T> Fields(params string[] fields) => Assign(f => f.And(fields));
		public FieldsDescriptor<T> Fields(IEnumerable<Field> fields) => Assign(f => f.ListOfFields.AddRange(fields));

		public FieldsDescriptor<T> Field(Expression<Func<T, object>> field, double? boost = null) => Assign(f => f.And(field, boost));
		public FieldsDescriptor<T> Field(string field, double? boost = null) => Assign(f => f.And(field, boost));
	}
}


text:
<?php
/* @var $this SiteController */
/* @var $model LoginForm */
/* @var $form CActiveForm  */

$this->pageTitle=Yii::app()->name . ' - Login';
$this->breadcrumbs=array(
	'Login',
);
?>

Login to your account

<?php
	$this->beginWidget('zii.widgets.CPortlet', array(
		'title'=>"Private access",
	));

?>

Please fill out the following form with your login credentials:

    <?php $form=$this->beginWidget('CActiveForm', array(
        'id'=>'login-form',
        'enableClientValidation'=>true,
        'clientOptions'=>array(
            'validateOnSubmit'=>true,
        ),
    )); ?>

Fields with * are required.

            <?php echo $form->labelEx($model,'username'); ?>
            <?php echo $form->textField($model,'username'); ?>
            <?php echo $form->error($model,'username'); ?>

            <?php echo $form->labelEx($model,'password'); ?>
            <?php echo $form->passwordField($model,'password'); ?>
            <?php echo $form->error($model,'password'); ?>

                Hint: You may login with demo/demo or admin/admin.

            <?php echo $form->checkBox($model,'rememberMe'); ?>
            <?php echo $form->label($model,'rememberMe'); ?>
            <?php echo $form->error($model,'rememberMe'); ?>

            <?php echo CHtml::submitButton('Login',array('class'=>'btn btn btn-primary')); ?>

    <?php $this->endWidget(); ?>

<?php $this->endWidget();?>


text:
package swarm

import (
	"fmt"
	"io"
	"os"

	"golang.org/x/net/context"

	"github.com/docker/cli/cli/command"
	"github.com/docker/cli/cli/command/bundlefile"
	"github.com/docker/cli/cli/command/stack/options"
	"github.com/docker/cli/cli/compose/convert"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/swarm"
	"github.com/pkg/errors"
)

func deployBundle(ctx context.Context, dockerCli command.Cli, opts options.Deploy) error {
	bundle, err := loadBundlefile(dockerCli.Err(), opts.Namespace, opts.Bundlefile)
	if err != nil {
		return err
	}

	if err := checkDaemonIsSwarmManager(ctx, dockerCli); err != nil {
		return err
	}

	namespace := convert.NewNamespace(opts.Namespace)

	if opts.Prune {
		services := map[string]struct{}{}
		for service := range bundle.Services {
			services[service] = struct{}{}
		}
		pruneServices(ctx, dockerCli, namespace, services)
	}

	networks := make(map[string]types.NetworkCreate)
	for _, service := range bundle.Services {
		for _, networkName := range service.Networks {
			networks[networkName] = types.NetworkCreate{
				Labels: convert.AddStackLabel(namespace, nil),
			}
		}
	}

	services := make(map[string]swarm.ServiceSpec)
	for internalName, service := range bundle.Services {
		name := namespace.Scope(internalName)

		var ports []swarm.PortConfig
		for _, portSpec := range service.Ports {
			ports = append(ports, swarm.PortConfig{
				Protocol:   swarm.PortConfigProtocol(portSpec.Protocol),
				TargetPort: portSpec.Port,
			})
		}

		nets := []swarm.NetworkAttachmentConfig{}
		for _, networkName := range service.Networks {
			nets = append(nets, swarm.NetworkAttachmentConfig{
				Target:  namespace.Scope(networkName),
				Aliases: []string{internalName},
			})
		}

		serviceSpec := swarm.ServiceSpec{
			Annotations: swarm.Annotations{
				Name:   name,
				Labels: convert.AddStackLabel(namespace, service.Labels),
			},
			TaskTemplate: swarm.TaskSpec{
				ContainerSpec: &swarm.ContainerSpec{
					Image:   service.Image,
					Command: service.Command,
					Args:    service.Args,
					Env:     service.Env,
					// Service Labels will not be copied to Containers
					// automatically during the deployment so we apply
					// it here.
					Labels: convert.AddStackLabel(namespace, nil),
				},
			},
			EndpointSpec: &swarm.EndpointSpec{
				Ports: ports,
			},
			Networks: nets,
		}

		services[internalName] = serviceSpec
	}

	if err := createNetworks(ctx, dockerCli, namespace, networks); err != nil {
		return err
	}
	return deployServices(ctx, dockerCli, services, namespace, opts.SendRegistryAuth, opts.ResolveImage)
}

func loadBundlefile(stderr io.Writer, namespace string, path string) (*bundlefile.Bundlefile, error) {
	defaultPath := fmt.Sprintf("%s.dab", namespace)

	if path == "" {
		path = defaultPath
	}
	if _, err := os.Stat(path); err != nil {
		return nil, errors.Errorf(
			"Bundle %s not found. Specify the path with --file",
			path)
	}

	fmt.Fprintf(stderr, "Loading bundle from %s\n", path)
	reader, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer reader.Close()

	bundle, err := bundlefile.LoadFile(reader)
	if err != nil {
		return nil, errors.Errorf("Error reading %s: %v\n", path, err)
	}
	return bundle, err
}


text:
'use strict';
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');

describe('node:cli', () => {
  beforeEach(() => {
    return helpers.run(require.resolve('../generators/cli')).on('ready', generator => {
      generator.fs.write(generator.destinationPath('package.json'), '{"name": "my-lib"}');
    });
  });

  it('creates cli.js', () => {
    assert.file('lib/cli.js');
    assert.fileContent('lib/cli.js', "const meow = require('meow')");
    assert.fileContent('lib/cli.js', "const myLib = require('./')");
  });

  it('Extends package.json', () => {
    assert.fileContent('package.json', '"bin": "lib/cli.js"');
    assert.fileContent('package.json', '"meow"');
    assert.fileContent('package.json', /"lec": "\^/);
    assert.fileContent('package.json', '"prepare": "lec lib/cli.js -c LF"');
  });
});

describe('node:cli', () => {
  beforeEach(() => {
    return helpers
      .run(require.resolve('../generators/cli'))
      .withOptions({ generateInto: 'other/' })
      .on('ready', generator => {
        generator.fs.write(
          generator.destinationPath('other/package.json'),
          '{"name": "my-lib"}'
        );
      });
  });

  it('creates cli.js with path option', () => {
    assert.file('other/lib/cli.js');
  });
});


text:
import pprint
import sys

class TraceCalls(object):
    def __init__(self, stream=sys.stdout, indent='  ', files=()):
        self.stream = stream
        self.indent = indent
        self.files = frozenset(files)
        self.stack_depth = 0
        self.max_depth = 0
    def __call__(self, frame, event, arg):
        if event == 'call':
            if not self.files or frame.f_code.co_filename in self.files:
                self.stack_depth += 1
                if self.stack_depth > self.max_depth:
                    self.max_depth = self.stack_depth
                name = frame.f_code.co_name
                print(self.indent * self.stack_depth, frame.f_code.co_filename, name)
                if not (name == '__str__' or name == '__init__' or name == '<lambda>'):
                    pprint.pprint(frame.f_locals)
        elif event == 'return':
            if not self.files or frame.f_code.co_filename in self.files:
                print(self.indent * self.stack_depth, frame.f_code.co_filename, frame.f_code.co_name, arg)
                self.stack_depth -= 1
        return self

class StackDepth(object):
    def __init__(self):
        self.stack_depth = 0
        self.max_depth = 0
    def __call__(self, frame, event, arg):
        if event == 'call':
            self.stack_depth += 1
        if event == 'return':
            self.stack_depth -= 1
        return self


text:
<myRes>
 <head>
  <its:rules xmlns:its="http://www.w3.org/2005/11/its" version="2.0">
   <its:locNoteRule locNoteType="alert" selector="//msg[@id='DisableInfo']">
    <its:locNote>The variable {0} has three possible values: 'printer',
    'stacker' and 'stapler options'.</its:locNote>
   </its:locNoteRule>
  </its:rules>
 </head>
 <body>
  <msg id="DisableInfo">The {0} has been disabled.</msg>
 </body>
</myRes>


text:
import React from 'react';

import { fetchTweetStatus } from '../services';

interface TweetStatus {
  items: {
    statusId: number;
    userId: number;
    userName: string;
    screenName: string;
    text: string;
    tweetedAt: Date;
    profileImageUrl: string;
    statusUrl: string;
    userUrl: string;
    mediaUrl: string;
  }[]
}

const useTweetStatus = (date?: Date): {
  value?: TweetStatus;
  loading : boolean;
} => {

  const [ value, setValue ] = React.useState<TweetStatus>();
  const [ loading, setLoading ] = React.useState<boolean>(false);

  React.useEffect(() => {
    if (!date) {
      return;
    }
    (async () => {
      try {
        setLoading(true);
        const minDate = new Date(date.toDateString());
        const maxDate = new Date(date.toDateString());
        maxDate.setDate(maxDate.getDate() + 1);
        const json = await fetchTweetStatus(minDate, maxDate);
        setValue((value) => ({
          ...value,
          items: json.items.map(item => ({
            statusId: item.statusId,
            userId: item.userId,
            userName: item.userName,
            screenName: item.screenName,
            text: item.text,
            tweetedAt: new Date(item.tweetedAt),
            profileImageUrl: item.profileImageUrl,
            statusUrl: item.statusUrl,
            userUrl: item.userUrl,
            mediaUrl: item.mediaUrl
          }))
        }));
      } finally {
        setLoading(false);
      }
    })();
  }, [ date ]);

  return {
    loading,
    value
  };

};

export default useTweetStatus;


text:
package org.jetbrains.plugins.github.util;

import com.intellij.concurrency.JobScheduler;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.ThrowableComputable;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ConcurrencyUtil;
import com.intellij.util.Consumer;
import com.intellij.util.ThrowableConsumer;
import com.intellij.util.ThrowableConvertor;
import com.intellij.util.containers.Convertor;
import git4idea.DialogManager;
import git4idea.GitUtil;
import git4idea.commands.GitCommand;
import git4idea.commands.GitSimpleHandler;
import git4idea.config.GitVcsApplicationSettings;
import git4idea.config.GitVersion;
import git4idea.i18n.GitBundle;
import git4idea.repo.GitRemote;
import git4idea.repo.GitRepository;
import git4idea.repo.GitRepositoryManager;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.github.api.GithubApiUtil;
import org.jetbrains.plugins.github.api.GithubConnection;
import org.jetbrains.plugins.github.api.GithubFullPath;
import org.jetbrains.plugins.github.api.GithubUserDetailed;
import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException;
import org.jetbrains.plugins.github.exceptions.GithubOperationCanceledException;
import org.jetbrains.plugins.github.exceptions.GithubTwoFactorAuthenticationException;
import org.jetbrains.plugins.github.ui.GithubBasicLoginDialog;
import org.jetbrains.plugins.github.ui.GithubLoginDialog;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * Various utility methods for the GutHub plugin.
 *
 * @author oleg
 * @author Kirill Likhodedov
 * @author Aleksey Pivovarov
 */
public class GithubUtil {

  public static final Logger LOG = Logger.getInstance("github");

  // TODO: Consider sharing of GithubAuthData between actions (as member of GithubSettings)
  public static <T> T runTask(@NotNull Project project,
                              @NotNull GithubAuthDataHolder authHolder,
                              @NotNull final ProgressIndicator indicator,
                              @NotNull ThrowableConvertor<GithubConnection, T, IOException> task) throws IOException {
    GithubAuthData auth = authHolder.getAuthData();
    try {
      final GithubConnection connection = new GithubConnection(auth, true);
      ScheduledFuture<?> future = null;

      try {
        future = addCancellationListener(indicator, connection);
        return task.convert(connection);
      }
      finally {
        connection.close();
        if (future != null) future.cancel(true);
      }
    }
    catch (GithubTwoFactorAuthenticationException e) {
      getTwoFactorAuthData(project, authHolder, indicator, auth);
      return runTask(project, authHolder, indicator, task);
    }
    catch (GithubAuthenticationException e) {
      getValidAuthData(project, authHolder, indicator, auth);
      return runTask(project, authHolder, indicator, task);
    }
  }

  public static <T> T runTaskWithBasicAuthForHost(@NotNull Project project,
                                                  @NotNull GithubAuthDataHolder authHolder,
                                                  @NotNull final ProgressIndicator indicator,
                                                  @NotNull String host,
                                                  @NotNull ThrowableConvertor<GithubConnection, T, IOException> task) throws IOException {
    GithubAuthData auth = authHolder.getAuthData();
    try {
      if (auth.getAuthType() != GithubAuthData.AuthType.BASIC) {
        throw new GithubAuthenticationException("Expected basic authentication");
      }

      final GithubConnection connection = new GithubConnection(auth, true);
      ScheduledFuture<?> future = null;

      try {
        future = addCancellationListener(indicator, connection);
        return task.convert(connection);
      }
      finally {
        connection.close();
        if (future != null) future.cancel(true);
      }
    }
    catch (GithubTwoFactorAuthenticationException e) {
      getTwoFactorAuthData(project, authHolder, indicator, auth);
      return runTaskWithBasicAuthForHost(project, authHolder, indicator, host, task);
    }
    catch (GithubAuthenticationException e) {
      getValidBasicAuthDataForHost(project, authHolder, indicator, auth, host);
      return runTaskWithBasicAuthForHost(project, authHolder, indicator, host, task);
    }
  }

  @NotNull
  private static GithubUserDetailed testConnection(@NotNull Project project,
                                                   @NotNull GithubAuthDataHolder authHolder,
                                                   @NotNull final ProgressIndicator indicator) throws IOException {
    GithubAuthData auth = authHolder.getAuthData();
    try {
      final GithubConnection connection = new GithubConnection(auth, true);
      ScheduledFuture<?> future = null;

      try {
        future = addCancellationListener(indicator, connection);
        return GithubApiUtil.getCurrentUserDetailed(connection);
      }
      finally {
        connection.close();
        if (future != null) future.cancel(true);
      }
    }
    catch (GithubTwoFactorAuthenticationException e) {
      getTwoFactorAuthData(project, authHolder, indicator, auth);
      return testConnection(project, authHolder, indicator);
    }
  }

  @NotNull
  private static ScheduledFuture<?> addCancellationListener(@NotNull Runnable run) {
    return JobScheduler.getScheduler().scheduleWithFixedDelay(run, 1000, 300, TimeUnit.MILLISECONDS);
  }

  @NotNull
  private static ScheduledFuture<?> addCancellationListener(@NotNull final ProgressIndicator indicator,
                                                            @NotNull final GithubConnection connection) {
    return addCancellationListener(new Runnable() {
      @Override
      public void run() {
        if (indicator.isCanceled()) connection.abort();
      }
    });
  }

  @NotNull
  private static ScheduledFuture<?> addCancellationListener(@NotNull final ProgressIndicator indicator,
                                                            @NotNull final Thread thread) {
    return addCancellationListener(new Runnable() {
      @Override
      public void run() {
        if (indicator.isCanceled()) thread.interrupt();
      }
    });
  }

  public static void getValidAuthData(@NotNull final Project project,
                                      @NotNull final GithubAuthDataHolder authHolder,
                                      @NotNull final ProgressIndicator indicator,
                                      @NotNull final GithubAuthData oldAuth) throws GithubOperationCanceledException {
    authHolder.runTransaction(oldAuth, new ThrowableComputable<GithubAuthData, GithubOperationCanceledException>() {
      @Override
      @NotNull
      public GithubAuthData compute() throws GithubOperationCanceledException {
        final GithubAuthData[] authData = new GithubAuthData[1];
        final boolean[] ok = new boolean[1];
        ApplicationManager.getApplication().invokeAndWait(new Runnable() {
          @Override
          public void run() {
            final GithubLoginDialog dialog = new GithubLoginDialog(project, oldAuth);
            DialogManager.show(dialog);
            ok[0] = dialog.isOK();

            if (ok[0]) {
              authData[0] = dialog.getAuthData();
              GithubSettings.getInstance().setAuthData(authData[0], dialog.isSavePasswordSelected());
            }
          }
        }, indicator.getModalityState());
        if (!ok[0]) {
          throw new GithubOperationCanceledException("Can't get valid credentials");
        }
        return authData[0];
      }
    });
  }

  public static void getValidBasicAuthDataForHost(@NotNull final Project project,
                                                  @NotNull final GithubAuthDataHolder authHolder,
                                                  @NotNull final ProgressIndicator indicator,
                                                  @NotNull final GithubAuthData oldAuth,
                                                  @NotNull final String host) throws GithubOperationCanceledException {
    authHolder.runTransaction(oldAuth, new ThrowableComputable<GithubAuthData, GithubOperationCanceledException>() {
      @Override
      @NotNull
      public GithubAuthData compute() throws GithubOperationCanceledException {
        final GithubAuthData[] authData = new GithubAuthData[1];
        final boolean[] ok = new boolean[1];
        ApplicationManager.getApplication().invokeAndWait(new Runnable() {
          @Override
          public void run() {
            final GithubLoginDialog dialog = new GithubBasicLoginDialog(project, oldAuth, host);
            DialogManager.show(dialog);
            ok[0] = dialog.isOK();
            if (ok[0]) {
              authData[0] = dialog.getAuthData();

              final GithubSettings settings = GithubSettings.getInstance();
              if (settings.getAuthType() != GithubAuthData.AuthType.TOKEN) {
                GithubSettings.getInstance().setAuthData(authData[0], dialog.isSavePasswordSelected());
              }
            }
          }
        }, indicator.getModalityState());
        if (!ok[0]) {
          throw new GithubOperationCanceledException("Can't get valid credentials");
        }
        return authData[0];
      }
    });
  }

  private static void getTwoFactorAuthData(@NotNull final Project project,
                                           @NotNull final GithubAuthDataHolder authHolder,
                                           @NotNull final ProgressIndicator indicator,
                                           @NotNull final GithubAuthData oldAuth) throws GithubOperationCanceledException {
    authHolder.runTransaction(oldAuth, new ThrowableComputable<GithubAuthData, GithubOperationCanceledException>() {
      @Override
      @NotNull
      public GithubAuthData compute() throws GithubOperationCanceledException {
        if (authHolder.getAuthData().getAuthType() != GithubAuthData.AuthType.BASIC) {
          throw new GithubOperationCanceledException("Two factor authentication can be used only with Login/Password");
        }

        GithubApiUtil.askForTwoFactorCodeSMS(new GithubConnection(oldAuth, false));

        final Ref<String> codeRef = new Ref<String>();
        ApplicationManager.getApplication().invokeAndWait(new Runnable() {
          @Override
          public void run() {
            codeRef.set(Messages.showInputDialog(project, "Authentication Code", "Github Two-Factor Authentication", null));
          }
        }, indicator.getModalityState());
        if (codeRef.isNull()) {
          throw new GithubOperationCanceledException("Can't get two factor authentication code");
        }

        GithubSettings settings = GithubSettings.getInstance();
        if (settings.getAuthType() == GithubAuthData.AuthType.BASIC &&
            StringUtil.equalsIgnoreCase(settings.getLogin(), oldAuth.getBasicAuth().getLogin())) {
          settings.setValidGitAuth(false);
        }

        return oldAuth.copyWithTwoFactorCode(codeRef.get());
      }
    });
  }

  @NotNull
  public static GithubAuthDataHolder getValidAuthDataHolderFromConfig(@NotNull Project project, @NotNull ProgressIndicator indicator)
    throws IOException {
    GithubAuthData auth = GithubAuthData.createFromSettings();
    GithubAuthDataHolder authHolder = new GithubAuthDataHolder(auth);
    try {
      checkAuthData(project, authHolder, indicator);
      return authHolder;
    }
    catch (GithubAuthenticationException e) {
      getValidAuthData(project, authHolder, indicator, auth);
      return authHolder;
    }
  }

  @NotNull
  public static GithubUserDetailed checkAuthData(@NotNull Project project,
                                                 @NotNull GithubAuthDataHolder authHolder,
                                                 @NotNull ProgressIndicator indicator) throws IOException {
    GithubAuthData auth = authHolder.getAuthData();

    if (StringUtil.isEmptyOrSpaces(auth.getHost())) {
      throw new GithubAuthenticationException("Target host not defined");
    }

    switch (auth.getAuthType()) {
      case BASIC:
        GithubAuthData.BasicAuth basicAuth = auth.getBasicAuth();
        assert basicAuth != null;
        if (StringUtil.isEmptyOrSpaces(basicAuth.getLogin()) || StringUtil.isEmptyOrSpaces(basicAuth.getPassword())) {
          throw new GithubAuthenticationException("Empty login or password");
        }
        break;
      case TOKEN:
        GithubAuthData.TokenAuth tokenAuth = auth.getTokenAuth();
        assert tokenAuth != null;
        if (StringUtil.isEmptyOrSpaces(tokenAuth.getToken())) {
          throw new GithubAuthenticationException("Empty token");
        }
        break;
      case ANONYMOUS:
        throw new GithubAuthenticationException("Anonymous connection not allowed");
    }

    return testConnection(project, authHolder, indicator);
  }

  public static <T> T computeValueInModal(@NotNull Project project,
                                          @NotNull String caption,
                                          @NotNull final ThrowableConvertor<ProgressIndicator, T, IOException> task) throws IOException {
    final Ref<T> dataRef = new Ref<T>();
    final Ref<Throwable> exceptionRef = new Ref<Throwable>();
    ProgressManager.getInstance().run(new Task.Modal(project, caption, true) {
      public void run(@NotNull ProgressIndicator indicator) {
        try {
          dataRef.set(task.convert(indicator));
        }
        catch (Throwable e) {
          exceptionRef.set(e);
        }
      }
    });
    if (!exceptionRef.isNull()) {
      Throwable e = exceptionRef.get();
      if (e instanceof IOException) throw ((IOException)e);
      if (e instanceof RuntimeException) throw ((RuntimeException)e);
      if (e instanceof Error) throw ((Error)e);
      throw new RuntimeException(e);
    }
    return dataRef.get();
  }

  public static <T> T computeValueInModal(@NotNull Project project,
                                          @NotNull String caption,
                                          @NotNull final Convertor<ProgressIndicator, T> task) {
    return computeValueInModal(project, caption, true, task);
  }

  public static <T> T computeValueInModal(@NotNull Project project,
                                          @NotNull String caption,
                                          boolean canBeCancelled,
                                          @NotNull final Convertor<ProgressIndicator, T> task) {
    final Ref<T> dataRef = new Ref<T>();
    final Ref<Throwable> exceptionRef = new Ref<Throwable>();
    ProgressManager.getInstance().run(new Task.Modal(project, caption, canBeCancelled) {
      public void run(@NotNull ProgressIndicator indicator) {
        try {
          dataRef.set(task.convert(indicator));
        }
        catch (Throwable e) {
          exceptionRef.set(e);
        }
      }
    });
    if (!exceptionRef.isNull()) {
      Throwable e = exceptionRef.get();
      if (e instanceof RuntimeException) throw ((RuntimeException)e);
      if (e instanceof Error) throw ((Error)e);
      throw new RuntimeException(e);
    }
    return dataRef.get();
  }

  public static void computeValueInModal(@NotNull Project project,
                                         @NotNull String caption,
                                         boolean canBeCancelled,
                                         @NotNull final Consumer<ProgressIndicator> task) {
    final Ref<Throwable> exceptionRef = new Ref<Throwable>();
    ProgressManager.getInstance().run(new Task.Modal(project, caption, canBeCancelled) {
      public void run(@NotNull ProgressIndicator indicator) {
        try {
          task.consume(indicator);
        }
        catch (Throwable e) {
          exceptionRef.set(e);
        }
      }
    });
    if (!exceptionRef.isNull()) {
      Throwable e = exceptionRef.get();
      if (e instanceof RuntimeException) throw ((RuntimeException)e);
      if (e instanceof Error) throw ((Error)e);
      throw new RuntimeException(e);
    }
  }

  public static <T> T runInterruptable(@NotNull final ProgressIndicator indicator,
                                       @NotNull ThrowableComputable<T, IOException> task) throws IOException {
    ScheduledFuture<?> future = null;
    try {
      final Thread thread = Thread.currentThread();
      future = addCancellationListener(indicator, thread);

      return task.compute();
    }
    finally {
      if (future != null) future.cancel(true);
      Thread.interrupted();
    }
  }

  /*
  * Git utils
  */

  @Nullable
  public static String findGithubRemoteUrl(@NotNull GitRepository repository) {
    Pair<GitRemote, String> remote = findGithubRemote(repository);
    if (remote == null) {
      return null;
    }
    return remote.getSecond();
  }

  @Nullable
  public static Pair<GitRemote, String> findGithubRemote(@NotNull GitRepository repository) {
    Pair<GitRemote, String> githubRemote = null;
    for (GitRemote gitRemote : repository.getRemotes()) {
      for (String remoteUrl : gitRemote.getUrls()) {
        if (GithubUrlUtil.isGithubUrl(remoteUrl)) {
          final String remoteName = gitRemote.getName();
          if ("github".equals(remoteName) || "origin".equals(remoteName)) {
            return Pair.create(gitRemote, remoteUrl);
          }
          if (githubRemote == null) {
            githubRemote = Pair.create(gitRemote, remoteUrl);
          }
          break;
        }
      }
    }
    return githubRemote;
  }

  @Nullable
  public static String findUpstreamRemote(@NotNull GitRepository repository) {
    for (GitRemote gitRemote : repository.getRemotes()) {
      final String remoteName = gitRemote.getName();
      if ("upstream".equals(remoteName)) {
        for (String remoteUrl : gitRemote.getUrls()) {
          if (GithubUrlUtil.isGithubUrl(remoteUrl)) {
            return remoteUrl;
          }
        }
        return gitRemote.getFirstUrl();
      }
    }
    return null;
  }

  public static boolean testGitExecutable(final Project project) {
    final GitVcsApplicationSettings settings = GitVcsApplicationSettings.getInstance();
    final String executable = settings.getPathToGit();
    final GitVersion version;
    try {
      version = GitVersion.identifyVersion(executable);
    }
    catch (Exception e) {
      GithubNotifications.showErrorDialog(project, GitBundle.getString("find.git.error.title"), e);
      return false;
    }

    if (!version.isSupported()) {
      GithubNotifications.showWarningDialog(project, GitBundle.message("find.git.unsupported.message", version.toString(), GitVersion.MIN),
                                            GitBundle.getString("find.git.success.title"));
      return false;
    }
    return true;
  }

  public static boolean isRepositoryOnGitHub(@NotNull GitRepository repository) {
    return findGithubRemoteUrl(repository) != null;
  }

  public static void setVisibleEnabled(AnActionEvent e, boolean visible, boolean enabled) {
    e.getPresentation().setVisible(visible);
    e.getPresentation().setEnabled(enabled);
  }

  @NotNull
  public static String getErrorTextFromException(@NotNull Exception e) {
    if (e instanceof UnknownHostException) {
      return "Unknown host: " + e.getMessage();
    }
    return e.getMessage();
  }

  @Nullable
  public static GitRepository getGitRepository(@NotNull Project project, @Nullable VirtualFile file) {
    GitRepositoryManager manager = GitUtil.getRepositoryManager(project);
    List<GitRepository> repositories = manager.getRepositories();
    if (repositories.size() == 0) {
      return null;
    }
    if (repositories.size() == 1) {
      return repositories.get(0);
    }
    if (file != null) {
      GitRepository repository = manager.getRepositoryForFile(file);
      if (repository != null) {
        return repository;
      }
    }
    return manager.getRepositoryForFile(project.getBaseDir());
  }

  public static boolean addGithubRemote(@NotNull Project project,
                                        @NotNull GitRepository repository,
                                        @NotNull String remote,
                                        @NotNull String url) {
    final GitSimpleHandler handler = new GitSimpleHandler(project, repository.getRoot(), GitCommand.REMOTE);
    handler.setSilent(true);

    try {
      handler.addParameters("add", remote, url);
      handler.run();
      if (handler.getExitCode() != 0) {
        GithubNotifications.showError(project, "Can't add remote", "Failed to add GitHub remote: '" + url + "'. " + handler.getStderr());
        return false;
      }
      // catch newly added remote
      repository.update();
      return true;
    }
    catch (VcsException e) {
      GithubNotifications.showError(project, "Can't add remote", e);
      return false;
    }
  }
}


text:
import itertools
from pprint import pprint

from email_ab import email_ab

class email_conf(email_ab):

    ready_state = 11

    subject_template = "[{{ep.show.name}}] Video public: {{ep.name}}"
    body_body = """
Your video has been approved and made public:
    {% for url in urls %} {{url}}
    {% endfor %}
    {% if ep.twitter_url %}
It has also been tweeted: {{ ep.twitter_url }}
    {% endif %}
Please help us promote your talk by retweeting it, blogging it, and sharing it with your networks.
    """

    def context(self, ep):
        ctx = super(email_conf, self).context(ep)

        # dig around for URLs that might be relevant
        urls = filter( None,
                [ep.public_url,
                    ep.host_url,
                    ep.archive_url,
                    ep.archive_mp4_url] )

        ctx['urls'] = urls
        ctx['py_name'] = "email_conf.py"

        return ctx

if __name__ == '__main__':
    p=email_conf()
    p.main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  TR-140 StorageService:1.2

  Notice:
    The Broadband Forum is a non-profit corporation organized to create
    guidelines for broadband network system development and deployment.
    This Broadband Forum Document has been approved by members of the
    Forum. This Broadband Forum Document is not binding on the Broadband
    Forum, any of its members, or any developer or service provider.
    This Broadband Forum Document is subject to change, but only with
    approval of members of the Forum.  This Document is copyrighted by
    the Broadband Forum, and all rights are reserved.  Portions of this
    Document may be copyrighted by Broadband Forum members.

    This Broadband Forum Document is provided AS IS, WITH ALL FAULTS.
    ANY PERSON HOLDING A COPYRIGHT IN THIS BROADBAND FORUM DOCUMENT,
    OR ANY PORTION THEREOF, DISCLAIMS TO THE FULLEST EXTENT PERMITTED
    BY LAW ANY REPRESENTATION OR WARRANTY, EXPRESS OR IMPLIED,
    INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY:

    (a) OF ACCURACY, COMPLETENESS, MERCHANTABILITY, FITNESS FOR A
        PARTICULAR PURPOSE, NON-INFRINGEMENT, OR TITLE;
    (b) THAT THE CONTENTS OF THIS BROADBAND FORUM DOCUMENT ARE SUITABLE
        FOR ANY PURPOSE, EVEN IF THAT PURPOSE IS KNOWN TO THE COPYRIGHT
        HOLDER;
    (c) THAT THE IMPLEMENTATION OF THE CONTENTS OF THE DOCUMENT WILL NOT
        INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR
        OTHER RIGHTS.

    By using this Broadband Forum Document, users acknowledge that
    implementation may require licenses to patents.  The Broadband Forum
    encourages but does not require its members to identify such
    patents.  For a list of declarations made by Broadband Forum member
    companies, please see http://www.broadband-forum.org.  No assurance
    is given that licenses to patents necessary to implement this
    Document will be available for license at all or on reasonable and
    non-discriminatory terms.

    ANY PERSON HOLDING A COPYRIGHT IN THIS BROADBAND FORUM DOCUMENT, OR
    ANY PORTION THEREOF, DISCLAIMS TO THE FULLEST EXTENT PERMITTED BY
    LAW (A) ANY LIABILITY (INCLUDING DIRECT, INDIRECT, SPECIAL, OR
    CONSEQUENTIAL DAMAGES UNDER ANY LEGAL THEORY) ARISING FROM OR
    RELATED TO THE USE OF OR RELIANCE UPON THIS DOCUMENT; AND (B) ANY
    OBLIGATION TO UPDATE OR CORRECT THIS DOCUMENT.

    Broadband Forum Documents may be copied, downloaded, stored on a
    server or otherwise re-distributed in their entirety only, and may
    not be modified without the advance written permission of the
    Broadband Forum.

    The text of this notice must be included in all copies of this
    Broadband Forum Document.

  Summary:
  TR-140 StorageService:1.2 Service Object update.

  Editors:
    Sarah Banks, Cisco
    Andrea Colmegna, FASTWEB
    Tim Spets, Motorola Mobility

  Editors Object Addressing Extensions:
    Sarah Banks, Cisco
    Andrea Colmegna, FASTWEB
    Ping Fang, Huawei Technologies
    Nils Magnusson, TeliaSonera
    Anton Okmyanskiy, Cisco
    Staffan Ungsgard, TeliaSonera

  Editors Remote Management of non-TR-069 devices:
    John Blackford, Pace
    Ping Fang, Huawei Technologies
    Tim Spets, Motorola Mobility

  BroadbandHome™ Working Group Chairs:
    Greg Bathrick, PMC-Sierra
    Heather Kirksey, Alcatel-Lucent

  Vice Chair:
    Jason Walls, UNH

  Chief Editor:
    Michael Hanrahan, Huawei Technologies

  Version History:
  * April 2010 : tr-140-1-0-2.xml, corresponds to TR-140 Issue 1, Corrigendum 2
  * April 2010 : tr-140-1-1-0.xml, corresponds to TR-140 Issue 1, Amendment 1
  * July  2011 : tr-140-1-2-0.xml, corresponds to TR-140 Issue 1, Amendment 2

-->

<dm:document xmlns:dm="urn:broadband-forum-org:cwmp:datamodel-1-4"
             xmlns:dmr="urn:broadband-forum-org:cwmp:datamodel-report-0-1"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="urn:broadband-forum-org:cwmp:datamodel-1-4
                                    http://www.broadband-forum.org/cwmp/cwmp-datamodel-1-4.xsd
                                 urn:broadband-forum-org:cwmp:datamodel-report-0-1
                                    http://www.broadband-forum.org/cwmp/cwmp-datamodel-report.xsd"
             spec="urn:broadband-forum-org:tr-140-1-2-0" file="tr-140-1-2-0.xml">

  <description>StorageService:1.2 Service Object</description>

  <!-- import Alias DT definition -->
  <import file="tr-106-1-0-types.xml" spec="urn:broadband-forum-org:tr-106-1-0">
    <dataType name="Alias"/>
  </import>

  <import file="tr-140-1-1.xml" spec="urn:broadband-forum-org:tr-140-1-1">
    <model name="StorageService:1.1"></model>
  </import>

  <model name="StorageService:1.2" base="StorageService:1.1" isService="true">

    <!-- extends non-transient objects with Alias parameter -->
    <object base="StorageService.{i}." access="readOnly" numEntriesParameter="StorageServiceNumberOfEntries" minEntries="0" maxEntries="unbounded">
      <uniqueKey functional="false">
        <parameter ref="Alias"/>
      </uniqueKey>
      <parameter name="Alias" access="readWrite" activeNotify="canDeny" dmr:previousParameter="Enable">
        <description>{{datatype|expand}}</description>
        <syntax>
          <dataType ref="Alias"/>
        </syntax>
      </parameter>
    </object>

    <object base="StorageService.{i}.UserGroup.{i}." access="readWrite" numEntriesParameter="UserGroupNumberOfEntries" enableParameter="Enable" minEntries="0" maxEntries="unbounded">
      <uniqueKey functional="false">
        <parameter ref="Alias"/>
      </uniqueKey>
      <parameter name="Alias" access="readWrite" activeNotify="canDeny" dmr:previousParameter="Enable">
        <description>{{datatype|expand}}</description>
        <syntax>
          <dataType ref="Alias"/>
        </syntax>
      </parameter>
    </object>

    <object base="StorageService.{i}.UserAccount.{i}." access="readWrite" numEntriesParameter="UserAccountNumberOfEntries" enableParameter="Enable" minEntries="0" maxEntries="unbounded">
      <uniqueKey functional="false">
        <parameter ref="Alias"/>
      </uniqueKey>
      <parameter name="Alias" access="readWrite" activeNotify="canDeny" dmr:previousParameter="Enable">
        <description>{{datatype|expand}}</description>
        <syntax>
          <dataType ref="Alias"/>
        </syntax>
      </parameter>
    </object>

    <object base="StorageService.{i}.PhysicalMedium.{i}." access="readOnly" numEntriesParameter="PhysicalMediumNumberOfEntries" minEntries="0" maxEntries="unbounded">
      <uniqueKey functional="false">
        <parameter ref="Alias"/>
      </uniqueKey>
      <parameter name="Alias" access="readWrite" activeNotify="canDeny" dmr:previousParameter="">
        <description>{{datatype|expand}}</description>
        <syntax>
          <dataType ref="Alias"/>
        </syntax>
      </parameter>
    </object>

    <object base="StorageService.{i}.StorageArray.{i}." access="readWrite" numEntriesParameter="StorageArrayNumberOfEntries" enableParameter="Enable" minEntries="0" maxEntries="unbounded">
      <uniqueKey functional="false">
        <parameter ref="Alias"/>
      </uniqueKey>
      <parameter name="Alias" access="readWrite" activeNotify="canDeny" dmr:previousParameter="">
        <description>{{datatype|expand}}</description>
        <syntax>
          <dataType ref="Alias"/>
        </syntax>
      </parameter>
    </object>

    <object base="StorageService.{i}.LogicalVolume.{i}." access="readWrite" numEntriesParameter="LogicalVolumeNumberOfEntries" enableParameter="Enable" minEntries="0" maxEntries="unbounded">
      <uniqueKey functional="false">
        <parameter ref="Alias"/>
      </uniqueKey>
      <parameter name="Alias" access="readWrite" activeNotify="canDeny" dmr:previousParameter="">
        <description>{{datatype|expand}}</description>
        <syntax>
          <dataType ref="Alias"/>
        </syntax>
      </parameter>
    </object>

    <object base="StorageService.{i}.LogicalVolume.{i}.Folder.{i}." access="readWrite" numEntriesParameter="FolderNumberOfEntries" enableParameter="Enable" minEntries="0" maxEntries="unbounded">
      <uniqueKey functional="false">
        <parameter ref="Alias"/>
      </uniqueKey>
      <parameter name="Alias" access="readWrite" activeNotify="canDeny" dmr:previousParameter="">
        <description>{{datatype|expand}}</description>
        <syntax>
          <dataType ref="Alias"/>
        </syntax>
      </parameter>
    </object>

    <object base="StorageService.{i}.LogicalVolume.{i}.Folder.{i}.UserAccess.{i}." access="readWrite" numEntriesParameter="UserAccessNumberOfEntries" enableParameter="Enable" minEntries="0" maxEntries="unbounded">
      <uniqueKey functional="false">
        <parameter ref="Alias"/>
      </uniqueKey>
      <parameter name="Alias" access="readWrite" activeNotify="canDeny" dmr:previousParameter="">
        <description>{{datatype|expand}}</description>
        <syntax>
          <dataType ref="Alias"/>
        </syntax>
      </parameter>
    </object>

    <object base="StorageService.{i}.LogicalVolume.{i}.Folder.{i}.GroupAccess.{i}." access="readWrite" numEntriesParameter="GroupAccessNumberOfEntries" enableParameter="Enable" minEntries="0" maxEntries="unbounded">
      <uniqueKey functional="false">
        <parameter ref="Alias"/>
      </uniqueKey>
      <parameter name="Alias" access="readWrite" activeNotify="canDeny" dmr:previousParameter="">
        <description>{{datatype|expand}}</description>
        <syntax>
          <dataType ref="Alias"/>
        </syntax>
      </parameter>
    </object>

  </model>

</dm:document>


text:
<?php
/************************************************************************/
/* ATutor																*/
/************************************************************************/
/* Copyright (c) 2002-2010                                              */
/* Inclusive Design Institute                                           */
/* http://atutor.ca                                                     */
/* This program is free software. You can redistribute it and/or        */
/* modify it under the terms of the GNU General Public License          */
/* as published by the Free Software Foundation.                        */
/************************************************************************/
// $Id$ $

define('AT_INCLUDE_PATH', '../../../include/');
require(AT_INCLUDE_PATH.'vitals.inc.php');

admin_authenticate(AT_ADMIN_PRIV_ADMIN);

if (isset($_POST['cancel'])) {
	$msg->addFeedback('CANCELLED');
	header('Location: '.$_base_href.'mods/_core/courses/admin/courses.php');
	exit;
}

$_POST['encyclopedia'] == $addslashes($_POST['encyclopedia']);
$_POST['dictionary'] == $addslashes($_POST['dictionary']);
$_POST['thesaurus'] == $addslashes($_POST['thesaurus']);
$_POST['atlas'] == $addslashes($_POST['atlas']);
$_POST['calculator'] == $addslashes($_POST['calculator']);
$_POST['abacus'] == $addslashes($_POST['abacas']);
$_POST['note_taking'] == $addslashes($_POST['note_taking']);

if (isset($_POST['submit'])) {
	foreach ($_POST as $key => $value){
		if($key != "submit"){
		    $sql    = "REPLACE INTO %sconfig VALUES('%s', '%s')";
		    $result = queryDB($sql, array(TABLE_PREFIX, $key, $value));
		};
	}

	$msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
	header('Location:'. $_SERVER[PHP_SELF]);
	exit;

}
require(AT_INCLUDE_PATH.'header.inc.php');

?>

<?php
$savant->display('admin/courses/scaffolds.tmpl.php');
require(AT_INCLUDE_PATH.'footer.inc.php'); ?>


text:
<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Date;
//use Symfony\Component\Form\Extension\Core\Type\Date;

class DiscountType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class, array('label'=>'Enter title'))
            ->add('startDate', DateType::class,
                array(
                    'label'=>"Start Date",
                    'widget' =>'single_text',
                    'html5' => false,
                    'attr' => ['class' => 'js-datepicker'],
//                ));
                ))
            ->add('endDate', DateType::class,
                array(
                    "label"=>"End Date",
                    'widget' =>'single_text',
                    'html5' => false,
                    'attr' => ['class' => 'js-datepicker'],

                ))
            ->add('promotion', FileType::class, array("label" => "Select Image", 'data_class'=>null) )
            //->add('created', 'datetime')
            //->add('updated', 'datetime')
            ->add('submit', SubmitType::class, array('label'=>'Submit'));
    }

    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Discount',
            'attr'=>array('novalidate'=>'novalidate')
        ));
    }

    public function getName(){
        return 'company_discount_form';
    }
}


text:
package com.thoughtworks.go.util.validators;

import com.thoughtworks.go.util.SystemEnvironment;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mock;

import java.io.File;
import java.io.IOException;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

public class JettyWorkDirValidatorTest {

    private JettyWorkDirValidator jettyWorkDirValidator;

    @Mock
    public SystemEnvironment systemEnvironment;

    @Rule
    public final TemporaryFolder temporaryFolder =  new TemporaryFolder();
    private File homeDir;

    @Before
    public void setUp() throws Exception {
        initMocks(this);
        homeDir = temporaryFolder.newFolder();
        jettyWorkDirValidator = new JettyWorkDirValidator(systemEnvironment);

    }

    @Test
    public void shouldSetJettyHomeAndBasePropertyIfItsNotSet() {
        when(systemEnvironment.getPropertyImpl("jetty.home")).thenReturn("");
        when(systemEnvironment.getPropertyImpl("user.dir")).thenReturn("junk");
        Validation val = new Validation();
        jettyWorkDirValidator.validate(val);
        assertThat(val.isSuccessful(), is(true));

        verify(systemEnvironment).getPropertyImpl("user.dir");
        verify(systemEnvironment).setProperty("jetty.home", "junk");
    }

    @Test
    public void shouldSetJettyBaseToValueOfJettyHome() {
        when(systemEnvironment.getPropertyImpl("jetty.home")).thenReturn("foo");
        Validation val = new Validation();
        jettyWorkDirValidator.validate(val);
        assertThat(val.isSuccessful(), is(true));
        verify(systemEnvironment).setProperty("jetty.base", "foo");
    }

    @Test
    public void shouldCreateWorkDirIfItDoesNotExist() {
        when(systemEnvironment.getPropertyImpl("jetty.home")).thenReturn(homeDir.getAbsolutePath());
        Validation val = new Validation();
        jettyWorkDirValidator.validate(val);
        assertThat(val.isSuccessful(), is(true));
        File work = new File(homeDir, "work");
        assertThat(work.exists(), is(true));
    }

    @Test
    public void shouldNotCreateTheJettyHomeDirIfItDoesNotExist() {
        String jettyHome = "home_dir";
        when(systemEnvironment.getPropertyImpl("jetty.home")).thenReturn(jettyHome);
        Validation val = new Validation();
        jettyWorkDirValidator.validate(val);
        assertThat(val.isSuccessful(), is(true));
        assertThat(new File(jettyHome).exists(), is(false));
    }

    @Test
    public void shouldRecreateWorkDirIfItExists() throws IOException {
        File oldWorkDir = new File(homeDir, "work");
        oldWorkDir.mkdir();
        new File(oldWorkDir, "junk.txt").createNewFile();
        when(systemEnvironment.getPropertyImpl("jetty.home")).thenReturn(homeDir.getAbsolutePath());
        Validation val = new Validation();
        jettyWorkDirValidator.validate(val);
        assertThat(val.isSuccessful(), is(true));
        File recreatedWorkDir = new File(homeDir, "work");
        assertThat(recreatedWorkDir.exists(), is(true));
        assertThat(recreatedWorkDir.listFiles().length, is(0));
    }
}