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

#ifndef RCLCPP__CONTEXT_HPP_
#define RCLCPP__CONTEXT_HPP_

#include <condition_variable>
#include <functional>
#include <memory>
#include <mutex>
#include <string>
#include <typeindex>
#include <typeinfo>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

#include "rcl/context.h"
#include "rcl/guard_condition.h"
#include "rcl/wait.h"
#include "rclcpp/init_options.hpp"
#include "rclcpp/macros.hpp"
#include "rclcpp/visibility_control.hpp"

namespace rclcpp
{

/// Thrown when init is called on an already initialized context.
class ContextAlreadyInitialized : public std::runtime_error
{
public:
  ContextAlreadyInitialized()
  : std::runtime_error("context is already initialized") {}
};

/// Forward declare WeakContextsWrapper
class WeakContextsWrapper;

class ShutdownCallbackHandle
{
  friend class Context;

public:
  using ShutdownCallbackType = std::function<void ()>;

private:
  std::weak_ptr<ShutdownCallbackType> callback;
};

using OnShutdownCallbackHandle = ShutdownCallbackHandle;
using PreShutdownCallbackHandle = ShutdownCallbackHandle;

/// Context which encapsulates shared state between nodes and other similar entities.
/**
 * A context also represents the lifecycle between init and shutdown of rclcpp.
 * It is often used in conjunction with rclcpp::init, or rclcpp::init_local,
 * and rclcpp::shutdown.
 */
class Context : public std::enable_shared_from_this<Context>
{
public:
  RCLCPP_SMART_PTR_DEFINITIONS(Context)

  /// Default constructor, after which the Context is still not "initialized".
  /**
   * Every context which is constructed is added to a global vector of contexts,
   * which is used by the signal handler to conditionally shutdown each context
   * on SIGINT.
   * See the shutdown_on_signal option in the InitOptions class.
   */
  RCLCPP_PUBLIC
  Context();

  RCLCPP_PUBLIC
  virtual
  ~Context();

  /// Initialize the context, and the underlying elements like the rcl context.
  /**
   * This method must be called before passing this context to things like the
   * constructor of Node.
   * It must also be called before trying to shutdown the context.
   *
   * Note that this function does not setup any signal handlers, so if you want
   * it to be shutdown by the signal handler, then you need to either install
   * them manually with rclcpp::install_signal_handlers() or use rclcpp::init().
   * In addition to installing the signal handlers, the shutdown_on_signal
   * of the InitOptions needs to be `true` for this context to be shutdown by
   * the signal handler, otherwise it will be passed over.
   *
   * After calling this method, shutdown() can be called to invalidate the
   * context for derived entities, e.g. nodes, guard conditions, etc.
   * However, the underlying rcl context is not finalized until this Context's
   * destructor is called or this function is called again.
   * Allowing this class to go out of scope and get destructed or calling this
   * function a second time while derived entities are still using the context
   * is undefined behavior and should be avoided.
   * It's a good idea to not reuse context objects and instead create a new one
   * each time you need to shutdown and init again.
   * This allows derived entities to hold on to shard pointers to the first
   * context object until they are done.
   *
   * This function is thread-safe.
   *
   * \param[in] argc number of arguments
   * \param[in] argv argument array which may contain arguments intended for ROS
   * \param[in] init_options initialization options for rclcpp and underlying layers
   * \throw ContextAlreadyInitialized if called if init is called more than once
   * \throws anything rclcpp::exceptions::throw_from_rcl_error can throw.
   * \throws std::runtime_error if the global logging configure mutex is NULL
   * \throws exceptions::UnknownROSArgsError if there are unknown ROS arguments
   */
  RCLCPP_PUBLIC
  virtual
  void
  init(
    int argc,
    char const * const * argv,
    const rclcpp::InitOptions & init_options = rclcpp::InitOptions());

  /// Return true if the context is valid, otherwise false.
  /**
   * The context is valid if it has been initialized but not shutdown.
   *
   * This function is thread-safe.
   * This function is lock free so long as pointers and uint64_t atomics are
   * lock free.
   *
   * \return true if valid, otherwise false
   */
  RCLCPP_PUBLIC
  bool
  is_valid() const;

  /// Return the init options used during init.
  RCLCPP_PUBLIC
  const rclcpp::InitOptions &
  get_init_options() const;

  /// Return a copy of the init options used during init.
  RCLCPP_PUBLIC
  rclcpp::InitOptions
  get_init_options();

  /// Return actual domain id.
  RCLCPP_PUBLIC
  size_t
  get_domain_id() const;

  /// Return the shutdown reason, or empty string if not shutdown.
  /**
   * This function is thread-safe.
   */
  RCLCPP_PUBLIC
  std::string
  shutdown_reason() const;

  /// Shutdown the context, making it uninitialized and therefore invalid for derived entities.
  /**
   * Several things happen when the context is shutdown, in this order:
   *
   * - acquires a lock to prevent race conditions with init, on_shutdown, etc.
   * - if the context is not initialized, return false
   * - rcl_shutdown() is called on the internal rcl_context_t instance
   * - the shutdown reason is set
   * - each on_shutdown callback is called, in the order that they were added
   * - interrupt blocking sleep_for() calls, so they return early due to shutdown
   * - interrupt blocking executors and wait sets
   *
   * The underlying rcl context is not finalized by this function.
   *
   * This function is thread-safe.
   *
   * Note that if you override this method, but leave shutdown to be called in
   * the destruction of this base class, it will not call the overridden
   * version from your base class.
   * So you need to ensure you call your class's shutdown() in its destructor.
   *
   * \param[in] reason the description of why shutdown happened
   * \return true if shutdown was successful, false if context was already shutdown
   * \throw various exceptions derived from rclcpp::exceptions::RCLError, if rcl_shutdown fails
   */
  RCLCPP_PUBLIC
  virtual
  bool
  shutdown(const std::string & reason);

  using OnShutdownCallback = OnShutdownCallbackHandle::ShutdownCallbackType;

  /// Add a on_shutdown callback to be called when shutdown is called for this context.
  /**
   * These callbacks will be called in the order they are added as the second
   * to last step in shutdown().
   *
   * When shutdown occurs due to the signal handler, these callbacks are run
   * asynchronously in the dedicated singal handling thread.
   *
   * Also, shutdown() may be called from the destructor of this function.
   * Therefore, it is not safe to throw exceptions from these callbacks.
   * Instead, log errors or use some other mechanism to indicate an error has
   * occurred.
   *
   * On shutdown callbacks may be registered before init and after shutdown,
   * and persist on repeated init's.
   *
   * \param[in] callback the on shutdown callback to be registered
   * \return the callback passed, for convenience when storing a passed lambda
   */
  RCLCPP_PUBLIC
  virtual
  OnShutdownCallback
  on_shutdown(OnShutdownCallback callback);

  /// Add a on_shutdown callback to be called when shutdown is called for this context.
  /**
   * These callbacks will be called in the order they are added as the second
   * to last step in shutdown().
   *
   * When shutdown occurs due to the signal handler, these callbacks are run
   * asynchronously in the dedicated signal handling thread.
   *
   * Also, shutdown() may be called from the destructor of this function.
   * Therefore, it is not safe to throw exceptions from these callbacks.
   * Instead, log errors or use some other mechanism to indicate an error has
   * occurred.
   *
   * On shutdown callbacks may be registered before init and after shutdown,
   * and persist on repeated init's.
   *
   * \param[in] callback the on_shutdown callback to be registered
   * \return the created callback handle
   */
  RCLCPP_PUBLIC
  virtual
  OnShutdownCallbackHandle
  add_on_shutdown_callback(OnShutdownCallback callback);

  /// Remove an registered on_shutdown callbacks.
  /**
   * \param[in] callback_handle the on_shutdown callback handle to be removed.
   * \return true if the callback is found and removed, otherwise false.
   */
  RCLCPP_PUBLIC
  virtual
  bool
  remove_on_shutdown_callback(const OnShutdownCallbackHandle & callback_handle);

  using PreShutdownCallback = PreShutdownCallbackHandle::ShutdownCallbackType;

  /// Add a pre_shutdown callback to be called before shutdown is called for this context.
  /**
   * These callbacks will be called in the order they are added.
   *
   * When shutdown occurs due to the signal handler, these callbacks are run
   * asynchronously in the dedicated signal handling thread.
   *
   * \param[in] callback the pre_shutdown callback to be registered
   * \return the created callback handle
   */
  RCLCPP_PUBLIC
  virtual
  PreShutdownCallbackHandle
  add_pre_shutdown_callback(PreShutdownCallback callback);

  /// Remove an registered pre_shutdown callback.
  /**
   * \param[in] callback_handle the pre_shutdown callback handle to be removed.
   * \return true if the callback is found and removed, otherwise false.
   */
  RCLCPP_PUBLIC
  virtual
  bool
  remove_pre_shutdown_callback(const PreShutdownCallbackHandle & callback_handle);

  /// Return the shutdown callbacks.
  /**
   * Returned callbacks are a copy of the registered callbacks.
   */
  RCLCPP_PUBLIC
  std::vector<OnShutdownCallback>
  get_on_shutdown_callbacks() const;

  /// Return the pre-shutdown callbacks.
  /**
   * Returned callbacks are a copy of the registered callbacks.
   */
  RCLCPP_PUBLIC
  std::vector<PreShutdownCallback>
  get_pre_shutdown_callbacks() const;

  /// Return the internal rcl context.
  RCLCPP_PUBLIC
  std::shared_ptr<rcl_context_t>
  get_rcl_context();

  /// Sleep for a given period of time or until shutdown() is called.
  /**
   * This function can be interrupted early if:
   *
   *   - this context is shutdown()
   *   - this context is destructed (resulting in shutdown)
   *   - this context has shutdown_on_signal=true and SIGINT/SIGTERM occurs (resulting in shutdown)
   *   - interrupt_all_sleep_for() is called
   *
   * \param[in] nanoseconds A std::chrono::duration representing how long to sleep for.
   * \return true if the condition variable did not timeout, i.e. you were interrupted.
   */
  RCLCPP_PUBLIC
  bool
  sleep_for(const std::chrono::nanoseconds & nanoseconds);

  /// Interrupt any blocking sleep_for calls, causing them to return immediately and return true.
  RCLCPP_PUBLIC
  void
  interrupt_all_sleep_for();

  /// Return a singleton instance for the SubContext type, constructing one if necessary.
  template<typename SubContext, typename ... Args>
  std::shared_ptr<SubContext>
  get_sub_context(Args && ... args)
  {
    std::lock_guard<std::recursive_mutex> lock(sub_contexts_mutex_);

    std::type_index type_i(typeid(SubContext));
    std::shared_ptr<SubContext> sub_context;
    auto it = sub_contexts_.find(type_i);
    if (it == sub_contexts_.end()) {
      // It doesn't exist yet, make it
      sub_context = std::shared_ptr<SubContext>(
        new SubContext(std::forward<Args>(args) ...),
        [](SubContext * sub_context_ptr) {
          delete sub_context_ptr;
        });
      sub_contexts_[type_i] = sub_context;
    } else {
      // It exists, get it out and cast it.
      sub_context = std::static_pointer_cast<SubContext>(it->second);
    }
    return sub_context;
  }

protected:
  // Called by constructor and destructor to clean up by finalizing the
  // shutdown rcl context and preparing for a new init cycle.
  RCLCPP_PUBLIC
  void
  clean_up();

private:
  RCLCPP_DISABLE_COPY(Context)

  // This mutex is recursive so that the destructor can ensure atomicity
  // between is_initialized and shutdown.
  mutable std::recursive_mutex init_mutex_;
  std::shared_ptr<rcl_context_t> rcl_context_;
  rclcpp::InitOptions init_options_;
  std::string shutdown_reason_;

  // Keep shared ownership of the global logging mutex.
  std::shared_ptr<std::recursive_mutex> logging_mutex_;

  std::unordered_map<std::type_index, std::shared_ptr<void>> sub_contexts_;
  // This mutex is recursive so that the constructor of a sub context may
  // attempt to acquire another sub context.
  std::recursive_mutex sub_contexts_mutex_;

