text:
class Clock;
class Game_Result;
class Player;

class Move;
class Castle;
class En_Passant;
class Pawn_Promotion;
class Pawn_Double_Move;
class Pawn_Move;

class UCI_Mediator;

//! \brief This class represents the physical chess board.
//!
//! Each instance contains data to track the position of pieces, move history,
//! 3-fold repetition, 50-move draw status, and legal moves.
//!
//! Some abbreviation definitions:
//! - FEN: Forsyth-Edwards Notation: a succinct format for encoding the state of a board in text. (https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation)
//! - PGN: Portable Game Notation: the standard way of recording moves in a game. (https://en.wikipedia.org/wiki/Portable_Game_Notation)
class Board
{
    public:
        //! \brief Constructs a board in the standard starting position.
        Board() noexcept;

        //! \brief Constructs a board according to an FEN string.
        //!
        //! \param fen An text string given in FEN.
        //! \exception std::invalid_argument Thrown if the FEN string does not represent a valid board state.
        explicit Board(const std::string& fen);

        //! \brief Updates the state of the board according to a Player-selected Move.
        //!
        //! \param move A Move-class instance. This must be an item taken from Board::legal_moves().
        //!        The input move is only checked for legality in DEBUG builds, where illegal moves
        //!        will trip an assert. In RELEASE builds, playing an illegal move is undefined,
        //!        resulting in anything from an invalid board state to a crash due to segfault.
        //! \returns Returns a Game_Result indicating the result of the move and whether the game has ended.
        Game_Result play_move(const Move& move) noexcept;

        //! \brief Updates the state of the board according to the text-based move.
        //!
        //! This is equivalent to calling board.play_move(board.interpret_move(move)).
        //! \param move A text string specifying a move in any notation that uniquely identifies a
        //!        legal move (PGN, coordinate, etc.).
        //! \returns A Game_Result indicating the result of the move and whether the game has ended.
        //! \exception Illegal_Move if the text represents an illegal or ambiguous move. The Board is unchanged in this event.
        Game_Result play_move(const std::string& move);

        //! \brief Figure out a move sequence to get from the current board state to the new state given by the parameter.
        //!
        //! \param new_board The new board state to be reached.
        //! \returns A list of moves that will result in the desired board state. An empty list will be returned
        //!          if no sequence of moves (maximum of 2) can be found.
        std::vector<const Move*> derive_moves(const Board& new_board) const noexcept;

        //! \brief Creates a Move instance given a text string representation.
        //!
        //! \param move A string using coordinate notation ("a2b3")
        //!        or [algebraic notation](https://en.wikipedia.org/wiki/Algebraic_notation_(chess)) ("Bb3").
        //! \returns A Move instance corresponding to the input string.
        //! \exception Illegal_Move if the text does not represent a legal move or if the wanted move is ambiguous.
        const Move& interpret_move(const std::string& move) const;

        //! \brief Determine if a text string represents a legal move in the current position.
        //!
        //! \param text The text to examine.
        //! \returns Whether the text is a valid move text.
        bool is_legal_move(const std::string& text) const noexcept;

        //! \brief Tells which player is due to move.
        //!
        //! \returns Color of player who is next to move.
        Piece_Color whose_turn() const noexcept;

        //! \brief Returns the status of the game in FEN.
        //!
        //! \returns A textual representation of the game state.
        //!
        //! This may slightly differ from the output of other programs
        //! in that the en passant target is only listed if there is a
        //! legal en passant move to be made.
        std::string fen() const noexcept;

        //! Print a representation of the board to the command line.
        void cli_print() const noexcept;

        //! \brief Returns the FEN string that was used to create the Board.
        std::string original_fen() const noexcept;

        //! \brief Returns the last move made on this Board
        //!
        //! \returns A pointer representing the last move made.
        const Move* last_move() const noexcept;

        //! \brief The number of plies played on this Board.
        //!
        //! \returns The number of plies (1. e4 e5 is two plies) made on this board since its construction.
        size_t played_ply_count() const noexcept;

        //! \brief The number of plies since the start of the game on this board.
        //!
        //! \returns The number of plies (1. e4 e5 is two plies) on this board including those before the construction of the board.
        //!
        //! The quantity can start as greater than zero if the FEN string used to create the board has
        //! a full-move clock value (the sixth field) of more than 1 or if black is the first to move.
        //! The calculation assumes that every game starts with white's move, even if the FEN string
        //! indicates that black is the first to move, since this would indicate a game state that is
        //! after the start of the game.
        size_t all_ply_count() const noexcept;

        //! \brief The direction (if any) of the castling move made by a player.
        //!
        //! \param player The color of the player being queried.
        //! \returns A number indicating the direction of the castling
        //!          (positive for kingside, negative for queenside, zero
        //!          for no castling yet).
        int castling_direction(Piece_Color player) const noexcept;

        //! \brief Prints the PGN game record with commentary from Players.
        //!
        //! \param game_record_listing A list of Moves. This must be a legal sequence of moves starting from
        //!        the state of the Board at its creation and resulting in the current state of the Board.
        //! \param white Pointer to Player playing white to provide commentary for moves. Can be nullptr.
        //! \param black Pointer to Player playing black to provide commentary for moves. Can be nullptr.
        //! \param file_name Name of the text file where the game will be printed. If empty, print to stdout.
        //! \param result The result of the last action (move, clock punch, or outside intervention) in the game.
        //! \param game_clock The game clock used during the game.
        //! \param event_name The name of the event where the game will take place. May be empty.
        //! \param location The name of the location of the game. May be empty.
        void print_game_record(const std::vector<const Move*>& game_record_listing,
                               const Player& white,
                               const Player& black,
                               const std::string& file_name,
                               const Game_Result& result,
                               const Clock& game_clock,
                               const std::string& event_name,
                               const std::string& location) const noexcept;

        //! \brief Get the piece on the square indicated by coordinates.
        //!
        //! \param square The queried square.
        //! \returns Piece instance on square. May be an invalid Piece if square is emtpy.
        Piece piece_on_square(Square square) const noexcept;

        //! \brief Get a list of all legal moves for the current player.
        //!
        //! \returns A list of pointers to legal moves. Any call to Board::play_move() must take
        //!          its argument from this list.
        const std::vector<const Move*>& legal_moves() const noexcept;

        //! \brief Whether there are no legal moves for the current player.
        //!
        //! This will be true when the current player is checkmated or stalemated.
        bool no_legal_moves() const noexcept;

        //! \brief Whether a square is attacked by a piece of a given color.
        //!
        //! \param target The square under consideration.
        //! \param attacker The color of the piece doing the attacking.
        bool attacked_by(Square target, Piece_Color attacker) const noexcept;

        //! \brief Find out whether the input square is safe for the given king to occupy.
        //!
        //! A square is not safe for the king if the opposing pieces can attack the square.
        //! \param square The queried square.
        //! \param king_color The color of the king piece that is under potential attack.
        //! \returns Whether the king would be in check if it was placed on the square in question.
        bool safe_for_king(Square square, Piece_Color king_color) const noexcept;

        //! \brief Determine if there are any attacks on a square that are blocked by other pieces.
        //!
        //! \param square The queried square.
        //! \param attacking_color The color of the attacking pieces.
        //! \returns Whether there is an attack on the square that is blocked by another piece.
        bool blocked_attack(Square square, Piece_Color attacking_color) const noexcept;

        //! \brief Finds the square on which a king resides.
        //!
        //! \param color Which king to find.
        //! \returns Square which contains the sought after king.
        Square find_king(Piece_Color color) const noexcept;

        //! \brief Find out if the king of the player to move is currently in check.
        //!
        //! \returns If the current player is in check.
        bool king_is_in_check() const noexcept;

        //! \brief Check if a move will leave the player making the move in check.
        //!
        //! \param move A possibly legal move to check.
        //! \returns Whether the move under consideration will leave the friendly king in check.
        bool king_is_in_check_after_move(const Move& move) const noexcept;

        //! \brief Determines if the moving piece will put the king in check after the given move.
        //!
        //! \param move The move that may put the opponent king in check.
        //! \returns Whether the moving piece attacks the king after the move.
        bool move_checks_king(const Move& move) const noexcept;

        //! \brief Determine whether a piece would be pinned to the king by an opposing piece if it was on the given square.
        //!
        //! \param square The queried square.
        //! \returns Whether there is an opposing piece (of color opposite(Board::whose_turn()))
        //!          that would pin a piece occupying the queried square to its king. For example,
        //!          if it is white's turn, is there is a black piece that would pin a (possibly non-
        //!          existant) white piece on the given square to the white king?
        bool piece_is_pinned(Square square) const noexcept;

        //! \brief Checks whether there are enough pieces on the board for any possible checkmate.
        //!
        //! The following piece sets on the board make checkmate possible:
        //! - Any single pawn, rook, or queen,
        //! - At least two bishops (of any color) on oppositely colored squares,
        //! - A bishop and knight (of an piece color or square color combination),
        //! - Two knights (of any piece color or square color combination).
        //! \param color The player color of the pieces to check.
        //! \returns If there are enough pieces on the board on one side to make a checkmate arrangement.
        bool enough_material_to_checkmate(Piece_Color color) const noexcept;

        //! \brief Checks whether there are enough pieces on the board for any possible checkmate.
        //!
        //! The following piece sets on the board make checkmate possible:
        //! - Any single pawn, rook, or queen,
        //! - At least two bishops (of any color) on oppositely colored squares,
        //! - A bishop and knight (of an piece color or square color combination),
        //! - Two knights (of any piece color or square color combination).
        //! \returns If there are enough pieces on the board to make a checkmate arrangement.
        //!          If the method returns false, this will usually lead to a drawn game.
        bool enough_material_to_checkmate() const noexcept;

        //! \brief Check if castling is legal for the given player color and direction.
        //!
        //! \param color The color of the player.
        //! \param direction The direction of castling: Direction::LEFT for queenside and Direction::RIGHT for kingside.
        //! \returns Whether the castling move is legal for the player.
        bool castle_is_legal(Piece_Color color, Direction direction) const noexcept;

        //! \brief Determines whether a move will capture on the current board.
        //!
        //! \param move Move to check.
        //! \returns If the move captures an opponent's piece.
        //! \exception assertion_failure In DEBUG builds, if the move to check is not legal, an assert fails.
        bool move_captures(const Move& move) const noexcept;

        //! \brief Determines whether a move will change the material on the current board.
        //!
        //! \param move Move to check.
        //! \returns If the move captures an opponent's piece or promotes a pawn.
        //! \exception assertion_failure In DEBUG builds, if the move to check is not legal, an assert fails.
        bool move_changes_material(const Move& move) const noexcept;

        //! \brief Number of moves since the last pawn move or capturing move.
        //!
        //! If this count reaches 100 (50 moves on each side), the game ends in
        //! a draw.
        size_t moves_since_pawn_or_capture() const noexcept;

        //! \brief Counts the number of times the current board position has been seen in the last few plies.
        //!
        //! \param depth The number of plies to look back for equivalent positions.
        std::ptrdiff_t repeat_count_from_depth(size_t depth) const noexcept;

        //! \brief Returns the Zobrist hash of the current state of the board.
        //!
        //! See https://en.wikipedia.org/wiki/Zobrist_hashing for details.
        uint64_t board_hash() const noexcept;

