text:
<?php

/**
 * In this file we store all generic functions that we will be using in the Catalog module
 *
 * @author Tim van Wolfswinkel <tim@webleads.nl>
 */
class BackendCatalogModel
{
	const QRY_DATAGRID_BROWSE =
		'SELECT i.id, i.category_id, i.title AS title, i.sequence
		 FROM catalog_products AS i
		 WHERE i.language = ?
		 ORDER BY i.sequence ASC';

	const QRY_DATAGRID_BROWSE_FOR_CATEGORY =
		'SELECT
			i.id, i.category_id, i.title AS title, i.sequence,
			c.title AS category
		 FROM catalog_products AS i
		 INNER JOIN catalog_categories AS c ON i.category_id = c.id
		 WHERE i.category_id = ? AND i.language = ?
		 ORDER BY i.sequence ASC';

	const QRY_DATAGRID_BROWSE_COMMENTS =
		'SELECT
		 	i.id, UNIX_TIMESTAMP(i.created_on) AS created_on, i.author, i.text,
		 	p.id AS product_id, p.title AS product_title, m.url AS product_url
		 FROM catalog_comments AS i
		 INNER JOIN catalog_products AS p
			ON i.product_id = p.id
			AND i.language = p.language
		 INNER JOIN meta AS m ON p.meta_id = m.id
		 WHERE i.status = ? AND i.language = ?
		 GROUP BY i.id';

	const QRY_DATAGRID_BROWSE_ORDERS =
		'SELECT
		 	i.id, i.id AS order_nr, i.status, UNIX_TIMESTAMP(i.date) AS ordered_on,
			i.email, i.fname AS FirstName, i.lname AS LastName, i.total AS TotalPrice
		 FROM catalog_orders AS i
		 WHERE i.status = ?
		 GROUP BY i.id';

	const QRY_DATAGRID_BROWSE_PRODUCTS_ORDER =
		'SELECT c.title, c.price, o.*, m.url
		 FROM `catalog_orders_values` AS o
		 INNER JOIN `catalog_products` AS c ON o.product_id = c.id
		 INNER JOIN meta AS m ON c.meta_id = m.id
		 WHERE o.order_id = ?';

	const QRY_DATAGRID_BROWSE_CATEGORIES =
		'SELECT c.id, c.title, COUNT(i.id) AS num_products, c.sequence
		 FROM catalog_categories AS c
		 LEFT OUTER JOIN catalog_products AS i
			ON c.id = i.category_id
			AND i.language = c.language
		 WHERE c.language = ?
		 GROUP BY c.id
		 ORDER BY c.sequence ASC';

	const QRY_DATAGRID_BROWSE_SPECIFICATIONS =
		'SELECT c.id, c.title AS specification, c.sequence
		 FROM catalog_specifications AS c
		 WHERE c.language = ?
		 GROUP BY c.id
		 ORDER BY c.sequence ASC';

	const QRY_DATAGRID_BROWSE_IMAGES =
		'SELECT i.id, i.product_id, i.filename, i.title, i.sequence
		 FROM catalog_images AS i
		 WHERE i.product_id = ?
		 GROUP BY i.id';

	const QRY_DATAGRID_BROWSE_FILES =
		'SELECT i.id, i.product_id, i.filename, i.title, i.sequence
		 FROM catalog_files AS i
		 WHERE i.product_id = ?
		 GROUP BY i.id';

	const QRY_DATAGRID_BROWSE_VIDEOS =
		'SELECT i.id, i.product_id, i.embedded_url, i.title, i.sequence
		 FROM catalog_videos AS i
		 WHERE i.product_id = ?
		 GROUP BY i.id';

	/**
	 * Delete a certain item
	 *
	 * @param int $id
	 */
	public static function delete($id)
	{
		BackendModel::getContainer()->get('database')->delete('catalog_products', 'id = ?', (int) $id);
		BackendModel::getContainer()->get('database')->delete('catalog_specifications_values', 'product_id = ?', (int) $id);
	}

	/**
	 * Delete a specific category
	 *
	 * @param int $id
	 */
	public static function deleteCategory($id)
	{
		$db = BackendModel::getContainer()->get('database');
		$item = self::getCategory($id);

		if(!empty($item))
		{
			$db->delete('meta', 'id = ?', array($item['meta_id']));
			$db->delete('catalog_categories', 'id = ?', array((int) $id));
			$db->update('catalog_products', array('category_id' => null), 'category_id = ?', array((int) $id));
		}
	}

	/**
	 * Deletes one or more comments
	 *
	 * @param array $ids The id(s) of the items(s) to delete.
	 */
	public static function deleteComments($ids)
	{
		// make sure $ids is an array
		$ids = (array) $ids;

		// loop and cast to integers
		foreach($ids as &$id) $id = (int) $id;

		// create an array with an equal amount of questionmarks as ids provided
		$idPlaceHolders = array_fill(0, count($ids), '?');

		// get db
		$db = BackendModel::getContainer()->get('database');

		// get ids
		$itemIds = (array) $db->getColumn(
			'SELECT i.product_id
			 FROM catalog_comments AS i
			 WHERE i.id IN (' . implode(', ', $idPlaceHolders) . ')',
			$ids
		);

		// update record
		$db->delete('catalog_comments', 'id IN (' . implode(', ', $idPlaceHolders) . ')', $ids);

		// recalculate the comment count
		if(!empty($itemIds)) self::reCalculateCommentCount($itemIds);

		// invalidate the cache for catalog
		BackendModel::invalidateFrontendCache('catalog', BL::getWorkingLanguage());
	}

	/**
	 * Deletes one or more orders
	 *
	 * @param array $ids The id(s) of the items(s) to delete.
	 */
	public static function deleteOrders($ids)
	{
		// make sure $ids is an array
		$ids = (array) $ids;

		// loop and cast to integers
		foreach($ids as &$id) $id = (int) $id;

		// create an array with an equal amount of questionmarks as ids provided
		$idPlaceHolders = array_fill(0, count($ids), '?');

		// get db
		$db = BackendModel::getContainer()->get('database');

		// get ids
		$itemIds = (array) $db->getColumn(
			'SELECT i.id
			 FROM catalog_orders AS i
			 WHERE i.id IN (' . implode(', ', $idPlaceHolders) . ')',
			$ids
		);

		// update record
		$db->delete('catalog_orders', 'id IN (' . implode(', ', $idPlaceHolders) . ')', $ids);

		// invalidate the cache for catalog
		BackendModel::invalidateFrontendCache('catalog', BL::getWorkingLanguage());
	}

	/**
	 * Delete a specific specification
	 *
	 * @param int $id
	 */
	public static function deleteSpecification($id)
	{
		$db = BackendModel::getContainer()->get('database');
		$item = self::getSpecification($id);

		if(!empty($item))
		{
			$db->delete('meta', 'id = ?', array($item['meta_id']));
			$db->delete('catalog_specifications', 'id = ?', array((int) $id));
			$db->delete('catalog_specifications_values', 'specification_id = ?', array((int) $id));
		}
	}

	/**
	 * Delete all spam
	 */
	public static function deleteSpamComments()
	{
		$db = BackendModel::getContainer()->get('database');

		// get ids
		$itemIds = (array) $db->getColumn(
			'SELECT i.product_id
			 FROM catalog_comments AS i
			 WHERE status = ? AND i.language = ?',
			array('spam', BL::getWorkingLanguage())
		);

		// update record
		$db->delete('catalog_comments', 'status = ? AND language = ?', array('spam', BL::getWorkingLanguage()));

		// recalculate the comment count
		if(!empty($itemIds)) self::reCalculateCommentCount($itemIds);

		// invalidate the cache for blog
		BackendModel::invalidateFrontendCache('catalog', BL::getWorkingLanguage());
	}

	/**
	 * Delete all spam
	 */
	public static function deleteCompletedOrders()
	{
		$db = BackendModel::getContainer()->get('database');

		// get ids
		$itemIds = (array) $db->getColumn(
			'SELECT i.id
			 FROM catalog_orders AS i
			 WHERE status = ?',
			array('completed')
		);

		// update record
		$db->delete('catalog_orders', 'status = ?', array('completed'));

		// invalidate the cache for catalog
		BackendModel::invalidateFrontendCache('catalog', BL::getWorkingLanguage());
	}
	/**
	 * Delete related product
	 *
	 * @param int The product id
	 * @param int[optional] The related product id
	 */
	public static function deleteRelatedProduct($productId, $relatedProductId = null)
	{
		// delete specific related product
		if(isset($relatedProductId))
		{
			BackendModel::getContainer()->get('database')->delete('catalog_related_products', 'product_id = ? AND related_product_id = ?', array((int) $productId, (int) $relatedProductId));
		}

		// delete all related products from product
		else
		{
			BackendModel::getContainer()->get('database')->delete('catalog_related_products', 'product_id = ?', array((int) $productId));
		}
	}

	/**
	 * @param array $ids
	 */
	public static function deleteImage(array $ids)
	{
		if(empty($ids)) return;

		foreach($ids as $id)
		{
			$item = self::getImage($id);
			$product = self::get($item['product_id']);

			// delete image reference from db
			BackendModel::getContainer()->get('database')->delete('catalog_images', 'id = ?', array($id));

			// delete image from disk
			$basePath = FRONTEND_FILES_PATH . '/catalog/' . $item['product_id'];
			SpoonFile::delete($basePath . '/source/' . $item['filename']);
			SpoonFile::delete($basePath . '/64x64/' . $item['filename']);
			SpoonFile::delete($basePath . '/128x128/' . $item['filename']);
			SpoonFile::delete($basePath . '/' . BackendModel::getModuleSetting('catalog', 'width1') . 'x' . BackendModel::getModuleSetting('catalog', 'height1') . '/' . $item['filename']);
			SpoonFile::delete($basePath . '/' . BackendModel::getModuleSetting('catalog', 'width2') . 'x' . BackendModel::getModuleSetting('catalog', 'height2') . '/' . $item['filename']);
			SpoonFile::delete($basePath . '/' . BackendModel::getModuleSetting('catalog', 'width3') . 'x' . BackendModel::getModuleSetting('catalog', 'height3') . '/' . $item['filename']);
		}

		BackendModel::invalidateFrontendCache('slideshowCache');
	}

	/**
	 * @param array $ids
	 */
	public static function deleteFile(array $ids)
	{
		if(empty($ids)) return;

		foreach($ids as $id)
		{
			$item = self::getFile($id);
			$product = self::get($item['product_id']);

			// delete file reference from db
			BackendModel::getContainer()->get('database')->delete('catalog_files', 'id = ?', array($id));

			// delete file from disk
			$basePath = FRONTEND_FILES_PATH . '/catalog/' . $item['product_id'];
			SpoonFile::delete($basePath . '/source/' . $item['filename']);
		}
	}

	/**
	 * @param array $ids
	 */
	public static function deleteVideo(array $ids)
	{
		if(empty($ids)) return;

		foreach($ids as $id)
		{
			$item = self::getVideo($id);
			$product = self::get($item['product_id']);

			// delete video reference from db
			BackendModel::getContainer()->get('database')->delete('catalog_videos', 'id = ?', array($id));
		}
	}

	/**
	 * Checks if a certain item exists
	 *
	 * @param int $id
	 * @return bool
	 */
	public static function exists($id)
	{
		return (bool) BackendModel::getContainer()->get('database')->getVar(
			'SELECT 1
			 FROM catalog_products AS i
			 WHERE i.id = ?
			 LIMIT 1',
			array((int) $id)
		);
	}