  std::unordered_set<std::shared_ptr<OnShutdownCallback>> on_shutdown_callbacks_;
  mutable std::mutex on_shutdown_callbacks_mutex_;

  std::unordered_set<std::shared_ptr<PreShutdownCallback>> pre_shutdown_callbacks_;
  mutable std::mutex pre_shutdown_callbacks_mutex_;

  /// Condition variable for timed sleep (see sleep_for).
  std::condition_variable interrupt_condition_variable_;
  /// Mutex for protecting the global condition variable.
  std::mutex interrupt_mutex_;

  /// Keep shared ownership of global vector of weak contexts
  std::shared_ptr<WeakContextsWrapper> weak_contexts_;

  enum class ShutdownType
  {
    pre_shutdown,
    on_shutdown
  };

  using ShutdownCallback = ShutdownCallbackHandle::ShutdownCallbackType;

  RCLCPP_LOCAL
  ShutdownCallbackHandle
  add_shutdown_callback(
    ShutdownType shutdown_type,
    ShutdownCallback callback);

  RCLCPP_LOCAL
  bool
  remove_shutdown_callback(
    ShutdownType shutdown_type,
    const ShutdownCallbackHandle & callback_handle);

  std::vector<rclcpp::Context::ShutdownCallback>
  get_shutdown_callback(ShutdownType shutdown_type) const;
};

/// Return a copy of the list of context shared pointers.
/**
 * This function is thread-safe.
 */
RCLCPP_PUBLIC
std::vector<Context::SharedPtr>
get_contexts();

}  // namespace rclcpp

#endif  // RCLCPP__CONTEXT_HPP_


text:
Game::Game()
{
  m_IsDone = false;
  m_Interval = 0.25f;
  m_ElapsedTime = 0.0f;
  m_FrameCount = 0;
  m_FramesPerSecond = 0;
  m_ObjectCount = 0;
  m_State = STATE_MENU;
  m_IsSinglePlayer = true;
  m_IsDebugShown = false;
}

Game::~Game()
{
}

bool Game::Run()
{
  if (!OnStart())
  {
    return false;
  }

  while (!m_IsDone)
  {
    OnThink();
    OnUpdate();
    OnRender();
  }

  OnEnd();

  return true;
}

bool Game::OnStart()
{
  if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
  {
    SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Unable to initialize SDL: %s", SDL_GetError());
    return false;
  }
  SDL_Log("Initializing SDL... complete!");

  if (TTF_Init() < 0)
  {
    SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Unable to initialize SDL_TTF: %s", SDL_GetError());
    return false;
  }
  SDL_Log("Initializing TTF... complete!");

  if (Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 1024) < 0)
  {
    SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Unable to initialize SDL_Mixer: %s", SDL_GetError());
    return false;
  }
  SDL_Log("Initializing audio... complete!");

  m_Window = SDL_CreateWindow("Ace of Space", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, c_ScreenWidth, c_ScreenHeight, 0);
  if (m_Window == nullptr)
  {
    SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Failed to initialize the window.");
    return false;
  }
  SDL_Log("Initializing window... complete!");

  m_Renderer = SDL_CreateRenderer(m_Window, -1, SDL_RENDERER_ACCELERATED);
  if (m_Renderer == nullptr)
  {
    SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Failed to initialize the renderer.");
    return false;
  }
  SDL_Log("Initializing renderer... complete!");

  SDL_ShowCursor(SDL_DISABLE);
  SDL_SetRenderDrawBlendMode(m_Renderer, SDL_BLENDMODE_BLEND);

  if (!m_Font10.Load(m_Renderer, c_FontFilename, 10, TTF_STYLE_NORMAL, TTF_HINTING_LIGHT) ||
      !m_Font14.Load(m_Renderer, c_FontFilename, 14, TTF_STYLE_NORMAL, TTF_HINTING_LIGHT) ||
      !m_Font16.Load(m_Renderer, c_FontFilename, 16, TTF_STYLE_NORMAL, TTF_HINTING_LIGHT) ||
      !m_Font20.Load(m_Renderer, c_FontFilename, 20, TTF_STYLE_NORMAL, TTF_HINTING_LIGHT) ||
      !m_Font25.Load(m_Renderer, c_FontFilename, 25, TTF_STYLE_NORMAL, TTF_HINTING_LIGHT) ||
      !m_Font35.Load(m_Renderer, c_FontFilename, 35, TTF_STYLE_NORMAL, TTF_HINTING_LIGHT))
  {
    return false;
  }

  if (!Texture::LoadTextures(m_Renderer) || !Sound::LoadSounds())
  {
    return false;
  }

  Sound::PlaySound("Intro");

  return true;
}

void Game::OnEnd()
{
  m_Font10.Unload();
  m_Font14.Unload();
  m_Font16.Unload();
  m_Font20.Unload();
  m_Font25.Unload();
  m_Font35.Unload();

  Texture::UnloadTextures();
  Sound::UnloadSounds();
  Player::RemovePlayers();
  Object::RemoveAll();

  Mix_CloseAudio();
  SDL_Log("Closing SDL_Mixer... complete!");

  TTF_Quit();
  SDL_Log("Closing SDL_TTF... complete!");

  SDL_DestroyRenderer(m_Renderer);
  SDL_DestroyWindow(m_Window);
  SDL_Quit();
  SDL_Log("Closing SDL... complete!");
}

void Game::OnThink()
{
  while (SDL_PollEvent(&m_Event))
  {
    Uint32 type = m_Event.type;
    SDL_Keycode key = m_Event.key.keysym.sym;

    switch (type)
    {
      case SDL_QUIT:
        m_IsDone = true;
        break;
      case SDL_KEYDOWN:
        switch (key)
        {
          case SDLK_ESCAPE:
            m_IsDone = true;
            break;
          case SDLK_TAB:
            m_IsDebugShown = !m_IsDebugShown;
            break;
        }
        break;
    }

    switch (m_State)
    {
      case STATE_MENU:
        switch (type)
        {
          case SDL_KEYDOWN:
            switch (key)
            {
              case SDLK_RETURN:
                m_Level.BuildLevel();
                Player::AddPlayers();
                Player::SpawnPlayer(PLAYER_ONE);
                if (!m_IsSinglePlayer)
                {
                  Player::SpawnPlayer(PLAYER_TWO);
                }
                Sound::PlaySound("Theme");
                m_State = STATE_PLAYING;
                break;
              case SDLK_1:
                m_IsSinglePlayer = !m_IsSinglePlayer;
                break;
              case SDLK_2:
                m_State = STATE_CONTROLS;
                break;
              case SDLK_3:
                m_State = STATE_CREDITS;
                break;
            }
            break;
        }
        break;
      case STATE_GAMEOVER:
      case STATE_VICTORY:
        switch (type)
        {
          case SDL_KEYDOWN:
            switch (key)
            {
              case SDLK_RETURN:
                Player::RemovePlayers();
                Boss::RemoveBoss();
                Object::RemoveAll();
                Sound::PlaySound("Intro");
                m_State = STATE_MENU;
                break;
            }
            break;
        }
        break;
      case STATE_CONTROLS:
      case STATE_CREDITS:
        switch (type)
        {
          case SDL_KEYDOWN:
            switch (key)
            {
              case SDLK_RETURN:
                m_State = STATE_MENU;
                break;
            }
            break;
        }
        break;
      case STATE_PLAYING:
        Player::ProcessInput(type, key);
        switch (type)
        {
          case SDL_KEYDOWN:
            switch (key)
            {
              case SDLK_RSHIFT:
                m_IsSinglePlayer = false;
                break;
              case SDLK_RETURN:
                m_State = STATE_PAUSED;
                break;
            }
            break;
        }
        break;
      case STATE_PAUSED:
        switch (type)
        {
          case SDL_KEYDOWN:
            switch (key)
            {
              case SDLK_RETURN:
                m_State = STATE_PLAYING;
                break;
            }
            break;
        }
        break;
    }
  }
}

void Game::OnUpdate()
{
  float deltaTime = m_Timer.GetDeltaTime();

  switch (m_State)
  {
    case STATE_PLAYING:
      Object::UpdateObjects(deltaTime);
      m_Level.Update(deltaTime);
      m_Starfield.Update(deltaTime);
      bool isSinglePlayerDead = m_IsSinglePlayer && Player::Players[0].GetLives()  <= 0;
      bool isTwoPlayerDead = !m_IsSinglePlayer && Player::Players[0].GetLives() + Player::Players[1].GetLives() <= 0;
      if (isSinglePlayerDead || isTwoPlayerDead)
      {
        Sound::PlaySound("GameOver");
        m_State = STATE_GAMEOVER;
      }
      if (Boss::FinalBoss.IsSpawned() && Boss::FinalBoss.IsKilled())
      {
        Sound::PlaySound("Victory");
        m_State = STATE_VICTORY;
      }
      break;
  }

  ++m_FrameCount;
  m_ElapsedTime += deltaTime;
  if (m_ElapsedTime >= m_Interval)
  {
    m_FramesPerSecond = static_cast<int>(m_FrameCount / m_Interval);
    m_ObjectCount = static_cast<int>(Object::ObjectList.size());
    m_ElapsedTime = 0.0f;
    m_FrameCount = 0;
  }
}

void Game::OnRender()
{
  SDL_SetRenderDrawColor(m_Renderer, 0, 0, 0, 255);
  SDL_RenderClear(m_Renderer);

  switch (m_State)
  {
    case STATE_MENU:
      DrawTitle();
      break;
    case STATE_CONTROLS:
      DrawControls();
      break;
    case STATE_CREDITS:
      DrawCredits();
      break;
    case STATE_PLAYING:
      Object::RenderObjects(m_Renderer);
      DrawHUD();
      break;
    case STATE_PAUSED:
      Object::RenderObjects(m_Renderer);
      DrawHUD();
      DrawPaused();
      break;
    case STATE_GAMEOVER:
      Object::RenderObjects(m_Renderer);
      DrawHUD();
      DrawGameOver();
      break;
    case STATE_VICTORY:
      Object::RenderObjects(m_Renderer);
      DrawHUD();
      DrawVictory();
      break;
  }

  if (m_IsDebugShown)
  {
    DrawDebug();
  }

  SDL_RenderPresent(m_Renderer);
}

void Game::DrawHUD()
{
  // Player 1 HUD
  SDL_Rect health1 = { 20, c_ScreenHeight - 25, 200, 10 };
  Graphics::FillRectangle(m_Renderer, health1, Color::DarkGray);

  const PlayerShip* playerShip1 = Player::Players[0].GetPlayerShip();
  if (playerShip1 != nullptr)
  {
    health1.w = playerShip1->GetHealth() * 2;
    Graphics::FillRectangle(m_Renderer, health1, Color::DarkRed);
  }

  for (int i = 0; i < Player::Players[0].GetLives(); ++i)
  {
    SDL_Rect box = { (i + 1) * 20, c_ScreenHeight - 45, 10, 10 };
    Graphics::FillRectangle(m_Renderer, box, Color::White);
  }

  // Player 2 HUD
  if (!m_IsSinglePlayer)
  {
    SDL_Rect health2 = { c_ScreenWidth - 220, c_ScreenHeight - 25, 200, 10 };
    Graphics::FillRectangle(m_Renderer, health2, Color::DarkGray);

    const PlayerShip* playerShip2 = Player::Players[1].GetPlayerShip();
    if (playerShip2 != nullptr)
    {
      health2.x = c_ScreenWidth - 220 + (c_PlayerHealth - playerShip2->GetHealth()) * 2;
      health2.w = playerShip2->GetHealth() * 2;
      Graphics::FillRectangle(m_Renderer, health2, Color::DarkBlue);
    }

    for (int i = 0; i < Player::Players[1].GetLives(); ++i)
    {
      SDL_Rect box = { c_ScreenWidth - 10 - (i + 1) * 20, c_ScreenHeight - 45, 10, 10 };
      Graphics::FillRectangle(m_Renderer, box, Color::White);
    }
  }

  // Display Score
  std::stringstream ss;
  ss << Player::Players[0].GetScore();
  Graphics::DrawText(m_Renderer, m_Font10, "SCORE", c_HalfScreenWidth, c_ScreenHeight - 35, Color::White);
  Graphics::DrawText(m_Renderer, m_Font16, ss.str(), c_HalfScreenWidth, c_ScreenHeight - 20, Color::White);

  // Boss HUD
  if (Boss::FinalBoss.IsSpawned() && !Boss::FinalBoss.IsKilled())
  {
    int barWidth = c_ScreenWidth - 40;
    SDL_Rect boss = { 20, 20, barWidth, 10 };
    Graphics::FillRectangle(m_Renderer, boss, Color::DarkGray);

    const BossEnemy* bossEnemy = Boss::FinalBoss.GetBossEnemy();
    if (bossEnemy != nullptr)
    {
      boss.w = bossEnemy->GetHealth() / c_BossHealth * barWidth;
      Graphics::FillRectangle(m_Renderer, boss, Color::DarkGreen);
    }
  }
}