        //! \brief Returns whether the specified player has castled.
        //!
        //! \param player The color of the player being queried.
        bool player_castled(Piece_Color player) const noexcept;

        //! \brief Gets the ply move during which a player castled.
        //!
        //! \param player The color of the player being queried.
        //! \returns The ply count when the player castled, or MAX(size_t) if the player has not castled.
        size_t castling_move_index(Piece_Color player) const noexcept;

        //! \brief Create a copy of the board with a random pawn removed.
        //!
        //! This can be used by a Player to calibrate the value of a centipawn.
        //! \exception Debug assertion failure if there are no pawns on the board.
        Board without_random_pawn() const noexcept;

        //! \brief Returns a list of moves that results in a quiescent version of the board.
        //!
        //! This list is created by performing all possible captures on
        //! the ending square of the last move. If multiple captures are
        //! possible, the weakest pieces goes first according to the piece
        //! values array.
        //! \param piece_values An array indexed by Piece::type() that gives
        //!        the value of the piece.
        std::vector<const Move*> quiescent(const std::array<double, 6>& piece_values) const noexcept;

        //! \brief Print data on why boards have different Zobrist hashes
        //!
        //! \param other The other board with which to compare.
        void compare_hashes(const Board& other) const noexcept;

    private:
        std::array<Piece, 64> board;
        Fixed_Capacity_Vector<uint64_t, 101> repeat_count;
        Piece_Color turn_color = Piece_Color::WHITE;
        size_t game_move_count = 0;
        const Move* previous_move = nullptr;
        std::array<std::array<bool, 2>, 2> legal_castles{}; // indexed by [Piece_Color][Direction]
        Square en_passant_target;
        Square unused_en_passant_target;
        uint64_t starting_hash{};
        std::array<Square, 2> king_location;
        Square checking_square;
        size_t plies_at_construction;

        // Stores the moves that attack a square. The innermost array
        // is filled with bools indicating the direction the piece attacking
        // the square moves to reach that square: (from white's perspective)
        // up, down, left, right, up-left, up-right, down-left, down-right,
        // 2x1 up-left, 1x2 up-left, 2x1 up-right, 1x2 up-right,
        // 2x1 down-left, 1x2 down-left, 2x1 down-right, 1x2 down-right
        std::array<std::array<std::bitset<16>, 64>, 2> potential_attacks{}; // indexed by [attacker color][square index];
        std::array<std::array<std::bitset<16>, 64>, 2> blocked_attacks{};

        void add_attacks_from(Square square, Piece piece) noexcept;
        void remove_attacks_from(Square square, Piece old_piece) noexcept;
        void modify_attacks(Square square, Piece piece, bool adding_attacks) noexcept;
        void update_blocks(Square square, Piece old_piece, Piece new_piece) noexcept;
        std::bitset<16> moves_attacking_square(Square square, Piece_Color attacking_color) const noexcept;
        std::bitset<16> checking_moves() const noexcept;
        Square find_checking_square() const noexcept;

        // Information cache for gene reference
        std::array<size_t, 2> castling_index{size_t(-1), size_t(-1)};
        std::array<int, 2> castling_movement{0, 0};

        // Caches
        std::vector<const Move*> legal_moves_cache;
        void recreate_move_caches() noexcept;

        Piece& piece_on_square(Square square) noexcept;
        void remove_piece(Square square) noexcept;
        void move_piece(const Move& move) noexcept;
        void make_en_passant_targetable(Square square) noexcept;
        void clear_en_passant_target() noexcept;
        bool is_en_passant_targetable(Square square) const noexcept;
        void disable_en_passant_target() noexcept;
        bool is_in_legal_moves_list(const Move& move) const noexcept;
        void place_piece(Piece piece, Square square) noexcept;
        void record_king_location(Piece_Color color, Square square);
        bool all_empty_between(Square start, Square end) const noexcept;
        void update_board(const Move& move) noexcept;
        void switch_turn() noexcept;
        Game_Result move_result() const noexcept;
        void make_castle_legal(Piece_Color color, Direction direction) noexcept;
        void make_castle_illegal(Piece_Color color, Direction direction) noexcept;

        // Track threefold repetition and fifty-move rule
        void add_board_position_to_repeat_record() noexcept;
        void add_to_repeat_count(uint64_t new_hash) noexcept;
        ptrdiff_t current_board_position_repeat_count() const noexcept;
        void clear_repeat_count() noexcept;

        // Zobrist hashing (implementation of threefold/fifty-move tracking)
        uint64_t current_board_hash = 0;

        void update_board_hash(Square square) noexcept;
        uint64_t square_hash(Square square) const noexcept;
        void update_whose_turn_hash() noexcept;

        bool king_multiply_checked() const noexcept;

        static void fen_parse_assert(bool assertion, const std::string& input_fen, const std::string& failure_message);

        // Moves with side effects are friends of Board
        friend class Castle; // moves second piece
        friend class En_Passant; // capture piece on another square
        friend class Pawn_Promotion; // replace piece
        friend class Pawn_Double_Move; // mark square as En Passant target
        friend class Pawn_Move; // reset three-fold and 50-move counts

        // Allow UCI_Mediator to change the legal moves with searchmoves command
        friend class UCI_Mediator;
};

#endif // BOARD_H


text:
import * as React from 'react';
import { IconBaseProps } from 'react-icon-base';
export default class MdOpenInBrowser extends React.Component<IconBaseProps, any> { }

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<PlgElasticReportDictionaries>
  <Dictionary key="Scada.Web.Plugins.ElasticReport.Config.ElasticRepConfig">
    <Phrase key="LoadConfigError">Erro ao carregar a configuração de relatório elástico</Phrase>
    <Phrase key="UnableReceiveConfig">Não foi possível receber a configuração elástica do relatório.</Phrase>
    <Phrase key="ConfigMissing">A configuração está ausente no XML.</Phrase>
    <Phrase key="SectionIdMissing">O ID da seção está ausente.</Phrase>
    <Phrase key="SectionIdDuplicated">O ID da seção está duplicado.</Phrase>
  </Dictionary>
  <Dictionary key="Scada.Web.Plugins.ElasticReport.Model.Builder">
    <Phrase key="WorkPeriod">Período de trabalho: </Phrase>
    <Phrase key="Generated">Gerado: </Phrase>
    <Phrase key="GenerateSectionError">Erro ao gerar seção com ID "{0}"</Phrase>
    <Phrase key="CellNotSupported">N/a</Phrase>
    <Phrase key="IncorrectColumnIndex">Índice de coluna incorreto</Phrase>
    <Phrase key="DateCell">Encontro</Phrase>
    <Phrase key="TimeCell">Tempo</Phrase>
    <Phrase key="CaptionCell">Nome</Phrase>
    <Phrase key="TotalCell">Total</Phrase>
    <Phrase key="AvgCell">Média</Phrase>
  </Dictionary>
  <Dictionary key="Scada.Web.Plugins.ElasticReport.ElasticRepPdfBuilder">
    <Phrase key="FontNotFoundError">Pelo menos um dos seguintes arquivos de fonte não encontrado:</Phrase>
  </Dictionary>
  <Dictionary key="Scada.Web.Plugins.ElasticReport.PdfStyles">
    <Phrase key="LoadPdfStylesError">Erro ao carregar estilos de documento PDF</Phrase>
    <Phrase key="LoadPdfStyleError">Erro ao carregar o estilo "{0}"</Phrase>
  </Dictionary>
  <Dictionary key="Scada.Web.Plugins.ElasticReport.WFrmElasticRep">
    <Phrase key="this">Relatório elástico - Rapid SCADA</Phrase>
    <Phrase key="lblTitle">Relatório elástico</Phrase>
    <Phrase key="lblDateFrom">De</Phrase>
    <Phrase key="lblDateTo">À</Phrase>
    <Phrase key="lblMonthFrom">De</Phrase>
    <Phrase key="lblMonthTo">À</Phrase>
    <Phrase key="lblFormat">Formato de saída:</Phrase>
    <Phrase key="lblExcelFormat">Excel</Phrase>
    <Phrase key="lblPdfFormat">PDF</Phrase>
    <Phrase key="lblHtmlFormat">HTML</Phrase>
    <Phrase key="btnGenReport">Obter relatório</Phrase>
    <Phrase key="lblGenStarted">Gerando o relatório. Por favor, espere...</Phrase>
  </Dictionary>
  <Dictionary key="Scada.Web.Plugins.ElasticReport.WFrmElasticRepHtmlOut">
    <Phrase key="btnClose">Fechar</Phrase>
  </Dictionary>
</PlgElasticReportDictionaries>


text:
namespace v8 {
namespace base {

namespace {

void (*g_print_stack_trace)() = nullptr;

}  // namespace

void SetPrintStackTrace(void (*print_stack_trace)()) {
  g_print_stack_trace = print_stack_trace;
}

// Explicit instantiations for commonly used comparisons.
#define DEFINE_MAKE_CHECK_OP_STRING(type) \
  template std::string* MakeCheckOpString<type, type>(type, type, char const*);
DEFINE_MAKE_CHECK_OP_STRING(int)
DEFINE_MAKE_CHECK_OP_STRING(long)       // NOLINT(runtime/int)
DEFINE_MAKE_CHECK_OP_STRING(long long)  // NOLINT(runtime/int)
DEFINE_MAKE_CHECK_OP_STRING(unsigned int)
DEFINE_MAKE_CHECK_OP_STRING(unsigned long)       // NOLINT(runtime/int)
DEFINE_MAKE_CHECK_OP_STRING(unsigned long long)  // NOLINT(runtime/int)
DEFINE_MAKE_CHECK_OP_STRING(char const*)
DEFINE_MAKE_CHECK_OP_STRING(void const*)
#undef DEFINE_MAKE_CHECK_OP_STRING

// Explicit instantiations for floating point checks.
#define DEFINE_CHECK_OP_IMPL(NAME)                                            \
  template std::string* Check##NAME##Impl<float, float>(float lhs, float rhs, \
                                                        char const* msg);     \
  template std::string* Check##NAME##Impl<double, double>(                    \
      double lhs, double rhs, char const* msg);
DEFINE_CHECK_OP_IMPL(EQ)
DEFINE_CHECK_OP_IMPL(NE)
DEFINE_CHECK_OP_IMPL(LE)
DEFINE_CHECK_OP_IMPL(LT)
DEFINE_CHECK_OP_IMPL(GE)
DEFINE_CHECK_OP_IMPL(GT)
#undef DEFINE_CHECK_OP_IMPL

}  // namespace base
}  // namespace v8

// Contains protection against recursive calls (faults while handling faults).
extern "C" void V8_Fatal(const char* file, int line, const char* format, ...) {
  fflush(stdout);
  fflush(stderr);
  v8::base::OS::PrintError("\n\n#\n# Fatal error in %s, line %d\n# ", file,
                           line);
  va_list arguments;
  va_start(arguments, format);
  v8::base::OS::VPrintError(format, arguments);
  va_end(arguments);
  v8::base::OS::PrintError("\n#\n");

  if (v8::base::g_print_stack_trace) v8::base::g_print_stack_trace();

  fflush(stderr);
  v8::base::OS::Abort();
}


text: from sensors import *


text:
// Copyright 2004-present Facebook. All Rights Reserved.

#pragma once

#include <map>
#include "rsocket/Payload.h"
#include "yarpl/Flowable.h"
#include "yarpl/Single.h"

