text:
<?php
/**
 * @package The_SEO_Framework\Classes
 */
namespace The_SEO_Framework;

defined( 'ABSPATH' ) or die;

/**
 * The SEO Framework plugin
 * Copyright (C) 2015 - 2016 Sybre Waaijer, CyberWire (https://cyberwire.nl/)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3 as published
 * by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Class The_SEO_Framework\Render
 *
 * Puts all data into HTML valid meta tags.
 *
 * @since 2.8.0
 */
class Render extends Admin_Init {

	/**
	 * Theme title doing it wrong boolean.
	 *
	 * @since 2.4.0
	 *
	 * @var bool Holds Theme is doing it wrong.
	 */
	protected $title_doing_it_wrong = null;

	/**
	 * Constructor, load parent constructor
	 */
	protected function __construct() {
		parent::__construct();
	}

	/**
	 * Cache description in static variable
	 * Must be called inside the loop
	 *
	 * @since 2.2.2
	 * @staticvar array $description_cache
	 *
	 * @return string The description
	 */
	public function description_from_cache( $social = false ) {

		static $description_cache = array();

		if ( isset( $description_cache[ $social ] ) )
			return $description_cache[ $social ];

		return $description_cache[ $social ] = $this->generate_description( '', array( 'social' => $social ) );
	}

	/**
	 * Cache current URL in static variable
	 * Must be called inside the loop
	 *
	 * @since 2.2.2
	 * @staticvar array $url_cache
	 *
	 * @param string $url the url
	 * @param int $post_id the page id, if empty it will fetch the requested ID, else the page uri
	 * @param bool $paged Return current page URL with pagination
	 * @param bool $from_option Get the canonical uri option
	 * @param bool $paged_plural Whether to allow pagination on second or later pages.
	 * @return string The url
	 */
	public function the_url_from_cache( $url = '', $post_id = null, $paged = false, $from_option = true, $paged_plural = true ) {

		static $url_cache = array();

		if ( empty( $post_id ) )
			$post_id = $this->get_the_real_ID();

		if ( isset( $url_cache[ $url ][ $post_id ][ $paged ][ $from_option ][ $paged_plural ] ) )
			return $url_cache[ $url ][ $post_id ][ $paged ][ $from_option ][ $paged_plural ];

		return $url_cache[ $url ][ $post_id ][ $paged ][ $from_option ][ $paged_plural ] = $this->the_url( $url, array( 'paged' => $paged, 'get_custom_field' => $from_option, 'id' => $post_id, 'paged_plural' => $paged_plural ) );
	}

	/**
	 * Cache home URL in static variable
	 *
	 * @since 2.5.0
	 * @staticvar array $url_cache
	 *
	 * @param bool $force_slash Force slash
	 * @return string The url
	 */
	public function the_home_url_from_cache( $force_slash = false ) {

		static $url_cache = array();

		if ( isset( $url_cache[ $force_slash ] ) )
			return $url_cache[ $force_slash ];

		return $url_cache[ $force_slash ] = $this->the_url( '', array( 'home' => true, 'forceslash' => $force_slash ) );
	}

	/**
	 * Cache current Title in static variable
	 * Must be called inside the loop
	 *
	 * @since 2.2.2
	 * @since 2.4.0 : If the theme is doing it right, override cache parameters to speed things up.
	 * @staticvar array $title_cache
	 *
	 * @param string $title The Title to return
	 * @param string $sep The Title sepeartor
	 * @param string $seplocation The Title sepeartor location ( accepts 'left' or 'right' )
	 * @param bool $meta Ignore theme doing it wrong.
	 * @return string The title
	 */
	public function title_from_cache( $title = '', $sep = '', $seplocation = '', $meta = false ) {

		/**
		 * Cache the inputs, for when the title is doing it right.
		 * Use those values to fetch the cached title.
		 *
		 * @since 2.4.0
		 */
		static $setup_cache = null;
		static $title_param_cache = null;
		static $sep_param_cache = null;
		static $seplocation_param_cache = null;

		if ( ! isset( $setup_cache ) ) {
			if ( \doing_filter( 'pre_get_document_title' ) || \doing_filter( 'wp_title' ) ) {
				$title_param_cache = $title;
				$sep_param_cache = $sep;
				$seplocation_param_cache = $seplocation;

				$setup_cache = 'I like turtles.';
			}
		}

		if ( isset( $this->title_doing_it_wrong ) && false === $this->title_doing_it_wrong ) {
			$title = $title_param_cache;
			$sep = $sep_param_cache;
			$seplocation = $seplocation_param_cache;
			$meta = false;
		}

		static $title_cache = array();

		if ( isset( $title_cache[ $title ][ $sep ][ $seplocation ][ $meta ] ) )
			return $title_cache[ $title ][ $sep ][ $seplocation ][ $meta ];

		return $title_cache[ $title ][ $sep ][ $seplocation ][ $meta ] = $this->title( $title, $sep, $seplocation, array( 'meta' => $meta ) );
	}

	/**
	 * Caches current Image URL in static variable.
	 * Must be called inside the loop.
	 *
	 * @since 2.2.2
	 * @since 2.7.0 $get_id parameter has been added.
	 * @staticvar string $cache
	 *
	 * @return string The image URL.
	 */
	public function get_image_from_cache() {

		static $cache = null;

		return isset( $cache ) ? $cache : $cache = $this->get_image( $this->get_the_real_ID() );
	}

	/**
	 * Returns the current Twitter card type.
	 *
	 * @since 2.8.2
	 * @staticvar string $cache
	 *
	 * @return string The cached Twitter card.
	 */
	public function get_current_twitter_card_type() {

		static $cache = null;

		return isset( $cache ) ? $cache : $cache = $this->generate_twitter_card_type();
	}