void Game::DrawTitle()
{
  Texture* titleTexture = Texture::TextureList["Title"];
  SDL_Rect titleRect = { c_HalfScreenWidth - titleTexture->GetWidth() / 2, c_HalfScreenHeight - titleTexture->GetHeight() / 2 - 100, titleTexture->GetWidth(), titleTexture->GetHeight() };
  SDL_RenderCopy(m_Renderer, titleTexture->GetTexture(0), nullptr, &titleRect);

  Graphics::DrawText(m_Renderer, m_Font25, "Press ENTER to Start", c_HalfScreenWidth, c_HalfScreenHeight + 75, Color::White);
  Graphics::DrawText(m_Renderer, m_Font20, (m_IsSinglePlayer ? "1-Player" : "2-Player"), c_HalfScreenWidth, c_HalfScreenHeight + 100, Color::White);

  Graphics::DrawText(m_Renderer, m_Font20, "Players", c_HalfScreenWidth - 100, c_HalfScreenHeight + 150, Color::White);
  Graphics::DrawText(m_Renderer, m_Font20, "(1)", c_HalfScreenWidth + 100, c_HalfScreenHeight + 150, Color::White);

  Graphics::DrawText(m_Renderer, m_Font20, "Controls", c_HalfScreenWidth - 100, c_HalfScreenHeight + 175, Color::White);
  Graphics::DrawText(m_Renderer, m_Font20, "(2)", c_HalfScreenWidth + 100, c_HalfScreenHeight + 175, Color::White);

  Graphics::DrawText(m_Renderer, m_Font20, "Credits", c_HalfScreenWidth - 100, c_HalfScreenHeight + 200, Color::White);
  Graphics::DrawText(m_Renderer, m_Font20, "(3)", c_HalfScreenWidth + 100, c_HalfScreenHeight + 200, Color::White);

  Graphics::DrawText(m_Renderer, m_Font20, "Debug", c_HalfScreenWidth - 100, c_HalfScreenHeight + 225, Color::White);
  Graphics::DrawText(m_Renderer, m_Font20, "(Tab)", c_HalfScreenWidth + 100, c_HalfScreenHeight + 225, Color::White);

  Graphics::DrawText(m_Renderer, m_Font20, "Exit", c_HalfScreenWidth - 100, c_HalfScreenHeight + 250, Color::White);
  Graphics::DrawText(m_Renderer, m_Font20, "(Esc)", c_HalfScreenWidth + 100, c_HalfScreenHeight + 250, Color::White);
}

void Game::DrawControls()
{
  Texture* keyTexture = Texture::TextureList["Keyboard"];
  SDL_Rect keyRect = { c_HalfScreenWidth - keyTexture->GetWidth() / 2, c_HalfScreenHeight - keyTexture->GetHeight() / 2, keyTexture->GetWidth(), keyTexture->GetHeight() };
  SDL_RenderCopy(m_Renderer, keyTexture->GetTexture(0), nullptr, &keyRect);

  Graphics::DrawText(m_Renderer, m_Font35, "CONTROLS", c_HalfScreenWidth, 40, Color::White);
  Graphics::DrawText(m_Renderer, m_Font16, "Press ENTER to Return to Main Menu", c_HalfScreenWidth, c_ScreenHeight - 40, Color::White);
}

void Game::DrawCredits()
{
  Graphics::DrawText(m_Renderer, m_Font35, "CREDITS", c_HalfScreenWidth, 40, Color::White);

  Graphics::DrawText(m_Renderer, m_Font14, "Programming", c_HalfScreenWidth, 150, Color::White);
  Graphics::DrawText(m_Renderer, m_Font25, "Jason Norris", c_HalfScreenWidth, 170, Color::White);

  Graphics::DrawText(m_Renderer, m_Font14, "Programming", c_HalfScreenWidth, 250, Color::White);
  Graphics::DrawText(m_Renderer, m_Font25, "Jason Norris", c_HalfScreenWidth, 270, Color::White);

  Graphics::DrawText(m_Renderer, m_Font14, "Programming", c_HalfScreenWidth, 350, Color::White);
  Graphics::DrawText(m_Renderer, m_Font25, "Jason Norris", c_HalfScreenWidth, 370, Color::White);

  Graphics::DrawText(m_Renderer, m_Font16, "Press ENTER to Return to Main Menu", c_HalfScreenWidth, c_ScreenHeight - 40, Color::White);
}

void Game::DrawPaused()
{
  SDL_Rect rect = { 0, 0, c_ScreenWidth, c_ScreenHeight };
  Graphics::FillRectangle(m_Renderer, rect, Color::BlackTransparent);
  Graphics::DrawText(m_Renderer, m_Font35, "PAUSED", c_HalfScreenWidth, c_HalfScreenHeight, Color::White);
}

void Game::DrawGameOver()
{
  SDL_Rect rect = { 0, 0, c_ScreenWidth, c_ScreenHeight };
  Graphics::FillRectangle(m_Renderer, rect, Color::RedTransparent);
  Graphics::DrawText(m_Renderer, m_Font35, "FAILURE", c_HalfScreenWidth, c_HalfScreenHeight, Color::Red);
  Graphics::DrawText(m_Renderer, m_Font14, "Press ENTER to Return to Main Menu", c_HalfScreenWidth, c_HalfScreenHeight + 50, Color::Red);
}

void Game::DrawVictory()
{
  SDL_Rect rect = { 0, 0, c_ScreenWidth, c_ScreenHeight };
  Graphics::FillRectangle(m_Renderer, rect, Color::GreenTransparent);
  Graphics::DrawText(m_Renderer, m_Font35, "SUCCESS", c_HalfScreenWidth, c_HalfScreenHeight, Color::Green);
  Graphics::DrawText(m_Renderer, m_Font14, "Press ENTER to Return to Main Menu", c_HalfScreenWidth, c_HalfScreenHeight + 50, Color::Green);
}

void Game::DrawDebug()
{
  std::stringstream ss;
  ss << "FPS: " << m_FramesPerSecond << "\nObjects: " << m_ObjectCount;
  Graphics::DrawText(m_Renderer, m_Font14, ss.str(), 10, 10, Color::White, false);
}

redpajama_set_name: RedPajamaGithub


text:
package betterwithaddons.tileentity;

import betterwithaddons.block.BlockRopePost;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;

public class TileEntityRopePost extends TileEntityBase {
    ItemStack plankStack = ItemStack.EMPTY;
    IBlockState fenceState;

    public void setPlanks(ItemStack stack)
    {
        plankStack = stack;
        validateState();
        markDirty();
    }

    public ItemStack getPlanks()
    {
        return plankStack;
    }

    public void setFenceState(IBlockState state)
    {
        fenceState = state;
        validateState();
        markDirty();
    }

    public IBlockState getFenceState() { return fenceState; }

    public void validateState()
    {
        if(world  == null)
            return;
        IBlockState state = world.getBlockState(pos);
        if(state.getBlock() instanceof BlockRopePost)
        {
            if(state.getValue(BlockRopePost.HAS_PLANKS) == plankStack.isEmpty())
                world.setBlockState(pos,state.withProperty(BlockRopePost.HAS_PLANKS,!plankStack.isEmpty()));
            if(state.getValue(BlockRopePost.HAS_POST) == (fenceState == null))
                world.setBlockState(pos,state.withProperty(BlockRopePost.HAS_POST,fenceState != null));
        }
    }

    @Override
    public void writeDataToNBT(NBTTagCompound compound) {
        if (fenceState != null) {
            compound.setString("Fence", Block.REGISTRY.getNameForObject(fenceState.getBlock()).toString());
            compound.setInteger("FenceMeta", fenceState.getBlock().getMetaFromState(fenceState));
        }
        if(!plankStack.isEmpty())
            compound.setTag("Planks",plankStack.serializeNBT());
    }

    @Override
    public void readDataFromNBT(NBTTagCompound compound) {
        if(compound.hasKey("Fence") && compound.hasKey("FenceMeta"))
        {
            Block block = Block.getBlockFromName(compound.getString("Fence"));
            if(block != Blocks.AIR)
                fenceState = block.getStateFromMeta(compound.getInteger("FenceMeta"));
        }
        if(compound.hasKey("Planks"))
            setPlanks(new ItemStack(compound.getCompoundTag("Planks")));
    }

    @Override
    public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newState) {
        return oldState.getBlock() != newState.getBlock();
    }
}


text:
'use strict';

module.exports = function (sequelize, DataTypes) {
  var UserMessage = sequelize.define('UserMessage', {
    'status': DataTypes.STRING
  }, {
    'classMethods': {
      associate: function associate(models) {
        UserMessage.belongsTo(models.User);
      }
    }
  });
  return UserMessage;
};


text:
typedef struct {
    int charge;
    std::vector <int> indexList;
} isoChain;

namespace pwiz {
namespace analysis {

using chemistry::MZTolerance;

// Deisotope high resolution ms2 spectra

struct PWIZ_API_DECL MS2Deisotoper : public SpectrumDataFilter
{
     /// PrecursorMassFilter's parameters
    struct PWIZ_API_DECL Config
    {
        Config(MZTolerance tol = MZTolerance(0.5), bool hires_ = false, bool poisson_ = false, int maxCharge_ = 3, int minCharge_ = 1)
            : matchingTolerance(tol), hires(hires_), poisson(poisson_), maxCharge(maxCharge_), minCharge(minCharge_) {}

        MZTolerance matchingTolerance;
        bool hires;
        bool poisson;
        int maxCharge;
        int minCharge;
    };

    MS2Deisotoper(const MS2Deisotoper::Config params_) : params(params_) {}
    virtual void operator () (const pwiz::msdata::SpectrumPtr) const;
    virtual void describe(pwiz::msdata::ProcessingMethod&) const;

    const MS2Deisotoper::Config params;
};

} // namespace analysis
} // namespace pwiz

#endif // _MS2DEISOTOPER_HPP_


text:
cd E:/04-MyProject/Weber/WBER.CMS/03.SourceCode/WBER.EMS.Customer.Website/assets/css
sass import.scss:custom.css


text:
#!/usr/bin/node
var server = require('net').createServer();
var fs = require('fs');

server.on('connection', function(socket) {
  console.log('new connection from', socket.remoteAddress);

  socket.setEncoding('utf8');

  socket.on('data', function(data) {
    /*
    var cmd = data.slice(0, data.length-2);

    console.log(socket.remoteAddress + ':' + socket.remotePort + ' > ' + cmd);

    switch(cmd) {
      case 'ls':
        var files = fs.readdirSync(__dirname);
        files.forEach(function(f) {
          socket.write(f + '\r\n');
        });
        break;

      case 'quit':
        server.close();
        process.exit(0);

      default:
        break;
    }
    */
    console.log(data.length, data);
  });

  socket.on('end', function() {
    console.log(socket.remoteAddress, 'disconnected');
  });
}).listen(8080, function() {
  console.log('TCP server is listening on port 8080');
});