namespace rsocket {
namespace tck {

class MarbleProcessor {
 public:
  explicit MarbleProcessor(const std::string /* marble */);

  std::tuple<int64_t, bool> run(
      std::shared_ptr<yarpl::flowable::Subscriber<rsocket::Payload>>
          subscriber,
      int64_t requested);

  void run(std::shared_ptr<yarpl::single::SingleObserver<rsocket::Payload>>
               subscriber);

 private:
  std::string marble_;

  // Stores a mapping from marble character to Payload (data, metadata)
  std::map<std::string, std::pair<std::string, std::string>> argMap_;

  // Keeps an account of how many messages can be sent.  This could be done
  // with Allowance
  std::atomic<size_t> canSend_{0};

  size_t index_{0};
};

} // tck
} // reactivesocket


text:
<?php

namespace Versionable\Prospect\Adapter;

abstract class AdapterAbstract
{
  protected $options = array();

  public function setOption($name, $value)
  {
    $this->options[$name] = $value;
  }
}


text:
<?php

namespace CodrPress\Admin\Controller;

use CodrPress\Helper\AuthHelper;
use CodrPress\Model\Post;
use Silex\Application;
use Silex\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request;

class PostController implements ControllerProviderInterface
{
    public function connect(Application $app)
    {
        $router = $app['controllers_factory'];
        $validateIdRegex = '[a-z0-9]{24}';
        $app['config']->set('codrpress.views.activeNavItem', 'posts');
        $authHelper = new AuthHelper();
        $authHelper->registerAuthErrorHandler($app);
        $login = $authHelper->getAuthCallable($app);

        $sanitize = function ($id) use ($app) {
            return $app['config']->sanitize($id);
        };

        $router->get('/admin/posts', function() use ($app) {
            return $app['twig']->render('admin/posts.haml', [
                'posts' => Post::where()->sort(['created_at' => -1])
            ]);
        })
            ->bind('admin_posts')
            ->before($login);

        $router->get('/admin/post/new', function() use ($app) {
            return $app['twig']->render('admin/post.haml', [
                'post' => new Post()
            ]);
        })
            ->bind('admin_post_new')
            ->before($login);

        $router->get('/admin/post/{id}', function($id) use ($app) {
            return $app['twig']->render('admin/post.haml', [
                'post' => Post::find($id)->first()
            ]);
        })
            ->assert('id', $validateIdRegex)
            ->convert('id', $sanitize)
            ->bind('admin_post')
            ->before($login);

        $router->post('/admin/post', function(Request $request) use($app) {
            $data = $request->request->get('post');
            $post = new Post($data);
            $post->store();

            return $app->redirect($app['url_generator']->generate('admin_posts'));
        })
            ->bind('admin_post_add')
            ->before($login);

        $router->post('/admin/post/{id}', function(Request $request, $id) use($app) {
            $data = $request->request->get('post');
            $post = Post::find($id)->first();

            $post->update($data);
            $post->store();

            return $app->redirect($app['url_generator']->generate('admin_posts'));
        })
            ->assert('id', $validateIdRegex)
            ->convert('id', $sanitize)
            ->bind('admin_post_edit')
            ->before($login);

        return $router;
    }
}


text:
namespace clang { class MacroDirective; }
namespace csabase { class Visitor; }

using namespace csabase;
using namespace clang;

// ----------------------------------------------------------------------------

static std::string const check_name("leaking-macro");

// ----------------------------------------------------------------------------

namespace
{
    struct leaking_macro
    {
        typedef std::map<std::string, SourceLocation> map_type;
        std::stack<map_type> d_macros;
        leaking_macro()
        {
            d_macros.push(map_type());
        }
    };
}

// ----------------------------------------------------------------------------

static void onOpenFile(Analyser* analyser,
                       SourceLocation location,
                       std::string const& current,
                       std::string const& opened)
{
    leaking_macro& context(analyser->attachment<leaking_macro>());
    context.d_macros.push(leaking_macro::map_type());
}

// ----------------------------------------------------------------------------

static void onCloseFile(Analyser* analyser,
                        SourceLocation location,
                        std::string const& current,
                        std::string const& closed)
{
    SourceManager& m = analyser->manager();
    if (location.isValid() && m.getMainFileID() == m.getFileID(location)) {
        return;                                                       // RETURN
    }

    FileName fn(closed);
    std::string component = llvm::StringRef(fn.component()).upper();

    leaking_macro& context(analyser->attachment<leaking_macro>());
    for (const auto& macro : context.d_macros.top()) {
        Location where(analyser->get_location(macro.second));
        if (   analyser->is_header(where.file())
            && macro.first.find("INCLUDED_") != 0
            && (   analyser->is_component_header(macro.second)
                || macro.first.size() < 4)
            && llvm::StringRef(macro.first).upper().find(component) != 0
            )
        {
            analyser->report(macro.second, check_name, "SLM01",
                             "Macro definition '%0' leaks from header")
                << macro.first;
        }
    }
    context.d_macros.pop();
}

// ----------------------------------------------------------------------------

static void onMacroDefined(Analyser* analyser,
                           Token const& token,
                           MacroDirective const* info)
{
    leaking_macro& context(analyser->attachment<leaking_macro>());
    std::string source(token.getIdentifierInfo()->getNameStart());
    context.d_macros.top().insert(std::make_pair(source, token.getLocation()));
}

static void onMacroUndefined(Analyser* analyser,
                             Token const& token,
                             MacroDirective const* info)
{
    leaking_macro& context(analyser->attachment<leaking_macro>());
    std::string source(token.getIdentifierInfo()->getNameStart());
    context.d_macros.top().erase(source);
}

static void onTranslationUnitDone(Analyser* analyser)
{
    SourceManager& m = analyser->manager();
    onCloseFile(analyser,
                SourceLocation(),
                "",
                m.getFilename(m.getLocForStartOfFile(m.getMainFileID())));
}

// ----------------------------------------------------------------------------

static void subscribe(Analyser& analyser, Visitor&, PPObserver& observer)
{
    observer.onOpenFile            += bind(&analyser, &onOpenFile);
    observer.onCloseFile           += bind(&analyser, &onCloseFile);
    observer.onMacroDefined        += bind(&analyser, &onMacroDefined);
    observer.onMacroUndefined      += bind(&analyser, &onMacroUndefined);
    analyser.onTranslationUnitDone += bind(&analyser, &onTranslationUnitDone);
}

// ----------------------------------------------------------------------------

static RegisterCheck register_observer(check_name, &subscribe);

// ----------------------------------------------------------------------------
// Copyright (C) 2014 Bloomberg Finance L.P.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------- END-OF-FILE ----------------------------------


text:
package mil.nga.giat.geowave.analytic;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import mil.nga.giat.geowave.adapter.vector.FeatureDataAdapter;
import mil.nga.giat.geowave.analytic.distance.DistanceFn;
import mil.nga.giat.geowave.analytic.distance.FeatureCentroidDistanceFn;
import mil.nga.giat.geowave.core.geotime.IndexType;
import mil.nga.giat.geowave.core.store.DataStore;
import mil.nga.giat.geowave.core.store.index.Index;
import mil.nga.giat.geowave.datastore.accumulo.AccumuloDataStore;
import mil.nga.giat.geowave.datastore.accumulo.BasicAccumuloOperations;

import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.ZooKeeperInstance;
import org.apache.accumulo.core.client.security.tokens.PasswordToken;
import org.apache.commons.lang3.tuple.Pair;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.feature.type.GeometryDescriptor;
import org.opengis.feature.type.GeometryType;
import org.opengis.referencing.cs.CoordinateSystem;
import org.opengis.referencing.cs.CoordinateSystemAxis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;

/**
 * Generate clusters of geometries.
 *
 */
public class GeometryDataSetGenerator
{
	final static Logger LOGGER = LoggerFactory.getLogger(GeometryDataSetGenerator.class);
	private final Random rand = new Random();
	private final GeometryFactory geoFactory = new GeometryFactory();
	private final DistanceFn<SimpleFeature> distanceFunction;
	private final SimpleFeatureBuilder builder;
	// coordinate system boundaries
	private SimpleFeature minFeature;
	private double[] minAxis;
	private double[] maxAxis;
	private CoordinateSystem coordSystem;
	private boolean includePolygons = true;

	public GeometryDataSetGenerator(
			final DistanceFn<SimpleFeature> distanceFunction,
			final SimpleFeatureBuilder builder ) {
		super();
		this.distanceFunction = distanceFunction;
		this.builder = builder;
		init();
	}

	public boolean isIncludePolygons() {
		return includePolygons;
	}

	public void setIncludePolygons(
			boolean includePolygons ) {
		this.includePolygons = includePolygons;
	}

	public SimpleFeature getCorner() {
		return minFeature;
	}

	public Geometry getBoundingRegion() {
		final int adder[] = {
			1,
			2,
			-1,
			2
		};
		int num = 0;
		int addCnt = 0;
		final int dims = coordSystem.getDimension();
		final int coords = (int) Math.pow(
				dims,
				2);

		final Coordinate[] coordinates = new Coordinate[coords + 1];
		for (int i = 0; i < coords; i++) {
			coordinates[i] = new Coordinate();
			for (int j = 0; j < dims; j++) {
				final boolean isMin = ((num >> j) % 2) == 0;
				coordinates[i].setOrdinate(
						j,
						isMin ? minAxis[j] : maxAxis[j]);
			}
			num += adder[addCnt];
			addCnt = (addCnt + 1) % 4;
		}
		coordinates[coords] = coordinates[0];
		return geoFactory.createPolygon(coordinates);
	}

	/**
	 * Calculate the range for the given bounds
	 *
	 * @param factor
	 * @param minAxis
	 * @param maxAxis
	 * @return
	 */
	private double[] createRange(
			final double factor,
			final double[] minAxis,
			final double[] maxAxis ) {
		final double range[] = new double[minAxis.length];
		for (int i = 0; i < minAxis.length; i++) {
			range[i] = (maxAxis[i] - minAxis[i]) * factor;
		}
		return range;
	}

	/**
	 * Pick a random grid cell and supply the boundary. The grid is determined
	 * by the parameter,which provides a percentage of distance over the total
	 * range for each cell.
	 *
	 * @param minCenterDistanceFactor
	 * @return
	 */
	private Pair<double[], double[]> gridCellBounds(
			final double minCenterDistanceFactor,
			final double[] minAxis,
			final double[] maxAxis ) {
		final double range[] = createRange(
				1.0,
				minAxis,
				maxAxis);
		final double min[] = new double[range.length];
		final double max[] = new double[range.length];
		for (int i = 0; i < range.length; i++) {
			min[i] = Math.max(
					minAxis[i] + (minCenterDistanceFactor * (rand.nextInt(Integer.MAX_VALUE) % (range[i] / minCenterDistanceFactor))),
					minAxis[i]);
			max[i] = Math.min(
					min[i] + (minCenterDistanceFactor * range[i]),
					maxAxis[i]);
		}
		return Pair.of(
				min,
				max);
	}

