text:
<?php

namespace WPMailSMTP;

class AM_Notification {
	/**
	 * The api url we are calling.
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	public $api_url = 'https://api.awesomemotive.com/v1/notification/';

	/**
	 * A unique slug for this plugin.
	 * (Not the WordPress plugin slug)
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	public $plugin;

	/**
	 * The current plugin version.
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	public $plugin_version;

	/**
	 * Flag if a notice has been registered.
	 *
	 * @since 1.0.0
	 *
	 * @var bool
	 */
	public static $registered = false;

	/**
	 * Construct.
	 *
	 * @since 1.0.0
	 *
	 * @param string $plugin The plugin slug.
	 * @param mixed $version The version of the plugin.
	 */
	public function __construct( $plugin = '', $version = 0 ) {
		$this->plugin         = $plugin;
		$this->plugin_version = $version;

		add_action( 'init', array( $this, 'custom_post_type' ) );
		add_action( 'admin_init', array( $this, 'get_remote_notifications' ), 100 );
		add_action( 'admin_notices', array( $this, 'display_notifications' ) );
		add_action( 'wp_ajax_am_notification_dismiss', array( $this, 'dismiss_notification' ) );
	}

	/**
	 * Registers a custom post type.
	 *
	 * @since 1.0.0
	 */
	public function custom_post_type() {
		register_post_type( 'amn_' . $this->plugin, array(
			'label'      => $this->plugin . ' Announcements',
			'can_export' => false,
			'supports'   => false,
		) );
	}

	/**
	 * Retrieve the remote notifications if the time has expired.
	 *
	 * @since 1.0.0
	 */
	public function get_remote_notifications() {
		if ( ! current_user_can( apply_filters( 'am_notifications_display', 'manage_options' ) ) ) {
			return;
		}

		$last_checked = get_option( '_amn_' . $this->plugin . '_last_checked', strtotime( '-1 week' ) );

		if ( $last_checked < strtotime( 'today midnight' ) ) {
			$plugin_notifications = $this->get_plugin_notifications( 1 );
			$notification_id      = null;

			if ( ! empty( $plugin_notifications ) ) {
				// Unset it from the array.
				$notification    = $plugin_notifications[0];
				$notification_id = get_post_meta( $notification->ID, 'notification_id', true );
			}

			$response = wp_remote_retrieve_body( wp_remote_post( $this->api_url, array(
				'body' => array(
					'slug'              => $this->plugin,
					'version'           => $this->plugin_version,
					'last_notification' => $notification_id,
				),
			) ) );

			$data = json_decode( $response );

			if ( ! empty( $data->id ) ) {
				$notifications = array();

				foreach ( (array) $data->slugs as $slug ) {
					$notifications = array_merge(
						$notifications,
						(array) get_posts(
							array(
								'post_type'   => 'amn_' . $slug,
								'post_status' => 'all',
								'meta_key'    => 'notification_id',
								'meta_value'  => $data->id,
							)
						)
					);
				}

				if ( empty( $notifications ) ) {
					$new_notification_id = wp_insert_post( array(
						                                       'post_content' => wp_kses_post( $data->content ),
						                                       'post_type'    => 'amn_' . $this->plugin,
					                                       ) );

					update_post_meta( $new_notification_id, 'notification_id', absint( $data->id ) );
					update_post_meta( $new_notification_id, 'type', sanitize_text_field( trim( $data->type ) ) );
					update_post_meta( $new_notification_id, 'dismissable', (bool) $data->dismissible ? 1 : 0 );
					update_post_meta( $new_notification_id, 'location', function_exists( 'wp_json_encode' ) ? wp_json_encode( $data->location ) : json_encode( $data->location ) );
					update_post_meta( $new_notification_id, 'version', sanitize_text_field( trim( $data->version ) ) );
					update_post_meta( $new_notification_id, 'viewed', 0 );
					update_post_meta( $new_notification_id, 'expiration', $data->expiration ? absint( $data->expiration ) : false );
					update_post_meta( $new_notification_id, 'plans', function_exists( 'wp_json_encode' ) ? wp_json_encode( $data->plans ) : json_encode( $data->plans ) );
				}
			}

			// Possibly revoke notifications.
			if ( ! empty( $data->revoked ) ) {
				$this->revoke_notifications( $data->revoked );
			}

			// Set the option now so we can't run this again until after 24 hours.
			update_option( '_amn_' . $this->plugin . '_last_checked', strtotime( 'today midnight' ) );
		}
	}

	/**
	 * Get local plugin notifications that have already been set.
	 *
	 * @since 1.0.0
	 *
	 * @param  integer $limit Set the limit for how many posts to retrieve.
	 * @param  array $args Any top-level arguments to add to the array.
	 *
	 * @return WP_Post[] WP_Post that match the query.
	 */
	public function get_plugin_notifications( $limit = -1, $args = array() ) {
		return get_posts(
			array(
				'posts_per_page' => $limit,
				'post_type'      => 'amn_' . $this->plugin,
			) + $args
		);
	}

	/**
	 * Display any notifications that should be displayed.
	 *
	 * @since 1.0.0
	 */
	public function display_notifications() {
		if ( ! current_user_can( apply_filters( 'am_notifications_display', 'manage_options' ) ) ) {
			return;
		}

		$plugin_notifications = $this->get_plugin_notifications( -1, array(
			'post_status' => 'all',
			'meta_key'    => 'viewed',
			'meta_value'  => '0',
		) );

		$plugin_notifications = $this->validate_notifications( $plugin_notifications );

		if ( ! empty( $plugin_notifications ) && ! self::$registered ) {
			foreach ( $plugin_notifications as $notification ) {
				$dismissable = get_post_meta( $notification->ID, 'dismissable', true );
				$type        = get_post_meta( $notification->ID, 'type', true );
				?>
				<div class="am-notification am-notification-<?php echo $notification->ID; ?> notice notice-<?php echo $type; ?><?php echo $dismissable ? ' is-dismissible' : ''; ?>">
					<?php echo $notification->post_content; ?>
				</div>
				<script type="text/javascript">
					jQuery(document).ready(function ($) {
						$(document).on('click', '.am-notification-<?php echo $notification->ID; ?> button.notice-dismiss', function (event) {
							$.post(ajaxurl, {
								action: 'am_notification_dismiss',
								notification_id: '<?php echo $notification->ID; ?>'
							});
						});
					});
				</script>
				<?php
			}

			self::$registered = true;
		}
	}

	/**
	 * Validate the notifications before displaying them.
	 *
	 * @since 1.0.0
	 *
	 * @param  array $plugin_notifications An array of plugin notifications.
	 *
	 * @return array                       A filtered array of plugin notifications.
	 */
	public function validate_notifications( $plugin_notifications ) {
		global $pagenow;

		foreach ( $plugin_notifications as $key => $notification ) {
			// Location validation.
			$location = (array) json_decode( get_post_meta( $notification->ID, 'location', true ) );
			$continue = false;
			if ( ! in_array( 'everywhere', $location, true ) ) {
				if ( in_array( 'index.php', $location, true ) && 'index.php' === $pagenow ) {
					$continue = true;
				}

				if ( in_array( 'plugins.php', $location, true ) && 'plugins.php' === $pagenow ) {
					$continue = true;
				}

				if ( ! $continue ) {
					unset( $plugin_notifications[ $key ] );
				}
			}

			// Plugin validation (OR conditional).
			$plugins  = (array) json_decode( get_post_meta( $notification->ID, 'plugins', true ) );
			$continue = false;
			if ( ! empty( $plugins ) ) {
				foreach ( $plugins as $plugin ) {
					if ( is_plugin_active( $plugin ) ) {
						$continue = true;
					}
				}

				if ( ! $continue ) {
					unset( $plugin_notifications[ $key ] );
				}
			}

			// Theme validation.
			$theme    = get_post_meta( $notification->ID, 'theme', true );
			$continue = (string) wp_get_theme() === $theme;

			if ( ! empty( $theme ) && ! $continue ) {
				unset( $plugin_notifications[ $key ] );
			}

			// Version validation.
			$version  = get_post_meta( $notification->ID, 'version', true );
			$continue = false;
			if ( ! empty( $version ) ) {
				if ( version_compare( $this->plugin_version, $version, '<=' ) ) {
					$continue = true;
				}

				if ( ! $continue ) {
					unset( $plugin_notifications[ $key ] );
				}
			}

			// Expiration validation.
			$expiration = get_post_meta( $notification->ID, 'expiration', true );
			$continue   = false;
			if ( ! empty( $expiration ) ) {
				if ( $expiration > time() ) {
					$continue = true;
				}

				if ( ! $continue ) {
					unset( $plugin_notifications[ $key ] );
				}
			}

			// Plan validation.
			$plans    = (array) json_decode( get_post_meta( $notification->ID, 'plans', true ) );
			$continue = false;
			if ( ! empty( $plans ) ) {
				$level = $this->get_plan_level();
				if ( in_array( $level, $plans, true ) ) {
					$continue = true;
				}

				if ( ! $continue ) {
					unset( $plugin_notifications[ $key ] );
				}
			}
		}

		return $plugin_notifications;
	}

	/**
	 * Grab the current plan level.
	 *
	 * @since 1.0.0
	 *
	 * @return string The current plan level.
	 */
	public function get_plan_level() {
		// Prepare variables.
		$key    = '';
		$level  = '';
		$option = false;
		switch ( $this->plugin ) {
			case 'wpforms' :
				$option = get_option( 'wpforms_license' );
				$key    = is_array( $option ) && isset( $option['key'] ) ? $option['key'] : '';
				$level  = is_array( $option ) && isset( $option['type'] ) ? $option['type'] : '';

				// Possibly check for a constant.
				if ( empty( $key ) && defined( 'WPFORMS_LICENSE_KEY' ) ) {
					$key = WPFORMS_LICENSE_KEY;
				}
				break;
			case 'mi' :
				$option = get_option( 'monsterinsights_license' );
				$key    = is_array( $option ) && isset( $option['key'] ) ? $option['key'] : '';
				$level  = is_array( $option ) && isset( $option['type'] ) ? $option['type'] : '';

				// Possibly check for a constant.
				if ( empty( $key ) && defined( 'MONSTERINSIGHTS_LICENSE_KEY' ) && is_string( MONSTERINSIGHTS_LICENSE_KEY ) && strlen( MONSTERINSIGHTS_LICENSE_KEY ) > 10 ) {
					$key = MONSTERINSIGHTS_LICENSE_KEY;
				}
				break;
			case 'sol' :
				$option = get_option( 'soliloquy' );
				$key    = is_array( $option ) && isset( $option['key'] ) ? $option['key'] : '';
				$level  = is_array( $option ) && isset( $option['type'] ) ? $option['type'] : '';

				// Possibly check for a constant.
				if ( empty( $key ) && defined( 'SOLILOQUY_LICENSE_KEY' ) ) {
					$key = SOLILOQUY_LICENSE_KEY;
				}
				break;
			case 'envira' :
				$option = get_option( 'envira_gallery' );
				$key    = is_array( $option ) && isset( $option['key'] ) ? $option['key'] : '';
				$level  = is_array( $option ) && isset( $option['type'] ) ? $option['type'] : '';

				// Possibly check for a constant.
				if ( empty( $key ) && defined( 'ENVIRA_LICENSE_KEY' ) ) {
					$key = ENVIRA_LICENSE_KEY;
				}
				break;
			case 'om' :
				$option = get_option( 'optin_monster_api' );
				$key    = is_array( $option ) && isset( $option['api']['apikey'] ) ? $option['api']['apikey'] : '';

				// Possibly check for a constant.
				if ( empty( $key ) && defined( 'OPTINMONSTER_REST_API_LICENSE_KEY' ) ) {
					$key = OPTINMONSTER_REST_API_LICENSE_KEY;
				}

				// If the key is still empty, check for the old legacy key.
				if ( empty( $key ) ) {
					$key = is_array( $option ) && isset( $option['api']['key'] ) ? $option['api']['key'] : '';
				}
				break;
		}

		// Possibly set the level to 'none' if the key is empty and no level has been set.
		if ( empty( $key ) && empty( $level ) ) {
			$level = 'none';
		}

		// Normalize the level.
		switch ( $level ) {
			case 'bronze' :
			case 'personal' :
				$level = 'basic';
				break;
			case 'silver' :
			case 'multi' :
				$level = 'plus';
				break;
			case 'gold' :
			case 'developer' :
				$level = 'pro';
				break;
			case 'platinum' :
			case 'master' :
				$level = 'ultimate';
				break;
		}

		// Return the plan level.
		return $level;
	}