text:
<TITLE>Review for Paradise Lost: The Child Murders at Robin Hood Hills (1996)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Paradise Lost: The Child Murders at Robin Hood Hills (1996)

reviewed by
Michael J. Legeros

                         Paradise Lost (1996)
                   A film review by Michael J. Legeros
                    Copyright 1996 Michael J. Legeros

PARADISE LOST

Directed by     Joe Berlinger and Bruce Sinofsky
Produced by     Joe Berlinger and Bruce Sinofsky
MPAA Rating     "R" (presumably for language and gore)
Running Time    150 minutes
Reviewed at     The Varsity, Chapel Hill, NC (3OCT96)

==

     A true-crime film that credits a "Heavy Metal Music Consultant?"
Believe it or not, a sparse soundtrack by Metallica is one of the many
pleasures to be partaken in PARADISE LOST: THE CHILD MURDERS AT ROBIN
HOOD HILLS.  This fascinating though overlong documentary from the
makers of BROTHER'S KEEPER recounts the events surrounding the discovery
of three murdered boys in West Memphis, Arkansas, the reaction of their
families, and the resulting trial that convicted three adolescent
outcasts with nary a shred of physical evidence.  Though the details of
the crime-- involving sexual mutilation-- are graphic enough to make
your hair stand on end, the most harrowing portrait of evil is that of
an unforgiving Christian community.  Filmmakers Joe Berlinger and Bruce
Sinofsy, who were given access to anyone and everyone associated with
the trial, take us into the churches, the trailer parks, and, in one
unforgettable sequence, onto the firing range where a grieving father
imagines the suspects as the giant pumpkin he's using for target
practice.  Recommended.

    Grade: B+

--
Mike Legeros
Corporate Training
SAS Institute Inc, Cary, NC, USA, Earth
mailto: legeros@unx.sas.com (w) legeros@pagesz.net (h)
"I don't know.  I'm just making this up as I go." - Harrison Ford

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package io.requery.sql;

import io.requery.query.BaseScalar;
import io.requery.query.Scalar;
import io.requery.query.element.QueryElement;
import io.requery.sql.gen.DefaultOutput;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Extends {@link UpdateOperation} specifically for binding to an entity, skipping the query
 * parameters to avoid boxing overhead.
 */
abstract class EntityUpdateOperation extends UpdateOperation {

    EntityUpdateOperation(RuntimeConfiguration configuration, GeneratedResultReader resultReader) {
        super(configuration, resultReader);
    }

    @Override
    public Scalar<Integer> evaluate(final QueryElement<Scalar<Integer>> query) {
        return new BaseScalar<Integer>(configuration.getWriteExecutor()) {
            @Override
            public Integer evaluate() {
                // doesn't use the query params, just maps to the parameterBinder callback
                QueryBuilder qb = new QueryBuilder(configuration.getQueryBuilderOptions());
                DefaultOutput output =
                new DefaultOutput(configuration.getStatementGenerator(), query, qb, null, false);
                String sql = output.toSql();
                int result;
                try (Connection connection = configuration.getConnection()) {
                    StatementListener listener = configuration.getStatementListener();
                    try (PreparedStatement statement = prepare(sql, connection)) {
                        bindParameters(statement);
                        listener.beforeExecuteUpdate(statement, sql, null);
                        result = statement.executeUpdate();
                        listener.afterExecuteUpdate(statement);
                        readGeneratedKeys(0, statement);
                    }
                } catch (SQLException e) {
                    throw new StatementExecutionException(e, sql);
                }
                return result;
            }
        };
    }

    public abstract int bindParameters(PreparedStatement statement) throws SQLException;
}


text:
package com.flextrade.jfixture.behaviours.tracing;

import com.flextrade.jfixture.FixtureBehaviour;
import com.flextrade.jfixture.SpecimenBuilder;

public class TracingBehaviour implements FixtureBehaviour {

    private final Appendable traceWriter;
    private final TracingStrategy strategy;

    public TracingBehaviour(TracingStrategy strategy, Appendable traceWriter) {

        if (strategy == null) throw new IllegalArgumentException("strategy must not be null");
        if (traceWriter == null) throw new IllegalArgumentException("traceWriter must not be null");

        this.strategy = strategy;
        this.traceWriter = traceWriter;
    }

    @Override
    public SpecimenBuilder transform(SpecimenBuilder builder) {

        if (builder == null) {
            throw new IllegalArgumentException("builder");
        }

        return new SpecimenTracer(builder, this.strategy, this.traceWriter);
    }
}


text:
package com.faforever.client.fa.relay;

import com.faforever.client.remote.domain.MessageTarget;
import com.faforever.client.remote.domain.SerializableMessage;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class GpgGameMessage implements SerializableMessage {

  private String command;
  private List<Object> args;
  private MessageTarget target = MessageTarget.GAME;

  public GpgGameMessage(GpgClientCommand command, List<Object> args) {
    this(command.getString(), args);
  }

  public GpgGameMessage(String command, List<Object> args) {
    this.command = command;
    this.args = args;
  }

  public List<Object> getArgs() {
    return args;
  }

  public GpgClientCommand getCommand() {
    return GpgClientCommand.fromString(command);
  }

  public Collection<String> getStringsToMask() {
    return Collections.emptyList();
  }

  public MessageTarget getTarget() {
    return target;
  }

  public void setTarget(MessageTarget target) {
    this.target = target;
  }

  protected int getInt(int index) {
    return ((Number) args.get(index)).intValue();
  }

  protected String getString(int index) {
    return ((String) args.get(index));
  }
}


text:
class geGdalUtils {
 public:
  geGdalUtils();
  // Combines JPEG data and alpha channel to PNG.
  // If image_alpha is NULL, then just converts source image data to png format.
  // Returns PNG using pimage_blend string pointer.
  static void BlendToPng(const std::string& pimage_data,
                         const std::string* image_alpha,
                         std::string* pimage_blend);

  static void ConvertToJpeg(const std::string& pimage_data,
                            std::string* pimage_blend);
};

class geGdalVSI {
 public:
  // Mutex wrappers to encapsulate UniqueVSIFilename creation and GDAL open
  // functions preventing identical filename collisions.
  static GDALDataset* VsiGdalCreateWrap(GDALDriverH hdriver,
                                        std::string* const vsifile,
                                        int nx, int ny, int nbands,
                                        GDALDataType bandtype,
                                        char **papszoptions);

  static GDALDataset* VsiGdalCreateCopyWrap(GDALDriverH hdriver,
                                            std::string* const vsifile,
                                            GDALDatasetH hdataset,
                                            int bstrict,
                                            char **papszoptions,
                                            GDALProgressFunc progressfunc,
                                            void *progressdata);

  static GDALDataset* VsiGdalOpenInternalWrap(std::string* const vsifile,
                                              const std::string& image_alpha);

  // Initialize random seed for unique VSI file generation.
  static void InitVSIRandomSeed();

 private:
  static khMutex& GetMutex();
};

#endif  // GEO_EARTH_ENTERPRISE_SRC_COMMON_GEGDALUTILS_H_


text:
package org.apache.ignite.internal.processors.query.calcite.message;

import org.apache.ignite.IgniteCheckedException;
import org.apache.ignite.marshaller.Marshaller;
import org.jetbrains.annotations.Nullable;

/** */
public interface MarshallingContext {
    /**
     * @return Message marshaller.
     */
    Marshaller marshaller();

    /**
     * @return Message class loader.
     */
    ClassLoader classLoader();

    /**
     * Unmarshals object from byte array.
     *
     * @param <T> Type of unmarshalled object.
     * @param bytes Byte array.
     * @return Unmarshalled object.
     * @throws IgniteCheckedException If unmarshalling failed.
     */
    default <T> T unmarshal(byte[] bytes) throws IgniteCheckedException {
        return marshaller().unmarshal(bytes, classLoader());
    }

    /**
     * Marshals object to byte array.
     *
     * @param obj Object to marshal. {@code null} object will be marshaled to binary {@code null} representation.
     * @return Byte array.
     * @throws IgniteCheckedException If marshalling failed.
     */
    default byte[] marshal(@Nullable Object obj) throws IgniteCheckedException {
        return marshaller().marshal(obj);
    }
}


text:
package hrider.converters;

import org.apache.hadoop.hbase.util.Bytes;

public class FloatConverter extends TypeConverter {

    private static final long serialVersionUID = -4945353944739350169L;

    @Override
    public String toString(byte[] value) {
        if (value == null) {
            return null;
        }
        return Float.toString(Bytes.toFloat(value));
    }

    @Override
    public boolean canConvert(byte[] value) {
        try {
            Bytes.toFloat(value);
            return true;
        }
        catch (Exception ignore) {
            return false;
        }
    }

    @Override
    public boolean supportsFormatting() {
        return false;
    }

    @Override
    public byte[] toBytes(String value) {
        if (value == null) {
            return EMPTY_BYTES_ARRAY;
        }
        return Bytes.toBytes(Float.parseFloat(value));
    }
}


text:
<!DOCTYPE html>

  <title>startProcess.js</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0; maximum-scale=1.0; user-scalable=0;">
  <link rel="stylesheet" media="all" href="../docco.css" />

startProcess.js

                ¶

The startProcess sends elements to be created then beings
the animationFrameProcess

startProcess

null 'start' -> IN

OUT -> null 'init'

OUT -> bool 'animate'

module.exports = function startProcess( app ) {

    function startComponent() {

        app.emit( 'init' );

        app.emit( 'animate', true );

    }

    app.on( 'start', startComponent );

};


text:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class edu_dhbw_andar_CameraPreviewHandler */

#ifndef _Included_edu_dhbw_andar_CameraPreviewHandler
#define _Included_edu_dhbw_andar_CameraPreviewHandler
#ifdef __cplusplus
extern "C" {
#endif
#undef edu_dhbw_andar_CameraPreviewHandler_MODE_RGB
#define edu_dhbw_andar_CameraPreviewHandler_MODE_RGB 0L
#undef edu_dhbw_andar_CameraPreviewHandler_MODE_GRAY
#define edu_dhbw_andar_CameraPreviewHandler_MODE_GRAY 1L
/*
 * Class:     edu_dhbw_andar_CameraPreviewHandler
 * Method:    yuv420sp2rgb
 * Signature: ([BIII[B)V
 */
JNIEXPORT void JNICALL Java_edu_dhbw_andar_CameraPreviewHandler_yuv420sp2rgb
  (JNIEnv *, jobject, jbyteArray, jint, jint, jint, jbyteArray);

#ifdef __cplusplus
}
#endif
#endif
/* Header for class edu_dhbw_andar_CameraPreviewHandler_AutoFocusHandler */

#ifndef _Included_edu_dhbw_andar_CameraPreviewHandler_AutoFocusHandler
#define _Included_edu_dhbw_andar_CameraPreviewHandler_AutoFocusHandler
#ifdef __cplusplus
extern "C" {
#endif
#undef edu_dhbw_andar_CameraPreviewHandler_AutoFocusHandler_MIN_PRIORITY
#define edu_dhbw_andar_CameraPreviewHandler_AutoFocusHandler_MIN_PRIORITY 1L
#undef edu_dhbw_andar_CameraPreviewHandler_AutoFocusHandler_NORM_PRIORITY
#define edu_dhbw_andar_CameraPreviewHandler_AutoFocusHandler_NORM_PRIORITY 5L
#undef edu_dhbw_andar_CameraPreviewHandler_AutoFocusHandler_MAX_PRIORITY
#define edu_dhbw_andar_CameraPreviewHandler_AutoFocusHandler_MAX_PRIORITY 10L
#undef edu_dhbw_andar_CameraPreviewHandler_AutoFocusHandler_MIN_TIME
#define edu_dhbw_andar_CameraPreviewHandler_AutoFocusHandler_MIN_TIME 1500L
#undef edu_dhbw_andar_CameraPreviewHandler_AutoFocusHandler_ENSURE_TIME
#define edu_dhbw_andar_CameraPreviewHandler_AutoFocusHandler_ENSURE_TIME 10000L
#ifdef __cplusplus
}
#endif
#endif
/* Header for class edu_dhbw_andar_CameraPreviewHandler_CameraConstFPS */

