text:
BSLS_IDENT("$Id: $")

//@PURPOSE: Provide a minimal-whitespace implementation for 'balxml_formatter'.
//
//@CLASSES:
//  balxml::Formatter_CompactImplState: state of formatter state machine
//  balxml::Formatter_CompactImplStateId: labels for formatter state
//  balxml::Formatter_CompactImplUtil: actions of formatter state machine
//
//@DESCRIPTION: This private, subordinate component to 'balxml_formatter'
// provides an in-core value semantic attribute class,
// 'balxml::Formatter_CompactImplState', and a utility 'struct',
// 'balxml::Formatter_CompactImplUtil', that implements XML printing operations
// using the state value type.  These two classes work in conjunction to
// implement a state machine for printing an XML document having minimal
// whitespace, given a sequence of tokens to emit.  The class
// 'balxml::Formatter_CompactImplStateId' enumerates the set of labels for
// distinct states of 'balxml::Formatter_CompactImplState', upon which most
// control-flow decisions of 'balxml::Formatter_CompactImplUtil' are
// based.

#include <balscm_version.h>

#include <balxml_encoderoptions.h>
#include <balxml_formatterwhitespacetype.h>
#include <balxml_typesprintutil.h>

#include <bsl_ostream.h>
#include <bsl_string_view.h>

namespace BloombergLP {
namespace balxml {

                    // ===================================
                    // struct Formatter_CompactImplStateId
                    // ===================================

struct Formatter_CompactImplStateId {
    // This 'struct' provides a namespace for enumerating a set of labels for
    // distinct states of 'Formatter_CompactImplState'.

    // TYPES
    enum Enum {
        e_AT_START,
            // This state indicates that the current write position of the
            // formatter is at the start of the document.  The formatter is
            // only allowed to add an XML header when in this state.

        e_IN_TAG,
            // This state indicates that the current write position of the
            // formatter is immediately after the name of an opening tag, or
            // otherwise immediately after the value of an attribute of an
            // opening tag.  In this state, most token printing operations,
            // other than adding attributes, need to emit a ">" character to
            // close the currently open tag before emitting their content.  For
            // example:
            //..
            //  1| <someTag
            //   `---------^
            //
            //   * Note that there is no '>' character yet
            //..
            // or:
            //..
            //  1| <someTag attr="value" otherAttr="42"
            //   `-------------------------------------^
            //..

        e_FIRST_DATA_BETWEEN_TAGS,
            // This state indicates that the current write position of the
            // formatter is either 1) after a closing tag, or 2) after a
            // complete opening tag and before any data for the tag.  In this
            // state, data printing operations do *not* need to emit delimiting
            // whitespace for their content.  Note that comments are not
            // considered data.  For example:
            //..
            //  1| <someTag>
            //   `----------^
            //..
            // or:
            //..
            //  1| <someTag><!-- comment -->
            //   `--------------------------^
            //..
            // or:
            //..
            //  1| <someTag></someTag>
            //   `--------------------^
            //..

        e_TRAILING_DATA_BETWEEN_TAGS
            // This state indicates that the current write position of the
            // formatter is after one or more data tokens for the
            // currently-open tag.  In this state, data printing operations
            // need to emit delimiting whitespace for their content.  For
            // example:
            //..
            //  1| <someTag>data
            //   `--------------^
            //..
            // or:
            //..
            //  1| <someTag>some list data
            //   `------------------------^
            //..
    };
};

                      // ================================
                      // class Formatter_CompactImplState
                      // ================================

class Formatter_CompactImplState {
    // This class provides an in-core, value-semantic attribute type that
    // maintains all of the state information needed to print an XML document
    // with minimal whitespace using the operations provided by
    // 'Formatter_CompactImplUtil'.

  public:
    // TYPES
    typedef Formatter_CompactImplStateId Id;

  private:
    // DATA
    Id::Enum d_id;
        // the canonical "state" in the state machine, upon which most
        // control-flow decisions are based when printing

    int      d_indentLevel;
        // the current open XML tag nesting depth

    int      d_initialIndentLevel;
        // the XML tag nesting depth to use at the start of the document, and
        // the value to which 'd_indentLevel' is set upon 'reset', which no
        // printing operations modify

    int      d_spacesPerLevel;
        // an option that the formatter does not use in compact mode, but
        // which is accessible to clients in any mode

    int      d_column;
        // an approximation of the current column number, which does not take
        // into account the number of characters used to print any data, and
        // which the formatter does not use in compact mode, but is accessible
        // to clients in any mode

  public:
    // CREATORS
    Formatter_CompactImplState();
        // Create a 'Formatter_CompactImplState' having an 'id' attribute of
        // 'Id::e_AT_START', and 'indentLevel', 'initialIndentLevel',
        // 'spacesPerLevel', and 'column' attributes of 0.

    Formatter_CompactImplState(int indentLevel, int spacesPerLevel);
        // Create a 'Formatter_CompactImplState' having an 'id' attribute of
        // 'Id::e_AT_START', the specified 'indentLevel' and 'spacesPerLevel',
        // as well as an 'initialIndentLevel' attribute equal to 'indentLevel',
        // and a 'column' attribute of 0.

    Formatter_CompactImplState(Id::Enum id,
                               int      indentLevel,
                               int      initialIndentLevel,
                               int      spacesPerLevel,
                               int      column);
        // Create a 'Formatter_CompactImplState' having the specified 'id',
        // 'indentLevel', 'initialIndentLevel', 'spacesPerLevel', and 'column'
        // attributes.

    // MANIPULATORS
    int& column();
        // Return a reference providing modifiable access to the 'column'
        // attribute of this object.

    Id::Enum& id();
        // Return a reference providing modifiable access to the 'id' attribute
        // of this object.

    int& indentLevel();
        // Return a reference providing modifiable access to the 'indentLevel'
        // attribute of this object.

    int& initialIndentLevel();
        // Return a reference providing modifiable access to the
        // 'initialIndentLevel' attribute of this object.

    int& spacesPerLevel();
        // Return a reference providing modifiable access to the
        // 'spacesPerLevel' attribute of this object.

    // ACCESSORS
    const int& column() const;
        // Return a reference providing non-modifiable access to the 'column'
        // attribute of this object.

    const Id::Enum& id() const;
        // Return a reference providing non-modifiable access to the 'id'
        // attribute of this object.

    const int& indentLevel() const;
        // Return a reference providing non-modifiable access to the
        // 'indentLevel' attribute of this object.

    const int& initialIndentLevel() const;
        // Return a reference providing non-modifiable access to the
        // 'initialIndentLevel' attribute of this object.

    const int& spacesPerLevel() const;
        // Return a reference providing non-modifiable access to the
        // 'spacesPerLevel' attribute of this object.
};

                      // ================================
                      // struct Formatter_CompactImplUtil
                      // ================================

struct Formatter_CompactImplUtil {
    // This utility 'struct' provides a namespace for a suite of operations
    // used to pretty-print XML documents given a sequence of tokens to emit.
    // Together with 'Formatter_CompactImplState', this 'struct' provides an
    // implementation of a state machine for such pretty-printing.

    // TYPES
    typedef Formatter_CompactImplState   State;
    typedef Formatter_CompactImplStateId StateId;
    typedef FormatterWhitespaceType      WhitespaceType;

  private:
    // PRIVATE CLASS METHODS
    static void addCommentImpl(bsl::ostream&            stream,
                               State                   *state,
                               const bsl::string_view&  comment,
                               const bsl::string_view&  openMarker,
                               const bsl::string_view&  closeMarker);
        // Write the specified 'openMarker', 'comment', and 'closeMarker' into
        // the specified 'stream', with formatting depending on the specified
        // 'state', and update the 'state' accordingly.  Note that if an
        // element-opening tag is not completed with a '>', this function will
        // add '>'.

  public:
    // CLASS METHODS
    template <class VALUE_TYPE>
    static bsl::ostream& addAttribute(
                   bsl::ostream&            stream,
                   State                   *state,
                   const bsl::string_view&  name,
                   const VALUE_TYPE&        value,
                   int                      valueFormattingMode = 0,
                   const EncoderOptions&    encoderOptions = EncoderOptions());
        // Add an attribute of the specified 'name' and specified 'value' to
        // the currently open element in the specified 'stream', with
        // formatting depending on the specified 'state', and update the
        // 'state' accordingly.  Return the 'stream'.  'value' can be of the
        // following types: 'char', 'short', 'int', 'bsls::Types::Int64',
        // 'float', 'double', 'bsl::string', 'bdlt::Datetime', 'bdlt::Date',
        // and 'bdlt::Time'.  Precede this name="value" pair with a single
        // space.  Wrap line (write the attribute on next line with proper
        // indentation), if the length of name="value" is too long.  Optionally
        // specify a 'valueFormattingMode' and 'encoderOptions' to control the
        // formatting of 'value'.  If 'value' is of type 'bsl::string', it is
        // truncated at any invalid UTF-8 byte-sequence or any control
        // character.  The list of invalid control characters includes
        // characters in the range '[0x00, 0x20)' and '0x7F' (DEL) but does not
        // include '0x9', '0xA', and '0x0D'.  The five special characters:
        // apostrophe, double quote, ampersand, less than, and greater than are
        // escaped in the output XML.  If 'value' is of type 'char', it is cast
        // to a signed byte value with a range '[ -128 ..  127 ]'.  The
        // behavior is undefined unless the last manipulator was 'openElement'
        // or 'addAttribute'.