	public void writeToGeoWave(
			final String zookeeper,
			final String instance,
			final String user,
			final String password,
			final String namespace,
			final List<SimpleFeature> featureData )
			throws IOException {
		final Instance zookeeperInstance = new ZooKeeperInstance(
				instance,
				zookeeper);
		try {
			final Connector accumuloConnector = zookeeperInstance.getConnector(
					user,
					new PasswordToken(
							password));

			final DataStore dataStore = new AccumuloDataStore(
					new BasicAccumuloOperations(
							accumuloConnector,
							namespace));
			final Index index = IndexType.SPATIAL_VECTOR.createDefaultIndex();
			final FeatureDataAdapter adapter = new FeatureDataAdapter(
					featureData.get(
							0).getFeatureType());
			final SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(
					featureData.get(
							0).getFeatureType());

			LOGGER.info("Accumulo " + zookeeper + " instance " + instance + " namespace " + namespace);
			LOGGER.info("Writing " + featureData.size() + " records to " + adapter.getType().getTypeName());
			Integer idCounter = 0;
			for (final SimpleFeature feature : featureData) {

				dataStore.ingest(
						adapter,
						index,
						feature);
				featureBuilder.reset();

				idCounter++;
			}

		}
		catch (AccumuloException | AccumuloSecurityException e) {
			throw new IOException(
					"Cannot write to " + instance,
					e);
		}
	}

	public List<SimpleFeature> generatePointSet(
			final double minCenterDistanceFactor,
			final double outlierFactor,
			final int numberOfCenters,
			final int minSetSize ) {
		return this.generatePointSet(
				minCenterDistanceFactor,
				outlierFactor,
				numberOfCenters,
				minSetSize,
				minAxis,
				maxAxis);
	}

	public List<SimpleFeature> generatePointSet(
			final double minCenterDistanceFactor,
			final double outlierFactor,
			final int numberOfCenters,
			final int minSetSize,
			final double minAxis[],
			final double maxAxis[] ) {

		final List<SimpleFeature> pointSet = new ArrayList<SimpleFeature>();
		final List<double[]> minForCenter = new ArrayList<double[]>();
		final List<double[]> maxForCenter = new ArrayList<double[]>();
		final double range[] = createRange(
				minCenterDistanceFactor,
				minAxis,
				maxAxis);
		if (numberOfCenters >= minSetSize) {
			LOGGER.error("The number of centers passed much be less than the minimum set size");
			throw new IllegalArgumentException(
					"The number of centers passed much be less than the minimum set size");
		}

		final double minDistance = computeMinDistance(
				minCenterDistanceFactor,
				minAxis,
				maxAxis);

		/**
		 * Pick the initial centers which have minimum distance from each other.
		 *
		 */
		while (pointSet.size() < numberOfCenters) {

			final Pair<double[], double[]> axis = gridCellBounds(
					minCenterDistanceFactor,
					minAxis,
					maxAxis);

			final SimpleFeature nextFeature = createNewFeature(
					axis.getLeft(),
					axis.getRight());
			if (isFarEnough(
					nextFeature,
					pointSet,
					minDistance)) {
				pointSet.add(nextFeature);
			}
		}

		/**
		 * Calculate the boundaries around each center point to place additional
		 * points, thus creating clusters
		 */
		for (final SimpleFeature center : pointSet) {
			final double[] centerMinAxis = new double[coordSystem.getDimension()];
			final double[] centerMaxAxis = new double[coordSystem.getDimension()];
			final Geometry geo = (Geometry) center.getDefaultGeometry();
			final Coordinate centerCoord = geo.getCentroid().getCoordinate();
			for (int i = 0; i < centerMinAxis.length; i++) {
				centerMinAxis[i] = centerCoord.getOrdinate(i) - (range[i] / 2.0);
				centerMaxAxis[i] = centerCoord.getOrdinate(i) + (range[i] / 2.0);
			}
			minForCenter.add(centerMinAxis);
			maxForCenter.add(centerMaxAxis);
		}

		/*
		 * Pick a random center point and add a new geometry with the bounding
		 * range around that point.
		 */
		final int clusterdItemsCount = (int) Math.ceil((minSetSize) * (1.0 - outlierFactor));
		while (pointSet.size() < clusterdItemsCount) {
			final int centerPos = rand.nextInt(Integer.MAX_VALUE) % minForCenter.size();

			pointSet.add(createNewFeature(
					minForCenter.get(centerPos),
					maxForCenter.get(centerPos)));
		}

		/**
		 * Add random points as potential outliers (no guarantees)
		 */
		while (pointSet.size() < minSetSize) {
			pointSet.add(createNewFeature(
					minAxis,
					maxAxis));
		}
		return pointSet;
	}

	public List<SimpleFeature> addRandomNoisePoints(
			List<SimpleFeature> pointSet,
			final int minSetSize,
			final double minAxis[],
			final double maxAxis[] ) {
		while (pointSet.size() < minSetSize) {
			pointSet.add(createNewFeature(
					minAxis,
					maxAxis));
		}
		return pointSet;
	}

	private void init() {
		final GeometryDescriptor geoDescriptor = builder.getFeatureType().getGeometryDescriptor();
		coordSystem = geoDescriptor.getType().getCoordinateReferenceSystem().getCoordinateSystem();

		minAxis = new double[coordSystem.getDimension()];
		maxAxis = new double[coordSystem.getDimension()];
		for (int i = 0; i < coordSystem.getDimension(); i++) {
			final CoordinateSystemAxis axis = coordSystem.getAxis(i);
			minAxis[i] = axis.getMinimumValue();
			maxAxis[i] = axis.getMaximumValue();
		}
		final int dims = coordSystem.getDimension();

		final Coordinate coordinate = new Coordinate();
		for (int i = 0; i < dims; i++) {
			coordinate.setOrdinate(
					i,
					minAxis[i]);
		}
		minFeature = createFeatureWithGeometry(geoFactory.createPoint(coordinate));

	}