#ifndef _Included_edu_dhbw_andar_CameraPreviewHandler_CameraConstFPS
#define _Included_edu_dhbw_andar_CameraPreviewHandler_CameraConstFPS
#ifdef __cplusplus
extern "C" {
#endif
#undef edu_dhbw_andar_CameraPreviewHandler_CameraConstFPS_MIN_PRIORITY
#define edu_dhbw_andar_CameraPreviewHandler_CameraConstFPS_MIN_PRIORITY 1L
#undef edu_dhbw_andar_CameraPreviewHandler_CameraConstFPS_NORM_PRIORITY
#define edu_dhbw_andar_CameraPreviewHandler_CameraConstFPS_NORM_PRIORITY 5L
#undef edu_dhbw_andar_CameraPreviewHandler_CameraConstFPS_MAX_PRIORITY
#define edu_dhbw_andar_CameraPreviewHandler_CameraConstFPS_MAX_PRIORITY 10L
#ifdef __cplusplus
}
#endif
#endif
/* Header for class edu_dhbw_andar_CameraPreviewHandler_ConversionWorker */

#ifndef _Included_edu_dhbw_andar_CameraPreviewHandler_ConversionWorker
#define _Included_edu_dhbw_andar_CameraPreviewHandler_ConversionWorker
#ifdef __cplusplus
extern "C" {
#endif
#undef edu_dhbw_andar_CameraPreviewHandler_ConversionWorker_MIN_PRIORITY
#define edu_dhbw_andar_CameraPreviewHandler_ConversionWorker_MIN_PRIORITY 1L
#undef edu_dhbw_andar_CameraPreviewHandler_ConversionWorker_NORM_PRIORITY
#define edu_dhbw_andar_CameraPreviewHandler_ConversionWorker_NORM_PRIORITY 5L
#undef edu_dhbw_andar_CameraPreviewHandler_ConversionWorker_MAX_PRIORITY
#define edu_dhbw_andar_CameraPreviewHandler_ConversionWorker_MAX_PRIORITY 10L
#ifdef __cplusplus
}
#endif
#endif


text:
package visitors

import (
	"errors"
	"fmt"
	"io/ioutil"
	"strconv"
	"strings"

	"github.com/linuxboot/fiano/pkg/uefi"
)

// InsertType defines the insert type operation that is requested
type InsertType int

// Insert Types
const (

	// == Deprectated ==

	// These first two specify a firmware volume.

	// InsertTypeFront inserts a file at the beginning of the firmware volume,
	// which is specified by 1) FVname GUID, or (File GUID/File name) of a file
	// inside that FV.
	InsertTypeFront InsertType = iota
	// InsertTypeEnd inserts a file at the end of the specified firmware volume.
	InsertTypeEnd

	// These two specify a File to insert before or after
	// InsertTypeAfter inserts after the specified file,
	// which is specified by a File GUID or File name.
	InsertTypeAfter
	// InsertTypeBefore inserts before the specified file.
	InsertTypeBefore
	// InsertTypeDXE inserts into the Dxe Firmware Volume. This works by searching
	// for the DxeCore first to identify the Dxe Firmware Volume.
	InsertTypeDXE

	// == Not deprecated ==

	// InsertTypeReplaceFFS replaces the found file with the new FFS. This is used
	// as a shortcut for remove and insert combined, but also when we want to make
	// sure that the starting offset of the new file is the same as the old.
	InsertTypeReplaceFFS
	// TODO: Add InsertIn

	// InsertTypeInsert is generalization of all InsertTypeInsert* above. Arguments:
	// * The first argument specifies the type of what to insert (possible values: "file" or "pad_file")
	// * The second argument specifies the content of what to insert:
	//     - If the first argument is "file" then a path to the file content is expected.
	//     - If the first argument is "pad_file" then the size is expected.
	// * The third argument specifies the preposition of where to insert to (possible values: "front", "end", "after", "before").
	// * The forth argument specifies the preposition object of where to insert to. It could be FV_or_File GUID_or_name.
	//   For example combination "end 5C60F367-A505-419A-859E-2A4FF6CA6FE5" means to insert to the end of volume
	//   "5C60F367-A505-419A-859E-2A4FF6CA6FE5".
	//
	// A complete example: "pad_file 256 after FC510EE7-FFDC-11D4-BD41-0080C73C8881" means to insert a pad file
	// of size 256 bytes after file with GUID "FC510EE7-FFDC-11D4-BD41-0080C73C8881".
	InsertTypeInsert
)

var insertTypeNames = map[InsertType]string{
	InsertTypeInsert:     "insert",
	InsertTypeReplaceFFS: "replace_ffs",

	// Deprecated:
	InsertTypeFront:  "insert_front",
	InsertTypeEnd:    "insert_end",
	InsertTypeAfter:  "insert_after",
	InsertTypeBefore: "insert_before",
	InsertTypeDXE:    "insert_dxe",
}

// String creates a string representation for the insert type.
func (i InsertType) String() string {
	if t, ok := insertTypeNames[i]; ok {
		return t
	}
	return "UNKNOWN"
}

// InsertWhatType defines the type of inserting object
type InsertWhatType int

const (
	InsertWhatTypeUndefined = InsertWhatType(iota)
	InsertWhatTypeFile
	InsertWhatTypePadFile

	EndOfInsertWhatType
)

// String implements fmt.Stringer.
func (t InsertWhatType) String() string {
	switch t {
	case InsertWhatTypeUndefined:
		return "undefined"
	case InsertWhatTypeFile:
		return "file"
	case InsertWhatTypePadFile:
		return "pad_file"
	}
	return fmt.Sprintf("unknown_%d", t)
}

// ParseInsertWhatType converts a string to InsertWhatType
func ParseInsertWhatType(s string) InsertWhatType {
	// TODO: it is currently O(n), optimize

	s = strings.Trim(strings.ToLower(s), " \t")
	for t := InsertWhatTypeUndefined; t < EndOfInsertWhatType; t++ {
		if t.String() == s {
			return t
		}
	}
	return InsertWhatTypeUndefined
}

// InsertWherePreposition defines the type of inserting object
type InsertWherePreposition int

const (
	InsertWherePrepositionUndefined = InsertWherePreposition(iota)
	InsertWherePrepositionFront
	InsertWherePrepositionEnd
	InsertWherePrepositionAfter
	InsertWherePrepositionBefore

	EndOfInsertWherePreposition
)

// String implements fmt.Stringer.
func (p InsertWherePreposition) String() string {
	switch p {
	case InsertWherePrepositionUndefined:
		return "undefined"
	case InsertWherePrepositionFront:
		return "front"
	case InsertWherePrepositionEnd:
		return "end"
	case InsertWherePrepositionAfter:
		return "after"
	case InsertWherePrepositionBefore:
		return "before"
	}
	return fmt.Sprintf("unknown_%d", p)
}

// ParseInsertWherePreposition converts a string to InsertWherePreposition
func ParseInsertWherePreposition(s string) InsertWherePreposition {
	// TODO: it is currently O(n), optimize

	s = strings.Trim(strings.ToLower(s), " \t")
	for t := InsertWherePrepositionUndefined; t < EndOfInsertWherePreposition; t++ {
		if t.String() == s {
			return t
		}
	}
	return InsertWherePrepositionUndefined
}

// Insert inserts a firmware file into an FV
type Insert struct {
	// TODO: use InsertWherePreposition to define the location, instead of InsertType

	// Input
	Predicate func(f uefi.Firmware) bool
	NewFile   *uefi.File
	InsertType

	// Matched File
	FileMatch uefi.Firmware
}

// Run wraps Visit and performs some setup and teardown tasks.
func (v *Insert) Run(f uefi.Firmware) error {
	// First run "find" to generate a position to insert into.
	find := Find{
		Predicate: v.Predicate,
	}
	if err := find.Run(f); err != nil {
		return err
	}

	if numMatch := len(find.Matches); numMatch > 1 {
		return fmt.Errorf("more than one match, only one match allowed! got %v", find.Matches)
	} else if numMatch == 0 {
		return errors.New("no matches found")
	}

	// Find should only match a file or a firmware volume. If it's an FV, we can
	// edit the FV directly.
	if fvMatch, ok := find.Matches[0].(*uefi.FirmwareVolume); ok {
		switch v.InsertType {
		case InsertTypeFront:
			fvMatch.Files = append([]*uefi.File{v.NewFile}, fvMatch.Files...)
		case InsertTypeEnd:
			fvMatch.Files = append(fvMatch.Files, v.NewFile)
		default:
			return fmt.Errorf("matched FV but insert operation was %s, which only matches Files",
				v.InsertType.String())
		}
		return nil
	}
	var ok bool
	if v.FileMatch, ok = find.Matches[0].(*uefi.File); !ok {
		return fmt.Errorf("match was not a file or a firmware volume: got %T, unable to insert", find.Matches[0])
	}
	// Match is a file, apply visitor.
	return f.Apply(v)
}

// Visit applies the Insert visitor to any Firmware type.
func (v *Insert) Visit(f uefi.Firmware) error {
	switch f := f.(type) {
	case *uefi.FirmwareVolume:
		for i := 0; i < len(f.Files); i++ {
			if f.Files[i] == v.FileMatch {
				// TODO: use InsertWherePreposition to define the location, instead of InsertType
				switch v.InsertType {
				case InsertTypeFront:
					f.Files = append([]*uefi.File{v.NewFile}, f.Files...)
				case InsertTypeDXE:
					fallthrough
				case InsertTypeEnd:
					f.Files = append(f.Files, v.NewFile)
				case InsertTypeAfter:
					f.Files = append(f.Files[:i+1], append([]*uefi.File{v.NewFile}, f.Files[i+1:]...)...)
				case InsertTypeBefore:
					f.Files = append(f.Files[:i], append([]*uefi.File{v.NewFile}, f.Files[i:]...)...)
				case InsertTypeReplaceFFS:
					f.Files = append(f.Files[:i], append([]*uefi.File{v.NewFile}, f.Files[i+1:]...)...)
				}
				return nil
			}
		}
	}

	return f.ApplyChildren(v)
}

func parseFile(filePath string) (*uefi.File, error) {
	fileBytes, err := ioutil.ReadFile(filePath)
	if err != nil {
		return nil, fmt.Errorf("unable to read file '%s': %w", filePath, err)
	}

	file, err := uefi.NewFile(fileBytes)
	if err != nil {
		return nil, fmt.Errorf("unable to parse file '%s': %w", filePath, err)
	}

	return file, nil
}

func genInsertRegularFileCLI(iType InsertType) func(args []string) (uefi.Visitor, error) {
	return func(args []string) (uefi.Visitor, error) {
		var pred FindPredicate
		var err error
		var filename string

		if iType == InsertTypeDXE {
			pred = FindFileTypePredicate(uefi.FVFileTypeDXECore)
			filename = args[0]
		} else {
			pred, err = FindFileFVPredicate(args[0])
			if err != nil {
				return nil, err
			}
			filename = args[1]
		}

		file, err := parseFile(filename)
		if err != nil {
			return nil, fmt.Errorf("unable to parse file '%s': %w", args[1], err)
		}

		// Insert File.
		return &Insert{
			Predicate:  pred,
			NewFile:    file,
			InsertType: iType,
		}, nil
	}
}