	/**
	 * Does the category exist?
	 *
	 * @param int $id
	 * @return bool
	 */
	public static function existsCategory($id)
	{
		return (bool) BackendModel::getContainer()->get('database')->getVar(
			'SELECT 1
			 FROM catalog_categories AS i
			 WHERE i.id = ? AND i.language = ?
			 LIMIT 1',
			array((int) $id, BL::getWorkingLanguage()));
	}

	/**
	 * Checks if a comment exists
	 *
	 * @param int $id The id of the item to check for existence.
	 * @return int
	 */
	public static function existsComment($id)
	{
		return (bool) BackendModel::getContainer()->get('database')->getVar(
			'SELECT 1
			 FROM catalog_comments AS i
			 WHERE i.id = ? AND i.language = ?
			 LIMIT 1',
			array((int) $id, BL::getWorkingLanguage())
		);
	}

	/**
	 * Checks if a order exists
	 *
	 * @param int $id The id of the item to check for existence.
	 * @return int
	 */
	public static function existsOrder($id)
	{
		return (bool) BackendModel::getContainer()->get('database')->getVar(
			'SELECT 1
			 FROM catalog_orders AS i
			 WHERE i.id = ?
			 LIMIT 1',
			array((int) $id)
		);
	}

	/**
	 * Checks if specification exists
	 *
	 * @param int $id Id of a specification.
	 * @param int[optional] $productId Id of a product.
	 * @return bool
	 */
	public static function existsSpecification($id)
	{
		return (bool) BackendModel::getContainer()->get('database')->getVar(
			'SELECT 1
			 FROM catalog_specifications AS i
			 WHERE i.id = ? AND i.language = ?
			 LIMIT 1',
			array((int) $id, BL::getWorkingLanguage()));
	}

	/**
	 * Checks if value of specification exists
	 *
	 * @param int $id Id of a specification.
	 * @param int[optional] $productId Id of a product.
	 * @return bool
	 */
	public static function existsSpecificationValue($productId, $specificationId)
	{
		return (bool) BackendModel::getContainer()->get('database')->getVar(
			'SELECT 1
			 FROM catalog_specifications_values AS i
			 WHERE i.product_id = ? AND i.specification_id = ?
			 LIMIT 1',
			array((int) $productId, (int) $specificationId));
	}

	/**
	 * Checks if image exists
	 *
	 * @param int $id
	 * @return bool
	 */
	public static function existsImage($id)
	{
		return (bool) BackendModel::getContainer()->get('database')->getVar(
			'SELECT 1
			 FROM catalog_images AS a
			 WHERE a.id = ?',
			array((int) $id)
		);
	}

	/**
	 * Checks if file exists
	 *
	 * @param int $id
	 * @return bool
	 */
	public static function existsFile($id)
	{
		return (bool) BackendModel::getContainer()->get('database')->getVar(
			'SELECT 1
			 FROM catalog_files AS a
			 WHERE a.id = ?',
			array((int) $id)
		);
	}

	/**
	 * Checks if video exists
	 *
	 * @param int $id
	 * @return bool
	 */
	public static function existsVideo($id)
	{
		return (bool) BackendModel::getContainer()->get('database')->getVar(
			'SELECT 1
			 FROM catalog_videos AS a
			 WHERE a.id = ?',
			array((int) $id)
		);
	}

	/**
	 * Fetches a certain item
	 *
	 * @param int $id
	 * @return array
	 */
	public static function get($id)
	{
		return (array) BackendModel::getContainer()->get('database')->getRecord(
			'SELECT i.*
			 FROM catalog_products AS i
			 WHERE i.id = ?',
			array((int) $id)
		);
	}

	/**
	 * Fetches a all items
	 *
	 * @param int $id
	 * @return array
	 */
	public static function getAll()
	{
		$db = BackendModel::getContainer()->get('database');

		return (array) $db->getPairs(
		'SELECT i.id, i.title
			 FROM catalog_products AS i
			 WHERE i.language = ?
			 GROUP BY i.id',
		array(BL::getWorkingLanguage()));
	}

	/**
	 * Get all the categories
	 *
	 * @param bool[optional] $includeCount
	 * @return array
	 */
	public static function getCategories($includeCount = false)
	{
		$db = BackendModel::getContainer()->get('database');

		if($includeCount)
		{
			$allCategories = (array) $db->getRecords(
				'SELECT i.id, i.parent_id, CONCAT(i.title, " (", COUNT(p.category_id) ,")") AS title
				 FROM catalog_categories AS i
				 LEFT OUTER JOIN catalog_products AS p ON i.id = p.category_id AND i.language = p.language
				 WHERE i.language = ?
				 GROUP BY i.id
				 ORDER BY i.sequence',
				 array(BL::getWorkingLanguage()));

			$tree = array();

			$categoryTree = self::buildTree($tree, $allCategories);
			$categoryTree = array('0' => ucfirst(BL::lbl('None'))) + $categoryTree;

			return $categoryTree;
		}
	}

	/**
	 * Build the category tree
	 *
	 * @param $tree
	 * @param array $categories
	 * @param int $parentId
	 * @param int $level
	 * @return array
	 */
	public static function buildTree(array &$tree, array $categories, $parentId = 0, $level = 0)
	{
		foreach($categories as $category)
		{
			if ($category['parent_id'] == $parentId)
			{
				$tree[$category['id']] = str_repeat('-', $level). $category['title'];

				$level++;
				$children = self::buildTree($tree, $categories, $category['id'], $level);
				$level--;
			}
		}
		return $tree;
	}

	/**
	 * Get all data for a given id
	 *
	 * @param int $id The Id of the comment to fetch?
	 * @return array
	 */
	public static function getComment($id)
	{
		return (array) BackendModel::getContainer()->get('database')->getRecord(
			'SELECT i.*, UNIX_TIMESTAMP(i.created_on) AS created_on,
			 p.id AS product_id, p.title AS product_title, m.url AS product_url
			 FROM catalog_comments AS i
			 INNER JOIN catalog_products AS p ON i.product_id = p.id AND i.language = p.language
			 INNER JOIN meta AS m ON p.meta_id = m.id
			 WHERE i.id = ?
			 LIMIT 1',
			array((int) $id)
		);
	}

	/**
	 * Get all data for a given id
	 *
	 * @param int $id The Id of the order to fetch?
	 * @return array
	 */
	public static function getOrder($id)
	{
		return (array) BackendModel::getContainer()->get('database')->getRecord(
			'SELECT i.*, UNIX_TIMESTAMP(i.date) AS ordered_on,
			 p.amount AS amount_of_product, c.title AS product_title
			 FROM catalog_orders AS i
			 INNER JOIN catalog_orders_values AS p ON i.id = p.order_id
			 INNER JOIN catalog_products AS c ON p.product_id = c.id
			 WHERE i.id = ?
			 LIMIT 1',
			array((int) $id)
		);
	}

	/**
	 * Get multiple comments at once
	 *
	 * @param array $ids The id(s) of the comment(s).
	 * @return array
	 */
	public static function getComments(array $ids)
	{
		return (array) BackendModel::getContainer()->get('database')->getRecords(
			'SELECT *
			 FROM catalog_comments AS i
			 WHERE i.id IN (' . implode(', ', array_fill(0, count($ids), '?')) . ')',
			$ids
		);
	}

	/**
	 * Get a count per comment
	 *
	 * @return array
	 */
	public static function getCommentStatusCount()
	{
		return (array) BackendModel::getContainer()->get('database')->getPairs(
			'SELECT i.status, COUNT(i.id)
			 FROM catalog_comments AS i
			 WHERE i.language = ?
			 GROUP BY i.status',
			array(BL::getWorkingLanguage())
		);
	}

	/**
	 * Get all products grouped by categories
	 *
	 * @return array
	 */
	public static function getAllProductsGroupedByCategories()
	{
		$db = BackendModel::getContainer()->get('database');

		$allProducts = (array) $db->getRecords(
			'SELECT p.id, p.title, pc.id AS category_id, pc.title AS category_title
			 FROM catalog_products p
			 INNER JOIN catalog_categories pc ON p.category_id = pc.id
			 WHERE p.language = ?',
			 array(BL::getWorkingLanguage()));

		$productsGroupedByCategory = array();

		foreach($allProducts as $pid => $product)
		{
			$productsGroupedByCategory[$product['category_title']][$product['id']] = $product['title'];
		}

		return $productsGroupedByCategory;
	}

	/**
	 * Get related products of an item
	 *
	 * @param int $id The product id
	 * @return array
	 */
	public static function getRelatedProducts($id)
	{
		$db = BackendModel::getContainer()->get('database');

		$relatedProducts = (array) $db->getPairs(
			'SELECT r.related_product_id AS keyId, r.related_product_id AS valueId
			 FROM catalog_related_products r
			 WHERE r.product_id = ?',
			 array((int) $id));

		// build new keys (starting from zero)
		$i = 0;

		foreach($relatedProducts as $key => $value)
		{
			if(isset($relatedProducts[$key]))
			{
				$relatedProducts[$i] = $relatedProducts[$key];
				unset($relatedProducts[$key]);
			}
			$i++;
		}

		return $relatedProducts;
	}

	/**
	 * Get specification value of an item
	 *
	 * @param int $specificationId The specification id
	 * @param int $productId The product id
	 * @return string
	 */
	public static function getSpecificationValue($specificationId, $productId)
	{
		$db = BackendModel::getContainer()->get('database');

		$value = (array) $db->getRecord(
			'SELECT i.value
			 FROM catalog_specifications_values i
			 WHERE i.specification_id = ? AND i.product_id = ?',
			 array((int) $specificationId, (int) $productId));

		return $value;
	}

	/**
	 * Fetch an image
	 *
	 * @param int $id
	 * @return array
	 */
	public static function getImage($id)
	{
		return (array) BackendModel::getContainer()->get('database')->getRecord(
			'SELECT i.*
			 FROM catalog_images AS i
			 WHERE i.id = ?',
			 array((int) $id));
	}

	/**
	 * Fetch an file
	 *
	 * @param int $id
	 * @return array
	 */
	public static function getFile($id)
	{
		return (array) BackendModel::getContainer()->get('database')->getRecord(
			'SELECT i.*
			 FROM catalog_files AS i
			 WHERE i.id = ?',
			 array((int) $id));
	}

	/**
	 * Fetch an video
	 *
	 * @param int $id
	 * @return array
	 */
	public static function getVideo($id)
	{
		return (array) BackendModel::getContainer()->get('database')->getRecord(
			'SELECT i.*
			 FROM catalog_videos AS i
			 WHERE i.id = ?',
			 array((int) $id));
	}

	/**
	 * Check if category has children
	 *
	 * @param int $id
	 * @return bool
	 */
	public static function categoryHasChildren($id)
	{
		// gives children from category
		$item = (array) BackendModel::getContainer()->get('database')->getRecord(
			'SELECT c1.id as childID, c1.title ChildName, c2.title as ParentName
			 FROM catalog_categories AS c1
			 LEFT OUTER JOIN catalog_categories AS c2 ON c1.id = c2.parent_id
			 WHERE c1.language = ? AND c1.parent_id = ?',
			array(BL::getWorkingLanguage(), $id)
		);

		if($item == null)
		{
			return false;
		} else
		{
			return true;
		}
	}