    static bsl::ostream& addBlankLine(bsl::ostream& stream, State *state);
        // Insert one or two newline characters into the specified 'stream'
        // stream such that a blank line results, depending on the specified
        // 'state', and update the 'state' accordingly.  Return the 'stream'.
        // If the last output was a newline, then only one newline is added,
        // otherwise two newlines are added.  If following a call to
        // 'openElement', or 'addAttribute', add a closing '>' to the opened
        // tag.

    static bsl::ostream& addComment(
                                 bsl::ostream&            stream,
                                 State                   *state,
                                 const bsl::string_view&  comment,
                                 bool                     forceNewline = true);
        // !DEPRECATED!: Use 'addValidComment' instead.
        //
        // Write the specified 'comment' into the specified 'stream', with
        // formatting depending on the specified 'state', and update the
        // 'state' accordingly.  Return the 'stream'.  The optionally specified
        // 'forceNewline', if true, forces to start a new line solely for the
        // comment if it's not on a new line already.  Otherwise, comments
        // continue on current line.  If an element-opening tag is not
        // completed with a '>', 'addComment' will add '>'.

    template <class VALUE_TYPE>
    static bsl::ostream& addData(
                     bsl::ostream&          stream,
                     State                 *state,
                     const VALUE_TYPE&      value,
                     int                    formattingMode = 0,
                     const EncoderOptions&  encoderOptions = EncoderOptions());
        // Add the specified 'value' as the data content to the specified
        // 'stream', with formatting depending on the specified 'state', and
        // update 'state' accordingly.  Return the 'stream'.  'value' can be of
        // the following types: 'char', 'short', 'int', 'bsls::Types::Int64',
        // 'float', 'double', 'bsl::string', 'bdlt::Datetime', 'bdlt::Date',
        // and 'bdlt::Time'.  Perform no line-wrapping or indentation as if the
        // whitespace constraint were always 'BAEXML_PRESERVE_WHITESPACE' in
        // 'openElement', with the only exception that an initial newline and
        // an initial indent is added when 'openElement' specifies
        // 'BAEXML_NEWLINE_INDENT' option.  If 'value' is of type
        // 'bsl::string', it is truncated at any invalid UTF-8 byte-sequence or
        // any control character.  The list of invalid control characters
        // includes characters in the range '[0x00, 0x20)' and '0x7F' (DEL) but
        // does not include '0x9', '0xA', and '0x0D'.  The five special
        // characters: apostrophe, double quote, ampersand, less than, and
        // greater than are escaped in the output XML.  If 'value' is of type
        // 'char', it is cast to a signed byte value with a range of '[ -128 ..
        // 127 ]'.  Optionally specify the 'formattingMode' and
        // 'encoderOptions' to specify the format used to encode 'value'.  The
        // behavior is undefined if the call is made when there are no opened
        // elements.

    template <class TYPE>
    static bsl::ostream& addElementAndData(
                   bsl::ostream&            stream,
                   State                   *state,
                   const bsl::string_view&  name,
                   const TYPE&              value,
                   int                      formattingMode = 0,
                   const EncoderOptions&    encoderOptions = EncoderOptions());
        // Add element of the specified 'name' and the specified 'value' as the
        // data content to the specified 'stream', with formatting depending on
        // the specified 'state' and the optionally specified 'encoderOptions',
        // and update 'state' accordingly.  Return the 'stream'.  This has the
        // same effect as calling the following sequence: 'openElement(name);
        // addData(value), closeElement(name);'.  Optionally specify the
        // 'formattingMode'.

    static bsl::ostream& addHeader(bsl::ostream&            stream,
                                   State                   *state,
                                   const bsl::string_view&  encoding);
        // Add XML header with optionally specified 'encoding' to the specified
        // 'stream', with formatting depending on the specified 'state', and
        // update 'state' accordingly.  Return the 'stream'.  Version is always
        // "1.0".  The behavior is undefined unless 'addHeader' is the first
        // manipulator (with the exception of 'rawOutputStream') after
        // construction or 'reset'.

    template <class VALUE_TYPE>
    static bsl::ostream& addListData(
                     bsl::ostream&          stream,
                     State                 *state,
                     const VALUE_TYPE&      value,
                     int                    formattingMode = 0,
                     const EncoderOptions&  encoderOptions = EncoderOptions());
        // Add the specified 'value' as the data content to the specified
        // 'stream', with formatting depending on the specified 'state', and
        // update 'state' accordingly.  Return the 'stream'.  'value' can be of
        // the following types: 'char', 'short', 'int', 'bsls::Types::Int64',
        // 'float', 'double', 'bsl::string', 'bdlt::Datetime', 'bdlt::Date',
        // and 'bdlt::Time'.  Prefix the 'value' with a space('0x20') unless
        // the data being added is the first data on a line.  When adding the
        // data makes the line too long, perform line-wrapping and indentation
        // as determined by the whitespace constraint used when the current
        // element is opened with 'openElement'.  If 'value' is of type
        // 'bsl::string', it is truncated at any invalid UTF-8 byte-sequence or
        // any control character.  The list of invalid control characters
        // includes characters in the range '[0x00, 0x20)' and '0x7F' (DEL) but
        // does not include '0x9', '0xA', and '0x0D'.  The five special
        // characters: apostrophe, double quote, ampersand, less than, and
        // greater than are escaped in the output XML.  If 'value' is of type
        // 'char', it is cast to a signed byte value with a range of '[ -128 ..
        // 127 ]'.  Optionally specify the 'formattingMode' and
        // 'encoderOptions' to specify the format used to encode 'value'.  The
        // behavior is undefined if the call is made when there are no opened
        // elements.

    static bsl::ostream& addNewline(bsl::ostream& stream, State *state);
        // Insert a literal newline into the XML output of the specified
        // 'stream', with formatting depending on the specified 'state', and
        // update 'state' accordingly.  Return the 'stream'.  If following a
        // call to 'openElement', or 'addAttribute', add a closing '>' to the
        // opened tag.

    static int addValidComment(
                     bsl::ostream&            stream,
                     State                   *state,
                     const bsl::string_view&  comment,
                     bool                     forceNewline            = true,
                     bool                     omitEnclosingWhitespace = false);
        // Write the specified 'comment' into the specified 'stream', with
        // formatting depending on the specified 'state', and update the
        // 'state' accordingly.  If the optionally specified 'forceNewline' is
        // 'true' then a new line is inserted for comments not already on a new
        // line.  Also optionally specify an 'omitEnclosingWhitespace' that
        // specifies if a space character should be omitted before and after
        // 'comment'.  If 'omitEnclosingWhitespace' is not specified then a
        // space character is inserted before and after 'comment'.  Return 0 on
        // success, and non-zero value otherwise.  Note that a non-zero return
        // value is returned if either 'comment' contains '--' or if
        // 'omitEnclosingWhitespace' is 'true' and 'comment' ends with '-'.
        // Also note that if an element-opening tag is not completed with a
        // '>', 'addValidComment' will add '>'.

    static bsl::ostream& closeElement(bsl::ostream&            stream,
                                      State                   *state,
                                      const bsl::string_view&  name);
        // Decrement the indent level and add the closing tag for the element
        // of the specified 'name' to the specified 'stream', with formatting
        // depending on the specified 'state', and update 'state' accordingly.
        // Return the 'stream'.  If the element does not have content, write
        // '/>' and a newline into stream.  Otherwise, write '</name>' and a
        // newline.  If this '</name>' does not share the same line with data,
        // or it follows another element's closing tag, indent properly before
        // writing '</name>' and the newline.  If 'name' is root element, flush
        // the output stream.  The behavior is undefined if 'name' is not the
        // most recently opened element that's yet to be closed.

    static bsl::ostream& flush(bsl::ostream& stream, State *state);
        // Insert the closing '>' if there is an incomplete tag, and flush the
        // specified output 'stream', with formatting depending on the
        // specified 'state', and update 'state' accordingly.  Return the
        // 'stream'.