func genInsertFileCLI() func(args []string) (uefi.Visitor, error) {
	return func(args []string) (uefi.Visitor, error) {
		whatType := ParseInsertWhatType(args[0])
		if whatType == InsertWhatTypeUndefined {
			return nil, fmt.Errorf("unknown what-type: '%s'", args[0])
		}

		var file *uefi.File
		switch whatType {
		case InsertWhatTypeFile:
			var err error
			file, err = parseFile(args[1])
			if err != nil {
				return nil, fmt.Errorf("unable to parse file '%s': %w", args[1], err)
			}
		case InsertWhatTypePadFile:
			padSize, err := strconv.ParseUint(args[1], 0, 64)
			if err != nil {
				return nil, fmt.Errorf("unable to parse pad file size '%s': %w", args[1], err)
			}
			file, err = uefi.CreatePadFile(padSize)
			if err != nil {
				return nil, fmt.Errorf("unable to create a pad file of size %d: %w", padSize, err)
			}
		default:
			return nil, fmt.Errorf("what-type '%s' is not supported, yet", whatType)
		}

		wherePreposition := ParseInsertWherePreposition(args[2])
		if wherePreposition == InsertWherePrepositionUndefined {
			return nil, fmt.Errorf("unknown where-preposition: '%s'", args[2])
		}

		pred, err := FindFileFVPredicate(args[3])
		if err != nil {
			return nil, fmt.Errorf("unable to parse the predicate parameters '%s': %w", args[0], err)
		}

		// TODO: use InsertWherePreposition to define the location, instead of InsertType
		var insertType InsertType
		switch wherePreposition {
		case InsertWherePrepositionFront:
			insertType = InsertTypeFront
		case InsertWherePrepositionEnd:
			insertType = InsertTypeEnd
		case InsertWherePrepositionAfter:
			insertType = InsertTypeAfter
		case InsertWherePrepositionBefore:
			insertType = InsertTypeBefore
		default:
			return nil, fmt.Errorf("where-preposition '%s' is not supported, yet", wherePreposition)
		}

		// Insert File.
		return &Insert{
			Predicate: pred,
			NewFile:   file,
			// TODO: use InsertWherePreposition to define the location, instead of InsertType
			InsertType: insertType,
		}, nil
	}
}

func init() {
	RegisterCLI(insertTypeNames[InsertTypeInsert],
		"insert a file", 4, genInsertFileCLI())
	RegisterCLI(insertTypeNames[InsertTypeReplaceFFS],
		"replace a file with another file", 2, genInsertRegularFileCLI(InsertTypeReplaceFFS))
	RegisterCLI(insertTypeNames[InsertTypeFront],
		"(deprecated) insert a file at the beginning of a firmware volume", 2, genInsertRegularFileCLI(InsertTypeFront))
	RegisterCLI(insertTypeNames[InsertTypeEnd],
		"(deprecated) insert a file at the end of a firmware volume", 2, genInsertRegularFileCLI(InsertTypeEnd))
	RegisterCLI(insertTypeNames[InsertTypeDXE],
		"(deprecated) insert a file at the end of the DXE firmware volume", 1, genInsertRegularFileCLI(InsertTypeDXE))
	RegisterCLI(insertTypeNames[InsertTypeAfter],
		"(deprecated) insert a file after another file", 2, genInsertRegularFileCLI(InsertTypeAfter))
	RegisterCLI(insertTypeNames[InsertTypeBefore],
		"(deprecated) insert a file before another file", 2, genInsertRegularFileCLI(InsertTypeBefore))
}


text:
require 'chef/knife'
require 'chef/knife/base_vsphere_command'

# Lists all known data stores in datacenter with sizes
class Chef::Knife::VsphereVlanList < Chef::Knife::BaseVsphereCommand
  banner 'knife vsphere vlan list'

  common_options

  def run
    $stdout.sync = true

    vim_connection
    dc = datacenter
    dc.network.each do |network|
      puts "#{ui.color('VLAN', :cyan)}: #{network.name}"
    end
  end
end


text:
<?php

namespace Magento\CatalogSearch\Model\Indexer;

class Fulltext implements \Magento\Indexer\Model\ActionInterface, \Magento\Framework\Mview\ActionInterface
{
    /**
     * Indexer ID in configuration
     */
    const INDEXER_ID = 'catalogsearch_fulltext';

    /**
     * @var \Magento\Catalog\Model\Indexer\Category\Flat\Action\FullFactory
     */
    protected $fullActionFactory;

    /**
     * @var \Magento\Catalog\Model\Indexer\Category\Flat\Action\RowsFactory
     */
    protected $rowsActionFactory;

    /** @var \Magento\Indexer\Model\IndexerRegistry */
    protected $indexerRegistry;

    /**
     * @param Fulltext\Action\FullFactory $fullActionFactory
     * @param Fulltext\Action\RowsFactory $rowsActionFactory
     * @param \Magento\Indexer\Model\IndexerRegistry $indexerRegistry
     */
    public function __construct(
        Fulltext\Action\FullFactory $fullActionFactory,
        Fulltext\Action\RowsFactory $rowsActionFactory,
        \Magento\Indexer\Model\IndexerRegistry $indexerRegistry
    ) {
        $this->fullActionFactory = $fullActionFactory;
        $this->rowsActionFactory = $rowsActionFactory;
        $this->indexerRegistry = $indexerRegistry;
    }

    /**
     * Execute materialization on ids entities
     *
     * @param int[] $ids
     * @return void
     */
    public function execute($ids)
    {
        $this->indexerRegistry->get(self::INDEXER_ID);

        /** @var Fulltext\Action\Rows $action */
        $action = $this->rowsActionFactory->create();
        $action->reindex($ids);
    }

    /**
     * Execute full indexation
     *
     * @return void
     */
    public function executeFull()
    {
        $this->fullActionFactory->create()->reindexAll();
    }

    /**
     * Execute partial indexation by ID list
     *
     * @param int[] $ids
     * @return void
     */
    public function executeList(array $ids)
    {
        $this->execute($ids);
    }

    /**
     * Execute partial indexation by ID
     *
     * @param int $id
     * @return void
     */
    public function executeRow($id)
    {
        $this->execute([$id]);
    }
}


text:
<?php

declare(strict_types=1);

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

/**
 * Class TagsTable
 */
final class TagsTable extends Migration
{
    use MigrationTrait;

    /** @var string  */
    protected $table = 'tags';

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $this->schemaBuilder($this->getConnection())
            ->create($this->table, function (Blueprint $table) {
                $table->increments('tag_id');
                $table->string('name', 255)->unique();
                $table->string('display_title')->nullable();
                $table->timestamps();
            });
    }
}


text:
#if !defined(EF_GY_GLOBAL_H)
#define EF_GY_GLOBAL_H

#include <set>

namespace efgy {
/* Lazily-initialised global object.
 * @object The type of the object to initialise. Must be default-constructible.
 *
 * Sometimes it's neat to have a default instance of, say, a list of things that
 * your binary supports, and that multiple pieces of the code can add to.
 * A typical example might be servlets in a network server, or command line
 * options, or test cases scattered throughout a library.
 *
 * @return A global default version of the type you used.
 */
template <class type>
static type &global(void) {
  static type obj;
  return obj;
}

/* Object beacon.
 * @type The type of the object to remember.
 *
 * This class allows registering an object for as long as it exists, and to then
 * automatically remove the reference when it no longer does.
 */
template <class type>
class beacon {
 public:
  /* Set type.
   *
   * This type is here to help you know what you need to pass into the
   * constructor.
   */
  using set = std::set<type *>;

  /* Construct with reference.
   * @pReference What to keep track of.
   * @pRoot Where to keep track of that; optional, defaults to a global set.
   *
   * Allows constructing a beacon by using a reference to whatever needs to be
   * tracked. By forcing construction with a reference, the object we do keep
   * track of must already be initialised by the time the beacon is constructed,
   * which helps in avoiding exposing uninitialised objets.
   *
   * Note: multiple objects with the same address and of the same type will not
   * work as expected. Or, they will, until the destructor comes into play. so
   * you'll be fine for global, static things, but you won't be fine for local
   * objects in the sense that they might get removed from the set earlier than
   * they should.
   */
  beacon(type &pReference, set &pRoot = global<set>())
      : reference(pReference), root(pRoot) {
    root.insert(&reference);
  }

  /* Unregister the reference.
   *
   * This destructor removes the reference from the set of things to keep track
   * of. The destructor is the perfect place for this, since we want this to be
   * bound to the lifecycle of the beacon.
   *
   * Also, the order of destructors is defined to be the reverse of the
   * constructors, so if the reference and the beacon were in the same scope
   * then the beacon would have to be destroyed first, since we require a
   * reference to construct the beacon.
   */
  ~beacon(void) { root.erase(&reference); }

 protected:
  /* What we keep track of.
   *
   * This is a reference to the thing we keep track of, as outlined in the
   * constructor and destructor docs.
   */
  type &reference;

  /* Where we keep track of the reference.
   *
   * A reference to the set of things that are being kept track of by other
   * beacons.
   */
  set &root;
};

/* Type alias for registered sets.
 * @type What was registered.
 *
 * This is a minor convenience alias to get the set type right when dealing with
 * things that use a beacon.
 */
template <typename type>
using beacons = typename beacon<type>::set;
}  // namespace efgy

#endif


text: Slides for LondonAPI made with reveal.js.


text:
package com.google.zxing.web.generator.client;

import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

/**
 * Generator for email address.
 *
 * @author Yohann Coppel
 */
public final class EmailGenerator implements GeneratorSource {

  private Grid table;
  private final TextBox email = new TextBox();

  public EmailGenerator(ChangeHandler handler, KeyPressHandler keyListener) {
    email.addStyleName(StylesDefs.INPUT_FIELD_REQUIRED);
    email.addChangeHandler(handler);
    email.addKeyPressHandler(keyListener);
  }

  @Override
  public String getName() {
    return "Email address";
  }

  @Override
  public String getText() throws GeneratorException {
    return "mailto:" + getEmailField();
  }

  private String getEmailField() throws GeneratorException {
    String input = email.getText();
    if (input.length() < 1) {
      throw new GeneratorException("Email must be present.");
    }
    Validators.validateEmail(input);
    return input;
  }

  @Override
  public Grid getWidget() {
    if (table != null) {
      return table;
    }
    table = new Grid(1, 2);
    table.setText(0, 0, "Address");
    table.setWidget(0, 1, email);
    return table;
  }

  @Override
  public void validate(Widget widget) throws GeneratorException {
    if (widget == email) {
      getEmailField();
    }
  }

  @Override
  public void setFocus() {
    email.setFocus(true);
  }
}


text:
<?php

namespace Magento\Mtf\Client\Element;

use Magento\Mtf\Client\Locator;

/**
 * Typified element class for  Multiple Select List elements
 */
class MultiselectlistElement extends MultiselectElement
{
    /**
     * XPath selector for finding option by its position number
     *
     * @var string
     */
    protected $optionElement = './/*[contains(@class,"mselect-list-item")][%d]/label';

    /**
     * XPath selector for checking is option checked
     *
     * @var string
     */
    protected $optionCheckedElement = './/*[contains(@class, "mselect-checked")]/following-sibling::span';

    /**
     * Option locator by value.
     *
     * @var string
     */
    protected $optionByValue = './/*[contains(@class,"mselect-list-item")]/label[contains(normalize-space(.), %s)]';

    /**
     * Select options by values in multiple select list
     *
     * @param array|string $values
     * @throws \Exception
     */
    public function setValue($values)
    {
        $options = $this->getOptions();
        $values = is_array($values) ? $values : [$values];

        foreach ($options as $option) {
            /** @var \Magento\Mtf\Client\ElementInterface $option */
            $optionText = $option->getText();
            $isChecked = $option->find($this->optionCheckedElement, Locator::SELECTOR_XPATH)->isVisible();
            $inArray = in_array($optionText, $values);
            if (($isChecked && !$inArray) || (!$isChecked && $inArray)) {
                $option->click();
            }
        }
    }

    /**
     * Method that returns array with checked options in multiple select list
     *
     * @return array|string
     */
    public function getValue()
    {
        $checkedOptions = [];
        $options = $this->getOptions();

        foreach ($options as $option) {
            /** @var \Magento\Mtf\Client\ElementInterface $option */
            $checkedOption = $option->find($this->optionCheckedElement, Locator::SELECTOR_XPATH);
            if ($checkedOption->isVisible()) {
                $checkedOptions[] = $checkedOption->getText();
            }
        }

        return $checkedOptions;
    }

