text:
<?php

class OmniwebShowtimes_AdminPageFramework_Form_View___Script_CollapsibleSection extends OmniwebShowtimes_AdminPageFramework_Form_View___Script_Base {
    public function construct() {
        wp_enqueue_script('juery');
        wp_enqueue_script('juery-ui-accordion');
    }
    static public function getScript() {
        $_aParams = func_get_args() + array(null);
        $_oMsg = $_aParams[0];
        $_sToggleAllButtonHTML = '"' . self::_getToggleAllButtonHTML($_oMsg) . '"';
        return <<<JAVASCRIPTS
( function( $ ) {

    jQuery( document ).ready( function() {
        jQuery( this ).initializeOmniwebShowtimes_AdminPageFrameworkCollapsibleSections();
    });

    /**
     * Gets triggered when a widget of the framework is saved.
     * @since    3.7.0
     */
    jQuery( document ).bind( 'omniweb-showtimes_saved_widget', function( event, oWidget ){
        jQuery( oWidget ).initializeOmniwebShowtimes_AdminPageFrameworkCollapsibleSections();
    });

    $.fn.initializeOmniwebShowtimes_AdminPageFrameworkCollapsibleSections = function() {

        // Expand collapsible sections that are set not to collapse by default
        jQuery( this ).find( '.omniweb-showtimes-collapsible-sections-title[data-is_collapsed=\"0\"]' )
            .next( '.omniweb-showtimes-collapsible-sections-content' )
            .slideDown( 'fast' );
        jQuery( this ).find( '.omniweb-showtimes-collapsible-section-title[data-is_collapsed=\"0\"]' )
            .closest( '.omniweb-showtimes-section-table' )
            .find( 'tbody' )
            .slideDown( 'fast' );

        // Hide collapsible sections of 'section' containers as they are somehow do not get collapsed by default.
        jQuery( this ).find( '.omniweb-showtimes-collapsible-section-title[data-is_collapsed=\"1\"]' )
            .closest( '.omniweb-showtimes-section-table' )
            .find( 'tbody' )
            .hide();

        // Bind the click event to the title element.
        jQuery( this ).find( '.omniweb-showtimes-collapsible-sections-title, .omniweb-showtimes-collapsible-section-title' ).enableOmniwebShowtimes_AdminPageFrameworkCollapsibleButton();

        // Insert the toggle all button.
        jQuery( this ).find( '.omniweb-showtimes-collapsible-title[data-toggle_all_button!=\"0\"]' ).each( function(){

            var _oThis        = jQuery( this ); // to access from inside the below each() method.
            var _bForSections = jQuery( this ).hasClass( 'omniweb-showtimes-collapsible-sections-title' );   // or for the 'section' container.
            var _isPositions  = jQuery( this ).data( 'toggle_all_button' );
            var _isPositions  = 1 === _isPositions
                ? 'top-right'   // default
                : _isPositions;
            var _aPositions   = 'string' === typeof _isPositions
                ? _isPositions.split( ',' )
                : [ 'top-right' ];

            jQuery.each( _aPositions, function( iIndex, _sPosition ) {

                var _oButton = jQuery( $_sToggleAllButtonHTML );
                var _sLeftOrRight = -1 !== jQuery.inArray( _sPosition, [ 'top-right', 'bottom-right', '0' ] )   // if found
                    ? 'right'   // default
                    : 'left';
                _oButton.find( '.omniweb-showtimes-collapsible-toggle-all-button' ).css( 'float', _sLeftOrRight );

                var _sTopOrBottom = -1 !== jQuery.inArray( _sPosition, [ 'top-right', 'top-left', '0' ] )   // if found
                    ? 'before'   // default
                    : 'after';

                // Insert the button - there are two versions: for the sections container or the section container.
                if ( _bForSections ) {
                    var _oTargetElement = 'before' === _sTopOrBottom
                        ? _oThis
                        : _oThis.next( '.omniweb-showtimes-collapsible-content' );
                        _oTargetElement[ _sTopOrBottom ]( _oButton );
                } else {    // for 'section' containers
                    _oThis.closest( '.omniweb-showtimes-section' )[ _sTopOrBottom ]( _oButton );
                }

                // Expand or collapse this panel
                jQuery( _oButton ).unbind( 'click' );       // for initially dropped (created) widgets
                _oButton.click( function(){

                    var _oButtons = _bForSections
                        ? jQuery( this ).closest( '.omniweb-showtimes-sectionset' ).siblings().andSelf().find( '> .omniweb-showtimes-collapsible-toggle-all-button-container' )
                        : jQuery( this ).siblings( '.omniweb-showtimes-collapsible-toggle-all-button-container' ).andSelf();
                    _oButtons.toggleClass( 'flipped' );
                    if ( _bForSections ) {
                        _oButton.parent().parent().children().children( '* > .omniweb-showtimes-collapsible-title' ).each( function() {
                            jQuery( this ).trigger( 'click', [ 'by_toggle_all_button' ] );
                        } );
                    } else {
                        _oButton.closest( '.omniweb-showtimes-sections' ).children( '.omniweb-showtimes-section' ).children( '.omniweb-showtimes-section-table' ).children( 'caption' ).children( '.omniweb-showtimes-collapsible-title' ).each( function() {
                            jQuery( this ).trigger( 'click', [ 'by_toggle_all_button' ] );
                        } );
                    }

                } );

            });

        } );

    }
    /**
     * Binds the click event to collapsible buttons.
     */
    $.fn.enableOmniwebShowtimes_AdminPageFrameworkCollapsibleButton = function() {

        /**
         * Unbind the event first.
         * This is for widgets as the initial model widgets placed on the left side is dragged-and-dropped to a sidebar definition container.
         * Then the event binding will be lost so it needs to be rebound.
         */
        jQuery( this ).unbind( 'click' );

        jQuery( this ).click( function( event, sContext ){

            // If a field element is clicked, do not collapse or expand the container box.
            var _sClickedTag = jQuery( event. target ).prop( 'tagName' ).toLowerCase();
            if ( -1 !== jQuery.inArray( _sClickedTag, [ 'input', 'span', 'label', 'fieldset' ] ) ) {
                return true;
            }

            // Expand or collapse this panel
            var _oThis = jQuery( this );
            var _sContainerType = jQuery( this ).hasClass( 'omniweb-showtimes-collapsible-sections-title' )
                ? 'sections'
                : 'section';
            var _oTargetContent = 'sections' === _sContainerType
                ? jQuery( this ).next( '.omniweb-showtimes-collapsible-content' ).first()
                : jQuery( this ).parent().siblings( 'tbody' );
            var _sAction = _oTargetContent.is( ':visible' ) ? 'collapse' : 'expand';

            _oThis.removeClass( 'collapsed' );
            _oTargetContent.slideToggle( 'fast', function(){

                // For Google Chrome, table-caption will animate smoothly for the 'section' containers (not 'sections' container). For FireFox, 'block' is required. For IE both works.
                var _bIsChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
                if ( 'expand' === _sAction && 'section' === _sContainerType && ! _bIsChrome ) {
                    _oTargetContent.css( 'display', 'block' );
                }

                // Update the class selector.
                if ( _oTargetContent.is( ':visible' ) ) {
                    _oThis.removeClass( 'collapsed' );
                } else {
                    _oThis.addClass( 'collapsed' );
                }

            } );

            // If it is triggered from the toggle all button, do not continue.
            if ( 'by_toggle_all_button' === sContext ) {
                return;
            }

            // If collapse_others_on_expand argument is true, collapse others
            if ( 'expand' === _sAction && _oThis.data( 'collapse_others_on_expand' ) ) {
                _oThis.parent().parent().children().children( '* > .omniweb-showtimes-collapsible-content' ).not( _oTargetContent ).slideUp( 'fast', function() {
                    jQuery( this ).prev( '.omniweb-showtimes-collapsible-title' ).addClass( 'collapsed' );
                });
            }

        });

    }
}( jQuery ));
JAVASCRIPTS;

    }
    static private function _getToggleAllButtonHTML($oMsg) {
        $_sLabelToggleAll = $oMsg->get('toggle_all');
        $_sLabelToggleAllSections = $oMsg->get('toggle_all_collapsible_sections');
        $_sDashIconSort = self::getAOrB(version_compare($GLOBALS['wp_version'], '3.8', '<'), '', 'dashicons dashicons-sort');
        $_sText = self::getAOrB($_sDashIconSort, '', $_sLabelToggleAll);
        return "
" . "" . $_sText . "" . "
";
    }
}


text:
//
//  IXSize.h
//  Ignite Engine
//
//  Created by Brandon on 3/25/15.
//

//

#import <Foundation/Foundation.h>

@interface IXSize : NSObject

@property (nonatomic, strong) NSString* width;
@property (nonatomic, strong) NSString* height;

@end

redpajama_set_name: RedPajamaGithub


text:
package org.hibernate.test.domain;

import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CacheConcurrencyStrategy;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * org.hibernate.test.domain.Event
 *
 * @author sunghyouk.bae@gmail.com
 * @since 13. 4. 6. 오전 12:53
 */
@Entity
@org.hibernate.annotations.Cache(region = "account", usage = CacheConcurrencyStrategy.READ_WRITE)
@Getter
@Setter
public class Event implements Serializable {

    private static final long serialVersionUID = 4714760453860670689L;

    @Id
    @GeneratedValue
    private Long id;

    private String title;

    @Temporal(TemporalType.TIMESTAMP)
    private Date date;

    @ManyToMany(cascade = { CascadeType.ALL })
    private Set<Person> participants = new HashSet<Person>();

    @ManyToOne
    @JoinColumn(name = "Organizer_Id")
    private Person organizer;

    public void addParticipant(Person person) {
        participants.add(person);
        person.getEvents().add(this);
    }

    public void removeParticipant(Person person) {
        participants.remove(person);
        person.getEvents().remove(this);
    }

    public String toString() {
        return getTitle() + ": " + getDate();
    }
}


text:
#include "cbase.h"
#include <vgui_controls/ImagePanel.h>
#include "vgui_controls/AnimationController.h"
#include <vgui_controls/ImagePanel.h>
#include "soundenvelope.h"
#include "BriefingTooltip.h"
#include "StatsBar.h"

// memdbgon must be the last include file in a .cpp file!!!
#include <tier0/memdbgon.h>

StatsBar::StatsBar(vgui::Panel *parent, const char *name) :
	vgui::Panel(parent, name)
{
	m_pUnusedBar = new vgui::Panel( this, "UnusedBarPanel" );
	m_pUnusedBar->SetVisible( true );
	m_pBar = new vgui::Panel(this, "StatsBarPanel");
	m_pBar->SetVisible(false);
	m_pIncreaseBar = new vgui::Panel( this, "IncreaseBarPanel" );
	m_pIncreaseBar->SetVisible( false );

	m_pLabel = new vgui::Label(this, "StatsBarLabel", "");
	m_pLabel->SetContentAlignment(vgui::Label::a_center);
	m_pLabel->SetVisible(false);

	m_fStart = 0;
	m_fTarget = 0;
	m_fCurrent = 0;
	m_flBorder = 2.0f;
	m_fIncreaseRate = 100.0f;
	m_bDisplayInteger = true;
	m_bDisplayPercentage = false;
	m_bDisplayTime = false;
	m_bShowCumulativeTotal = false;
	m_flNextUpdateTime = 0;
	m_flUpdateInterval = 0.05f;

	m_bInit = false;
	m_fStartTime = 0;
	m_pLoopingSound = NULL;
	m_hExternalCounter = NULL;
	m_bShowMaxOnCounter = false;

	m_TextColor = Color(255,255,255,255);	// white
	m_BarColor = Color(66,142,192,255);	// lightblue
	m_IncreaseBarColor = Color(66,142,192,255);	// white
	m_BackgroundColor = Color(65,74,96,255);	// greyblue
	m_UnusedColor = Color(65,74,96,255);
}

void StatsBar::SetColors(Color text, Color bar, Color increasebar, Color unusedbar, Color background)
{
	m_TextColor = text;
	m_BarColor = bar;
	m_IncreaseBarColor = increasebar;
	m_BackgroundColor = background;
	m_UnusedColor = unusedbar;

	m_pLabel->SetFgColor( m_TextColor );
	m_pBar->SetBgColor( m_BarColor );
	m_pUnusedBar->SetBgColor( unusedbar );
	m_pIncreaseBar->SetBgColor( m_IncreaseBarColor );
	SetBgColor( m_BackgroundColor );

	m_flNextUpdateTime = 0;
// 	if ( m_hExternalCounter.Get() )
// 	{
// 		m_hExternalCounter->SetFgColor( m_TextColor );
// 	}
}