	private boolean isFarEnough(
			final SimpleFeature feature,
			final List<SimpleFeature> set,
			final double minDistance ) {
		for (final SimpleFeature setItem : set) {
			if (distanceFunction.measure(
					feature,
					setItem) < minDistance) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Find the distance maximum distance of the entire space and multiply that
	 * by the distance factor to determine a minimum distance each initial
	 * center point occurs from each other.
	 *
	 * @param minCenterDistanceFactor
	 * @return
	 */
	private double computeMinDistance(
			final double minCenterDistanceFactor,
			final double minAxis[],
			final double maxAxis[] ) {
		assert (minCenterDistanceFactor > 0.001);
		assert (minCenterDistanceFactor < 0.75);

		final int dims = coordSystem.getDimension();

		Coordinate coordinate = new Coordinate();
		for (int i = 0; i < dims; i++) {
			coordinate.setOrdinate(
					i,
					minAxis[i]);
		}
		final SimpleFeature minFeature = createFeatureWithGeometry(geoFactory.createPoint(coordinate));

		coordinate = new Coordinate();
		for (int i = 0; i < dims; i++) {
			coordinate.setOrdinate(
					i,
					maxAxis[i]);
		}

		final SimpleFeature maxFeature = createFeatureWithGeometry(geoFactory.createPoint(coordinate));

		return minCenterDistanceFactor * distanceFunction.measure(
				minFeature,
				maxFeature);
	}

	private SimpleFeature createNewFeature(
			final double minAxis[],
			final double maxAxis[] ) {

		final int dims = coordSystem.getDimension();

		final int shapeSize = includePolygons ? (rand.nextInt(Integer.MAX_VALUE) % 5) + 1 : 1;
		final Coordinate[] shape = new Coordinate[shapeSize > 2 ? shapeSize + 1 : shapeSize];
		final double[] constrainedMaxAxis = Arrays.copyOf(
				maxAxis,
				maxAxis.length);
		final double[] constrainedMinAxis = Arrays.copyOf(
				minAxis,
				minAxis.length);
		for (int s = 0; s < shapeSize; s++) {
			final Coordinate coordinate = new Coordinate();
			for (int i = 0; i < dims; i++) {
				coordinate.setOrdinate(
						i,
						constrainedMinAxis[i] + (rand.nextDouble() * (constrainedMaxAxis[i] - constrainedMinAxis[i])));
			}
			shape[s] = coordinate;
			if (s == 0) {
				constrain(
						coordinate,
						constrainedMaxAxis,
						constrainedMinAxis);
			}
		}
		if (shapeSize > 2) {
			shape[shapeSize] = shape[0];
			return createFeatureWithGeometry(geoFactory.createLinearRing(
					shape).convexHull());
		}
		else if (shapeSize == 2) {
			return createFeatureWithGeometry(geoFactory.createLineString(shape));
		}
		else {
			return createFeatureWithGeometry(geoFactory.createPoint(shape[0]));
		}
	}

	/**
	 * Change the constrain min and max to center around the coordinate to keep
	 * the polygons tight.
	 *
	 * @param coordinate
	 * @param constrainedMaxAxis
	 * @param constrainedMinAxis
	 */
	private void constrain(
			final Coordinate coordinate,
			final double[] constrainedMaxAxis,
			final double[] constrainedMinAxis ) {
		for (int i = 0; i < constrainedMaxAxis.length; i++) {
			final double range = (constrainedMaxAxis[i] - constrainedMinAxis[i]) * 0.001;
			constrainedMaxAxis[i] = Math.min(
					coordinate.getOrdinate(i) + range,
					constrainedMaxAxis[i]);
			constrainedMinAxis[i] = Math.max(
					coordinate.getOrdinate(i) - range,
					constrainedMinAxis[i]);
		}
	}

	private SimpleFeature createFeatureWithGeometry(
			final Geometry geometry ) {
		final Object values[] = new Object[builder.getFeatureType().getAttributeCount()];
		for (int i = 0; i < values.length; i++) {
			final AttributeDescriptor desc = builder.getFeatureType().getDescriptor(
					i);
			if (desc.getType() instanceof GeometryType) {
				values[i] = geometry;
			}
			else {
				final Class<?> binding = desc.getType().getBinding();
				if (String.class.isAssignableFrom(binding)) {
					values[i] = UUID.randomUUID().toString();
				}
			}
		}
		return builder.buildFeature(
				UUID.randomUUID().toString(),
				values);

	}

	public static void main(
			final String args[] )
			throws IOException {
		final GeometryDataSetGenerator dataGenerator = new GeometryDataSetGenerator(
				new FeatureCentroidDistanceFn(),
				getBuilder(args[5]));
		final String zookeeper = args[0].trim();
		final String instance = args[1].trim();
		final String user = args[2];
		final String password = args[3];
		final String namespace = args[4].trim();
		dataGenerator.writeToGeoWave(
				zookeeper,
				instance,
				user,
				password,
				namespace,
				dataGenerator.generatePointSet(
						0.2,
						0.2,
						5,
						5000,
						new double[] {
							-100,
							-45
						},
						new double[] {
							-90,
							-35
						}));
		dataGenerator.writeToGeoWave(
				zookeeper,
				instance,
				user,
				password,
				namespace,
				dataGenerator.generatePointSet(
						0.2,
						0.2,
						7,
						5000,
						new double[] {
							0,
							0
						},
						new double[] {
							10,
							10
						}));
		dataGenerator.writeToGeoWave(
				zookeeper,
				instance,
				user,
				password,
				namespace,
				dataGenerator.addRandomNoisePoints(
						dataGenerator.generatePointSet(
								0.2,
								0.2,
								6,
								5000,
								new double[] {
									65,
									35
								},
								new double[] {
									75,
									45
								}),
						6000,
						new double[] {
							-90,
							-90
						},
						new double[] {
							90,
							90
						}));
	}

	private static SimpleFeatureBuilder getBuilder(
			String name ) {
		final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
		typeBuilder.setName(name);
		typeBuilder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate
														// reference
		// add attributes in order
		typeBuilder.add(
				"geom",
				Geometry.class);
		typeBuilder.add(
				"name",
				String.class);
		typeBuilder.add(
				"count",
				Long.class);

		// build the type
		return new SimpleFeatureBuilder(
				typeBuilder.buildFeatureType());
	}
}


text:
package tianma.ss.spider.http;

import org.apache.http.client.CookieStore;

/**
 * This class used for manage the CookieStore
 *
 * @author Tianma
 *
 */
public final class CookieStoreManager {
	private ThreadLocal<CookieStore> threadLocal;

	private CookieStoreManager() {
		threadLocal = new ThreadLocal<CookieStore>();
	}

	public synchronized CookieStore getCookieStore() {
		return threadLocal.get();
	}

	public synchronized void setCookieStore(CookieStore cookieStore) {
		if (cookieStore != null)
			threadLocal.set(cookieStore);
	}

	public static final CookieStoreManager getInstance() {
		return CookieStoreManagerHolder.sInstance;
	}

	private static class CookieStoreManagerHolder {
		public static CookieStoreManager sInstance = new CookieStoreManager();
	}
}


text:
/* @flow strict-local */
import { StackActions } from 'react-navigation';

import type {
  Dispatch,
  NavigationAction,
  GetState,
  Message,
  Narrow,
  UserOrBot,
  ApiResponseServerSettings,
} from '../types';
import { getSameRoutesCount } from '../selectors';

export const navigateBack = () => (dispatch: Dispatch, getState: GetState): NavigationAction =>
  dispatch(StackActions.pop({ n: getSameRoutesCount(getState()) }));

// Other stack routes reached through `navReducer`:
//    StackActions.push({ routeName: 'loading' });
//    StackActions.push({ routeName: 'realm' });
//    StackActions.push({ routeName: 'account' });
//    StackActions.push({ routeName: 'main' });

/** Only call this via `doNarrow`.  See there for details. */
export const navigateToChat = (narrow: Narrow): NavigationAction =>
  StackActions.push({ routeName: 'chat', params: { narrow } });

export const navigateToUsersScreen = (): NavigationAction =>
  StackActions.push({ routeName: 'users' });

export const navigateToSearch = (): NavigationAction => StackActions.push({ routeName: 'search' });

export const navigateToEmojiPicker = (messageId: number): NavigationAction =>
  StackActions.push({ routeName: 'emoji-picker', params: { messageId } });

export const navigateToAuth = (serverSettings: ApiResponseServerSettings): NavigationAction =>
  StackActions.push({ routeName: 'auth', params: { serverSettings } });

export const navigateToDev = (): NavigationAction => StackActions.push({ routeName: 'dev' });

export const navigateToPassword = (requireEmailFormat: boolean): NavigationAction =>
  StackActions.push({ routeName: 'password', params: { requireEmailFormat } });

export const navigateToAccountPicker = (): NavigationAction =>
  StackActions.push({ routeName: 'account' });

export const navigateToAccountDetails = (userId: number): NavigationAction =>
  StackActions.push({ routeName: 'account-details', params: { userId } });

export const navigateToGroupDetails = (recipients: UserOrBot[]): NavigationAction =>
  StackActions.push({ routeName: 'group-details', params: { recipients } });

export const navigateToRealmScreen = (realm?: string): NavigationAction =>
  StackActions.push({ routeName: 'realm', params: { realm } });

export const navigateToLightbox = (src: string, message: Message): NavigationAction =>
  StackActions.push({ routeName: 'lightbox', params: { src, message } });

export const navigateToLanguage = (): NavigationAction =>
  StackActions.push({ routeName: 'language' });

export const navigateToCreateGroup = (): NavigationAction =>
  StackActions.push({ routeName: 'group' });

export const navigateToDiagnostics = (): NavigationAction =>
  StackActions.push({ routeName: 'diagnostics' });

export const navigateToVariables = (): NavigationAction =>
  StackActions.push({ routeName: 'variables' });

export const navigateToTiming = (): NavigationAction => StackActions.push({ routeName: 'timing' });

export const navigateToStorage = (): NavigationAction =>
  StackActions.push({ routeName: 'storage' });

export const navigateToDebug = (): NavigationAction => StackActions.push({ routeName: 'debug' });

export const navigateToStream = (streamId: number): NavigationAction =>
  StackActions.push({ routeName: 'stream', params: { streamId } });

export const navigateToTopicList = (streamId: number): NavigationAction =>
  StackActions.push({ routeName: 'topics', params: { streamId } });

export const navigateToCreateStream = (): NavigationAction =>
  StackActions.push({ routeName: 'stream-create' });

export const navigateToEditStream = (streamId: number): NavigationAction =>
  StackActions.push({ routeName: 'stream-edit', params: { streamId } });

export const navigateToStreamSubscribers = (streamId: number): NavigationAction =>
  StackActions.push({ routeName: 'invite-users', params: { streamId } });

export const navigateToNotifications = (): NavigationAction =>
  StackActions.push({ routeName: 'notifications' });

export const navigateToMessageReactionScreen = (
  messageId: number,
  reactionName?: string,
): NavigationAction =>
  StackActions.push({ routeName: 'message-reactions', params: { messageId, reactionName } });

export const navigateToLegal = (): NavigationAction => StackActions.push({ routeName: 'legal' });

export const navigateToUserStatus = (): NavigationAction =>
  StackActions.push({ routeName: 'user-status' });


text:
<?php
require_once __DIR__.'/../vendor/autoload.php';
require_once __DIR__.'/../shared/connect.php';
require_once __DIR__.'/../shared/listeners.php';
require_once __DIR__.'/../commonFramework/modelsManager/modelsTools.inc.php';
require_once __DIR__.'/lib.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

ob_start();

try {
    $client = new FranceIOI\LoginModuleClient\Client($config->login_module_client);
    $authorization_helper = $client->getAuthorizationHelper();
    $user = $authorization_helper->queryUser();
    $params = remapUserArray($user);
    createUpdateUser($db, $params);
} catch(Exception $e) {
    echo json_encode([
        'result' => true,
        'error' => $e->getMessage()
    ]);
}

$json_result = ob_get_contents();
ob_end_clean();

?>
<!DOCTYPE html>
<html>
<body>
    <script type="text/javascript">
        if(window.opener && window.opener['__LoginModuleOnProfile']) {
            window.opener.__LoginModuleOnProfile(<?=$json_result?>);
        } else {
            window.close();
        }
    </script>
</body>
</html>


text:
require File.dirname(__FILE__) + '/../test_helper.rb'

class SessionSettingsTest < ActiveSupport::TestCase

  must "RPX API key is set" do
    assert UserSession.rpx_key, "the RPX API key must be set in the Authlogic::Session class configuration"
  end

  must "auto_register default is enabled" do
    UserSession.auto_register
    assert_true UserSession.auto_register_value
  end

  must "auto_register set disabled" do
    UserSession.auto_register false
    assert_false UserSession.auto_register_value
  end

  must "auto_register set enabled" do
    UserSession.auto_register true
    assert_true UserSession.auto_register_value
  end

  must "rpx_extended_info default is disbled" do
    assert_false UserSession.rpx_extended_info_value
  end

  must "rpx_extended_info set enabled" do
    UserSession.rpx_extended_info true
    assert_true UserSession.rpx_extended_info_value
  end

  must "rpx_extended_info set disabled" do
    UserSession.rpx_extended_info false
    assert_false UserSession.rpx_extended_info_value
  end

end


text:
package com.enonic.harvest.harvestclient.models;

import com.enonic.harvest.harvestclient.exceptions.HarvestClientException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@XmlRootElement(name = "users")
@XmlAccessorType(XmlAccessType.NONE)
public class UserCollection
        implements Iterable<User>
{
    @XmlElement(name = "user")
    private List<User> list = new ArrayList<User>();

    public List<User> getList()
    {
        return list;
    }

    public void setList(List<User> list)
    {
        this.list = list;
    }

    public static UserCollection fromInputStream(final InputStream xml)
            throws HarvestClientException
    {
        try
        {
            JAXBContext context = JAXBContext.newInstance(UserCollection.class);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            return (UserCollection) unmarshaller.unmarshal(xml);
        }
        catch (Exception e)
        {
            throw new HarvestClientException("Unable to parse XML into UserCollection.", e);
        }

    }

    @Override
    public Iterator<User> iterator()
    {
        return this.list.iterator();
    }
}


text:
import SocketServer
from threading import Thread
import CTCore

class server(Thread):
    def __init__(self):
        super(server, self).__init__()
        self.srv = SocketServer.TCPServer((CTCore.HOST, CTCore.PORT), TCPHandler)

    def run(self):
        print CTCore.newLine + "[+] Started Web Server on http://" + CTCore.HOST + ":" + str(CTCore.PORT)
        print "[+] Listening to requests..." + CTCore.newLine
        self.srv.serve_forever()

    def shutdown(self):
        if (CTCore.web_server_turned_on):
            self.srv.shutdown()
            self.srv.server_close()
            print "WebServer Shutdown."
            CTCore.web_server_turned_on = False

class TCPHandler(SocketServer.BaseRequestHandler):

    def check_request(self, conv_req, get_uri):
        if (get_uri.lower() == conv_req.lower()):
            return True
        else:
            return False

    def get_clear_uri(self):
        try:
            get_request = self.data.splitlines()[0]
            import datetime
            now_s = datetime.datetime.now()
            CTCore.request_logs.append("[" + str(now_s.isoformat()) + "] " + self.client_address[0] + " : " + get_request)

            get_start = get_request.find(' ') + 1
            get_end = get_request.rfind(' ')
            loop_start = get_start + 1
            for i in range(loop_start, get_end):
                if get_request[i] == '/':
                    get_start += 1
                else:
                    break
            get_uri = get_request[get_start:get_end]
            return get_uri
        except Exception,e:
            print "[-] Error parsing data: " + self.data + ":" + str(e)

    def handle(self):
        self.data = self.request.recv(1024).strip()

        if (self.data != ""):
            get_uri = self.get_clear_uri()

            for conv in CTCore.all_conversations:
                if (self.check_request(conv.uri, get_uri) == True):
                    resp = conv.res_head
                    if conv.orig_resp != "":
                        resp = resp + "\r\n\r\n" + conv.orig_resp
                    else:
                        resp = resp + "\r\n\r\n" + conv.res_body

                    self.request.send(resp)
                    break


text:
package org.apache.drill.exec.fn.impl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.List;

import org.apache.drill.common.util.FileUtils;
import org.apache.drill.exec.client.DrillClient;
import org.apache.drill.exec.pop.PopUnitTestBase;
import org.apache.drill.exec.record.RecordBatchLoader;
import org.apache.drill.exec.record.VectorWrapper;
import org.apache.drill.exec.rpc.user.QueryResultBatch;
import org.apache.drill.exec.server.Drillbit;
import org.apache.drill.exec.server.RemoteServiceSet;
import org.apache.drill.exec.vector.ValueVector;
import org.junit.Ignore;
import org.junit.Test;

import com.google.common.base.Charsets;
import com.google.common.io.Files;

public class TestDateFunctions extends PopUnitTestBase {
    static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TestDateFunctions.class);

    public void testCommon(String[] expectedResults, String physicalPlan, String resourceFile) throws Exception {
        try (RemoteServiceSet serviceSet = RemoteServiceSet.getLocalServiceSet();
             Drillbit bit = new Drillbit(CONFIG, serviceSet);
             DrillClient client = new DrillClient(CONFIG, serviceSet.getCoordinator())) {

            // run query.
            bit.run();
            client.connect();
            List<QueryResultBatch> results = client.runQuery(org.apache.drill.exec.proto.UserBitShared.QueryType.PHYSICAL,
                    Files.toString(FileUtils.getResourceAsFile(physicalPlan), Charsets.UTF_8)
                            .replace("#{TEST_FILE}", resourceFile));

            RecordBatchLoader batchLoader = new RecordBatchLoader(bit.getContext().getAllocator());

            QueryResultBatch batch = results.get(0);
            assertTrue(batchLoader.load(batch.getHeader().getDef(), batch.getData()));

            int i = 0;
            for (VectorWrapper<?> v : batchLoader) {

                ValueVector.Accessor accessor = v.getValueVector().getAccessor();
                System.out.println(accessor.getObject(0));
                assertEquals( expectedResults[i++], accessor.getObject(0).toString());
            }

            batchLoader.clear();
            for(QueryResultBatch b : results){
                b.release();
            }
        }
    }

    @Test
    @Ignore("relies on particular timezone")
    public void testDateIntervalArithmetic() throws Exception {
        String expectedResults[] = {"2009-02-23T00:00:00.000-08:00",
                                    "2008-02-24T00:00:00.000-08:00",
                                    "1970-01-01T13:20:33.000-08:00",
                                    "2008-02-24T12:00:00.000-08:00",
                                    "2009-04-23T12:00:00.000-07:00",
                                    "2008-02-24T12:00:00.000-08:00",
                                    "2009-04-23T12:00:00.000-07:00",
                                    "2009-02-23T00:00:00.000-08:00",
                                    "2008-02-24T00:00:00.000-08:00",
                                    "1970-01-01T13:20:33.000-08:00",
                                    "2008-02-24T12:00:00.000-08:00",
                                    "2009-04-23T12:00:00.000-07:00",
                                    "2008-02-24T12:00:00.000-08:00",
                                    "2009-04-23T12:00:00.000-07:00"};
        testCommon(expectedResults, "/functions/date/date_interval_arithmetic.json", "/test_simple_date.json");
    }

    @Test
    public void testDateDifferenceArithmetic() throws Exception {

        String[] expectedResults = {"P365D",
                                    "P-366DT-60S",
                                    "PT10800S",
                                    "PT39600S"};
        testCommon(expectedResults, "/functions/date/date_difference_arithmetic.json", "/test_simple_date.json");
    }

    @Test
    public void testAge() throws Exception {
        String[] expectedResults = { "P109M16DT82800S",
                                     "P172M27D",
                                     "P-172M-27D",
                                     "P-39M-18DT-63573S"};
        testCommon(expectedResults, "/functions/date/age.json", "/test_simple_date.json");
    }

    @Test
    public void testIntervalArithmetic() throws Exception {

      String expectedResults[] = {"P2Y2M",
          "P2DT3723S",
          "P2M",
          "PT3723S",
          "P28M",
          "PT7206S",
          "P7M",
          "PT1801.500S",
          "P33M18D",
          "PT8647.200S",
          "P6M19DT86399.999S",
          "PT1715.714S"};

        testCommon(expectedResults, "/functions/date/interval_arithmetic.json", "/test_simple_date.json");
    }

    @Test
    public void testToChar() throws Exception {

        String expectedResults[] = {"2008-Feb-23",
                                    "12 20 30",
                                    "2008 Feb 23 12:00:00",
                                    "2008-02-23 20:00:00 America/Los_Angeles"};
        testCommon(expectedResults, "/functions/date/to_char.json", "/test_simple_date.json");
    }

    @Test
    @Ignore("relies on particular time zone")
    public void testToDateType() throws Exception {
        String expectedResults[] = {"2008-02-23T00:00:00.000-08:00",
                                    "1970-01-01T12:20:30.000-08:00",
                                    "2008-02-23T12:00:00.000-08:00",
                                    "2008-02-23T12:00:00.000-08:00"};

        testCommon(expectedResults, "/functions/date/to_date_type.json", "/test_simple_date.json");
    }

}


text:
package boofcv.alg.tracker;

import boofcv.abst.feature.detect.interest.ConfigFastHessian;
import boofcv.abst.feature.detect.interest.ConfigGeneralDetector;
import boofcv.abst.feature.tracker.PointTrack;
import boofcv.abst.feature.tracker.PointTracker;
import boofcv.alg.tracker.klt.PkltConfig;
import boofcv.factory.feature.tracker.FactoryPointTracker;
import boofcv.gui.VideoProcessAppBase;
import boofcv.gui.feature.VisualizeFeatures;
import boofcv.gui.image.ImagePanel;
import boofcv.gui.image.ShowImages;
import boofcv.io.PathLabel;
import boofcv.io.image.SimpleImageSequence;
import boofcv.struct.image.ImageFloat32;
import boofcv.struct.image.ImageSingleBand;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

/**
 * Runs a KLT tracker through a video sequence
 *
 * @author Peter Abeles
 */
// todo extract out base class for handling videos
public class VideoTrackerPointFeaturesApp<I extends ImageSingleBand, D extends ImageSingleBand>
		extends VideoProcessAppBase<I> implements MouseListener
{

	int maxFeatures = 400;
	int minFeatures = 150;

	PointTracker<I> tracker;

	ImagePanel gui = new ImagePanel();

	BufferedImage workImage;

	public VideoTrackerPointFeaturesApp(Class<I> imageType, Class<D> derivType) {
		super(1,imageType);

		PkltConfig config = new PkltConfig();
		config.templateRadius = 3;
		config.pyramidScaling = new int[]{1,2,4,8};

		ConfigFastHessian configFH = new ConfigFastHessian();
		configFH.maxFeaturesPerScale = 200;
		configFH.extractRadius = 4;
		configFH.detectThreshold = 15f;

		addAlgorithm(0,"KLT", FactoryPointTracker.klt(config, new ConfigGeneralDetector(maxFeatures, 1, 3),
				imageType, derivType));
		addAlgorithm(0,"ST-BRIEF", FactoryPointTracker.
				dda_ST_BRIEF(200, new ConfigGeneralDetector(maxFeatures, 3, 1), imageType, derivType));
		addAlgorithm(0,"ST-NCC", FactoryPointTracker.
				dda_ST_NCC(new ConfigGeneralDetector(maxFeatures, 3, 2), 5, imageType, derivType));
		addAlgorithm(0,"FH-SURF", FactoryPointTracker.
				dda_FH_SURF_Fast(configFH, null, null, imageType));
		addAlgorithm(0,"ST-SURF-KLT", FactoryPointTracker.
				combined_ST_SURF_KLT(new ConfigGeneralDetector(maxFeatures, 3, 1),
						config, 50, null, null, imageType, derivType));
		addAlgorithm(0,"FH-SURF-KLT", FactoryPointTracker.combined_FH_SURF_KLT(
				config, 50, configFH, null, null, imageType));

		gui.addMouseListener(this);
		gui.requestFocus();
		setMainGUI(gui);
	}

	@Override
	public void loadConfigurationFile(String fileName) {}

	@Override
	public void process( SimpleImageSequence<I> sequence ) {
		stopWorker();
		this.sequence = sequence;
		sequence.setLoop(true);
		doRefreshAll();
	}

	@Override
	public boolean getHasProcessedImage() {
		return workImage != null;
	}

	@Override
	public void refreshAll(Object[] cookies) {
		setActiveAlgorithm(0,null,cookies[0]);
	}

	@Override
	public void setActiveAlgorithm(int indexFamily, String name, Object cookie) {
		if( sequence == null )
			return;

		stopWorker();

		tracker = (PointTracker<I>)cookie;
		sequence.reset();

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				I image = sequence.next();
				gui.setPreferredSize(new Dimension(image.width,image.height));
				workImage = new BufferedImage(image.width,image.height,BufferedImage.TYPE_INT_BGR);
				gui.setBufferedImage(workImage);
				revalidate();
				startWorkerThread();
			}});
	}

	void renderFeatures( BufferedImage orig , double trackerFPS ) {
		Graphics2D g2 = workImage.createGraphics();

		g2.drawImage(orig,0,0,orig.getWidth(),orig.getHeight(),null);
		for( PointTrack p : tracker.getActiveTracks(null) ) {
			int x = (int)p.x;
			int y = (int)p.y;

			VisualizeFeatures.drawPoint(g2,x,y,Color.blue);
		}

		for( PointTrack p : tracker.getNewTracks(null) ) {
			int x = (int)p.x;
			int y = (int)p.y;

			VisualizeFeatures.drawPoint(g2,x,y,Color.green);
		}

		g2.setColor(Color.WHITE);
		g2.fillRect(5,15,140,20);
		g2.setColor(Color.BLACK);
		g2.drawString(String.format("Tracker FPS: %3.1f",trackerFPS),10,30);
	}

	@Override
	protected void updateAlg(I frame, BufferedImage buffImage) {
		tracker.process(frame);

		if( tracker.getActiveTracks(null).size() < minFeatures ) {
			tracker.spawnTracks();
		}
	}

	@Override
	protected void handleRunningStatus(int status) {}

	@Override
	protected void updateAlgGUI(ImageSingleBand frame, BufferedImage imageGUI, double fps) {
		renderFeatures((BufferedImage)sequence.getGuiImage(),fps);
	}

	public static void main( String args[] ) {
		Class imageType = ImageFloat32.class;
		Class derivType = ImageFloat32.class;

//		Class imageType = ImageUInt8.class;
//		Class derivType = ImageSInt16.class;

		VideoTrackerPointFeaturesApp app = new VideoTrackerPointFeaturesApp(imageType, derivType);

		java.util.List<PathLabel> inputs = new ArrayList<PathLabel>();
		inputs.add(new PathLabel("Shake", "../data/applet/shake.mjpeg"));
		inputs.add(new PathLabel("Zoom", "../data/applet/zoom.mjpeg"));
		inputs.add(new PathLabel("Rotate", "../data/applet/rotate.mjpeg"));

		app.setInputList(inputs);

		// wait for it to process one image so that the size isn't all screwed up
		while( !app.getHasProcessedImage() ) {
			Thread.yield();
		}

		ShowImages.showWindow(app, "Feature Tracker",true);
	}
}