    /**
     * Getting all options in multi select list
     *
     * @return array
     */
    protected function getOptions()
    {
        $options = [];
        $counter = 1;

        $newOption = $this->find(sprintf($this->optionElement, $counter), Locator::SELECTOR_XPATH);
        while ($newOption->isVisible()) {
            $options[] = $newOption;
            $counter++;
            $newOption = $this->find(sprintf($this->optionElement, $counter), Locator::SELECTOR_XPATH);
        }

        return $options;
    }

    /**
     * Method that returns array with all options in multiple select list
     *
     * @return array
     */
    public function getAllValues()
    {
        $optionsValue = [];
        $options = $this->getOptions();

        foreach ($options as $option) {
            /** @var \Magento\Mtf\Client\ElementInterface $option */
            $optionsValue[] = $option->getText();
        }

        return $optionsValue;
    }

    /**
     * Check whether value is visible in the list.
     *
     * @param string $value
     * @return bool
     */
    public function isValueVisible($value)
    {
        $option = $this->find(sprintf($this->optionByValue, $this->escapeQuotes($value)), Locator::SELECTOR_XPATH);
        return $option->isVisible();
    }
}


text:
Contributing
---

The issue tracker is at [github.com/CartoDB/node-cartodb-redis](https://github.com/CartoDB/node-cartodb-redis).

We love pull requests from everyone, see [Contributing to Open Source on GitHub](https://guides.github.com/activities/contributing-to-open-source/#contributing).

## Submitting Contributions

* You will need to sign a Contributor License Agreement (CLA) before making a submission. [Learn more here](https://cartodb.com/contributing).


text:
<?php

namespace common\models\base;

use Yii;

/**
 * This is the base model class for table "{{%product_attribute}}".
 *
 * @property integer $id
 * @property integer $product_id
 * @property string $name
 * @property string $value
 *
 * @property \common\models\Product $product
 */
class ProductAttribute extends \yii\db\ActiveRecord
{
    use \mootensai\relation\RelationTrait;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['product_id'], 'integer'],
            [['name', 'value'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%product_attribute}}';
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'product_id' => 'Product ID',
            'name' => 'Name',
            'value' => 'Value',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProduct()
    {
        return $this->hasOne(\common\models\Product::className(), ['id' => 'product_id']);
    }
    }


text:
layout: default
---

{{ page.title }}

    {{ content }}

  {% if page.share %}
    {% include addthis.html %}
  {% endif %}

  {% if page.comments %}
     {% include disqus.html %}
  {% endif %}


text:
<?php
declare(strict_types=1);

namespace Kafka\Exception;

use Kafka\Exception;

class Protocol extends Exception
{
}


text:
from datetime import datetime

from sqlalchemy.dialects.postgresql import JSON

from app import db

class Model(object):

    def __init__(self, **kw):
        for key, value in kw.items():
            setattr(self, key, value)

class Report(Model, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.String(), index=True)
    har = db.Column(JSON)
    ref = db.Column(db.String(), index=True)  # Git commit SHA or custom name.
    created = db.Column(db.DateTime, default=datetime.now)

    __tablename__ = 'reports'

    def __repr__(self):
        return '<Report: %s: %s>' % (self.id, self.url)


text:
"use strict"

const expect = require(`expect`)
const createBufferReader = require(`./createBufferReader.js`)
const filler = require(`./filler`)
const zlib = require(`zlib`)
const {makeBuffer, B} = require(`./makeBuffer`)

{
  // empty buffer is at end
  const reader = createBufferReader({
    data: Buffer.from(``)
  })

  expect(reader.atEnd()).toBe(true)
}

{
  // at end after whitespace
  const reader = createBufferReader({
    data: Buffer.from(` `)
  })

  expect(reader.atEnd()).toBe(false)
  reader.readWhitespace()
  expect(reader.atEnd()).toBe(true)
}

{
  // at end after string
  const reader = createBufferReader({
    data: Buffer.from(`This`)
  })

  expect(reader.atEnd()).toBe(false)
  reader.readString()
  expect(reader.atEnd()).toBe(true)
}

{
  // can read bytes
  const reader = createBufferReader({
    data: Buffer.from([3, 2, 1])
  })

  expect(reader.readByte()).toBe(3)
  expect(reader.readByte()).toBe(2)
  expect(reader.readByte()).toBe(1)
}

{
  // can read byte array
  const reader = createBufferReader({
    data: Buffer.from([3, 2, 1])
  })

  expect(reader.readByteArray(3)).toEqual([3, 2, 1])
}

const wordArray = [65535, 1, 256]

{
  // can read words
  const reader = createBufferReader({
    data: B.u16(wordArray)
  })

  expect(reader.readWord()).toBe(65535)
  expect(reader.readWord()).toBe(1)
  expect(reader.readWord()).toBe(256)
}

{
  // can read word array
  const reader = createBufferReader({
    data: B.u16(wordArray)
  })

  expect(reader.readWordArray(3)).toEqual(wordArray)
}

const quadArray = [90000, 1, 65536]

{
  // can read quads
  const reader = createBufferReader({
    data: B.u32(quadArray)
  })

  expect(reader.readQuad()).toBe(90000)
  expect(reader.readQuad()).toBe(1)
  expect(reader.readQuad()).toBe(65536)
}

{
  // can read quad array
  const reader = createBufferReader({
    data: B.u32(quadArray)
  })

  expect(reader.readQuadArray(3)).toEqual(quadArray)
}

const doubleArray = [1, 1.5, -1, -1.5, 0.003, 0]

{
  // can read doubles
  const reader = createBufferReader({
    data: B.f64(doubleArray)
  })

  expect(reader.readDouble()).toBe(1)
  expect(reader.readDouble()).toBe(1.5)
  expect(reader.readDouble()).toBe(-1)
  expect(reader.readDouble()).toBe(-1.5)
  expect(reader.readDouble()).toBe(0.003)
  expect(reader.readDouble()).toBe(0)
}

{
  // can read double array
  const reader = createBufferReader({
    data: B.f64([1, 1.5, -1, -1.5, 0.003, 0])
  })

  expect(reader.readDoubleArray(doubleArray.length)).toEqual(doubleArray)
}

{
  // can read strings
  const reader = createBufferReader({
    data: Buffer.from(`tic tac toe`)
  })

  expect(reader.readStringFixed(3)).toBe(`tic`)
  expect(reader.readStringFixed(5)).toBe(` tac `)
  expect(reader.readStringFixed(3)).toBe(`toe`)
}

{
  // can read length-encoded strings
  const cuteCuddlyKitten = 'Cute Cuddly Kitten'
  const reader = createBufferReader({
    data: makeBuffer([
      B.u32(cuteCuddlyKitten.length),
      Buffer.from(cuteCuddlyKitten),
    ])
  })

  expect(reader.readStringLengthEncoded()).toBe(cuteCuddlyKitten)
}

{
  // can read null terminated strings
  const reader = createBufferReader({
    data: Buffer.from(`Cute\0Cuddly\0Kittens`)
  })

  expect(reader.readStringNullTerminated()).toBe(`Cute`)
  expect(reader.readStringNullTerminated()).toBe(`Cuddly`)
  expect(() => reader.readStringNullTerminated()).toThrow(RangeError)
}

{
  // reading a string should ignore garbage after null terminator
  const reader = createBufferReader({
    data: Buffer.from(`HAHN01.VSP\0he`)
  })

  expect(reader.readStringFixed(13)).toBe(`HAHN01.VSP`)
}

{
  // can get length
  const reader = createBufferReader({
    data: Buffer.from(filler(13, 0))
  })

  expect(reader.length).toBe(13)
}

{
  let data = filler(13, 99)
  data[data.length - 1] = 88

  // can set position
  const reader = createBufferReader({
    data: Buffer.from(data)
  })

  reader.position = data.length - 1
  expect(reader.readByte()).toBe(88)
}

{
  // can read whitespace
  const reader = createBufferReader({
    data: Buffer.from(` \n\r\tThis n that`)
  })

  expect(reader.readWhitespace()).toBe(` \n\r\t`)
}

{
  // can read whitespace at end of data
  const reader = createBufferReader({
    data: Buffer.from(` \n\r\t`)
  })

  expect(reader.readWhitespace()).toBe(` \n\r\t`)
}

{
  // can read variable length string up to space
  const reader = createBufferReader({
    data: Buffer.from(`This n that`)
  })

  expect(reader.readString()).toBe(`This`)
  expect(reader.readString()).toBe(`n`)
  expect(reader.readString()).toBe(`that`)
}

{
  // can read variable length string as byte
  const doubleNegMax = -256 * 2
  const reader = createBufferReader({
    data: Buffer.from(`255 256 -1 ` + doubleNegMax)
  })

  expect(reader.readStringAsByte()).toBe(255)
  expect(reader.readStringAsByte()).toBe(0)
  expect(reader.readStringAsByte()).toBe(255)
  expect(reader.readStringAsByte()).toBe(0)
}

{
  // can read variable length string as word
  const doubleNegMax = -65536 * 2
  const reader = createBufferReader({
    data: Buffer.from(`65535 65536 -1 ` + doubleNegMax)
  })

  expect(reader.readStringAsWord()).toBe(65535)
  expect(reader.readStringAsWord()).toBe(0)
  expect(reader.readStringAsWord()).toBe(65535)
}

{
  // can read variable length string as quad
  const doubleNegMax = -4294967296 * 2
  const reader = createBufferReader({
    data: Buffer.from(`4294967295 4294967296 -1 ` + doubleNegMax)
  })

  expect(reader.readStringAsQuad()).toBe(4294967295)
  expect(reader.readStringAsQuad()).toBe(0)
  expect(reader.readStringAsQuad()).toBe(4294967295)
  expect(reader.readStringAsQuad()).toBe(0)
}

{
  // can read line to end of data
  const reader = createBufferReader({
    data: Buffer.from(`Attention:`)
  })

  expect(reader.readLine()).toBe(`Attention:`)
}

{
  // can read line to newline
  const reader = createBufferReader({
    data: Buffer.from(`Attention:\nBacon`)
  })

  expect(reader.readLine()).toBe(`Attention:`)
}

{
  // can read line to carriage return
  const reader = createBufferReader({
    data: Buffer.from(`Attention:\rBacon`)
  })

  expect(reader.readLine()).toBe(`Attention:`)
}

{
  // can read empty line
  const reader = createBufferReader({
    data: Buffer.from(`\nBacon`)
  })

  expect(reader.readLine()).toBe(``)
}

{
  // at match
  const reader = createBufferReader({
    data: Buffer.from(`// Attention: Bacon`)
  })

  expect(reader.atMatch(`?`)).toBe(false)
  expect(reader.atMatch(`/`)).toBe(true)
  expect(reader.atMatch(`//`)).toBe(true)
  expect(reader.atMatch(`// Attention:`)).toBe(true)
  expect(reader.atMatch(`// Attention: Bacon`)).toBe(true)
  expect(reader.atMatch(`// Attention: Bacon Bits`)).toBe(false)
}

{
  // can read compressed word array
  const buffer = makeBuffer([
    B.u32([4 * 2]),
    B.u16([1, ((16 * 16) - 2) | 0xff00, 2, 3]),
  ])
  const reader = createBufferReader({
    data: buffer
  })

  let decompressedLayout = filler(16 * 16, 2)
  decompressedLayout[0] = 1
  decompressedLayout[255] = 3

  const data = reader.readWordArrayCompressed(16 * 16)
  expect(data.bufsize).toEqual(4 * 2)
  expect(data.decompressed).toEqual(decompressedLayout)
}

{
  // can read compressed byte array
  const buffer = makeBuffer([
    B.u32(5),
    B.u8([1, 0xff, ((16 * 16) - 2), 2, 3]),
  ])
  const reader = createBufferReader({
    data: buffer
  })

  let decompressedLayout = filler(16 * 16, 2)
  decompressedLayout[0] = 1
  decompressedLayout[255] = 3

  const data = reader.readByteArrayCompressed(16 * 16)
  expect(data.bufsize).toEqual(5)
  expect(data.decompressed).toEqual(decompressedLayout)
}

{
  // can get remaining # bytes
  const reader = createBufferReader({
    data: Buffer.from([1, 2])
  })

  expect(reader.remaining).toBe(2)
  reader.readByte()
  expect(reader.remaining).toBe(1)
  reader.readByte()
  expect(reader.remaining).toBe(0)
}

{
  // can read zlibU8 buffers
  const raw = filler(16 * 16, 99)
  const compressedBuffer = zlib.deflateSync(B.u8(raw))
  const buffer = makeBuffer([
    B.u32([raw.length, compressedBuffer.length]),
    compressedBuffer
  ])
  const reader = createBufferReader({data: buffer})
  const data = reader.readZlibU8(16 * 16)

  expect(data.mysize).toBe(raw.length)
  expect(data.comprLen).toBe(compressedBuffer.length)
  expect(data.compressed.length).toBe(compressedBuffer.length)
  expect(data.compressed).toEqual(Array.from(compressedBuffer))
  expect(data.decompressed.length).toBe(raw.length)
  expect(data.decompressed).toEqual(raw)
}

{
  // can read zlibU16 buffers
  const raw = filler(16 * 16, 0xbeef)
  const compressedBuffer = zlib.deflateSync(B.u16(raw))
  const buffer = makeBuffer([
    B.u32([raw.length * 2, compressedBuffer.length]),
    compressedBuffer
  ])
  const reader = createBufferReader({data: buffer})
  const data = reader.readZlibU16(16 * 16)

  expect(data.mysize).toBe(raw.length * 2)
  expect(data.comprLen).toBe(compressedBuffer.length)
  expect(data.compressed.length).toBe(compressedBuffer.length)
  expect(data.compressed).toEqual(Array.from(compressedBuffer))
  expect(data.decompressed.length).toBe(raw.length)
  expect(data.decompressed).toEqual(raw)
}

{
  // can read ika zlibU8 buffers
  const raw = filler(16 * 16, 99)
  const compressedBuffer = zlib.deflateSync(B.u8(raw))
  const buffer = makeBuffer([
    B.u32(compressedBuffer.length),
    compressedBuffer
  ])
  const reader = createBufferReader({data: buffer})
  const data = reader.readIkaZlibU8(16 * 16)

  expect(data.comprLen).toBe(compressedBuffer.length)
  expect(data.compressed.length).toBe(compressedBuffer.length)
  expect(data.compressed).toEqual(Array.from(compressedBuffer))
  expect(data.decompressed.length).toBe(raw.length)
  expect(data.decompressed).toEqual(raw)
}

{
  // can read ika zlibU32 buffers
  const raw = filler(16 * 16, 0xbeef)
  const compressedBuffer = zlib.deflateSync(B.u32(raw))
  const buffer = makeBuffer([
    B.u32(compressedBuffer.length),
    compressedBuffer
  ])
  const reader = createBufferReader({data: buffer})
  const data = reader.readIkaZlibU32(16 * 16)

  expect(data.comprLen).toBe(compressedBuffer.length)
  expect(data.compressed.length).toBe(compressedBuffer.length)
  expect(data.compressed).toEqual(Array.from(compressedBuffer))
  expect(data.decompressed.length).toBe(raw.length)
  expect(data.decompressed).toEqual(raw)
}

{
  // throw on zlibU8 size mismatch
  const reader = createBufferReader({
    data: B.u32(16 * 16 * 3),
  })

  expect(() => {
    reader.readZlibU8(16 * 16)
  }).toThrow(`expected an uncompressed byte length of 256 but got 768`)
}

{
  // throw on zlibU16 size mismatch
  const howManyWords = 3
  const reader = createBufferReader({
    data: B.u32((howManyWords * 2) + 1),
  })

  expect(() => {
    reader.readZlibU16(howManyWords)
  }).toThrow(`expected an uncompressed byte length of 6 but got 7`)
}


text: require 'active_couch'


text:
package com.ait.lienzo.client.core.shape.wires.layout.direction;

import java.util.HashMap;
import java.util.Map;

import com.ait.lienzo.client.core.shape.wires.layout.direction.DirectionLayout.Direction;
import com.ait.lienzo.client.core.shape.wires.layout.direction.DirectionLayout.Orientation;
import com.ait.lienzo.client.core.shape.wires.layout.direction.DirectionLayout.ReferencePosition;
import com.ait.lienzo.client.core.shape.wires.layout.direction.DirectionLayout.VerticalAlignment;
import com.ait.lienzo.client.core.types.BoundingBox;
import com.ait.tooling.common.api.java.util.function.Function;

public class VerticalLayoutFactory
{
    private static final Map<ReferencePosition, DirectionLayoutBuilder<VerticalAlignment>> BUILDERS = builders();

    private static Map<ReferencePosition, DirectionLayoutBuilder<VerticalAlignment>> builders()
    {
        final Map<ReferencePosition, DirectionLayoutBuilder<VerticalAlignment>> builders = new HashMap<>();
        builders.put(ReferencePosition.OUTSIDE, new OuterVerticalLayoutBuilder());
        builders.put(ReferencePosition.INSIDE, new InnerVerticalLayoutBuilder());
        return builders;
    }

    private VerticalLayoutFactory()
    {

    }

    public static DirectionLayoutBuilder<VerticalAlignment> get(ReferencePosition referencePosition)
    {
        return BUILDERS.get(referencePosition);
    }

    protected static final class OuterVerticalLayoutBuilder implements DirectionLayoutBuilder<VerticalAlignment>
    {
        @Override
        public Double apply(final BoundingBox parentBoundingBox, final BoundingBox childBoundingBox,
                            final VerticalAlignment alignment, final Orientation orientation,
                            final Function<Direction, Double> margins)
        {
            switch (alignment)
            {
                case TOP:
                    return parentBoundingBox.getMinY() - childBoundingBox.getHeight() - margins
                            .apply(VerticalAlignment.TOP);
                case BOTTOM:
                    return parentBoundingBox.getMaxY() + margins.apply(VerticalAlignment.BOTTOM) + (Orientation.VERTICAL
                                                                                .equals(orientation) ? childBoundingBox.getWidth() : 0);
                case MIDDLE:
                default:
                    return getMiddle(parentBoundingBox, childBoundingBox, orientation,
                                     margins.apply(VerticalAlignment.TOP));
            }
        }
    }

    protected static final class InnerVerticalLayoutBuilder implements DirectionLayoutBuilder<VerticalAlignment>
    {
        @Override
        public Double apply(final BoundingBox parentBoundingBox, final BoundingBox childBoundingBox,
                            final VerticalAlignment alignment, final Orientation orientation,
                            final Function<Direction, Double> margins)
        {
            switch (alignment)
            {
                case TOP:
                    return parentBoundingBox.getMinY() + margins.apply(VerticalAlignment.TOP) + (Orientation.VERTICAL
                                                                                .equals(orientation) ? childBoundingBox.getWidth() : 0);
                case BOTTOM:
                    return parentBoundingBox.getMaxY() - childBoundingBox.getHeight() - margins
                            .apply(VerticalAlignment.BOTTOM) - (Orientation.VERTICAL.equals(orientation) ?
                                                                childBoundingBox.getWidth() :
                                                                0);
                case MIDDLE:
                default:
                    return getMiddle(parentBoundingBox, childBoundingBox, orientation,
                                     margins.apply(VerticalAlignment.TOP));
            }
        }
    }

    private static double getMiddle(final BoundingBox parentBoundingBox, final BoundingBox childBoundingBox,
                                    final Orientation orientation, final double margin)
    {
        double y = parentBoundingBox.getMinY() + (parentBoundingBox.getHeight() / 2) + (Orientation.VERTICAL
                                                                                .equals(orientation) ? (childBoundingBox.getHeight() / 2) : -(childBoundingBox.getHeight() / 2));
        return y > margin ? y : margin;
    }
}


text:
package avltree

// addData holds information used when adding nodes
type addData struct {
	lookingFor interface{}
	duplicate  interface{}
	tree       *Tree
}

func (d *addData) add(node **treeNode, taller *bool) interface{} {
	*taller = false // default: not taller
	var ptr interface{}
	ptr = nil

	if *node == nil {
		*node = newNode(d.lookingFor)
		*taller = true
		if *node != nil {
			ptr = (*node).value
		}
	} else {
		tallerSubTree := false

		code := d.tree.compare(d.lookingFor, (*node).value)

		if code == 0 && (d.tree.treeFlags&AllowDuplicates) != 0 {
			code = -1 // go left for duplicates
		}

		if code < 0 {
			ptr = d.add(&((*node).left), &tallerSubTree)
			if ptr != nil {
				if tallerSubTree {
					switch (*node).bal {
					case leftHigh:
						*node, *taller = leftBalance(*node, *taller)
					case equal:
						(*node).bal = leftHigh
						*taller = true
					case rightHigh:
						(*node).bal = equal
						*taller = false
					}
				}
			}
		} else if code > 0 {
			ptr = d.add(&((*node).right), &tallerSubTree)
			if ptr != nil {
				if tallerSubTree {
					switch (*node).bal {
					case leftHigh:
						(*node).bal = equal
						*taller = false
					case equal:
						(*node).bal = rightHigh
						*taller = true
					case rightHigh:
						*node, *taller = rightBalance(*node, *taller)
					}
				}
			}
		} else {
			d.duplicate = (*node).value // this node is the duplicate
		}

		if ptr != nil {
			(*node).size = (*node).leftSize() + (*node).rightSize() + 1
		}
	}

	return ptr
}

// Add adds an item to the tree, returning a pair indicating the added
// (or duplicate) item, and a flag indicating whether the item is the
// duplicate that was found. A duplicate will never be returned if the
// tree's AllowDuplicates flag is set.
func (t *Tree) Add(o interface{}) (val interface{}, isDupe bool) {
	d := &addData{o, nil, t}
	taller := false
	isDupe = false
	val = d.add(&t.root, &taller)
	if val == nil {
		isDupe = true
		val = d.duplicate
	}
	return
}

func rightBalance(node *treeNode, taller bool) (*treeNode, bool) {
	var x *treeNode // right subtree of node
	var w *treeNode // left subtree of x

	x = node.right

	switch x.bal {
	case rightHigh:
		node.bal = equal
		x.bal = equal
		node = rotateLeft(node)
		taller = false
	case equal:
		// this should be impossible
	case leftHigh:
		w = x.left
		switch w.bal {
		case equal:
			node.bal = equal
			x.bal = equal
		case leftHigh:
			node.bal = equal
			x.bal = rightHigh
		case rightHigh:
			node.bal = leftHigh
			x.bal = equal
		}
		w.bal = equal
		x = rotateRight(x)
		node.right = x
		node = rotateLeft(node)
		taller = false
	}
	return node, taller
}

func leftBalance(node *treeNode, taller bool) (*treeNode, bool) {
	var x *treeNode // left subtree of node
	var w *treeNode // right subtree of x

	x = node.left

	switch x.bal {
	case leftHigh:
		node.bal = equal
		x.bal = equal
		node = rotateRight(node)
		taller = false
	case equal:
		// this should be impossible
	case rightHigh:
		w = x.right
		switch w.bal {
		case equal:
			node.bal = equal
			x.bal = equal
		case rightHigh:
			node.bal = equal
			x.bal = leftHigh
		case leftHigh:
			node.bal = rightHigh
			x.bal = equal
		}
		w.bal = equal
		x = rotateLeft(x)
		node.left = x
		node = rotateRight(node)
		taller = false
	}
	return node, taller
}

func rotateLeft(node *treeNode) *treeNode {
	if node != nil && node.right != nil {
		ptr := node.right
		node.size = node.leftSize() + ptr.leftSize() + 1
		ptr.size = node.size + ptr.rightSize() + 1
		node.right = ptr.left
		ptr.left = node
		node = ptr
	}
	return node
}

func rotateRight(node *treeNode) *treeNode {
	if node != nil && node.left != nil {
		ptr := node.left
		node.size = node.rightSize() + ptr.rightSize() + 1
		ptr.size = node.size + ptr.leftSize() + 1
		node.left = ptr.right
		ptr.right = node
		node = ptr
	}
	return node
}