void StatsBar::ApplySchemeSettings(vgui::IScheme *pScheme)
{
	BaseClass::ApplySchemeSettings(pScheme);

	if ( m_hExternalCounter.Get() )
	{
// 		m_hExternalCounter->SetFgColor(m_TextColor);
// 		m_hExternalCounter->SetFont(pScheme->GetFont("Default"));
	}
	else
	{
		m_pLabel->SetFgColor(m_TextColor);
		m_pLabel->SetFont( pScheme->GetFont( "Default", IsProportional() ) );
	}

	m_pUnusedBar->SetPaintBackgroundEnabled( true );
	m_pUnusedBar->SetPaintBackgroundType( 0 );
	m_pUnusedBar->SetBgColor( m_UnusedColor );

	m_pBar->SetPaintBackgroundEnabled( true );
	m_pBar->SetPaintBackgroundType( 0 );
	m_pBar->SetBgColor( m_BarColor );

	m_pIncreaseBar->SetPaintBackgroundEnabled( true );
	m_pIncreaseBar->SetPaintBackgroundType( 0 );
	m_pIncreaseBar->SetBgColor( m_IncreaseBarColor );

	SetPaintBackgroundEnabled(true);
	SetPaintBackgroundType(0);
	SetBgColor(m_BackgroundColor);
	m_flNextUpdateTime = 0;
}

void StatsBar::PerformLayout()
{
	BaseClass::PerformLayout();

	int w, t;
	GetSize(w, t);

	m_pLabel->SetBounds(0, 0, w, t);
}

void StatsBar::OnThink()
{
	BaseClass::OnThink();

	if ( m_flNextUpdateTime > gpGlobals->curtime )
		return;

	m_flNextUpdateTime = gpGlobals->curtime + m_flUpdateInterval;

	if (m_fStartTime > 0 && gpGlobals->curtime > m_fStartTime && m_bInit)
	{
		float passed = gpGlobals->curtime - m_fStartTime;
		float increase = m_fStart + passed * m_fIncreaseRate;
		//if (m_bDisplayInteger)
		//increase = int(increase);

		m_fCurrent = MIN(increase, m_fTarget);
	}

	float fScale = (ScreenWidth() / 1024.0f);
	int w, t, padding;
	GetSize(w, t);
	padding = m_flBorder * fScale;

	float flBarMin = GetBarMin();
	float flBarMax = GetBarMax();
	float initial_bar_fraction = ( m_fStart - flBarMin ) / ( flBarMax - flBarMin );
	initial_bar_fraction = MAX( initial_bar_fraction, 0 );

	m_pUnusedBar->SetBounds( padding, padding, w - padding * 2, t - padding * 2 );

	if ( initial_bar_fraction > 0 )
	{
		m_pBar->SetVisible(true);
		m_pBar->SetBounds(padding, padding, (w - padding * 2) * initial_bar_fraction, (t - padding * 2));
	}
	else
	{
		m_pBar->SetVisible(false);
	}

	if (m_fStartTime > 0 && gpGlobals->curtime > m_fStartTime && m_bInit)
	{
		// update bar and label
		float bar_fraction = ( m_fCurrent - MAX( m_fStart, flBarMin ) ) / ( flBarMax - flBarMin );
		bar_fraction = MAX( bar_fraction, 0 );

		if ( bar_fraction > 0 )
		{
			m_pIncreaseBar->SetVisible(true);
			m_pIncreaseBar->SetBounds( padding + (w - padding * 2) * initial_bar_fraction, padding, (w - padding * 2) * bar_fraction, (t - padding * 2));
		}
		else
		{
			m_pIncreaseBar->SetVisible(false);
		}

		bool bFinished = (m_fCurrent == m_fTarget);
		if (m_fTarget > 0 && m_fCurrent > 0)
		{
			if (m_pLoopingSound == NULL && !bFinished)
			{
				CLocalPlayerFilter filter;
				m_pLoopingSound = CSoundEnvelopeController::GetController().SoundCreate( filter, 0, "ASWInterface.AreaBracketsLoop" );
				CSoundEnvelopeController::GetController().Play( m_pLoopingSound, 1.0, 100 );
			}
			else if (m_pLoopingSound && bFinished)
			{
				CSoundEnvelopeController::GetController().SoundDestroy( m_pLoopingSound );
				m_pLoopingSound = NULL;
				CLocalPlayerFilter filter;
				C_BaseEntity::EmitSound( filter, -1 /*SOUND_FROM_LOCAL_PLAYER*/, "ASWInterface.Teletype3" );
			}
		}
	}

	// update label text
	int current_number = (int) m_fCurrent;
	int max_number = (int) flBarMax;

	if ( !m_bShowCumulativeTotal )
	{
		current_number = (int) ( m_fCurrent - flBarMin );
		max_number = (int) ( flBarMax - flBarMin );
	}

	char maxbuffer[64] = "";
	if ( m_bShowMaxOnCounter )
	{
		Q_snprintf( maxbuffer, sizeof( maxbuffer ), " / %d", max_number );		// TODO: Support float/time/percentage displays for max?
	}

	char buffer[64];
	if (m_bDisplayTime)
	{
		int minutes = (current_number) / 60;
		int remainder = (current_number) % 60;
		Q_snprintf(buffer, sizeof(buffer), "%.2d:%.2d%s", minutes, remainder, maxbuffer);
	}
	else if (m_bDisplayInteger)
	{
		if (m_bDisplayPercentage)
			Q_snprintf(buffer, sizeof(buffer), "%d%%%s", current_number, maxbuffer);
		else
			Q_snprintf(buffer, sizeof(buffer), "%d%s", current_number, maxbuffer);
	}
	else
	{
		if (m_bDisplayPercentage)
			Q_snprintf(buffer, sizeof(buffer), "%f%%%s", current_number, maxbuffer);
		else
			Q_snprintf(buffer, sizeof(buffer), "%f%s", current_number, maxbuffer);
	}
	if ( m_hExternalCounter.Get() )
	{
		m_hExternalCounter->SetText( buffer );
		m_pLabel->SetVisible( false );
	}
	else
	{
		m_pLabel->SetVisible( true );
		m_pLabel->SetBounds( 0, 0, w, t );
		m_pLabel->SetText( buffer );
	}
}

void StatsBar::Init(float fCurrent, float fTarget, float fIncreaseRate, bool bDisplayInteger, bool bDisplayPercentage)
{
	m_fStart = fCurrent;
	m_fCurrent = fCurrent;
	m_fTarget = fTarget;
	m_fIncreaseRate = fIncreaseRate;
	m_bDisplayInteger = bDisplayInteger;
	m_bDisplayPercentage = bDisplayPercentage;
	m_bInit = true;
	m_flNextUpdateTime = 0;
	InvalidateLayout(false, true);
	//Msg("StatsBar::Init cur=%f target=%f rate=%f max=%f int=%d perc=%d\n", fCurrent, fTarget, fIncreaseRate, fBarMax, bDisplayInteger, bDisplayPercentage);
}

void StatsBar::UseExternalCounter( vgui::Label *pCounter )
{
	m_hExternalCounter = pCounter;
}

void StatsBar::AddMinMax( float flBarMin, float flBarMax )
{
	StatsBarMinMax bounds;
	bounds.flMin = flBarMin;
	bounds.flMax = flBarMax;
	m_Bounds.AddToTail( bounds );
	m_flNextUpdateTime = 0;
}

void StatsBar::ClearMinMax()
{
	m_Bounds.Purge();
	m_flNextUpdateTime = 0;
}

float StatsBar::GetBarMin()
{
	for ( int i = 0; i < m_Bounds.Count(); i++ )
	{
		if ( ( m_fCurrent >= m_Bounds[ i ].flMin && m_fCurrent < m_Bounds[ i ].flMax ) || ( i == m_Bounds.Count() - 1 ) )
			return m_Bounds[ i ].flMin;
	}
	return 0.0f;
}

float StatsBar::GetBarMax()
{
	for ( int i = 0; i < m_Bounds.Count(); i++ )
	{
		if ( ( m_fCurrent >= m_Bounds[ i ].flMin && m_fCurrent < m_Bounds[ i ].flMax ) || ( i == m_Bounds.Count() - 1 ) )
			return m_Bounds[ i ].flMax;
	}
	return 100.0f;
}


text:
class ForumAttachment < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
  has_many :stars, :dependent => :destroy
  belongs_to :document_forum, :class_name => 'Forum', :foreign_key => :forum_id

  cattr_reader :per_page
  @@per_page = 8

  before_create :set_user, :if => :post_id
  after_save   :set_forum_id

  has_attached_file :file

  named_scope :documents, :conditions => ['forum_id IS NOT NULL']
  named_scope :by_forum, lambda{ |forum_id| { :conditions => { :forum_id => forum_id || Forum.all.map(&:id) } } }

  def self.generate(forum_attachments)
    forum_attachments.select{ |fa| !fa.nil? }.map{ |fa| ForumAttachment.new(:file => fa) }
  end

  def name
    file_file_name
  end

  def url
    file.url.gsub("%", "%25")
  end

  def topic
    post.topic
  end

  def forum
    post.forum
  end

  def file_type
    File.extname(name).gsub!('.','')
  end

  searchable do
	  text :file_file_name
	  integer :id
	end

  protected

  def set_user
    self.user_id = self.post.user_id
  end

  def set_forum_id
    already_set_forum_id = update_attribute(:forum_id, self.post.forum_id) if self.post && !self.forum_id && !already_set_forum_id
  end
end


text:
package com.github.ambry.clustermap;

import java.util.List;

/**
 * A callback that needs to be implemented by dynamic implementations of the cluster manager which can be
 * used by dynamic cluster manager components such as {@link AmbryDataNode}, {@link AmbryDisk},
 * {@link AmbryPartition}, and {@link AmbryReplica}
 */
interface ClusterManagerCallback {
  /**
   * Get all replica ids associated with the given {@link AmbryPartition}
   * @param partition the {@link AmbryPartition} for which to get the list of replicas.
   * @return the list of {@link AmbryReplica}s associated with the given partition.
   */
  List<AmbryReplica> getReplicaIdsForPartition(AmbryPartition partition);

  /**
   * Get the counter for the sealed state change for partitions.
   * @return the counter for the sealed state change for partitions.
   */
  long getSealedStateChangeCounter();
}


text:
<?php

/**
 * Analysis types result
 *
 * @package Solarium
 * @subpackage Result
 */
class Solarium_Result_Analysis_Types extends Solarium_Result_Analysis_List
{

    /**
     * Get index analysis list
     *
     * @return Solarium_Result_Analysis_List|null
     */
    public function getIndexAnalysis()
    {
        foreach ($this->_items AS $item) {
            if ($item->getName() == 'index') {
                return $item;
            }
        }

        return null;
    }

    /**
     * Get query analysis list
     *
     * @return Solarium_Result_Analysis_List|null
     */
    public function getQueryAnalysis()
    {
        foreach ($this->_items AS $item) {
            if ($item->getName() == 'query') {
                return $item;
            }
        }

        return null;
    }

}


text:
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

from distutils.extension import Extension

import numpy
try:
    numpy_include = numpy.get_include()
except AttributeError:
    numpy_include = numpy.get_numpy_include()

# Handle cython modules
try:
    from Cython.Distutils import build_ext
    use_cython = True
    cmdclass = {'build_ext': build_ext}
except ImportError:
    use_cython = False
    cmdclass = {}
finally:
    print 'use_cython: {}'.format(use_cython)

ext_modules = [Extension("pyqcprot_bac", ["pyqcprot_bac.{}".format('pyx' if use_cython else 'c')],
                include_dirs=[numpy_include],
                extra_compile_args=["-O3","-ffast-math"])]

setup(
  name = 'Python qcprot_bac module',
  cmdclass = cmdclass,
  ext_modules = ext_modules,
  install_requires = ['MDAnalysis'],
)


text:
'use strict';

const _ = require('lodash');
const objectToHtml = require('../objectToHtml');