text:
const { BN, constants, expectEvent, expectRevert } = require('@openzeppelin/test-helpers');
const { ZERO_ADDRESS } = constants;

const { expect } = require('chai');

const ERC777SenderRecipientMock = artifacts.require('ERC777SenderRecipientMock');

function shouldBehaveLikeERC777DirectSendBurn (holder, recipient, data) {
  shouldBehaveLikeERC777DirectSend(holder, recipient, data);
  shouldBehaveLikeERC777DirectBurn(holder, data);
}

function shouldBehaveLikeERC777OperatorSendBurn (holder, recipient, operator, data, operatorData) {
  shouldBehaveLikeERC777OperatorSend(holder, recipient, operator, data, operatorData);
  shouldBehaveLikeERC777OperatorBurn(holder, operator, data, operatorData);
}

function shouldBehaveLikeERC777UnauthorizedOperatorSendBurn (holder, recipient, operator, data, operatorData) {
  shouldBehaveLikeERC777UnauthorizedOperatorSend(holder, recipient, operator, data, operatorData);
  shouldBehaveLikeERC777UnauthorizedOperatorBurn(holder, operator, data, operatorData);
}

function shouldBehaveLikeERC777DirectSend (holder, recipient, data) {
  describe('direct send', function () {
    context('when the sender has tokens', function () {
      shouldDirectSendTokens(holder, recipient, new BN('0'), data);
      shouldDirectSendTokens(holder, recipient, new BN('1'), data);

      it('reverts when sending more than the balance', async function () {
        const balance = await this.token.balanceOf(holder);
        await expectRevert.unspecified(this.token.send(recipient, balance.addn(1), data, { from: holder }));
      });

      it('reverts when sending to the zero address', async function () {
        await expectRevert.unspecified(this.token.send(ZERO_ADDRESS, new BN('1'), data, { from: holder }));
      });
    });

    context('when the sender has no tokens', function () {
      removeBalance(holder);

      shouldDirectSendTokens(holder, recipient, new BN('0'), data);

      it('reverts when sending a non-zero amount', async function () {
        await expectRevert.unspecified(this.token.send(recipient, new BN('1'), data, { from: holder }));
      });
    });
  });
}