	/**
	 * Fetch a category
	 *
	 * @param int $id
	 * @return array
	 */
	public static function getCategory($id)
	{
		return (array) BackendModel::getContainer()->get('database')->getRecord(
			'SELECT i.*
			 FROM catalog_categories AS i
			 WHERE i.id = ? AND i.language = ?',
			 array((int) $id, BL::getWorkingLanguage()));
	}

	/**
	 * Fetch a specification
	 *
	 * @param int $id
	 * @return array
	 */
	public static function getSpecification($id)
	{
		return (array) BackendModel::getContainer()->get('database')->getRecord(
			'SELECT i.*
			 FROM catalog_specifications AS i
			 WHERE i.id = ? AND i.language = ?',
			 array((int) $id, BL::getWorkingLanguage()));
	}

	/**
	 * Get the maximum sequence for a category
	 *
	 * @return int
	 */
	public static function getMaximumCategorySequence()
	{
		return (int) BackendModel::getContainer()->get('database')->getVar(
			'SELECT MAX(i.sequence)
			 FROM catalog_categories AS i
			 WHERE i.language = ?',
			 array(BL::getWorkingLanguage()));
	}

	/**
	 * Get the maximum sequence for a specification
	 *
	 * @return int
	 */
	public static function getMaximumSpecificationSequence()
	{
		return (int) BackendModel::getContainer()->get('database')->getVar(
			'SELECT MAX(i.sequence)
			 FROM catalog_specifications AS i
			 WHERE i.language = ?',
			 array(BL::getWorkingLanguage()));
	}

	/**
	 * Get the max sequence id for an image
	 *
	 * @param int $id The product id.
	 * @return int
	 */
	public static function getMaximumImagesSequence($id)
	{
		return (int) BackendModel::getContainer()->get('database')->getVar(
			'SELECT MAX(i.sequence)
			 FROM catalog_images AS i
			 WHERE i.product_id = ?',
			 array((int) $id));
	}

	/**
	 * Get the max sequence id for an file
	 *
	 * @param int $id The product id.
	 * @return int
	 */
	public static function getMaximumFilesSequence($id)
	{
		return (int) BackendModel::getContainer()->get('database')->getVar(
			'SELECT MAX(i.sequence)
			 FROM catalog_files AS i
			 WHERE i.product_id = ?',
			 array((int) $id));
	}

	/**
	 * Get the max sequence id for an videos
	 *
	 * @param int $id The product id.
	 * @return int
	 */
	public static function getMaximumVideosSequence($id)
	{
		return (int) BackendModel::getContainer()->get('database')->getVar(
			'SELECT MAX(i.sequence)
			 FROM catalog_videos AS i
			 WHERE i.product_id = ?',
			 array((int) $id));
	}

	/**
	 * Get the maximum sequence
	 *
	 * @return int
	 */
	public static function getMaximumSequence()
	{
		return (int) BackendModel::getContainer()->get('database')->getVar(
			'SELECT MAX(i.sequence)
			 FROM catalog_products AS i'
		);
	}

	/**
	 * Get all the specifications
	 *
	 * @return array
	 */
	public static function getSpecifications()
	{
		$db = BackendModel::getContainer()->get('database');

		$items = (array) $db->getRecords(
			'SELECT i.id, i.title, i.type
			 FROM catalog_specifications AS i
			 WHERE i.language = ?
			 GROUP BY i.id
			 ORDER BY i.sequence',
			 array(BL::getWorkingLanguage()));

		return $items;
	}

	/**
	 * Retrieve the unique URL for an item
	 *
	 * @param string $url
	 * @param int[optional] $id	The id of the item to ignore.
	 * @return string
	 */
	public static function getURL($url, $id = null)
	{
		$url = SpoonFilter::urlise((string) $url);
		$db = BackendModel::getContainer()->get('database');

		// new item
		if($id === null)
		{
			// already exists
			if((bool) $db->getVar(
				'SELECT 1
				 FROM catalog_products AS i
				 INNER JOIN meta AS m ON i.meta_id = m.id
				 WHERE i.language = ? AND m.url = ?
				 LIMIT 1',
				array(BL::getWorkingLanguage(), $url)))
			{
				$url = BackendModel::addNumber($url);
				return self::getURL($url);
			}
		}

		// current item should be excluded
		else
		{
			// already exists
			if((bool) $db->getVar(
				'SELECT 1
				 FROM catalog_products AS i
				 INNER JOIN meta AS m ON i.meta_id = m.id
				 WHERE i.language = ? AND m.url = ? AND i.id != ?
				 LIMIT 1',
				array(BL::getWorkingLanguage(), $url, $id)))
			{
				$url = BackendModel::addNumber($url);
				return self::getURL($url, $id);
			}
		}

		return $url;
	}

	/**
	 * Retrieve the unique URL for a specification
	 *
	 * @param string $url
	 * @param int[optional] $id The id of the specification to ignore.
	 * @return string
	 */
	public static function getURLForSpecification($url, $id = null)
	{
		$url = SpoonFilter::urlise((string) $url);
		$db = BackendModel::getContainer()->get('database');

		// new specification
		if($id === null)
		{
			if((bool) $db->getVar(
				'SELECT 1
				 FROM catalog_specifications AS i
				 INNER JOIN meta AS m ON i.meta_id = m.id
				 WHERE i.language = ? AND m.url = ?
				 LIMIT 1',
				array(BL::getWorkingLanguage(), $url)))
			{
				$url = BackendModel::addNumber($url);
				return self::getURLForSpecification($url);
			}
		}

		// current specification should be excluded
		else
		{
			if((bool) $db->getVar(
				'SELECT 1
				 FROM catalog_specifications AS i
				 INNER JOIN meta AS m ON i.meta_id = m.id
				 WHERE i.language = ? AND m.url = ? AND i.id != ?
				 LIMIT 1',
				array(BL::getWorkingLanguage(), $url, $id)))
			{
				$url = BackendModel::addNumber($url);
				return self::getURLForSpecification($url, $id);
			}
		}

		return $url;
	}

	/**
	 * Retrieve the unique URL for a category
	 *
	 * @param string $url
	 * @param int[optional] $id The id of the category to ignore.
	 * @return string
	 */
	public static function getURLForCategory($url, $id = null)
	{
		$url = SpoonFilter::urlise((string) $url);
		$db = BackendModel::getContainer()->get('database');

		// new category
		if($id === null)
		{
			if((bool) $db->getVar(
				'SELECT 1
				 FROM catalog_categories AS i
				 INNER JOIN meta AS m ON i.meta_id = m.id
				 WHERE i.language = ? AND m.url = ?
				 LIMIT 1',
				array(BL::getWorkingLanguage(), $url)))
			{
				$url = BackendModel::addNumber($url);
				return self::getURLForCategory($url);
			}
		}

		// current category should be excluded
		else
		{
			if((bool) $db->getVar(
				'SELECT 1
				 FROM catalog_categories AS i
				 INNER JOIN meta AS m ON i.meta_id = m.id
				 WHERE i.language = ? AND m.url = ? AND i.id != ?
				 LIMIT 1',
				array(BL::getWorkingLanguage(), $url, $id)))
			{
				$url = BackendModel::addNumber($url);
				return self::getURLForCategory($url, $id);
			}
		}

		return $url;
	}

	/**
	 * Insert an item in the database
	 *
	 * @param array $item
	 * @return int
	 */
	public static function insert(array $item)
	{
		$item['created_on'] = BackendModel::getUTCDate();

		return (int) BackendModel::getContainer()->get('database')->insert('catalog_products', $item);
	}

	/**
	 * Insert a category in the database
	 *
	 * @param array $item
	 * @return int
	 */
	public static function insertCategory(array $item)
	{
		$item['created_on'] = BackendModel::getUTCDate();
		return BackendModel::getContainer()->get('database')->insert('catalog_categories', $item);
	}

	/**
	 * Insert a specification in the database
	 *
	 * @param array $item
	 * @return int
	 */
	public static function insertSpecification(array $item)
	{
		return BackendModel::getContainer()->get('database')->insert('catalog_specifications', $item);
	}

	/**
	 * Insert a specification value in the database
	 *
	 * @param array $item
	 * @return int
	 */
	public static function insertSpecificationValue(array $item)
	{
		return BackendModel::getContainer()->get('database')->insert('catalog_specifications_values', $item);
	}

	/**
	 * Insert a related product in the database
	 *
	 * @param string $item
	 * @return int
	 */
	private static function insertRelatedProduct($item)
	{
		return (int) BackendModel::getContainer()->get('database')->insert('catalog_related_products', $item);
	}

	/**
	 * Insert a image in the database
	 *
	 * @param string $item
	 * @return int
	 */
	private static function insertImage($item)
	{
		return (int) BackendModel::getContainer()->get('database')->insert('catalog_images', $item);
	}

	/**
	 * Insert a file in the database
	 *
	 * @param string $item
	 * @return int
	 */
	private static function insertFile($item)
	{
		return (int) BackendModel::getContainer()->get('database')->insert('catalog_files', $item);
	}

	/**
	 * Insert a video in the database
	 *
	 * @param string $item
	 * @return int
	 */
	private static function insertVideo($item)
	{
		return (int) BackendModel::getContainer()->get('database')->insert('catalog_videos', $item);
	}

	/**
	 * Is this category allowed to be deleted?
	 *
	 * @return	bool
	 * @param	int $id		The category id to check.
	 */
	public static function isCategoryAllowedToBeDeleted($id)
	{
		return ! (bool) BackendModel::getContainer()->get('database')->getVar('SELECT COUNT(i.id)
														FROM catalog_products AS i
														INNER JOIN catalog_categories AS c
														WHERE i.category_id = ? OR c.parent_id = ?
														',
														array((int) $id, (int) $id));
	}

	/**
	 * Recalculate the commentcount
	 *
	 * @param array $ids The id(s) of the product wherefore the commentcount should be recalculated.
	 * @return bool
	 */
	public static function reCalculateCommentCount(array $ids)
	{
		// validate
		if(empty($ids)) return false;

		// make unique ids
		$ids = array_unique($ids);

		// get db
		$db = BackendModel::getContainer()->get('database');

		// get counts
		$commentCounts = (array) $db->getPairs(
			'SELECT i.product_id, COUNT(i.id) AS comment_count
			 FROM catalog_comments AS i
			 INNER JOIN catalog_products AS p ON i.product_id = p.id AND i.language = p.language
			 WHERE i.status = ? AND i.product_id IN (' . implode(',', $ids) . ') AND i.language = ?
			 GROUP BY i.product_id',
			array('published', BL::getWorkingLanguage())
		);

		foreach($ids as $id)
		{
			// get count
			$count = (isset($commentCounts[$id])) ? (int) $commentCounts[$id] : 0;

			// update
			$db->update('catalog_products', array('num_comments' => $count), 'id = ? AND language = ?', array($id, BL::getWorkingLanguage()));
		}

		return true;
	}