	/**
	 * Renders the description meta tag.
	 *
	 * @since 1.3.0
	 * @uses $this->description_from_cache()
	 * @uses $this->detect_seo_plugins()
	 *
	 * @return string The description meta tag.
	 */
	public function the_description() {

		if ( $this->detect_seo_plugins() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_description_output' : string
		 * @since 2.3.0
		 * @since 2.7.0 : Added output within filter.
		 */
		$description = (string) \apply_filters( 'the_seo_framework_description_output', $this->description_from_cache(), $this->get_the_real_ID() );

		if ( $description )
			return '<meta name="description" content="' . \esc_attr( $description ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders og:description meta tag
	 *
	 * @since 1.3.0
	 * @uses $this->description_from_cache()
	 *
	 * @return string The Open Graph description meta tag.
	 */
	public function og_description() {

		if ( ! $this->use_og_tags() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_ogdescription_output' : string
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 */
		$description = (string) \apply_filters( 'the_seo_framework_ogdescription_output', $this->description_from_cache( true ), $this->get_the_real_ID() );

		if ( $description )
			return '<meta property="og:description" content="' . \esc_attr( $description ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders the OG locale meta tag.
	 *
	 * @since 1.0.0
	 *
	 * @return string The Open Graph locale meta tag.
	 */
	public function og_locale() {

		if ( ! $this->use_og_tags() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_oglocale_output' : string
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 */
		$locale = (string) \apply_filters( 'the_seo_framework_oglocale_output', $this->fetch_locale(), $this->get_the_real_ID() );

		if ( $locale )
			return '<meta property="og:locale" content="' . \esc_attr( $locale ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders the Open Graph title meta tag.
	 *
	 * @uses $this->title_from_cache()
	 * @since 2.0.3
	 *
	 * @return string The Open Graph title meta tag.
	 */
	public function og_title() {

		if ( ! $this->use_og_tags() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_ogtitle_output' : string
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 */
		$title = (string) \apply_filters( 'the_seo_framework_ogtitle_output', $this->title_from_cache( '', '', '', true ), $this->get_the_real_ID() );

		if ( $title )
			return '<meta property="og:title" content="' . \esc_attr( $title ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders the Open Graph type meta tag.
	 *
	 * @since 1.1.0
	 *
	 * @return string The Open Graph type meta tag.
	 */
	public function og_type() {

		if ( ! $this->use_og_tags() )
			return '';

		if ( $type = $this->get_og_type() )
			return '<meta property="og:type" content="' . \esc_attr( $type ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders Open Graph image meta tag.
	 *
	 * @since 1.3.0
	 * @since 2.6.0 : Added WooCommerce gallery images.
	 * @since 2.7.0 : Added image dimensions if found.
	 *
	 * @return string The Open Graph image meta tag.
	 */
	public function og_image() {

		if ( ! $this->use_og_tags() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_ogimage_output' : string|bool
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 *
		 * @NOTE: Use of this might cause incorrect meta since other functions
		 * depend on the image from cache.
		 *
		 * @todo Place in listener cache.
		 * @priority medium 2.8.0+
		 */
		$image = \apply_filters( 'the_seo_framework_ogimage_output', $this->get_image_from_cache(), $id = $this->get_the_real_ID() );

		/**
		 * Now returns empty string on false.
		 * @since 2.6.0
		 */
		if ( false === $image )
			return '';

		$image = (string) $image;

		/**
		 * Always output
		 * @since 2.1.1
		 */
		$output = '<meta property="og:image" content="' . \esc_attr( $image ) . '" />' . "\r\n";

		if ( $image ) {
			if ( ! empty( $this->image_dimensions[ $id ]['width'] ) && ! empty( $this->image_dimensions[ $id ]['height'] ) ) {
				$output .= '<meta property="og:image:width" content="' . \esc_attr( $this->image_dimensions[ $id ]['width'] ) . '" />' . "\r\n";
				$output .= '<meta property="og:image:height" content="' . \esc_attr( $this->image_dimensions[ $id ]['height'] ) . '" />' . "\r\n";
			}
		}

		//* Fetch Product images.
		$woocommerce_product_images = $this->render_woocommerce_product_og_image();

		return $output . $woocommerce_product_images;
	}

	/**
	 * Renders WooCommerce Product Gallery OG images.
	 *
	 * @since 2.6.0
	 * @since 2.7.0 : Added image dimensions if found.
	 * @since 2.8.0 : Checks for featured ID internally, rather than using a far-off cache.
	 *
	 * @return string The rendered OG Image.
	 */
	public function render_woocommerce_product_og_image() {

		$output = '';

		if ( $this->is_wc_product() ) {

			$images = $this->get_image_from_woocommerce_gallery();

			if ( $images && is_array( $images ) ) {

				$post_id = $this->get_the_real_ID();
				$post_manual_og = $this->get_custom_field( '_social_image_id', $post_id );
				$featured_id = $post_manual_og ? (int) $post_manual_og : (int) \get_post_thumbnail_id( $post_id );

				foreach ( $images as $id ) {

					if ( $id === $featured_id )
						continue;

					//* Parse 1500px url.
					$img = $this->parse_og_image( $id );

					if ( $img ) {
						$output .= '<meta property="og:image" content="' . \esc_attr( $img ) . '" />' . "\r\n";

						if ( ! empty( $this->image_dimensions[ $id ]['width'] ) && ! empty( $this->image_dimensions[ $id ]['height'] ) ) {
							$output .= '<meta property="og:image:width" content="' . \esc_attr( $this->image_dimensions[ $id ]['width'] ) . '" />' . "\r\n";
							$output .= '<meta property="og:image:height" content="' . \esc_attr( $this->image_dimensions[ $id ]['height'] ) . '" />' . "\r\n";
						}
					}
				}
			}
		}

		return $output;
	}

	/**
	 * Renders Open Graph sitename meta tag.
	 *
	 * @since 1.3.0
	 *
	 * @return string The Open Graph sitename meta tag.
	 */
	public function og_sitename() {

		if ( ! $this->use_og_tags() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_ogsitename_output' : string
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 */
		$sitename = (string) \apply_filters( 'the_seo_framework_ogsitename_output', \get_bloginfo( 'name' ), $this->get_the_real_ID() );

		if ( $sitename )
			return '<meta property="og:site_name" content="' . \esc_attr( $sitename ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders Open Graph URL meta tag.
	 *
	 * @since 1.3.0
	 * @uses $this->the_url_from_cache()
	 *
	 * @return string The Open Graph URL meta tag.
	 */
	public function og_url() {

		if ( $this->use_og_tags() )
			return '<meta property="og:url" content="' . $this->the_url_from_cache() . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders the Twitter Card type meta tag.
	 *
	 * @since 2.2.2
	 *
	 * @return string The Twitter Card meta tag.
	 */
	public function twitter_card() {

		if ( ! $this->use_twitter_tags() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_twittercard_output' : string
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 */
		$card = (string) \apply_filters( 'the_seo_framework_twittercard_output', $this->get_current_twitter_card_type(), $this->get_the_real_ID() );

		if ( $card )
			return '<meta name="twitter:card" content="' . \esc_attr( $card ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders the Twitter Site meta tag.
	 *
	 * @since 2.2.2
	 *
	 * @return string The Twitter Site meta tag.
	 */
	public function twitter_site() {

		if ( ! $this->use_twitter_tags() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_twittersite_output' : string
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 */
		$site = (string) \apply_filters( 'the_seo_framework_twittersite_output', $this->get_option( 'twitter_site' ), $this->get_the_real_ID() );

		if ( $site )
			return '<meta name="twitter:site" content="' . \esc_attr( $site ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders The Twitter Creator meta tag.
	 * If no Twitter Site is found, it will render the Twitter Site ID meta tag.
	 *
	 * @since 2.2.2
	 *
	 * @return string The Twitter Creator or Twitter Site ID meta tag.
	 */
	public function twitter_creator() {

		if ( ! $this->use_twitter_tags() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_twittercreator_output' : string
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 */
		$creator = (string) \apply_filters( 'the_seo_framework_twittercreator_output', $this->get_option( 'twitter_creator' ), $this->get_the_real_ID() );

		if ( $creator ) {
			/**
			 * Return site:id instead of creator is no twitter:site is found.
			 * Per Twitter requirements.
			 */
			if ( $this->get_option( 'twitter_site' ) ) {
				return '<meta name="twitter:site:id" content="' . \esc_attr( $creator ) . '" />' . "\r\n";
			} else {
				return '<meta name="twitter:creator" content="' . \esc_attr( $creator ) . '" />' . "\r\n";
			}
		}

		return '';
	}

	/**
	 * Renders Twitter Title meta tag.
	 *
	 * @uses $this->title_from_cache()
	 * @since 2.2.2
	 *
	 * @return string The Twitter Title meta tag.
	 */
	public function twitter_title() {

		if ( ! $this->use_twitter_tags() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_twittertitle_output' : string
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 */
		$title = (string) \apply_filters( 'the_seo_framework_twittertitle_output', $this->title_from_cache( '', '', '', true ), $this->get_the_real_ID() );

		if ( $title )
			return '<meta name="twitter:title" content="' . \esc_attr( $title ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders Twitter Description meta tag.
	 *
	 * @uses $this->description_from_cache()
	 * @since 2.2.2
	 *
	 * @return string The Twitter Descritpion meta tag.
	 */
	public function twitter_description() {

		if ( ! $this->use_twitter_tags() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_twitterdescription_output' : string
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 */
		$description = (string) \apply_filters( 'the_seo_framework_twitterdescription_output', $this->description_from_cache( true ), $this->get_the_real_ID() );

		if ( $description )
			return '<meta name="twitter:description" content="' . \esc_attr( $description ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders Twitter Image meta tag.
	 *
	 * @since 2.2.2
	 *
	 * @return string The Twitter Image meta tag.
	 */
	public function twitter_image() {

		if ( ! $this->use_twitter_tags() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_twitterimage_output' : string|bool
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 */
		$image = (string) \apply_filters( 'the_seo_framework_twitterimage_output', $this->get_image_from_cache(), $id = $this->get_the_real_ID() );

		$output = '';

		if ( $image ) {
			$output = '<meta name="twitter:image" content="' . \esc_attr( $image ) . '" />' . "\r\n";

			if ( ! empty( $this->image_dimensions[ $id ]['width'] ) && ! empty( $this->image_dimensions[ $id ]['height'] ) ) {
				$output .= '<meta name="twitter:image:width" content="' . \esc_attr( $this->image_dimensions[ $id ]['width'] ) . '" />' . "\r\n";
				$output .= '<meta name="twitter:image:height" content="' . \esc_attr( $this->image_dimensions[ $id ]['height'] ) . '" />' . "\r\n";
			}
		}

		return $output;
	}

	/**
	 * Renders Facebook Author meta tag.
	 *
	 * @since 2.2.2
	 * @since 2.8.0 : Return empty on og:type 'website' or 'product'
	 *
	 * @return string The Facebook Author meta tag.
	 */
	public function facebook_author() {

		if ( ! $this->use_facebook_tags() )
			return '';

		if ( in_array( $this->get_og_type(), array( 'website', 'product' ), true ) )
			return '';

		/**
		 * Applies filters 'the_seo_framework_facebookauthor_output' : string
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 */
		$author = (string) \apply_filters( 'the_seo_framework_facebookauthor_output', $this->get_option( 'facebook_author' ), $this->get_the_real_ID() );

		if ( $author )
			return '<meta property="article:author" content="' . \esc_attr( \esc_url_raw( $author ) ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders Facebook Publisher meta tag.
	 *
	 * @since 2.2.2
	 *
	 * @return string The Facebook Publisher meta tag.
	 */
	public function facebook_publisher() {

		if ( ! $this->use_facebook_tags() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_facebookpublisher_output' : string
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 */
		$publisher = (string) \apply_filters( 'the_seo_framework_facebookpublisher_output', $this->get_option( 'facebook_publisher' ), $this->get_the_real_ID() );

		if ( $publisher )
			return '<meta property="article:publisher" content="' . \esc_attr( \esc_url_raw( $publisher ) ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders Facebook App ID meta tag.
	 *
	 * @since 2.2.2
	 *
	 * @return string The Facebook App ID meta tag.
	 */
	public function facebook_app_id() {

		if ( ! $this->use_facebook_tags() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_facebookappid_output' : string
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 */
		$app_id = (string) \apply_filters( 'the_seo_framework_facebookappid_output', $this->get_option( 'facebook_appid' ), $this->get_the_real_ID() );

		if ( $app_id )
			return '<meta property="fb:app_id" content="' . \esc_attr( $app_id ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders Article Publishing Time meta tag.
	 *
	 * @since 2.2.2
	 * @since 2.8.0 Returns empty on product pages.
	 *
	 * @return string The Article Publishing Time meta tag.
	 */
	public function article_published_time() {

		//* Don't do anything if it's not a page or post.
		if ( false === $this->is_singular() )
			return '';

		if ( 'product' === $this->get_og_type() )
			return '';

		if ( $this->is_front_page() ) {
			//* If it's the frontpage, but the option is disabled, don't do anything.
			if ( ! $this->get_option( 'home_publish_time' ) )
				return '';
		} else {
			//* If it's a post, but the option is disabled, don't do anything.
			if ( $this->is_single() && ! $this->get_option( 'post_publish_time' ) )
				return '';

			//* If it's a page, but the option is disabled, don't do anything.
			if ( $this->is_page() && ! $this->get_option( 'page_publish_time' ) )
				return '';
		}

		$id = $this->get_the_real_ID();

		/**
		 * Applies filters 'the_seo_framework_publishedtime_output' : string
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 */
		$time = (string) \apply_filters( 'the_seo_framework_publishedtime_output', \get_the_date( 'Y-m-d', $id ), $id );

		if ( $time )
			return '<meta property="article:published_time" content="' . \esc_attr( $time ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders Article Modified Time meta tag.
	 * Also renders the Open Graph Updated Time meta tag if Open Graph tags are enabled.
	 *
	 * @since 2.2.2
	 * @since 2.7.0 Listens to $this->get_the_real_ID() instead of WordPress Core ID determination.
	 * @since 2.8.0 Returns empty on product pages.
	 *
	 * @return string The Article Modified Time meta tag, and optionally the Open Graph Updated Time.
	 */
	public function article_modified_time() {

		// Don't do anything if it's not a page or post.
		if ( false === $this->is_singular() )
			return '';

		if ( 'product' === $this->get_og_type() )
			return '';

		if ( $this->is_front_page() ) {
			//* If it's the frontpage, but the option is disabled, don't do anything.
			if ( ! $this->get_option( 'home_modify_time' ) )
				return '';
		} else {
			//* If it's a post, but the option is disabled, don't do anyhting.
			if ( $this->is_single() && ! $this->get_option( 'post_modify_time' ) )
				return '';

			//* If it's a page, but the option is disabled, don't do anything.
			if ( $this->is_page() && ! $this->get_option( 'page_modify_time' ) )
				return '';
		}

		$id = $this->get_the_real_ID();

		/**
		 * Applies filters 'the_seo_framework_modifiedtime_output' : string
		 * @since 2.3.0
		 * @since 2.7.0 Added output within filter.
		 */
		$time = (string) \apply_filters( 'the_seo_framework_modifiedtime_output', \get_post_modified_time( 'Y-m-d', false, $id, false ), $id );

		if ( $time ) {
			$output = '<meta property="article:modified_time" content="' . \esc_attr( $time ) . '" />' . "\r\n";

			if ( $this->use_og_tags() )
				$output .= '<meta property="og:updated_time" content="' . \esc_attr( $time ) . '" />' . "\r\n";

			return $output;
		}

		return '';
	}

	/**
	 * Renders Canonical URL meta tag.
	 *
	 * @since 2.0.6
	 * @uses $this->the_url_from_cache()
	 *
	 * @return string The Canonical URL meta tag.
	 */
	public function canonical() {

		/**
		 * Applies filters the_seo_framework_output_canonical : Don't output canonical if false.
		 * @since 2.4.2
		 *
		 * @deprecated
		 * @since 2.7.0
		 */
		if ( true !== \apply_filters( 'the_seo_framework_output_canonical', true, $this->get_the_real_ID() ) ) {
			$this->_deprecated_filter( 'the_seo_framework_output_canonical', '2.7.0', "add_filter( 'the_seo_framework_rel_canonical_output', '__return_empty_string' );" );
			return '';
		}

		/**
		 * Applies filters 'the_seo_framework_rel_canonical_output' : Change canonical URL output.
		 * @since 2.6.5
		 */
		$url = (string) \apply_filters( 'the_seo_framework_rel_canonical_output', $this->the_url_from_cache(), $this->get_the_real_ID() );

		/**
		 * @since 2.7.0 Listens to the second filter.
		 */
		if ( $url )
			return '<link rel="canonical" href="' . $url . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders LD+JSON Schema.org scripts.
	 *
	 * @uses $this->render_ld_json_scripts()
	 *
	 * @since 1.2.0
	 * @return string The LD+json Schema.org scripts.
	 */
	public function ld_json() {

		//* Don't output on Search, 404 or preview.
		if ( $this->is_search() || $this->is_404() || $this->is_preview() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_ldjson_scripts' : string
		 * @since 2.6.0
		 */
		$json = (string) \apply_filters( 'the_seo_framework_ldjson_scripts', $this->render_ld_json_scripts(), $this->get_the_real_ID() );

		return $json;
	}

	/**
	 * Renders Google Site Verification Code meta tag.
	 *
	 * @since 2.2.4
	 *
	 * @return string The Google Site Verification code meta tag.
	 */
	public function google_site_output() {

		/**
		 * Applies filters 'the_seo_framework_googlesite_output' : string
		 * @since 2.6.0
		 */
		$code = (string) \apply_filters( 'the_seo_framework_googlesite_output', $this->get_option( 'google_verification' ), $this->get_the_real_ID() );

		if ( $code )
			return '<meta name="google-site-verification" content="' . \esc_attr( $code ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders Bing Site Verification Code meta tag.
	 *
	 * @since 2.2.4
	 *
	 * @return string The Bing Site Verification Code meta tag.
	 */
	public function bing_site_output() {

		/**
		 * Applies filters 'the_seo_framework_bingsite_output' : string
		 * @since 2.6.0
		 */
		$code = (string) \apply_filters( 'the_seo_framework_bingsite_output', $this->get_option( 'bing_verification' ), $this->get_the_real_ID() );

		if ( $code )
			return '<meta name="msvalidate.01" content="' . \esc_attr( $code ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders Yandex Site Verification code meta tag.
	 *
	 * @since 2.6.0
	 *
	 * @return string The Yandex Site Verification code meta tag.
	 */
	public function yandex_site_output() {

		/**
		 * Applies filters 'the_seo_framework_yandexsite_output' : string
		 * @since 2.6.0
		 */
		$code = (string) \apply_filters( 'the_seo_framework_yandexsite_output', $this->get_option( 'yandex_verification' ), $this->get_the_real_ID() );

		if ( $code )
			return '<meta name="yandex-verification" content="' . \esc_attr( $code ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders Pinterest Site Verification code meta tag.
	 *
	 * @since 2.5.2
	 *
	 * @return string The Pinterest Site Verification code meta tag.
	 */
	public function pint_site_output() {

		/**
		 * Applies filters 'the_seo_framework_pintsite_output' : string
		 * @since 2.6.0
		 */
		$code = (string) \apply_filters( 'the_seo_framework_pintsite_output', $this->get_option( 'pint_verification' ), $this->get_the_real_ID() );

		if ( $code )
			return '<meta name="p:domain_verify" content="' . \esc_attr( $code ) . '" />' . "\r\n";

		return '';
	}

	/**
	 * Renders Robots meta tags.
	 * Returns early if blog isn't public. WordPress Core will then output the meta tags.
	 *
	 * @since 2.0.0
	 *
	 * @return string The Robots meta tags.
	 */
	public function robots() {

		//* Don't do anything if the blog isn't set to public.
		if ( false === $this->is_blog_public() )
			return '';

		/**
		 * Applies filters 'the_seo_framework_robots_meta' : array
		 * @since 2.6.0
		 */
		$meta = (array) \apply_filters( 'the_seo_framework_robots_meta', $this->robots_meta(), $this->get_the_real_ID() );

		if ( empty( $meta ) )
			return '';

		return sprintf( '<meta name="robots" content="%s" />' . "\r\n", implode( ',', $meta ) );
	}

	/**
	 * Renders Shortlink meta tag
	 *
	 * @since 2.2.2
	 * @uses $this->get_shortlink()
	 *
	 * @return string The Shortlink meta tag.
	 */
	public function shortlink() {

		/**
		 * Applies filters 'the_seo_framework_shortlink_output' : string
		 * @since 2.6.0
		 */
		$url = (string) \apply_filters( 'the_seo_framework_shortlink_output', $this->get_shortlink(), $this->get_the_real_ID() );

		if ( $url )
			return sprintf( '<link rel="shortlink" href="%s" />' . "\r\n", $url );

		return '';
	}

	/**
	 * Renders Prev/Next Paged URL meta tags.
	 *
	 * @since 2.2.2
	 * @uses $this->get_paged_url()
	 *
	 * @return string The Prev/Next Paged URL meta tags.
	 */
	public function paged_urls() {

		$id = $this->get_the_real_ID();

		/**
		 * Applies filters 'the_seo_framework_paged_url_output' : array
		 * @since 2.6.0
		 */
		$next = (string) \apply_filters( 'the_seo_framework_paged_url_output_next', $this->get_paged_url( 'next' ), $id );

		/**
		 * Applies filters 'the_seo_framework_paged_url_output' : array
		 * @since 2.6.0
		 */
		$prev = (string) \apply_filters( 'the_seo_framework_paged_url_output_prev', $this->get_paged_url( 'prev' ), $id );

		$output = '';

		if ( $prev )
			$output .= sprintf( '<link rel="prev" href="%s" />' . "\r\n", $prev );

		if ( $next )
			$output .= sprintf( '<link rel="next" href="%s" />' . "\r\n", $next );

		return $output;
	}

	/**
	 * Determines whether we can use Open Graph tags.
	 *
	 * @since 2.6.0
	 * @staticvar bool $cache
	 *
	 * @return bool
	 */
	public function use_og_tags() {

		static $cache = null;

		if ( isset( $cache ) )
			return $cache;

		return $cache = $this->is_option_checked( 'og_tags' ) && false === $this->detect_og_plugin();
	}

	/**
	 * Determines whether we can use Facebook tags.
	 *
	 * @since 2.6.0
	 * @staticvar bool $cache
	 *
	 * @return bool
	 */
	public function use_facebook_tags() {

		static $cache = null;

		if ( isset( $cache ) )
			return $cache;

		return $cache = $this->is_option_checked( 'facebook_tags' );
	}

	/**
	 * Determines whether we can use Twitter tags.
	 *
	 * @since 2.6.0
	 * @since 2.8.2 : Now also considers Twitter card type output.
	 * @staticvar bool $cache
	 *
	 * @return bool
	 */
	public function use_twitter_tags() {

		static $cache = null;

		if ( isset( $cache ) )
			return $cache;

		return $cache = $this->is_option_checked( 'twitter_tags' ) && false === $this->detect_twitter_card_plugin() && $this->get_current_twitter_card_type();
	}

	/**
	 * Determines whether we can use Google+ tags.
	 *
	 * @since 2.6.0
	 * @staticvar bool $cache
	 * @NOTE: not used.
	 *
	 * @return bool
	 */
	public function use_googleplus_tags() {

		return false;

		static $cache = null;

		if ( isset( $cache ) )
			return $cache;

		return $cache = $this->is_option_checked( 'googleplus_tags' );
	}
}


text:
/**
 * Built-in Log Configuration
 * (sails.config.log)
 *
 * Configure the log level for your app, as well as the transport
 * (Underneath the covers, Sails uses Winston for logging, which
 * allows for some pretty neat custom transports/adapters for log messages)
 *
 * For more information on the Sails logger, check out:
 * http://sailsjs.org/#!/documentation/concepts/Logging
 */

module.exports.log = {

  /***************************************************************************
  *                                                                          *
  * Valid `level` configs: i.e. the minimum log level to capture with        *
  * sails.log.*()                                                            *
  *                                                                          *
  * The order of precedence for log levels from lowest to highest is:        *
  * silly, verbose, info, debug, warn, error                                 *
  *                                                                          *
  * You may also set the level to "silent" to suppress all logs.             *
  *                                                                          *
  ***************************************************************************/

   level: 'info'
   //level: 'silly'
   //level: 'error'

};

//
//var winston = require('winston');
//var customLogger = new winston.Logger();
//
//// A console transport logging debug and above.
//customLogger.add(winston.transports.Console, {
//  //level: 'error',
//  //level: 'silly',
//  level: 'debug',
//  colorize: true
//});
//
//// A file based transport logging only errors formatted as json.
//customLogger.add(winston.transports.File, {
//  level: 'error',
//  filename: 'filename.log',
//  json: true
////});
//
//module.exports.log = {
//  // Pass in our custom logger, and pass all log levels through.
//  custom: customLogger,
//  level: 'silly',
//
//  // Disable captain's log so it doesn't prefix or stringify our meta data.
//  inspect: false
//};

redpajama_set_name: RedPajamaGithub


text:
module Libvirt
  module Exceptions
    autoload :MissingLib, 'libvirt/exceptions/missing_lib'
    autoload :InvalidFunction, 'libvirt/exceptions/invalid_function'
    autoload :NoReturnParameter, 'libvirt/exceptions/no_return_parameter'
    autoload :WrongCall, 'libvirt/exceptions/wrong_call'
  end
end


text:
package com.cisco.axl.api._8;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for GetOSVersionRes complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="GetOSVersionRes">
 *   <complexContent>
 *     <extension base="{http://www.cisco.com/AXL/API/8.0}APIResponse">
 *       <sequence>
 *         <element name="return">
 *           <complexType>
 *             <complexContent>
 *               <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *                 <sequence>
 *                   <element name="os" type="{http://www.cisco.com/AXL/API/8.0}XOSVersion"/>
 *                 </sequence>
 *               </restriction>
 *             </complexContent>
 *           </complexType>
 *         </element>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GetOSVersionRes", propOrder = {
    "_return"
})
public class GetOSVersionRes
    extends APIResponse
{

    @XmlElement(name = "return", required = true)
    protected GetOSVersionRes.Return _return;

    /**
     * Gets the value of the return property.
     *
     * @return
     *     possible object is
     *     {@link GetOSVersionRes.Return }
     *
     */
    public GetOSVersionRes.Return getReturn() {
        return _return;
    }

    /**
     * Sets the value of the return property.
     *
     * @param value
     *     allowed object is
     *     {@link GetOSVersionRes.Return }
     *
     */
    public void setReturn(GetOSVersionRes.Return value) {
        this._return = value;
    }

    /**
     *
Java class for anonymous complex type.
     *
     *
The following schema fragment specifies the expected content contained within this class.
     *
     *

     * <complexType>
     *   <complexContent>
     *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
     *       <sequence>
     *         <element name="os" type="{http://www.cisco.com/AXL/API/8.0}XOSVersion"/>
     *       </sequence>
     *     </restriction>
     *   </complexContent>
     * </complexType>
     *

     *
     *
     */
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "os"
    })
    public static class Return {

        @XmlElement(required = true)
        protected XOSVersion os;

        /**
         * Gets the value of the os property.
         *
         * @return
         *     possible object is
         *     {@link XOSVersion }
         *
         */
        public XOSVersion getOs() {
            return os;
        }

        /**
         * Sets the value of the os property.
         *
         * @param value
         *     allowed object is
         *     {@link XOSVersion }
         *
         */
        public void setOs(XOSVersion value) {
            this.os = value;
        }

    }

}


text:
module Ubiquitously
  module Command
    class Base
      class << self
        def run(args)
          new(args).run
        end
      end

      attr_accessor :services, :attributes

      def write(to, content = "")
        File.open(to, "w+") { |file| file.puts content }
      end

      def configure(folder)
        Dir.mkdir(folder) unless File.exists?(folder)
        secrets_path     = File.join(folder, "secrets.yml")
        tokens_path      = File.join(folder, "tokens.yml")

        # usernames and passwords for post services
        unless File.exists?(secrets_path)
          secrets = "# #{secrets_path}, in your home directory\n"
          secrets << "# write your username and passwords for the different services\n"
          secrets << "# as necessary.\n\n"
          Ubiquitously.services.each do |service|
            secrets << "#{service}:\n"
            secrets << "  key: your_username\n"
            secrets << "  secret: your_password\n"
          end
          write(secrets_path, secrets)
          system("open", secrets_path)
          puts "Please configure your service username and passwords and rerun your command."
          exit
        end

        Ubiquitously.configure(secrets_path)

        # oauth keys and secrets from services
        unless File.exists?(tokens_path)
          tokens = "# #{tokens_path}, in your home directory\n"
          tokens << "# Get app key/secrets from the oauth providers below\n"
          tokens << "# and fill them out as desired.\n\n"
          tokens << "services:\n"
          Passport.services.each do |service|
            tokens << "  #{service}:\n"
            tokens << "    key: app_key\n"
            tokens << "    secrets: app_secret\n"
          end
          write(tokens_path, tokens)
          system("open", tokens_path)
          puts "Please configure your oauth keys and secrets and rerun your command."
          exit
        end

        Passport.configure(tokens_path)
      end

      def main_folder
        File.expand_path("~/.u.me")
      end

      def show
        tmp = File.join(main_folder, "post.yml")
        if File.exists?(tmp)
          post = IO.read(tmp)
        else
          post = ""
          post << "services: \n"
          post << "url: \n"
          post << "title: \n"
          post << "description: \n"
          post << "tags: \n"
          write(tmp, post)
        end
        system("open", tmp)
        require 'timeout'
        begin
          Timeout::timeout(30) {
            puts "Will timeout in 30 seconds. Press Enter when you're ready."
            STDIN.gets.chomp
            self.attributes = YAML.load_file(tmp).symbolize_keys
            #File.delete(tmp) if File.exists?(tmp)
            # Something that should be interrupted if it takes too much time...
          }
        rescue Exception => e
          puts e.inspect
          puts "Resubmit post with same command.  Finished process executing to clean things up."
          exit
        end

      end

      def initialize(args)
        configure(main_folder)
        self.services = []
        self.attributes = {}
        show if args.blank?
        self.services << args.shift while args.length > 0 && args.first !~ /^-/
        self.services << attributes.delete(:services) if attributes.has_key?(:services)
        self.attributes[:title] = self.services.pop unless Ubiquitously.include?(self.services.last)
        self.attributes = parse_options(args, attributes)

        self.attributes.each do |key, value|
          self.send("#{key.to_s}=", value) if self.respond_to?(key)
        end
      end

      def parse_options(attributes)

      end

      def run

      end
    end
  end
end


text:
#ifndef __LINUX_PACKET_POOL_MANAGER_HEADER_INCLUDED_DEFINED__
#define __LINUX_PACKET_POOL_MANAGER_HEADER_INCLUDED_DEFINED__

#include "LPacketBase.h"
#include "LFixLenCircleBuf.h"
#include "LErrorWriter.h"

extern LErrorWriter g_ErrorWriter;

typedef struct _Packet_Pool_Desc
{
	unsigned short usPacketLen;
	unsigned int unInitSize;
	unsigned int unMaxAllocSize;
	//_Packet_Pool_Desc()
	//{
	//	usPacketLen		= 0;
	//	unInitSize 		= 0;
	//	unMaxAllocSize 	= 0;
	//}
}t_Packet_Pool_Desc;

template<class T> class LPacketPoolManager
{
public:
	LPacketPoolManager()
	{
		m_usMinPacketSize 		= 0;
		m_usMaxPacketSize 		= 0;
		m_unPacketLenTypeCount 	= 0;
		m_parrPacketPoolDesc 	= NULL;
		m_parrFixLenCircleBuf 	= NULL;
		m_pGlobalPoolManager 	= NULL;
		m_bEnableAllocBuf 		= false;
	}
	~LPacketPoolManager()
	{
	}

	void ReleasePacketPoolManagerResource()
	{
		if (m_parrPacketPoolDesc != NULL)
		{
			delete[] m_parrPacketPoolDesc;
		}
		if (m_parrFixLenCircleBuf != NULL)
		{
			for (unsigned int unIndex = 0; unIndex < m_unPacketLenTypeCount; ++unIndex)
			{
				T* p = NULL;
				while (1)
				{
					E_Circle_Error error = m_parrFixLenCircleBuf[unIndex].GetOneItem((char*)&p, sizeof(T*));
					if (error == E_Circle_Buf_Input_Buf_Null || error == E_Circle_Buf_Input_Buf_Not_Enough_Len || error == E_Circle_Buf_Is_Empty || error == E_Circle_Buf_Uninitialized)
					{
						break;
					}
					else
					{
						if (p->DecrementRefCountAndResultIsTrue())
						{
							delete p;
						}
						p = NULL;
					}
				}
			}
			delete[] m_parrFixLenCircleBuf;
		}
	}

	void SetReuqestPoolFromGlobalManager(LPacketPoolManager<T>* pGlobalPoolManager)
	{
		m_pGlobalPoolManager = pGlobalPoolManager;
	}
	void SetEnableAlloc(bool bEnableAllocBuf)
	{
		m_bEnableAllocBuf = bEnableAllocBuf;
	}
public:
	bool Initialize(t_Packet_Pool_Desc tpacketDesc[], size_t sArraySize)
	{
		if (sArraySize == 0)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::Initialize, sArraySize == 0\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return false;
		}
		if (OrderAndSetPacketDesc(tpacketDesc, sArraySize) == false)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::Initialize, OrderAndSetPacketDesc Failed\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return false;
		}
		m_parrFixLenCircleBuf = new LFixLenCircleBuf[m_unPacketLenTypeCount];
		if (m_parrFixLenCircleBuf == NULL)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::Initialize, m_parrFixLenCircleBuf == NULL\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return false;
		}
		for (unsigned int unIndex = 0; unIndex < m_unPacketLenTypeCount; ++unIndex)
		{
			if (!m_parrFixLenCircleBuf[unIndex].Initialize(sizeof(T*), m_parrPacketPoolDesc[unIndex].unMaxAllocSize))
			{
				char szError[512];
				sprintf(szError, "LPacketPoolManager::Initialize, m_parrFixLenCircleBuf[unIndex].Initialize Failed\n");
				g_ErrorWriter.WriteError(szError, strlen(szError));
				return false;
			}
			for (unsigned int unInnerIndex = 0; unInnerIndex < m_parrPacketPoolDesc[unIndex].unInitSize; ++unInnerIndex)
			{
				T* pTemp = new T(m_parrPacketPoolDesc[unIndex].usPacketLen);
				if (pTemp == NULL)
				{
					char szError[512];
					sprintf(szError, "LPacketPoolManager::Initialize, pTemp == NULL\n");
					g_ErrorWriter.WriteError(szError, strlen(szError));
					return false;
				}
				if (m_parrFixLenCircleBuf[unIndex].AddItems((char*)&pTemp, 1) != 0)
				{
					char szError[512];
					sprintf(szError, "LPacketPoolManager::Initialize, m_parrFixLenCircleBuf[unIndex].AddItems\n");
					g_ErrorWriter.WriteError(szError, strlen(szError));
					delete pTemp;
					return false;
				}
			}
		}
		return true;
	}

	T* RequestOnePacket(unsigned short usPacketLen)
	{
		T* pTemp = NULL;
		int nSelectedIndex = SelectIndexForPacketLen(usPacketLen);
		if (nSelectedIndex == -1)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::RequestOnePacket, nSelectedIndex == -1\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return NULL;
		}

			if (m_parrFixLenCircleBuf[nSelectedIndex].GetOneItem((char*)&pTemp, sizeof(T*)) == E_Circle_Buf_No_Error)
			{
				return pTemp;
			}

		return pTemp;
	}
	int Request(LFixLenCircleBuf* pFixLenCircleBuf, unsigned int unExpecttedCount, unsigned short usPoolItemLen)
	{
		if (pFixLenCircleBuf == NULL)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::Request, pFixLenCircleBuf == NULL\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return 0;
		}
		if (unExpecttedCount == 0)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::Request, unExpecttedCount == 0\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return 0;
		}
		int nSelectedIndex = SelectIndexForPacketLenEqual(usPoolItemLen);
		if (nSelectedIndex == -1)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::Request, nSelectedIndex == -1\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return 0;
		}
		int nGettedCount = m_parrFixLenCircleBuf[nSelectedIndex].RequestItems(pFixLenCircleBuf, unExpecttedCount);
		return nGettedCount;
	}
	bool FreeOneItemToPool(T* pValue, unsigned short usExtractBufLen)
	{
		int nSelectIndex = SelectIndexForPacketLenEqual(usExtractBufLen);
		if (nSelectIndex < 0)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::FreeOneItemToPool, nSelectIndex < 0\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return false;
		}
		if (m_parrFixLenCircleBuf[nSelectIndex].AddItems((char*)&pValue, 1) != E_Circle_Buf_No_Error)
		{
			return false;
		}
		return true;
	}
	bool CommitToAnother(LPacketPoolManager<T> *pPool, unsigned short usPoolSize)
	{
		if (pPool == NULL)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::CommitToAnother, pPool == NULL\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return false;
		}
		int nSelectIndex = SelectIndexForPacketLenEqual(usPoolSize);
		if (nSelectIndex < 0)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::CommitToAnother, nSelectIndex < 0\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return false;
		}
		unsigned int unCanAddMaxItemCountToIt = 0;
		LFixLenCircleBuf* pDestBuf = pPool->GetFixLenCircleBuf(usPoolSize, unCanAddMaxItemCountToIt);
		if (pDestBuf == NULL)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::CommitToAnother, pDestBuf == NULL\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return false;
		}
		if (!m_parrFixLenCircleBuf[nSelectIndex].CopyAllItemsToOtherFixLenCircleBuf(pDestBuf))
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::CommitToAnother, CopyAllItemsToOtherFixLenCircleBuf Failed\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return false;
		}
		return true;
	}
	LFixLenCircleBuf* GetFixLenCircleBuf(unsigned short usPoolSize, unsigned int& unMaxCanAddtoPoolCount)
	{
		int nSelectIndex = SelectIndexForPacketLenEqual(usPoolSize);
		if (nSelectIndex == -1)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::GetFixLenCircleBuf, nSelectIndex < 0\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return NULL;
		}
		unMaxCanAddtoPoolCount = m_parrPacketPoolDesc[nSelectIndex].unMaxAllocSize - 1;
		return &m_parrFixLenCircleBuf[nSelectIndex];
	}
protected:
	bool OrderAndSetPacketDesc(t_Packet_Pool_Desc tPacketDesc[], size_t sArraySize)
	{
		unsigned int unArraySize = sArraySize;
		if (unArraySize == 0)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::OrderAndSetPacketDesc, unArraySize == 0\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return false;
		}

		for (unsigned int unIndex = 0; unIndex < unArraySize; ++unIndex)
		{
			if (tPacketDesc[unIndex].usPacketLen == 0 || tPacketDesc[unIndex].unMaxAllocSize == 0)
			{
				char szError[512];
				sprintf(szError, "LPacketPoolManager::OrderAndSetPacketDesc, Error Len \n");
				g_ErrorWriter.WriteError(szError, strlen(szError));
				return false;
			}
		}
		for (unsigned int unIndex = 0; unIndex < unArraySize; ++unIndex)
		{
			for (unsigned int unInnerIndex = unIndex + 1; unInnerIndex < unArraySize; ++unInnerIndex)
			{
				if (tPacketDesc[unIndex].usPacketLen == tPacketDesc[unInnerIndex].usPacketLen)
				{
					char szError[512];
					sprintf(szError, "LPacketPoolManager::OrderAndSetPacketDesc, Exist Same Length packet size \n");
					g_ErrorWriter.WriteError(szError, strlen(szError));
					return false;
				}
			}
		}
		m_unPacketLenTypeCount = unArraySize;
		for (unsigned int unIndex = 0; unIndex < m_unPacketLenTypeCount; ++unIndex)
		{
			for (unsigned int unInnerIndex = unIndex + 1; unInnerIndex < m_unPacketLenTypeCount; ++unInnerIndex)
			{
				if (tPacketDesc[unIndex].usPacketLen > tPacketDesc[unInnerIndex].usPacketLen)
				{
					t_Packet_Pool_Desc tppd 	= tPacketDesc[unIndex];
					tPacketDesc[unIndex] 		= tPacketDesc[unInnerIndex];
					tPacketDesc[unInnerIndex] 	= tPacketDesc[unIndex];
				}
			}
		}

		m_parrPacketPoolDesc = new t_Packet_Pool_Desc[m_unPacketLenTypeCount];
		if (m_parrPacketPoolDesc == NULL)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::OrderAndSetPacketDesc, m_parrPacketPoolDesc == NULL\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return false;
		}
		memcpy(m_parrPacketPoolDesc, tPacketDesc, sizeof(t_Packet_Pool_Desc) * m_unPacketLenTypeCount);

		m_usMinPacketSize 		= m_parrPacketPoolDesc[0].usPacketLen;
		m_usMaxPacketSize 		= m_parrPacketPoolDesc[m_unPacketLenTypeCount - 1].usPacketLen;

		return true;
	}
	int SelectIndexForPacketLen(unsigned short usPacketLen)
	{
		if (usPacketLen > m_usMaxPacketSize)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::SelectIndexForPacketLen, usPacketLen > m_usMaxPacketSize\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return -1;
		}
		for (unsigned int unIndex = 0; unIndex < m_unPacketLenTypeCount; ++unIndex)
		{
			if (usPacketLen <= m_parrPacketPoolDesc[unIndex].usPacketLen)
			{
				return unIndex;
			}
		}
		return -1;
	}
	int SelectIndexForPacketLenEqual(unsigned short usPacketLen)
	{
		if (usPacketLen > m_usMaxPacketSize)
		{
			char szError[512];
			sprintf(szError, "LPacketPoolManager::SelectIndexForPacketLenEqual, usPacketLen > m_usMaxPacketSize\n");
			g_ErrorWriter.WriteError(szError, strlen(szError));
			return -1;
		}
		for (unsigned int unIndex = 0; unIndex < m_unPacketLenTypeCount; ++unIndex)
		{
			if (usPacketLen == m_parrPacketPoolDesc[unIndex].usPacketLen)
			{
				return unIndex;
			}
		}
		return -1;

	}
public:
	bool CommitAllLocalPacketPoolToGlobalPacketPool()
	{
		if (m_pGlobalPoolManager)
		{
			return false;
		}
		for (unsigned int unIndex = 0; unIndex < m_unPacketLenTypeCount; ++unIndex)
		{
			if (!CommitToAnother(m_pGlobalPoolManager, m_parrPacketPoolDesc[unIndex].usPacketLen))
			{
				char szError[512];
				sprintf(szError, "LPacketPoolManager::CommitAllLocalPacketPoolToGlobalPacketPool, CommitToAnother Failed, PacketLen:%hd\n", m_parrPacketPoolDesc[unIndex].usPacketLen);
				g_ErrorWriter.WriteError(szError, strlen(szError));
			}
		}
		return true;
	}
private:
	unsigned int m_unPacketLenTypeCount;
	unsigned short m_usMinPacketSize;
	unsigned short m_usMaxPacketSize;
	t_Packet_Pool_Desc* m_parrPacketPoolDesc;
	LFixLenCircleBuf* m_parrFixLenCircleBuf;
	LPacketPoolManager<T>* m_pGlobalPoolManager;
	bool m_bEnableAllocBuf;
};

#endif


text:
package com.hazelcast.internal.management.request;

import com.eclipsesource.json.JsonObject;
import com.hazelcast.config.Config;
import com.hazelcast.config.ConfigXmlGenerator;
import com.hazelcast.internal.management.ManagementCenterService;
import com.hazelcast.util.JsonUtil;

/**
 * Request for fetching member XML configuration.
 */
public class MemberConfigRequest implements ConsoleRequest {

    public MemberConfigRequest() {
    }

    @Override
    public int getType() {
        return ConsoleRequestConstants.REQUEST_TYPE_MEMBER_CONFIG;
    }

    @Override
    public Object readResponse(JsonObject json) {
        return JsonUtil.getString(json, "configXmlString", "Error while reading response " + MemberConfigRequest.class.getName());
    }

    @Override
    public void writeResponse(ManagementCenterService mcs, JsonObject root) {
        final JsonObject result = new JsonObject();
        ConfigXmlGenerator configXmlGenerator = new ConfigXmlGenerator(true);
        Config config = mcs.getHazelcastInstance().getConfig();
        String configXmlString = configXmlGenerator.generate(config);
        result.add("configXmlString", configXmlString);
        root.add("result", result);
    }

    @Override
    public JsonObject toJson() {
        return new JsonObject();
    }

    @Override
    public void fromJson(JsonObject json) {
    }
}


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

<mapper namespace="com.lijuyong.startup.dao.mapper.SeqMapper">
    <insert id="getUserNo" parameterType="SequenceNoDO">
        <selectKey resultType="Long" order="AFTER" keyProperty="sequenceNoDO.id">
            SELECT LAST_INSERT_ID() as id;
        </selectKey>
        REPLACE INTO user_seq(stub) VALUES ('a');
    </insert>
</mapper>


text:
from debug import logger
from messagetypes import MsgBase

class Message(MsgBase):
    def __init__(self):
        return

    def decode(self, data):
        # UTF-8 and variable type validator
        if type(data["subject"]) is str:
            self.subject = unicode(data["subject"], 'utf-8', 'replace')
        else:
            self.subject = unicode(str(data["subject"]), 'utf-8', 'replace')
        if type(data["body"]) is str:
            self.body = unicode(data["body"], 'utf-8', 'replace')
        else:
            self.body = unicode(str(data["body"]), 'utf-8', 'replace')

    def encode(self, data):
        super(Message, self).encode()
        try:
            self.data["subject"] = data["subject"]
            self.data["body"] = data["body"]
        except KeyError as e:
            logger.error("Missing key %s", e.name)
        return self.data

    def process(self):
        logger.debug("Subject: %i bytes", len(self.subject))
        logger.debug("Body: %i bytes", len(self.body))


text:
/*	$NetBSD: fixcoff.c,v 1.8 2003/12/11 00:27:42 matt Exp $ */

/*
 * Copyright (c) 1999 National Aeronautics & Space Administration
 * All rights reserved.
 *
 * This software was written by William Studenmund of the
 * Numerical Aerospace Similation Facility, NASA Ames Research Center.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the National Aeronautics & Space Administration
 *    nor the names of its contributors may be used to endorse or promote
 *    products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NATIONAL AERONAUTICS & SPACE ADMINISTRATION
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE ADMINISTRATION OR CONTRIB-
 * UTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * This program fixes up the extended xcoff headers generated when an elf
 * file is turned into an xcoff one with the current objcopy. It should
 * go away someday, when objcopy will correctly fix up the output xcoff
 *
 * Partially inspired by hack-coff, written by Paul Mackerras.
 */

#if HAVE_NBTOOL_CONFIG_H
#include "nbtool_config.h"
#endif

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/endian.h>

struct filehdr {
#define U802WRMAGIC     0730
#define U802ROMAGIC     0735
#define U802TOCMAGIC    0737
	char f_magic[2];
	char f_nsect[2];
	char f_time[4];
	char f_symtab[4];
	char f_nsyms[4];
	char f_opthdr[2];
	char f_flags[2];
};

struct sectionhdr {
	char	s_name[8];
	char	s_paddr[4];
	char	s_vaddr[4];
	char	s_size[4];
	char	s_section[4];
	char	s_reloc[4];
	char	s_lineno[4];
	char	s_nreloc[2];
	char	s_nlineno[2];
	char	s_flags[4];
};

struct aouthdr {
	char	magic[2];
	char	vstamp[2];
	char	tsize[4];
	char	dsize[4];
	char	bsize[4];
	char	entry[4];
	char	text_start[4];
	char	data_start[4];
#define SMALL_AOUTSZ	28
	char	o_toc[4];
	char	o_snentry[2];
	char	o_sntext[2];
	char	o_sndata[2];
	char	o_sntoc[2];
	char	o_snloader[2];
	char	o_snbss[2];
	char	o_algntext[2];
	char	o_algndata[2];
	char	o_modtype[2];
	char	o_cputype[2];
	char	o_maxstack[4];
	char	o_maxdata[4];
	char	o_resv2[12];
};
#define RS6K_AOUTHDR_ZMAGIC     0x010B

void
usage(prog)
	char	*prog;
{
	fprintf(stderr, "Usage: %s [-h] | [<file to fix>]\n", prog);
}

void
help(prog)
	char	*prog;
{
	fprintf(stderr, "%s\tis designed to fix the xcoff headers in a\n",prog);
	fprintf(stderr,
"\tbinary generated using objcopy from a non-xcoff source.\n");
	usage(prog);
	exit(0);
}

main(argc, argv)
	int		argc;
	char * const	*argv;
{
	int	fd, i, n, ch;
	struct	filehdr	fh;
	struct	aouthdr aoh;
	struct	sectionhdr sh;

	while ((ch = getopt(argc, argv, "h")) != -1)
	    switch (ch) {
		case 'h':
		help(getprogname());
	}

	argc -= optind;
	argv += optind;

	if (argc != 1) {
		usage(getprogname());
		exit(1);
	}

	if ((fd = open(argv[0], O_RDWR, 0)) == -1)
		err(i, "%s", argv[0]);

	/*
	 * Make sure it looks like an xcoff file..
	 */
	if (read(fd, &fh, sizeof(fh)) != sizeof(fh))
		err(1, "%s reading header", argv[0]);

	i = be16toh(*(uint16_t *)fh.f_magic);
	if ((i != U802WRMAGIC) && (i != U802ROMAGIC) && (i != U802TOCMAGIC))
		errx(1, "%s: not a valid xcoff file", argv[0]);

	/* Does the AOUT "Optional header" make sense? */
	i = be16toh(*(uint16_t *)fh.f_opthdr);

	if (i == SMALL_AOUTSZ)
		errx(1, "%s: file has small \"optional\" header, inappropriate for use with %s", argv[0], getprogname());
	else if (i != sizeof(aoh))
		errx(1, "%s: invalid \"optional\" header", argv[0]);

	if (read(fd, &aoh, i) != i)
		err(1, "%s reading \"optional\" header", argv[0]);

	/* Now start filing in the AOUT header */
	*(uint16_t *)aoh.magic = htobe16(RS6K_AOUTHDR_ZMAGIC);
	n = be16toh(*(uint16_t *)fh.f_nsect);

	for (i = 0; i < n; i++) {
		if (read(fd, &sh, sizeof(sh)) != sizeof(sh))
			err(1, "%s reading section headers", argv[0]);
		if (strcmp(sh.s_name, ".text") == 0) {
			*(uint16_t *)(aoh.o_snentry) = htobe16(i+1);
			*(uint16_t *)(aoh.o_sntext) = htobe16(i+1);
		} else if (strcmp(sh.s_name, ".data") == 0) {
			*(uint16_t *)(aoh.o_sndata) = htobe16(i+1);
		} else if (strcmp(sh.s_name, ".bss") == 0) {
			*(uint16_t *)(aoh.o_snbss) = htobe16(i+1);
		}
	}

	/* now write it out */
	if (pwrite(fd, &aoh, sizeof(aoh), sizeof(struct filehdr))
			!= sizeof(aoh))
		err(1, "%s writing modified header", argv[0]);
	close(fd);
	exit(0);
}


text:
A decentralized free encyclopedia built on top of github

This is the source code of http://gitipedia.github.io


text:
using Parse;

namespace ArtportalenApp.Model
{
    [ParseClassName("_Installation")]
    public class ApParseInstallation : ParseInstallation
    {
        [ParseFieldName("user")]
        public ParseUser User
        {
            get { return GetProperty<ParseUser>(); }
            set { SetProperty(value); }
        }

        [ParseFieldName("deviceInfo")]
        public string DeviceInfo
        {
            get { return GetProperty<string>(); }
            set { SetProperty(value); }
        }
    }
}


text:
from __future__ import print_function
import fitz
import sys, os, subprocess, tempfile, time
'''
Optimizes a PDF with FileOptimizer. But as "/Producer" and "/Creator" get
spoiled by this, we first save metadata and restore it after optimization.
This means we also accept non-compressed object definitions (as created by
FileOptimizer).
'''
assert len(sys.argv) == 2, "need filename parameter"
fn = sys.argv[1]
assert fn.lower().endswith(".pdf"), "must be a PDF file"

fullname = os.path.abspath(fn)         # get the full path & name
t0 = time.clock()                      # save current time
doc = fitz.open(fullname)              # open PDF to save metadata
meta = doc.metadata
doc.close()

t1 = time.clock()                      # save current time again
subprocess.call(["fileoptimizer64", fullname])   # now invoke FileOptimizer
t2 = time.clock()                      # save current time again

cdir = os.path.split(fullname)[0]      # split dir from filename
fnout = tempfile.mkstemp(suffix = ".pdf", dir = cdir) # create temp pdf name
doc = fitz.open(fullname)              # open now optimized PDF
doc.setMetadata(meta)                  # restore old metadata
doc.save(fnout[1], garbage = 4)        # save temp PDF with it, a little sub opt
doc.close()                            # close it

os.remove(fn)                          # remove super optimized file
os.close(fnout[0])                     # close temp file
os.rename(fnout[1], fn)                # and rename it to original filename
t3 = time.clock()                      # save current time again

# put out runtime statistics
print("Timings:")
print(str(round(t1-t0, 4)).rjust(10), "save old metata")
print(str(round(t2-t1, 4)).rjust(10), "execute FileOptimizer")
print(str(round(t3-t2, 4)).rjust(10), "restore old metadata")


text:
module ApplicationHelper

  def bookmarklet_link(dashboard = '')
    "javascript:(function() {d=document, w=window, e=w.getSelection, k=d.getSelection, x=d.selection, s=(e?e():(k)?k():(x?x.createRange().text:0)), e=encodeURIComponent, document.location='#{root_url}urls/new.bookmark?url[dashboard_ids][]=#{dashboard.id}&url[url]='+e(document.location)+'&url[title]='+e(document.title)+'&url[description]='+e(s);} )();"
  end

  def flash_class(level)
    case level
      when :notice then "alert-info"
      when :error then "alert-error"
      when :alert then "alert-warning"
    end
  end

  def background_image_tag(src, options = {})

    style = "background:url(#{image_path src}) no-repeat; background-size: cover;"
     # "width: 100px; height: 100px"

    ['width', 'height'].each do |dim|
      if val = options.delete(dim.to_sym)
        style += "#{dim}: #{!val.to_i.eql?(0) ? val.to_s+'px' : val };"
      end
    end

    if css = options.delete(:style)
      style += css
    end

    options[:style] = style

    image_tag 's.png', options
  end

end


text:
{-# LANGUAGE OverloadedStrings, TupleSections #-}

module XmppTypes (
	elementToStanza,
	stanzaToElement,
	Stanza(..),
	Mechanism(..),
	Challenge(..),
	Response(..),
	Feature(..),
	Bind(..),
	IqType(..),
	IqBody(..),
) where

import Control.Applicative
import Data.Maybe
import Data.List
import Data.XML.Types
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString.Base64 as B64

import DigestMd5

data Stanza
	= StanzaMechanismList [Mechanism]
	| StanzaMechanism Mechanism
	| StanzaChallenge Challenge
	| StanzaResponse Response
	| StanzaSuccess
	| StanzaFeatureList [Feature]
	| StanzaIq {
		iqId :: Text,
		iqType :: IqType,
		iqTo :: Maybe Text,
		iqBody :: IqBody }
	| StanzaPresence {
		presenceId :: Text,
		presenceBody :: [PresenceBody] }
	| StanzaMessage { -- [(Name, [Content])] [Node] -- {
		messageType :: Text, -- MessageType,
		messageId :: Text,
		messageFrom :: Maybe Text,
		messageTo :: Maybe Text,
		messageBody :: [Node] }
	| StanzaTag Tag Element
	| StanzaRaw Element
	deriving Show

data PresenceBody
	= PresenceBodyCaps Caps
	| PresenceBodyRaw Element
	deriving Show

toPresenceBody :: Element -> PresenceBody
toPresenceBody (Element nm ats [])
	| Just TagC <- nameToTag nm = PresenceBodyCaps $ toCaps ats
toPresenceBody e = PresenceBodyRaw e

fromPresenceBody :: PresenceBody -> Element
fromPresenceBody (PresenceBodyCaps c) = Element
	(fromJust $ lookup TagC tagName) (fromCaps c) []
fromPresenceBody (PresenceBodyRaw e) = e

data IqType
	= IqGet
	| IqSet
	| IqResult
	| IqError
	| IqRaw Text
	deriving Show

toIqType :: Text -> IqType
toIqType "get" = IqGet
toIqType "set" = IqSet
toIqType "result" = IqResult
toIqType "error" = IqError
toIqType tp = IqRaw tp

fromIqType :: IqType -> Text
fromIqType IqGet = "get"
fromIqType IqSet = "set"
fromIqType IqResult = "result"
fromIqType IqError = "error"
fromIqType (IqRaw t) = t

data IqBody
	= IqBodyBind [Bind]
	| IqBodySession
	| IqBodyRosterQuery {
		rosterVer :: Maybe Int,
		rosterBody :: [Node] }
	| IqBodyDiscoQuery
	| IqBodyTag Tag Element
	| IqBodyRaw Element
	| IqBodyNull
	deriving Show

toIqBody :: Element -> IqBody
toIqBody (Element nm [] nds)
	| Just TagBind <- nameToTag nm = IqBodyBind $
		map (toBind . \(NodeElement e) -> e) nds
toIqBody (Element nm [] [])
	| Just TagSession <- nameToTag nm = IqBodySession
toIqBody (Element nm ats nds)
	| Just TagRosterQuery <- nameToTag nm = IqBodyRosterQuery {
		rosterVer = read . Text.unpack <$> lookupAttrM "ver" ats,
		rosterBody = nds }
toIqBody (Element nm [] [])
	| Just TagDiscoQuery <- nameToTag nm = IqBodyDiscoQuery
toIqBody e@(Element nm _ _)
	| Just t <- nameToTag nm = IqBodyTag t e
toIqBody e = IqBodyRaw e

fromIqBody :: IqBody -> Element
fromIqBody (IqBodyBind nds) = Element (fromJust $ lookup TagBind tagName) [] $
	map (NodeElement . fromBind) nds
fromIqBody IqBodySession = Element (fromJust $ lookup TagSession tagName) [] []
fromIqBody (IqBodyRosterQuery vr bd) =
	flip (Element . fromJust $ lookup TagRosterQuery tagName) bd $
		maybe [] (\v -> [(Name "ver" Nothing Nothing,
			[ContentText . Text.pack $ show v])]) vr
fromIqBody IqBodyDiscoQuery = Element
	(fromJust $ lookup TagDiscoQuery tagName) [] []
fromIqBody (IqBodyTag _ e) = e
fromIqBody (IqBodyRaw e) = e
fromIqBody IqBodyNull = error "fromIqBody: No iq body"

data Bind
	= Required
	| BindResource Text
	| BindJid Text
	| BindTag Tag Element
	| BindRaw Element
	deriving (Show, Eq)

toBind :: Element -> Bind
toBind (Element nm [] [])
	| Just TagRequired <- nameToTag nm = Required
toBind (Element nm [] [NodeContent (ContentText rn)])
	| Just TagResource <- nameToTag nm = BindResource rn
toBind (Element nm [] [NodeContent (ContentText jid)])
	| Just TagJid <- nameToTag nm = BindJid jid
toBind e@(Element nm _ _)
	| Just t <- nameToTag nm = BindTag t e
toBind e = BindRaw e

fromBind :: Bind -> Element
fromBind Required = Element (fromJust $ lookup TagRequired tagName) [] []
fromBind (BindResource rn) = Element (fromJust $ lookup TagResource tagName) []
	[NodeContent (ContentText rn)]
fromBind (BindJid jid) = Element (fromJust $ lookup TagJid tagName) []
	[NodeContent (ContentText jid)]
fromBind (BindTag _ e) = e
fromBind (BindRaw e) = e

data Feature
	= FeatureVer Ver
	| FeatureBind Bind
	| FeatureSession Session
	| FeatureC Caps
	| FeatureTag Tag Element
	| FeatureRaw Element
	deriving (Show, Eq)

data Caps = Caps {
	capsHash :: Text,
	capsVer :: Text,
	capsNode :: Text } deriving (Show, Eq)

toCaps :: [(Name, [Content])] -> Caps
toCaps ats = Caps {
	capsHash = lookupAttr "hash" ats,
	capsVer = lookupAttr "ver" ats,
	capsNode = lookupAttr "node" ats
 }

fromCaps :: Caps -> [(Name, [Content])]
fromCaps ats = [
	(Name "hash" Nothing Nothing, [ContentText $ capsHash ats]),
	(Name "ver" Nothing Nothing, [ContentText $ capsVer ats]),
	(Name "node" Nothing Nothing, [ContentText $ capsNode ats])
 ]

data Ver
	= Optional
	| VerRaw Element
	deriving (Show, Eq)

data Session
	= SessionOptional
	| SessionRaw Element
	deriving (Show, Eq)

toFeature :: Element -> Feature
toFeature (Element nm [] [NodeElement e])
	| Just TagVer <- nameToTag nm = FeatureVer $ case e of
		Element n [] [] | Just TagOptional <- nameToTag n -> Optional
		_ -> VerRaw e
toFeature (Element nm [] [NodeElement e])
	| Just TagBind <- nameToTag nm = FeatureBind $ case e of
		Element n [] []
			| Just TagRequired <- nameToTag n -> Required
		_ -> BindRaw e
toFeature (Element nm [] [NodeElement e])
	| Just TagSession <- nameToTag nm = FeatureSession $ case e of
		Element n [] []
			| Just TagSessionOptional <- nameToTag n -> SessionOptional
		_ -> SessionRaw e
toFeature (Element nm ats [])
	| Just TagC <- nameToTag nm = FeatureC $ toCaps ats
toFeature e@(Element nm _ _)
	| Just tg <- nameToTag nm = FeatureTag tg e
toFeature e = FeatureRaw e

fromFeature :: Feature -> Element
fromFeature (FeatureVer o) = Element
	(fromJust $ lookup TagVer tagName) [] . (: []) . NodeElement $ case o of
		Optional -> Element (fromJust $ lookup TagOptional tagName) [] []
		VerRaw e -> e
fromFeature (FeatureBind o) = Element
	(fromJust $ lookup TagBind tagName) [] . (: []) . NodeElement $ case o of
		Required -> Element (fromJust $ lookup TagRequired tagName) [] []
		BindRaw e -> e
		_ -> error "fromFeature: error"
fromFeature (FeatureSession o) = Element (fromJust $ lookup TagSession tagName)
	[] . (: []) . NodeElement $ case o of
		SessionOptional -> Element
			(fromJust $ lookup TagSessionOptional tagName) [] []
		SessionRaw e -> e
fromFeature (FeatureC c) =
	flip (Element (fromJust $ lookup TagC tagName)) [] $ fromCaps c
fromFeature (FeatureTag _ e) = e
fromFeature (FeatureRaw e) = e

lookupAttr :: Text -> [(Name, [Content])] -> Text
lookupAttr bs ats = case filter ((== Name bs Nothing Nothing) . fst) ats of
	[(_, [ContentText txt])] -> txt
	_ -> error "lookupAttr: bad"

lookupAttrM :: Text -> [(Name, [Content])] -> Maybe Text
lookupAttrM bs ats = case filter ((== Name bs Nothing Nothing) . fst) ats of
	[(_, [ContentText txt])] -> Just txt
	_ -> Nothing

data Challenge
	= Challenge {
		realm :: ByteString,
		nonce :: ByteString,
		qop :: ByteString,
		charset :: ByteString,
		algorithm :: ByteString
	 }
	| ChallengeRspauth ByteString
	| ChallengeRaw [(ByteString, ByteString)]
	deriving Show

toChallenge :: [(ByteString, ByteString)] -> Challenge
toChallenge kvs
	| sort (map fst kvs) ==
		sort ["realm", "nonce", "qop", "charset", "algorithm"] =
		Challenge {
			realm = unquoteBS $ lu "realm" kvs,
			nonce = unquoteBS $ lu "nonce" kvs,
			qop = unquoteBS $ lu "qop" kvs,
			charset = lu "charset" kvs,
			algorithm = lu "algorithm" kvs
		 }
	where
	lu = (fromJust .) . lookup
toChallenge [("rspauth", rsp)] = ChallengeRspauth rsp
toChallenge kvs = ChallengeRaw kvs

fromChallenge :: Challenge -> [(ByteString, ByteString)]
fromChallenge c@(Challenge {}) = [
	("realm", quoteBS $ realm c),
	("nonce", quoteBS $ nonce c),
	("qop", quoteBS $ qop c),
	("charset", charset c),
	("algorithm", algorithm c)
 ]
fromChallenge (ChallengeRspauth rsp) = [("rspauth", rsp)]
fromChallenge (ChallengeRaw kvs) = kvs

data Response
	= Response {
		rUsername :: ByteString,
		rRealm :: ByteString,
		rPassword :: ByteString,
		rCnonce :: ByteString,
		rNonce :: ByteString,
		rNc :: ByteString,
		rQop :: ByteString,
		rDigestUri :: ByteString,
--		rResponse :: ByteString,
		rCharset :: ByteString }
	| ResponseNull
	| ResponseRaw [Node]
	deriving Show

calcMd5 :: Bool -> Response -> ByteString
calcMd5 isClient = digestMd5 isClient
	<$> rUsername <*> rRealm <*> rPassword  <*> rQop <*> rDigestUri
	<*> rNonce <*> rNc <*> rCnonce

toResponse :: [Node] -> Response
toResponse [NodeContent (ContentText txt)]
	| kvs <- readSaslData txt, sort (map fst kvs) == sort [
			"username", "realm", "nonce", "cnonce", "nc", "qop",
			"digest-uri", "response", "charset" ] =
		kvsToResponse kvs
toResponse [] = ResponseNull
toResponse nds = ResponseRaw nds

kvsToResponse :: [(ByteString, ByteString)] -> Response
kvsToResponse kvs = Response {
		rUsername = unquoteBS $ lu "username" kvs,
		rRealm = unquoteBS $ lu "realm" kvs,
		rPassword = "password",
		rNonce = unquoteBS $ lu "nonce" kvs,
		rCnonce = unquoteBS $ lu "cnonce" kvs,
		rNc = lu "nc" kvs,
		rQop = lu "qop" kvs,
		rDigestUri = unquoteBS $ lu "digest-uri" kvs,
--		rResponse = lu "response" kvs,
		rCharset = lu "charset" kvs
	 }
	where
	lu = (fromJust .) . lookup

fromResponse :: Response -> [Node]
fromResponse rsp@(Response {}) =
	[NodeContent . ContentText . showSaslData $ responseToKvs rsp]
fromResponse ResponseNull = []
fromResponse (ResponseRaw nds) = nds

responseToKvs :: Response -> [(ByteString, ByteString)]
responseToKvs rsp = [
	("username", quoteBS $ rUsername rsp),
	("realm", quoteBS $ rRealm rsp),
	("nonce", quoteBS $ rNonce rsp),
	("cnonce", quoteBS $ rCnonce rsp),
	("nc", rNc rsp),
	("qop", rQop rsp),
	("digest-uri", quoteBS $ rDigestUri rsp),
	("response", calcMd5 True rsp),
--	("response", rResponse rsp),
	("charset", rCharset rsp)
 ]

data Tag
	= TagFeatures
	| Mechanisms
	| Mechanism
	| Auth
	| TagChallenge
	| TagResponse
	| TagSuccess
	| TagVer
	| TagBind
	| TagOptional
	| TagRequired
	| TagSession
	| TagSessionOptional
	| TagC
	| TagIq
	| TagResource
	| TagJid
	| TagRosterQuery
	| TagPresence
	| TagDiscoQuery
	| TagMessage
	deriving (Show, Eq)

data Mechanism
	= ScramSha1
	| DigestMd5
	| UnknownMechanism Text
	| NotMechanism Element
	deriving (Show, Eq)

elementToStanza :: Element -> Stanza
elementToStanza (Element nm [] (NodeElement (Element nm' [] nds) : _))
	| Just TagFeatures <- nameToTag nm,
		Just Mechanisms <- nameToTag nm' =
		StanzaMechanismList $ map
			(elementToMechanism . fromJust . nodeElementElement) nds
elementToStanza (Element nm
	[(Name "mechanism" Nothing Nothing, [ContentText at])] [])
	| Just Auth <- nameToTag nm = StanzaMechanism $ case at of
		"SCRAM-SHA-1" -> ScramSha1
		"DIGEST-MD5" -> DigestMd5
		_ -> UnknownMechanism at
elementToStanza (Element nm [] [NodeContent (ContentText cnt)])
	| Just TagChallenge <- nameToTag nm = StanzaChallenge . toChallenge $
		readSaslData cnt
elementToStanza (Element nm [] nds)
	| Just TagResponse <- nameToTag nm = StanzaResponse $ toResponse nds
elementToStanza (Element nm [] [])
	| Just TagSuccess <- nameToTag nm = StanzaSuccess
elementToStanza (Element nm [] nds)
	| Just TagFeatures <- nameToTag nm =
		StanzaFeatureList $ map (toFeature . \(NodeElement e) -> e) nds
elementToStanza (Element nm ats [])
	| Just TagIq <- nameToTag nm = StanzaIq {
		iqId = lookupAttr "id" ats,
		iqType = toIqType $ lookupAttr "type" ats,
		iqTo = lookupAttrM "to" ats,
		iqBody = IqBodyNull
	 }
elementToStanza (Element nm ats [NodeElement e])
	| Just TagIq <- nameToTag nm = StanzaIq {
		iqId = lookupAttr "id" ats,
		iqType = toIqType $ lookupAttr "type" ats,
		iqTo = lookupAttrM "to" ats,
		iqBody = toIqBody e
	 }
elementToStanza (Element nm ats nds)
	| Just TagPresence <- nameToTag nm = StanzaPresence {
		presenceId = lookupAttr "id" ats,
		presenceBody = map (toPresenceBody . \(NodeElement e) -> e) nds
	 }
elementToStanza (Element nm ats nds)
	| Just TagMessage <- nameToTag nm = StanzaMessage {
		messageType = lookupAttr "type" ats,
		messageId = lookupAttr "id" ats,
		messageFrom = lookupAttrM "from" ats,
		messageTo = lookupAttrM "to" ats,
		messageBody = nds }
elementToStanza e@(Element n _ _)
	| Just t <- nameToTag n = StanzaTag t e
	| otherwise = StanzaRaw e

readSaslData :: Text -> [(ByteString, ByteString)]
readSaslData = map ((\[k, v] -> (k, v)) . BSC.split '=') . BSC.split ',' .
	(\(Right c) -> c) . B64.decode . encodeUtf8

stanzaToElement :: Stanza -> Element
stanzaToElement (StanzaMechanismList nds) = Element
	(fromJust $ lookup TagFeatures tagName) [] [NodeElement e]
	where
	e = Element (fromJust $ lookup Mechanisms tagName) [] $
		map (NodeElement . mechanismToElement) nds
stanzaToElement (StanzaMechanism at)
	| Just c <- mct = Element (fromJust $ lookup Auth tagName)
		[(Name "mechanism" Nothing Nothing, [c])] []
	where
	mct = case at of
		ScramSha1 -> Just $ ContentText "SCRAM-SHA-1"
		DigestMd5 -> Just $ ContentText "DIGEST-MD5"
		UnknownMechanism mn -> Just $ ContentText mn
		_ -> Nothing
stanzaToElement (StanzaChallenge cnt) = Element
	(fromJust $ lookup TagChallenge tagName) [] . (: []) . NodeContent .
		ContentText .  showSaslData $
			fromChallenge cnt
stanzaToElement (StanzaResponse rp) = Element
	(fromJust $ lookup TagResponse tagName) [] $ fromResponse rp
stanzaToElement StanzaSuccess = Element
	(fromJust $ lookup TagSuccess tagName) [] []
stanzaToElement (StanzaFeatureList fts) = Element
	(fromJust $ lookup TagFeatures tagName) [] $
		map (NodeElement . fromFeature) fts
stanzaToElement s@(StanzaIq {})
	| IqBodyNull <- iqBody s =
		flip (Element . fromJust $ lookup TagIq tagName) [] [
			(Name "id" Nothing Nothing, [ContentText $ iqId s]),
			(Name "type" Nothing Nothing,
				[ContentText . fromIqType $ iqType s]) ]
	| otherwise =
		flip (Element . fromJust $ lookup TagIq tagName)
			[NodeElement . fromIqBody $ iqBody s] $ [
				(Name "id" Nothing Nothing,
					[ContentText $ iqId s]),
				(Name "type" Nothing Nothing,
					[ContentText . fromIqType $ iqType s]) ] ++
				maybe [] (: [(Name "from" Nothing Nothing, [ContentText ""])]) ((Name "to" Nothing Nothing ,)
					. (: [])
					. ContentText <$>  iqTo s)
--				(Name "to" Nothing Nothing,
--					maybe [] ((: []) . ContentText) $ iqTo s)
--			 ]
stanzaToElement s@(StanzaPresence {}) =
	Element (fromJust $ lookup TagPresence tagName)
		[(Name "id" Nothing Nothing, [ContentText $ presenceId s])]
		(map (NodeElement . fromPresenceBody) $ presenceBody s)
stanzaToElement s@(StanzaMessage {}) =
	flip (Element . fromJust $ lookup TagMessage tagName) (messageBody s) [
		(Name "id" Nothing Nothing, [ContentText $ messageId s]),
		(Name "type" Nothing Nothing, [ContentText $ messageType s]),
		(Name "from" Nothing Nothing,
			maybe [] ((: []) . ContentText) $ messageFrom s),
		(Name "to" Nothing Nothing,
			maybe [] ((: []) . ContentText) $ messageTo s) ]
stanzaToElement (StanzaTag _ e) = e
stanzaToElement (StanzaRaw e) = e
stanzaToElement _ = error "stanzaToElement: error"

showSaslData :: [(ByteString, ByteString)] -> Text
showSaslData = decodeUtf8 . B64.encode . BSC.intercalate "," .
	map (BSC.intercalate "=" . (\(k, v) -> [k, v]))

elementToMechanism :: Element -> Mechanism
elementToMechanism e@(Element nm [] [NodeContent (ContentText mn)])
	| Just Mechanism <- nameToTag nm = case mn of
		"SCRAM-SHA-1" -> ScramSha1
		"DIGEST-MD5" -> DigestMd5
		_ -> UnknownMechanism mn
	| otherwise = NotMechanism e
elementToMechanism e = NotMechanism e

mechanismToElement :: Mechanism -> Element
mechanismToElement (NotMechanism e) = e
mechanismToElement m = let Just nm = lookup Mechanism tagName in
	Element nm [] . (: []) . NodeContent . ContentText $ case m of
		ScramSha1 -> "SCRAM-SHA-1"
		DigestMd5 -> "DIGEST-MD5"
		UnknownMechanism mn -> mn
		NotMechanism _ -> error "mechanismToElement: never occur"

tagName :: [(Tag, Name)]
tagName = [
	(TagFeatures, Name "features"
		(Just "http://etherx.jabber.org/streams") (Just "stream")),
	(Mechanisms, Name "mechanisms"
		(Just "urn:ietf:params:xml:ns:xmpp-sasl") Nothing),
	(Mechanism, Name "mechanism"
		(Just "urn:ietf:params:xml:ns:xmpp-sasl") Nothing),
	(Mechanism, Name "mechanism" Nothing Nothing),
	(Auth, Name "auth"
		(Just "urn:ietf:params:xml:ns:xmpp-sasl") Nothing),
	(TagChallenge, Name "challenge"
		(Just "urn:ietf:params:xml:ns:xmpp-sasl") Nothing),
	(TagResponse, Name "response"
		(Just "urn:ietf:params:xml:ns:xmpp-sasl") Nothing),
	(TagSuccess, Name "success"
		(Just "urn:ietf:params:xml:ns:xmpp-sasl") Nothing),
	(TagVer, Name "ver"
		(Just "urn:xmpp:features:rosterver") Nothing),
	(TagBind, Name "bind"
		(Just "urn:ietf:params:xml:ns:xmpp-bind") Nothing),
	(TagOptional, Name "optional"
		(Just "urn:xmpp:features:rosterver") Nothing),
	(TagRequired, Name "required"
		(Just "urn:ietf:params:xml:ns:xmpp-bind") Nothing),
	(TagSession, Name "session"
		(Just "urn:ietf:params:xml:ns:xmpp-session") Nothing),
	(TagSessionOptional, Name "optional"
		(Just "urn:ietf:params:xml:ns:xmpp-session") Nothing),
	(TagC, Name "c"
		(Just "http://jabber.org/protocol/caps") Nothing),
	(TagIq, Name "iq" (Just "jabber:client") Nothing),
	(TagResource, Name "resource"
		(Just "urn:ietf:params:xml:ns:xmpp-bind") Nothing),
	(TagJid, Name "jid"
		(Just "urn:ietf:params:xml:ns:xmpp-bind") Nothing),
	(TagRosterQuery, Name "query" (Just "jabber:iq:roster") Nothing),
	(TagPresence, Name "presence" (Just "jabber:client") Nothing),
	(TagDiscoQuery, Name "query"
		(Just "http://jabber.org/protocol/disco#info") Nothing),
	(TagMessage, Name "message" (Just "jabber:client") Nothing)
 ]

nameToTag :: Name -> Maybe Tag
nameToTag = flip lookup $ map (\(x, y) -> (y, x)) tagName

nodeElementElement :: Node -> Maybe Element
nodeElementElement (NodeElement e) = Just e
nodeElementElement _ = Nothing

unquoteBS :: ByteString -> ByteString
unquoteBS bs = case BSC.uncons bs of
	Just ('"', t) -> case unsnoc t of
		Just (i, '"') -> i
		_ -> error "unquoteBS: not quoted"
	_ -> error "unquoteBS: not quoted"

unsnoc :: ByteString -> Maybe (ByteString, Char)
unsnoc bs
	| BSC.null bs = Nothing
	| otherwise = Just (BSC.init bs, BSC.last bs)

quoteBS :: ByteString -> ByteString
quoteBS bs = "\"" `BS.append` bs `BS.append` "\""


text:
var readJson = require('read-package-json');
var mapSeries = require('async/mapSeries');

var libFunctions = require('./lib/functions');

module.exports = function listDependencies(expr, callback) {
  readJson('package.json', function (er, data) {
    if (er) {
      console.error("There was an error reading the package.json file");
      return
    }

    var regexp = new RegExp(expr),
        deps = Object.keys(data.dependencies);

    mapSeries(deps, function(dep, callback){

      if (regexp.test(dep)) {
        libFunctions.processSingleDependency(dep, callback);
      }
      else {
        callback(null, null);
      }
    }, function(err, results) {
      // results now equals an array of the hash { name: String, version: String }
      callback(results.filter(function(entry){
        return entry !== null;
      }));
    });

  });
};


text:
""" Baseclass for benchmarking against an example timeseries
"""
import os

import numpy as np

class PixelTimeseries(object):
    """ Setup example timeseries of a pixel

    Attributes:
        dat (np.lib.npyio.NpzFile): saved timeseries
        X (np.ndarray): n_obs x n_features design matrix
        Y (np.ndarray): n_series x n_obs independent variable
        dates (np.ndarray): n_obs array of ordinal dates for each ``Y``
    """
    example_data = os.path.join(
        os.path.dirname(__file__),
        '..', '..', '..', 'tests', 'algorithms', 'data',
        'example_timeseries_masked.npz')

    def setup_cache(self):
        self.dat = np.load(self.example_data)
        self.X = self.dat['X']
        self.Y = self.dat['Y']
        self.dates = self.dat['dates']
        return {'X': self.X, 'Y': self.Y, 'dates': self.dates}


text:
#ifndef _SIMPLEJSON_H_
#define _SIMPLEJSON_H_

/* $Id */

#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <apr.h>
#include <apr_pools.h>
#include <apr_tables.h>
#include <apr_strings.h>
#include "json_skip.h"

typedef struct {
	const char *jstring;
	const char *offset;
	const char *end;
	apr_pool_t *mpool;
} json_string;

typedef enum {
	JSON_OBJECT,
	JSON_ARRAY,
	JSON_STRING,
	JSON_LONG,
	JSON_DOUBLE,
	JSON_BOOLEAN,
	JSON_NULL,
} JSON_TYPES;

typedef struct {
	union {
		json_skip_head_t *object;
		apr_array_header_t *array;
		double dnumber;
		long lnumber;
		char *string;
		char boolean;
	} value;
	JSON_TYPES type;
} json_value;

//json_value * decode_json(const char *injson,apr_pool_t *mpool);
json_value * decode_json(const char *injson,int size, apr_pool_t *mpool);
void encode_json(json_value *json);

/** HELPER FUNCTION **/
json_value* json_null_create(apr_pool_t *mpool);
json_value* json_long_create(apr_pool_t *mpool,long number);
json_value* json_double_create(apr_pool_t *mpool,double number);
json_value* json_string_create(apr_pool_t *mpool,const char *string);
json_value* json_boolean_create(apr_pool_t *mpool,char b);
json_value* json_object_create(apr_pool_t *mpool);
json_value* json_array_create(apr_pool_t *mpool,int size);
void  json_object_add(json_value *jobject, const char *key, json_value *value);
void  json_array_append(json_value *jarray,  json_value *value);
char * json_serialize(apr_pool_t *mpool, json_value *json);

#endif //_SIMPLEJSON_H_


text:
function Logger() {

    function self() {}

    var _buffer = [];
    var _view = "";
    var _startTime = new Date() * 1;
    var _maxBufferSize = 10;
    var _loggerUrl = "";

    self.register = function(view) {
        _view = view;
        return self;
    }

    self.log = function(obj) {
        obj.view = _view;
        obj.time = new Date() * 1;
        obj.location = document.location.href;

        _buffer.push(obj);
        // console.warn("logger",obj);
        // uncomment this console to see the log event

        if (_buffer.length > _maxBufferSize) {
            self.sync();
        }
        return self;
    }

    self.sync = function() {
        console.warn("uploading");

        var upload = JSON.stringify(_buffer);
        _buffer = [];
        d3.json(_loggerUrl)
            .post(upload, function(error, data) {
                console.warn("done uploading")
            });
    }

    self.buffer = function() {
        console.warn("logger", _buffer);
        return self;
    }

    self.bufferSize = function(_) {
        _maxBufferSize = _;
        return self;
    }

    self.url = function(_) {
        _loggerUrl = _;
        return self;
    }

    window.onbeforeunload = function() {
        self.log({ action: "close" });
        self.sync();
    };

    return self;
}


text:
import sys

import click

from marshmallow import ValidationError

from polyaxon import settings
from polyaxon.cli.executor import docker_run, k8s_run, platform_run
from polyaxon.cli.options import OPTIONS_NAME, OPTIONS_PROJECT
from polyaxon.env_vars.getters import get_project_or_local
from polyaxon.exceptions import PolyaxonSchemaError
from polyaxon.logger import clean_outputs
from polyaxon.managers.git import GitConfigManager
from polyaxon.polyaxonfile import (
    CompiledOperationSpecification,
    OperationSpecification,
    check_polyaxonfile,
)
from polyaxon.utils import code_reference
from polyaxon.utils.formatting import Printer
from polyaxon.utils.validation import validate_tags

@click.command()
@click.option(*OPTIONS_PROJECT["args"], **OPTIONS_PROJECT["kwargs"])
@click.option(
    "-f",
    "--file",
    "polyaxonfile",
    multiple=True,
    type=click.Path(exists=True),
    help="The polyaxonfiles to run.",
)
@click.option(
    "-pm",
    "--python-module",
    type=str,
    help="The python module containing the polyaxonfile to run.",
)
@click.option(
    "--url",
    type=str,
    help="The url containing the polyaxonfile to run.",
)
@click.option(
    "--hub",
    type=str,
    help="The Component Hub name containing the polyaxonfile to run.",
)
@click.option(
    *OPTIONS_NAME["args"],
    type=str,
    help="Name to give to this run, must be unique within the project, could be none.",
)
@click.option("--tags", type=str, help="Tags of this run (comma separated values).")
@click.option("--description", type=str, help="The description to give to this run.")
@click.option(
    "--shell",
    "-s",
    is_flag=True,
    default=False,
    help="To start a shell session after scheduling the run.",
)
@click.option(
    "--log",
    "--logs",
    "-l",
    is_flag=True,
    default=False,
    help="To start logging after scheduling the run.",
)
@click.option(
    "--upload",
    "-u",
    is_flag=True,
    default=False,
    help="To upload the working dir to run's artifacts path "
    "as an init context before scheduling the run.",
)
@click.option(
    "--upload-from",
    "-u-from",
    type=str,
    help="The path to upload from relative the current location (or absolute path), "
    "Note that this must be a valid path, or the CLI will raise an error. "
    "Defaults to the current path.",
)
@click.option(
    "--upload-to",
    "-u-to",
    type=str,
    help="The path to upload to relative the run's root context."
    "To upload to root path you can use `/`, "
    "otherwise the values should start without the separator, "
    "e.g. `uploads`, `code`, `dataset/images/values`, ...",
)
@click.option(
    "--watch",
    "-w",
    is_flag=True,
    default=False,
    help="To start statuses watch loop after scheduling the run.",
)
@click.option(
    "--local",
    is_flag=True,
    default=False,
    help="To start the run locally, with `docker` environment as default.",
)
@click.option(
    "--params",
    "--param",
    "-P",
    metavar="NAME=VALUE",
    multiple=True,
    help="A parameter to override the default params of the run, form -P name=value.",
)
@click.option(
    "--hparams",
    "--hparam",
    "-HP",
    metavar="NAME=VALUE",
    multiple=True,
    help="A hyper-parameter to override the default params of the run, "
    "form: -HP name='range:start:stop:step' "
    "or -HP name='range:[start,stop,step]' "
    "or -HP name='choice:[v1,v2,v3,...]'",
)
@click.option(
    "--matrix-kind", type=str, help="Matrix kind if hparams are provided, default grid."
)
@click.option(
    "--matrix-concurrency",
    type=int,
    help="Matrix concurrency if hparams are provided, default 1.",
)
@click.option(
    "--matrix-num-runs",
    type=int,
    help="Matrix maximum number of runs to create, default all.",
)
@click.option("--presets", type=str, help="Name of the presets to use for this run.")
@click.option(
    "--queue",
    "-q",
    type=str,
    help="Name of the queue to use for this run. "
    "If the name is not namespaced by the agent name the default agent is used: "
    "queue-name or agent-name/queue-name",
)
@click.option(
    "--nocache",
    is_flag=True,
    default=False,
    help="[DEPRECATED] Please use '--cache=f' instead. "
    "Disable cache check before starting this operation.",
)
@click.option(
    "--cache",
    help="To enable/disable cache check before starting this operation, "
    "similar to 'cache: {disable: true/false}'. "
    "Can be used with yes/no, y/n, false/true, f/t, 1/0. "
    "e.g. '--cache=1', '--cache=yes', '--cache=false', '--cache=t', ...",
)
@click.option(
    "--approved",
    help="To enable/disable human in the loop validation without changing the polyaxonfile, "
    "similar to 'isApproved: true/false'. "
    "Can be used with yes/no, y/n, false/true, f/t, 1/0. "
    "e.g. '--approved=1', '--approved=yes', '--approved=false', '--approved=t', ...",
)
@click.option(
    "--eager",
    is_flag=True,
    default=False,
    help="A flag to enable eager mode for pipeline operations, "
    "currently this mode supports grid search, random search, and parallel mapping. "
    "Note that this flag requires numpy.",
)
@click.option(
    "--git-preset",
    is_flag=True,
    default=False,
    help="A flag to enable automatic injection of a git initializer as a preset "
    "using the initialized git connection.",
)
@click.option(
    "--git-revision",
    type=str,
    help="If provided, Polyaxon will use this git revision "
    "instead of trying to detected and use the latest commit. "
    "The git revision could be a commit or a branch or any valid tree-ish. "
    "This flag is only used when the repo is initialized with: "
    "`polyaxon init [--git-connection] [--git-url]`",
)
@click.option(
    "--ignore-template",
    is_flag=True,
    default=False,
    help="If provided, Polyaxon will ignore template definition and "
    "submit the manifest to be checked by the API.",
)
@click.option(
    "--output",
    "-o",
    type=str,
    help="Optional flag to print the response as a json object or store the response as json file."
    "Example `-o json` or `-o path=./data.json`",
)
@click.pass_context
@clean_outputs
def run(
    ctx,
    project,
    polyaxonfile,
    python_module,
    url,
    hub,
    name,
    tags,
    description,
    shell,
    log,
    upload,
    upload_from,
    upload_to,
    watch,
    local,
    params,
    hparams,
    matrix_kind,
    matrix_concurrency,
    matrix_num_runs,
    presets,
    queue,
    nocache,
    cache,
    approved,
    eager,
    git_preset,
    git_revision,
    ignore_template,
    output,
):
    """Run polyaxonfile specification.

    Examples:

    \b
    $ polyaxon run -f file -f file_override ...

    Run and set description and tags for this run

    \b
    $ polyaxon run -f file --description="Description of the current run" --tags="foo, bar, moo"

    Run and set a unique name for this run

    \b
    polyaxon run --name=foo

    Run for a specific project

    \b
    $ polyaxon run -p project1 -f file.yaml

    Run with updated params

    \b
    $ polyaxon run -p project1 -f file.yaml -P param1=234.2 -P param2=relu

    If a python file contains a component main, you can run that component

    \b
    $ polyaxon run -pm path/to/my-component.py

    If a python file contains more than one component, you can specify the component to run

    \b
    $ polyaxon run -pm path/to/my-component.py:componentA

    Uploading from everything in the current folder to the default uploads path

    \b
    $ polyaxon run ... -u

    Uploading from everything in the current folder to a custom path, e.g. code

    \b
    $ polyaxon run ... -u-to code

    Uploading from everything from a sub-folder, e.g. ./code to the a custom path, e.g. new-code

    \b
    $ polyaxon run ... -u-from ./code -u-to new-code
    """
    if log and shell:
        Printer.print_error(
            "You can't use `--logs` and `--shell` at the same, please keep one option.",
            sys_exit=True,
        )
    if cache and nocache:
        Printer.print_error(
            "You can't use `--cache` and `--nocache` at the same.", sys_exit=True
        )
    if nocache:
        Printer.print_error(
            "'--nocache' is DEPRECATED and will be removed in the future, "
            "please use '--cache=f' instead.",
        )
    if (upload_to or upload_from) and not upload:
        upload = True

    git_init = None
    if git_preset or git_revision:
        # Check that the current path was initialized
        if not GitConfigManager.is_initialized():
            Printer.print_error(
                "You can't use `--git-preset [--git-revision]`, "
                "the current path is not initialized with a valid git connection or a git url, "
                "please run `polyaxon init [--git-connection] [--git-url]` "
                "to set a valid git configuration.",
                sys_exit=True,
            )
        git_init = GitConfigManager.get_config()
        if git_revision:
            git_init.git.revision = git_revision
        elif code_reference.is_git_initialized(path="."):
            if code_reference.is_dirty(path="."):
                Printer.print_warning(
                    "Polyaxon detected uncommitted changes in the current git repo!"
                )
            commit_hash = code_reference.get_commit()
            git_init.git.revision = commit_hash
        else:
            Printer.print_warning(
                "Polyaxon could not find a valid git repo, "
                "and will not add the current commit to the git initializer."
            )

    presets = validate_tags(presets)

    op_spec = check_polyaxonfile(
        polyaxonfile=polyaxonfile,
        python_module=python_module,
        url=url,
        hub=hub,
        params=params,
        hparams=hparams,
        matrix_kind=matrix_kind,
        matrix_concurrency=matrix_concurrency,
        matrix_num_runs=matrix_num_runs,
        presets=presets,
        queue=queue,
        cache=cache,
        nocache=nocache,
        approved=approved,
        verbose=False,
        eager=eager,
        git_init=git_init,
        ignore_template=ignore_template,
    )

    if ignore_template:
        op_spec.disable_template()
    if op_spec.is_template():
        Printer.print("Please customize the specification or disable the template!")
        sys.exit(1)

    owner, project_name = get_project_or_local(project, is_cli=True)
    tags = validate_tags(tags, validate_yaml=True)

    if local:
        try:
            compiled_operation = OperationSpecification.compile_operation(op_spec)
            compiled_operation = (
                CompiledOperationSpecification.apply_operation_contexts(
                    compiled_operation
                )
            )
        except (PolyaxonSchemaError, ValidationError):
            Printer.print_error(
                "Could not run this polyaxonfile locally, "
                "a context is required to resolve it dependencies."
            )
            sys.exit(1)
        docker_run(
            ctx=ctx,
            name=name,
            owner=owner,
            project_name=project_name,
            description=description,
            tags=tags,
            compiled_operation=compiled_operation,
            log=log,
            shell=shell,
        )
    elif settings.CLIENT_CONFIG.no_api:
        k8s_run(
            ctx=ctx,
            name=name,
            owner=owner,
            project_name=project_name,
            description=description,
            tags=tags,
            op_spec=op_spec,
            log=log,
        )
    else:
        platform_run(
            ctx=ctx,
            name=name,
            owner=owner,
            project_name=project_name,
            description=description,
            tags=tags,
            op_spec=op_spec,
            log=log,
            upload=upload,
            upload_to=upload_to,
            upload_from=upload_from,
            watch=watch,
            eager=eager,
            output=output,
            shell=shell,
        )


text:
(function() {
    'use strict';

    Game.Utils.FpsMeter = function(game, x, y) {

        Phaser.Text.call(this, game, x, y);

        this.game.time.advancedTiming = true;
        this.fixedToCamera = true;

        return this;
    };

    // Clone the Phaser.Sprite prototype, and use it as our own.
    // This is how inheritance works in JavaScript btw
    Game.Utils.FpsMeter.prototype = Object.create(Phaser.Text.prototype);
    Game.Utils.FpsMeter.prototype.constructor = Game.Utils.FpsMeter;

    Game.Utils.FpsMeter.prototype.update = function() {

        this.text = 'FPS: ' + this.game.time.fps;

    };

})();