function shouldBehaveLikeERC777OperatorSend (holder, recipient, operator, data, operatorData) {
  describe('operator send', function () {
    context('when the sender has tokens', async function () {
      shouldOperatorSendTokens(holder, operator, recipient, new BN('0'), data, operatorData);
      shouldOperatorSendTokens(holder, operator, recipient, new BN('1'), data, operatorData);

      it('reverts when sending more than the balance', async function () {
        const balance = await this.token.balanceOf(holder);
        await expectRevert.unspecified(
          this.token.operatorSend(holder, recipient, balance.addn(1), data, operatorData, { from: operator }),
        );
      });

      it('reverts when sending to the zero address', async function () {
        await expectRevert.unspecified(
          this.token.operatorSend(
            holder, ZERO_ADDRESS, new BN('1'), data, operatorData, { from: operator },
          ),
        );
      });
    });

    context('when the sender has no tokens', function () {
      removeBalance(holder);

      shouldOperatorSendTokens(holder, operator, recipient, new BN('0'), data, operatorData);

      it('reverts when sending a non-zero amount', async function () {
        await expectRevert.unspecified(
          this.token.operatorSend(holder, recipient, new BN('1'), data, operatorData, { from: operator }),
        );
      });

      it('reverts when sending from the zero address', async function () {
        // This is not yet reflected in the spec
        await expectRevert.unspecified(
          this.token.operatorSend(
            ZERO_ADDRESS, recipient, new BN('0'), data, operatorData, { from: operator },
          ),
        );
      });
    });
  });
}

function shouldBehaveLikeERC777UnauthorizedOperatorSend (holder, recipient, operator, data, operatorData) {
  describe('operator send', function () {
    it('reverts', async function () {
      await expectRevert.unspecified(this.token.operatorSend(holder, recipient, new BN('0'), data, operatorData));
    });
  });
}

function shouldBehaveLikeERC777DirectBurn (holder, data) {
  describe('direct burn', function () {
    context('when the sender has tokens', function () {
      shouldDirectBurnTokens(holder, new BN('0'), data);
      shouldDirectBurnTokens(holder, new BN('1'), data);

      it('reverts when burning more than the balance', async function () {
        const balance = await this.token.balanceOf(holder);
        await expectRevert.unspecified(this.token.burn(balance.addn(1), data, { from: holder }));
      });
    });

    context('when the sender has no tokens', function () {
      removeBalance(holder);

      shouldDirectBurnTokens(holder, new BN('0'), data);

      it('reverts when burning a non-zero amount', async function () {
        await expectRevert.unspecified(this.token.burn(new BN('1'), data, { from: holder }));
      });
    });
  });
}

function shouldBehaveLikeERC777OperatorBurn (holder, operator, data, operatorData) {
  describe('operator burn', function () {
    context('when the sender has tokens', async function () {
      shouldOperatorBurnTokens(holder, operator, new BN('0'), data, operatorData);
      shouldOperatorBurnTokens(holder, operator, new BN('1'), data, operatorData);

      it('reverts when burning more than the balance', async function () {
        const balance = await this.token.balanceOf(holder);
        await expectRevert.unspecified(
          this.token.operatorBurn(holder, balance.addn(1), data, operatorData, { from: operator }),
        );
      });
    });

    context('when the sender has no tokens', function () {
      removeBalance(holder);

      shouldOperatorBurnTokens(holder, operator, new BN('0'), data, operatorData);

      it('reverts when burning a non-zero amount', async function () {
        await expectRevert.unspecified(
          this.token.operatorBurn(holder, new BN('1'), data, operatorData, { from: operator }),
        );
      });

      it('reverts when burning from the zero address', async function () {
        // This is not yet reflected in the spec
        await expectRevert.unspecified(
          this.token.operatorBurn(
            ZERO_ADDRESS, new BN('0'), data, operatorData, { from: operator },
          ),
        );
      });
    });
  });
}

function shouldBehaveLikeERC777UnauthorizedOperatorBurn (holder, operator, data, operatorData) {
  describe('operator burn', function () {
    it('reverts', async function () {
      await expectRevert.unspecified(this.token.operatorBurn(holder, new BN('0'), data, operatorData));
    });
  });
}

function shouldDirectSendTokens (from, to, amount, data) {
  shouldSendTokens(from, null, to, amount, data, null);
}

function shouldOperatorSendTokens (from, operator, to, amount, data, operatorData) {
  shouldSendTokens(from, operator, to, amount, data, operatorData);
}

function shouldSendTokens (from, operator, to, amount, data, operatorData) {
  const operatorCall = operator !== null;

  it(`${operatorCall ? 'operator ' : ''}can send an amount of ${amount}`, async function () {
    const initialTotalSupply = await this.token.totalSupply();
    const initialFromBalance = await this.token.balanceOf(from);
    const initialToBalance = await this.token.balanceOf(to);

    let receipt;
    if (!operatorCall) {
      (receipt = await this.token.send(to, amount, data, { from }));
      expectEvent(receipt, 'Sent', {
        operator: from,
        from,
        to,
        amount,
        data,
        operatorData: null,
      });
    } else {
      (receipt = await this.token.operatorSend(from, to, amount, data, operatorData, { from: operator }));
      expectEvent(receipt, 'Sent', {
        operator,
        from,
        to,
        amount,
        data,
        operatorData,
      });
    }

    expectEvent(receipt, 'Transfer', {
      from,
      to,
      value: amount,
    });

    const finalTotalSupply = await this.token.totalSupply();
    const finalFromBalance = await this.token.balanceOf(from);
    const finalToBalance = await this.token.balanceOf(to);

    expect(finalTotalSupply).to.be.bignumber.equal(initialTotalSupply);
    expect(finalToBalance.sub(initialToBalance)).to.be.bignumber.equal(amount);
    expect(finalFromBalance.sub(initialFromBalance)).to.be.bignumber.equal(amount.neg());
  });
}

function shouldDirectBurnTokens (from, amount, data) {
  shouldBurnTokens(from, null, amount, data, null);
}

function shouldOperatorBurnTokens (from, operator, amount, data, operatorData) {
  shouldBurnTokens(from, operator, amount, data, operatorData);
}

function shouldBurnTokens (from, operator, amount, data, operatorData) {
  const operatorCall = operator !== null;

  it(`${operatorCall ? 'operator ' : ''}can burn an amount of ${amount}`, async function () {
    const initialTotalSupply = await this.token.totalSupply();
    const initialFromBalance = await this.token.balanceOf(from);

    let receipt;
    if (!operatorCall) {
      (receipt = await this.token.burn(amount, data, { from }));
      expectEvent(receipt, 'Burned', {
        operator: from,
        from,
        amount,
        data,
        operatorData: null,
      });
    } else {
      (receipt = await this.token.operatorBurn(from, amount, data, operatorData, { from: operator }));
      expectEvent(receipt, 'Burned', {
        operator,
        from,
        amount,
        data,
        operatorData,
      });
    }

    expectEvent(receipt, 'Transfer', {
      from,
      to: ZERO_ADDRESS,
      value: amount,
    });

    const finalTotalSupply = await this.token.totalSupply();
    const finalFromBalance = await this.token.balanceOf(from);

    expect(finalTotalSupply.sub(initialTotalSupply)).to.be.bignumber.equal(amount.neg());
    expect(finalFromBalance.sub(initialFromBalance)).to.be.bignumber.equal(amount.neg());
  });
}

function shouldBehaveLikeERC777InternalMint (recipient, operator, amount, data, operatorData) {
  shouldInternalMintTokens(operator, recipient, new BN('0'), data, operatorData);
  shouldInternalMintTokens(operator, recipient, amount, data, operatorData);

  it('reverts when minting tokens for the zero address', async function () {
    await expectRevert.unspecified(
      this.token.mintInternal(ZERO_ADDRESS, amount, data, operatorData, { from: operator }),
    );
  });
}

function shouldInternalMintTokens (operator, to, amount, data, operatorData) {
  it(`can (internal) mint an amount of ${amount}`, async function () {
    const initialTotalSupply = await this.token.totalSupply();
    const initialToBalance = await this.token.balanceOf(to);

    const receipt = await this.token.mintInternal(to, amount, data, operatorData, { from: operator });

    expectEvent(receipt, 'Minted', {
      operator,
      to,
      amount,
      data,
      operatorData,
    });

    expectEvent(receipt, 'Transfer', {
      from: ZERO_ADDRESS,
      to,
      value: amount,
    });

    const finalTotalSupply = await this.token.totalSupply();
    const finalToBalance = await this.token.balanceOf(to);

    expect(finalTotalSupply.sub(initialTotalSupply)).to.be.bignumber.equal(amount);
    expect(finalToBalance.sub(initialToBalance)).to.be.bignumber.equal(amount);
  });
}

function shouldBehaveLikeERC777SendBurnMintInternalWithReceiveHook (operator, amount, data, operatorData) {
  context('when TokensRecipient reverts', function () {
    beforeEach(async function () {
      await this.tokensRecipientImplementer.setShouldRevertReceive(true);
    });

    it('send reverts', async function () {
      await expectRevert.unspecified(sendFromHolder(this.token, this.sender, this.recipient, amount, data));
    });

    it('operatorSend reverts', async function () {
      await expectRevert.unspecified(
        this.token.operatorSend(this.sender, this.recipient, amount, data, operatorData, { from: operator }),
      );
    });

    it('mint (internal) reverts', async function () {
      await expectRevert.unspecified(
        this.token.mintInternal(this.recipient, amount, data, operatorData, { from: operator }),
      );
    });
  });

  context('when TokensRecipient does not revert', function () {
    beforeEach(async function () {
      await this.tokensRecipientImplementer.setShouldRevertSend(false);
    });

    it('TokensRecipient receives send data and is called after state mutation', async function () {
      const { tx } = await sendFromHolder(this.token, this.sender, this.recipient, amount, data);

      const postSenderBalance = await this.token.balanceOf(this.sender);
      const postRecipientBalance = await this.token.balanceOf(this.recipient);

      await assertTokensReceivedCalled(
        this.token,
        tx,
        this.sender,
        this.sender,
        this.recipient,
        amount,
        data,
        null,
        postSenderBalance,
        postRecipientBalance,
      );
    });

    it('TokensRecipient receives operatorSend data and is called after state mutation', async function () {
      const { tx } = await this.token.operatorSend(
        this.sender, this.recipient, amount, data, operatorData,
        { from: operator },
      );

      const postSenderBalance = await this.token.balanceOf(this.sender);
      const postRecipientBalance = await this.token.balanceOf(this.recipient);

      await assertTokensReceivedCalled(
        this.token,
        tx,
        operator,
        this.sender,
        this.recipient,
        amount,
        data,
        operatorData,
        postSenderBalance,
        postRecipientBalance,
      );
    });

    it('TokensRecipient receives mint (internal) data and is called after state mutation', async function () {
      const { tx } = await this.token.mintInternal(
        this.recipient, amount, data, operatorData, { from: operator },
      );

      const postRecipientBalance = await this.token.balanceOf(this.recipient);

      await assertTokensReceivedCalled(
        this.token,
        tx,
        operator,
        ZERO_ADDRESS,
        this.recipient,
        amount,
        data,
        operatorData,
        new BN('0'),
        postRecipientBalance,
      );
    });
  });
}