	/**
	 * Save or update related product (values)
	 *
	 * @param int $productId The id of the item where to assign the related projects.
	 * @param array $relatedProducts The related products for the item.
	 * @param array[optional] $oRelatedProducts The related products already existing for the item. If not provided a new record will be created.
	 *
	 * @return int
	 */
	public static function saveRelatedProducts($productId, $relatedProducts, $oRelatedProducts = null)
	{
		$item['product_id'] = $productId;

		// existing related products
		if(isset($oRelatedProducts))
		{
			// insert new records
			$newRelatedProducts = array_diff($relatedProducts, $oRelatedProducts);
			foreach($newRelatedProducts AS $key => $newRelatedProduct)
			{
				$item['related_product_id'] = $newRelatedProduct;
				self::insertRelatedProduct($item);
			}

			// delete old records
			$oldRelatedProducts = array_diff($oRelatedProducts, $relatedProducts);
			foreach($oldRelatedProducts AS $key => $oldRelatedProduct)
			{
				$item['related_product_id'] = $oldRelatedProduct;
				self::deleteRelatedProduct($item['product_id'], $item['related_product_id']);
			}
		}

		// new related products
		else
		{
			// insert new records
			foreach($relatedProducts AS $key => $relatedProduct)
			{
				$item['related_product_id'] = $relatedProduct;
				self::insertRelatedProduct($item);
			}
		}
	}

	/**
	 * Save or update a image
	 *
	 * @param array $item
	 * @return int
	 */
	public static function saveImage(array $item)
	{
		// update image
		if(isset($item['id']) && self::existsImage($item['id']))
		{
			self::updateImage($item);
		}

		// insert image
		else
		{
			$item['id'] = self::insertImage($item);
		}

		BackendModel::invalidateFrontendCache('productsCache');
		return (int) $item['id'];
	}

	/**
	 * Save or update a file
	 *
	 * @param array $item
	 * @return int
	 */
	public static function saveFile(array $item)
	{
		// update file
		if(isset($item['id']) && self::existsFile($item['id']))
		{
			self::updateFile($item);
		}

		// insert file
		else
		{
			$item['id'] = self::insertFile($item);
		}

		BackendModel::invalidateFrontendCache('productsCache');
		return (int) $item['id'];
	}

	/**
	 * Save or update a video
	 *
	 * @param array $item
	 * @return int
	 */
	public static function saveVideo(array $item)
	{
		// update video
		if(isset($item['id']) && self::existsVideo($item['id']))
		{
			self::updateVideo($item);
		}

		// insert video
		else
		{
			$item['id'] = self::insertVideo($item);
		}

		BackendModel::invalidateFrontendCache('productsCache');
		return (int) $item['id'];
	}

	/**
	 * Updates an item
	 *
	 * @param array $item
	 */
	public static function update(array $item)
	{
		$item['edited_on'] = BackendModel::getUTCDate();

		BackendModel::getContainer()->get('database')->update('catalog_products', $item, 'id = ?', (int) $item['id']);
	}

	/**
	 * Update a certain category
	 *
	 * @param array $item
	 */
	public static function updateCategory(array $item)
	{
		$item['edited_on'] = BackendModel::getUTCDate();
		BackendModel::getContainer()->get('database')->update('catalog_categories', $item, 'id = ?', array($item['id']));
	}

	/**
	 * Update a certain comment
	 *
	 * @param array $item The new data.
	 * @return int
	 */
	public static function updateComment(array $item)
	{
		return BackendModel::getContainer()->get('database')->update('catalog_comments', $item, 'id = ?', array((int) $item['id']));
	}

	/**
	 * Update a certain order
	 *
	 * @param array $item The new data.
	 * @return int
	 */
	public static function updateOrder(array $item)
	{
		return BackendModel::getContainer()->get('database')->update('catalog_orders', $item, 'id = ?', array((int) $item['id']));
	}

	/**
	 * Updates one or more order' status
	 *
	 * @param array $ids The id(s) of the order(s) to change the status for.
	 * @param string $status The new status.
	 */
	public static function updateOrderStatuses($ids, $status)
	{
		// make sure $ids is an array
		$ids = (array) $ids;

		// loop and cast to integers
		foreach($ids as &$id) $id = (int) $id;

		// create an array with an equal amount of questionmarks as ids provided
		$idPlaceHolders = array_fill(0, count($ids), '?');

		// get the items and their languages
		$items = (array) BackendModel::getContainer()->get('database')->getPairs(
			'SELECT i.id, i.status
			 FROM catalog_orders AS i
			 WHERE i.id IN (' . implode(', ', $idPlaceHolders) . ')',
			$ids, 'id'
		);

		// only proceed if there are items
		if(!empty($items))
		{
			// get the ids
			$itemIds = array_keys($items);

			// update records
			BackendModel::getContainer()->get('database')->execute(
				'UPDATE catalog_orders
				 SET status = ?
				 WHERE id IN (' . implode(', ', $idPlaceHolders) . ')',
				array_merge(array((string) $status), $ids)
			);
		}
	}

	/**
	 * Updates one or more comments' status
	 *
	 * @param array $ids The id(s) of the comment(s) to change the status for.
	 * @param string $status The new status.
	 */
	public static function updateCommentStatuses($ids, $status)
	{
		// make sure $ids is an array
		$ids = (array) $ids;

		// loop and cast to integers
		foreach($ids as &$id) $id = (int) $id;

		// create an array with an equal amount of questionmarks as ids provided
		$idPlaceHolders = array_fill(0, count($ids), '?');

		// get the items and their languages
		$items = (array) BackendModel::getContainer()->get('database')->getPairs(
			'SELECT i.product_id, i.language
			 FROM catalog_comments AS i
			 WHERE i.id IN (' . implode(', ', $idPlaceHolders) . ')',
			$ids, 'product_id'
		);

		// only proceed if there are items
		if(!empty($items))
		{
			// get the ids
			$itemIds = array_keys($items);

			// get the unique languages
			$languages = array_unique(array_values($items));

			// update records
			BackendModel::getContainer()->get('database')->execute(
				'UPDATE catalog_comments
				 SET status = ?
				 WHERE id IN (' . implode(', ', $idPlaceHolders) . ')',
				array_merge(array((string) $status), $ids)
			);

			// recalculate the comment count
			self::reCalculateCommentCount($itemIds);

			// invalidate the cache for blog
			foreach($languages as $language) BackendModel::invalidateFrontendCache('catalog', $language);
		}
	}

    /**
     * Update a certain specification
     *
     * @param int $id
     * @param array $item
     */
    public static function updateSpecification($id, $item)
    {
        BackendModel::getContainer()->get('database')->update('catalog_specifications', $item, 'id = ?', array($id));
    }

	/**
	 * Update value of a certain specification
	 *
	 * @param int $specificationId
	 * @param int $productId
	 * @param array $item
	 */
	public static function updateSpecificationValue($specificationId, $productId, $item)
	{
		BackendModel::getContainer()->get('database')->update('catalog_specifications_values', $item, 'specification_id = ? AND product_id = ?', array((int) $specificationId, (int) $productId));
	}

	/**
	 * @param array $item
	 * @return int
	 */
	public static function updateImage(array $item)
	{
		BackendModel::invalidateFrontendCache('productsCache');
		return (int) BackendModel::getContainer()->get('database')->update(
			'catalog_images',
			$item,
			'id = ?',
			array($item['id'])
		);
	}

	/**
	 * @param array $item
	 * @return int
	 */
	public static function updateFile(array $item)
	{
		BackendModel::invalidateFrontendCache('productsCache');
		return (int) BackendModel::getContainer()->get('database')->update(
			'catalog_files',
			$item,
			'id = ?',
			array($item['id'])
		);
	}

	/**
	 * @param array $item
	 * @return int
	 */
	public static function updateVideo(array $item)
	{
		BackendModel::invalidateFrontendCache('productsCache');
		return (int) BackendModel::getContainer()->get('database')->update(
			'catalog_videos',
			$item,
			'id = ?',
			array($item['id'])
		);
	}
}


text:
<configuration scan="true">
  <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
    <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
      <Pattern>%d{HH:mm:ss.SSS} %X{key} [%thread] %-5level %logger{36} - %msg%n</Pattern>
    </encoder>
  </appender>
  <logger name="ch.qos.logback" level="warn" />
  <root level="info">
    <appender-ref ref="console"/>
  </root>
</configuration>

redpajama_set_name: RedPajamaGithub


text:
module Transportation
  class Vehicle < ::ActiveRecord::Base
  end
end


text:
package mocktikv

import (
	"github.com/golang/protobuf/proto"
	"github.com/juju/errors"
	"github.com/pingcap/kvproto/pkg/coprocessor"
	"github.com/pingcap/tidb/distsql/xeval"
	"github.com/pingcap/tidb/kv"
	"github.com/pingcap/tidb/sessionctx/variable"
	"github.com/pingcap/tipb/go-tipb"
)

// MockDAGRequest is used for testing now.
var MockDAGRequest bool

type dagContext struct {
	dagReq    *tipb.DAGRequest
	keyRanges []*coprocessor.KeyRange
	eval      *xeval.Evaluator
	sc        *variable.StatementContext
	columns   []*tipb.ColumnInfo
}

func (h *rpcHandler) handleCopDAGRequest(req *coprocessor.Request) (*coprocessor.Response, error) {
	resp := &coprocessor.Response{}
	if len(req.Ranges) == 0 {
		return resp, nil
	}
	if req.GetTp() != kv.ReqTypeDAG {
		return resp, nil
	}
	if err := h.checkContext(req.GetContext()); err != nil {
		resp.RegionError = err
		return resp, nil
	}

	dagReq := new(tipb.DAGRequest)
	err := proto.Unmarshal(req.Data, dagReq)
	if err != nil {
		return nil, errors.Trace(err)
	}
	sc := xeval.FlagsToStatementContext(dagReq.Flags)
	ctx := &dagContext{
		dagReq:    dagReq,
		keyRanges: req.Ranges,
		sc:        sc,
		eval:      xeval.NewEvaluator(sc),
	}
	e, err := h.buildDAG(ctx, dagReq.Executors)
	if err != nil {
		return nil, errors.Trace(err)
	}
	var chunks []tipb.Chunk
	for {
		handle, row, err := e.Next()
		if err != nil {
			return nil, errors.Trace(err)
		}
		if row == nil {
			break
		}
		data := dummySlice
		for _, val := range row {
			data = append(data, val...)
		}
		chunks = appendRow(chunks, handle, data)
	}
	return buildResp(chunks, err)
}

func (h *rpcHandler) buildExec(ctx *dagContext, curr *tipb.Executor) (executor, error) {
	var currExec executor
	switch curr.GetTp() {
	case tipb.ExecType_TypeTableScan:
		columns := curr.TblScan.Columns
		ctx.eval.SetColumnInfos(columns)
		colIDs := make(map[int64]int)
		for i, col := range columns {
			colIDs[col.GetColumnId()] = i
		}
		ranges := h.extractKVRanges(ctx.keyRanges, *curr.TblScan.Desc)
		currExec = &tableScanExec{
			TableScan:   curr.TblScan,
			kvRanges:    ranges,
			colIDs:      colIDs,
			startTS:     ctx.dagReq.GetStartTs(),
			mvccStore:   h.mvccStore,
			rawStartKey: h.rawStartKey,
			rawEndKey:   h.rawEndKey,
		}
	case tipb.ExecType_TypeIndexScan:
		columns := curr.IdxScan.Columns
		ctx.eval.SetColumnInfos(columns)
		length := len(columns)
		// The PKHandle column info has been collected in ctx.
		if columns[length-1].GetPkHandle() {
			columns = columns[:length-1]
		}
		ranges := h.extractKVRanges(ctx.keyRanges, *curr.IdxScan.Desc)
		currExec = &indexScanExec{
			IndexScan:   curr.IdxScan,
			kvRanges:    ranges,
			colsLen:     len(columns),
			startTS:     ctx.dagReq.GetStartTs(),
			mvccStore:   h.mvccStore,
			rawStartKey: h.rawStartKey,
			rawEndKey:   h.rawEndKey,
		}
	case tipb.ExecType_TypeSelection:
		var cond *tipb.Expr
		// TODO: Now len(Conditions) is 1.
		if len(curr.Selection.Conditions) > 0 {
			cond = curr.Selection.Conditions[0]
		}
		colIDs := make(map[int64]int)
		err := extractColIDsInExpr(cond, ctx.eval.ColumnInfos, colIDs)
		if err != nil {
			return nil, errors.Trace(err)
		}
		currExec = &selectionExec{
			Selection: curr.Selection,
			eval:      ctx.eval,
			colIDs:    colIDs,
			sc:        ctx.sc,
		}
	default:
		// TODO: Support other types.
	}

	return currExec, nil
}