    static bsl::ostream&
    openElement(bsl::ostream&            stream,
                State                   *state,
                const bsl::string_view&  name,
                WhitespaceType::Enum     whitespaceMode =
                    WhitespaceType::e_PRESERVE_WHITESPACE);
        // Open an element of the specified 'name' at current indent level with
        // the optionally specified whitespace constraint 'whitespaceMode' for
        // its textual data to the specified 'stream', with formatting
        // depending on the specified 'state', and update 'state' accordingly,
        // incrementing the indent level.  Return the 'stream'.
        // 'whitespaceMode' constrains how textual data is written with
        // 'addListData' for the current element, but not its nested elements.
        // The behavior is undefined if 'openElement' is called after the root
        // element is closed and there is no subsequent call to 'reset'.

    static void reset(State *state);
        // Reset the specified formatter 'state' such that it can be used to
        // format a new XML document as if the formatter were just constructed.
};

// ============================================================================
//                            INLINE DEFINITIONS
// ============================================================================

                      // --------------------------------
                      // class Formatter_CompactImplState
                      // --------------------------------

// CREATORS
inline
Formatter_CompactImplState::Formatter_CompactImplState()
: d_id()
, d_indentLevel()
, d_initialIndentLevel()
, d_spacesPerLevel()
, d_column()
{
}

inline
Formatter_CompactImplState::Formatter_CompactImplState(int indentLevel,
                                                       int spacesPerLevel)
: d_id()
, d_indentLevel(indentLevel)
, d_initialIndentLevel(indentLevel)
, d_spacesPerLevel(spacesPerLevel)
, d_column()
{
}

inline
Formatter_CompactImplState::Formatter_CompactImplState(
                                                   Id::Enum id,
                                                   int      indentLevel,
                                                   int      initialIndentLevel,
                                                   int      spacesPerLevel,
                                                   int      column)
: d_id(id)
, d_indentLevel(indentLevel)
, d_initialIndentLevel(initialIndentLevel)
, d_spacesPerLevel(spacesPerLevel)
, d_column(column)
{
}

// MANIPULATORS
inline
int& Formatter_CompactImplState::column()
{
    return d_column;
}

inline
Formatter_CompactImplStateId::Enum& Formatter_CompactImplState::id()
{
    return d_id;
}

inline
int& Formatter_CompactImplState::indentLevel()
{
    return d_indentLevel;
}

inline
int& Formatter_CompactImplState::initialIndentLevel()
{
    return d_initialIndentLevel;
}

inline
int& Formatter_CompactImplState::spacesPerLevel()
{
    return d_spacesPerLevel;
}

// ACCESSORS
inline
const int& Formatter_CompactImplState::column() const
{
    return d_column;
}

inline
const Formatter_CompactImplStateId::Enum&
Formatter_CompactImplState::id() const
{
    return d_id;
}

inline
const int& Formatter_CompactImplState::indentLevel() const
{
    return d_indentLevel;
}

inline
const int& Formatter_CompactImplState::initialIndentLevel() const
{
    return d_initialIndentLevel;
}

inline
const int& Formatter_CompactImplState::spacesPerLevel() const
{
    return d_spacesPerLevel;
}

                      // --------------------------------
                      // struct Formatter_CompactImplUtil
                      // --------------------------------

// CLASS METHODS
template <class VALUE_TYPE>
bsl::ostream& Formatter_CompactImplUtil::addAttribute(
                                       bsl::ostream&            stream,
                                       State                   *state,
                                       const bsl::string_view&  name,
                                       const VALUE_TYPE&        value,
                                       int                      formattingMode,
                                       const EncoderOptions&    encoderOptions)
{

    stream << ' ' << name << "=\"";
    TypesPrintUtil::print(stream, value, formattingMode, &encoderOptions);
    stream << '"';

    // Minimum output if value is empty.
    state->column() += static_cast<int>(name.length()) + 4;

    return stream;
}

template <class VALUE_TYPE>
bsl::ostream& Formatter_CompactImplUtil::addData(
                                         bsl::ostream&          stream,
                                         State                 *state,
                                         const VALUE_TYPE&      value,
                                         int                    formattingMode,
                                         const EncoderOptions&  encoderOptions)
{
    // Step 1: Print a sequence of conditional tokens to 'stream' and update
    //         the column number and indentation level of 'state'.

    if (StateId::e_IN_TAG == state->id()) {
        stream << '>';
        state->column() += 1;
    }

    TypesPrintUtil::print(stream, value, formattingMode, &encoderOptions);
    state->column() += 1;

    // Step 2: Update the ID of 'state'.

    state->id() = StateId::e_TRAILING_DATA_BETWEEN_TAGS;

    return stream;
}

template <class TYPE>
bsl::ostream& Formatter_CompactImplUtil::addElementAndData(
                                       bsl::ostream&            stream,
                                       State                   *state,
                                       const bsl::string_view&  name,
                                       const TYPE&              value,
                                       int                      formattingMode,
                                       const EncoderOptions&    encoderOptions)
{
    openElement(stream, state, name, WhitespaceType::e_PRESERVE_WHITESPACE);
    addData(stream, state, value, formattingMode, encoderOptions);
    closeElement(stream, state, name);

    return stream;
}

template <class VALUE_TYPE>
bsl::ostream& Formatter_CompactImplUtil::addListData(
                                         bsl::ostream&          stream,
                                         State                 *state,
                                         const VALUE_TYPE&      value,
                                         int                    formattingMode,
                                         const EncoderOptions&  encoderOptions)
{
    // Step 1: Print a sequence of conditional tokens to 'stream' and update
    //         the column number and indentation level of 'state'.

    if (StateId::e_IN_TAG == state->id()) {
        stream << '>';
        state->column() += 1;
    }

    if (StateId::e_FIRST_DATA_BETWEEN_TAGS != state->id() &&
        StateId::e_IN_TAG != state->id()) {
        stream << ' ';
        state->column() += 1;
    }

    TypesPrintUtil::print(stream, value, formattingMode, &encoderOptions);
    state->column() += 1; // assume value is not empty

    // Step 2: Update the ID of 'state'.

    state->id() = StateId::e_TRAILING_DATA_BETWEEN_TAGS;

    return stream;
}

inline
void Formatter_CompactImplUtil::reset(State *state)
{
    state->column()      = 0;
    state->id()          = StateId::e_AT_START;
    state->indentLevel() = state->initialIndentLevel();
}

}  // close package namespace
}  // close enterprise namespace

#endif // INCLUDED_BALXML_FORMATTER_COMPACTIMPL

// ----------------------------------------------------------------------------
// Copyright 2021 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tag_project;

import bropals.lib.simplegame.entity.GameWorld;
import bropals.lib.simplegame.entity.block.BlockEntity;
import bropals.lib.simplegame.logger.InfoLogger;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;

/**
 * Represents an isometric entity.
 *
 * @author Jonathon
 */
public class IsometricEntity extends BlockEntity {

    private BufferedImage north, south, east, west;
    private IsometricDirection facing;
    private BufferedImage using = null, drawnImage = null;

    ;

    private static BufferedImage shadow, shadowSmall;

    private final float localWidth;
    private final float localHeight;
    private float z = 0;
    private float renderCoordX, renderCoordY;
    private final float ISO_ANGLE = (float) Math.atan(69.5 / 40);

    private static final float CAMERA_REFERENCE_LINE = -3000; //Y in render coords

    public IsometricEntity(GameWorld parent,
            float x, float y, float width, float height,
            boolean anchored, IsometricDirection facing,
            BufferedImage north, BufferedImage south, BufferedImage east,
            BufferedImage west) {
        super(parent, x, y, 0, 0, anchored);
        this.north = north;
        this.south = south;
        this.east = east;
        this.west = west;
        if (facing == IsometricDirection.NORTH || facing == IsometricDirection.SOUTH) {
            localWidth = width;
            localHeight = height;
        } else {
            localWidth = height;
            localHeight = width;
        }
        setWidth(localWidth);
        setHeight(localHeight);
        renderCoordX = 0;
        renderCoordY = 0;
        setFacing(facing);
    }

    /**
     * Sets this entity's Z value
     *
     * @param z the new Z value
     */
    public void setZ(float z) {
        this.z = z;
    }

    /**
     * Gets this entity's Z value
     *
     * @return the entity's Z value
     */
    public float getZ() {
        return z;
    }

    /**
     * Returns true if the other entity is behind (has a greater Z
     * value) than this isometric entity.
     *
     * @param other the other entity
     * @return if it is behind
     */
    public boolean behind(IsometricEntity other) {
        return other.getZ() > getZ();
    }

    /**
     * Returns true if the other entity is in front of (has a
     * smaller Z value) than this isometric entity.
     *
     * @param other the other entity
     * @return if it is behind
     */
    public boolean inFrontOf(IsometricEntity other) {
        return other.getZ() < getZ();
    }

    @Override
    public void collideWith(BlockEntity other) {
        if (!(other instanceof BiscuitEntity)) {
            super.collideWith(other);
        }
    }