function shouldBehaveLikeERC777SendBurnWithSendHook (operator, amount, data, operatorData) {
  context('when TokensSender reverts', function () {
    beforeEach(async function () {
      await this.tokensSenderImplementer.setShouldRevertSend(true);
    });

    it('send reverts', async function () {
      await expectRevert.unspecified(sendFromHolder(this.token, this.sender, this.recipient, amount, data));
    });

    it('operatorSend reverts', async function () {
      await expectRevert.unspecified(
        this.token.operatorSend(this.sender, this.recipient, amount, data, operatorData, { from: operator }),
      );
    });

    it('burn reverts', async function () {
      await expectRevert.unspecified(burnFromHolder(this.token, this.sender, amount, data));
    });

    it('operatorBurn reverts', async function () {
      await expectRevert.unspecified(
        this.token.operatorBurn(this.sender, amount, data, operatorData, { from: operator }),
      );
    });
  });

  context('when TokensSender does not revert', function () {
    beforeEach(async function () {
      await this.tokensSenderImplementer.setShouldRevertSend(false);
    });

    it('TokensSender receives send data and is called before state mutation', async function () {
      const preSenderBalance = await this.token.balanceOf(this.sender);
      const preRecipientBalance = await this.token.balanceOf(this.recipient);

      const { tx } = await sendFromHolder(this.token, this.sender, this.recipient, amount, data);

      await assertTokensToSendCalled(
        this.token,
        tx,
        this.sender,
        this.sender,
        this.recipient,
        amount,
        data,
        null,
        preSenderBalance,
        preRecipientBalance,
      );
    });

    it('TokensSender receives operatorSend data and is called before state mutation', async function () {
      const preSenderBalance = await this.token.balanceOf(this.sender);
      const preRecipientBalance = await this.token.balanceOf(this.recipient);

      const { tx } = await this.token.operatorSend(
        this.sender, this.recipient, amount, data, operatorData,
        { from: operator },
      );

      await assertTokensToSendCalled(
        this.token,
        tx,
        operator,
        this.sender,
        this.recipient,
        amount,
        data,
        operatorData,
        preSenderBalance,
        preRecipientBalance,
      );
    });

    it('TokensSender receives burn data and is called before state mutation', async function () {
      const preSenderBalance = await this.token.balanceOf(this.sender);

      const { tx } = await burnFromHolder(this.token, this.sender, amount, data, { from: this.sender });

      await assertTokensToSendCalled(
        this.token, tx, this.sender, this.sender, ZERO_ADDRESS, amount, data, null, preSenderBalance,
      );
    });

    it('TokensSender receives operatorBurn data and is called before state mutation', async function () {
      const preSenderBalance = await this.token.balanceOf(this.sender);

      const { tx } = await this.token.operatorBurn(this.sender, amount, data, operatorData, { from: operator });

      await assertTokensToSendCalled(
        this.token, tx, operator, this.sender, ZERO_ADDRESS, amount, data, operatorData, preSenderBalance,
      );
    });
  });
}

function removeBalance (holder) {
  beforeEach(async function () {
    await this.token.burn(await this.token.balanceOf(holder), '0x', { from: holder });
    expect(await this.token.balanceOf(holder)).to.be.bignumber.equal('0');
  });
}

async function assertTokensReceivedCalled (token, txHash, operator, from, to, amount, data, operatorData, fromBalance,
  toBalance = '0') {
  await expectEvent.inTransaction(txHash, ERC777SenderRecipientMock, 'TokensReceivedCalled', {
    operator, from, to, amount, data, operatorData, token: token.address, fromBalance, toBalance,
  });
}

async function assertTokensToSendCalled (token, txHash, operator, from, to, amount, data, operatorData, fromBalance,
  toBalance = '0') {
  await expectEvent.inTransaction(txHash, ERC777SenderRecipientMock, 'TokensToSendCalled', {
    operator, from, to, amount, data, operatorData, token: token.address, fromBalance, toBalance,
  });
}

async function sendFromHolder (token, holder, to, amount, data) {
  if ((await web3.eth.getCode(holder)).length <= '0x'.length) {
    return token.send(to, amount, data, { from: holder });
  } else {
    // assume holder is ERC777SenderRecipientMock contract
    return (await ERC777SenderRecipientMock.at(holder)).send(token.address, to, amount, data);
  }
}

async function burnFromHolder (token, holder, amount, data) {
  if ((await web3.eth.getCode(holder)).length <= '0x'.length) {
    return token.burn(amount, data, { from: holder });
  } else {
    // assume holder is ERC777SenderRecipientMock contract
    return (await ERC777SenderRecipientMock.at(holder)).burn(token.address, amount, data);
  }
}

module.exports = {
  shouldBehaveLikeERC777DirectSendBurn,
  shouldBehaveLikeERC777OperatorSendBurn,
  shouldBehaveLikeERC777UnauthorizedOperatorSendBurn,
  shouldBehaveLikeERC777InternalMint,
  shouldBehaveLikeERC777SendBurnMintInternalWithReceiveHook,
  shouldBehaveLikeERC777SendBurnWithSendHook,
};


text:
package org.wikipedia.feed.searchbar;

import android.support.annotation.NonNull;

import org.wikipedia.feed.model.Card;
import org.wikipedia.feed.model.CardType;

public class SearchCard extends Card {
    @NonNull @Override public CardType type() {
        return CardType.SEARCH_BAR;
    }
}


text:
namespace ManagedBass.DirectX8
{
    /// <summary>
    /// DX8 Reverb Effect.
    /// </summary>
    public sealed class DXReverbEffect : Effect<DXReverbParameters>
    {
        /// <summary>
        /// Input gain of signal, in decibels (dB), in the range from -96 through 0. The default value is 0 dB.
        /// </summary>
        public double InGain
        {
            get => Parameters.fInGain;
            set
            {
                Parameters.fInGain = (float)value;

                OnPropertyChanged();
            }
        }

        /// <summary>
        /// Reverb mix, in dB, in the range from -96 through 0. The default value is 0 dB.
        /// </summary>
        public double ReverbMix
        {
            get => Parameters.fReverbMix;
            set
            {
                Parameters.fReverbMix = (float)value;

                OnPropertyChanged();
            }
        }

        /// <summary>
        /// Reverb time, in milliseconds, in the range from 0.001 through 3000. The default value is 1000.
        /// </summary>
        public double ReverbTime
        {
            get => Parameters.fReverbTime;
            set
            {
                Parameters.fReverbTime = (float)value;

                OnPropertyChanged();
            }
        }

        /// <summary>
        /// In the range from 0.001 through 0.999. The default value is 0.001.
        /// </summary>
        public double HighFreqRTRatio
        {
            get => Parameters.fHighFreqRTRatio;
            set
            {
                Parameters.fHighFreqRTRatio = (float)value;

                OnPropertyChanged();
            }
        }
    }
}


text:
/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 *    TrainingSetEvent.java
 *    Copyright (C) 2002 University of Waikato, Hamilton, New Zealand
 *
 */

package weka.gui.beans;

import weka.core.Instances;

import java.util.EventObject;

/**
 * Event encapsulating a training set
 *
 * @author Mark Hall
 * @version $Revision: 4761 $
 */
public class TrainingSetEvent
  extends EventObject {

  /** for serialization */
  private static final long serialVersionUID = 5872343811810872662L;

  /**
   * The training instances
   */
  protected Instances m_trainingSet;
  private boolean m_structureOnly;

  /**
   * What run number is this training set from.
   */
  protected int m_runNumber = 1;

  /**
   * Maximum number of runs.
   */
  protected int m_maxRunNumber = 1;

  /**
   * what number is this training set (ie fold 2 of 10 folds)
   */
  protected int m_setNumber;

  /**
   * Maximum number of sets (ie 10 in a 10 fold)
   */
  protected int m_maxSetNumber;

  /**
   * Creates a new TrainingSetEvent
   *
   * @param source the source of the event
   * @param trainSet the training instances
   */
  public TrainingSetEvent(Object source, Instances trainSet) {
    super(source);
    m_trainingSet = trainSet;
    if (m_trainingSet != null && m_trainingSet.numInstances() == 0) {
      m_structureOnly = true;
    }
  }

  /**
   * Creates a new TrainingSetEvent
   *
   * @param source the source of the event
   * @param trainSet the training instances
   * @param setNum the number of the training set
   * @param maxSetNum the maximum number of sets
   */
  public TrainingSetEvent(Object source, Instances trainSet, int setNum, int maxSetNum) {
    this(source, trainSet);
    m_setNumber = setNum;
    m_maxSetNumber = maxSetNum;
  }

  /**
   * Creates a new TrainingSetEvent
   *
   * @param source the source of the event
   * @param trainSet the training instances
   * @param runNum the run number that the training set belongs to
   * @param maxRunNum the maximum run number
   * @param setNum the number of the training set
   * @param maxSetNum the maximum number of sets
   */
  public TrainingSetEvent(Object source, Instances trainSet, int runNum,
      int maxRunNum, int setNum, int maxSetNum) {
    this(source, trainSet, setNum, maxSetNum);

    m_runNumber = runNum;
    m_maxRunNumber = maxRunNum;
  }

  /**
   * Get the training instances
   *
   * @return an Instances value
   */
  public Instances getTrainingSet() {
    return m_trainingSet;
  }

  /**
   * Get the run number that this training set belongs to.
   *
   * @return the run number for this training set.
   */
  public int getRunNumber() {
    return m_runNumber;
  }

  /**
   * Get the maximum number of runs.
   *
   * @return return the maximum number of runs.
   */
  public int getMaxRunNumber() {
    return m_maxRunNumber;
  }

  /**
   * Get the set number (eg. fold 2 of a 10 fold split)
   *
   * @return an int value
   */
  public int getSetNumber() {
    return m_setNumber;
  }

  /**
   * Get the maximum set number
   *
   * @return an int value
   */
  public int getMaxSetNumber() {
    return m_maxSetNumber;
  }

  /**
   * Returns true if the encapsulated instances
   * contain just header information
   *
   * @return true if only header information is
   * available in this DataSetEvent
   */
  public boolean isStructureOnly() {
    return m_structureOnly;
  }
}