func (h *rpcHandler) buildDAG(ctx *dagContext, executors []*tipb.Executor) (executor, error) {
	var src executor
	for i := 0; i < len(executors); i++ {
		curr, err := h.buildExec(ctx, executors[i])
		if err != nil {
			return nil, errors.Trace(err)
		}
		curr.SetSrcExec(src)
		src = curr
	}
	return src, nil
}


text:
package org.jetbrains.plugins.scala.codeInspection.annotations

import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import org.jetbrains.plugins.scala.codeInspection.AbstractInspection
import org.jetbrains.plugins.scala.lang.psi.api.expr.ScAnnotation

/**
 * User: Dmitry.Naydanov
 * Date: 30.09.15.
 */
class MultipleArgLists extends AbstractInspection("ScalaAnnotMultipleArgLists", "MultipleArgListsInAnnotation") {
  override def actionFor(holder: ProblemsHolder): PartialFunction[PsiElement, Any] = {
    case annotation: ScAnnotation if annotation.constructor.arguments.length > 1 =>
      holder.registerProblem(annotation,
        "Implementation limitation: multiple argument lists on annotations are currently not supported")
  }
}


text:
package de.lessvoid.nifty.examples.helloniftybuilder;

import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.builder.*;
import de.lessvoid.nifty.examples.LwjglInitHelper;
import de.lessvoid.nifty.examples.NiftyExample;
import de.lessvoid.nifty.renderer.lwjgl.render.LwjglRenderDevice;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.screen.ScreenController;
import de.lessvoid.nifty.sound.openal.OpenALSoundDevice;
import de.lessvoid.nifty.spi.time.impl.AccurateTimeProvider;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * The Nifty Hello World. This time using the Nifty Builder classes
 * to dynamically create Nifty screens WITHOUT the xml.
 *
 * @author void
 */
public class HelloNiftyBuilderExampleMain implements ScreenController, NiftyExample {
  private Nifty nifty;

  public static void main(final String[] args) {
    if (!LwjglInitHelper.initSubSystems("Hello Nifty Builder World")) {
      System.exit(0);
    }

    // create nifty
    Nifty nifty = new Nifty(
        new LwjglRenderDevice(),
        new OpenALSoundDevice(),
        LwjglInitHelper.getInputSystem(),
        new AccurateTimeProvider());

    HelloNiftyBuilderExampleMain screenController = new HelloNiftyBuilderExampleMain();
    screenController.prepareStart(nifty);

    nifty.gotoScreen("start");

    // render
    LwjglInitHelper.renderLoop(nifty, null);
    LwjglInitHelper.destroy();
  }

  @Override
  public void bind(@Nonnull final Nifty nifty, @Nonnull final Screen screen) {
    System.out.println("bind()");
    this.nifty = nifty;
  }

  @Override
  public void onStartScreen() {
    System.out.println("onStartScreen()");
  }

  @Override
  public void onEndScreen() {
    System.out.println("onEndScreen()");
  }

  public void quit() {
    nifty.exit();
  }

  @Nonnull
  @Override
  public String getStartScreen() {
    return "start";
  }

  @Nullable
  @Override
  public String getMainXML() {
    return null;
  }

  @Nonnull
  @Override
  public String getTitle() {
    return "Hello Nifty Builder World";
  }

  @Override
  public void prepareStart(@Nonnull final Nifty nifty) {
    // create a screen
    Screen screen = new ScreenBuilder("start") {{
      controller(HelloNiftyBuilderExampleMain.this);

      layer(new LayerBuilder("layer") {{
        backgroundColor("#003f");
        childLayoutCenter();

        panel(new PanelBuilder() {{
          id("panel");
          childLayoutCenter();
          height("25%");
          width("80%");
          alignCenter();
          valignCenter();
          backgroundColor("#f60f");
          visibleToMouse();
          interactOnClick("quit()");
          padding("10px");

          onStartScreenEffect(new EffectBuilder("move") {{
            effectParameter("mode", "in");
            effectParameter("direction", "top");
            length(300);
            startDelay(0);
            inherit(true);
          }});

          onEndScreenEffect(new EffectBuilder("move") {{
            effectParameter("mode", "out");
            effectParameter("direction", "bottom");
            length(300);
            startDelay(0);
            inherit(true);
          }});

          onHoverEffect(new HoverEffectBuilder("pulsate") {{
            effectParameter("scaleFactor", "0.008");
            effectParameter("startColor", "#f600");
            effectParameter("endColor", "#ffff");
            post(true);
          }});

          panel(new PanelBuilder() {{
            childLayoutHorizontal();
            alignCenter();
            valignCenter();
            width("100%");

            image(new ImageBuilder() {{
              filename("nifty-logo-150x150.png");
            }});

            text(new TextBuilder() {{
              text("Hello Nifty Builder World!!!");
              font("aurulent-sans-17.fnt");
              color("#000f");
              width("*");
              alignCenter();
              valignCenter();
            }});
          }});
        }});
      }});
    }}.build(nifty);

    nifty.addScreen("start", screen);
  }
}


text:
CREATE SCHEMA [Integration]
AUTHORIZATION [dbo]
GO
EXEC sp_addextendedproperty N'Description', N'Tables and procedures required for integration with the data warehouse', 'SCHEMA', N'Integration', NULL, NULL, NULL, NULL
GO


text:
	  <?php
    $escuela_variable = get_field('escuela_relationship_field'); //
    $escuela_ID = $escuela_variable[0]->ID;
    ?>
	<article <?php post_class(); ?>>

		<?php if ( has_post_thumbnail()) : ?>
		<a href="<?php the_permalink(); ?>" class="featured-image" title="<?php the_title_attribute(); ?>" >
		<img src="<?php
		$imgsrc = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), "large");
		echo $imgsrc[0];
		?>" width="100%" />

		<?php endif; ?>

			<?php if(get_field('ciudad_en_irlanda', $escuela_ID)){ ?>
              €
              <?php } ?>
              <?php if(get_field('ciudad_en_inglaterra', $escuela_ID)){ ?>
              £
              <?php } ?>

				<?php the_field('precio') ?>

<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?>

<?php if (get_field(valida_hasta)): ?>
			<?php the_field('lang_en_oferta_hasta_el','options')?>:  <?php
						$fecha = DateTime::createFromFormat('Ymd', get_field('valida_hasta'));
						echo $fecha->format('d M Y');?>

		<?php endif ?>
		<a href="<?php the_permalink(); ?>" class="btn btn-default btn-sm pull-right" title="<?php the_field(lang_ver_detalles,'options') ?> <?php the_title_attribute(); ?>"><?php the_field(lang_ver_detalles,'options') ?>


text:
package org.italiangrid.authz.pdp;

import java.util.List;

public interface PolicyManagement {
	public List<Policy> getPolicies();
	public boolean addPolicy(Policy p);
	public void clearPolicies();
}


text:
<?php namespace Klubitus\Gallery\Updates;

use Schema;
use October\Rain\Database\Updates\Migration;

class SystemFilesAddImageSize extends Migration {

    public function up() {
        Schema::table('system_files', function($table) {
            $table->integer('image_width')->nullable();
            $table->integer('image_height')->nullable();
            $table->string('source')->nullable();
        });
    }

    public function down() {
        Schema::table('system_files', function($table) {
            $table->dropColumn('image_width', 'image_height', 'source');
        });
    }

}


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.

-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">

  <bean id="properties" class="org.apache.camel.component.properties.PropertiesComponent"/>

  <bean id="poolConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" init-method="start" destroy-method="stop">
    <property name="maxConnections" value="8"/>
    <property name="connectionFactory" ref="jmsConnectionFactory"/>
  </bean>

  <bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
    <property name="brokerURL" value="vm://localhost?broker.persistent=false&create=false"/>
  </bean>

  <bean id="jmsTransactionManager" class="org.springframework.jms.connection.JmsTransactionManager">
    <property name="connectionFactory" ref="poolConnectionFactory"/>
    <property name="nestedTransactionAllowed" value="true"/>
  </bean>

  <bean id="transactionPolicy" class="org.apache.camel.spring.spi.SpringTransactionPolicy">
    <property name="transactionManager" ref="jmsTransactionManager"/>
    <property name="propagationBehaviorName" value="PROPAGATION_REQUIRES_NEW"/>
  </bean>

  <bean id="activemq" class="org.apache.camel.component.activemq.ActiveMQComponent">
    <property name="connectionFactory" ref="poolConnectionFactory"/>
    <property name="transacted" value="true"/>
    <property name="transactionManager" ref="jmsTransactionManager"/>
    <!-- we do not want any exceptions to be logged -->
    <property name="errorHandlerLoggingLevel" value="OFF"/>
    <property name="errorHandlerLogStackTrace" value="false"/>
  </bean>

  <camelContext xmlns="http://camel.apache.org/schema/spring">

    <errorHandler id="txEH" type="DeadLetterChannel" deadLetterUri="direct:error-handler"/>

    <route>
      <from uri="direct:error-handler"/>
      <to uri="mock:got-message"/>
      <rollback markRollbackOnlyLast="true"/>
    </route>

    <route errorHandlerRef="txEH">
      <from uri="activemq:queue:okay"/>
      <transacted ref="transactionPolicy"/>
      <to uri="activemq:queue:not-okay"/>
      <process ref="errorProducer"/>
    </route>

    <route errorHandlerRef="txEH">
      <from uri="activemq:queue:not-okay"/>
      <to uri="mock:not-okay"/>
    </route>

  </camelContext>

  <bean id="errorProducer" class="org.apache.camel.itest.jms.JMSNestedTransactionRollbackTest.ErrorThrowProcessor"/>

</beans>


text:
@implementation DemoObject

@end


text:
package org.epnoi.learner.relations.patterns;

public interface RelationalPatternsModelBuilder {

	public void addPattern(RelationalPattern relationalPattern);

	public void addNegativePattern(RelationalPattern relationalPattern);

	public RelationalPatternsModel build();

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.vsked</groupId>
  <artifactId>sssdatajpa</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>sssdatajpa Maven Webapp</name>
  <url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
		<spring.version>4.3.6.RELEASE</spring.version>
		<shiro.version>1.3.2</shiro.version>
	</properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
    </parent>
	<dependencies>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
		</dependency>
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.glassfish.web/jstl-impl -->
		<dependency>
			<groupId>org.glassfish.web</groupId>
			<artifactId>jstl-impl</artifactId>
			<version>1.2</version>
		</dependency>
<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>el-impl</artifactId>
    <version>2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <!-- 排除内置容器,排除内置容器导出成war包可以让外部容器运行spring-boot项目-->
    <exclusions>
      <exclusion>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
      </exclusion>
    </exclusions>
</dependency>

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.46</version>
</dependency>