	/**
	 * Dismiss the notification via AJAX.
	 *
	 * @since 1.0.0
	 */
	public function dismiss_notification() {
		if ( ! current_user_can( apply_filters( 'am_notifications_display', 'manage_options' ) ) ) {
			die;
		}

		$notification_id = intval( $_POST['notification_id'] );
		update_post_meta( $notification_id, 'viewed', 1 );
		die;
	}

	/**
	 * Revokes notifications.
	 *
	 * @since 1.0.0
	 *
	 * @param array $ids An array of notification IDs to revoke.
	 */
	public function revoke_notifications( $ids ) {
		// Loop through each of the IDs and find the post that has it as meta.
		foreach ( (array) $ids as $id ) {
			$notifications = $this->get_plugin_notifications( -1, array( 'post_status' => 'all', 'meta_key' => 'notification_id', 'meta_value' => $id ) );
			if ( $notifications ) {
				foreach ( $notifications as $notification ) {
					update_post_meta( $notification->ID, 'viewed', 1 );
				}
			}
		}
	}
}


text:
from Node import error
from kinds import lowercase_first_word  # noqa: I201

class SyntaxClassification(object):
    '''
    Represents a classification a token can receive for syntax highlighting.
    '''

    def __init__(self, name, description):
        self.name = name
        self.swift_name = lowercase_first_word(name)
        self.description = description

SYNTAX_CLASSIFICATIONS = [
    SyntaxClassification('None', description='''
    The token should not receive syntax coloring.
    '''),
    SyntaxClassification('Keyword', description='''
    A Swift keyword, including contextual keywords.
    '''),
    SyntaxClassification('Identifier', description='''
    A generic identifier.
    '''),
    SyntaxClassification('TypeIdentifier', description='''
    An identifier referring to a type.
    '''),
    SyntaxClassification('DollarIdentifier', description='''
    An identifier starting with `$` like `$0`.
    '''),
    SyntaxClassification('IntegerLiteral', description='''
    An integer literal.
    '''),
    SyntaxClassification('FloatingLiteral', description='''
    A floating point literal.
    '''),
    SyntaxClassification('StringLiteral', description='''
    A string literal including multiline string literals.
    '''),
    SyntaxClassification('StringInterpolationAnchor', description='''
    The opening and closing paranthesis of string interpolation.
    '''),
    SyntaxClassification('PoundDirectiveKeyword', description='''
    A `#` keyword like `#warning`.
    '''),
    SyntaxClassification('BuildConfigId', description='''
    A build configuration directive like `#if`, `#elseif`, `#else`.
    '''),
    SyntaxClassification('Attribute', description='''
    An attribute starting with an `@`.
    '''),
    SyntaxClassification('ObjectLiteral', description='''
    An image, color, etc. literal.
    '''),
    SyntaxClassification('EditorPlaceholder', description='''
    An editor placeholder of the form `<#content#>`
    '''),
    SyntaxClassification('LineComment', description='''
    A line comment starting with `//`.
    '''),
    SyntaxClassification('DocLineComment', description='''
    A doc line comment starting with `///`.
    '''),
    SyntaxClassification('BlockComment', description='''
    A block comment starting with `/**` and ending with `*/.
    '''),
    SyntaxClassification('DocBlockComment', description='''
    A doc block comment starting with `/**` and ending with `*/.
    '''),
]

def classification_by_name(classification_name):
    if classification_name is None:
        return None
    for classification in SYNTAX_CLASSIFICATIONS:
        if classification.name == classification_name:
            return classification
    error("Unknown syntax classification '%s'" % classification_name)

redpajama_set_name: RedPajamaGithub


text:
using System;
using Xunit;

namespace TestEasy.WebServer.Test
{
    public class ApplicationExtensionsFacts
    {
        public class Deploy
        {
            [Fact]
            public void WhenSourceDoesNotExist_ShouldThrow()
            {
                // Arrange
                var mock = new WebServerMockGenerator()
                            .MockApplicationDeploySourceDoesNotExist();

                // Act, Assert
                var exception = Assert.Throws<Exception>(() => ApplicationExtensions.Deploy(
                    mock.ServerManager.Sites[0].Applications[0],
                    @"c:\Temp\MySite",
                    mock.FileSystem.Object));
                Assert.Equal(@"Failed to deploy files to application, source directory does not exist: 'c:\Temp\MySite'.", exception.Message);
            }

            [Fact]
            public void WhenVirtualDirectoryDoesNotExist_ShouldThrow()
            {
                // Arrange
                var mock = new WebServerMockGenerator()
                            .MockApplication()
                            .MockApplicationVirtualDirectoryDoesNotExist();
                // Act, Assert
                var exception = Assert.Throws<Exception>(() => ApplicationExtensions.Deploy(
                    mock.ServerManager.Sites[0].Applications[mock.MockApplicationName],
                    @"c:\Temp\MySite",
                    mock.FileSystem.Object));
                Assert.Equal(string.Format(@"Application '{0}' does not have a virtual directory.", mock.MockApplicationName), exception.Message);
            }

            [Fact]
            public void WhenVirtualDirectoryPathNotExist_ShouldCreate()
            {
                // Arrange
                var mock = new WebServerMockGenerator()
                            .MockApplication()
                            .MockApplicationDeployVirtualDirectoryPathNotExistShouldCreate();

                // Act, Assert
                ApplicationExtensions.Deploy(
                    mock.ServerManager.Sites[0].Applications[mock.MockApplicationName],
                    @"c:\Temp\MySite",
                    mock.FileSystem.Object);
            }

            [Fact]
            public void WhenVirtualDirectoryPathExist_ShouldJustCopy()
            {
                // Arrange
                var mock = new WebServerMockGenerator()
                           .MockApplication()
                           .MockApplicationDeployVirtualDirectoryPathExistShouldJustCopy();

                // Act, Assert
                ApplicationExtensions.Deploy(
                    mock.ServerManager.Sites[0].Applications[mock.MockApplicationName],
                    @"c:\Temp\MySite",
                    mock.FileSystem.Object);
            }

            [Fact]
            public void WhenVirtualDirectoryPathExist_IfRelativePathProvided_ShouldCopyToRelative()
            {
                // Arrange
                var mock = new WebServerMockGenerator()
                           .MockApplication()
                           .MockApplicationDeployVirtualDirectoryPathExistIfRelativePathProvidedShouldCopyToRelative();

                // Act, Assert
                ApplicationExtensions.Deploy(
                    mock.ServerManager.Sites[0].Applications[mock.MockApplicationName],
                    @"c:\Temp\MySite",
                    mock.FileSystem.Object,
                    @"..\otherfolder");
            }

            [Fact]
            public void WhenDeployingListOfFiles_IfListIsEmpty_ShouldThrow()
            {
                // Arrange
                var mock = new WebServerMockGenerator()
                           .MockApplication()
                           .MockApplicationDeployListOfFilesIfListIsEmptyShouldThrow();

                // Act, Assert
                var exception = Assert.Throws<ArgumentNullException>(() => ApplicationExtensions.Deploy(
                    mock.ServerManager.Sites[0].Applications[mock.MockApplicationName],
                    (string[])null,
                    "",
                    mock.FileSystem.Object));
                Assert.True(exception.Message.Contains("filePaths"));
            }

            [Fact]
            public void WhenDeployingListOfFiles_IfVirtualDirectoryDoesNotExist_ShouldThrow()
            {
                // Arrange
                var mock = new WebServerMockGenerator()
                           .MockApplication()
                           .MockApplicationPhysicalDirectoryExist()
                           .MockApplicationVirtualDirectoryDoesNotExist();

                // Act, Assert
                var exception = Assert.Throws<Exception>(() => ApplicationExtensions.Deploy(
                    mock.ServerManager.Sites[0].Applications[mock.MockApplicationName],
                    new[]
                    {
                        @"c:\Temp\MySite\file1.html",
                        @"c:\Temp\MySite\file2.html",
                        @"c:\Temp\MySite\file3.html"
                    },
                    "",
                    mock.FileSystem.Object));
                Assert.Equal(string.Format(@"Application '{0}' does not have a virtual directory.", mock.MockApplicationName), exception.Message);
            }

            [Fact]
            public void WhenDeployingListOfFiles_ShouldCopyExistingFilesToRelativeSubFolder()
            {
                // Arrange
                var mock = new WebServerMockGenerator()
                           .MockApplication()
                           .MockApplicationDeployListOfFilesShouldCopyExistingFilesToRelativeSubFolder();

                // Act, Assert
                ApplicationExtensions.Deploy(
                    mock.ServerManager.Sites[0].Applications[mock.MockApplicationName],
                    new []
                    {
                        @"c:\Temp\MySite\file1.html",
                        @"c:\Temp\MySite\file2.html",
                        @"c:\Temp\MySite\file3.html"
                    },
                    @"relative",
                    mock.FileSystem.Object);
            }

            [Fact]
            public void WhenDeployingFileContent_ShouldCreateFile()
            {
                // Arrange
                var mock = new WebServerMockGenerator()
                           .MockApplication()
                           .MockApplicationDeployFileContentShouldCreateFile();

                // Act, Assert
                ApplicationExtensions.Deploy(
                    mock.ServerManager.Sites[0].Applications[mock.MockApplicationName],
                    mock.MockRelativePath,
                    mock.MockSampleFileContent,
                    mock.FileSystem.Object);
            }
        }
    }
}


text:
typedef int (*seta001_gfxbank_callback_func)(running_machine &machine, UINT16 code, UINT8 color);