function prettyMiddleware() {
  return (request, response, next) => {
    if (request.query.pretty !== undefined) {
      let originalSend = response.send;
      response.send = object => {
        let body = object;
        if (_.isObject(object)) {
          body = objectToHtml(object);
        }
        originalSend.call(response, body);
      };
    }
    next();
  };
}

module.exports = prettyMiddleware;


text:
/** Basic loading screen using DOM
 *
 * Loading screen is a state like any other except that
 * it is loaded from `PLAYGROUND.LoadingScreen`. To override
 * simply define a `PLAYGROUND.LoadingScreen` in your code after
 * playground.js was imported.
 */
PLAYGROUND.LoadingScreen = {

  logoRaw: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAANoAAAASBAMAAADPiN0xAAAAGFBMVEUAAQAtLixHSUdnaGaJioimqKXMzsv7/fr5shgVAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB98EAwkeA4oQWJ4AAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAB9klEQVQ4y72UvW+rMBDAz+FrpVKrrFmesmapWNOlrKjSe1kZ+uoVAvj+/frujG1SaJcqJwU7voOf7xMQzQmsIDi5NPTMsLRntH3U+F6SAZo3NlCvcgBFJz8o+vkDiE63lI95Y/UmpinsZWkgJWJiDbAVQ16htptxSTNloIlugwaw001Ey3ASF3so6L1qLNXzQS5S0UGKL/CI5wWNriE0UH9Yty37LqIVg+wsqu7Ix0MwVBSF/dU+jv2SNnma021LEdPqVnMeU3xAu0kXcSGjmq7Ox4E2Wn88LZ2+EFj3avjixzai6VPVyuYveZLHF2XfdDnvAq27DIHGuq+0DJFsE30OtB1KqOwd8Dr7PcM4b+jfj2g5lp4WyntBK66qua3JzEA+uXJpwH/NlVuzRVPY/kTLB2mjuN+KwdZ8FOy8j2gDbEUSqumnSCY4lf4ibq3IhVM4ycZQRnv+zFqVdJQVn6BxvUqebGpuaNo3sZxwBzjajiMZOoBiwyVF+kCr+nUaJOaGpnAeRPPJZTr4FqmHRXcneEo4DqQ/ftfdnLeDrUAME8xWKPeKCwW6YkEpXfs3p1EWJhdcUAYP0TI/uYaV8cgjwBovaeyWwji2T9rTFIdS/cP/MnkTLRUWxgNNZVin7bT5fqT9miDcUVJzR1gRpfIONMmulU+5Qqr6zXAUqAAAAABJRU5ErkJggg==",

  create: function() {

    var self = this;

    this.logo = new Image;

    this.logo.addEventListener("load", function() {
      self.ready = true;
      self.createElements();
    });

    this.logo.src = this.logoRaw;

    this.background = "#000";

    if (window.getComputedStyle) {
      this.background = window.getComputedStyle(document.body).backgroundColor || "#000";
    }

  },

  enter: function() {

    this.current = 0;

  },

  leave: function() {

    this.locked = true;

    this.animation = this.app.tween(this)
      .to({
        current: 1
      }, 0.5);

  },

  step: function(delta) {

    if (this.locked) {

      if (this.animation.finished) {
        this.locked = false;
        this.wrapper.parentNode.removeChild(this.wrapper);
      }

    } else {

      this.current = this.current + Math.abs(this.app.loader.progress - this.current) * delta;
    }

  },

  createElements: function() {

    this.width = window.innerWidth * 0.6 | 0;
    this.height = window.innerHeight * 0.1 | 0;

    this.wrapper = document.createElement("div");
    this.wrapper.style.width = this.width + "px";
    this.wrapper.style.height = this.height + "px";
    this.wrapper.style.background = "#000";
    this.wrapper.style.border = "4px solid #fff";
    this.wrapper.style.position = "absolute";
    this.wrapper.style.left = (window.innerWidth / 2 - this.width / 2 | 0) + "px";
    this.wrapper.style.top = (window.innerHeight / 2 - this.height / 2 | 0) + "px";
    this.wrapper.style.zIndex = 100;

    this.app.container.appendChild(this.wrapper);

    this.progressBar = document.createElement("div");
    this.progressBar.style.width = "0%";
    this.progressBar.style.height = this.height + "px";
    this.progressBar.style.background = "#fff";

    this.wrapper.appendChild(this.progressBar);

  },

  render: function() {

    if (!this.ready) return;

    this.progressBar.style.width = (this.current * 100 | 0) + "%";

  }

};


text: Page Template


text:
//    !!! ->   TODO: replace 'username' in the line below with the merchants username.     <- !!!