    /**
     * Gets the raw width of the furniture, unrotated.
     *
     * @return the raw width of the furniture, unrotated
     */
    public float getLocalWidth() {
        return localWidth;
    }

    /**
     * Gets the raw height of the furniture, unrotated.
     *
     * @return the raw height of the furniture, unrotated
     */
    public float getLocalHeight() {
        return localHeight;
    }

    /**
     * Gets the north drawn image
     *
     * @return the north drawn image
     */
    public BufferedImage getNorth() {
        return north;
    }

    /**
     * Sets the north drawn image
     *
     * @param north the north drawn image
     */
    public void setNorth(BufferedImage north) {
        this.north = north;
        revalidateImage();
    }

    /**
     * Gets the south drawn image
     *
     * @return the south drawn image
     */
    public BufferedImage getSouth() {
        return south;
    }

    /**
     * Sets the south drawn image
     *
     * @param south the south drawn image
     */
    public void setSouth(BufferedImage south) {
        this.south = south;
        revalidateImage();
    }

    /**
     * Gets the east drawn image
     *
     * @return the east drawn image
     */
    public BufferedImage getEast() {
        return east;
    }

    /**
     * Sets the east drawn image
     *
     * @param east the east drawn image
     */
    public void setEast(BufferedImage east) {
        this.east = east;
        revalidateImage();
    }

    /**
     * Gets the west drawn image
     *
     * @return the west drawn image
     */
    public BufferedImage getWest() {
        return west;
    }

    /**
     * Sets the west drawn image
     *
     * @param west the west drawn image
     */
    public void setWest(BufferedImage west) {
        this.west = west;
        revalidateImage();
    }

    /**
     * Gets the direction this entity is facing
     *
     * @return the direction this entity is facing
     */
    public IsometricDirection getFacing() {
        return facing;
    }

    /**
     * Sets the direction this entity is facing
     *
     * @param facing the direction this entity is facing
     */
    public void setFacing(IsometricDirection facing) {
        this.facing = facing;
        if (facing == IsometricDirection.NORTH || facing == IsometricDirection.SOUTH) {
            setWidth(localWidth);
            setHeight(localHeight);
        } else {
            setWidth(localHeight);
            setHeight(localWidth);
        }
        revalidateImage();
    }

    /**
     * Ensures that this IsometricEntity is using the correct image.
     */
    public void revalidateImage() {
        switch (facing) {
            case NORTH:
                using = north;
                break;
            case SOUTH:
                using = south;
                break;
            case EAST:
                using = east;
                break;
            case WEST:
                using = west;
                break;
        }
        if (!(this instanceof AnimatedIsometricEntity)
                && !(this instanceof FurnitureEntity) && !(this instanceof BiscuitEntity)) {
            rebuildDrawnImage();
        } else {
            drawnImage = using;
        }
    }

    /*
     @Override
     public void setY(float y) {
     super.setY(y);
     if (getParent() != null) {
     ((IsometricGameWorld) getParent()).reorderEntity(this);
     }
     }
     */
    /**
     * Gets what image is being used currently
     *
     * @return the currently used image
     */
    public BufferedImage getUsing() {
        return using;
    }

    /**
     * Sets what image this Isometric entity will use to draw
     *
     * @param using what image is being used
     */
    public void setUsing(BufferedImage using) {
        this.using = using;
    }

    public void setDrawn(BufferedImage drawn) {
        drawnImage = using;
    }

    public void calcRenderCoords() {
        renderCoordX = ((float) 69.5 * ((getY() / 80) - (getX() / 80)));
        renderCoordY = (40 * ((getX() / 80) + (getY() / 80)));
    }

    public void calcZValue() {
        if (this instanceof DecorationEntity) {
            z = 5000;
        } else {
            z = CAMERA_REFERENCE_LINE + (40 * (((getX() + getWidth()) / 80) + ((getY() + getHeight()) / 80)));
        }
    }

    @Override
    public void render(Object graphicsObj) {
        Graphics g = (Graphics) graphicsObj;
        //80 y -> +40y -70x
        //80 x -> +40y +70x

        if (getParent() == null || getCamera() == null) // don't draw with no parent or camera
            return;

        if (drawnImage == null) {
            this.revalidateImage();
            drawnImage = using;
        }
        if (drawnImage == null) {
            return; // we give up on u drawnImage
        }
        int imagePosX = 0;
        int imagePosY = 0;
        if (!(this instanceof FurnitureEntity)) {
            imagePosX = (int) (renderCoordX - (Math.sin(ISO_ANGLE) * getWidth()) - getCamera().getX());
            imagePosY = (int) (renderCoordY - getCamera().getY() - 120);
        } else {
            // find teh bottom right of the image
            float bottomRightX = renderCoordX
                    - (float) ((Math.sin(ISO_ANGLE) * getWidth()));
            float bottomRightY = renderCoordY
                    + (float) (Math.cos(ISO_ANGLE) * getHeight())
                    + (float) (Math.cos(ISO_ANGLE) * getWidth());
            imagePosX = (int) (bottomRightX - getCamera().getX());
            imagePosY = (int) (bottomRightY - drawnImage.getHeight() - getCamera().getY());

        }
        //Don't draw it if it is off the screen
            int sw = getParent().getState().getWindow().getScreenWidth();
            int sh = getParent().getState().getWindow().getScreenHeight();
            if (imagePosX > sw
                    || imagePosY > sh
                    || imagePosX < -drawnImage.getWidth()
                    || imagePosY < -drawnImage.getHeight()) {
                return;
            }
        // drawing the shadows
        if (this instanceof AnimatedIsometricEntity) {
            if (shadow == null) {
                shadow = getParent().getState().getAssetManager().getImage("shadow");
            }
            g.drawImage(shadow,
                    (int) imagePosX, (int) imagePosY + 120, null);
        } else if (this instanceof BiscuitEntity) {
            if (shadowSmall == null) {
                shadowSmall = getParent().getState().getAssetManager().getImage("shadowSmall");
            }
            g.drawImage(shadowSmall,
                    (int) imagePosX, (int) imagePosY + 120, null);
        }
        g.drawImage(drawnImage, imagePosX, imagePosY, null);

        //g.setColor(Color.RED);
        //int cornerPosX = (int) (renderCoordX - getCamera().getX()); // render coord local (0, 0) (NOT image coordinate)
        //int cornerPosY = (int) (renderCoordY - getCamera().getY());
        // draw the renderCoord local (0, 0) point
        //g.fillRect(cornerPosX, cornerPosY, 6, 6);
        // display it's world coordinates
        //g.drawString("(" + getX() + ", " + getY() + ", " + getZ() + ")", cornerPosX + 10, cornerPosY);

        /*
         // draw a box around it
         if (drawnImage != null) {
         g.drawRect(imagePosX, imagePosY, (int) drawnImage.getWidth(),
         (int) drawnImage.getHeight());
         }
         */
    }

    private void rebuildDrawnImage() {
        // make a tiled image for isometric drawing
        if (getLocalWidth() == 0 || getLocalHeight() == 0) {
            InfoLogger.println("This ain't no good size");
            return; // :(
        }
        float width = (float) ((getHeight() * Math.sin(ISO_ANGLE))
                + (getWidth() * Math.sin(ISO_ANGLE)));
        float height = 120 + (float) ((getHeight() * Math.cos(ISO_ANGLE))
                + (getWidth() * Math.cos(ISO_ANGLE)));
        //System.out.println("Width: " + width + "  Height: " + height);
        drawnImage = new BufferedImage((int) width, (int) height, BufferedImage.TRANSLUCENT);
        Graphics2D g2img = (Graphics2D) drawnImage.getGraphics();
        float basePointX = (float) (Math.sin(ISO_ANGLE) * getWidth());
        float basePointY = 200f;
        int numTilesDrawn = 0;
        for (float h = 0; h < (getHeight() / 80); h++) {
            for (float w = 0; w < (getWidth() / 80); w++) {
                double xPos = basePointX - (69.5 * w) + (69.5 * h);
                double yPos = basePointY + (40 * w) + (40 * h);
                g2img.drawImage(using, (int) (xPos - 69.5),
                        (int) (yPos - 200), null);
                numTilesDrawn++;
            }
        }
    }

    public Camera getCamera() {
        return ((HouseState) getParent().getState()).getCamera();
    }

    public float getRenderCoordX() {
        return renderCoordX;
    }

    public float getRenderCoordY() {
        return renderCoordY;
    }

    public void setVelocityTowards(float x, float y, float speed) {
        float diffX = x - getCenterX();
        float diffY = y - getCenterY();
        getVelocity().setValues(diffX, diffY);
        getVelocity().normalizeLocal();
        getVelocity().scaleLocal(speed);
    }