class seta001_device : public device_t
{
public:
	seta001_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);

	void seta001_draw_sprites(running_machine &machine, bitmap_t *bitmap, const rectangle *cliprect, int bank_size, int setac);

	void setac_eof( void );
	void tnzs_eof( void );

	UINT8 m_bgflag;

	UINT8 m_spritectrl[4];
	UINT8 m_spriteylow[0x300]; // 0x200 low y + 0x100 bg stuff

	UINT8 m_spritecodelow[0x2000]; // tnzs.c stuff only uses half?
	UINT8 m_spritecodehigh[0x2000]; // ^

	// position kludges for seta.c & srmp2.c
	void set_fg_xoffsets( int flip, int noflip ) { m_fg_flipxoffs = flip; m_fg_noflipxoffs = noflip; };
	int m_fg_flipxoffs, m_fg_noflipxoffs;
	void set_fg_yoffsets( int flip, int noflip ) { m_fg_flipyoffs = flip; m_fg_noflipyoffs = noflip; };
	int m_fg_flipyoffs, m_fg_noflipyoffs;
	void set_bg_yoffsets( int flip, int noflip ) { m_bg_flipyoffs = flip; m_bg_noflipyoffs = noflip; };
	int m_bg_flipyoffs, m_bg_noflipyoffs;
	void set_bg_xoffsets( int flip, int noflip ) { m_bg_flipxoffs = flip; m_bg_noflipxoffs = noflip; };
	int m_bg_flipxoffs, m_bg_noflipxoffs;

	void set_transpen ( int pen ) { m_transpen = pen; };
	int m_transpen;

	int is_flipped() { return ((m_spritectrl[ 0 ] & 0x40) >> 6); };

	void set_gfxbank_callback(seta001_gfxbank_callback_func callback) { m_bankcallback = callback; };
	seta001_gfxbank_callback_func m_bankcallback;

	void set_colorbase(int base) { m_colorbase = base; };
	int m_colorbase;

	void set_spritelimit(int limit) { m_spritelimit = limit; };
	int m_spritelimit;

protected:
	virtual void device_start();
	virtual void device_reset();
	private:

private:

	void seta001_draw_background( running_machine &machine, bitmap_t *bitmap, const rectangle *cliprect, int bank_size, int setac_type);
	void seta001_draw_foreground( running_machine &machine, bitmap_t *bitmap, const rectangle *cliprect, int bank_size);

};

WRITE8_DEVICE_HANDLER( spritebgflag_w8 );

READ16_DEVICE_HANDLER( spritectrl_r16 );
WRITE16_DEVICE_HANDLER( spritectrl_w16 );
READ8_DEVICE_HANDLER( spritectrl_r8 );
WRITE8_DEVICE_HANDLER( spritectrl_w8 );

READ16_DEVICE_HANDLER( spriteylow_r16 );
WRITE16_DEVICE_HANDLER( spriteylow_w16 );
READ8_DEVICE_HANDLER( spriteylow_r8 );
WRITE8_DEVICE_HANDLER( spriteylow_w8 );

READ8_DEVICE_HANDLER( spritecodelow_r8 );
WRITE8_DEVICE_HANDLER( spritecodelow_w8 );
READ8_DEVICE_HANDLER( spritecodehigh_r8 );
WRITE8_DEVICE_HANDLER( spritecodehigh_w8 );
READ16_DEVICE_HANDLER( spritecode_r16 );
WRITE16_DEVICE_HANDLER( spritecode_w16 );

extern const device_type SETA001_SPRITE;