	</dependencies>
  <build>
    <finalName>sssdatajpa</finalName>
  </build>
	<profiles>
		<profile>
			<id>jdk18</id>
			<activation>
				<activeByDefault>true</activeByDefault>
				<jdk>${java.version}</jdk>
			</activation>
			<properties>
				<maven.compiler.source>${java.version}</maven.compiler.source>
				<maven.compiler.target>${java.version}</maven.compiler.target>
				<maven.compiler.compilerVersion>${java.version}</maven.compiler.compilerVersion>
			</properties>
		</profile>
	</profiles>
</project>


text:
CREATE TABLE public.aireas_hist
(
  gid integer NOT NULL DEFAULT nextval('aireas_hist_gid_seq'::regclass),
  airbox character varying(255),
  retrieveddatechar character varying(60),
  measuredatechar character varying(60),
  retrieveddate timestamp with time zone,
  measuredate timestamp with time zone,
  gpslat character varying(60),
  gpslng character varying(60),
  lat double precision,
  lng double precision,
  pm1 character varying(60),
  pm25 character varying(60),
  pm10 character varying(60),
  ufp character varying(60),
  ozon character varying(60),
  hum character varying(60),
  celc character varying(60),
  no2 character varying(60),
  gpslatfloat double precision,
  gpslngfloat double precision,
  pm1float double precision,
  pm25float double precision,
  pm10float double precision,
  ufpfloat double precision,
  ozonfloat double precision,
  humfloat double precision,
  celcfloat double precision,
  no2float double precision,
  geom geometry(Point),
  geom28992 geometry(Point,28992),
  mark_date timestamp with time zone,
  mark_desc character varying(255),
  CONSTRAINT aireas_hist_pkey PRIMARY KEY (gid)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE public.aireas_hist
  OWNER TO postgres;

-- Index: public.aireas_hist_airbox_idx

-- DROP INDEX public.aireas_hist_airbox_idx;

CREATE INDEX aireas_hist_airbox_idx
  ON public.aireas_hist
  USING btree
  (airbox COLLATE pg_catalog."default");

-- Index: public.aireas_hist_geom_gist

-- DROP INDEX public.aireas_hist_geom_gist;

CREATE INDEX aireas_hist_geom_gist
  ON public.aireas_hist
  USING gist
  (geom);

-- Index: public.aireas_hist_retrieveddate_idx

-- DROP INDEX public.aireas_hist_retrieveddate_idx;

CREATE INDEX aireas_hist_retrieveddate_idx
  ON public.aireas_hist
  USING btree
  (retrieveddate);

-- Index: public.idx_aireas_hist_geom28992

-- DROP INDEX public.idx_aireas_hist_geom28992;

CREATE INDEX idx_aireas_hist_geom28992
  ON public.aireas_hist
  USING gist
  (geom28992);


text:
package com.intellij.psi.impl.source;

import com.intellij.extapi.psi.StubBasedPsiElementBase;
import com.intellij.lang.ASTNode;
import com.intellij.navigation.ItemPresentation;
import com.intellij.navigation.ItemPresentationProviders;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.Queryable;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.UserDataHolder;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.impl.*;
import com.intellij.psi.impl.java.stubs.JavaStubElementTypes;
import com.intellij.psi.impl.java.stubs.PsiClassInitializerStub;
import com.intellij.psi.impl.java.stubs.PsiClassStub;
import com.intellij.psi.impl.java.stubs.PsiMethodStub;
import com.intellij.psi.impl.source.tree.ChildRole;
import com.intellij.psi.impl.source.tree.CompositeElement;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.scope.PsiScopeProcessor;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.stubs.IStubElementType;
import com.intellij.psi.stubs.PsiFileStub;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.util.*;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class PsiClassImpl extends JavaStubPsiElement<PsiClassStub<?>> implements PsiExtensibleClass, Queryable {
  private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.PsiClassImpl");

  private final ClassInnerStuffCache myInnersCache = new ClassInnerStuffCache(this);
  private volatile String myCachedName;

  public PsiClassImpl(final PsiClassStub stub) {
    this(stub, JavaStubElementTypes.CLASS);
  }

  protected PsiClassImpl(final PsiClassStub stub, final IStubElementType type) {
    super(stub, type);
    addTrace(null);
  }

  public PsiClassImpl(final ASTNode node) {
    super(node);
    addTrace(null);
  }

  private void addTrace(@Nullable PsiClassStub stub) {
    if (ourTraceStubAstBinding) {
      String creationTrace = "Creation thread: " + Thread.currentThread() + "\n" + DebugUtil.currentStackTrace();
      if (stub != null) {
        creationTrace += "\nfrom stub " + stub + "@" + System.identityHashCode(stub) + "\n";
        if (stub instanceof UserDataHolder) {
          String stubTrace = ((UserDataHolder)stub).getUserData(CREATION_TRACE);
          if (stubTrace != null) {
            creationTrace += stubTrace;
          }
        }
      }
      putUserData(CREATION_TRACE, creationTrace);
    }
  }

  @Override
  public void subtreeChanged() {
    dropCaches();
    super.subtreeChanged();
  }

  private void dropCaches() {
    myInnersCache.dropCaches();
    myCachedName = null;
  }

  @Override
  protected Object clone() {
    PsiClassImpl clone = (PsiClassImpl)super.clone();
    clone.dropCaches();
    return clone;
  }

  @Override
  public PsiElement getOriginalElement() {
    return CachedValuesManager.getCachedValue(this, () -> {
      final JavaPsiImplementationHelper helper = JavaPsiImplementationHelper.getInstance(getProject());
      final PsiClass result = helper != null ? helper.getOriginalClass(this) : this;
      return CachedValueProvider.Result.create(result, PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT);
    });
  }

  @Override
  @NotNull
  public CompositeElement getNode() {
    return (CompositeElement)super.getNode();
  }

  @Override
  public PsiIdentifier getNameIdentifier() {
    return (PsiIdentifier)getNode().findChildByRoleAsPsiElement(ChildRole.NAME);
  }

  @Override
  public PsiElement getScope() {
    final PsiClassStub stub = getStub();
    if (stub != null) {
      return stub.getParentStub().getPsi();
    }

    ASTNode treeElement = getNode();
    ASTNode parent = treeElement.getTreeParent();

    while(parent != null) {
      if (parent.getElementType() instanceof IStubElementType){
        return parent.getPsi();
      }
      parent = parent.getTreeParent();
    }

    return getContainingFile();
  }

  @Override
  public String getName() {
    String name = myCachedName;
    if (name != null) return name;
    final PsiClassStub stub = getGreenStub();
    if (stub == null) {
      PsiIdentifier identifier = getNameIdentifier();
      name = identifier == null ? null : identifier.getText();
    }
    else {
      name = stub.getName();
    }
    myCachedName = name;
    return name;
  }

  @Override
  public String getQualifiedName() {
    final PsiClassStub stub = getGreenStub();
    if (stub != null) {
      return stub.getQualifiedName();
    }

    PsiElement parent = getParent();
    if (parent instanceof PsiJavaFile) {
      return StringUtil.getQualifiedName(((PsiJavaFile)parent).getPackageName(), getName());
    }
    if (parent instanceof PsiClass) {
      String parentQName = ((PsiClass)parent).getQualifiedName();
      if (parentQName == null) return null;
      return StringUtil.getQualifiedName(parentQName, getName());
    }

    return null;
  }

  @Override
  public PsiModifierList getModifierList() {
    return getRequiredStubOrPsiChild(JavaStubElementTypes.MODIFIER_LIST);
  }

  @Override
  public boolean hasModifierProperty(@NotNull String name) {
    final PsiModifierList modlist = getModifierList();
    return modlist != null && modlist.hasModifierProperty(name);
  }

  @Override
  public PsiReferenceList getExtendsList() {
    return getStubOrPsiChild(JavaStubElementTypes.EXTENDS_LIST);
  }

  @Override
  public PsiReferenceList getImplementsList() {
    return getStubOrPsiChild(JavaStubElementTypes.IMPLEMENTS_LIST);
  }

  @Override
  @NotNull
  public PsiClassType[] getExtendsListTypes() {
    return PsiClassImplUtil.getExtendsListTypes(this);
  }

  @Override
  @NotNull
  public PsiClassType[] getImplementsListTypes() {
    return PsiClassImplUtil.getImplementsListTypes(this);
  }

  @Override
  public PsiClass getSuperClass() {
    return PsiClassImplUtil.getSuperClass(this);
  }

  @NotNull
  @Override
  public PsiClass[] getInterfaces() {
    return PsiClassImplUtil.getInterfaces(this);
  }

  @Override
  @NotNull
  public PsiClass[] getSupers() {
    return PsiClassImplUtil.getSupers(this);
  }

  @Override
  @NotNull
  public PsiClassType[] getSuperTypes() {
    return PsiClassImplUtil.getSuperTypes(this);
  }

  @Override
  @Nullable
  public PsiClass getContainingClass() {
    final PsiClassStub stub = getGreenStub();
    if (stub != null) {
      StubElement parent = stub.getParentStub();
      return parent instanceof PsiClassStub ? ((PsiClassStub<?>)parent).getPsi() : null;
    }

    PsiElement parent = getParent();

    if (parent instanceof PsiClassLevelDeclarationStatement) {
      return PsiTreeUtil.getParentOfType(this, PsiSyntheticClass.class);
    }

    return parent instanceof PsiClass ? (PsiClass)parent : null;
  }

  @Override
  public PsiElement getContext() {
    StubElement contextStub = getContextStub();
    if (contextStub != null) {
      return contextStub.getPsi();
    }

    return super.getContext();
  }

  @Nullable
  private StubElement getContextStub() {
    PsiClassStub<?> stub = getStub();
    if (stub == null) return null;

    // if AST is not loaded, then we only can need context to resolve supertype references
    // this can be done by stubs unless there are local/anonymous classes referencing other local classes
    StubElement parent = stub.getParentStub();
    if (parent instanceof PsiClassInitializerStub || parent instanceof PsiMethodStub) {
      if (parent.getChildrenByType(JavaStubElementTypes.CLASS, PsiElement.ARRAY_FACTORY).length <= 1) {
        parent = parent.getParentStub();
      }
    }
    return parent instanceof PsiClassStub ? parent : null;
  }

  @Override
  @NotNull
  public Collection<HierarchicalMethodSignature> getVisibleSignatures() {
    return PsiSuperMethodImplUtil.getVisibleSignatures(this);
  }

  @Override
  @NotNull
  public PsiField[] getFields() {
    return myInnersCache.getFields();
  }

  @Override
  @NotNull
  public PsiMethod[] getMethods() {
    return myInnersCache.getMethods();
  }

  @Override
  @NotNull
  public PsiMethod[] getConstructors() {
    return myInnersCache.getConstructors();
  }

  @Override
  @NotNull
  public PsiClass[] getInnerClasses() {
    return myInnersCache.getInnerClasses();
  }

  @NotNull
  @Override
  public List<PsiField> getOwnFields() {
    return Arrays.asList(getStubOrPsiChildren(Constants.FIELD_BIT_SET, PsiField.ARRAY_FACTORY));
  }

  @NotNull
  @Override
  public List<PsiMethod> getOwnMethods() {
    return Arrays.asList(getStubOrPsiChildren(Constants.METHOD_BIT_SET, PsiMethod.ARRAY_FACTORY));
  }

  @NotNull
  @Override
  public List<PsiClass> getOwnInnerClasses() {
    return Arrays.asList(getStubOrPsiChildren(JavaStubElementTypes.CLASS, PsiClass.ARRAY_FACTORY));
  }

  @Override
  @NotNull
  public PsiClassInitializer[] getInitializers() {
    return getStubOrPsiChildren(JavaStubElementTypes.CLASS_INITIALIZER, PsiClassInitializer.ARRAY_FACTORY);
  }

  @Override
  @NotNull
  public PsiTypeParameter[] getTypeParameters() {
    return PsiImplUtil.getTypeParameters(this);
  }

  @Override
  @NotNull
  public PsiField[] getAllFields() {
    return PsiClassImplUtil.getAllFields(this);
  }

  @Override
  @NotNull
  public PsiMethod[] getAllMethods() {
    return PsiClassImplUtil.getAllMethods(this);
  }

  @Override
  @NotNull
  public PsiClass[] getAllInnerClasses() {
    return PsiClassImplUtil.getAllInnerClasses(this);
  }

  @Override
  public PsiField findFieldByName(String name, boolean checkBases) {
    return myInnersCache.findFieldByName(name, checkBases);
  }

  @Override
  public PsiMethod findMethodBySignature(PsiMethod patternMethod, boolean checkBases) {
    return PsiClassImplUtil.findMethodBySignature(this, patternMethod, checkBases);
  }

  @Override
  @NotNull
  public PsiMethod[] findMethodsBySignature(PsiMethod patternMethod, boolean checkBases) {
    return PsiClassImplUtil.findMethodsBySignature(this, patternMethod, checkBases);
  }

  @Override
  @NotNull
  public PsiMethod[] findMethodsByName(String name, boolean checkBases) {
    return myInnersCache.findMethodsByName(name, checkBases);
  }

  @Override
  @NotNull
  public List<Pair<PsiMethod, PsiSubstitutor>> findMethodsAndTheirSubstitutorsByName(String name, boolean checkBases) {
    return PsiClassImplUtil.findMethodsAndTheirSubstitutorsByName(this, name, checkBases);
  }

  @Override
  @NotNull
  public List<Pair<PsiMethod, PsiSubstitutor>> getAllMethodsAndTheirSubstitutors() {
    return PsiClassImplUtil.getAllWithSubstitutorsByMap(this, PsiClassImplUtil.MemberType.METHOD);
  }

  @Override
  public PsiClass findInnerClassByName(String name, boolean checkBases) {
    return myInnersCache.findInnerClassByName(name, checkBases);
  }

  @Override
  public PsiTypeParameterList getTypeParameterList() {
    return getRequiredStubOrPsiChild(JavaStubElementTypes.TYPE_PARAMETER_LIST);
  }

  @Override
  public boolean hasTypeParameters() {
    return PsiImplUtil.hasTypeParameters(this);
  }

  @Override
  public boolean isDeprecated() {
    final PsiClassStub stub = getGreenStub();
    if (stub != null) {
      return stub.isDeprecated() || stub.hasDeprecatedAnnotation() && PsiImplUtil.isDeprecatedByAnnotation(this);
    }

    return PsiImplUtil.isDeprecatedByDocTag(this) || PsiImplUtil.isDeprecatedByAnnotation(this);
  }

  @Override
  public PsiDocComment getDocComment(){
    return (PsiDocComment)getNode().findChildByRoleAsPsiElement(ChildRole.DOC_COMMENT);
  }

  @Override
  public PsiJavaToken getLBrace() {
    return (PsiJavaToken)getNode().findChildByRoleAsPsiElement(ChildRole.LBRACE);
  }

  @Override
  public PsiJavaToken getRBrace() {
    return (PsiJavaToken)getNode().findChildByRoleAsPsiElement(ChildRole.RBRACE);
  }

  @Override
  public boolean isInterface() {
    final PsiClassStub stub = getGreenStub();
    if (stub != null) {
      return stub.isInterface();
    }

    ASTNode keyword = getNode().findChildByRole(ChildRole.CLASS_OR_INTERFACE_KEYWORD);
    return keyword != null && keyword.getElementType() == JavaTokenType.INTERFACE_KEYWORD;
  }

  @Override
  public boolean isAnnotationType() {
    final PsiClassStub stub = getGreenStub();
    if (stub != null) {
      return stub.isAnnotationType();
    }

    return getNode().findChildByRole(ChildRole.AT) != null;
  }

  @Override
  public boolean isEnum() {
    final PsiClassStub stub = getGreenStub();
    if (stub != null) {
      return stub.isEnum();
    }

    final ASTNode keyword = getNode().findChildByRole(ChildRole.CLASS_OR_INTERFACE_KEYWORD);
    return keyword != null && keyword.getElementType() == JavaTokenType.ENUM_KEYWORD;
  }

  @Override
  public void accept(@NotNull PsiElementVisitor visitor){
    if (visitor instanceof JavaElementVisitor) {
      ((JavaElementVisitor)visitor).visitClass(this);
    }
    else {
      visitor.visitElement(this);
    }
  }

  public String toString(){
    return "PsiClass:" + getName();
  }

  @Override
  public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) {
    if (isEnum()) {
      if (!PsiClassImplUtil.processDeclarationsInEnum(processor, state, myInnersCache)) return false;
    }

    LanguageLevel level = PsiUtil.getLanguageLevel(place);
    return PsiClassImplUtil.processDeclarationsInClass(this, processor, state, null, lastParent, place, level, false);
  }

  @Override
  public PsiElement setName(@NotNull String newName) throws IncorrectOperationException{
    String oldName = getName();
    boolean isRenameFile = isRenameFileOnRenaming();

    PsiImplUtil.setName(getNameIdentifier(), newName);

    if (isRenameFile) {
      PsiFile file = (PsiFile)getParent();
      String fileName = file.getName();
      int dotIndex = fileName.lastIndexOf('.');
      file.setName(dotIndex >= 0 ? newName + "." + fileName.substring(dotIndex + 1) : newName);
    }

    // rename constructors
    for (PsiMethod method : getMethods()) {
      if (method.isConstructor() && method.getName().equals(oldName)) {
        method.setName(newName);
      }
    }

    return this;
  }

  private boolean isRenameFileOnRenaming() {
    final PsiElement parent = getParent();
    if (parent instanceof PsiFile) {
      PsiFile file = (PsiFile)parent;
      String fileName = file.getName();
      int dotIndex = fileName.lastIndexOf('.');
      String name = dotIndex >= 0 ? fileName.substring(0, dotIndex) : fileName;
      String oldName = getName();
      return name.equals(oldName);
    }
    else {
      return false;
    }
  }

  // optimization to not load tree when resolving bases of anonymous and locals
  // if there is no local classes with such name in scope it's possible to use outer scope as context
  @Nullable
  public PsiElement calcBasesResolveContext(String baseClassName, final PsiElement defaultResolveContext) {
    return calcBasesResolveContext(this, baseClassName, true, defaultResolveContext);
  }

  private static boolean isAnonymousOrLocal(PsiClass aClass) {
    if (aClass instanceof PsiAnonymousClass) return true;

    final PsiClassStub stub = ((PsiClassImpl)aClass).getGreenStub();
    if (stub != null) {
      final StubElement parentStub = stub.getParentStub();
      return !(parentStub instanceof PsiClassStub || parentStub instanceof PsiFileStub);
    }

    PsiElement parent = aClass.getParent();
    while (parent != null) {
      if (parent instanceof PsiMethod || parent instanceof PsiField || parent instanceof PsiClassInitializer) return true;
      if (parent instanceof PsiClass || parent instanceof PsiFile) return false;
      parent = parent.getParent();
    }

    return false;
  }

  @Nullable
  private static PsiElement calcBasesResolveContext(@NotNull PsiElement scope,
                                                    String baseClassName,
                                                    boolean isInitialClass,
                                                    final PsiElement defaultResolveContext) {
    final StubElement stub = scope instanceof StubBasedPsiElementBase ? ((StubBasedPsiElementBase<?>)scope).getStub() : null;
    if (stub == null || stub instanceof PsiClassStub && ((PsiClassStub)stub).isAnonymousInQualifiedNew()) {
      return scope.getParent();
    }

    if (scope instanceof PsiClass) {
      if (!isAnonymousOrLocal((PsiClass)scope)) {
        return isInitialClass ? defaultResolveContext : scope;
      }

      if (!isInitialClass) {
        if (((PsiClass)scope).findInnerClassByName(baseClassName, true) != null) return scope;
      }
    }

    final StubElement parentStub = stub.getParentStub();
    PsiElement psi = parentStub.getPsi();
    if (!(psi instanceof StubBasedPsiElementBase)) {
      return null;
    }

    if (hasChildClassStub(parentStub, baseClassName, scope)) {
      return scope.getParent();
    }

    if (psi instanceof PsiMember) {
      return psi;
    }
    if (psi instanceof PsiFunctionalExpression) {
      return calcBasesResolveContext(psi, baseClassName, false, defaultResolveContext);
    }
    LOG.error(parentStub);
    return psi;
  }

  private static boolean hasChildClassStub(StubElement parentStub, String className, PsiElement place) {
    PsiClass[] classesInScope = (PsiClass[])parentStub.getChildrenByType(Constants.CLASS_BIT_SET, PsiClass.ARRAY_FACTORY);

    for (PsiClass scopeClass : classesInScope) {
      if (scopeClass == place) continue;
      if (className.equals(scopeClass.getName())) {
        return true;
      }
    }

    if (place instanceof PsiClass) {
      if (classesInScope.length == 0) {
        LOG.error("Parent stub: " + parentStub.getStubType() + "; children: " + parentStub.getChildrenStubs() + "; \ntext:" + parentStub.getPsi().getText());
      }
      LOG.assertTrue(Arrays.asList(classesInScope).contains(place));
    }
    return false;
  }

  @Override
  public boolean isInheritor(@NotNull PsiClass baseClass, boolean checkDeep) {
    return InheritanceImplUtil.isInheritor(this, baseClass, checkDeep);
  }

  @Override
  public boolean isInheritorDeep(PsiClass baseClass, PsiClass classToByPass) {
    return InheritanceImplUtil.isInheritorDeep(this, baseClass, classToByPass);
  }

  @Override
  public ItemPresentation getPresentation() {
    return ItemPresentationProviders.getItemPresentation(this);
  }

  @Override
  public Icon getElementIcon(final int flags) {
    return PsiClassImplUtil.getClassIcon(flags, this);
  }

  @Override
  public boolean isEquivalentTo(final PsiElement another) {
    return PsiClassImplUtil.isClassEquivalentTo(this, another);
  }

  @Override
  @NotNull
  public SearchScope getUseScope() {
    return PsiClassImplUtil.getClassUseScope(this);
  }

  @Override
  public void putInfo(@NotNull Map<String, String> info) {
    putInfo(this, info);
  }

  public static void putInfo(@NotNull PsiClass psiClass, @NotNull Map<String, String> info) {
    info.put("className", psiClass.getName());
    info.put("qualifiedClassName", psiClass.getQualifiedName());
    PsiFile file = psiClass.getContainingFile();
    if (file instanceof Queryable) {
      ((Queryable)file).putInfo(info);
    }
  }

  @Override
  protected boolean isVisibilitySupported() {
    return true;
  }

  @Nullable
  public PsiMethod getValuesMethod() {
    return myInnersCache.getValuesMethod();
  }
}


text:
<?php

namespace Simnang\LoanPro\Constants\LOAN_FUNDING;

/**
 * Class LOAN_FUNDING_COUNTRY__C
 * @package Simnang\LoanPro\Constants\LOAN_SETUP
 */
class LOAN_FUNDING_COUNTRY__C{
    const CANADA        = 'company.country.can';
    const UNITED_STATES = 'company.country.usa';
}


text:
```sh
$ sudo destroy-unit mysql/0
```
```sh
$ sudo destroy-machine 1
```

##2.- Volver a crear la máquina anterior y añadirle mediawiki y una relación entre ellos.

```sh
$ juju deploy wikimedia
```
```sh
$ juju add-relation mediawiki:db mysql
```

##3.- Crear un script en shell para reproducir la configuración usada en las máquinas que hagan falta.

![imagen_Ejercicio_7_a](https://dl.dropboxusercontent.com/s/rkvclmud3ogxbt9/Ejercicio7_%20imagen_1.png?dl=0)


text:
/*jshint node: true*/
/**
 * @author lattmann / https://github.com/lattmann
 * @author pmeijer / https://github.com/pmeijer
 */

var env = process.env.NODE_ENV ? process.env.NODE_ENV : process.platform === 'win32' ? 'win' : 'default',
    configFilename = __dirname + '/config.' + env + '.js',
    config = require(configFilename),
    validateConfig = require('webgme/config/validator');

validateConfig(configFilename);
module.exports = config;


text:
<?xml version="1.0" encoding="utf-8"?>
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="zend.filter.set.alnum"><info><title>Alnum</title></info>

    <para>
        <classname>Zend_Filter_Alnum</classname> ist ein Filter welche nur alphabetische Zeichen und
        Ziffern zurückgibt. Alle anderen Zeichen werden unterdrückt.
    </para>

    <section xml:id="zend.filter.set.alnum.options"><info><title>Unterstützte Optionen für Zend_Filter_Alnum</title></info>

        <para>
            Die folgenden Optionen werden für <classname>Zend_Filter_Alnum</classname> unterstützt:
        </para>

        <itemizedlist>
            <listitem>
                <para>
                    <emphasis><property>allowwhitespace</property></emphasis>: Wenn diese Option
                    gesetzt wird dann sind Leerzeichen erlaubt. Andernfalls werden Sie unterdrückt.
                    Standardmäßig sind Leerzeichen nicht erlaubt.
                </para>
            </listitem>
        </itemizedlist>
    </section>

    <section xml:id="zend.filter.set.alnum.basic"><info><title>Grundsätzliche Verwendung</title></info>

        <para>
            Das folgende Beispiel zeigt das Standardverhalten dieses Filters.
        </para>

        <programlisting language="php"><![CDATA[
$filter = new Zend_Filter_Alnum();
$return = $filter->filter('This is (my) content: 123');
// Gibt 'Thisismycontent123' zurück
]]></programlisting>

        <para>
            Das oben stehende Beispiel gibt 'Thisismycontent123' zurück. Wie man sehen kann werden
            alle Leerzeichen und auch die Klammern gefiltert.
        </para>

        <note>
            <para>
                <classname>Zend_Filter_Alnum</classname> arbeitet auf fast allen Sprachen. Aber
                aktuell gibt es drei Ausnahmen: Chinesisch, Japanisch und Koreanisch. In diesen
                Sprachen wird statt dessen das englische Alphabeth statt den Zeichen dieser Sprache
                verwendet. Die Sprache selbst wird durch Verwendung von
                <classname>Zend_Locale</classname> erkannt.
            </para>
        </note>
    </section>

    <section xml:id="zend.filter.set.alnum.whitespace"><info><title>Leerzeichen erlauben</title></info>

        <para>
            <classname>Zend_Filter_Alnum</classname> kann auch Leerzeichen erlauben. Das kann
            nützlich sein wenn man spezielle Zeichen von einem Text entfernen will. Siehe das
            folgende Beispiel:
        </para>

        <programlisting language="php"><![CDATA[
$filter = new Zend_Filter_Alnum(array('allowwhitespace' => true));
$return = $filter->filter('This is (my) content: 123');
// Gibt 'This is my content 123' zurück
]]></programlisting>

        <para>
            Das obige Beispiel gibt 'This is my content 123' zurück. Wie man sieht werden nur die
            Klammern gefiltert wobei die Leerzeichen nicht angefasst werden.
        </para>

        <para>
            Am <property>allowWhiteSpace</property> im Nachhinein zu ändern kann man
            <methodname>setAllowWhiteSpace</methodname> und
            <methodname>getAllowWhiteSpace</methodname> verwenden.
        </para>
    </section>
</section>


text:
@implementation DRCircularImageView

- (id)init {
    if (self = [super init]) {
        [self setup];
        [self setupConstraints];
    }

    return self;
}

- (void)setup {
    self.imageView = [UIImageView new];

    [self.imageView.layer setBorderColor:[UIColor whiteColor].CGColor];
    [self.imageView.layer setBorderWidth:1.5];
    [self.imageView setClipsToBounds:YES];

    [self addSubview:self.imageView];
}

- (void)setupConstraints {
    [self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@0);
    }];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    [self.layer setCornerRadius:self.frame.size.width/2];
    [self.imageView.layer setCornerRadius:self.frame.size.width/2];
}