    public Rectangle toRect() {
        return new Rectangle((int) getX(), (int) getY(), (int) getWidth(), (int) getHeight());
    }
}

redpajama_set_name: RedPajamaGithub


text:
package d_m

//compatibility stub
trait ReportingCompat


text:
require "test_helper"

module ActiveRecord
  module Type
    class BooleanTest < SpannerAdapter::TestCase
      include SpannerAdapter::Types::TestHelper

      def test_convert_to_sql_type
        assert_equal "BOOL", connection.type_to_sql(:boolean)
      end

      def test_set_boolean_value_in_create
        record = TestTypeModel.create(active: true)
        record.reload
        assert_equal true, record.active

        record = TestTypeModel.create(active: false)
        record.reload
        assert_equal false, record.active
      end
    end
  end
end


text:
import fileinput
import glob
import optparse
import os
import shlex
import textwrap

def AggregateVectorIcons(working_directory, file_list, output_cc, output_h):
  """Compiles all .icon files in a directory into two C++ files.

  Args:
      working_directory: The path to the directory that holds the .icon files
          and C++ templates.
      file_list: A file containing the list of vector icon files to process.
          Used for GN only (this argument defaults to None for GYP).
      output_cc: The path that should be used to write the .cc file.
      output_h: The path that should be used to write the .h file.
  """

  icon_list = []
  if file_list is None:
    # TODO(GYP_GONE): |file_list| is only None for GYP builds (where response
    # files are not supported), in which case we process all .icon files
    # contained within |working_directory| and all of its descendant
    # directories. This logic can be removed when GN is used everywhere.
    # See crbug.com/535386.
    for dirpath, dirnames, filenames in os.walk(working_directory):
      icon_list.extend(glob.glob(os.path.join(dirpath, "*.icon")))
  else:
    with open(file_list, 'r') as f:
      file_list_contents = f.read()
    icon_list = shlex.split(file_list_contents)

  input_header_template = open(os.path.join(working_directory,
                                            "vector_icons.h.template"))
  header_template_contents = input_header_template.readlines()
  input_header_template.close()
  output_header = open(output_h, "w")
  for line in header_template_contents:
    if not "TEMPLATE_PLACEHOLDER" in line:
      output_header.write(line)
      continue

    for icon_path in icon_list:
      # The icon name should be of the format "foo.icon" or "foo.1x.icon".
      (icon_name, extension) = os.path.splitext(os.path.basename(icon_path))
      (icon_name, scale_factor) = os.path.splitext(icon_name)
      if not scale_factor:
        output_header.write("  {},\n".format(icon_name.upper()))
  output_header.close()

  input_cc_template = open(
      os.path.join(working_directory, "vector_icons.cc.template"))
  cc_template_contents = input_cc_template.readlines()
  input_cc_template.close()
  output_cc = open(output_cc, "w")
  for line in cc_template_contents:
    if not "TEMPLATE_PLACEHOLDER" in line:
      output_cc.write(line)
      continue;

    for icon_path in icon_list:
      (icon_name, extension) = os.path.splitext(os.path.basename(icon_path))
      (icon_name, scale_factor) = os.path.splitext(icon_name)
      assert not scale_factor or scale_factor == ".1x"
      if (("1X" in line and scale_factor != ".1x") or
          (not "1X" in line and scale_factor == ".1x")):
        continue

      icon_file = open(icon_path)
      vector_commands = "".join(icon_file.readlines())
      icon_file.close()
      output_cc.write("ICON_TEMPLATE({}, {})\n".format(icon_name.upper(),
                                                       vector_commands))
  output_cc.close()

def main():
  parser = optparse.OptionParser()
  parser.add_option("--working_directory",
                    help="The directory to look for template C++ as well as "
                         "icon files.")
  parser.add_option("--file_list",
                    help="A response file containing the list of icon files "
                         "to be processed (GN only). Defaults to None.",
                    default=None)
  parser.add_option("--output_cc",
                    help="The path to output the CC file to.")
  parser.add_option("--output_h",
                    help="The path to output the header file to.")

  (options, args) = parser.parse_args()

  AggregateVectorIcons(options.working_directory,
                       options.file_list,
                       options.output_cc,
                       options.output_h)

if __name__ == "__main__":
  main()


text:
package com.intellij.java.find;

import com.intellij.codeInsight.hint.EditorHintListener;
import com.intellij.find.FindModel;
import com.intellij.find.impl.livePreview.LivePreview;
import com.intellij.find.impl.livePreview.LivePreviewController;
import com.intellij.find.impl.livePreview.SearchResults;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.testFramework.EditorTestUtil;
import com.intellij.testFramework.LightCodeInsightTestCase;
import com.intellij.testFramework.fixtures.EditorMouseFixture;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;

import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

public class FindInEditorTest extends LightCodeInsightTestCase {

  private LivePreviewController myLivePreviewController;
  private FindModel myFindModel;

  private ByteArrayOutputStream myOutputStream;

  @Override
  protected void setUp() throws Exception {
    super.setUp();

    myFindModel = new FindModel();

    myOutputStream = new ByteArrayOutputStream();
    LivePreview.ourTestOutput = new PrintStream(myOutputStream);
    EditorHintListener listener = (project, hint, flags) -> LivePreview.processNotFound();
    ApplicationManager.getApplication().getMessageBus().connect(getTestRootDisposable()).subscribe(EditorHintListener.TOPIC, listener);
  }

  @Override
  protected void tearDown() throws Exception {
    myFindModel = null;
    myOutputStream = null;
    myLivePreviewController = null;
    super.tearDown();
  }

  @Override
  // disabling execution of tests in command/write action
  protected void runTest() throws Throwable {
    doRunTest();
  }

  private void initFind() {
    SearchResults searchResults = new SearchResults(getEditor(), getProject());
    myLivePreviewController = new LivePreviewController(searchResults, null, getTestRootDisposable());
    myFindModel.addObserver(findModel -> myLivePreviewController.updateInBackground(myFindModel, true));
    myLivePreviewController.on();
  }

  public void testBasicFind() {
    configureFromText("ab");
    initFind();
    myFindModel.setStringToFind("a");
    checkResults();
    myFindModel.setStringToFind("a2");
    assertTrue(!myEditor.getSelectionModel().hasSelection());
  }

  public void testEmacsLikeFallback() {
    configureFromText("a\nab");
    initFind();
    myFindModel.setStringToFind("a");
    myFindModel.setStringToFind("ab");
    myFindModel.setStringToFind("a");
    checkResults();
  }

  public void testReplacementWithEmptyString() {
    configureFromText("a");
    initFind();

    myFindModel.setRegularExpressions(true);
    myFindModel.setStringToFind("a");
    myFindModel.setStringToReplace("");
    myFindModel.setReplaceState(true);

    myLivePreviewController.performReplace();
    checkResults();
  }

  public void testSecondFind() {
    configureFromText("<selection>a<caret></selection> b b a");
    invokeFind();
    new EditorMouseFixture((EditorImpl)myEditor).doubleClickAt(0, 3);
    invokeFind();
    checkResultByText("a <selection>b<caret></selection> b a");
  }

  public void testSecondRegexReplaceShowsPopup() {
    configureFromText("<caret> aba");
    initFind();
    myFindModel.setRegularExpressions(true);
    myFindModel.setStringToFind("a");
    myFindModel.setStringToReplace("c");
    myFindModel.setReplaceState(true);
    myLivePreviewController.performReplace();
    checkResults();
  }

  public void testUndoingReplaceBringsChangePlaceIntoView() {
    configureFromText("abc\n\n\n\n\nabc\n");
    EditorTestUtil.setEditorVisibleSize(myEditor, 100, 3);
    executeAction(IdeActions.ACTION_EDITOR_TEXT_END_WITH_SELECTION);

    EditorTestUtil.testUndoInEditor(myEditor, () -> {
      initFind();
      myFindModel.setReplaceState(true);
      myFindModel.setGlobal(false);
      myFindModel.setStringToFind("abc");
      myFindModel.setStringToReplace("def");

      myLivePreviewController.performReplace();
      myLivePreviewController.performReplace();

      executeAction(IdeActions.ACTION_UNDO);
      executeAction(IdeActions.ACTION_UNDO);

      checkResultByText("abc\n\n\n\n\nabc\n");
      checkOffsetIsVisible(myEditor, 0);
    });
  }

  private static void checkOffsetIsVisible(@NotNull Editor editor, int offset) {
    Point point = editor.offsetToXY(offset);
    assertTrue(editor.getScrollingModel().getVisibleAreaOnScrollingFinished().contains(point));
  }

  private static void invokeFind() {
    executeAction(IdeActions.ACTION_FIND);
    UIUtil.dispatchAllInvocationEvents();
  }

  private static void configureFromText(String text) {
    configureFromFileText("file.txt", text);
  }