var store_filter = function(_app) {
	var r = {

////////////////////////////////////   CALLBACKS    \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

	vars : {
		templates : [
			"filteredSearchTemplate",
			"filteredSearchTemplateBrand"
			],
		filterLoadingComplete : false,
		filterPages : [],
		filterPageLoadQueue : [],
		elasticFields : {} // will get populated with data from appResource call
		},

	filterData : {}, //will get populated with data from filterPages, pushed from other extensions

	callbacks : {
//executed when extension is loaded. should include any validation that needs to occur.
		init : {
			onSuccess : function()	{
				var r = false; //return false if extension won't load for some reason (account config, dependencies, etc).

				_app.model.addDispatchToQ({"_cmd":"appResource","filename":"elastic_public.json","_tag":{"datapointer":"appResource|elastic_public", "callback":"handleElasticFields","extension":"store_filter"}},'mutable');
				_app.model.dispatchThis('mutable');

				function loadPage(id, successCallback, failCallback){
					var pageObj = _app.ext.store_filter.vars.filterPageLoadQueue[id];
					if(pageObj){
						$.getJSON(pageObj.jsonPath+"?_v="+(new Date()).getTime(), function(json){
							_app.ext.store_filter.filterData[pageObj.id] = json;
							if(typeof successCallback == 'function'){
								successCallback();
								}
							})
							.fail(function(){
								dump("FILTER DATA FOR PAGE: "+pageObj.id+" UNAVAILABLE AT PATH: "+pageObj.jsonPath);
								if(typeof failCallback == 'function'){
									failCallback();
									}
								});
						}
					else {
						if(typeof failCallback == 'function'){
							failCallback();
							}
						}
					};

				function queuePage(pageObj){
					_app.ext.store_filter.vars.filterPageLoadQueue[pageObj.id] = pageObj;
					};

				for(var i in _app.ext.store_filter.vars.filterPages){
					queuePage(_app.ext.store_filter.vars.filterPages[i]);
					}
				_app.ext.store_filter.vars.filterPages = {push : queuePage}

				function showPage(routeObj){
					routeObj.params.templateID = routeObj.params.templateID || "filteredSearchTemplate";
					routeObj.params.dataset = $.extend(true, {}, _app.ext.store_filter.filterData[routeObj.params.id]);

					var optStrs = routeObj.params.dataset.optionList;
					routeObj.params.dataset.options = routeObj.params.dataset.options || {};
					for(var i in optStrs){
						var o = optStrs[i];
						if(_app.ext.store_filter.vars.elasticFields[o]){
							routeObj.params.dataset.options[o] = $.extend(true, {}, _app.ext.store_filter.vars.elasticFields[o]);
							if(routeObj.searchParams && routeObj.searchParams[o]){
								var values = routeObj.searchParams[o].split('|');
								for(var i in routeObj.params.dataset.options[o].options){
									var option = routeObj.params.dataset.options[o].options[i];
									if($.inArray(option.v, values) >= 0){
										option.checked = "checked";
										}
									}
								}
							}
						else {
							dump("Unrecognized option "+o+" on filter page "+routeObj.params.id);
							}
						}
					// routeObj.params.loadFullList = _app.ext.seo_robots.u.isRobotPresent();
					routeObj.params.loadFullList = false;
					routeObj.params.pageType = 'static';
					routeObj.params.require = ['templates.html','store_routing','store_search','prodlist_infinite'];
					_app.ext.quickstart.a.showContent(routeObj.value,routeObj.params);
					}

				_app.router.addAlias('filter', function(routeObj){
					if(_app.ext.store_filter.filterData[routeObj.params.id]){
						showPage(routeObj);
						}
					else {
						loadPage(
							routeObj.params.id,
							function(){showPage(routeObj);},
							function(){_app.router.handleURIString('/404');}
							);
						}
					});

				_app.router.addAlias('brandFilter', function(routeObj){
					routeObj.params.templateID = "filteredSearchTemplateBrand"
					if(_app.ext.store_filter.filterData[routeObj.params.id]){
						showPage(routeObj);
						}
					else {
						loadPage(
							routeObj.params.id,
							function(){showPage(routeObj);},
							function(){_app.router.handleURIString('/404');}
							);
						}
					});

				//_app.router.appendHash({'type':'match','route':'filter/{{id}}*','callback':});

				//if there is any functionality required for this extension to load, put it here. such as a check for async google, the FB object, etc. return false if dependencies are not present. don't check for other extensions.
				r = true;

				return r;
				},
			onError : function()	{
//errors will get reported for this callback as part of the extensions loading.  This is here for extra error handling purposes.
//you may or may not need it.
				_app.u.dump('BEGIN store_filter.callbacks.init.onError');
				}
			},
		handleElasticFields : {
			onSuccess : function(rd){
				var data = _app.data[rd.datapointer];
				for(var i in data.contents['@products']){
					var field = data.contents['@products'][i];
					_app.ext.store_filter.vars.elasticFields[field.id] = field;
					}
				},
			onError : function(){
				_app.u.dump('BEGIN store_filter.callbacks.handleElasticFields.onError');
				}
			}
		}, //callbacks

////////////////////////////////////   ACTION    \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//actions are functions triggered by a user interaction, such as a click/tap.
//these are going the way of the do do, in favor of app events. new extensions should have few (if any) actions.
		a : {

			}, //Actions

////////////////////////////////////   TLCFORMATS    \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

		tlcFormats : {
			filterrange : function(data, thisTLC){
				var args = thisTLC.args2obj(data.command.args, data.globals);
				if(typeof args.filterType === "undefined"){
					args.filterType = 'range';
					}
				if(args.index){

					var range = data.globals.binds[data.globals.focusBind];
					range.min = range.min || 0;
					range.step = range.step || 1;
					var $tag = data.globals.tags[data.globals.focusTag];

					$tag.attr('data-filter-index',args.index);
					$tag.attr('data-filter-type',args.filterType);

					$tag.slider({
						range : true,
						min : range.min,
						max : range.max,
						step : range.step,
						values : [range.min, range.max],
						//change : function(event, ui){_app.ext.store_filter.e.execFilteredSearch($(this), event);},
						slide : function(event, ui){$('.sliderVal', ui.handle).text(ui.value);},
						create : function(event, ui){
							$(this).find(".ui-slider-handle").each(function(i){
								var vals = $tag.slider('values');
								var $tooltip = $('$'+vals[i]+'');
								$(this).append($tooltip);
								});
							}
						})
					}
				else {
					return false;
					}
				return true;
				},
			filtercheckboxlist : function(data, thisTLC){
				var args = thisTLC.args2obj(data.command.args, data.globals);
				if(typeof args.filterType === "undefined"){
					args.filterType = 'checkboxList';
					}
				if(args.index){
					var list = data.globals.binds[data.globals.focusBind];
					var $tag = data.globals.tags[data.globals.focusTag];
					if(args.filterType){
						$tag.attr('data-filter-type',args.filterType);
						}
					$tag.attr('data-filter-index',args.index);
					for(var i in list){
						var o = list[i];
						var $t = $('

');
						$t.append('<input data-filter="filterCheckbox" type="checkbox" name="'+o.v+'" '+(o.checked ? 'checked="checked"' : '')+' />'+o.p+' ');
						//$('input', $t).on('change', function(event){
						//	_app.ext.store_filter.e.execFilteredSearch($(this), event);
						//	});
						if(o.hidden){$t.addClass('displayNone');}
						$tag.append($t);
						}
					return true;
					}
				else {
					return false;
					}
				},
			}, //tlcFormats
////////////////////////////////////   UTIL [u]   \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

//utilities are typically functions that are exected by an event or action.
//any functions that are recycled should be here.
		u : {
			}, //u [utilities]

//app-events are added to an element through data-app-event="extensionName|functionName"
//right now, these are not fully supported, but they will be going forward.
//they're used heavily in the admin.html file.
//while no naming convention is stricly forced,
//when adding an event, be sure to do off('click.appEventName') and then on('click.appEventName') to ensure the same event is not double-added if app events were to get run again over the same template.
		e : {
			execFilteredSearch : function($form, p){
				var loadFullList = $form.data('loadFullList');
				dump("Executing Filtered Search");
				if(loadFullList){
					_app.ext.store_filter.vars.filterLoadingComplete = false;
					}
				else {
					_app.ext.store_filter.vars.filterLoadingComplete = true;
					}
				var $page = $form.data('jqContext');
				dump($page);
				p.preventDefault();
				var $resultsContainer = $page.closest('[data-filter=parent]').find('[data-filter=resultsList]');
				dump($form.attr('data-filter-base'));
				var filterBase = JSON.parse($form.attr('data-filter-base'));
				var elasticsearch = {
					"filter" : {
						"and" : [filterBase]
						},
					"facets" : {}
					}
				$('[data-filter-type=sort]', $form).each(function(){
					var $selectedOption = $('option:selected',$(this));
					if($selectedOption.attr('data-filter-sort-attribute')){
						elasticsearch.sort = elasticsearch.sort || [];
						var sort = {};
						sort[$selectedOption.attr('data-filter-sort-attribute')] = {"order":$selectedOption.attr('data-filter-sort-direction')};
						elasticsearch.sort.push(sort);
						}
					});
				$('[data-filter-type=range]', $form).each(function(){
					var f = {"range" : {}};
					var vals = $(this).slider('values');
					var m =$(this).attr('data-filter-range-mult')
					if(m){
						vals = $.map(vals, function(e, i){ return e*m; });
						}
					f.range[$(this).attr('data-filter-index')] = {
						"gte" : vals[0],
						"lte" : vals[1]
						}
					elasticsearch.filter.and.push(f);
					});
				$('[data-filter-type=checkboxList]', $form).each(function(){
					var filter = {"or" : []};
					$('[data-filter=count]', $(this)).empty();
					$('input[data-filter=filterCheckbox]', $(this)).each(function(){
						var index = $(this).closest('[data-filter-index]').attr('data-filter-index');
						if(!elasticsearch.facets[index]){
							elasticsearch.facets[index] = {"terms" : {"field":index}}
							}
						if($(this).is(":checked")){
							var f = {"term" : {}};
							f.term[index] = $(this).attr('name');
							filter.or.push(f);
							}
						});

					if(filter.or.length > 0){
						elasticsearch.filter.and.push(filter);
						}
					else {
						}
					});

				var es;
				if(!elasticsearch.sort){
					var tmp = {
						"query" :{
							"function_score" : {
								"filter":elasticsearch.filter,
								"functions" : [
									{
										"field_value_factor" : {
											"field" : "booster"
											}
										}
									],
								"boost_mode" : "sum"
								}
							},
						"facets" : elasticsearch.facets
						}
					//tmp.query.function_score.boost_mode = "sum";
					//tmp.query.function_score.script_score = {"script":"doc['boost'].value"};
					//tmp.query.function_score.script_score = {"script":"_score"};
					es = _app.ext.store_search.u.buildElasticRaw(tmp);
					}
				else {
					es = _app.ext.store_search.u.buildElasticRaw(elasticsearch);
					}

				//var es = _app.ext.store_search.u.buildElasticRaw(elasticsearch);
				if(loadFullList){
					es.size = 200;
					es.timeout = 60;
					}
				else {
					es.size = 30;
					}
				$resultsContainer.empty();
				$resultsContainer.append('

');
				_app.ext.store_search.u.updateDataOnListElement($resultsContainer,_app.u.getBlacklistedObject(es, ["facets"]),1);
				//dump(es);
				_app.model.dispatchThis();
				_app.ext.store_search.calls.appPublicSearch.init(es, {'callback':function(rd){
					if(_app.model.responseHasErrors(rd)){
						_app.u.throwMessage(rd);
						}
					else {
						$('.loader', rd.list).empty().remove();
						_app.ext.prodlist_infinite.callbacks.handleInfiniteElasticResults.onSuccess(rd);
						if(_app.data[rd.datapointer].facets){
							$('[data-filter-type=checkboxList]',rd.filterList).each(function(){
								$('input', $(this)).each(function(){
									var index = $(this).closest('[data-filter-index]').attr('data-filter-index');
									var val = $(this).attr('name');

									var $fg = $(this).closest('.filterGroup')
									var $ic = $(this).closest('[data-filter=inputContainer]');

									var summary = $.grep(_app.data[rd.datapointer].facets[index].terms, function(e, i){
										return e.term === val;
										})[0];
									if(summary || $(this).prop('checked')){
										summary = summary || {count:0};
										$fg.show();
										$ic.show();
										$ic.addClass('show');
										$('[data-filter=count]', $ic).text("("+summary.count+")");
										}
									else {
										if($fg.hasClass('countHideImmune')){/*Don't hide it if it's immune*/}
										else{
											$ic.hide();
											$ic.removeClass('show');
											//$(this).prop('checked',false);
											if($('[data-filter=inputContainer].show',$fg).length < 1){
												$fg.hide();
												}
											}
										}
									});

								});
							}
						}
					}, 'datapointer':'appFilteredSearch','templateID':'productListTemplateResults','list':$resultsContainer, 'filterList' : $form, 'loadFullList' : loadFullList});
				_app.model.dispatchThis();

				}
			}, //e [app Events]
		couplers : {
			addPage : function(args){
				_app.ext.store_filter.vars.filterPageLoadQueue[args.id] = args;
				}
			}
		} //r object.
	return r;
	}


text:
#include "tensorflow/python/client/tf_session_helper.h"

#include <cstring>

#include "tensorflow/c/c_api.h"
#include "tensorflow/c/tf_status_helper.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/log_memory.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/lib/core/coding.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/equal_graph_def.h"
#include "tensorflow/python/lib/core/ndarray_tensor_bridge.h"

namespace tensorflow {

namespace {

static const char* kFeedDictErrorMsg =
    "feed_dict must be a dictionary mapping strings to NumPy arrays.";

Status PyArrayDescr_to_TF_DataType(PyArray_Descr* descr,
                                   TF_DataType* out_tf_datatype) {
  PyObject* key;
  PyObject* value;
  Py_ssize_t pos = 0;
  if (PyDict_Next(descr->fields, &pos, &key, &value)) {
    // In Python 3, the keys of numpy custom struct types are unicode, unlike
    // Python 2, where the keys are bytes.
    const char* key_string =
        PyBytes_Check(key) ? PyBytes_AsString(key)
                           : PyBytes_AsString(PyUnicode_AsASCIIString(key));
    if (!key_string) {
      return errors::Internal("Corrupt numpy type descriptor");
    }
    tensorflow::string key = key_string;
    // The typenames here should match the field names in the custom struct
    // types constructed in test_util.py.
    // TODO(mrry,keveman): Investigate Numpy type registration to replace this
    // hard-coding of names.
    if (key == "quint8") {
      *out_tf_datatype = TF_QUINT8;
    } else if (key == "qint8") {
      *out_tf_datatype = TF_QINT8;
    } else if (key == "qint16") {
      *out_tf_datatype = TF_QINT16;
    } else if (key == "quint16") {
      *out_tf_datatype = TF_QUINT16;
    } else if (key == "qint32") {
      *out_tf_datatype = TF_QINT32;
    } else if (key == "resource") {
      *out_tf_datatype = TF_RESOURCE;
    } else {
      return errors::Internal("Unsupported numpy data type");
    }
    return Status::OK();
  }
  return errors::Internal("Unsupported numpy data type");
}

Status PyArray_TYPE_to_TF_DataType(PyArrayObject* array,
                                   TF_DataType* out_tf_datatype) {
  int pyarray_type = PyArray_TYPE(array);
  PyArray_Descr* descr = PyArray_DESCR(array);
  switch (pyarray_type) {
    case NPY_FLOAT16:
      *out_tf_datatype = TF_HALF;
      break;
    case NPY_FLOAT32:
      *out_tf_datatype = TF_FLOAT;
      break;
    case NPY_FLOAT64:
      *out_tf_datatype = TF_DOUBLE;
      break;
    case NPY_INT32:
      *out_tf_datatype = TF_INT32;
      break;
    case NPY_UINT8:
      *out_tf_datatype = TF_UINT8;
      break;
    case NPY_UINT16:
      *out_tf_datatype = TF_UINT16;
      break;
    case NPY_INT8:
      *out_tf_datatype = TF_INT8;
      break;
    case NPY_INT16:
      *out_tf_datatype = TF_INT16;
      break;
    case NPY_INT64:
      *out_tf_datatype = TF_INT64;
      break;
    case NPY_BOOL:
      *out_tf_datatype = TF_BOOL;
      break;
    case NPY_COMPLEX64:
      *out_tf_datatype = TF_COMPLEX64;
      break;
    case NPY_COMPLEX128:
      *out_tf_datatype = TF_COMPLEX128;
      break;
    case NPY_OBJECT:
      *out_tf_datatype = TF_STRING;
      break;
    case NPY_VOID:
      // Quantized types are currently represented as custom struct types.
      // PyArray_TYPE returns NPY_VOID for structs, and we should look into
      // descr to derive the actual type.
      // Direct feeds of certain types of ResourceHandles are represented as a
      // custom struct type.
      return PyArrayDescr_to_TF_DataType(descr, out_tf_datatype);
    default:
      // TODO(mrry): Support these.
      return errors::Internal("Unsupported feed type");
  }
  return Status::OK();
}

// Iterate over the string array 'array', extract the ptr and len of each string
// element and call f(ptr, len).
template <typename F>
Status PyBytesArrayMap(PyArrayObject* array, F f) {
  Safe_PyObjectPtr iter = tensorflow::make_safe(
      PyArray_IterNew(reinterpret_cast<PyObject*>(array)));
  while (PyArray_ITER_NOTDONE(iter.get())) {
    auto item = tensorflow::make_safe(PyArray_GETITEM(
        array, static_cast<char*>(PyArray_ITER_DATA(iter.get()))));
    if (!item.get()) {
      return errors::Internal("Unable to get element from the feed - no item.");
    }
    char* ptr;
    Py_ssize_t len;

    if (PyUnicode_Check(item.get())) {
#if PY_VERSION_HEX >= 0x03030000
      // Accept unicode by converting to UTF-8 bytes.
      ptr = PyUnicode_AsUTF8AndSize(item.get(), &len);
      if (!ptr) {
        return errors::Internal(
            "Unable to get element from the feed as UTF-8.");
      }
      f(ptr, len);
#else
      PyObject* utemp = PyUnicode_AsUTF8String(item.get());
      if (!utemp || PyBytes_AsStringAndSize(utemp, &ptr, &len) == -1) {
        Py_XDECREF(utemp);
        return errors::Internal(
            "Unable to convert element from the feed to UTF-8.");
      }
      f(ptr, len);
      Py_DECREF(utemp);
#endif
    } else {
      int success = PyBytes_AsStringAndSize(item.get(), &ptr, &len);
      if (success != 0) {
        return errors::Internal(
            "Unable to get element from the feed as bytes.");
      }
      f(ptr, len);
    }
    PyArray_ITER_NEXT(iter.get());
  }
  return Status::OK();
}

// Encode the strings in 'array' into a contiguous buffer and return the base of
// the buffer. The caller takes ownership of the buffer.
Status EncodePyBytesArray(PyArrayObject* array, tensorflow::int64 nelems,
                          size_t* size, void** buffer) {
  // Compute bytes needed for encoding.
  *size = 0;
  TF_RETURN_IF_ERROR(PyBytesArrayMap(array, [&size](char* ptr, Py_ssize_t len) {
    *size +=
        sizeof(tensorflow::uint64) + tensorflow::core::VarintLength(len) + len;
  }));
  // Encode all strings.
  std::unique_ptr<char[]> base_ptr(new char[*size]);
  char* base = base_ptr.get();
  char* data_start = base + sizeof(tensorflow::uint64) * nelems;
  char* dst = data_start;  // Where next string is encoded.
  tensorflow::uint64* offsets = reinterpret_cast<tensorflow::uint64*>(base);

  TF_RETURN_IF_ERROR(PyBytesArrayMap(
      array, [&base, &data_start, &dst, &offsets](char* ptr, Py_ssize_t len) {
        *offsets = (dst - data_start);
        offsets++;
        dst = tensorflow::core::EncodeVarint64(dst, len);
        memcpy(dst, ptr, len);
        dst += len;
      }));
  CHECK_EQ(dst, base + *size);
  *buffer = base_ptr.release();
  return Status::OK();
}

// Determine the pointer and offset of the string at offset 'i' in the string
// tensor 'src', whose total length is 'num_elements'.
static Status TF_StringTensor_GetPtrAndLen(const TF_Tensor* src,
                                           tensorflow::int64 num_elements,
                                           tensorflow::int64 i,
                                           const char** ptr,
                                           tensorflow::uint64* len) {
  const char* input = reinterpret_cast<const char*>(TF_TensorData(src));
  const size_t src_size = TF_TensorByteSize(src);
  const char* data_start = input + sizeof(tensorflow::uint64) * num_elements;
  const char* limit = input + src_size;
  tensorflow::uint64 offset =
      reinterpret_cast<const tensorflow::uint64*>(input)[i];
  const char* p =
      tensorflow::core::GetVarint64Ptr(data_start + offset, limit, len);
  if (static_cast<int64>(offset) >= (limit - data_start) || !p ||
      static_cast<int64>(*len) > (limit - p)) {
    return errors::InvalidArgument("Malformed TF_STRING tensor; element ", i,
                                   " out of range");
  }
  *ptr = p;
  return Status::OK();
}

// Copy the string at offset 'i' in the (linearized) string tensor 'tensor' into
// 'pyarray' at offset pointed by the 'i_ptr' iterator.
static Status CopyStringToPyArrayElement(PyArrayObject* pyarray, void* i_ptr,
                                         TF_Tensor* tensor,
                                         tensorflow::int64 num_elements,
                                         tensorflow::int64 i) {
  const char* ptr = nullptr;
  tensorflow::uint64 len = 0;
  TF_RETURN_IF_ERROR(
      TF_StringTensor_GetPtrAndLen(tensor, num_elements, i, &ptr, &len));
  auto py_string = tensorflow::make_safe(PyBytes_FromStringAndSize(ptr, len));
  int success = PyArray_SETITEM(
      pyarray, static_cast<char*>(PyArray_ITER_DATA(i_ptr)), py_string.get());
  if (success != 0) {
    return errors::Internal("Error setting element ", i);
  }
  return Status::OK();
}

// Determine the dimensions of a numpy ndarray to be created to represent an
// output Tensor.
gtl::InlinedVector<npy_intp, 4> GetPyArrayDimensionsForTensor(
    const TF_Tensor* tensor, tensorflow::int64* nelems) {
  if (TF_TensorType(tensor) == TF_RESOURCE) {
    gtl::InlinedVector<npy_intp, 4> dims(1);
    ResourceHandle* resource_handle =
        reinterpret_cast<ResourceHandle*>(TF_TensorData(tensor));
    dims[0] = resource_handle->SerializeAsString().size();
    *nelems = dims[0];

    return dims;
  } else {
    const int ndims = TF_NumDims(tensor);
    gtl::InlinedVector<npy_intp, 4> dims(ndims);
    *nelems = 1;
    for (int i = 0; i < ndims; ++i) {
      dims[i] = TF_Dim(tensor, i);
      *nelems *= dims[i];
    }

    return dims;
  }
}

// Determine the type description (PyArray_Descr) of a numpy ndarray to be
// created to represent an output Tensor.
Status GetPyArrayDescrForTensor(const TF_Tensor* tensor,
                                PyArray_Descr** descr) {
  if (TF_TensorType(tensor) == TF_RESOURCE) {
    PyObject* field = PyTuple_New(3);
#if PY_MAJOR_VERSION < 3
    PyTuple_SetItem(field, 0, PyBytes_FromString("resource"));
#else
    PyTuple_SetItem(field, 0, PyUnicode_FromString("resource"));
#endif
    PyTuple_SetItem(field, 1, PyArray_TypeObjectFromType(NPY_UBYTE));
    PyTuple_SetItem(field, 2, PyLong_FromLong(1));
    PyObject* fields = PyList_New(1);
    PyList_SetItem(fields, 0, field);
    int convert_result = PyArray_DescrConverter(fields, descr);
    Py_CLEAR(field);
    Py_CLEAR(fields);
    if (convert_result != 1) {
      return errors::Internal("Failed to create numpy array description for ",
                              "TF_RESOURCE-type tensor");
    }
  } else {
    int type_num = -1;
    TF_RETURN_IF_ERROR(
        TF_DataType_to_PyArray_TYPE(TF_TensorType(tensor), &type_num));
    *descr = PyArray_DescrFromType(type_num);
  }

  return Status::OK();
}

// Converts the given TF_Tensor to a numpy ndarray.
// If the returned status is OK, the caller becomes the owner of *out_array.
Status TFTensorToPyArray(Safe_TF_TensorPtr tensor, PyObject** out_ndarray) {
  // A fetched operation will correspond to a null tensor, and a None
  // in Python.
  if (tensor == nullptr) {
    Py_INCREF(Py_None);
    *out_ndarray = Py_None;
    return Status::OK();
  }

  tensorflow::int64 nelems = -1;
  gtl::InlinedVector<npy_intp, 4> dims =
      GetPyArrayDimensionsForTensor(tensor.get(), &nelems);

  // Convert TensorFlow dtype to numpy type descriptor.
  PyArray_Descr* descr = nullptr;
  TF_RETURN_IF_ERROR(GetPyArrayDescrForTensor(tensor.get(), &descr));

  // If the type is neither string nor resource we can reuse the Tensor memory.
  TF_Tensor* original = tensor.get();
  TF_Tensor* moved = TF_TensorMaybeMove(tensor.release());
  if (moved != nullptr) {
    if (ArrayFromMemory(dims.size(), dims.data(), TF_TensorData(moved),
                        static_cast<DataType>(TF_TensorType(moved)),
                        [moved] { TF_DeleteTensor(moved); }, out_ndarray)
            .ok()) {
      return Status::OK();
    }
  }
  tensor.reset(original);

  // Copy the TF_TensorData into a newly-created ndarray and return it.
  Safe_PyObjectPtr safe_out_array =
      tensorflow::make_safe(PyArray_Empty(dims.size(), dims.data(), descr, 0));
  if (!safe_out_array) {
    return errors::Internal("Could not allocate ndarray");
  }
  PyArrayObject* py_array =
      reinterpret_cast<PyArrayObject*>(safe_out_array.get());
  if (PyArray_NBYTES(py_array) !=
      static_cast<int64>(TF_TensorByteSize(tensor.get()))) {
    if (TF_TensorType(tensor.get()) == TF_STRING) {
      // Copy element by element.
      auto iter = tensorflow::make_safe(PyArray_IterNew(safe_out_array.get()));
      for (tensorflow::int64 i = 0; i < nelems; ++i) {
        auto s = CopyStringToPyArrayElement(py_array, iter.get(), tensor.get(),
                                            nelems, i);
        if (!s.ok()) {
          return s;
        }
        PyArray_ITER_NEXT(iter.get());
      }
    } else if (TF_TensorType(tensor.get()) == TF_RESOURCE) {
      ResourceHandle* resource_handle =
          reinterpret_cast<ResourceHandle*>(TF_TensorData(tensor.get()));
      memcpy(PyArray_DATA(py_array),
             resource_handle->SerializeAsString().c_str(),
             PyArray_NBYTES(py_array));
    } else {
      return errors::Internal("ndarray was ", PyArray_NBYTES(py_array),
                              " bytes but TF_Tensor was ",
                              TF_TensorByteSize(tensor.get()), " bytes");
    }
  } else {
    memcpy(PyArray_DATA(py_array), TF_TensorData(tensor.get()),
           PyArray_NBYTES(py_array));
  }

  // PyArray_Return turns rank 0 arrays into numpy scalars
  *out_ndarray = PyArray_Return(
      reinterpret_cast<PyArrayObject*>(safe_out_array.release()));
  return Status::OK();
}

// Converts the given numpy ndarray to a (safe) TF_Tensor. The returned
// TF_Tensor in `out_tensor` will have its own Python reference to `ndarray`s
// data. After `out_tensor` is destroyed, this reference must (eventually) be
// decremented via ClearDecrefCache().
//
// If `ndarray` contains a resource handle, `*resource_handle` will be set to
// the deserialized handle. Otherwise it is set to nullptr. Caller becomes owner
// of `*resource_handle` if it's set, and it must outlive the returned
// `out_tensor`.
//
// `resource_handle` and `out_tensor` must be non-null. Caller retains ownership
// of `ndarray`.
Status PyArrayToTFTensor(PyObject* ndarray, Safe_TF_TensorPtr* out_tensor,
                         ResourceHandle** resource_handle) {
  DCHECK(out_tensor != nullptr);
  DCHECK(resource_handle != nullptr);
  *resource_handle = nullptr;

  // Make sure we dereference this array object in case of error, etc.
  Safe_PyObjectPtr array_safe(make_safe(
      PyArray_FromAny(ndarray, nullptr, 0, 0, NPY_ARRAY_CARRAY, nullptr)));
  if (!array_safe) return errors::InvalidArgument(kFeedDictErrorMsg);
  PyArrayObject* array = reinterpret_cast<PyArrayObject*>(array_safe.get());

  // Convert numpy dtype to TensorFlow dtype.
  TF_DataType dtype = TF_FLOAT;
  TF_RETURN_IF_ERROR(PyArray_TYPE_to_TF_DataType(array, &dtype));

  tensorflow::int64 nelems = 1;
  gtl::InlinedVector<int64_t, 4> dims;
  for (int i = 0; i < PyArray_NDIM(array); ++i) {
    dims.push_back(PyArray_SHAPE(array)[i]);
    nelems *= dims[i];
  }

  // Create a TF_Tensor based on the fed data. In the case of non-string data
  // type, this steals a reference to array, which will be relinquished when
  // the underlying buffer is deallocated. For string, a new temporary buffer
  // is allocated into which the strings are encoded.
  if (dtype == TF_RESOURCE) {
    const string serialized(reinterpret_cast<char*>(PyArray_DATA(array)),
                            PyArray_NBYTES(array));
    *resource_handle = new ResourceHandle();
    (*resource_handle)->ParseFromString(serialized);
    TF_Tensor* tf_tensor =
        TF_AllocateTensor(dtype, {}, 0, sizeof(ResourceHandle));
    std::memcpy(TF_TensorData(tf_tensor),
                reinterpret_cast<void*>(*resource_handle),
                sizeof(ResourceHandle));
    *out_tensor = make_safe(tf_tensor);
  } else if (dtype != TF_STRING) {
    size_t size = PyArray_NBYTES(array);
    array_safe.release();
    *out_tensor = make_safe(TF_NewTensor(dtype, dims.data(), dims.size(),
                                         PyArray_DATA(array), size,
                                         &DelayedNumpyDecref, array));
  } else {
    size_t size = 0;
    void* encoded = nullptr;
    TF_RETURN_IF_ERROR(EncodePyBytesArray(array, nelems, &size, &encoded));
    *out_tensor =
        make_safe(TF_NewTensor(dtype, dims.data(), dims.size(), encoded, size,
                               [](void* data, size_t len, void* arg) {
                                 delete[] reinterpret_cast<char*>(data);
                               },
                               nullptr));
  }
  return Status::OK();
}

}  // namespace

Safe_PyObjectPtr make_safe(PyObject* o) {
  return Safe_PyObjectPtr(o, Py_DECREF_wrapper);
}

Safe_TF_TensorPtr make_safe(TF_Tensor* tensor) {
  return Safe_TF_TensorPtr(tensor, TF_DeleteTensor);
}

void TF_Run_wrapper_helper(TF_DeprecatedSession* session, const char* handle,
                           const TF_Buffer* run_options, PyObject* feed_dict,
                           const NameVector& output_names,
                           const NameVector& target_nodes,
                           TF_Status* out_status, PyObjectVector* out_values,
                           TF_Buffer* run_outputs) {
  // 1. Convert the feed inputs to the appropriate form for TF_Run.
  if (!PyDict_Check(feed_dict)) {
    Set_TF_Status_from_Status(out_status,
                              errors::InvalidArgument(kFeedDictErrorMsg));
    return;
  }

  NameVector input_names;
  std::vector<Safe_TF_TensorPtr> inputs_safe;  // Used to delete tensors.
  TF_TensorVector inputs_unsafe;     // Used to contain the arg to TF_Run.

  PyObject* key;
  PyObject* value;
  Py_ssize_t pos = 0;
  int index = 0;
  Status s;

  gtl::InlinedVector<std::unique_ptr<ResourceHandle>, 4> resource_handles;
  while (PyDict_Next(feed_dict, &pos, &key, &value)) {
    char* key_string = PyBytes_AsString(key);
    if (!key_string) {
      Set_TF_Status_from_Status(out_status,
                                errors::InvalidArgument(kFeedDictErrorMsg));
      return;
    }
    input_names.push_back(key_string);

    inputs_safe.emplace_back(make_safe(static_cast<TF_Tensor*>(nullptr)));
    ResourceHandle* resource_handle;
    s = PyArrayToTFTensor(value, &inputs_safe.back(), &resource_handle);
    if (!s.ok()) {
      Set_TF_Status_from_Status(out_status, s);
      return;
    }
    inputs_unsafe.push_back(inputs_safe.back().get());
    if (resource_handle != nullptr) {
      resource_handles.emplace_back(resource_handle);
    }
    ++index;
  }

  // 2. Allocate a container for the output data.
  TF_TensorVector outputs(output_names.size());

  // In case any tensors were leftover from previous runs we might as well clear
  // them here.
  ClearDecrefCache();

  // 3. Actually call TF_Run().
  Py_BEGIN_ALLOW_THREADS;
  if (handle == nullptr) {
    TF_Run(session, run_options, input_names.data(), inputs_unsafe.data(),
           input_names.size(), const_cast<const char**>(output_names.data()),
           outputs.data(), output_names.size(),
           const_cast<const char**>(target_nodes.data()), target_nodes.size(),
           run_outputs, out_status);
  } else {
    TF_PRun(session, handle, input_names.data(), inputs_unsafe.data(),
            input_names.size(), const_cast<const char**>(output_names.data()),
            outputs.data(), output_names.size(),
            const_cast<const char**>(target_nodes.data()), target_nodes.size(),
            out_status);
  }

  Py_END_ALLOW_THREADS;

  // Decref any numpy arrays we are not using anymore.
  ClearDecrefCache();

  if (TF_GetCode(out_status) != TF_OK) {
    return;
  }

  // 4. We now own the fetched tensors, so set up a safe container to
  // delete them when we exit this scope.
  std::vector<Safe_TF_TensorPtr> tf_outputs_safe;
  for (const auto& output : outputs) {
    tf_outputs_safe.emplace_back(make_safe(output));
  }

  // 5. Convert the fetched tensors into numpy ndarrays. Store them in a safe
  // container so that we do not leak
  std::vector<Safe_PyObjectPtr> py_outputs_safe;
  for (size_t i = 0; i < output_names.size(); ++i) {
    PyObject* py_array;
    s = TFTensorToPyArray(std::move(tf_outputs_safe[i]), &py_array);
    if (!s.ok()) {
      Set_TF_Status_from_Status(out_status, s);
      return;
    }
    py_outputs_safe.emplace_back(make_safe(py_array));
  }

  // 6. If we reach this point, we have successfully built a list of objects
  // so we can release them from the safe container.
  for (auto& output : py_outputs_safe) {
    out_values->push_back(output.release());
  }
}

// Wrapper for TF_Run that converts the arguments to appropriate types.
// If *out_status is OK, the caller becomes the owner of the PyObjects
// in *out_values.
void TF_Run_wrapper(TF_DeprecatedSession* session, const TF_Buffer* run_options,
                    PyObject* feed_dict, const NameVector& output_names,
                    const NameVector& target_nodes, TF_Status* out_status,
                    PyObjectVector* out_values, TF_Buffer* run_outputs) {
  TF_Run_wrapper_helper(session, nullptr, run_options, feed_dict, output_names,
                        target_nodes, out_status, out_values, run_outputs);
  ClearDecrefCache();
}

// Wrapper for TF_PRunSetup that converts the arguments to appropriate types.
// If *out_status is OK, the caller becomes the owner of *out_handle.
void TF_PRunSetup_wrapper(TF_DeprecatedSession* session,
                          const NameVector& input_names,
                          const NameVector& output_names,
                          const NameVector& target_nodes, TF_Status* out_status,
                          const char** out_handle) {
  Py_BEGIN_ALLOW_THREADS;
  TF_PRunSetup(
      session, const_cast<const char**>(input_names.data()), input_names.size(),
      const_cast<const char**>(output_names.data()), output_names.size(),
      const_cast<const char**>(target_nodes.data()), target_nodes.size(),
      out_handle, out_status);
  Py_END_ALLOW_THREADS;
}

// Wrapper for TF_PRun that converts the arguments to appropriate types.
// If *out_status is OK, the caller becomes the owner of the PyObjects
// in *out_values.
void TF_PRun_wrapper(TF_DeprecatedSession* session, const char* handle,
                     PyObject* feed_dict, const NameVector& output_names,
                     TF_Status* out_status, PyObjectVector* out_values) {
  TF_Run_wrapper_helper(session, handle, nullptr, feed_dict, output_names,
                        NameVector(), out_status, out_values, nullptr);
  ClearDecrefCache();
}

// Wrapper for TF_Reset that converts the string vectors to character arrays.
void TF_Reset_wrapper(const TF_SessionOptions* opt,
                      const NameVector& containers, TF_Status* out_status) {
  TF_Reset(opt, const_cast<const char**>(containers.data()), containers.size(),
           out_status);
}

void TF_SessionRun_wrapper_helper(TF_Session* session, const char* handle,
                                  const TF_Buffer* run_options,
                                  const std::vector<TF_Output>& inputs,
                                  const std::vector<PyObject*>& input_ndarrays,
                                  const std::vector<TF_Output>& outputs,
                                  const std::vector<TF_Operation*>& targets,
                                  TF_Buffer* run_metadata,
                                  TF_Status* out_status,
                                  std::vector<PyObject*>* py_outputs) {
  DCHECK_EQ(inputs.size(), input_ndarrays.size());
  DCHECK(py_outputs != nullptr);
  DCHECK(py_outputs->empty());
  Status s;

  // Convert input ndarray PyObjects to TF_Tensors. We maintain a continuous
  // array of TF_Tensor*s as well as scoped containers to make sure they're
  // cleaned up properly.
  //
  // Memory management:
  // PyArrayToTFTensor() creates a new ndarray PyObject from the input
  // ndarray. We manage the new ndarray's lifetime in order to keep the
  // underlying data buffer alive (the new ndarray also guarantees a contiguous
  // data buffer). The new ndarray's data buffer is used to create the
  // corresponding TF_Tensor. The TF_Tensor's deallocator will queue the new
  // ndarray to be decref'd by the next ClearDecrefCache() call (we can't call
  // Py_DECREF in the deallocator directly because the GIL must be held).
  //
  // Note that TF_Tensor may directly delegate its data and deallocator to a
  // TensorBuffer, which may outlive the TF_Tensor (e.g. if the tensor gets
  // queued or assigned to a variable).
  TF_TensorVector input_vals;
  std::vector<Safe_TF_TensorPtr> input_vals_safe;
  gtl::InlinedVector<std::unique_ptr<ResourceHandle>, 4> resource_handles;
  for (PyObject* ndarray : input_ndarrays) {
    input_vals_safe.emplace_back(make_safe(static_cast<TF_Tensor*>(nullptr)));
    ResourceHandle* resource_handle;
    s = PyArrayToTFTensor(ndarray, &input_vals_safe.back(), &resource_handle);
    if (resource_handle != nullptr) {
      resource_handles.emplace_back(resource_handle);
    }
    if (!s.ok()) {
      Set_TF_Status_from_Status(out_status, s);
      return;
    }
    input_vals.push_back(input_vals_safe.back().get());
  }

  // Allocate space for output TF_Tensor*s
  TF_TensorVector output_vals(outputs.size());

  // Clear up any unused memory leftover from previous runs
  ClearDecrefCache();

  // Call TF_SessionRun() (and release GIL during execution)
  Py_BEGIN_ALLOW_THREADS;
  if (handle == nullptr) {
    TF_SessionRun(session, run_options, inputs.data(), input_vals.data(),
                  inputs.size(), outputs.data(), output_vals.data(),
                  outputs.size(), targets.data(), targets.size(), run_metadata,
                  out_status);
  } else {
    TF_SessionPRun(session, handle, inputs.data(), input_vals.data(),
                   inputs.size(), outputs.data(), output_vals.data(),
                   outputs.size(), targets.data(), targets.size(), out_status);
  }
  Py_END_ALLOW_THREADS;

  // Create scoped containers for output tensors
  std::vector<Safe_TF_TensorPtr> output_vals_safe;
  for (TF_Tensor* output : output_vals) {
    output_vals_safe.emplace_back(make_safe(output));
  }

  // Convert outputs to ndarrays (in scoped containers)
  std::vector<Safe_PyObjectPtr> py_outputs_safe;
  for (int i = 0; i < outputs.size(); ++i) {
    PyObject* py_array;
    s = TFTensorToPyArray(std::move(output_vals_safe[i]), &py_array);
    if (!s.ok()) {
      Set_TF_Status_from_Status(out_status, s);
      return;
    }
    py_outputs_safe.emplace_back(make_safe(py_array));
  }

  // If we reach this point, we have successfully built a list of objects so we
  // can release them from the safe container into the return vector.
  for (int i = 0; i < outputs.size(); ++i) {
    py_outputs->push_back(py_outputs_safe[i].release());
  }
}

void TF_SessionRun_wrapper(TF_Session* session, const TF_Buffer* run_options,
                           const std::vector<TF_Output>& inputs,
                           const std::vector<PyObject*>& input_ndarrays,
                           const std::vector<TF_Output>& outputs,
                           const std::vector<TF_Operation*>& targets,
                           TF_Buffer* run_metadata, TF_Status* out_status,
                           std::vector<PyObject*>* py_outputs) {
  TF_SessionRun_wrapper_helper(session, nullptr, run_options, inputs,
                               input_ndarrays, outputs, targets, run_metadata,
                               out_status, py_outputs);
  // Release any unused ndarray references (see memory management comment in
  // TF_SessionRun_wrapper_helper)
  ClearDecrefCache();
}

string EqualGraphDefWrapper(const string& actual, const string& expected) {
  GraphDef actual_def;
  if (!actual_def.ParseFromString(actual)) {
    return "actual is not a valid serialized GraphDef";
  }
  GraphDef expected_def;
  if (!expected_def.ParseFromString(expected)) {
    return "expected is not a valid serialized GraphDef";
  }
  string diff;
  return EqualGraphDef(actual_def, expected_def, &diff) ? "" : diff;
}

void TF_SessionPRunSetup_wrapper(TF_Session* session,
                                 const std::vector<TF_Output>& inputs,
                                 const std::vector<TF_Output>& outputs,
                                 const std::vector<TF_Operation*>& targets,
                                 const char** out_handle,
                                 TF_Status* out_status) {
  // Call TF_SessionPRunSetup() (and release GIL during execution)
  Py_BEGIN_ALLOW_THREADS;
  TF_SessionPRunSetup(session, inputs.data(), inputs.size(), outputs.data(),
                      outputs.size(), targets.data(), targets.size(),
                      out_handle, out_status);
  Py_END_ALLOW_THREADS;
}

void TF_SessionPRun_wrapper(TF_Session* session, const char* handle,
                            const std::vector<TF_Output>& inputs,
                            const std::vector<PyObject*>& input_ndarrays,
                            const std::vector<TF_Output>& outputs,
                            TF_Status* out_status,
                            std::vector<PyObject*>* py_outputs) {
  const std::vector<TF_Operation*> targets;
  TF_SessionRun_wrapper_helper(session, handle,
                               nullptr,  // run_options
                               inputs, input_ndarrays, outputs, targets,
                               nullptr,  // run_metadata
                               out_status, py_outputs);
  // Release any unused ndarray references (see memory management comment in
  // TF_SessionRun_wrapper_helper)
  ClearDecrefCache();
}

}  // namespace tensorflow


text:
<!doctype html>

    <meta charset="utf-8">
    <title>CA DIALOG | Web Lab Common UI</title>

    <link rel="import" href="/bower_components/imd/imd.html">
    <link rel="import" href="/components/ca-dialog.html">
    <link href="/examples/index.css" rel="stylesheet">

CA DIALOG EXAMPLE

    <ca-dialog heading="hello" type="error"></ca-dialog>
    <button onclick="openDialog()">Open Dialog</button>


text:
package com.amazonaws.services.xray.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.xray.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * AliasMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class AliasMarshaller {

    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Name").build();
    private static final MarshallingInfo<List> NAMES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Names").build();
    private static final MarshallingInfo<String> TYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Type").build();

    private static final AliasMarshaller instance = new AliasMarshaller();

    public static AliasMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(Alias alias, ProtocolMarshaller protocolMarshaller) {

        if (alias == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(alias.getName(), NAME_BINDING);
            protocolMarshaller.marshall(alias.getNames(), NAMES_BINDING);
            protocolMarshaller.marshall(alias.getType(), TYPE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="Navigation" inherits="Spatial" category="Core" version="3.0.alpha.custom_build">
	<brief_description>
	</brief_description>
	<description>
	</description>
	<tutorials>
	</tutorials>
	<demos>
	</demos>
	<methods>
		<method name="get_closest_point">
			<return type="Vector3">
			</return>
			<argument index="0" name="to_point" type="Vector3">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_closest_point_normal">
			<return type="Vector3">
			</return>
			<argument index="0" name="to_point" type="Vector3">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_closest_point_owner">
			<return type="Object">
			</return>
			<argument index="0" name="to_point" type="Vector3">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_closest_point_to_segment">
			<return type="Vector3">
			</return>
			<argument index="0" name="start" type="Vector3">
			</argument>
			<argument index="1" name="end" type="Vector3">
			</argument>
			<argument index="2" name="use_collision" type="bool" default="false">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_simple_path">
			<return type="PoolVector3Array">
			</return>
			<argument index="0" name="start" type="Vector3">
			</argument>
			<argument index="1" name="end" type="Vector3">
			</argument>
			<argument index="2" name="optimize" type="bool" default="true">
			</argument>
			<description>
			</description>
		</method>
		<method name="get_up_vector" qualifiers="const">
			<return type="Vector3">
			</return>
			<description>
			</description>
		</method>
		<method name="navmesh_create">
			<return type="int">
			</return>
			<argument index="0" name="mesh" type="NavigationMesh">
			</argument>
			<argument index="1" name="xform" type="Transform">
			</argument>
			<argument index="2" name="owner" type="Object" default="null">
			</argument>
			<description>
			</description>
		</method>
		<method name="navmesh_remove">
			<return type="void">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<description>
			</description>
		</method>
		<method name="navmesh_set_transform">
			<return type="void">
			</return>
			<argument index="0" name="id" type="int">
			</argument>
			<argument index="1" name="xform" type="Transform">
			</argument>
			<description>
			</description>
		</method>
		<method name="set_up_vector">
			<return type="void">
			</return>
			<argument index="0" name="up" type="Vector3">
			</argument>
			<description>
			</description>
		</method>
	</methods>
	<members>
		<member name="up_vector" type="Vector3" setter="set_up_vector" getter="get_up_vector">
		</member>
	</members>
	<constants>
	</constants>
</class>


text:
package es.gimix.simyo;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;

/** List of phone numbers */
public class PhoneNumberList extends ArrayList<String> {
	private static final long serialVersionUID = 1L;

	public String toJson() {
		JSONArray aNumbers = new JSONArray();
		for(String number : this)
			aNumbers.put(number);
		return aNumbers.toString();
	}

	public static PhoneNumberList fromJson(String json) throws JSONException {
		PhoneNumberList result = new PhoneNumberList();
		JSONArray aNumbers = new JSONArray(json);
		for(int i=0; i < aNumbers.length(); i++) {
			result.add(aNumbers.getString(i));
		}
		return result;
	}

}


text:
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('letter', '0002_auto_20200303_1117'),
        ('guide', '0005_action_mail_intent'),
    ]

    operations = [
        migrations.AddField(
            model_name='action',
            name='letter_template',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='letter.LetterTemplate'),
        ),
    ]


text:
// This checker checks the accelerator's utilization.
#ifndef THIRD_PARTY_TENSORFLOW_TOOLS_TFPROF_INTERNAL_ADVISOR_ACCELERATOR_UTILIZATION_CHECKER_H_
#define THIRD_PARTY_TENSORFLOW_TOOLS_TFPROF_INTERNAL_ADVISOR_ACCELERATOR_UTILIZATION_CHECKER_H_

#include "tensorflow/tools/tfprof/internal/advisor/checker.h"

namespace tensorflow {
namespace tfprof {

struct ExecStats {
 public:
  // Earliest start time of a step.
  int64 start_micros;
  // Latest finish time of a step.
  int64 end_micros;
  // The duration spent on running a kernel during a step.
  int64 exec_micros;
};

class AcceleratorUtilizationChecker : public Checker {
 public:
  string name() override { return "AcceleratorUtilizationChecker"; }

 private:
  std::vector<string> Check(const TFStats* stats) override {
    if (!stats) {
      fprintf(stderr, "Missing profiles (e.g. graph, run_meta). Skip %s\n",
              name().c_str());
      return reports_;
    }
    for (const auto& n : stats->nodes()) {
      BuildExecStats(n.second.get());
    }
    return CheckInternal();
  }

  std::vector<string> CheckInternal() {
    for (const auto& s : accelerator_exec_stats_) {
      const ExecStats& stat = s.second;
      int64 total_micros = stat.end_micros - stat.start_micros;
      if (total_micros <= 0) continue;
      double utilization = 1.0 * stat.exec_micros / total_micros;
      if (utilization >= 0.5) {
        reports_.push_back(strings::Printf("%s: device: %s utilization: %.2f",
                                           kLevel[0], s.first.c_str(),
                                           utilization));
      } else if (utilization < 0.5 && utilization > 0.2) {
        reports_.push_back(
            strings::Printf("%s: device: %s low utilization: %.2f", kLevel[1],
                            s.first.c_str(), utilization));
      } else if (utilization <= 0.2) {
        reports_.push_back(
            strings::Printf("%s: device: %s low utilization: %.2f", kLevel[2],
                            s.first.c_str(), utilization));
      }
    }
    return reports_;
  }

  void BuildExecStats(const TFGraphNode* node) {
    const auto& execs = node->all_op_execs();
    if (execs.empty()) {
      return;
    }
    if (!IsPlacedOnAccelerator(node->canonical_device())) {
      return;
    }

    if (accelerator_exec_stats_.find(node->canonical_device()) ==
        accelerator_exec_stats_.end()) {
      accelerator_exec_stats_.insert(
          std::pair<string, ExecStats>(node->canonical_device(), ExecStats()));
    }
    ExecStats& stats = accelerator_exec_stats_.at(node->canonical_device());

    // TODO(xpan): Use multiple steps?
    const ExecStep& exec = execs.rbegin()->second;

    if (stats.start_micros == 0) {
      stats.start_micros = exec.all_start_micros();
    } else if (exec.all_start_micros() != 0) {
      stats.start_micros =
          std::min(stats.start_micros, exec.all_start_micros());
    }
    stats.end_micros = std::max(stats.end_micros, exec.latest_end_micros());
    stats.exec_micros += exec.accelerator_exec_micros();
  }

  std::map<string, ExecStats> accelerator_exec_stats_;
  std::map<string, int64> ps_placement_;
  std::vector<string> reports_;
};

}  // namespace tfprof
}  // namespace tensorflow

#endif  // THIRD_PARTY_TENSORFLOW_TOOLS_TFPROF_INTERNAL_ADVISOR_ACCELERATOR_UTILIZATION_CHECKER_H_


text:
package com.netflix.zeno.diff;

import com.netflix.zeno.diff.TypeDiff.FieldDiffScore;
import com.netflix.zeno.serializer.NFTypeSerializer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import org.apache.commons.lang.mutable.MutableInt;

/**
 * This is the main interface for performing a diff between two arbitrary data states.<p/>
 *
 * @author dkoszewnik
 *
 */
public class TypeDiffOperation<T> {

    private final TypeDiffInstruction<T> instruction;

    public TypeDiffOperation(TypeDiffInstruction<T> instruction) {
        this.instruction = instruction;
    }

    @SuppressWarnings("unchecked")
    public TypeDiff<T> performDiff(DiffSerializationFramework framework, Iterable<T> fromState, Iterable<T> toState) {
        return performDiff(framework, fromState, toState, Runtime.getRuntime().availableProcessors());
    }

    @SuppressWarnings("unchecked")
    public TypeDiff<T> performDiff(DiffSerializationFramework framework, Iterable<T> fromState, Iterable<T> toState, int numThreads) {
        Map<Object, T> fromStateObjects = new HashMap<Object, T>();

        for(T obj : fromState) {
            fromStateObjects.put(instruction.getKey(obj), obj);
        }

        ArrayList<List<T>> perProcessorWorkList = new ArrayList<List<T>>(numThreads); // each entry is a job
        for (int i =0; i < numThreads; ++i) {
            perProcessorWorkList.add(new ArrayList<T>());
        }

        Map<Object, Object> toStateKeys = new ConcurrentHashMap<Object, Object>();

        int toIncrCount = 0;
        for(T toObject : toState) {
            perProcessorWorkList.get(toIncrCount % numThreads).add(toObject);
            toIncrCount++;
        }

        ExecutorService executor = Executors.newFixedThreadPool(numThreads, new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                final Thread thread = new Thread(r, "TypeDiff_" + instruction.getTypeIdentifier());
                thread.setDaemon(true);
                return thread;
            }
        });

        try {
            ArrayList<Future<TypeDiff<T>>> workResultList = new ArrayList<Future<TypeDiff<T>>>(perProcessorWorkList.size());
            for (final List<T> workList : perProcessorWorkList) {
                if (workList != null && !workList.isEmpty()) {
                    workResultList.add(executor.submit(new TypeDiffCallable<T>(framework, instruction, fromStateObjects, toStateKeys, workList)));
                }
            }

            TypeDiff<T> mergedDiff = new TypeDiff<T>(instruction.getTypeIdentifier());
            for (final Future<TypeDiff<T>> future : workResultList) {
                try {
                    TypeDiff<T> typeDiff = future.get();
                    mergeTypeDiff(mergedDiff, typeDiff);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            for(Map.Entry<Object, T> entry : fromStateObjects.entrySet()) {
                mergedDiff.incrementFrom();
                if(!toStateKeys.containsKey(entry.getKey()))
                    mergedDiff.addExtraInFrom(entry.getValue());
            }

            return mergedDiff;

        } finally {
            executor.shutdownNow();
        }
    }

    private void mergeTypeDiff(TypeDiff<T> mergedDiff, TypeDiff<T> typeDiff) {

        mergedDiff.getExtraInFrom().addAll(typeDiff.getExtraInFrom());
        mergedDiff.getExtraInTo().addAll(typeDiff.getExtraInTo());
        mergedDiff.getDiffObjects().addAll(typeDiff.getDiffObjects());
        mergedDiff.incrementFrom(typeDiff.getItemCountFrom());
        mergedDiff.incrementTo(typeDiff.getItemCountTo());

        Map<DiffPropertyPath, FieldDiffScore<T>> mergedFieldDifferences = mergedDiff.getFieldDifferences();
        Map<DiffPropertyPath, FieldDiffScore<T>> fieldDifferences = typeDiff.getFieldDifferences();
        for (final DiffPropertyPath path : fieldDifferences.keySet()) {
            FieldDiffScore<T> fieldDiffScore = fieldDifferences.get(path);

            FieldDiffScore<T> mergedFieldDiffScore = mergedFieldDifferences.get(path);
            if (mergedFieldDiffScore != null) {
                mergedFieldDiffScore.incrementDiffCountBy(fieldDiffScore.getDiffCount());
                mergedFieldDiffScore.incrementTotalCountBy(fieldDiffScore.getTotalCount());
                mergedFieldDiffScore.getDiffScores().addAll(fieldDiffScore.getDiffScores());
            } else {
                mergedFieldDifferences.put(path, fieldDiffScore);
            }
        }
    }

    class TypeDiffCallable<Z> implements Callable<TypeDiff<Z>> {

        private final TypeDiffInstruction<Z> instruction;
        private final List<Z> workList;
        private final Map<Object, Object> toStateKeys;
        private final Map<Object, Z> fromStateObjects;
        private final DiffSerializationFramework framework;

        public TypeDiffCallable(DiffSerializationFramework framework, TypeDiffInstruction<Z> instruction, Map<Object, Z> fromStateObjects, Map<Object, Object> toStateKeys, List<Z> workList) {
            this.framework = framework;
            this.instruction = instruction;
            this.fromStateObjects = fromStateObjects;
            this.toStateKeys = toStateKeys;
            this.workList = workList;
        }

        @Override
        public TypeDiff<Z> call() throws Exception {
            TypeDiff<Z> diff = new TypeDiff<Z>(instruction.getTypeIdentifier());
            NFTypeSerializer<Z> typeSerializer = (NFTypeSerializer<Z>) framework.getSerializer(instruction.getSerializerName());

            DiffRecord fromRec = new DiffRecord();
            fromRec.setSchema(typeSerializer.getFastBlobSchema());
            DiffRecord toRec = new DiffRecord();
            toRec.setSchema(typeSerializer.getFastBlobSchema());
            fromRec.setTopLevelSerializerName(instruction.getSerializerName());
            toRec.setTopLevelSerializerName(instruction.getSerializerName());

            for(Z toObject : workList) {
                diff.incrementTo();
                Object toStateKey = instruction.getKey(toObject);
                toStateKeys.put(toStateKey, Boolean.TRUE);
                Z fromObject = fromStateObjects.get(toStateKey);

                if(fromObject == null) {
                    diff.addExtraInTo(toObject);
                } else {
                    int diffScore = diffFields(diff, fromRec, toRec, typeSerializer, toObject, fromObject);
                    if(diffScore > 0)
                        diff.addDiffObject(fromObject, toObject, diffScore);
                }
            }

            return diff;
        }

        private int diffFields(TypeDiff<Z> diff, DiffRecord fromRec, DiffRecord toRec, NFTypeSerializer<Z> typeSerializer, Z toObject, Z fromObject) {
            typeSerializer.serialize(toObject, toRec);
            typeSerializer.serialize(fromObject, fromRec);

            int diffScore = incrementDiffFields(diff, toRec, fromRec, toObject, fromObject);

            toRec.clear();
            fromRec.clear();

            return diffScore;
        }

        private int incrementDiffFields(TypeDiff<Z> diff, DiffRecord toRecord, DiffRecord fromRecord, Z toObject, Z fromObject) {
            int objectDiffScore = 0;

            for(DiffPropertyPath key : toRecord.getFieldValues().keySet()) {
                List<Object> toObjects = toRecord.getFieldValues().getList(key);
                List<Object> fromObjects = fromRecord.getFieldValues().getList(key);
                int objectFieldDiffScore;

                if(fromObjects == null) {
                    diff.incrementFieldScores(key, toObjects.size(), toObjects.size());
                    objectFieldDiffScore = toObjects.size();
                } else {
                    objectFieldDiffScore = incrementDiffFields(diff, key, toObjects, fromObjects);
                }

                objectDiffScore += objectFieldDiffScore;

                diff.addFieldObjectDiffScore(key, toObject, fromObject, objectFieldDiffScore);
            }

            for(DiffPropertyPath key : fromRecord.getFieldValues().keySet()) {
                if(toRecord.getFieldValues().getList(key) == null) {
                    int diffSize = fromRecord.getFieldValues().getList(key).size();
                    diff.incrementFieldScores(key, diffSize, diffSize);
                    objectDiffScore += diffSize;

                    diff.addFieldObjectDiffScore(key, toObject, fromObject, diffSize);
                }
            }

            return objectDiffScore;
        }

        private int incrementDiffFields(TypeDiff<?> diff, DiffPropertyPath breadcrumbs, List<Object> toObjects, List<Object> fromObjects) {
            int objectFieldDiffScore = 0;

            Map<Object, MutableInt> objectSet = getObjectMap();

            for(Object obj : toObjects) {
                increment(objectSet, obj);
            }

            for(Object obj : fromObjects) {
                if(!decrement(objectSet, obj)) {
                    objectFieldDiffScore++;
                }
            }

            if(!objectSet.isEmpty()) {
                for(Map.Entry<Object, MutableInt>entry : objectSet.entrySet()) {
                    objectFieldDiffScore += entry.getValue().intValue();
                }
            }

            objectSet.clear();

            diff.incrementFieldScores(breadcrumbs, objectFieldDiffScore, toObjects.size() + fromObjects.size());
            return objectFieldDiffScore;
        }

        private void increment(Map<Object, MutableInt> map, Object obj) {
            MutableInt i = map.get(obj);
            if(i == null) {
                i = new MutableInt(0);
                map.put(obj, i);
            }
            i.increment();
        }

        private boolean decrement(Map<Object, MutableInt> map, Object obj) {
            MutableInt i = map.get(obj);
            if(i == null) {
                return false;
            }

            i.decrement();

            if(i.intValue() == 0) {
                map.remove(obj);
            }

            return true;
        }

    }

    private static final ThreadLocal<Map<Object, MutableInt>> objectSet = new ThreadLocal<Map<Object, MutableInt>>();

    private Map<Object, MutableInt> getObjectMap() {
        Map<Object, MutableInt> objectSet = TypeDiffOperation.objectSet.get();
        if(objectSet == null) {
            objectSet = new HashMap<Object, MutableInt>();
            TypeDiffOperation.objectSet.set(objectSet);
        }
        return objectSet;
    }
}


text:
\setcounter{section}{12}
\section{Regelung im Zustandsraum}
\input{content/1301_Regler.tex}
\input{content/1302_Referenzsystem.tex}
\input{content/1303_Beobachter.tex}
\input{content/1304_Kompensator.tex}


text:
import { DataStore } from "../../archive/search/data-store.js"

export class Pokemon {
	constructor(pokemon) {
		if (!pokemon)
			return
		// if pokemon is a base pokemon
		if (typeof pokemon !== "Pokemon" && !pokemon.base && pokemon.abilities) {
			this.base = pokemon
			this.id = pokemon.id
			this.name = pokemon.name
			this.form = pokemon.form
			return
		}
		var poke = stuff.data.getPokemonFrom(pokemon)
		if (!poke)
			return
		this.base = poke.base
		if (typeof pokemon != "string")
			for (var i in pokemon)
				this[i] = pokemon[i]
		this.id = poke.base.id
		this.name = poke.base.name
		this.form = poke.base.form
	}

	get forms() { return this.base.forms }
	get stats() { return this.base.stats }
	get abilities() { return this.base.abilities }
	get classification() { return this.base.classification }
	get description() { return this.base.description }
	get locations() { return this.base.locations }
	get eggGroups() { return this.base.eggGroups }
	get eggs() { return this.base.eggs }
	get evolvesFrom() { return this.base.evolvesFrom }
	get evolvesTo() { return this.base.evolvesTo }
	get height() { return this.base.height }
	get weight() { return this.base.weight }
	get moves() { return this.base.moves }
	get ratio() { return this.base.ratio }
	get types() { return this.base.types }
}

export class PokemonData extends DataStore {
	constructor() {
		super()
		this.pokemons = []
		this.moves = {}
		this.abilities = {}
		this.natures = {}
		this.eggGroups = []
		this.types = {}
		this.typeNames = []
		this.typeColors = {
			Bug: "#A8B820",
			Dark: "#705848",
			Dragon: "#7038F8",
			Electric: "#F8D030",
			Fairy: "#EE99AC",
			Fighting: "#C03028",
			Fire: "#F08030",
			Flying: "#A890F0",
			Ghost: "#705898",
			Grass: "#78C850",
			Ground: "#E0C068",
			Ice: "#98D8D8",
			Normal: "#A8A878",
			Poison: "#A040A0",
			Psychic: "#F85888",
			Rock: "#B8A038",
			Steel: "#B8B8D0",
			Water: "#6890F0"
		}
		this.pokeballs = [
			"Poké",
			"Great",
			"Ultra",
			"Master",
			"Safari",
			"Level",
			"Lure",
			"Moon",
			"Friend",
			"Love",
			"Heavy",
			"Fast",
			"Sport",
			"Premier",
			"Repeat",
			"Timer",
			"Nest",
			"Net",
			"Dive",
			"Luxury",
			"Heal",
			"Quick",
			"Dusk",
			"Cherish",
			"Dream",
			"Beast"
		]
	}

	findPokemon(id, form) {
		var pokemon = new Pokemon()
		pokemon.id = id
		var possiblePokes = this.pokemons.filter(e => id == e.id)
		if (possiblePokes.length == 0)
			return null
		pokemon.base = possiblePokes[0]
		if (possiblePokes[0].forms)
			pokemon.form = this.findBestFormFit(possiblePokes[0].forms, form)
		else
			pokemon.form = "Base"
		if (possiblePokes.length > 1) {
			var possibleForms = possiblePokes.filter(e => e.form == pokemon.form)
			if (possibleForms.length == 1)
				pokemon.base = possibleForms[0]
		}
		pokemon.name = pokemon.base.name
		return pokemon
	}

	findBestFormFit(forms, form) {
		if (!form)
			return forms[0]
		var fits = forms.filter(e => e.toLowerCase() == form.toLowerCase())
		if (fits.length)
			return fits[0]
		fits = []
		var words = form.split(" ")
		var highestCount = 0
		for (var i in forms) {
			var count = 0
			for (var j in words)
				if (forms[i].toLowerCase().indexOf(words[j].toLowerCase()) > -1)
					count++
			if (count > highestCount) {
				fits = [forms[i]]
				highestCount = count
			} else if (count == highestCount)
				fits.push(forms[i])
		}
		if (fits.length)
			return fits[0]
		return forms[0]
	}

	getPokemonFrom(idformthing) {
		if (idformthing > 0)
			return this.findPokemon(+idformthing)
		if (typeof idformthing == "string")
			idformthing = { name: idformthing }
		if (!idformthing.id && idformthing.name) {
			var possiblePokes = this.pokemons.filter(e => idformthing.name.toLowerCase() == e.name.toLowerCase())
			if (possiblePokes.length)
				idformthing.id = possiblePokes[0].id
			else
				return false
		}
		return this.findPokemon(idformthing.id, idformthing.form)
	}

	uniqueBy(list, key) {
		var seen = {};
		return list.filter(function (item) {
			var k = key(item);
			return seen.hasOwnProperty(k) ? false : (seen[k] = true);
		})
	}

	tallyDefense(attackType, pokemon) {
		var defense = 1
		defense *= this.getTypeDefense(attackType, pokemon.types[0])
		if (pokemon.types[1])
			defense *= this.getTypeDefense(attackType, pokemon.types[1])
		return defense
	}

	getTypeDefense(attackType, defenseType) {
		if (this.types[defenseType].weaknesses.indexOf(attackType) > -1)
			return 2
		else if (this.types[defenseType].strengths.indexOf(attackType) > -1)
			return 0.5
		else if (this.types[defenseType].immunities.indexOf(attackType) > -1)
			return 0
		return 1
	}

	getGeneration(pokemon) {
		if (pokemon.id <= 151)
			return 1
		if (pokemon.id <= 251)
			return 2
		if (pokemon.id <= 386)
			return 3
		if (pokemon.id <= 493)
			return 4
		if (pokemon.id <= 649)
			return 5
		if (pokemon.id <= 721)
			return 6
		if (pokemon.id <= 802)
			return 7
		return 8
	}

	getTotalBaseStat(pokemon) {
		var count = 0
		for (var i in pokemon.stats)
			count += pokemon.stats[i]
		return count
	}

	getStatAtLevel(pokemon, stat, level) {
		if (pokemon.id == 292 && stat == "hp")
			return 1
		var base = +pokemon.stats[stat]
		var iv = pokemon.ivs ? +pokemon.ivs[stat] : 0
		iv = iv ? iv : 0
		var ev = pokemon.evs ? +pokemon.evs[stat] : 0
		ev = ev ? ev : 0
		if (stat == "hp")
			return Math.floor((2 * base + iv + ev / 4) * level / 100) + 10 + level
		var nature = PokeText.natureCssClass(stat, pokemon)
		switch (nature) {
			case "positive-nature": nature = 1.1; break;
			case "negative-nature": nature = 0.9; break;
			default: nature = 1; break;
		}
		return Math.floor((Math.floor((2 * base + iv + ev / 4) * level / 100) + 5) * nature)
	}
}