@end


text:
<?php

namespace app\models\user;

use dektrium\user\models\User as UserBaseModel;
use app\models\UserAssignment;

class User extends UserBaseModel
{
    /**
     * @return bool Whether the user is confirmed or not.
     */
    public function getIsConfirmed()
    {
        return $this->confirmed_at != null;
    }

    /**
     * @return bool Whether the user is blocked or not.
     */
    public function getIsBlocked()
    {
        return $this->blocked_at != null;
    }

    /**
     * @return bool Whether the user is an admin or not.
     */
    public function getIsAdmin()
    {
        return
            (\Yii::$app->getAuthManager() && $this->module->adminPermission ?
                \Yii::$app->user->can($this->module->adminPermission) : false)
            || in_array($this->username, $this->module->admins);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProfile()
    {
        return UserAssignment::find()->where(['user_id'=>$this->id]);
    }

    /** @inheritdoc */
    public function getId()
    {
        return $this->getAttribute('id');
    }
}


text:
module HealthSeven::V2_6
class OrlO36 < ::HealthSeven::Message
  attribute :msh, Msh, position: "MSH", require: true
  attribute :msa, Msa, position: "MSA", require: true
  attribute :errs, Array[Err], position: "ERR", multiple: true
  attribute :sfts, Array[Sft], position: "SFT", multiple: true
  attribute :uac, Uac, position: "UAC"
  attribute :ntes, Array[Nte], position: "NTE", multiple: true
  class Response < ::HealthSeven::SegmentGroup
    attribute :pid, Pid, position: "PID", require: true
    class Specimen < ::HealthSeven::SegmentGroup
      attribute :spm, Spm, position: "SPM", require: true
      attribute :obxes, Array[Obx], position: "OBX", multiple: true
      attribute :ntes, Array[Nte], position: "NTE", multiple: true
      class SpecimenContainer < ::HealthSeven::SegmentGroup
        attribute :sac, Sac, position: "SAC", require: true
        class Order < ::HealthSeven::SegmentGroup
          attribute :orc, Orc, position: "ORC", require: true
          class Timing < ::HealthSeven::SegmentGroup
            attribute :tq1, Tq1, position: "TQ1", require: true
            attribute :tq2s, Array[Tq2], position: "TQ2", multiple: true
          end
          attribute :timings, Array[Timing], position: "ORL_O36.TIMING", multiple: true
          class ObservationRequest < ::HealthSeven::SegmentGroup
            attribute :obr, Obr, position: "OBR", require: true
            attribute :rols, Array[Rol], position: "ROL", multiple: true
          end
          attribute :observation_request, ObservationRequest, position: "ORL_O36.OBSERVATION_REQUEST"
        end
        attribute :orders, Array[Order], position: "ORL_O36.ORDER", multiple: true
      end
      attribute :specimen_containers, Array[SpecimenContainer], position: "ORL_O36.SPECIMEN_CONTAINER", require: true, multiple: true
    end
    attribute :specimen, Array[Specimen], position: "ORL_O36.SPECIMEN", require: true, multiple: true
  end
  attribute :response, Response, position: "ORL_O36.RESPONSE"
end
end


text:
<?php defined("BASEPATH") or exit("No direct script access allowed"); ?>

<?php $this->layout("templates::master") ?>

<?php $this->start('header') ?>
<?php $this->insert("structure::header", ['sess' => $sess]) ?>
<?php $this->stop() ?>

<?php $this->start('nav') ?>
<?php $this->insert("structure::nav") ?>
<?php $this->stop() ?>

<?php $this->start('section') ?>

No se ha encontrado la página solicitada o no existe.

<?php $this->stop() ?>


text:
'use strict'

/**
 * User menu and related controls
 *
 * @param hackBrowserWindow
 * @constructor
 */
function UserMenu(hackBrowserWindow) {
	const electron = require('electron')
	const remote = electron.remote
	const Menu = remote.Menu
	const logger = remote.getGlobal('__app').logger

	let menuTemplate

	// An estimate of the user menu's width
	// Since there is no way to programmatically get the width
	// of user menu, the fixed value here is used to open the logger
	const menuWidth = 221

	let _this = this

	/* ====================================
	 private member variables
	 ====================================== */
	let userMenuBtnEl

	/* ====================================
	 private methods
	 ====================================== */
	let init = function() {
		userMenuBtnEl = document.getElementById('button-menu')

		menuTemplate = [
			{
				label: "New tab",
				accelerator: "Ctrl+T",
				enabled: true,
				click: function(item, focusedWindow) {
					logger.debug('New Tab')
				}
			},
			{
				label: "New window",
				accelerator: "Ctrl+N",
				enabled: true,
				click: function(item, focusedWindow) {
					logger.debug('New window')
					// hackBrowserWindow.goForward()
				}
			},
			{
				type: "separator"
			},
			{
				label: "Print",
				accelerator: "CmdOrCtrl+P",
				click: function(item, focusedWindow) {
					hackBrowserWindow.getActiveTabView().getWebViewEl().print()
				}
			}
		]

		attachEventListeners()
	}

	let attachEventListeners = function() {
		userMenuBtnEl.addEventListener('click', handleMenuBtnClick, false)
	}

	let handleMenuBtnClick = function(e) {
		e.preventDefault()

		showUserMenu()
	}

	let calculateOpenPosition = function() {
		// Calculate open position
		let browserWindowContentBounds = electron.remote.getCurrentWindow().getContentBounds()
		let windowXPos = browserWindowContentBounds.x
		let windowWidth = browserWindowContentBounds.width

		return {
			x: windowWidth - menuWidth,
			y: 60
		}
	}

	/**
	 * Build and show user menu
	 */
	let buildUserMenu = function() {
		var userMenu = Menu.buildFromTemplate(menuTemplate)

		return userMenu
	}

	let showUserMenu = function() {
		let userMenu = buildUserMenu()
		let openPosition = calculateOpenPosition()

		userMenu.popup(remote.getCurrentWindow(), {
			x: openPosition.x,
			y: openPosition.y,
			async: true
		})
	}

	/* ====================================
	 public methods
	 ====================================== */

	/**
	 * Open user menu
	 */
	_this.open = function() {
		showUserMenu()
	}

	init()
}