  private void checkResults() {
    String name = getTestName(false);
    assertSameLinesWithFile(getTestDataPath() + "/find/findInEditor/" + name + ".gold", myOutputStream.toString());
  }
}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const store_1 = require(".././store");
function input(field) {
    const node = {
        deps: field,
        events: [{ name: "input", listener: onInputChange, options: false }],
        name: "input"
    };
    function onInputChange(e) {
        field.value = e.data;
        store_1.saveField(field);
    }
    return node;
}
exports.input = input;
//# sourceMappingURL=input.js.map


text:
@interface NSObject (PropertyInjection)

- (void)typhoon_injectValue:(id)value forPropertyName:(NSString *)propertyName;

@end


text:
'use strict';

const Fs = require('fs');
const Path = require('path');

const Boom = require('@hapi/boom');
const Bounce = require('@hapi/bounce');
const Hoek = require('@hapi/hoek');
const Validate = require('@hapi/validate');

const Schemas = require('./schemas');
const Utils = require('./utils');

// Additional helper modules required in constructor

const internals = {};

internals.defaults = {
    // defaultExtension: '',
    // path: '',
    // relativeTo: '',
    compileOptions: {},
    runtimeOptions: {},
    layout: false,
    layoutKeyword: 'content',
    encoding: 'utf8',
    isCached: true,
    allowAbsolutePaths: false,
    allowInsecureAccess: false,
    // partialsPath: '',
    contentType: 'text/html',
    compileMode: 'sync',
    context: null
};