text:
<template name='wish'>

  Title:
  {{#if editMode}}
    <input value='{{wish.title}}' class="edit-inline form-control" id='title-{{wish._id}}'/>
  {{else}}
    {{wish.title}}
  {{/if}}

Description:

{{#if editMode}}
  <textarea class="edit-inline form-control" rows="3" id='description-{{wish._id}}'>{{wish.description}}</textarea>
{{else}}

{{{marked wish.description}}}

{{/if}}

  {{#each positiveVotes}}

  {{/each}}

  {{#if owns wish}}
    {{#if editMode}}

    {{/if}}

    {{#if editMode}}

    {{else}}

    {{/if}}
  {{else}}

  {{/if}}

{{#with wishObj}}
  {{> comments}}
{{/with}}
</template>


text:
responsible_parties = Person.where(:responsible_parties => {"$ne" => nil})

total_count = responsible_parties.count

count = 0

responsible_parties.each do |responsible_party|
	first_name = responsible_party.name_first
	last_name = responsible_party.name_last
	potential_matches = Person.where(name_first: first_name, name_last: last_name, authority_member_id: {"$ne" => nil}).to_a
	if potential_matches.count != 0
		count += 1
		puts "#{first_name} #{last_name}"
		puts "--------------------------"
		puts potential_matches.inspect
		puts "-"*100
	end

end

puts "#{count} responsible parties have potential person matches out of a total of #{total_count}."


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.vision.v1p1beta1.model;

/**
 * Information about a product.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Vision API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleCloudVisionV1p4beta1ProductSearchResultsResult extends com.google.api.client.json.GenericJson {

  /**
   * The resource name of the image from the product that is the closest match to the query.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String image;

  /**
   * The Product.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private GoogleCloudVisionV1p4beta1Product product;

  /**
   * A confidence level on the match, ranging from 0 (no confidence) to 1 (full confidence).
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Float score;

  /**
   * The resource name of the image from the product that is the closest match to the query.
   * @return value or {@code null} for none
   */
  public java.lang.String getImage() {
    return image;
  }

  /**
   * The resource name of the image from the product that is the closest match to the query.
   * @param image image or {@code null} for none
   */
  public GoogleCloudVisionV1p4beta1ProductSearchResultsResult setImage(java.lang.String image) {
    this.image = image;
    return this;
  }

  /**
   * The Product.
   * @return value or {@code null} for none
   */
  public GoogleCloudVisionV1p4beta1Product getProduct() {
    return product;
  }

  /**
   * The Product.
   * @param product product or {@code null} for none
   */
  public GoogleCloudVisionV1p4beta1ProductSearchResultsResult setProduct(GoogleCloudVisionV1p4beta1Product product) {
    this.product = product;
    return this;
  }

  /**
   * A confidence level on the match, ranging from 0 (no confidence) to 1 (full confidence).
   * @return value or {@code null} for none
   */
  public java.lang.Float getScore() {
    return score;
  }

  /**
   * A confidence level on the match, ranging from 0 (no confidence) to 1 (full confidence).
   * @param score score or {@code null} for none
   */
  public GoogleCloudVisionV1p4beta1ProductSearchResultsResult setScore(java.lang.Float score) {
    this.score = score;
    return this;
  }

  @Override
  public GoogleCloudVisionV1p4beta1ProductSearchResultsResult set(String fieldName, Object value) {
    return (GoogleCloudVisionV1p4beta1ProductSearchResultsResult) super.set(fieldName, value);
  }

  @Override
  public GoogleCloudVisionV1p4beta1ProductSearchResultsResult clone() {
    return (GoogleCloudVisionV1p4beta1ProductSearchResultsResult) super.clone();
  }

}


text:
package com.netflix.hollow.api.perfapi;

import com.netflix.hollow.core.read.iterator.HollowMapEntryOrdinalIterator;

public class HollowPerfMapEntryIterator {

    private final long keyMaskedTypeIdx;
    private final long valueMaskedTypeIdx;
    private final HollowMapEntryOrdinalIterator iter;

    public HollowPerfMapEntryIterator(HollowMapEntryOrdinalIterator iter, long keyMaskedTypeIdx, long valueMaskedTypeIdx) {
        this.iter = iter;
        this.keyMaskedTypeIdx = keyMaskedTypeIdx;
        this.valueMaskedTypeIdx = valueMaskedTypeIdx;
    }

    public boolean next() {
        return iter.next();
    }

    public long getKey() {
        return Ref.toRefWithTypeMasked(keyMaskedTypeIdx, iter.getKey());
    }

    public long getValue() {
        return Ref.toRefWithTypeMasked(valueMaskedTypeIdx, iter.getValue());
    }

}


text:
namespace power_sampler {

class JsonExporterTest : public testing::Test {
 protected:
  void SetUp() override { ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); }

  base::ScopedTempDir temp_dir_;
};

TEST_F(JsonExporterTest, CreateFile) {
  base::FilePath file_path = temp_dir_.GetPath().Append("dummy.json");
  std::unique_ptr<JsonExporter> exporter =
      JsonExporter::Create(file_path, base::TimeTicks());

  base::File dummy(file_path, base::File::FLAG_OPEN | base::File::FLAG_READ);
  EXPECT_TRUE(dummy.IsValid());
}

TEST_F(JsonExporterTest, InvalidPath) {
  base::FilePath file_path =
      temp_dir_.GetPath().Append("invalid").Append("dummy.json");
  std::unique_ptr<JsonExporter> exporter =
      JsonExporter::Create(file_path, base::TimeTicks());
  EXPECT_EQ(nullptr, exporter);
}

TEST_F(JsonExporterTest, JSONFile) {
  // ScopedTempDir temp_dir;
  base::FilePath file_path = temp_dir_.GetPath().Append("output.json");
  std::unique_ptr<JsonExporter> exporter =
      JsonExporter::Create(file_path, base::TimeTicks());

  DataColumnKey speed1{"odometer", "speed"};
  DataColumnKey speed2{"satelite", "speed"};
  DataColumnKey height{"satelite", "height"};
  exporter->OnStartSession({
      {speed1, "m/s"},
      {speed2, "m/s"},
      {height, "km"},
  });

  EXPECT_EQ(base::JSONReader::Read(R"json(
    {
      "odometer_speed": "m/s",
      "satelite_speed": "m/s",
      "satelite_height": "km"
    }
    )json"),
            exporter->GetColumnLabelsForTesting());

  exporter->OnSample(base::TimeTicks() + base::Milliseconds(1),
                     {{speed1, 0.5}, {speed2, 1.0}});
  exporter->OnSample(base::TimeTicks() + base::Milliseconds(2),
                     {{speed2, 1.5}});

  EXPECT_EQ(base::JSONReader::Read(R"json(
    [ {
      "sample_time": 1000.0,
      "odometer_speed": 0.5,
      "satelite_speed": 1.0
    }, {
      "sample_time": 2000.0,
      "satelite_speed": 1.5
    } ]
    )json"),
            exporter->GetDataRowsForTesting());

  exporter->OnEndSession();

  std::string json_string;
  EXPECT_TRUE(base::ReadFileToString(file_path, &json_string));
  EXPECT_EQ(base::JSONReader::Read(R"json(
    {
      "column_labels": {
        "odometer_speed": "m/s",
        "satelite_height": "km",
        "satelite_speed": "m/s"
      },
      "data_rows": [ {
        "odometer_speed": 0.5,
        "sample_time": 1000.0,
        "satelite_speed": 1.0
      }, {
        "sample_time": 2000.0,
        "satelite_speed": 1.5
      } ]
    }
    )json"),
            base::JSONReader::Read(json_string));
}

}  // namespace power_sampler


text:
package org.gradoop.temporal.model.impl.operators.matching.common.query.predicates.comparables;

import org.gradoop.common.model.api.entities.GraphElement;
import org.gradoop.common.model.impl.properties.PropertyValue;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.Embedding;
import org.gradoop.flink.model.impl.operators.matching.single.cypher.pojos.EmbeddingMetaData;
import org.gradoop.gdl.model.comparables.time.TimePoint;
import org.gradoop.gdl.model.comparables.time.TimeSelector;
import org.gradoop.temporal.model.impl.pojo.TemporalGraphElement;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * Wraps an {@link org.gradoop.gdl.model.comparables.time.TimeSelector}
 */
public class TimeSelectorComparable extends TemporalComparable {

  /**
   * The wrapped TimeSelector
   */
  private final TimeSelector timeSelector;

  /**
   * Creates a new wrapper
   *
   * @param timeSelector the wrapped literal
   */
  public TimeSelectorComparable(TimeSelector timeSelector) {
    this.timeSelector = timeSelector;
  }

  /**
   * Returns the variable of the wrapped TimeSelector
   *
   * @return variable of the TimeSelector
   */
  public String getVariable() {
    return timeSelector.getVariable();
  }

  /**
   * Returns the TimeField (i.e. TX_FROM, TX_TO, VAL_FROM or VAL_TO) of the wrapped TimeSelector
   *
   * @return TimeField of wrapped TimeSelector
   */
  public TimeSelector.TimeField getTimeField() {
    return timeSelector.getTimeProp();
  }

  @Override
  public PropertyValue evaluate(Embedding embedding, EmbeddingMetaData metaData) {
    String selectorString = timeSelector.getTimeProp().toString();
    int column = metaData
      .getPropertyColumn(timeSelector.getVariable(), selectorString);

    return embedding.getProperty(column);
  }

  @Override
  public PropertyValue evaluate(GraphElement element) {
    // here no distinction from global selectors, as element is always a single vertex or edge
    Long time = -1L;
    TimeSelector.TimeField field = timeSelector.getTimeProp();
    if (field.equals(TimeSelector.TimeField.TX_FROM)) {
      time = ((TemporalGraphElement) element).getTxFrom();
    } else if (field == TimeSelector.TimeField.TX_TO) {
      time = ((TemporalGraphElement) element).getTxTo();
    } else if (field == TimeSelector.TimeField.VAL_FROM) {
      time = ((TemporalGraphElement) element).getValidFrom();
    } else if (field == TimeSelector.TimeField.VAL_TO) {
      time = ((TemporalGraphElement) element).getValidTo();
    }
    return PropertyValue.create(time);
  }

  @Override
  public Set<String> getPropertyKeys(String variable) {
    return getVariable().equals(variable) ?
      new HashSet<>(Collections.singletonList(getTimeField().toString())) :
      new HashSet<>();
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    TimeSelectorComparable that = (TimeSelectorComparable) o;

    return that.timeSelector.equals(timeSelector);
  }

  @Override
  public int hashCode() {
    return timeSelector != null ? timeSelector.hashCode() : 0;
  }

  @Override
  public TimePoint getWrappedComparable() {
    return timeSelector;
  }
}


text:
package com.nidkil.util

import org.jsoup._
import org.jsoup.nodes._
import org.jsoup.select._

object JSoup {
  import language.implicitConversions

  implicit def _IterableElements(elems: Elements): Iterable[Element] =
    scala.collection.convert.Wrappers.JIteratorWrapper[Element](elems.iterator()).toIterable

  implicit def _IterableAttributes(attrs: Attributes): Iterable[Attribute] =
    scala.collection.convert.Wrappers.JIteratorWrapper[Attribute](attrs.iterator()).toIterable

  implicit def _RichElement(elem: Element): RichElement = new RichElement(elem)

  class RichElement(elem: Element) {
    def attrOpt(name: String): Option[String] = elem.attr(name) match {
      case "" => None
      case a => Some(a)
    }
  }

}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Increase array members</title>

Problem 4. Average age of females

Write a function that calculates the average age of all females, extracted from an array of persons

Use Array#filter

You could use Chrome console (F12) or Firebug to see the results.


text:
"""
Example that finds CPCs in different ways.
"""

import sys
import requests.packages.urllib3

import zhmcclient
from zhmcclient.testutils import hmc_definitions

requests.packages.urllib3.disable_warnings()

# Get HMC info from HMC inventory and vault files
hmc_def = hmc_definitions()[0]
nickname = hmc_def.nickname
host = hmc_def.host
userid = hmc_def.userid
password = hmc_def.password
verify_cert = hmc_def.verify_cert

print(__doc__)

print("Using HMC {} at {} with userid {} ...".format(nickname, host, userid))

print("Creating a session with the HMC ...")
try:
    session = zhmcclient.Session(
        host, userid, password, verify_cert=verify_cert)
except zhmcclient.Error as exc:
    print("Error: Cannot establish session with HMC {}: {}: {}".
          format(host, exc.__class__.__name__, exc))
    sys.exit(1)

try:
    client = zhmcclient.Client(session)

    print("Finding CPCs in classic mode by filtering on properties ...")
    cpcs = client.cpcs.list(filter_args={'dpm-enabled': False})
    if not cpcs:
        print("Error: HMC at {} does not manage any CPCs in classic mode".
              format(host))
        sys.exit(1)
    cpc_names = [cpc.name for cpc in cpcs]
    print("Found CPCs: {}".format(', '.join(cpc_names)))

    cpc_name = cpc_names[0]
    print("Finding CPC by name={} ...".format(cpc_name))
    try:
        cpc = client.cpcs.find(name=cpc_name)
    except zhmcclient.NotFound:
        print("Error: Could not find CPC {}".format(cpc_name))
        sys.exit(1)
    print("Found CPC: {}".format(cpc.name))

finally:
    print("Logging off ...")
    session.logoff()


text:
export * from './analysis';
export * from './gql';
export * from './list';
export * from './net-worth';
export * from './page';
export * from './shared';
export * from './user';


text:
/*
  The interfrost dtheta_dpressure model is an algebraic model with dependencies.

  Generated via evaluator_generator with:
Interfrost water content portion sl.

  Authors: Ethan Coon (ecoon@lanl.gov)
*/

#ifndef AMANZI_FLOW_INTERFROST_DTHETA_DPRESSURE_MODEL_HH_
#define AMANZI_FLOW_INTERFROST_DTHETA_DPRESSURE_MODEL_HH_

namespace Amanzi {
namespace Flow {
namespace Relations {

class InterfrostDthetaDpressureModel {

 public:
  explicit
  InterfrostDthetaDpressureModel(Teuchos::ParameterList& plist);

  double DThetaDpCoef(double nl, double sl, double phi) const;

  double DDThetaDpCoefDMolarDensityLiquid(double nl, double sl, double phi) const;
  double DDThetaDpCoefDSaturationLiquid(double nl, double sl, double phi) const;
  double DDThetaDpCoefDPorosity(double nl, double sl, double phi) const;

 protected:
  void InitializeFromPlist_(Teuchos::ParameterList& plist);

 protected:

  double beta_;

};

} //namespace
} //namespace
} //namespace

#endif


text:
status: publish
tags:
- "10100111001"
published: true
title: GMail Invites und kein Ende
type: post
meta:
  tags: ""
layout: post
---
Jeden Tag eine gute Tat ;)

Nachdem Googles GMail offenbar im Moment mit Einladungen zu seinem Mail-Service nur so um sich wirft, scheinen nicht mehr viele leute Bedarf an so einem Postfach zu haben. Das Feedback auf meine letzte Verschenk-Aktion war jedenfalls eher gering.

Daher habe ich heute mal zwei Einladungen an den "GMail Invite Spooler" geschickt, um damit zwei fremde Erdenbürger glücklich zu machen ;) Kaum verschickt, waren sie übrigens schon wieder weg. Obwohl über diesen Service schon fast 130.000 Einladungen verschickt wurden, scheint die Nachfrage ungebrochen. Happy Mailing!


text:
package com.google.android.exoplayer2.video;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.media.MediaCodec;
import android.media.MediaCrypto;
import android.media.MediaFormat;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Surface;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.drm.DrmInitData;
import com.google.android.exoplayer2.drm.DrmSessionManager;
import com.google.android.exoplayer2.drm.FrameworkMediaCrypto;
import com.google.android.exoplayer2.mediacodec.MediaCodecInfo;
import com.google.android.exoplayer2.mediacodec.MediaCodecRenderer;
import com.google.android.exoplayer2.mediacodec.MediaCodecSelector;
import com.google.android.exoplayer2.mediacodec.MediaCodecUtil;
import com.google.android.exoplayer2.mediacodec.MediaCodecUtil.DecoderQueryException;
import com.google.android.exoplayer2.util.MimeTypes;
import com.google.android.exoplayer2.util.TraceUtil;
import com.google.android.exoplayer2.util.Util;
import com.google.android.exoplayer2.video.VideoRendererEventListener.EventDispatcher;
import java.nio.ByteBuffer;

/**
 * Decodes and renders video using {@link MediaCodec}.
 */
@TargetApi(16)
public class MediaCodecVideoRenderer extends MediaCodecRenderer {

  private static final String TAG = "MediaCodecVideoRenderer";
  private static final String KEY_CROP_LEFT = "crop-left";
  private static final String KEY_CROP_RIGHT = "crop-right";
  private static final String KEY_CROP_BOTTOM = "crop-bottom";
  private static final String KEY_CROP_TOP = "crop-top";

  private final VideoFrameReleaseTimeHelper frameReleaseTimeHelper;
  private final EventDispatcher eventDispatcher;
  private final long allowedJoiningTimeMs;
  private final int videoScalingMode;
  private final int maxDroppedFramesToNotify;
  private final boolean deviceNeedsAutoFrcWorkaround;

  private Format[] streamFormats;
  private CodecMaxValues codecMaxValues;

  private Surface surface;
  private boolean renderedFirstFrame;
  private long joiningDeadlineMs;
  private long droppedFrameAccumulationStartTimeMs;
  private int droppedFrames;
  private int consecutiveDroppedFrameCount;

  private int pendingRotationDegrees;
  private float pendingPixelWidthHeightRatio;
  private int currentWidth;
  private int currentHeight;
  private int currentUnappliedRotationDegrees;
  private float currentPixelWidthHeightRatio;
  private int lastReportedWidth;
  private int lastReportedHeight;
  private int lastReportedUnappliedRotationDegrees;
  private float lastReportedPixelWidthHeightRatio;

  /**
   * @param context A context.
   * @param mediaCodecSelector A decoder selector.
   * @param videoScalingMode The scaling mode to pass to
   *     {@link MediaCodec#setVideoScalingMode(int)}.
   */
  public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector,
      int videoScalingMode) {
    this(context, mediaCodecSelector, videoScalingMode, 0);
  }

  /**
   * @param context A context.
   * @param mediaCodecSelector A decoder selector.
   * @param videoScalingMode The scaling mode to pass to
   *     {@link MediaCodec#setVideoScalingMode(int)}.
   * @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
   *     can attempt to seamlessly join an ongoing playback.
   */
  public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector,
      int videoScalingMode, long allowedJoiningTimeMs) {
    this(context, mediaCodecSelector, videoScalingMode, allowedJoiningTimeMs, null, null, -1);
  }

  /**
   * @param context A context.
   * @param mediaCodecSelector A decoder selector.
   * @param videoScalingMode The scaling mode to pass to
   *     {@link MediaCodec#setVideoScalingMode(int)}.
   * @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
   *     can attempt to seamlessly join an ongoing playback.
   * @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
   *     null if delivery of events is not required.
   * @param eventListener A listener of events. May be null if delivery of events is not required.
   * @param maxDroppedFrameCountToNotify The maximum number of frames that can be dropped between
   *     invocations of {@link VideoRendererEventListener#onDroppedFrames(int, long)}.
   */
  public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector,
      int videoScalingMode, long allowedJoiningTimeMs, Handler eventHandler,
      VideoRendererEventListener eventListener, int maxDroppedFrameCountToNotify) {
    this(context, mediaCodecSelector, videoScalingMode, allowedJoiningTimeMs, null, false,
        eventHandler, eventListener, maxDroppedFrameCountToNotify);
  }

  /**
   * @param context A context.
   * @param mediaCodecSelector A decoder selector.
   * @param videoScalingMode The scaling mode to pass to
   *     {@link MediaCodec#setVideoScalingMode(int)}.
   * @param allowedJoiningTimeMs The maximum duration in milliseconds for which this video renderer
   *     can attempt to seamlessly join an ongoing playback.
   * @param drmSessionManager For use with encrypted content. May be null if support for encrypted
   *     content is not required.
   * @param playClearSamplesWithoutKeys Encrypted media may contain clear (un-encrypted) regions.
   *     For example a media file may start with a short clear region so as to allow playback to
   *     begin in parallel with key acquisition. This parameter specifies whether the renderer is
   *     permitted to play clear regions of encrypted media files before {@code drmSessionManager}
   *     has obtained the keys necessary to decrypt encrypted regions of the media.
   * @param eventHandler A handler to use when delivering events to {@code eventListener}. May be
   *     null if delivery of events is not required.
   * @param eventListener A listener of events. May be null if delivery of events is not required.
   * @param maxDroppedFramesToNotify The maximum number of frames that can be dropped between
   *     invocations of {@link VideoRendererEventListener#onDroppedFrames(int, long)}.
   */
  public MediaCodecVideoRenderer(Context context, MediaCodecSelector mediaCodecSelector,
      int videoScalingMode, long allowedJoiningTimeMs,
      DrmSessionManager<FrameworkMediaCrypto> drmSessionManager,
      boolean playClearSamplesWithoutKeys, Handler eventHandler,
      VideoRendererEventListener eventListener, int maxDroppedFramesToNotify) {
    super(C.TRACK_TYPE_VIDEO, mediaCodecSelector, drmSessionManager, playClearSamplesWithoutKeys);
    this.videoScalingMode = videoScalingMode;
    this.allowedJoiningTimeMs = allowedJoiningTimeMs;
    this.maxDroppedFramesToNotify = maxDroppedFramesToNotify;
    frameReleaseTimeHelper = new VideoFrameReleaseTimeHelper(context);
    eventDispatcher = new EventDispatcher(eventHandler, eventListener);
    deviceNeedsAutoFrcWorkaround = deviceNeedsAutoFrcWorkaround();
    joiningDeadlineMs = C.TIME_UNSET;
    currentWidth = Format.NO_VALUE;
    currentHeight = Format.NO_VALUE;
    currentPixelWidthHeightRatio = Format.NO_VALUE;
    pendingPixelWidthHeightRatio = Format.NO_VALUE;
    lastReportedWidth = Format.NO_VALUE;
    lastReportedHeight = Format.NO_VALUE;
    lastReportedPixelWidthHeightRatio = Format.NO_VALUE;
  }

  @Override
  protected int supportsFormat(MediaCodecSelector mediaCodecSelector, Format format)
      throws DecoderQueryException {
    String mimeType = format.sampleMimeType;
    if (!MimeTypes.isVideo(mimeType)) {
      return FORMAT_UNSUPPORTED_TYPE;
    }
    boolean requiresSecureDecryption = false;
    DrmInitData drmInitData = format.drmInitData;
    if (drmInitData != null) {
      for (int i = 0; i < drmInitData.schemeDataCount; i++) {
        requiresSecureDecryption |= drmInitData.get(i).requiresSecureDecryption;
      }
    }
    MediaCodecInfo decoderInfo = mediaCodecSelector.getDecoderInfo(mimeType,
        requiresSecureDecryption);
    if (decoderInfo == null) {
      return FORMAT_UNSUPPORTED_SUBTYPE;
    }

    boolean decoderCapable = decoderInfo.isCodecSupported(format.codecs);
    if (decoderCapable && format.width > 0 && format.height > 0) {
      if (Util.SDK_INT >= 21) {
        if (format.frameRate > 0) {
          decoderCapable = decoderInfo.isVideoSizeAndRateSupportedV21(format.width, format.height,
              format.frameRate);
        } else {
          decoderCapable = decoderInfo.isVideoSizeSupportedV21(format.width, format.height);
        }
      } else {
        decoderCapable = format.width * format.height <= MediaCodecUtil.maxH264DecodableFrameSize();
      }
    }

    int adaptiveSupport = decoderInfo.adaptive ? ADAPTIVE_SEAMLESS : ADAPTIVE_NOT_SEAMLESS;
    int formatSupport = decoderCapable ? FORMAT_HANDLED : FORMAT_EXCEEDS_CAPABILITIES;
    return adaptiveSupport | formatSupport;
  }

  @Override
  protected void onEnabled(boolean joining) throws ExoPlaybackException {
    super.onEnabled(joining);
    eventDispatcher.enabled(decoderCounters);
    frameReleaseTimeHelper.enable();
  }

  @Override
  protected void onStreamChanged(Format[] formats) throws ExoPlaybackException {
    streamFormats = formats;
    super.onStreamChanged(formats);
  }

  @Override
  protected void onPositionReset(long positionUs, boolean joining) throws ExoPlaybackException {
    super.onPositionReset(positionUs, joining);
    renderedFirstFrame = false;
    consecutiveDroppedFrameCount = 0;
    joiningDeadlineMs = joining && allowedJoiningTimeMs > 0
        ? (SystemClock.elapsedRealtime() + allowedJoiningTimeMs) : C.TIME_UNSET;
  }

  @Override
  public boolean isReady() {
    if ((renderedFirstFrame || super.shouldInitCodec()) && super.isReady()) {
      // Ready. If we were joining then we've now joined, so clear the joining deadline.
      joiningDeadlineMs = C.TIME_UNSET;
      return true;
    } else if (joiningDeadlineMs == C.TIME_UNSET) {
      // Not joining.
      return false;
    } else if (SystemClock.elapsedRealtime() < joiningDeadlineMs) {
      // Joining and still within the joining deadline.
      return true;
    } else {
      // The joining deadline has been exceeded. Give up and clear the deadline.
      joiningDeadlineMs = C.TIME_UNSET;
      return false;
    }
  }

  @Override
  protected void onStarted() {
    super.onStarted();
    droppedFrames = 0;
    droppedFrameAccumulationStartTimeMs = SystemClock.elapsedRealtime();
  }

  @Override
  protected void onStopped() {
    joiningDeadlineMs = C.TIME_UNSET;
    maybeNotifyDroppedFrames();
    super.onStopped();
  }

  @Override
  protected void onDisabled() {
    currentWidth = Format.NO_VALUE;
    currentHeight = Format.NO_VALUE;
    currentPixelWidthHeightRatio = Format.NO_VALUE;
    pendingPixelWidthHeightRatio = Format.NO_VALUE;
    lastReportedWidth = Format.NO_VALUE;
    lastReportedHeight = Format.NO_VALUE;
    lastReportedPixelWidthHeightRatio = Format.NO_VALUE;
    frameReleaseTimeHelper.disable();
    try {
      super.onDisabled();
    } finally {
      decoderCounters.ensureUpdated();
      eventDispatcher.disabled(decoderCounters);
    }
  }

  @Override
  public void handleMessage(int messageType, Object message) throws ExoPlaybackException {
    if (messageType == C.MSG_SET_SURFACE) {
      setSurface((Surface) message);
    } else {
      super.handleMessage(messageType, message);
    }
  }

  private void setSurface(Surface surface) throws ExoPlaybackException {
    if (this.surface == surface) {
      return;
    }
    renderedFirstFrame = false;
    this.surface = surface;
    int state = getState();
    if (state == STATE_ENABLED || state == STATE_STARTED) {
      releaseCodec();
      maybeInitCodec();
    }
  }

  @Override
  protected boolean shouldInitCodec() {
    return super.shouldInitCodec() && surface != null && surface.isValid();
  }

  @Override
  protected void configureCodec(MediaCodec codec, Format format, MediaCrypto crypto) {
    codecMaxValues = getCodecMaxValues(format, streamFormats);
    MediaFormat mediaFormat = getMediaFormat(format, codecMaxValues, deviceNeedsAutoFrcWorkaround);
    codec.configure(mediaFormat, surface, crypto, 0);
  }

  @Override
  protected void onCodecInitialized(String name, long initializedTimestampMs,
      long initializationDurationMs) {
    eventDispatcher.decoderInitialized(name, initializedTimestampMs, initializationDurationMs);
  }

  @Override
  protected void onInputFormatChanged(Format newFormat) throws ExoPlaybackException {
    super.onInputFormatChanged(newFormat);
    eventDispatcher.inputFormatChanged(newFormat);
    pendingPixelWidthHeightRatio = getPixelWidthHeightRatio(newFormat);
    pendingRotationDegrees = getRotationDegrees(newFormat);
  }

  @Override
  protected void onOutputFormatChanged(MediaCodec codec, android.media.MediaFormat outputFormat) {
    boolean hasCrop = outputFormat.containsKey(KEY_CROP_RIGHT)
        && outputFormat.containsKey(KEY_CROP_LEFT) && outputFormat.containsKey(KEY_CROP_BOTTOM)
        && outputFormat.containsKey(KEY_CROP_TOP);
    currentWidth = hasCrop
        ? outputFormat.getInteger(KEY_CROP_RIGHT) - outputFormat.getInteger(KEY_CROP_LEFT) + 1
        : outputFormat.getInteger(MediaFormat.KEY_WIDTH);
    currentHeight = hasCrop
        ? outputFormat.getInteger(KEY_CROP_BOTTOM) - outputFormat.getInteger(KEY_CROP_TOP) + 1
        : outputFormat.getInteger(MediaFormat.KEY_HEIGHT);
    currentPixelWidthHeightRatio = pendingPixelWidthHeightRatio;
    if (Util.SDK_INT >= 21) {
      // On API level 21 and above the decoder applies the rotation when rendering to the surface.
      // Hence currentUnappliedRotation should always be 0. For 90 and 270 degree rotations, we need
      // to flip the width, height and pixel aspect ratio to reflect the rotation that was applied.
      if (pendingRotationDegrees == 90 || pendingRotationDegrees == 270) {
        int rotatedHeight = currentWidth;
        currentWidth = currentHeight;
        currentHeight = rotatedHeight;
        currentPixelWidthHeightRatio = 1 / currentPixelWidthHeightRatio;
      }
    } else {
      // On API level 20 and below the decoder does not apply the rotation.
      currentUnappliedRotationDegrees = pendingRotationDegrees;
    }
    // Must be applied each time the output format changes.
    codec.setVideoScalingMode(videoScalingMode);
  }

  @Override
  protected boolean canReconfigureCodec(MediaCodec codec, boolean codecIsAdaptive,
      Format oldFormat, Format newFormat) {
    return areAdaptationCompatible(oldFormat, newFormat)
        && newFormat.width <= codecMaxValues.width && newFormat.height <= codecMaxValues.height
        && newFormat.maxInputSize <= codecMaxValues.inputSize
        && (codecIsAdaptive
        || (oldFormat.width == newFormat.width && oldFormat.height == newFormat.height));
  }

  @Override
  protected boolean processOutputBuffer(long positionUs, long elapsedRealtimeUs, MediaCodec codec,
      ByteBuffer buffer, int bufferIndex, int bufferFlags, long bufferPresentationTimeUs,
      boolean shouldSkip) {
    if (shouldSkip) {
      skipOutputBuffer(codec, bufferIndex);
      return true;
    }

    if (!renderedFirstFrame) {
      if (Util.SDK_INT >= 21) {
        renderOutputBufferV21(codec, bufferIndex, System.nanoTime());
      } else {
        renderOutputBuffer(codec, bufferIndex);
      }
      return true;
    }

    if (getState() != STATE_STARTED) {
      return false;
    }

    // Compute how many microseconds it is until the buffer's presentation time.
    long elapsedSinceStartOfLoopUs = (SystemClock.elapsedRealtime() * 1000) - elapsedRealtimeUs;
    long earlyUs = bufferPresentationTimeUs - positionUs - elapsedSinceStartOfLoopUs;

    // Compute the buffer's desired release time in nanoseconds.
    long systemTimeNs = System.nanoTime();
    long unadjustedFrameReleaseTimeNs = systemTimeNs + (earlyUs * 1000);

    // Apply a timestamp adjustment, if there is one.
    long adjustedReleaseTimeNs = frameReleaseTimeHelper.adjustReleaseTime(
        bufferPresentationTimeUs, unadjustedFrameReleaseTimeNs);
    earlyUs = (adjustedReleaseTimeNs - systemTimeNs) / 1000;

    if (earlyUs < -30000) {
      // We're more than 30ms late rendering the frame.
      dropOutputBuffer(codec, bufferIndex);
      return true;
    }

    if (Util.SDK_INT >= 21) {
      // Let the underlying framework time the release.
      if (earlyUs < 50000) {
        renderOutputBufferV21(codec, bufferIndex, adjustedReleaseTimeNs);
        return true;
      }
    } else {
      // We need to time the release ourselves.
      if (earlyUs < 30000) {
        if (earlyUs > 11000) {
          // We're a little too early to render the frame. Sleep until the frame can be rendered.
          // Note: The 11ms threshold was chosen fairly arbitrarily.
          try {
            // Subtracting 10000 rather than 11000 ensures the sleep time will be at least 1ms.
            Thread.sleep((earlyUs - 10000) / 1000);
          } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
          }
        }
        renderOutputBuffer(codec, bufferIndex);
        return true;
      }
    }

    // We're either not playing, or it's not time to render the frame yet.
    return false;
  }

  private void skipOutputBuffer(MediaCodec codec, int bufferIndex) {
    TraceUtil.beginSection("skipVideoBuffer");
    codec.releaseOutputBuffer(bufferIndex, false);
    TraceUtil.endSection();
    decoderCounters.skippedOutputBufferCount++;
  }

  private void dropOutputBuffer(MediaCodec codec, int bufferIndex) {
    TraceUtil.beginSection("dropVideoBuffer");
    codec.releaseOutputBuffer(bufferIndex, false);
    TraceUtil.endSection();
    decoderCounters.droppedOutputBufferCount++;
    droppedFrames++;
    consecutiveDroppedFrameCount++;
    decoderCounters.maxConsecutiveDroppedOutputBufferCount = Math.max(consecutiveDroppedFrameCount,
        decoderCounters.maxConsecutiveDroppedOutputBufferCount);
    if (droppedFrames == maxDroppedFramesToNotify) {
      maybeNotifyDroppedFrames();
    }
  }

  private void renderOutputBuffer(MediaCodec codec, int bufferIndex) {
    maybeNotifyVideoSizeChanged();
    TraceUtil.beginSection("releaseOutputBuffer");
    codec.releaseOutputBuffer(bufferIndex, true);
    TraceUtil.endSection();
    decoderCounters.renderedOutputBufferCount++;
    consecutiveDroppedFrameCount = 0;
    if (!renderedFirstFrame) {
      renderedFirstFrame = true;
      eventDispatcher.renderedFirstFrame(surface);
    }
  }

  @TargetApi(21)
  private void renderOutputBufferV21(MediaCodec codec, int bufferIndex, long releaseTimeNs) {
    maybeNotifyVideoSizeChanged();
    TraceUtil.beginSection("releaseOutputBuffer");
    codec.releaseOutputBuffer(bufferIndex, releaseTimeNs);
    TraceUtil.endSection();
    decoderCounters.renderedOutputBufferCount++;
    consecutiveDroppedFrameCount = 0;
    if (!renderedFirstFrame) {
      renderedFirstFrame = true;
      eventDispatcher.renderedFirstFrame(surface);
    }
  }

  @SuppressLint("InlinedApi")
  private static MediaFormat getMediaFormat(Format format, CodecMaxValues codecMaxValues,
      boolean deviceNeedsAutoFrcWorkaround) {
    MediaFormat frameworkMediaFormat = format.getFrameworkMediaFormatV16();
    // Set the maximum adaptive video dimensions.
    frameworkMediaFormat.setInteger(MediaFormat.KEY_MAX_WIDTH, codecMaxValues.width);
    frameworkMediaFormat.setInteger(MediaFormat.KEY_MAX_HEIGHT, codecMaxValues.height);
    // Set the maximum input size.
    if (codecMaxValues.inputSize != Format.NO_VALUE) {
      frameworkMediaFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, codecMaxValues.inputSize);
    }
    // Set FRC workaround.
    if (deviceNeedsAutoFrcWorkaround) {
      frameworkMediaFormat.setInteger("auto-frc", 0);
    }
    return frameworkMediaFormat;
  }

  /**
   * Returns {@link CodecMaxValues} suitable for configuring a codec for {@code format} in a way
   * that will allow possible adaptation to other compatible formats in {@code streamFormats}.
   *
   * @param format The format for which the codec is being configured.
   * @param streamFormats The possible stream formats.
   * @return Suitable {@link CodecMaxValues}.
   */
  private static CodecMaxValues getCodecMaxValues(Format format, Format[] streamFormats) {
    int maxWidth = format.width;
    int maxHeight = format.height;
    int maxInputSize = getMaxInputSize(format);
    for (Format streamFormat : streamFormats) {
      if (areAdaptationCompatible(format, streamFormat)) {
        maxWidth = Math.max(maxWidth, streamFormat.width);
        maxHeight = Math.max(maxHeight, streamFormat.height);
        maxInputSize = Math.max(maxInputSize, getMaxInputSize(streamFormat));
      }
    }
    return new CodecMaxValues(maxWidth, maxHeight, maxInputSize);
  }

  /**
   * Returns a maximum input size for a given format.
   *
   * @param format The format.
   * @return An maximum input size in bytes, or {@link Format#NO_VALUE} if a maximum could not be
   *     determined.
   */
  private static int getMaxInputSize(Format format) {
    if (format.maxInputSize != Format.NO_VALUE) {
      // The format defines an explicit maximum input size.
      return format.maxInputSize;
    }

    if (format.width == Format.NO_VALUE || format.height == Format.NO_VALUE) {
      // We can't infer a maximum input size without video dimensions.
      return Format.NO_VALUE;
    }

    // Attempt to infer a maximum input size from the format.
    int maxPixels;
    int minCompressionRatio;
    switch (format.sampleMimeType) {
      case MimeTypes.VIDEO_H263:
      case MimeTypes.VIDEO_MP4V:
        maxPixels = format.width * format.height;
        minCompressionRatio = 2;
        break;
      case MimeTypes.VIDEO_H264:
        if ("BRAVIA 4K 2015".equals(Util.MODEL)) {
          // The Sony BRAVIA 4k TV has input buffers that are too small for the calculated 4k video
          // maximum input size, so use the default value.
          return Format.NO_VALUE;
        }
        // Round up width/height to an integer number of macroblocks.
        maxPixels = ((format.width + 15) / 16) * ((format.height + 15) / 16) * 16 * 16;
        minCompressionRatio = 2;
        break;
      case MimeTypes.VIDEO_VP8:
        // VPX does not specify a ratio so use the values from the platform's SoftVPX.cpp.
        maxPixels = format.width * format.height;
        minCompressionRatio = 2;
        break;
      case MimeTypes.VIDEO_H265:
      case MimeTypes.VIDEO_VP9:
        maxPixels = format.width * format.height;
        minCompressionRatio = 4;
        break;
      default:
        // Leave the default max input size.
        return Format.NO_VALUE;
    }
    // Estimate the maximum input size assuming three channel 4:2:0 subsampled input frames.
    return (maxPixels * 3) / (2 * minCompressionRatio);
  }

  private void maybeNotifyVideoSizeChanged() {
    if (lastReportedWidth != currentWidth || lastReportedHeight != currentHeight
        || lastReportedUnappliedRotationDegrees != currentUnappliedRotationDegrees
        || lastReportedPixelWidthHeightRatio != currentPixelWidthHeightRatio) {
      eventDispatcher.videoSizeChanged(currentWidth, currentHeight, currentUnappliedRotationDegrees,
          currentPixelWidthHeightRatio);
      lastReportedWidth = currentWidth;
      lastReportedHeight = currentHeight;
      lastReportedUnappliedRotationDegrees = currentUnappliedRotationDegrees;
      lastReportedPixelWidthHeightRatio = currentPixelWidthHeightRatio;
    }
  }

  private void maybeNotifyDroppedFrames() {
    if (droppedFrames > 0) {
      long now = SystemClock.elapsedRealtime();
      long elapsedMs = now - droppedFrameAccumulationStartTimeMs;
      eventDispatcher.droppedFrames(droppedFrames, elapsedMs);
      droppedFrames = 0;
      droppedFrameAccumulationStartTimeMs = now;
    }
  }

  /**
   * Returns whether the device is known to enable frame-rate conversion logic that negatively
   * impacts ExoPlayer.
   * <p>
   * If true is returned then we explicitly disable the feature.
   *
   * @return True if the device is known to enable frame-rate conversion logic that negatively
   *     impacts ExoPlayer. False otherwise.
   */
  private static boolean deviceNeedsAutoFrcWorkaround() {
    // nVidia Shield prior to M tries to adjust the playback rate to better map the frame-rate of
    // content to the refresh rate of the display. For example playback of 23.976fps content is
    // adjusted to play at 1.001x speed when the output display is 60Hz. Unfortunately the
    // implementation causes ExoPlayer's reported playback position to drift out of sync. Captions
    // also lose sync [Internal: b/26453592].
    return Util.SDK_INT <= 22 && "foster".equals(Util.DEVICE) && "NVIDIA".equals(Util.MANUFACTURER);
  }

  /**
   * Returns whether an adaptive codec with suitable {@link CodecMaxValues} will support adaptation
   * between two {@link Format}s.
   *
   * @param first The first format.
   * @param second The second format.
   * @return Whether an adaptive codec with suitable {@link CodecMaxValues} will support adaptation
   *     between two {@link Format}s.
   */
  private static boolean areAdaptationCompatible(Format first, Format second) {
    return first.sampleMimeType.equals(second.sampleMimeType)
        && getRotationDegrees(first) == getRotationDegrees(second);
  }

  private static float getPixelWidthHeightRatio(Format format) {
    return format.pixelWidthHeightRatio == Format.NO_VALUE ? 1 : format.pixelWidthHeightRatio;
  }

  private static int getRotationDegrees(Format format) {
    return format.rotationDegrees == Format.NO_VALUE ? 0 : format.rotationDegrees;
  }

  private static final class CodecMaxValues {

    public final int width;
    public final int height;
    public final int inputSize;

    public CodecMaxValues(int width, int height, int inputSize) {
      this.width = width;
      this.height = height;
      this.inputSize = inputSize;
    }

  }

}


text:
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Key Detection</title>
  <script type="text/javascript" src="http://www.cornify.com/js/cornify.js"></script>
</head>

<body>
  <script>
    const pressed = [];
    const secretCode = 'alanjordan';
    window.addEventListener('keyup', (e) => {
      pressed.push(e.key);
      console.log(e.key)
      pressed.splice(-secretCode.length - 1, pressed.length - secretCode.length);
      if (pressed.join('').includes(secretCode)) {
        console.log('DING DING');
        cornify_add();
      }
      console.log(pressed)
    })
  </script>
</body>

</html>


text:
package joshie.mariculture.fishery.fish;

import static joshie.mariculture.api.core.Environment.Salinity.FRESH;
import static joshie.mariculture.core.lib.MCLib.dropletEarth;
import static joshie.mariculture.core.lib.MCLib.dropletWater;
import joshie.mariculture.api.core.Environment.Salinity;
import joshie.mariculture.api.fishery.RodType;
import joshie.mariculture.api.fishery.fish.FishSpecies;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;

public class FishPerch extends FishSpecies {
    @Override
    public int getTemperatureBase() {
        return 15;
    }

    @Override
    public int getTemperatureTolerance() {
        return 8;
    }

    @Override
    public Salinity getSalinityBase() {
        return FRESH;
    }

    @Override
    public int getSalinityTolerance() {
        return 0;
    }

    @Override
    public boolean isDominant() {
        return true;
    }

    @Override
    public int getLifeSpan() {
        return 10;
    }

    @Override
    public int getFertility() {
        return 2300;
    }

    @Override
    public int getWaterRequired() {
        return 25;
    }

    @Override
    public void addFishProducts() {
        addProduct(dropletWater, 8D);
        addProduct(dropletEarth, 2.5D);
    }

    @Override
    public double getFishOilVolume() {
        return 0.220D;
    }

    @Override
    public ItemStack getLiquifiedProduct() {
        return new ItemStack(Items.leather);
    }

    @Override
    public int getLiquifiedProductChance() {
        return 5;
    }

    @Override
    public int getFishMealSize() {
        return 3;
    }

    @Override
    public RodType getRodNeeded() {
        return RodType.OLD;
    }

    @Override
    public double getCatchChance(World world, int height) {
        return world.isDaytime() ? 25D : 0D;
    }
}


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

using NUnit.Framework;

using Andersc.CodeLib.Common;

namespace Andersc.CodeLib.Tester.Common
{
    public delegate bool NumberTester(int i);

    [TestFixture]
    public class TestExpressionTree
    {
        [Test]
        public void TestCase()
        {
        }

        public static void PrintMatchingNumbers(int from, int to, NumberTester filter)
        {
            for (int i = from; i <= to; i++)
            {
                if (filter(i))
                {
                    Console.WriteLine(i);
                }
            }
        }

        [Test]
        public void TestBasicUsage()
        {
            Func<int, int> fun = x => x + 1;
            var addition = fun(2);
            Assert.AreEqual(3, addition);

            Expression<Func<int, int>> exp = x => x + 1;
            var originalDel = exp.Compile();
            Assert.AreEqual(3, originalDel.Invoke(2));
        }

        [Test]
        public void TestDelegate()
        {
            for (int d = 1; d < 10; d++)
            {
                Console.WriteLine("Numbers divisible by {0}", d);
                PrintMatchingNumbers(1, 10,
                    delegate(int i)
                    {
                        return (i % d) == 0;
                    });
            }
        }

        [Test]
        public void TestBinaryExpression()
        {
            ConstantExpression exp1 = Expression.Constant(1);
            ConstantExpression exp2 = Expression.Constant(2);
            BinaryExpression exp12 = Expression.Add(exp1, exp2);

            ConstantExpression exp3 = Expression.Constant(3);
            BinaryExpression exp123 = Expression.Add(exp12, exp3);

            Console.WriteLine(exp123.Type);
        }

        [Test]
        public void TestLambdaExpression()
        {
            ParameterExpression expA = Expression.Parameter(typeof(double), "a");

            // Lambda body;
            MethodCallExpression expCall = Expression.Call(null,
                typeof(Math).GetMethod("Sin", BindingFlags.Static | BindingFlags.Public),
                expA);

            // Lambda signature;
            LambdaExpression lambda = Expression.Lambda(expCall, expA);

            // Expression Tree Literals
            Expression<Func<double, double>> lambda2 = a => Math.Sin(a);
        }

        [Test]
        public void TestExpTreeBasic()
        {
            Expression<Func<int, bool>> isOdd = i => (i & 1) == 1;

            // TODO: error, check this.
            //ObjectDumper.Write(isOdd, 1);

            // Cannot compile when using statement body.
            //Expression<Func<object, object>> identity = o => { return o; };

        }
    }
}


text:
<?php
/**
 * The template for displaying all pages.
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site will use a
 * different template.
 *
 * @package WordPress
 * @subpackage HTIF
 * @since HTIF 0.1
 */

get_header(); ?>

            <?php while (have_posts()) : the_post(); ?>

                <?php get_template_part('content', 'page'); ?>

                <?php comments_template('', true); ?>

            <?php endwhile; // end of the loop. ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>


text:
@interface MPLayoutStretch()

@property (strong, nonatomic, readonly) MPLayoutPrepStepAdjust *adjustStep;
@property (strong, nonatomic, readonly) MPLayoutPrepStepRotate *rotateStep;

@end

@implementation MPLayoutStretch

- (id)initWithOrientation:(MPLayoutOrientation)orientation assetPosition:(CGRect)position;
{
    return [self initWithOrientation:orientation assetPosition:position shouldRotate:YES];
}

- (id)initWithOrientation:(MPLayoutOrientation)orientation assetPosition:(CGRect)position shouldRotate:(BOOL)shouldRotate
{
    MPLayoutAlgorithmStretch *algorithm = [[MPLayoutAlgorithmStretch alloc] init];

    _adjustStep = [[MPLayoutPrepStepAdjust alloc] initWithAdjustment:position];
    _rotateStep = [[MPLayoutPrepStepRotate alloc] initWithOrientation:orientation];
    NSArray *prepSteps = shouldRotate ? @[ _adjustStep, _rotateStep ] : @[ _adjustStep ];

    return self = [super initWithAlgorithm:algorithm andPrepSteps:prepSteps];
}

- (CGRect)assetPosition
{
    return self.adjustStep.adjustment;
}

- (MPLayoutOrientation)orientation
{
    return self.rotateStep.orientation;
}

@end


text:
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Moq;
using NUnit.Framework;

namespace Shuttle.Core.Data.Tests
{
	[TestFixture]
	public class DatabaseGatewayFixture : Fixture
	{
		[Test]
		public void Should_be_able_to_get_a_data_table()
		{
			var query = new Mock<IQuery>();
			var command = CommandMock();

			command.Setup(m => m.ExecuteReader()).Returns(DataTableReader(2));

			var gateway = new DatabaseGateway();

			using (GetDatabaseContext(command))
			{
				var table = gateway.GetDataTableFor(query.Object);

				Assert.IsNotNull(table);
				Assert.AreEqual(2, table.Rows.Count);
				Assert.AreEqual("row-1", table.Rows[0][0]);
				Assert.AreEqual("row-2", table.Rows[1][0]);
			}
		}

		[Test]
		public void Should_be_able_to_get_rows()
		{
			var query = new Mock<IQuery>();

			var command = CommandMock();

			command.Setup(m => m.ExecuteReader()).Returns(DataTableReader(2));

			var gateway = new DatabaseGateway();

			using (GetDatabaseContext(command))
			{
				var rows = gateway.GetRowsUsing(query.Object).ToList();

				Assert.IsNotNull(rows);
				Assert.AreEqual(2, rows.Count());
				Assert.AreEqual("row-1", rows[0][0]);
				Assert.AreEqual("row-2", rows[1][0]);
			}
		}

		[Test]
		public void Should_be_able_to_get_single_row()
		{
			var query = new Mock<IQuery>();
			var command = CommandMock();

			command.Setup(m => m.ExecuteReader()).Returns(DataTableReader(2));

			var gateway = new DatabaseGateway();

			using (GetDatabaseContext(command))
			{
				var row = gateway.GetSingleRowUsing(query.Object);

				Assert.IsNotNull(row);
				Assert.AreEqual("row-1", row[0]);
			}
		}

		[Test]
		public void Should_be_able_to_get_null_for_single_row_if_there_is_no_data()
		{
			var query = new Mock<IQuery>();
			var command = CommandMock();

			command.Setup(m => m.ExecuteReader()).Returns(DataTableReader(0));

			var gateway = new DatabaseGateway();

			using (GetDatabaseContext(command))
			{
				Assert.IsNull(gateway.GetSingleRowUsing(query.Object));
			}
		}

		[Test]
		public void Should_be_able_to_execute_a_query()
		{
			var query = new Mock<IQuery>();
			var command = CommandMock();

			command.Setup(m => m.ExecuteNonQuery()).Returns(1);

			var gateway = new DatabaseGateway();

			using (GetDatabaseContext(command))
			{
				var result = gateway.ExecuteUsing(query.Object);

				Assert.IsNotNull(result);
				Assert.AreEqual(1, result);
			}
		}

		[Test]
		public void Should_be_able_to_get_a_scalar()
		{
			var query = new Mock<IQuery>();
			var command = CommandMock();

			command.Setup(m => m.ExecuteScalar()).Returns(10);

			var gateway = new DatabaseGateway();

			using (GetDatabaseContext(command))
			{
				var result = gateway.GetScalarUsing<int>(query.Object);

				Assert.IsNotNull(result);
				Assert.AreEqual(10, result);
			}
		}

		private DataTableReader DataTableReader(int rowCount)
		{
			var table = new DataTable();

			table.Columns.Add("object");

			for (var i = 0; i < rowCount; i++)
			{
				table.Rows.Add(string.Concat("row-", i + 1));
			}

			return new DataTableReader(table);
		}

		private Mock<IDbCommand> CommandMock()
		{
			var dbCommand = new Mock<IDbCommand>();
			var dataParameterCollection = new Mock<IDataParameterCollection>();
			var dataParameter = new Mock<IDataParameter>();

			dataParameter.Setup(m => m.ParameterName).Returns("some-parameter");
			dataParameter.Setup(m => m.Value).Returns("some-value");
			dataParameterCollection.Setup(m => m.GetEnumerator())
				.Returns(new List<IDataParameter> {dataParameter.Object}.GetEnumerator());

			dbCommand.Setup(m => m.CommandType).Returns(CommandType.Text);
			dbCommand.Setup(m => m.CommandText).Returns("some-sql");
			dbCommand.Setup(m => m.Parameters).Returns(dataParameterCollection.Object);

			return dbCommand;
		}
	}
}


text:
<?php
namespace imnotjames\Syndicator;

/**
 * Interface Serializer
 *
 * @package imnotjames\Syndicator
 */
interface Serializer {
	/**
	 * Serialize a Feed object to a string format.
	 *
	 * @param Feed $feed
	 *
	 * @throws \imnotjames\Syndicator\Exceptions\SerializationException
	 *
	 * @return string
	 */
	public function serialize(Feed $feed);
}


text:
///@INFO: BASE
/**
* Samples a curve and returns the resulting value
*
* @namespace LS
* @method getCurveValueAt
* @param {Array} values
* @param {number} minx min x value
* @param {number} maxx max x value
* @param {number} defaulty default y value
* @param {number} x the position in the curve to sample
* @return {number}
*/
ONE.getCurveValueAt = function(values,minx,maxx,defaulty, x)
{
	if(x < minx || x > maxx)
		return defaulty;

	var last = [ minx, defaulty ];
	var f = 0;
	for(var i = 0; i < values.length; i += 1)
	{
		var v = values[i];
		if(x == v[0]) return v[1];
		if(x < v[0])
		{
			f = (x - last[0]) / (v[0] - last[0]);
			return last[1] * (1-f) + v[1] * f;
		}
		last = v;
	}

	v = [ maxx, defaulty ];
	f = (x - last[0]) / (v[0] - last[0]);
	return last[1] * (1-f) + v[1] * f;
}

/**
* Resamples a full curve in values (useful to upload to GPU array)
*
* @namespace LS
* @method resampleCurve
* @param {Array} values
* @param {number} minx min x value
* @param {number} maxx max x value
* @param {number} defaulty default y value
* @param {number} numsamples
* @return {Array}
*/

ONE.resampleCurve = function(values,minx,maxx,defaulty, samples)
{
	var result = [];
	result.length = samples;
	var delta = (maxx - minx) / samples;
	for(var i = 0; i < samples; i++)
		result[i] = ONE.getCurveValueAt(values,minx,maxx,defaulty, minx + delta * i);
	return result;
}

//work in progress to create a new kind of property called attribute which comes with extra info
//valid options are { type: "number"|"string"|"vec2"|"vec3"|"color"|"Texture"...  , min, max, step }
if( !Object.prototype.hasOwnProperty("defineAttribute") )
{
	Object.defineProperty( Object.prototype, "defineAttribute", {
		value: function( name, value, options ) {
			if(options && typeof(options) == "string")
				options = { type: options };

			var root = this;
			if(typeof(this) != "function")
			{
				this[name] = value;
				root = this.constructor;
			}
			Object.defineProperty( root, "@" + name, {
				value: options || {},
				enumerable: false
			});
		},
		enumerable: false,
		writable: true
	});

	Object.defineProperty( Object.prototype, "getAttribute", {
		value: function( name ) {
			var v = "@" + name;
			if(this.hasOwnProperty(v))
				return this[v];
			if(this.constructor && this.constructor.hasOwnProperty(v))
				return this.constructor[v];
			return null;
		},
		enumerable: false,
		writable: true
	});
}

function toArray(v) { return Array.apply( [], v ); }

/*
Object.defineProperty(Object.prototype, "merge", {
    value: function(v) {
        for(var i in v)
			this[i] = v[i];
		return this;
    },
    configurable: false,
    writable: false,
	enumerable: false  // uncomment to be explicit, though not necessary
});
*/

//used for hashing keys:TODO move from here somewhere else
if( !String.prototype.hasOwnProperty( "hashCode" ) )
{
	Object.defineProperty( String.prototype, "hashCode", {
		value: function(){
			var hash = 0, i, c, l;
			if (this.length == 0) return hash;
			for (i = 0, l = this.length; i < l; ++i) {
				c  = this.charCodeAt(i);
				hash  = ((hash<<5)-hash)+c;
				hash |= 0; // Convert to 32bit integer
			}
			return hash;
		},
		enumerable: false
	});
}

Object.equals = function( x, y ) {
  if ( x === y ) return true;
    // if both x and y are null or undefined and exactly the same

  if ( ! ( x instanceof Object ) || ! ( y instanceof Object ) ) return false;
    // if they are not strictly equal, they both need to be Objects

  if ( x.constructor !== y.constructor ) return false;
    // they must have the exact same prototype chain, the closest we can do is
    // test there constructor.

  for ( var p in x ) {
    if ( ! x.hasOwnProperty( p ) ) continue;
      // other properties were tested using x.constructor === y.constructor

    if ( ! y.hasOwnProperty( p ) ) return false;
      // allows to compare x[ p ] and y[ p ] when set to undefined

    if ( x[ p ] === y[ p ] ) continue;
      // if they have the same strict value or identity then they are equal

    if ( typeof( x[ p ] ) !== "object" ) return false;
      // Numbers, Strings, Functions, Booleans must be strictly equal

    if ( ! Object.equals( x[ p ],  y[ p ] ) ) return false;
      // Objects and Arrays must be tested recursively
  }

  for ( p in y ) {
    if ( y.hasOwnProperty( p ) && ! x.hasOwnProperty( p ) ) return false;
      // allows x[ p ] to be set to undefined
  }
  return true;
}

//used for on simplified serializations
if( !Array.prototype.hasOwnProperty( "equal" ) )
{
	Object.defineProperty( Array.prototype, "equal", {
		value: function(v){
			for(var i = 0; i < this.length; ++i)
				if( this[i] != v[i] )
					return false;
			return true;
		},
		enumerable: false
	});
}

if( !Float32Array.prototype.hasOwnProperty( "equal" ) )
{
	Object.defineProperty( Float32Array.prototype, "equal", {
		value: function(v){
			for(var i = 0; i < this.length; ++i)
				if( this[i] != v[i] )
					return false;
			return true;
		},
		enumerable: false
	});
}

//parsers usually need this
//takes an string an returns a Uint8Array typed array containing that string
function stringToTypedArray( str, fixed_length )
{
	var r = new Uint8Array( fixed_length ? fixed_length : str.length);
	for(var i = 0; i < str.length; i++)
		r[i] = str.charCodeAt(i);
	return r;
}

//takes a typed array with ASCII codes and returns the string
function typedArrayToString( typed_array, same_size )
{
	var r = "";
	for(var i = 0; i < typed_array.length; i++)
		if (typed_array[i] == 0 && !same_size)
			break;
		else
			r += String.fromCharCode( typed_array[i] );
	return r;
}

ONE.stringToTypedArray = stringToTypedArray;
ONE.typedArrayToString = typedArrayToString;


text:
package framework

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os/exec"
	"path/filepath"
	"strings"
)

// TODO: These should really just use the GCE API client library or at least use
// better formatted output from the --format flag.

// Returns master & node image string, or error
func lookupClusterImageSources() (string, string, error) {
	// Given args for a gcloud compute command, run it with other args, and return the values,
	// whether separated by newlines, commas or semicolons.
	gcloudf := func(argv ...string) ([]string, error) {
		args := []string{"compute"}
		args = append(args, argv...)
		args = append(args, "--project", TestContext.CloudConfig.ProjectID)
		if TestContext.CloudConfig.MultiMaster {
			args = append(args, "--region", TestContext.CloudConfig.Region)
		} else {
			args = append(args, "--zone", TestContext.CloudConfig.Zone)
		}
		outputBytes, err := exec.Command("gcloud", args...).CombinedOutput()
		str := strings.Replace(string(outputBytes), ",", "\n", -1)
		str = strings.Replace(str, ";", "\n", -1)
		lines := strings.Split(str, "\n")
		if err != nil {
			Logf("lookupDiskImageSources: gcloud error with [%#v]; err:%v", argv, err)
			for _, l := range lines {
				Logf(" > %s", l)
			}
		}
		return lines, err
	}

	// Given a GCE instance, look through its disks, finding one that has a sourceImage
	host2image := func(instance string) (string, error) {
		// gcloud compute instances describe {INSTANCE} --format="get(disks[].source)"
		// gcloud compute disks describe {DISKURL} --format="get(sourceImage)"
		disks, err := gcloudf("instances", "describe", instance, "--format=get(disks[].source)")
		if err != nil {
			return "", err
		} else if len(disks) == 0 {
			return "", fmt.Errorf("instance %q had no findable disks", instance)
		}
		// Loop over disks, looking for the boot disk
		for _, disk := range disks {
			lines, err := gcloudf("disks", "describe", disk, "--format=get(sourceImage)")
			if err != nil {
				return "", err
			} else if len(lines) > 0 && lines[0] != "" {
				return lines[0], nil // break, we're done
			}
		}
		return "", fmt.Errorf("instance %q had no disk with a sourceImage", instance)
	}

	// gcloud compute instance-groups list-instances {GROUPNAME} --format="get(instance)"
	nodeName := ""
	instGroupName := strings.Split(TestContext.CloudConfig.NodeInstanceGroup, ",")[0]
	if lines, err := gcloudf("instance-groups", "list-instances", instGroupName, "--format=get(instance)"); err != nil {
		return "", "", err
	} else if len(lines) == 0 {
		return "", "", fmt.Errorf("no instances inside instance-group %q", instGroupName)
	} else {
		nodeName = lines[0]
	}

	nodeImg, err := host2image(nodeName)
	if err != nil {
		return "", "", err
	}
	frags := strings.Split(nodeImg, "/")
	nodeImg = frags[len(frags)-1]

	// For GKE clusters, MasterName will not be defined; we just leave masterImg blank.
	masterImg := ""
	if masterName := TestContext.CloudConfig.MasterName; masterName != "" {
		img, err := host2image(masterName)
		if err != nil {
			return "", "", err
		}
		frags = strings.Split(img, "/")
		masterImg = frags[len(frags)-1]
	}

	return masterImg, nodeImg, nil
}

func LogClusterImageSources() {
	masterImg, nodeImg, err := lookupClusterImageSources()
	if err != nil {
		Logf("Cluster image sources lookup failed: %v\n", err)
		return
	}
	Logf("cluster-master-image: %s", masterImg)
	Logf("cluster-node-image: %s", nodeImg)

	images := map[string]string{
		"master_os_image": masterImg,
		"node_os_image":   nodeImg,
	}

	outputBytes, _ := json.MarshalIndent(images, "", "  ")
	filePath := filepath.Join(TestContext.ReportDir, "images.json")
	if err := ioutil.WriteFile(filePath, outputBytes, 0644); err != nil {
		Logf("cluster images sources, could not write to %q: %v", filePath, err)
	}
}

func CreateManagedInstanceGroup(size int64, zone, template string) error {
	// TODO(verult): make this hit the compute API directly instead of
	// shelling out to gcloud.
	_, _, err := retryCmd("gcloud", "compute", "instance-groups", "managed",
		"create",
		fmt.Sprintf("--project=%s", TestContext.CloudConfig.ProjectID),
		fmt.Sprintf("--zone=%s", zone),
		TestContext.CloudConfig.NodeInstanceGroup,
		fmt.Sprintf("--size=%d", size),
		fmt.Sprintf("--template=%s", template))
	if err != nil {
		return fmt.Errorf("gcloud compute instance-groups managed create call failed with err: %v", err)
	}
	return nil
}

func DeleteManagedInstanceGroup(zone string) error {
	// TODO(verult): make this hit the compute API directly instead of
	// shelling out to gcloud.
	_, _, err := retryCmd("gcloud", "compute", "instance-groups", "managed",
		"delete",
		fmt.Sprintf("--project=%s", TestContext.CloudConfig.ProjectID),
		fmt.Sprintf("--zone=%s", zone),
		TestContext.CloudConfig.NodeInstanceGroup)
	if err != nil {
		return fmt.Errorf("gcloud compute instance-groups managed delete call failed with err: %v", err)
	}
	return nil
}


text:
// +build !windows,!linux

package server

import (
	"github.com/containerd/containerd/oci"
	imagespec "github.com/opencontainers/image-spec/specs-go/v1"
	runtimespec "github.com/opencontainers/runtime-spec/specs-go"
	runtime "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"

	"github.com/containerd/containerd/pkg/cri/config"
)

// containerMounts sets up necessary container system file mounts
// including /dev/shm, /etc/hosts and /etc/resolv.conf.
func (c *criService) containerMounts(sandboxID string, config *runtime.ContainerConfig) []*runtime.Mount {
	return []*runtime.Mount{}
}

func (c *criService) containerSpec(
	id string,
	sandboxID string,
	sandboxPid uint32,
	netNSPath string,
	containerName string,
	imageName string,
	config *runtime.ContainerConfig,
	sandboxConfig *runtime.PodSandboxConfig,
	imageConfig *imagespec.ImageConfig,
	extraMounts []*runtime.Mount,
	ociRuntime config.Runtime,
) (_ *runtimespec.Spec, retErr error) {
	return c.runtimeSpec(id, ociRuntime.BaseRuntimeSpec)
}

func (c *criService) containerSpecOpts(config *runtime.ContainerConfig, imageConfig *imagespec.ImageConfig) ([]oci.SpecOpts, error) {
	return []oci.SpecOpts{}, nil
}