module.exports = class Manager {

    constructor(server, options) {

        Validate.assert(options, Schemas.manager);

        // Save non-defaults values

        const engines = options.engines;
        const defaultExtension = options.defaultExtension;

        // Clone options

        const defaults = Hoek.applyToDefaults(internals.defaults, options, { shallow: ['engines', 'context'] });
        delete defaults.engines;
        delete defaults.defaultExtension;

        // Prepare manager state

        const extensions = Object.keys(engines);
        Hoek.assert(extensions.length, 'Views manager requires at least one registered extension handler');

        // Private class props

        this._server = server;
        this._context = defaults.context;
        this._engines = {};
        this._defaultExtension = defaultExtension || (extensions.length === 1 ? extensions[0] : '');

        // Load engines

        for (const extension of extensions) {
            const config = engines[extension];
            const engine = {};

            if (typeof config.compile === 'function') {
                engine.module = config;
                engine.config = defaults;
            }
            else {
                Validate.assert(config, Schemas.view);

                engine.module = config.module;
                engine.config = Hoek.applyToDefaults(defaults, config, { shallow: ['module'] });
            }

            engine.suffix = '.' + extension;
            engine.compileFunc = engine.module.compile;

            if (engine.config.compileMode === 'sync') {
                engine.compileFunc = function (str, opt, next) {

                    let compiled = null;
                    try {
                        compiled = engine.module.compile(str, opt);
                    }
                    catch (err) {
                        return next(err);
                    }

                    const renderer = function (context, runtimeOptions, renderNext) {

                        let rendered = null;
                        try {
                            rendered = compiled(context, runtimeOptions);
                        }
                        catch (err) {
                            return renderNext(err);
                        }

                        return renderNext(null, rendered);
                    };

                    return next(null, renderer);
                };
            }

            if (engine.config.isCached) {
                engine.cache = {};
            }

            // When a prepare function is provided, state needs to be initialized before trying to compile and render

            engine.ready = !(engine.module.prepare && typeof engine.module.prepare === 'function');

            // Load partials and helpers

            this._loadPartials(engine);
            this._loadHelpers(engine);

            // Set engine

            this._engines[extension] = engine;
        }
    }

    _loadPartials(engine) {

        if (!engine.config.partialsPath ||
            !engine.module.registerPartial) {

            return;
        }

        const traverse = function (path) {

            let files = [];

            Fs.readdirSync(path).forEach((file) => {

                file = Path.join(path, file);
                const stat = Fs.statSync(file);
                if (stat.isDirectory()) {
                    files = files.concat(traverse(file));
                    return;
                }

                if (Path.basename(file)[0] !== '.' &&
                    Path.extname(file) === engine.suffix) {

                    files.push(file);
                }
            });

            return files;
        };

        const partialsPaths = [].concat(engine.config.partialsPath);

        for (const partialsPath of partialsPaths) {
            const path = internals.path(engine.config.relativeTo, partialsPath);
            const files = traverse(path);
            for (const file of files) {
                const offset = path.slice(-1) === Path.sep ? 0 : 1;
                const name = file.slice(path.length + offset, -engine.suffix.length).replace(/\\/g, '/');
                const src = Fs.readFileSync(file).toString(engine.config.encoding);
                engine.module.registerPartial(name, src);
            }
        }
    }

    _loadHelpers(engine) {

        if (!engine.config.helpersPath ||
            !engine.module.registerHelper) {

            return;
        }

        const helpersPaths = [].concat(engine.config.helpersPath);

        for (const helpersPath of helpersPaths) {
            let path = internals.path(engine.config.relativeTo, helpersPath);
            if (!Path.isAbsolute(path)) {
                path = Path.join(process.cwd(), path);
            }

            Fs.readdirSync(path).forEach((file) => {

                file = Path.join(path, file);
                const stat = Fs.statSync(file);
                if (stat.isDirectory() ||
                    Path.basename(file).startsWith('.') ||
                    !Object.keys(require.extensions).includes(Path.extname(file))) {
                    return;
                }

                try {
                    if (!engine.config.isCached) {
                        this._bustRequireCache(file);
                    }

                    const required = require(file);

                    const offset = path.slice(-1) === Path.sep ? 0 : 1;
                    const name = file.slice(path.length + offset, -Path.extname(file).length);
                    const helper = required[name] || required.default || required;
                    if (typeof helper === 'function') {
                        engine.module.registerHelper(name, helper);
                    }
                }
                catch (err) {
                    this._server.log(['vision', 'helper', 'load', 'error'], { file, err });
                }
            });
        }
    }

    async _prepare(template, options) {

        options = options || {};

        const fileExtension = Path.extname(template).slice(1);
        const extension = fileExtension || this._defaultExtension;
        if (!extension) {
            throw Boom.badImplementation('Unknown extension and no defaultExtension configured for view template: ' + template);
        }

        const engine = this._engines[extension];
        if (!engine) {
            throw Boom.badImplementation('No view engine found for file: ' + template);
        }

        template = template + (fileExtension ? '' : engine.suffix);

        if (!engine.ready) {
            await this._prepareEngine(engine);
        }

        return this._prepareTemplates(template, engine, options);
    }

    _prepareEngine(engine) {

        // _prepareEngine can only be invoked when the prepare function is defined

        return new Promise((resolve, reject) => {

            try {
                return engine.module.prepare(engine.config, (err) => {

                    if (err) {
                        return reject(err);
                    }

                    engine.ready = true;
                    return resolve();
                });
            }
            catch (err) {
                return reject(err);
            }
        });
    }

    async _prepareTemplates(template, engine, options) {

        const compiled = {
            settings: Hoek.applyToDefaults(engine.config, options)
        };

        const templatePath = await this._path(template, compiled.settings, false);

        if (!engine.config.isCached) {
            this._loadPartials(engine);
            this._loadHelpers(engine);
        }

        const compiledTemplate = await this._compile(templatePath, engine, compiled.settings);
        compiled.template = compiledTemplate;

        if (compiled.settings.layout) {
            const layoutPath = await this._path((compiled.settings.layout === true ? 'layout' : compiled.settings.layout) + engine.suffix, compiled.settings, true);
            compiled.layout = await this._compile(layoutPath, engine, compiled.settings);
        }

        return compiled;
    }

    async _path(template, settings, isLayout) {

        // Validate path

        const isAbsolutePath = Path.isAbsolute(template);
        const isInsecurePath = template.match(/\.\.\//g);

        if (!settings.allowAbsolutePaths &&
            isAbsolutePath) {

            throw Boom.badImplementation('Absolute paths are not allowed in views');
        }

        if (!settings.allowInsecureAccess &&
            isInsecurePath) {

            throw Boom.badImplementation('View paths cannot lookup templates outside root path (path includes one or more \'../\')');
        }

        // Resolve path and extension

        let paths;
        if (isAbsolutePath) {
            paths = [template];
        }
        else {
            paths = [].concat((isLayout && settings.layoutPath) || settings.path);

            for (let i = 0; i < paths.length; ++i) {
                paths[i] = internals.path(settings.relativeTo, paths[i], template);
            }
        }

        for (const path of paths) {
            try {
                const stats = await Utils.stat(path);
                if (stats.isFile()) {
                    return path;
                }
            }
            catch (err) {
                Bounce.rethrow(err, 'system');
            }
        }

        throw Boom.badImplementation('View file not found: `' + template + '`. Locations searched: [' + paths.join(',') + ']');
    }

    async _compile(template, engine, settings) {

        if (engine.cache &&
            engine.cache[template]) {

            return engine.cache[template];
        }

        settings.compileOptions.filename = template;            // Pass the template to Pug via this copy of compileOptions

        // Read file

        try {
            var data = await Utils.readFile(template, { encoding: settings.encoding });
        }
        catch (err) {
            throw Boom.badImplementation('Failed to read view file: ' + template);
        }

        return new Promise((resolve, reject) => {

            engine.compileFunc(data, settings.compileOptions, (err, compiled) => {

                if (err) {
                    reject(Boom.boomify(err));
                    return;
                }

                if (engine.cache) {
                    engine.cache[template] = compiled;
                }

                resolve(compiled);
            });
        });
    }

    async _render(compiled, context, request, callback) {

        if (this._context) {

            let base = this._context;

            if (typeof this._context === 'function') {

                base = await base(request);
            }

            if (context) {

                base = Object.assign({}, base);             // Shallow cloned
                const keys = Object.keys(context);

                for (let i = 0; i < keys.length; ++i) {
                    const key = keys[i];
                    base[key] = context[key];
                }
            }

            context = base;
        }

        context = context || {};

        if (compiled.layout &&
            context.hasOwnProperty(compiled.settings.layoutKeyword)) {

            throw Boom.badImplementation('settings.layoutKeyword conflict', { context, keyword: compiled.settings.layoutKeyword });
        }

        return new Promise((resolve, reject) => {

            compiled.template(context, compiled.settings.runtimeOptions, (err, renderedContent) => {

                if (err) {
                    reject(Boom.badImplementation(err.message, err));
                    return;
                }

                // No layout

                if (!compiled.layout) {
                    resolve(renderedContent);
                    return;
                }

                // With layout

                context[compiled.settings.layoutKeyword] = renderedContent;
                compiled.layout(context, compiled.settings.runtimeOptions, (err, renderedWithLayout) => {

                    delete context[compiled.settings.layoutKeyword];

                    if (err) {
                        reject(Boom.badImplementation(err.message, err));
                        return;
                    }

                    resolve(renderedWithLayout);
                });
            });
        });
    }

    _response(template, context, options, request) {

        Validate.assert(options, Schemas.viewOverride);

        const source = { manager: this, template, context, options };
        return request.generateResponse(source, { variety: 'view', marshal: internals.marshal, prepare: internals.prepare });
    }

    _bustRequireCache(path) {

        const modulekey = require.resolve(path);
        const mod = require.cache[modulekey];

        if (mod) {
            // Remove module from require cache
            delete require.cache[modulekey];

            // Remove module references from parent module
            mod.parent.children = mod.parent.children.filter((el) => el !== mod);
        }
    }

    getEngine(ext) {

        let engine;

        if (!ext) {
            // The _defaultExtension is set if there is a single extension in _engines
            if (!this._defaultExtension) {
                throw new Error('Must provide an extension or set defaultExtension in manager options');
            }

            engine = this._engines[this._defaultExtension];
        }
        else {
            engine = this._engines[ext];
            if (!engine) {
                throw new Error(`Extension "${ext}" not found on manager`);
            }
        }

        return engine;
    }

    clearCache(template, engine) {

        if (!template) {
            throw new Error('template is required');
        }

        // The _defaultExtension is set if there is a single extension in _engines
        if (!engine && !Path.extname(template) && !this._defaultExtension) {
            throw new Error('Must pass the engine, have a single engine on the manager, have an extension on the template name, or set defaultExtension on manager options');
        }

        const extension = Path.extname(template) ? Path.extname(template).slice(1) : this._defaultExtension;
        engine = engine || this.getEngine(extension);

        const templateWithSuffix = Path.extname(template) ? template : (template + engine.suffix);
        const templateFullPath = internals.path(engine.config.relativeTo, engine.config.path, templateWithSuffix);

        if (!engine.cache[templateFullPath]) {
            this._server.log(['vision', 'cache', 'clear', 'error'], { template: templateFullPath });
        }

        delete engine.cache[templateFullPath];
    }

    registerHelper(name, helper) {

        Object.keys(this._engines).forEach((extension) => {

            const engine = this._engines[extension];

            if (typeof engine.module.registerHelper === 'function') {
                engine.module.registerHelper(name, helper);
            }
        });
    }

    async render(filename, context, options, request) {

        const compiled = await this._prepare(filename, options);

        return await this._render(compiled, context, request);
    }
};

internals.path = function (base, path, file) {

    if (path &&
        Path.isAbsolute(path)) {

        return Path.join(path, file || '');
    }

    return Path.join(base || '', path || '', file || '');
};

internals.marshal = async function (response) {

    const manager = response.source.manager;
    const rendered = await manager._render(response.source.compiled, response.source.context, response.request);
    const config = response.source.compiled.settings;

    if (!response.headers['content-type']) {
        response.type(config.contentType);
    }

    response.encoding(config.encoding);
    return rendered;
};

internals.prepare = async function (response) {

    const manager = response.source.manager;
    response.source.compiled = await manager._prepare(response.source.template, response.source.options);
    return response;
};


text:
package com.popomusic.videoModel;

import java.util.List;

/**
 * @author zsj
 */

public class Replies {

    public List<ReplyList> replyList;

}


text:
package api

type FormatsResponse struct {
	Formats []string `json:"formats"`
}

func (a *API) getFormats(ctx *context) {
	ctx.Success(FormatsResponse{Formats: a.c.formats.Keys()})
}

type LeechTypesResponse struct {
	LeechTypes []string `json:"leech_types"`
}

func (a *API) getLeechTypes(ctx *context) {
	ctx.Success(LeechTypesResponse{LeechTypes: a.c.leechTypes.Keys()})
}

type MediaResponse struct {
	Media []string `json:"media"`
}

func (a *API) getMedia(ctx *context) {
	ctx.Success(MediaResponse{Media: a.c.media.Keys()})
}

type ReleaseGroupTypesResponse struct {
	ReleaseGroupTypes []string `json:"release_group_types"`
}

func (a *API) getReleaseGroupTypes(ctx *context) {
	ctx.Success(ReleaseGroupTypesResponse{ReleaseGroupTypes: a.c.releaseGroupTypes.Keys()})
}

type ReleasePropertiesResponse struct {
	ReleaseProperties []string `json:"release_properties"`
}

func (a *API) getReleaseProperties(ctx *context) {
	ctx.Success(ReleasePropertiesResponse{ReleaseProperties: a.c.releaseProperties.Keys()})
}

type ReleaseRolesResponse struct {
	ReleaseRoles []string `json:"release_roles"`
}

func (a *API) getReleaseRoles(ctx *context) {
	ctx.Success(ReleaseRolesResponse{ReleaseRoles: a.c.releaseRoles.Keys()})
}

type PrivilegesResponse struct {
	Privileges []string `json:"privileges"`
}

func (a *API) getPrivileges(ctx *context) {
	ctx.Success(PrivilegesResponse{Privileges: a.c.privileges.Keys()})
}


text:
title: "Production Readiness Checklist"
nav-parent_id: ops
nav-pos: 5
---
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

* ToC
{:toc}

## Production Readiness Checklist

Purpose of this production readiness checklist is to provide a condensed overview of configuration options that are
important and need **careful considerations** if you plan to bring your Flink job into **production**. For most of these options
Flink provides out-of-the-box defaults to make usage and adoption of Flink easier. For many users and scenarios, those
defaults are good starting points for development and completely sufficient for "one-shot" jobs.

However, once you are planning to bring a Flink application to production the requirements typically increase. For example,
you want your job to be (re-)scalable and to have a good upgrade story for your job and new Flink versions.

In the following, we present a collection of configuration options that you should check before your job goes into production.

### Set maximum parallelism for operators explicitly

Maximum parallelism is a configuration parameter that is newly introduced in Flink 1.2 and has important implications
for the (re-)scalability of your Flink job. This parameter, which can be set on a per-job and/or per-operator granularity,
determines the maximum parallelism to which you can scale operators. It is important to understand that (as of now) there
is **no way to change** this parameter after your job has been started, except for restarting your job completely
from scratch (i.e. with a new state, and not from a previous checkpoint/savepoint). Even if Flink would provide some way
to change maximum parallelism for existing savepoints in the future, you can already assume that for large states this is
likely a long running operation that you want to avoid. At this point, you might wonder why not just to use a very high
value as default for this parameter. The reason behind this is that high maximum parallelism can have some impact on your
application's performance and even state sizes, because Flink has to maintain certain metadata for its ability to rescale which
can increase with the maximum parallelism. In general, you should choose a max parallelism that is high enough to fit your
future needs in scalability, but keeping it as low as possible can give slightly better performance. In particular,
a maximum parallelism higher that 128 will typically result in slightly bigger state snapshots from the keyed backends.

Notice that maximum parallelism must fulfill the following conditions:

`0 < parallelism  <= max parallelism <= 2^15`

You can set the maximum parallelism by `setMaxParallelism(int maxparallelism)`. By default, Flink will choose the maximum
parallelism as a function of the parallelism when the job is first started:

- `128` : for all parallelism <= 128.
- `MIN(nextPowerOfTwo(parallelism + (parallelism / 2)), 2^15)` : for all parallelism > 128.

### Set UUIDs for operators

As mentioned in the documentation for [savepoints]({{ site.baseurl }}/ops/state/savepoints.html), users should set uids for
operators. Those operator uids are important for Flink's mapping of operator states to operators which, in turn, is
essential for savepoints. By default operator uids are generated by traversing the JobGraph and hashing certain operator
properties. While this is comfortable from a user perspective, it is also very fragile, as changes to the JobGraph (e.g.
exchanging an operator) will result in new UUIDs. To establish a stable mapping, we need stable operator uids provided
by the user through `setUid(String uid)`.

### Choice of state backend

Currently, Flink has the limitation that it can only restore the state from a savepoint for the same state backend that
took the savepoint. For example, this means that we can not take a savepoint with a memory state backend, then change
the job to use a RocksDB state backend and restore. While we are planning to make backends interoperable in the near
future, they are not yet. This means you should carefully consider which backend you use for your job before going to
production.

In general, we recommend using RocksDB because this is currently the only state backend that supports large states (i.e.
state that exceeds the available main memory) and asynchronous snapshots. From our experience, asynchronous snapshots are
very important for large states because they do not block the operators and Flink can write the snapshots without stopping
stream processing. However, RocksDB can have worse performance than, for example, the memory-based state backends. If
you are sure that your state will never exceed main memory and blocking the stream processing to write it is not an issue,
you **could consider** to not use the RocksDB backends. However, at this point, we **strongly recommend** using RocksDB
for production.

### Config JobManager High Availability(HA)

The JobManager coordinates every Flink deployment. It is responsible for both *scheduling* and *resource management*.

By default, there is a single JobManager instance per Flink cluster. This creates a *single point of failure* (SPOF):
if the JobManager crashes, no new programs can be submitted and running programs fail.

With JobManager High Availability, you can recover from JobManager failures and thereby eliminate the *SPOF*.
We **strongly recommend** you configure [high availability]({{ site.baseurl }}/ops/jobmanager_high_availability.html) for production.

{% top %}


text:
import access
import ranker
import grades_rank
import json
import vancouver

@auth.requires_signature()
def run_rep_sys():
    """Runs the reputation system."""
    c = db.venue(request.vars[REPUTATION_SYSTEM_PARAM_VENUE_ID])
    if c is None:
        logger.warning("Invalid call to reputation system computation: " + str(request))
        return redirect(URL('venues', 'managed_index'))
    try:
        current.num_iterations = int(request.vars[REPUTATION_SYSTEM_PARAM_NUM_ITERATIONS])
    except Exception:
        logger.warning("Missing number of iterations in specification.")
        current.num_iterations = ALGO_DEFAULT_NUM_ITERATIONS
    try:
        current.review_percentage = float(request.vars[REPUTATION_SYSTEM_PARAM_REVIEW_PERCENTAGE])
    except Exception:
        current.review_percentage = ALGO_DEFAULT_REVIEWS_AS_PERCENTAGE
    startover = False
    try:
        startover = request.vars[REPUTATION_SYSTEM_STARTOVER] == 'True'
    except Exception:
        pass
    run_id = request.vars[REPUTATION_SYSTEM_RUN_ID]
    publish = request.vars[REPUTATION_SYSTEM_PUBLISH] == 'True'
    algo = request.vars[REPUTATION_SYSTEM_ALGO]
    current.cost_type = request.vars[REPUTATION_SYSTEM_COST_TYPE]
    if current.cost_type is None:
        current.cost_type = ALGO_DEFAULT_COST_TYPE
    try:
        current.pos_slope = float(request.vars[REPUTATION_SYSTEM_POS_SLOPE])
    except Exception:
        current.pos_slope = ALGO_DEFAULT_POS_SLOPE
    try:
        current.neg_slope = float(request.vars[REPUTATION_SYSTEM_NEG_SLOPE])
    except Exception:
        current.neg_slope = ALGO_DEFAULT_NEG_SLOPE

    current.normalize_grades = request.vars[REPUTATION_SYSTEM_NORMALIZE_GRADES] == 'True'
    try:
        current.normalization_scale = float(request.vars[REPUTATION_SYSTEM_NORMALIZATION_SCALE])
    except Exception:
        current.normalization_scale = ALGO_DEFAULT_NORMALIZATION_SCALE

    current.use_submission_rank_in_rep = request.vars[REPUTATION_SYSTEM_USE_SUBMISSION_RANK_IN_REP] == 'True'
    try:
        current.submission_rank_exp = float(request.vars[REPUTATION_SYSTEM_SUBMISSION_RANK_REP_EXP])
    except Exception:
        current.submission_rank_exp = ALGO_DEFAULT_RANK_REP_EXP

    current.reputation_method = request.vars[REPUTATION_SYSTEM_REPUTATION_METHOD]
    if current.reputation_method is None:
        current.reputation_method = ALGO_DEFAULT_REPUTATION_METHOD

    try:
        current.prec_coefficient = float(request.vars[REPUTATION_SYSTEM_PREC_COEFF])
    except Exception:
        current.prec_coefficient = ALGO_DEFAULT_PREC_COEFF

    try:
        current.matrix_D_type = request.vars[REPUTATION_SYSTEM_MATRIX_D_TYPE]
    except Exception:
        current.matrix_D_type = MATRIX_D_TYPE_GRADES_DIST

    current.precision_method = request.vars[REPUTATION_SYSTEM_PREC_METHOD]
    if current.precision_method is None:
        current.precision_method = ALGO_DEFAULT_PREC_METHOD

    # Vancouver.
    current.vancouver_use_median = request.vars[REPUTATION_SYSTEM_USE_MEDIAN] != 'False'
    current.vancouver_do_debias = request.vars[REPUTATION_SYSTEM_DO_DEBIAS] == 'True'
    current.vancouver_use_reputation = request.vars[REPUTATION_SYSTEM_USE_REPUTATION] != 'False'

    logger.info("Reputation system request: %r" % request.vars)
    logger.info("Starting reputation system run for venue: " + c.name)
    logger.info("Requested number of iterations: %d" % current.num_iterations)
    logger.info("Review percentage: %f" % current.review_percentage)
    logger.info("Using algo: %r" % algo)
    logger.info("Run id: %r" % run_id)
    logger.info("Publish: %s" % publish)
    logger.info("Number of iterations: %s" % current.num_iterations)
    logger.info("Pos slope: %r" % current.pos_slope)
    logger.info("Neg slope: %r" % current.neg_slope)
    logger.info("Normalize grades: %r" % current.normalize_grades)
    logger.info("Normalization scale: %r" % current.normalization_scale)
    logger.info("Use submission rank in rep: %r" % current.use_submission_rank_in_rep)
    logger.info("Submission rank exponent for reputation: %r" % current.submission_rank_exp)
    logger.info("Reputation method: %r" % current.reputation_method)
    logger.info("Vancouver use median: %r" % current.vancouver_use_median)
    logger.info("Vancouver do debias: %r" % current.vancouver_do_debias)
    logger.info("Vancouver use reputation: %r" % current.vancouver_use_reputation)
    logger.info("Precision coefficient: %r" % current.prec_coefficient)
    logger.info("Type of matrix D: %r" % current.matrix_D_type)

    # Stores the run parameters.
    db.run_parameters.update_or_insert(
        (db.run_parameters.venue_id == c.id) & (db.run_parameters.run_id == run_id),
        venue_id = c.id,
        run_id = run_id,
        params = json.dumps(request.vars))

    if algo == ALGO_OPT:
        grades_rank.rank_by_grades(c.id, run_id=run_id, publish=publish)
    elif algo == ALGO_VANCOUVER:
        v = vancouver.Vancouver(c.id, run_id=run_id, publish=publish,
                                use_median=current.vancouver_use_median,
                                do_debias=current.vancouver_do_debias)
        v.run_evaluation(use_reputation=current.vancouver_use_reputation)
    else:
        # DEPRECATED
        ranker.run_reputation_system(c.id, num_of_iterations=current.num_iterations,
                                     review_percentage=current.review_percentage,
                                     startover=startover, publish=publish,
                                     run_id=run_id)
    logger.info("Completed reputation system run for venue: " + c.name)
    return redirect(URL('ranking', 'view_grades', args=[c.id]))