text:
namespace grpc_core {

// Describes the rules for matching permission or principal.
class AuthorizationMatcher {
 public:
  virtual ~AuthorizationMatcher() = default;

  // Returns whether or not the permission/principal matches the rules of the
  // matcher.
  virtual bool Matches(const EvaluateArgs& args) const = 0;

  // Creates an instance of a matcher based off the rules defined in Permission
  // config.
  static std::unique_ptr<AuthorizationMatcher> Create(
      Rbac::Permission permission);

  // Creates an instance of a matcher based off the rules defined in Principal
  // config.
  static std::unique_ptr<AuthorizationMatcher> Create(
      Rbac::Principal principal);
};

class AlwaysAuthorizationMatcher : public AuthorizationMatcher {
 public:
  explicit AlwaysAuthorizationMatcher() = default;

  bool Matches(const EvaluateArgs&) const override { return true; }
};

class AndAuthorizationMatcher : public AuthorizationMatcher {
 public:
  explicit AndAuthorizationMatcher(
      std::vector<std::unique_ptr<AuthorizationMatcher>> matchers)
      : matchers_(std::move(matchers)) {}

  bool Matches(const EvaluateArgs& args) const override;

 private:
  std::vector<std::unique_ptr<AuthorizationMatcher>> matchers_;
};

class OrAuthorizationMatcher : public AuthorizationMatcher {
 public:
  explicit OrAuthorizationMatcher(
      std::vector<std::unique_ptr<AuthorizationMatcher>> matchers)
      : matchers_(std::move(matchers)) {}

  bool Matches(const EvaluateArgs& args) const override;

 private:
  std::vector<std::unique_ptr<AuthorizationMatcher>> matchers_;
};

// Negates matching the provided permission/principal.
class NotAuthorizationMatcher : public AuthorizationMatcher {
 public:
  explicit NotAuthorizationMatcher(
      std::unique_ptr<AuthorizationMatcher> matcher)
      : matcher_(std::move(matcher)) {}

  bool Matches(const EvaluateArgs& args) const override;

 private:
  std::unique_ptr<AuthorizationMatcher> matcher_;
};

// TODO(ashithasantosh): Add matcher implementation for metadata field.

// Perform a match against HTTP headers.
class HeaderAuthorizationMatcher : public AuthorizationMatcher {
 public:
  explicit HeaderAuthorizationMatcher(HeaderMatcher matcher)
      : matcher_(std::move(matcher)) {}

  bool Matches(const EvaluateArgs& args) const override;

 private:
  const HeaderMatcher matcher_;
};

// Perform a match against IP Cidr Range.
class IpAuthorizationMatcher : public AuthorizationMatcher {
 public:
  enum class Type {
    kDestIp,
    kSourceIp,
    kDirectRemoteIp,
    kRemoteIp,
  };

  IpAuthorizationMatcher(Type type, Rbac::CidrRange range);

  bool Matches(const EvaluateArgs& args) const override;

 private:
  const Type type_;
  // Subnet masked address.
  grpc_resolved_address subnet_address_;
  const uint32_t prefix_len_;
};

// Perform a match against port number of the destination (local) address.
class PortAuthorizationMatcher : public AuthorizationMatcher {
 public:
  explicit PortAuthorizationMatcher(int port) : port_(port) {}

  bool Matches(const EvaluateArgs& args) const override;

 private:
  const int port_;
};

// Matches the principal name as described in the peer certificate. Uses URI SAN
// or DNS SAN in that order, otherwise uses subject field.
class AuthenticatedAuthorizationMatcher : public AuthorizationMatcher {
 public:
  explicit AuthenticatedAuthorizationMatcher(StringMatcher auth)
      : matcher_(std::move(auth)) {}

  bool Matches(const EvaluateArgs& args) const override;

 private:
  const StringMatcher matcher_;
};

// Perform a match against the request server from the client's connection
// request. This is typically TLS SNI. Currently unsupported.
class ReqServerNameAuthorizationMatcher : public AuthorizationMatcher {
 public:
  explicit ReqServerNameAuthorizationMatcher(
      StringMatcher requested_server_name)
      : matcher_(std::move(requested_server_name)) {}

  bool Matches(const EvaluateArgs&) const override;

 private:
  const StringMatcher matcher_;
};

// Perform a match against the path header of HTTP request.
class PathAuthorizationMatcher : public AuthorizationMatcher {
 public:
  explicit PathAuthorizationMatcher(StringMatcher path)
      : matcher_(std::move(path)) {}

  bool Matches(const EvaluateArgs& args) const override;

 private:
  const StringMatcher matcher_;
};

// Performs a match for policy field in RBAC, which is a collection of
// permission and principal matchers. Policy matches iff, we find a match in one
// of its permissions and a match in one of its principals.
class PolicyAuthorizationMatcher : public AuthorizationMatcher {
 public:
  explicit PolicyAuthorizationMatcher(Rbac::Policy policy)
      : permissions_(
            AuthorizationMatcher::Create(std::move(policy.permissions))),
        principals_(
            AuthorizationMatcher::Create(std::move(policy.principals))) {}

  bool Matches(const EvaluateArgs& args) const override;

 private:
  std::unique_ptr<AuthorizationMatcher> permissions_;
  std::unique_ptr<AuthorizationMatcher> principals_;
};

}  // namespace grpc_core

#endif  // GRPC_CORE_LIB_SECURITY_AUTHORIZATION_MATCHERS_H


text:
<?php
namespace Juniorb2ss\LaravelRouteExtendsMacros\Macros;
use Illuminate\Http\RedirectResponse;
use Illuminate\Routing\Router;
use Juniorb2ss\LaravelRouteExtendsMacros\Contracts\MacroInterface;

/**
 *
 */
class File implements MacroInterface {
	/**
	 * [register description]
	 * @return void
	 */
	public function register(Router $route) {
		$route->macro('file', function($url, $file, array $headers = []) use ($route) {
			return $route->any($url, '\Juniorb2ss\LaravelRouteExtendsMacros\Macros\File@handle')
				->defaults('file', compact('file', 'headers'));
		});
	}

	/**
	 * Return the raw contents of a binary file.
	 *
	 * @param  \SplFileInfo|string  $file
	 * @param  array  $headers
	 * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
	 */
	public function handle($file, array $headers = []) {
		$file = (is_callable($file) ? $file() : $file);
		return response()->file($file, $headers);
	}

	/**
	 * Extract the redirect data from the route and call the handler.
	 *
	 * @param  string  $method
	 * @param  array  $parameters
	 * @return \Illuminate\Http\RedirectResponse
	 * @SuppressWarnings("unused")
	 */
	public function callAction($method, $parameters) {
		return call_user_func_array([$this, $method], $parameters['file']);
	}
}

redpajama_set_name: RedPajamaGithub


text:
Hate keeping track of and setting up your development environment? So do we, so we made Silhouette!

- Use the buttons on the left to manage everything that is being tracked

- Click Set Up Environment to download your files, globally install modules and install applications to your applications folder

Enjoy!

## Dev

```
$ npm install
```

### Run

```
$ npm start
```

### Build

```
$ npm run build
```

## License

MIT © [Annie Cook, Anna Goldberg, Jovia Nierenberg](http://localhost:1337)


text:
package com.cloud.ucs.database;

import com.cloud.utils.db.GenericDao;

public interface UcsBladeDao extends GenericDao<UcsBladeVO, Long> {

}


text:
<?php

namespace Monolog\Handler;

use Monolog\Logger;

/**
 * Stores to any stream resource
 *
 * Can be used to store into php://stderr, remote and local files, etc.
 *
 * @author Jordi Boggiano <j.boggiano@seld.be>
 */
class StreamHandler extends AbstractProcessingHandler
{
    protected $stream;
    protected $url;

    /**
     * @param string  $stream
     * @param integer $level  The minimum logging level at which this handler will be triggered
     * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct($stream, $level = Logger::DEBUG, $bubble = true)
    {
        parent::__construct($level, $bubble);
        if (is_resource($stream)) {
            $this->stream = $stream;
        } else {
            $this->url = $stream;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function close()
    {
        if (is_resource($this->stream)) {
            fclose($this->stream);
        }
        $this->stream = null;
    }

    /**
     * {@inheritdoc}
     */
    protected function write(array $record)
    {
        if (null === $this->stream) {
            if (!$this->url) {
                throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().');
            }
            $errorMessage = null;
            set_error_handler(function ($code, $msg) use (&$errorMessage) {
                $errorMessage = preg_replace('{^fopen\(.*?\): }', '', $msg);
            });
            $this->stream = fopen($this->url, 'a');
            restore_error_handler();
            if (!is_resource($this->stream)) {
                $this->stream = null;
                throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened: '.$errorMessage, $this->url));
            }
        }
        fwrite($this->stream, (string) $record['formatted']);
    }
}


text:
#include "dart/utils/XmlHelpers.hpp"

#include <iostream>
#include <vector>

#include <fmt/format.h>

#include "dart/common/Console.hpp"
#include "dart/common/LocalResourceRetriever.hpp"
#include "dart/math/Geometry.hpp"

namespace dart {
namespace utils {

//==============================================================================
std::string toString(bool v)
{
  return fmt::format("{}", v);
}

//==============================================================================
std::string toString(int v)
{
  return std::to_string(v);
}

//==============================================================================
std::string toString(unsigned int v)
{
  return std::to_string(v);
}

//==============================================================================
std::string toString(float v)
{
  return std::to_string(v);
}

//==============================================================================
std::string toString(double v)
{
  return std::to_string(v);
}

//==============================================================================
std::string toString(char v)
{
  return fmt::format("{}", v);
}

//==============================================================================
bool toBool(const std::string& str)
{
  if (common::toUpper(str) == "TRUE" || str == "1")
    return true;
  else if (common::toUpper(str) == "FALSE" || str == "0")
    return false;
  else
  {
    dterr << "value [" << str << "] is not a valid boolean type. "
          << "Retuning false." << std::endl;
    return false;
  }
}

//==============================================================================
int toInt(const std::string& str)
{
  return std::stoi(str);
}

//==============================================================================
unsigned int toUInt(const std::string& str)
{
  return static_cast<unsigned int>(std::stoul(str));
}

//==============================================================================
float toFloat(const std::string& str)
{
  return std::stof(str);
}

//==============================================================================
double toDouble(const std::string& str)
{
  return std::stod(str);
}

//==============================================================================
char toChar(const std::string& str)
{
  if (str.empty())
  {
    DART_ERROR("");
    return 0;
  }

  if (str.size() != 1)
  {
    DART_ERROR("");
  }

  return str[0];
}

//==============================================================================
Eigen::Vector2d toVector2d(const std::string& str)
{
  Eigen::Vector2d ret;

  const std::vector<std::string> pieces = common::split(common::trim(str));
  assert(pieces.size() == 2);

  for (std::size_t i = 0; i < pieces.size(); ++i)
  {
    if (pieces[i] != "")
    {
      try
      {
        ret[i] = toDouble(pieces[i]);
      }
      catch (std::exception& e)
      {
        std::cerr << "value [" << pieces[i]
                  << "] is not a valid double for Eigen::Vector2d[" << i
                  << "]: " << e.what() << std::endl;
      }
    }
  }

  return ret;
}

//==============================================================================
Eigen::Vector2i toVector2i(const std::string& str)
{
  Eigen::Vector2i ret;

  const std::vector<std::string> pieces = common::split(common::trim(str));
  assert(pieces.size() == 2);

  for (std::size_t i = 0; i < pieces.size(); ++i)
  {
    if (pieces[i] != "")
    {
      try
      {
        ret[i] = toDouble(pieces[i]);
      }
      catch (std::exception& e)
      {
        std::cerr << "value [" << pieces[i]
                  << "] is not a valid double for Eigen::Vector2i[" << i
                  << "]: " << e.what() << std::endl;
      }
    }
  }

  return ret;
}

//==============================================================================
Eigen::Vector3d toVector3d(const std::string& str)
{
  Eigen::Vector3d ret;

  const std::vector<std::string> pieces = common::split(common::trim(str));
  assert(pieces.size() == 3);

  for (std::size_t i = 0; i < pieces.size(); ++i)
  {
    if (pieces[i] != "")
    {
      try
      {
        ret[i] = toDouble(pieces[i]);
      }
      catch (std::exception& e)
      {
        std::cerr << "value [" << pieces[i]
                  << "] is not a valid double for Eigen::Vector3d[" << i
                  << "]: " << e.what() << std::endl;
      }
    }
  }

  return ret;
}

//==============================================================================
Eigen::Vector3i toVector3i(const std::string& str)
{
  Eigen::Vector3i ret;

  const std::vector<std::string> pieces = common::split(common::trim(str));
  assert(pieces.size() == 3);

  for (std::size_t i = 0; i < pieces.size(); ++i)
  {
    if (pieces[i] != "")
    {
      try
      {
        ret[i] = toDouble(pieces[i]);
      }
      catch (std::exception& e)
      {
        std::cerr << "value [" << pieces[i]
                  << "] is not a valid int for Eigen::Vector3i[" << i
                  << "]: " << e.what() << std::endl;
      }
    }
  }

  return ret;
}

//==============================================================================
Eigen::Vector4d toVector4d(const std::string& str)
{
  Eigen::Vector4d ret;

  const std::vector<std::string> pieces = common::split(common::trim(str));
  assert(pieces.size() == 4);

  for (std::size_t i = 0; i < pieces.size(); ++i)
  {
    if (pieces[i] != "")
    {
      try
      {
        ret[i] = toDouble(pieces[i]);
      }
      catch (std::exception& e)
      {
        std::cerr << "value [" << pieces[i]
                  << "] is not a valid double for Eigen::Vector4d[" << i
                  << "]: " << e.what() << std::endl;
      }
    }
  }

  return ret;
}

//==============================================================================
Eigen::Vector6d toVector6d(const std::string& str)
{
  Eigen::Vector6d ret;

  const std::vector<std::string> pieces = common::split(common::trim(str));
  assert(pieces.size() == 6);

  for (std::size_t i = 0; i < pieces.size(); ++i)
  {
    if (pieces[i] != "")
    {
      try
      {
        ret[i] = toDouble(pieces[i]);
      }
      catch (std::exception& e)
      {
        std::cerr << "value [" << pieces[i]
                  << "] is not a valid double for Eigen::Vector6d[" << i
                  << "]: " << e.what() << std::endl;
      }
    }
  }

  return ret;
}

//==============================================================================
Eigen::VectorXd toVectorXd(const std::string& str)
{
  const std::vector<std::string> pieces = common::split(common::trim(str));
  assert(pieces.size() > 0);

  Eigen::VectorXd ret(pieces.size());

  for (std::size_t i = 0; i < pieces.size(); ++i)
  {
    if (pieces[i] != "")
    {
      try
      {
        ret[i] = toDouble(pieces[i]);
      }
      catch (std::exception& e)
      {
        std::cerr << "value [" << pieces[i]
                  << "] is not a valid double for Eigen::VectorXd[" << i
                  << "]: " << e.what() << std::endl;
      }
    }
  }

  return ret;
}

//==============================================================================
Eigen::Isometry3d toIsometry3d(const std::string& str)
{
  Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
  Eigen::Vector6d elements = Eigen::Vector6d::Zero();
  const std::vector<std::string> pieces = common::split(common::trim(str));
  assert(pieces.size() == 6);

  for (std::size_t i = 0; i < pieces.size(); ++i)
  {
    if (pieces[i] != "")
    {
      try
      {
        elements[i] = toDouble(pieces[i]);
      }
      catch (std::exception& e)
      {
        std::cerr << "value [" << pieces[i]
                  << "] is not a valid double for SE3[" << i
                  << "]: " << e.what() << std::endl;
      }
    }
  }

  T.linear() = math::eulerXYZToMatrix(elements.tail<3>());
  T.translation() = elements.head<3>();
  return T;
}

//==============================================================================
Eigen::Isometry3d toIsometry3dWithExtrinsicRotation(const std::string& str)
{
  Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
  Eigen::Vector6d elements = Eigen::Vector6d::Zero();
  const std::vector<std::string> pieces = common::split(common::trim(str));
  assert(pieces.size() == 6);

  for (std::size_t i = 0; i < pieces.size(); ++i)
  {
    if (pieces[i] != "")
    {
      try
      {
        elements[i] = toDouble(pieces[i]);
      }
      catch (std::exception& e)
      {
        std::cerr << "value [" << pieces[i]
                  << "] is not a valid double for SE3[" << i
                  << "]: " << e.what() << std::endl;
      }
    }
  }

  Eigen::Vector3d reverseEulerAngles(
      elements.tail<3>()[2], elements.tail<3>()[1], elements.tail<3>()[0]);

  T.linear() = math::eulerZYXToMatrix(reverseEulerAngles);
  T.translation() = elements.head<3>();
  return T;
}

//==============================================================================
std::string getValueString(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  std::string str = parentElement->FirstChildElement(name.c_str())->GetText();

  return str;
}

//==============================================================================
bool getValueBool(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  std::string str = parentElement->FirstChildElement(name.c_str())->GetText();

  if (common::toUpper(str) == "TRUE" || str == "1")
    return true;
  else if (common::toUpper(str) == "FALSE" || str == "0")
    return false;
  else
  {
    std::cerr << "value [" << str << "] is not a valid boolean type. "
              << "Returning false." << std::endl;
    assert(0);
    return false;
  }
}

//==============================================================================
int getValueInt(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  std::string str = parentElement->FirstChildElement(name.c_str())->GetText();

  return toInt(str);
}

//==============================================================================
unsigned int getValueUInt(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  std::string str = parentElement->FirstChildElement(name.c_str())->GetText();

  return toUInt(str);
}

//==============================================================================
float getValueFloat(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  std::string str = parentElement->FirstChildElement(name.c_str())->GetText();

  return toFloat(str);
}

//==============================================================================
double getValueDouble(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  std::string str = parentElement->FirstChildElement(name.c_str())->GetText();

  return toDouble(str);
}

//==============================================================================
char getValueChar(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  std::string str = parentElement->FirstChildElement(name.c_str())->GetText();

  return toChar(str);
}

//==============================================================================
Eigen::Vector2d getValueVector2d(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  std::string str = parentElement->FirstChildElement(name.c_str())->GetText();

  return toVector2d(str);
}

//==============================================================================
Eigen::Vector3d getValueVector3d(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  std::string str = parentElement->FirstChildElement(name.c_str())->GetText();

  return toVector3d(str);
}

//==============================================================================
Eigen::Vector3i getValueVector3i(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  std::string str = parentElement->FirstChildElement(name.c_str())->GetText();

  return toVector3i(str);
}

//==============================================================================
Eigen::Vector6d getValueVector6d(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  std::string str = parentElement->FirstChildElement(name.c_str())->GetText();

  return toVector6d(str);
}

//==============================================================================
Eigen::VectorXd getValueVectorXd(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  std::string str = parentElement->FirstChildElement(name.c_str())->GetText();

  return toVectorXd(str);
}

//==============================================================================
Eigen::Vector3d getValueVec3(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  std::string str = parentElement->FirstChildElement(name.c_str())->GetText();

  return toVector3d(str);
}

//==============================================================================
Eigen::Isometry3d getValueIsometry3d(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  std::string str = parentElement->FirstChildElement(name.c_str())->GetText();

  return toIsometry3d(str);
}

//==============================================================================
Eigen::Isometry3d getValueIsometry3dWithExtrinsicRotation(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  std::string str = parentElement->FirstChildElement(name.c_str())->GetText();

  return toIsometry3dWithExtrinsicRotation(str);
}

//==============================================================================
bool hasElement(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(parentElement != nullptr);
  assert(!name.empty());

  return parentElement->FirstChildElement(name.c_str()) == nullptr ? false
                                                                   : true;
}

//==============================================================================
const tinyxml2::XMLElement* getElement(
    const tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(!name.empty());

  return parentElement->FirstChildElement(name.c_str());
}

//==============================================================================
tinyxml2::XMLElement* getElement(
    tinyxml2::XMLElement* parentElement, const std::string& name)
{
  assert(!name.empty());

  return parentElement->FirstChildElement(name.c_str());
}

//==============================================================================
std::string toString(tinyxml2::XMLError errorCode)
{
  switch (errorCode)
  {
    case tinyxml2::XMLError::XML_SUCCESS:
      return "XML_SUCCESS";
    case tinyxml2::XMLError::XML_NO_ATTRIBUTE:
      return "XML_NO_ATTRIBUTE";
    case tinyxml2::XMLError::XML_WRONG_ATTRIBUTE_TYPE:
      return "XML_WRONG_ATTRIBUTE_TYPE";
    case tinyxml2::XMLError::XML_ERROR_FILE_NOT_FOUND:
      return "XML_ERROR_FILE_NOT_FOUND";
    case tinyxml2::XMLError::XML_ERROR_FILE_COULD_NOT_BE_OPENED:
      return "XML_ERROR_FILE_COULD_NOT_BE_OPENED";
    case tinyxml2::XMLError::XML_ERROR_FILE_READ_ERROR:
      return "XML_ERROR_FILE_READ_ERROR";
    case tinyxml2::XMLError::XML_ERROR_PARSING_ELEMENT:
      return "XML_ERROR_PARSING_ELEMENT";
    case tinyxml2::XMLError::XML_ERROR_PARSING_ATTRIBUTE:
      return "XML_ERROR_PARSING_ATTRIBUTE";
    case tinyxml2::XMLError::XML_ERROR_PARSING_TEXT:
      return "XML_ERROR_PARSING_TEXT";
    case tinyxml2::XMLError::XML_ERROR_PARSING_CDATA:
      return "XML_ERROR_PARSING_CDATA";
    case tinyxml2::XMLError::XML_ERROR_PARSING_COMMENT:
      return "XML_ERROR_PARSING_COMMENT";
    case tinyxml2::XMLError::XML_ERROR_PARSING_DECLARATION:
      return "XML_ERROR_PARSING_DECLARATION";
    case tinyxml2::XMLError::XML_ERROR_PARSING_UNKNOWN:
      return "XML_ERROR_PARSING_UNKNOWN";
    case tinyxml2::XMLError::XML_ERROR_EMPTY_DOCUMENT:
      return "XML_ERROR_EMPTY_DOCUMENT";
    case tinyxml2::XMLError::XML_ERROR_MISMATCHED_ELEMENT:
      return "XML_ERROR_MISMATCHED_ELEMENT";
    case tinyxml2::XMLError::XML_ERROR_PARSING:
      return "XML_ERROR_PARSING";
    case tinyxml2::XMLError::XML_CAN_NOT_CONVERT_TEXT:
      return "XML_CAN_NOT_CONVERT_TEXT";
    case tinyxml2::XMLError::XML_NO_TEXT_NODE:
      return "XML_NO_TEXT_NODE";
    case tinyxml2::XMLError::XML_ERROR_COUNT:
      return "XML_ERROR_COUNT";
    default:
      return "Unknow error";
  }
}

//==============================================================================
void openXMLFile(
    tinyxml2::XMLDocument& doc,
    const common::Uri& uri,
    const common::ResourceRetrieverPtr& retrieverOrNullPtr)
{
  common::ResourceRetrieverPtr retriever;
  if (retrieverOrNullPtr)
    retriever = retrieverOrNullPtr;
  else
    retriever = std::make_shared<common::LocalResourceRetriever>();

  const auto content = retriever->readAll(uri);
  const auto result = doc.Parse(&content.front());
  if (result != tinyxml2::XML_SUCCESS)
  {
    dtwarn << "[openXMLFile] Failed parsing XML: TinyXML2 returned error '"
           << toString(result) << "'.\n";
    throw std::runtime_error("Failed parsing XML.");
  }
}

//==============================================================================
bool readXmlFile(
    tinyxml2::XMLDocument& doc,
    const common::Uri& uri,
    const common::ResourceRetrieverPtr& retrieverOrNullPtr)
{
  common::ResourceRetrieverPtr retriever;
  if (retrieverOrNullPtr)
    retriever = retrieverOrNullPtr;
  else
    retriever = std::make_shared<common::LocalResourceRetriever>();

  const auto content = retriever->readAll(uri);
  const auto result = doc.Parse(&content.front());
  if (result != tinyxml2::XML_SUCCESS)
  {
    dtwarn << "[readXmlFile] Failed parsing XML: TinyXML2 returned error '"
           << toString(result) << "'.\n";
    return false;
  }

  return true;
}

//==============================================================================
bool hasAttribute(const tinyxml2::XMLElement* element, const char* const name)
{
  const char* const result = element->Attribute(name);
  return result != nullptr;
}

//==============================================================================
std::string getAttribute(tinyxml2::XMLElement* element, const char* const name)
{
  return getAttributeString(element, name);
}

//==============================================================================
void getAttribute(
    tinyxml2::XMLElement* element, const char* const name, double* d)
{
  *d = getAttributeDouble(element, name);
}

//==============================================================================
std::string getAttributeString(
    const tinyxml2::XMLElement* element, const std::string& attributeName)
{
  const char* const result = element->Attribute(attributeName.c_str());

  if (nullptr == result)
  {
    dtwarn << "[getAttribute] Error in parsing string type attribute ["
           << attributeName << "] of an element [" << element->Name()
           << "]. Returning empty string.\n";
    return std::string();
  }

  return std::string(result);
}

//==============================================================================
bool getAttributeBool(
    const tinyxml2::XMLElement* element, const std::string& attributeName)
{
  bool val = false;
  const int result = element->QueryBoolAttribute(attributeName.c_str(), &val);

  if (result != tinyxml2::XML_SUCCESS)
  {
    dtwarn << "[getAttribute] Error in parsing bool type attribute ["
           << attributeName << "] of an element [" << element->Name()
           << "]. Returning false instead.\n";
    return false;
  }

  return val;
}

//==============================================================================
int getAttributeInt(
    const tinyxml2::XMLElement* element, const std::string& attributeName)
{
  int val = 0;
  const int result = element->QueryIntAttribute(attributeName.c_str(), &val);

  if (result != tinyxml2::XML_SUCCESS)
  {
    dtwarn << "[getAttribute] Error in parsing int type attribute ["
           << attributeName << "] of an element [" << element->Name()
           << "]. Returning zero instead.\n";
    return 0;
  }

  return val;
}

//==============================================================================
unsigned int getAttributeUInt(
    const tinyxml2::XMLElement* element, const std::string& attributeName)
{
  unsigned int val = 0u;
  const int result
      = element->QueryUnsignedAttribute(attributeName.c_str(), &val);

  if (result != tinyxml2::XML_SUCCESS)
  {
    dtwarn << "[getAttribute] Error in parsing unsiged int type attribute ["
           << attributeName << "] of an element [" << element->Name()
           << "]. Returning zero instead.\n";
    return 0u;
  }

  return val;
}

//==============================================================================
float getAttributeFloat(
    const tinyxml2::XMLElement* element, const std::string& attributeName)
{
  float val = 0.0f;
  const int result = element->QueryFloatAttribute(attributeName.c_str(), &val);

  if (result != tinyxml2::XML_SUCCESS)
  {
    dtwarn << "[getAttribute] Error in parsing float type attribute ["
           << attributeName << "] of an element [" << element->Name()
           << "]. Returning zero instead.\n";
    return 0.0f;
  }

  return val;
}

//==============================================================================
double getAttributeDouble(
    const tinyxml2::XMLElement* element, const std::string& attributeName)
{
  double val = 0.0;
  const int result = element->QueryDoubleAttribute(attributeName.c_str(), &val);

  if (result != tinyxml2::XML_SUCCESS)
  {
    dtwarn << "[getAttribute] Error in parsing double type attribute ["
           << attributeName << "] of an element [" << element->Name()
           << "]. Returning zero instead.\n";
    return 0.0;
  }

  return val;
}

//==============================================================================
char getAttributeChar(
    const tinyxml2::XMLElement* element, const std::string& attributeName)
{
  const std::string val = getAttributeString(element, attributeName);

  return toChar(val);
}

//==============================================================================
Eigen::Vector2i getAttributeVector2i(
    const tinyxml2::XMLElement* element, const std::string& attributeName)
{
  const std::string val = getAttributeString(element, attributeName);

  return toVector2i(val);
}

//==============================================================================
Eigen::Vector2d getAttributeVector2d(
    const tinyxml2::XMLElement* element, const std::string& attributeName)
{
  const std::string val = getAttributeString(element, attributeName);

  return toVector2d(val);
}

//==============================================================================
Eigen::Vector3d getAttributeVector3d(
    const tinyxml2::XMLElement* element, const std::string& attributeName)
{
  const std::string val = getAttributeString(element, attributeName);

  return toVector3d(val);
}

//==============================================================================
Eigen::Vector4d getAttributeVector4d(
    const tinyxml2::XMLElement* element, const std::string& attributeName)
{
  const std::string val = getAttributeString(element, attributeName);

  return toVector4d(val);
}

//==============================================================================
Eigen::Vector6d getAttributeVector6d(
    const tinyxml2::XMLElement* element, const std::string& attributeName)
{
  const std::string val = getAttributeString(element, attributeName);

  return toVector6d(val);
}

//==============================================================================
Eigen::VectorXd getAttributeVectorXd(
    const tinyxml2::XMLElement* element, const std::string& attributeName)
{
  const std::string val = getAttributeString(element, attributeName);

  return toVectorXd(val);
}

//==============================================================================
bool copyNode(tinyxml2::XMLNode* destParent, const tinyxml2::XMLNode& src)
{
  // Protect from evil
  if (destParent == nullptr)
  {
    return false;
  }

  // Get the document context where new memory will be allocated from
  tinyxml2::XMLDocument* doc = destParent->GetDocument();

  // Make the copy
  tinyxml2::XMLNode* copy = src.ShallowClone(doc);
  if (copy == nullptr)
  {
    return false;
  }

  // Add this child
  destParent->InsertEndChild(copy);

  // Add the grandkids
  for (const tinyxml2::XMLNode* node = src.FirstChild(); node != nullptr;
       node = node->NextSibling())
  {
    if (!copyNode(copy, *node))
    {
      return false;
    }
  }

  return true;
}

//==============================================================================
bool copyChildNodes(tinyxml2::XMLNode* destParent, const tinyxml2::XMLNode& src)
{
  for (const tinyxml2::XMLNode* node = src.FirstChild(); node != nullptr;
       node = node->NextSibling())
  {
    if (!copyNode(destParent, *node))
    {
      return false;
    }
  }

  return true;
}

} // namespace utils
} // namespace dart


text: Whether to request the SAML IdP to force (re)authentication of the user, rather than allowing an existing session with the IdP to be reused.  Off by default.


text:
require 'rubygems'
require 'bundler/setup'

require 'semrush' # and any other gems you need
API_KEY = ENV['API_KEY'] || "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

RSpec.configure do |config|
  config.filter_run focus: true
  config.run_all_when_everything_filtered = true
end


text:
package org.lwjgl.vulkan;

import java.nio.*;

import org.lwjgl.*;
import org.lwjgl.system.*;

import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;

/**
 * Khronos Reference Page

 * Vulkan Specification
 *
 *
Describes a memory binding to a {@code VkBuffer} object.

 *
 *
Valid Usage

 *
 *

 *
{@code buffer} must be a valid {@code VkBuffer} handle

 *
{@code pBinds} must be a pointer to an array of {@code bindCount} valid {@link VkSparseMemoryBind} structures

 *
{@code bindCount} must be greater than 0

 *

 *
 *
Member documentation

 *
 *

 *
{@code buffer} – the {@code VkBuffer} object to be bound

 *
{@code bindCount} – the number of {@code VkSparseMemoryBind} structures in the {@code pBinds} array

 *
{@code pBinds} – a pointer to array of {@link VkSparseMemoryBind} structures

 *

 *
 *
Layout

 *
 *
struct VkSparseBufferMemoryBindInfo {
    VkBuffer buffer;
    uint32_t bindCount;
    const VkSparseMemoryBind * pBinds;
}

 */
public class VkSparseBufferMemoryBindInfo extends Struct {

	/** The struct size in bytes. */
	public static final int SIZEOF;

	public static final int ALIGNOF;

	/** The struct member offsets. */
	public static final int
		BUFFER,
		BINDCOUNT,
		PBINDS;

	static {
		Layout layout = __struct(
			__member(8),
			__member(4),
			__member(POINTER_SIZE)
		);

		SIZEOF = layout.getSize();
		ALIGNOF = layout.getAlignment();

		BUFFER = layout.offsetof(0);
		BINDCOUNT = layout.offsetof(1);
		PBINDS = layout.offsetof(2);
	}

	VkSparseBufferMemoryBindInfo(long address, ByteBuffer container) {
		super(address, container);
	}

	/**
	 * Creates a {@link VkSparseBufferMemoryBindInfo} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
	 * visible to the struct instance and vice versa.
	 *
	 *
The created instance holds a strong reference to the container object.

	 */
	public VkSparseBufferMemoryBindInfo(ByteBuffer container) {
		this(memAddress(container), checkContainer(container, SIZEOF));
	}

	@Override
	public int sizeof() { return SIZEOF; }

	/** Returns the value of the {@code buffer} field. */
	public long buffer() { return nbuffer(address()); }
	/** Returns the value of the {@code bindCount} field. */
	public int bindCount() { return nbindCount(address()); }
	/** Returns a {@link VkSparseMemoryBind.Buffer} view of the struct array pointed to by the {@code pBinds} field. */
	public VkSparseMemoryBind.Buffer pBinds() { return npBinds(address()); }

	/** Sets the specified value to the {@code buffer} field. */
	public VkSparseBufferMemoryBindInfo buffer(long value) { nbuffer(address(), value); return this; }
	/** Sets the address of the specified {@link VkSparseMemoryBind.Buffer} to the {@code pBinds} field. */
	public VkSparseBufferMemoryBindInfo pBinds(VkSparseMemoryBind.Buffer value) { npBinds(address(), value); return this; }

	/** Initializes this struct with the specified values. */
	public VkSparseBufferMemoryBindInfo set(
		long buffer,
		VkSparseMemoryBind.Buffer pBinds
	) {
		buffer(buffer);
		pBinds(pBinds);

		return this;
	}

	/** Unsafe version of {@link #set(VkSparseBufferMemoryBindInfo) set}. */
	public VkSparseBufferMemoryBindInfo nset(long struct) {
		memCopy(struct, address(), SIZEOF);
		return this;
	}

	/**
	 * Copies the specified struct data to this struct.
	 *
	 * @param src the source struct
	 *
	 * @return this struct
	 */
	public VkSparseBufferMemoryBindInfo set(VkSparseBufferMemoryBindInfo src) {
		return nset(src.address());
	}

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

	/** Returns a new {@link VkSparseBufferMemoryBindInfo} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
	public static VkSparseBufferMemoryBindInfo malloc() {
		return create(nmemAlloc(SIZEOF));
	}

	/** Returns a new {@link VkSparseBufferMemoryBindInfo} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
	public static VkSparseBufferMemoryBindInfo calloc() {
		return create(nmemCalloc(1, SIZEOF));
	}

	/** Returns a new {@link VkSparseBufferMemoryBindInfo} instance allocated with {@link BufferUtils}. */
	public static VkSparseBufferMemoryBindInfo create() {
		return new VkSparseBufferMemoryBindInfo(BufferUtils.createByteBuffer(SIZEOF));
	}

	/** Returns a new {@link VkSparseBufferMemoryBindInfo} instance for the specified memory address or {@code null} if the address is {@code NULL}. */
	public static VkSparseBufferMemoryBindInfo create(long address) {
		return address == NULL ? null : new VkSparseBufferMemoryBindInfo(address, null);
	}

	/**
	 * Returns a new {@link VkSparseBufferMemoryBindInfo.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer malloc(int capacity) {
		return create(nmemAlloc(capacity * SIZEOF), capacity);
	}

	/**
	 * Returns a new {@link VkSparseBufferMemoryBindInfo.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer calloc(int capacity) {
		return create(nmemCalloc(capacity, SIZEOF), capacity);
	}

	/**
	 * Returns a new {@link VkSparseBufferMemoryBindInfo.Buffer} instance allocated with {@link BufferUtils}.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer create(int capacity) {
		return new Buffer(BufferUtils.createByteBuffer(capacity * SIZEOF));
	}

	/**
	 * Create a {@link VkSparseBufferMemoryBindInfo.Buffer} instance at the specified memory.
	 *
	 * @param address  the memory address
	 * @param capacity the buffer capacity
	 */
	public static Buffer create(long address, int capacity) {
		return address == NULL ? null : new Buffer(address, null, -1, 0, capacity, capacity);
	}

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

	/** Returns a new {@link VkSparseBufferMemoryBindInfo} instance allocated on the thread-local {@link MemoryStack}. */
	public static VkSparseBufferMemoryBindInfo mallocStack() {
		return mallocStack(stackGet());
	}

	/** Returns a new {@link VkSparseBufferMemoryBindInfo} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */
	public static VkSparseBufferMemoryBindInfo callocStack() {
		return callocStack(stackGet());
	}

	/**
	 * Returns a new {@link VkSparseBufferMemoryBindInfo} instance allocated on the specified {@link MemoryStack}.
	 *
	 * @param stack the stack from which to allocate
	 */
	public static VkSparseBufferMemoryBindInfo mallocStack(MemoryStack stack) {
		return create(stack.nmalloc(ALIGNOF, SIZEOF));
	}

	/**
	 * Returns a new {@link VkSparseBufferMemoryBindInfo} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
	 *
	 * @param stack the stack from which to allocate
	 */
	public static VkSparseBufferMemoryBindInfo callocStack(MemoryStack stack) {
		return create(stack.ncalloc(ALIGNOF, 1, SIZEOF));
	}

	/**
	 * Returns a new {@link VkSparseBufferMemoryBindInfo.Buffer} instance allocated on the thread-local {@link MemoryStack}.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer mallocStack(int capacity) {
		return mallocStack(capacity, stackGet());
	}

	/**
	 * Returns a new {@link VkSparseBufferMemoryBindInfo.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer callocStack(int capacity) {
		return callocStack(capacity, stackGet());
	}

	/**
	 * Returns a new {@link VkSparseBufferMemoryBindInfo.Buffer} instance allocated on the specified {@link MemoryStack}.
	 *
	 * @param stack the stack from which to allocate
	 * @param capacity the buffer capacity
	 */
	public static Buffer mallocStack(int capacity, MemoryStack stack) {
		return create(stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
	}

	/**
	 * Returns a new {@link VkSparseBufferMemoryBindInfo.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
	 *
	 * @param stack the stack from which to allocate
	 * @param capacity the buffer capacity
	 */
	public static Buffer callocStack(int capacity, MemoryStack stack) {
		return create(stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
	}

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

	/** Unsafe version of {@link #buffer}. */
	public static long nbuffer(long struct) { return memGetLong(struct + VkSparseBufferMemoryBindInfo.BUFFER); }
	/** Unsafe version of {@link #bindCount}. */
	public static int nbindCount(long struct) { return memGetInt(struct + VkSparseBufferMemoryBindInfo.BINDCOUNT); }
	/** Unsafe version of {@link #pBinds}. */
	public static VkSparseMemoryBind.Buffer npBinds(long struct) { return VkSparseMemoryBind.create(memGetAddress(struct + VkSparseBufferMemoryBindInfo.PBINDS), nbindCount(struct)); }

	/** Unsafe version of {@link #buffer(long) buffer}. */
	public static void nbuffer(long struct, long value) { memPutLong(struct + VkSparseBufferMemoryBindInfo.BUFFER, value); }
	/** Sets the specified value to the {@code bindCount} field of the specified {@code struct}. */
	public static void nbindCount(long struct, int value) { memPutInt(struct + VkSparseBufferMemoryBindInfo.BINDCOUNT, value); }
	/** Unsafe version of {@link #pBinds(VkSparseMemoryBind.Buffer) pBinds}. */
	public static void npBinds(long struct, VkSparseMemoryBind.Buffer value) { memPutAddress(struct + VkSparseBufferMemoryBindInfo.PBINDS, value.address()); nbindCount(struct, value.remaining()); }

	/**
	 * Validates pointer members that should not be {@code NULL}.
	 *
	 * @param struct the struct to validate
	 */
	public static void validate(long struct) {
		checkPointer(memGetAddress(struct + VkSparseBufferMemoryBindInfo.PBINDS));
	}

	/**
	 * Calls {@link #validate(long)} for each struct contained in the specified struct array.
	 *
	 * @param array the struct array to validate
	 * @param count the number of structs in {@code array}
	 */
	public static void validate(long array, int count) {
		for ( int i = 0; i < count; i++ )
			validate(array + i * SIZEOF);
	}

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

	/** An array of {@link VkSparseBufferMemoryBindInfo} structs. */
	public static final class Buffer extends StructBuffer<VkSparseBufferMemoryBindInfo, Buffer> {

		/**
		 * Creates a new {@link VkSparseBufferMemoryBindInfo.Buffer} instance backed by the specified container.
		 *
		 * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
		 * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
		 * by {@link VkSparseBufferMemoryBindInfo#SIZEOF}, and its mark will be undefined.
		 *
		 *
The created buffer instance holds a strong reference to the container object.

		 */
		public Buffer(ByteBuffer container) {
			super(container, container.remaining() / SIZEOF);
		}

		Buffer(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
			super(address, container, mark, pos, lim, cap);
		}

		@Override
		protected Buffer self() {
			return this;
		}

		@Override
		protected Buffer newBufferInstance(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
			return new Buffer(address, container, mark, pos, lim, cap);
		}

		@Override
		protected VkSparseBufferMemoryBindInfo newInstance(long address) {
			return new VkSparseBufferMemoryBindInfo(address, getContainer());
		}

		@Override
		protected int sizeof() {
			return SIZEOF;
		}

		/** Returns the value of the {@code buffer} field. */
		public long buffer() { return VkSparseBufferMemoryBindInfo.nbuffer(address()); }
		/** Returns the value of the {@code bindCount} field. */
		public int bindCount() { return VkSparseBufferMemoryBindInfo.nbindCount(address()); }
		/** Returns a {@link VkSparseMemoryBind.Buffer} view of the struct array pointed to by the {@code pBinds} field. */
		public VkSparseMemoryBind.Buffer pBinds() { return VkSparseBufferMemoryBindInfo.npBinds(address()); }

		/** Sets the specified value to the {@code buffer} field. */
		public VkSparseBufferMemoryBindInfo.Buffer buffer(long value) { VkSparseBufferMemoryBindInfo.nbuffer(address(), value); return this; }
		/** Sets the address of the specified {@link VkSparseMemoryBind.Buffer} to the {@code pBinds} field. */
		public VkSparseBufferMemoryBindInfo.Buffer pBinds(VkSparseMemoryBind.Buffer value) { VkSparseBufferMemoryBindInfo.npBinds(address(), value); return this; }

	}

}


text:
This repository is slated for deletion, perhaps as soon as June 1, 2016.  Please find other solutions.
There will be no future updates or support.

#### WebServiceManager is now deprecated. There will be no future updates or support. Check out [AFNetworking](https://github.com/AFNetworking/AFNetworking) instead.


text:
package uitest

import com.flowy.common.utils.Utils
import org.scalatest.BeforeAndAfterEach
import uitest.pages.RegistrationPage

class RegisterUiSpec extends BaseUiSpec with BeforeAndAfterEach {

  val Login    = Utils.randomString(5)
  val Email    = Login + "@example.org"
  val Password = "test"

  final val EmailSubject = s"SoftwareMill Bootzooka - registration confirmation for user $Login"

  override protected def beforeEach(): Unit = {
    super.beforeEach()
    emailService.reset()
  }

  test("register new user and send an email") {
    //given
    val registrationPage = createPage(classOf[RegistrationPage])

    //when
    registrationPage.register(Login, Email, Password)

    //then
    messagesPage.getInfoText should include("User registered successfully")
    emailService.wasEmailSent(Email, EmailSubject) should be(true)
  }

  test("register - fail due to not matching passwords") {
    //given
    val registrationPage = createPage(classOf[RegistrationPage])

    // when
    registrationPage.register(Login, Email, Password, Some(Password + "FooBarBaz"))

    //then
    registrationPage.getPassErrorText should include("Passwords don't match!")
    emailService.wasEmailSent(Email, EmailSubject) should be(false)
  }

}


text:
require("./env");

var vows = require('vows');
var assert = require('assert');

var suite = vows.describe('Utils');

suite.addBatch({
    'dc.printer.filter':{
        topic:function(){
            return dc.printers.filter;
        },
        'print simple string':function(printer){
            assert.equal(dc.printers.filter("a"), "a");
        },
        'print date string':function(printer){
            assert.equal(dc.printers.filter(new Date(2012, 1, 1)), "02/01/2012");
        },
        'print int range':function(printer){
            assert.equal(dc.printers.filter([10, 30]), "[10 -> 30]");
        },
        'print float range':function(printer){
            assert.equal(dc.printers.filter([10.124244, 30.635623]), "[10 -> 31]");
        },
        'print date range':function(printer){
            assert.equal(dc.printers.filter([new Date(2012, 1, 1), new Date(2012, 1, 15)]), "[02/01/2012 -> 02/15/2012]");
        },
        'print single element array':function(printer){
            assert.equal(dc.printers.filter([new Date(2012, 1, 1)]), "02/01/2012");
        },
        'print null':function(printer){
            assert.equal(dc.printers.filter(null), "");
        }
    }
});

suite.export(module);


text:
package com.yammer.metrics.reporting;

import com.yammer.metrics.core.MetricsRegistry;
import java.util.Set;

public interface Reporter {

    /**
     * Stops the reporter and closes any internal resources.
     */
    public void shutdown();

    /**
     * Set of registries associated with this reporter
     *
     * @return registries
     */
    public Set<MetricsRegistry> getMetricsRegistries();

    /**
     * Name of this reporter.
     *
     * @return
     */
    public String getName();
}


text:
<?xml version="1.0" encoding="utf-8"?>

<Weavers>
    <NullGuard IncludeDebugAssert="false" />
    <EmptyStringGuard IncludeDebugAssert="false" />
    <Anotar.CommonLogging />
</Weavers>


text:
#pragma once

#if defined(__cplusplus)
extern "C" {
#endif

#define pdTRUE              1

#if defined(__cplusplus)
}
#endif


text:
require_relative '../../helpers/coverage_helper'
require_relative '../../../lib/armagh/actions/stateful'
require_relative '../../../lib/armagh/documents/doc_spec'
require_relative '../../../lib/armagh/actions'

require 'test/unit'
require 'mocha/test_unit'

class TestActionStateful < Test::Unit::TestCase

  def setup

    @logger = mock
    @caller = mock
    @collection = mock
    if Object.constants.include?( :SubSplit )
      Object.send( :remove_const, :SubSplit )
    end
    Object.const_set "SubSplit", Class.new( Armagh::Actions::Split )

    @config_store = []
    @action_name = 'fred_the_action'
    config = nil
    assert_nothing_raised {
      SubSplit.define_default_input_type 'test_type1'
      config = SubSplit.create_configuration( @config_store, @action_name, {
          'action' => { 'workflow' => 'wf'},
          'output' => {'docspec' => Armagh::Documents::DocSpec.new('type', Armagh::Documents::DocState::READY)}
      } )
      @action = SubSplit.new( @caller, 'logger_name', config )
    }

  end

  def test_with_locked_action_state
    hold = 100
    @caller.expects( :with_locked_action_state).with( @action_name, lock_hold_duration: hold )
    @action.with_locked_action_state( hold )
  end

end


text:
[![Build Status](http://jenkins.mobilesolutionworks.com:8080/job/github/job/mobilesolutionworks/job/works-controller-android/job/master/badge/icon)](http://jenkins.mobilesolutionworks.com:8080/job/github/job/mobilesolutionworks/job/works-controller-android/job/master/)
[![codecov](https://codecov.io/gh/mobilesolutionworks/works-controller-android/branch/master/graph/badge.svg)](https://codecov.io/gh/mobilesolutionworks/works-controller-android)

Works Controller Android is a library that will greatly help you dealing with Android Activity and
Fragment lifecycle with ease.

One of the bane on Android programming is that you need to deal with device orientation change that
will restart either your Activity or Fragments, and especially if you are doing asynchronous task on
the front end.

The other one is the situation where Android runs your callback in paused stated such as during
onActivityResult() leading to complexity to make sure the result is properly rendered.

## Getting Started
Below is the snippet to create a controller, the controller manager will only call the callback and
then creates the controller implementation only when the controller for the specified id has not been
created yet, otherwise it will immediately returns the previous created instance.

```java
public class WorksControllerImpl extends WorksController {

}

public class WorksFragmentImpl extends WorksFragment
{
    @Override
    public onCreate(Bundle savedInstanceState) {}
        WorksControllerImpl controller = getControllerManager().initController(0, null, new WorksControllerManager.ControllerCallbacks<WorksControllerImpl>() {
            @Override
            public WorksControllerImpl onCreateController(int id, Bundle args) {
                return new WorksControllerImpl();
            }
        });
    }
}
```

From the snippet above, you can start testing and observing that WorksController implementation is not
recreated, and from there you can start doing more asynchronous stuff that is previously difficult to be
done with Fragments alone.

## Solving Problems

In very basic, as long your Activity in still in task stacks or your Fragment is fragment stacks,
even tough they are recreated during device orientation, the controller are not.

### Persistent container
As controller are not recreated during host recreation, you can persist data such as Adapter that takes
time to load.

```java
public class WorksControllerImpl extends WorksController {

    Adapter mAdapter;

    @Override
    public void onCreate(Bundle arguments) {
            mAdapter = // ... this creates adapter
    }

    public Adapter getAdapter() { return mAdapter; }
}

public class ActivityImpl extends WorksActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // when device is rotate, this will return previous controller
        WorksControllerImpl controller = getControllerManager().initController(0, null, new WorksControllerManager.ControllerCallbacks<WorksControllerImpl>() {
             @Override
             public WorksControllerImpl onCreateController(int id, Bundle args) {
                 return new WorksControllerImpl();
             }
         });

        ListView listView = // ... get your list view here
        listView.setAdapter(controller.getAdapter());
    }
}
```

### Asynchronous operation
So yes, you can even run your asynchronous task without worrying that the host which is the Activity
or Fragment gets recreated. And we also provides you with a way to make sure the result will be delivered
to the correct host.

You can read more detail on how the [Controller Lifecycle](https://github.com/mobilesolutionworks/works-controller-android/wiki/Controller-Lifecycle) works.

```java
public class WorksControllerImpl extends WorksController {

    BaseAdapter mAdapter;

    AsyncTask mAsyncTask;

    @Override
    public void onCreate(Bundle arguments) {
        mAdapter = // ... this creates adapter
        mAsyncTask = new AsyncTask<String, String, String>() {

            protected String doInBackground(String ... params) {
                // load the data from network
                return string;
            }

            protected void onPostExecute(String result) {
                // reset the data and call notify data set changed
                mAdapter.resetDataFromString(result);
                mAdapter.notifyDataSetChanged();
            }
        };
    }

    public Adapter getAdapter() { return mAdapter; }
}

public class ActivityImpl extends WorksActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // when device is rotate, this will return previous controller
        WorksControllerImpl controller = getControllerManager().initController(0, null, new WorksControllerManager.ControllerCallbacks<WorksControllerImpl>() {
             @Override
             public WorksControllerImpl onCreateController(int id, Bundle args) {
                 return new WorksControllerImpl();
             }
         });

        ListView listView = // ... get your list view here

        // 1. if the async task above is not finished, the adapter show empty data
        // 2. if the async task is finished during rotation, after rotation we will set the adapter again.
        listView.setAdapter(controller.getAdapter());
    }
}
```

You can read get more complex async operation example on [here](https://github.com/mobilesolutionworks/works-controller-android/wiki/Async-Operation-Example)

### User Interface container readiness
In Android, there are certain state where the user interface is not ready for changes primarily because
it is still in paused state.

This behavior can be observe by running the example "Fragment Transaction Demo" and choose setResult #1.

In the demonstration, the flow are as such below:
1. A fragment A call startActivityForResult
2. When onActivityResult received, show the result in current fragment A
3. Push current fragment A to back stack, and push a new fragment B
4. When the fragment is popped, you will see changes on fragment A is not working

```java
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        // in this state, the fragment or activity is still in paused state
        controller.runWhenUiIsReady(new Runnable() {

            public void run() {
                // the codes here will be executed when the UI context is ready
            }
        });
    }
}
```

## Using Controller in your project

Add this line in your `dependencies` section in your build.gradle
```groovy
compile 'com.mobilesolutionworks:controller-core:1.1.0'
```

### Start using Controller
Controller is a drop in solution to your existing project if you are using Android support library for
activities and fragments.

1. Change the activity or fragment base class
   - Change your fragments base class from Android support Fragment into WorksFragment
   - Change your activity base class from Android support AppCompatActivity into WorksActivity
2. Then you can use controller in your project right away

### Adding Controller functionality
Controller can be added to your existing project as well, if you are bound to use third party base Activity
or Fragment.

Simple solution
1. Create a copy of WorksActivity and WorksFragment in your project with different package
2. Make WorksActivity and WorksFragment subclass of your third party base classes, or you can copy the content
of WorksActivity and WorksFragment into your base classes as well
3. Then you can use controller in your project right away

## Running TEst

In order to run the test properly, you need to install [Test Butler](https://github.com/linkedin/test-butler) into your simulator since the unit test will test rotating the device programmatically.


text:
module Sample {
    export class SourcecodeView extends showv.View {
        private titlePart: TitlePart;
        private sourcePart: SourcePart;
        constructor(title: string, source: string){
            super();
            this.titlePart = new TitlePart(title);
            this.sourcePart = new SourcePart(source);
        }
        render(): SourcecodeView {
            this.$el.append(
                this.titlePart.render().$el,
                this.sourcePart.render().$el
            );
            return this;
        }
    }
    class SourcePart extends showv.View {
        constructor(private sourcecode: string){
            super({
                tagName: 'pre',
                className: 'sourcecode prettyprint'
            });
            this.$el.append(
                this.sourcecode
            );
            return this;
        }
    }
    class TitlePart extends showv.View {
        constructor(private title: string){
            super({
                tagName: 'a',
                id: title,
                className: 'code-title linky'
            });
            this.$el.append(
                $('<h2>').text(this.title)
            );
            this.$el.attr({
                href: '#' + title
            });
            return this;
        }
    }
}


text:
describe("VIZI.BlueprintOutput", function() {
  var output;

  before(function() {
    output = new VIZI.BlueprintOutput();
  });

  it("exists in VIZI namespace", function() {
    expect(VIZI.BlueprintInput).to.exist;
  });

  it("is an instance of VIZI.Layer", function() {
    expect(output).to.be.an.instanceOf(VIZI.Layer);
  });

  it("has an options property", function() {
    expect(output.options).to.exist;
  });

  it("has an triggers property", function() {
    expect(output.triggers).to.exist;
  });

  it("has an actions property", function() {
    expect(output.actions).to.exist;
  });

  it("has an on method", function() {
    expect(output.on).to.exist;
  });

  it("has an emit method", function() {
    expect(output.emit).to.exist;
  });

  it("has an init method", function() {
    expect(output.init).to.exist;
  });

  it("has an onTick method", function() {
    expect(output.onTick).to.exist;
  });
});


text:
using System.Web.Http;
using System.Web.Mvc;

namespace Betabit.Lora.Nuget.EventHub
{
	public class WebApiApplication : System.Web.HttpApplication
	{
		protected void Application_Start()
		{
			AreaRegistration.RegisterAllAreas();
			GlobalConfiguration.Configure(WebApiConfig.Register);
			FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
		}
	}
}


text:
package com.hazelcast.jet.spring;

import com.hazelcast.jet.JetInstance;
import com.hazelcast.spring.AbstractHazelcastBeanDefinitionParser;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;

/**
 * BeanDefinitionParser for Hazelcast Instance created via Jet Instance.
 *

 * Sample Spring XML for Hazelcast Instance created via Jet Instance:
 *
{@code
 * <jet:hazelcast jet-instance-ref="jet-instance" id="hazelcast-instance"/>
 * }

 */
public class JetHazelcastBeanDefinitionParser extends AbstractHazelcastBeanDefinitionParser {

    @Override
    protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
        return new SpringXmlBuilder(parserContext).handle(element);
    }

    private class SpringXmlBuilder extends SpringXmlBuilderHelper {

        private final ParserContext parserContext;
        private final BeanDefinitionBuilder builder;

        SpringXmlBuilder(ParserContext parserContext) {
            this.parserContext = parserContext;
            this.builder = rootBeanDefinition(JetInstance.class).setFactoryMethod("getHazelcastInstance");
        }

        AbstractBeanDefinition handle(Element element) {
            handleCommonBeanAttributes(element, builder, parserContext);
            NamedNodeMap attributes = element.getAttributes();
            if (attributes != null) {
                Node jetInstanceRefNode = attributes.getNamedItem("jet-instance-ref");
                if (jetInstanceRefNode != null) {
                    String jetInstanceRef = getTextContent(jetInstanceRefNode);
                    builder.getRawBeanDefinition().setFactoryBeanName(jetInstanceRef);
                    return builder.addDependsOn(jetInstanceRef).getBeanDefinition();
                }
            }
            throw new IllegalStateException("'jet-instance-ref' attribute is required for creating HazelcastInstance");
        }

    }
}


text:
import Queue from '../../data-structures/Queue'
import Question from '../question'

export default class QuestionCatalog {
  private _questions

  constructor (...args: Question[]) {
    this._questions = new Queue(...arguments)
  }

  get questions () {
    return this._questions.items
  }

  get length () {
    return this._questions.items.length
  }

  public add (question: Question) {
    this._questions.enqueue(question)
  }

  public getNextQuestion () {
    return this.questions.length !== 0
            ? this._questions.dequeue()
            : null
  }
}


text:
extern const base::FilePath::CharType kChromeWatcherDll[];
// The name of the watcher DLLs entrypoint function.
extern const char kChromeWatcherDLLEntrypoint[];
// The subdirectory of the browser data directory where permanently failed crash
// reports will be stored.
extern const base::FilePath::CharType kPermanentlyFailedReportsSubdir[];

// The type of the watcher DLL's main entry point.
// Watches |parent_process|, whose main thread ID is |main_thread_id|, and
// records its exit code under |registry_path| in HKCU. A window named
// |message_window_name|, owned by |parent_process|, will be monitored for
// responsiveness. If SyzyASAN is enabled, a Kasko reporter process is also
// instantiated, using |browser_data_directory| to store crash reports.
// |on_initialized_event| will be signaled once the watcher process is fully
// initialized. Takes ownership of |parent_process| and |on_initialized_event|.
// |channel_name| is the current Chrome distribution channel (one of
// installer::kChromeChannelXXX).
typedef int (*ChromeWatcherMainFunction)(
    const base::char16* registry_path,
    HANDLE parent_process,
    DWORD main_thread_id,
    HANDLE on_initialized_event,
    const base::char16* browser_data_directory,
    const base::char16* message_window_name,
    const base::char16* channel_name);

// Returns an RPC endpoint name for the identified client process. This method
// may be invoked in both the client and the watcher process with the PID of the
// client process to establish communication between the two using a common
// endpoint name.
base::string16 GetKaskoEndpoint(base::ProcessId client_process_id);

#endif  // CHROME_CHROME_WATCHER_CHROME_WATCHER_MAIN_API_H_


text:
import sys, os
import json
import mimetypes
import glob

import httplib2
from oauth2client import client
from oauth2client import tools
import oauth2client.tools
import oauth2client.file

class ArgParseFakeFlags:

    def __init__(self):
        self.logging_level = 'ERROR'
        self.auth_host_name='localhost'
        self.auth_host_port=[8080, 8090]
        self.noauth_local_webserver=False

class ChromeWebStore(object):
    """
    See https://developer.chrome.com/webstore/using_webstore_api
    and https://developers.google.com/api-client-library/python/guide/aaa_oauth
    """

    def __init__(self):
        self.http = httplib2.Http()
        self.credentials = None
        self.api_base = "https://www.googleapis.com/chromewebstore/v1.1"
        self.api_base_upload = "https://www.googleapis.com/upload/chromewebstore/v1.1"
        self.api_scope = 'https://www.googleapis.com/auth/chromewebstore'
        self.common_headers = {
            "x-goog-api-version": "2",
        }

    def authorize(self, client_secrets, oauth2_storage, flags):
        print client_secrets, oauth2_storage
        storage = oauth2client.file.Storage(oauth2_storage)
        self.credentials = storage.get()

        if self.credentials is None or self.credentials.invalid:
            print 'WARNING: credentials invalid, doing OAuth dance'
            flow = client.flow_from_clientsecrets(client_secrets, scope=self.api_scope)
            self.credentials = oauth2client.tools.run_flow(flow, storage, flags)
        self.http = self.credentials.authorize(self.http)

    def upload(self, item_id, filename):
        file_content = open(filename, 'rb').read()
        content_type, body = 'application/octet-stream', file_content
         # encode_multipart_formdata([], [(filename, filename, file_content)])
        headers = dict(self.common_headers)
        headers.update({
            'Content-length': str(len(body)),
            'Content-Type': content_type,
        })
        url = self.api_base_upload+'/items/%s?uploadType=media' % (item_id,)
        print url, headers
        resp, content = self.http.request(url, "PUT", headers=headers, body=body)
        if resp['status'] != '200':
            raise ValueError('Could not upload, HTTP status != 200: %s, %s' % (str(resp), content))
        else:
            msg = json.loads(content)
            if msg['uploadState'] != 'SUCCESS':
                raise ValueError('Could not upload: %s' % (msg,))

    def publish(self, item_id, publish_target):
        headers = dict(self.common_headers)
        # Note: for some reason can't pass publishTarget as query string, even if docs say so
        headers.update({
            'publishTarget': publish_target,
            'Content-length': "0",
        })
        url = self.api_base + "/items/%s/publish" % (item_id,)
        print url, headers
        resp, content = self.http.request(url, "POST", headers=headers)
        if resp["status"] != '200':
            raise ValueError('Could not publish: %s, %s' % (str(resp), content))
        else:
            msg = json.loads(content)
            # Some funky version of the API returns a 1-item list of strings... Normalize
            status = msg['status']
            status = status if not hasattr(status, '__iter__') else status[0]
            if status != 'OK':
                raise ValueError('Could not publish: %s' % (msg,))

if __name__ == '__main__':

    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-u", "--upload", dest="upload", metavar="FILE.zip", default=None,
                      help="Upload FILE.zip as a new release")
    parser.add_option("-p", "--publish", dest="publish", metavar="public|internal", default=None,
                      help="Publish the current draft release")
    (options, args) = parser.parse_args()

    # Check before doing anything
    if options.publish:
        p = options.publish
        if p not in ('public', 'internal'):
            sys.stderr.write('Error: --publish target have to be either "public" or "internal"\n')
            parser.print_help()
            sys.exit(2)
            raise ValueError()
        else:
            p = 'trustedTesters' if p == 'internal' else p
            p = 'default' if p == 'public' else p
            options.publish = p

    if not len(args) == 1:
        sys.stderr.write("ERROR: Expected 1 argument, got %d\n" % len(args))
        parser.print_help()
        sys.exit(2)

    item = args[0]
    # From the service account created in https://console.developers.google.com
    secrets = os.environ.get("WEBSTORE_SECRETS_FILE", None)
    storage = os.environ.get("WEBSTORE_OAUTH2_FILE", None)

    if not secrets or not storage:
        sys.stderr.write("""ERROR: Chrome Web Store credentials not specified.
Environment variables WEBSTORE_SECRETS_FILE and WEBSTORE_OAUTH2_FILE\n\n""")
        parser.print_help()
        sys.exit(2)

    if not (options.upload or options.publish):
        sys.stderr.write("ERROR: No action specified\n")
        parser.print_help()
        sys.exit(2)

    # Run
    store = ChromeWebStore()
    flags = ArgParseFakeFlags()
    store.authorize(secrets, storage, flags)

    if options.upload:
        # Expand glob expression
        matches = glob.glob(options.upload)
        upload = None if len(matches) != 1 else matches[0]
        if not upload:
            sys.stderr.write("ERROR: Expected 1 file to upload, found %d: %s\n" % (len(matches), repr(matches)))
            sys.exit(2)

        print 'Uploading draft release %s for item %s' %(upload, item)
        store.upload(item, upload);

    if options.publish:
        print 'Publishing draft release for item %s' % (item,)
        store.publish(item, options.publish)


text:
using Couchbase.Configuration;
using Enyim.Caching;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Test.Framework.Cache.Memcache;

namespace Test.Framework.Session.Memcache
{
    public static class SessionBucketActivator
    {
        #region Members

        private static IMemcachedClient memcachedClient;

        public static IMemcachedClient Cache
        {
            get
            {
                if (memcachedClient == null)
                {
                    Initialize();
                }
                return memcachedClient;
            }
        }

        private static void Initialize()
        {
            ICouchbaseClientFactory factory = Container.Resolve<ICouchbaseClientFactory>();
            if (factory != null)
            {
                memcachedClient = factory.Create((ICouchbaseClientConfiguration)ConfigurationManager.GetSection("session-bucket"));
            }
        }

        #endregion
    }
}


text:
<?php

include '../../controller/Check.class.php';
$check = new Check();
$check->show('#EFDDDD');
?>


text:
package com.gs.collections.impl.map.mutable.primitive;

import com.gs.collections.impl.test.Verify;
import org.junit.Test;

public class ByteByteHashMapSerializationTest
{
    @Test
    public void serializedForm()
    {
        Verify.assertSerializedForm(
                1L,
                "rO0ABXNyAD1jb20uZ3MuY29sbGVjdGlvbnMuaW1wbC5tYXAubXV0YWJsZS5wcmltaXRpdmUuQnl0\n"
                        + "ZUJ5dGVIYXNoTWFwAAAAAAAAAAEMAAB4cHcEAAAAAHg=",
                new ByteByteHashMap());
    }
}


text:
using namespace std;

class My_object
{
  public:
    My_object();
    void print();
  private:
    int x;

};

#endif


text:
package org.apache.flink.runtime.io.network.buffer;

import org.apache.flink.core.memory.MemorySegment;

import org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf;
import org.apache.flink.shaded.netty4.io.netty.buffer.ByteBufAllocator;
import org.apache.flink.shaded.netty4.io.netty.buffer.ReadOnlyByteBuf;
import org.apache.flink.shaded.netty4.io.netty.buffer.SlicedByteBuf;

import java.nio.ByteBuffer;
import java.nio.ReadOnlyBufferException;

/**
 * Minimal best-effort read-only sliced {@link Buffer} implementation wrapping a
 * {@link NetworkBuffer}'s sub-region based on <tt>io.netty.buffer.SlicedByteBuf</tt> and
 * <tt>io.netty.buffer.ReadOnlyByteBuf</tt>.
 *
 *
BEWARE: We do not guarantee to block every operation that is able to write
 * data but all returned data structures should be handled as if it was!.
 */
public final class ReadOnlySlicedNetworkBuffer extends ReadOnlyByteBuf implements Buffer {

	private final int memorySegmentOffset;

	/**
	 * Creates a buffer which shares the memory segment of the given buffer and exposed the given
	 * sub-region only.
	 *
	 *
Reader and writer indices as well as markers are not shared. Reference counters are
	 * shared but the slice is not {@link #retainBuffer() retained} automatically.
	 *
	 * @param buffer the buffer to derive from
	 * @param index the index to start from
	 * @param length the length of the slice
	 */
	ReadOnlySlicedNetworkBuffer(NetworkBuffer buffer, int index, int length) {
		super(new SlicedByteBuf(buffer, index, length));
		this.memorySegmentOffset = buffer.getMemorySegmentOffset() + index;
	}

	/**
	 * Creates a buffer which shares the memory segment of the given buffer and exposed the given
	 * sub-region only.
	 *
	 *
Reader and writer indices as well as markers are not shared. Reference counters are
	 * shared but the slice is not {@link #retainBuffer() retained} automatically.
	 *
	 * @param buffer the buffer to derive from
	 * @param index the index to start from
	 * @param length the length of the slice
	 * @param memorySegmentOffset <tt>buffer</tt>'s absolute offset in the backing {@link MemorySegment}
	 */
	private ReadOnlySlicedNetworkBuffer(ByteBuf buffer, int index, int length, int memorySegmentOffset) {
		super(new SlicedByteBuf(buffer, index, length));
		this.memorySegmentOffset = memorySegmentOffset + index;
	}

	@Override
	public ByteBuf unwrap() {
		return super.unwrap();
	}

	@Override
	public boolean isBuffer() {
		return getBuffer().isBuffer();
	}

	@Override
	public void tagAsEvent() {
		throw new ReadOnlyBufferException();
	}

	/**
	 * Returns the underlying memory segment.
	 *
	 *
BEWARE: Although we cannot set the memory segment read-only it should be
	 * handled as if it was!.
	 *
	 * @return the memory segment backing this buffer
	 */
	@Override
	public MemorySegment getMemorySegment() {
		return getBuffer().getMemorySegment();
	}

	@Override
	public int getMemorySegmentOffset() {
		return memorySegmentOffset;
	}

	@Override
	public BufferRecycler getRecycler() {
		return getBuffer().getRecycler();
	}

	@Override
	public void recycleBuffer() {
		getBuffer().recycleBuffer();
	}

	@Override
	public boolean isRecycled() {
		return getBuffer().isRecycled();
	}

	@Override
	public ReadOnlySlicedNetworkBuffer retainBuffer() {
		getBuffer().retainBuffer();
		return this;
	}

	@Override
	public ReadOnlySlicedNetworkBuffer readOnlySlice() {
		return readOnlySlice(readerIndex(), readableBytes());
	}

	@Override
	public ReadOnlySlicedNetworkBuffer readOnlySlice(int index, int length) {
		return new ReadOnlySlicedNetworkBuffer(super.unwrap(), index, length, memorySegmentOffset);
	}

	@Override
	public int getMaxCapacity() {
		return maxCapacity();
	}

	@Override
	public int getReaderIndex() {
		return readerIndex();
	}

	@Override
	public void setReaderIndex(int readerIndex) throws IndexOutOfBoundsException {
		readerIndex(readerIndex);
	}

	@Override
	public int getSize() {
		return writerIndex();
	}

	@Override
	public void setSize(int writerIndex) {
		writerIndex(writerIndex);
	}

	@Override
	public ByteBuffer getNioBufferReadable() {
		return nioBuffer();
	}

	@Override
	public ByteBuffer getNioBuffer(int index, int length) throws IndexOutOfBoundsException {
		return nioBuffer(index, length);
	}

	@Override
	public ByteBuffer nioBuffer(int index, int length) {
		return super.nioBuffer(index, length).asReadOnlyBuffer();
	}

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

	@Override
	public boolean isWritable(int numBytes) {
		return false;
	}

	@Override
	public ByteBuf ensureWritable(int minWritableBytes) {
		// note: ReadOnlyByteBuf allows this but in most cases this does not make sense
		if (minWritableBytes != 0) {
			throw new ReadOnlyBufferException();
		}
		return this;
	}

	@Override
	public void setAllocator(ByteBufAllocator allocator) {
		getBuffer().setAllocator(allocator);
	}

	@Override
	public ByteBuf asByteBuf() {
		return this;
	}

	private Buffer getBuffer() {
		return ((Buffer) unwrap().unwrap());
	}
}


text:
using Newtonsoft.Json;
using RKon.Alexa.NET.Types;

namespace RKon.Alexa.NET.JsonObjects
{
    /// <summary>
    /// Class for Colorobjects with HUE
    /// </summary>
    public class Color
    {
        private double mHue;
        private double mSaturation;
        private double mBrightness;

        /// <summary>
        /// Double between 0.00 and 360.00
        /// </summary>
        [JsonProperty("hue")]
        public double Hue
        {
            get { return mHue; }
            set
            {
                mHue = value;
                if (value < 0)
                    mHue = 0;
                else if (value > 360)
                {
                    mHue = 360;
                }
            }
        }
        /// <summary>
        /// Double between 0.0000 and 1.0000
        /// </summary>
        [JsonProperty("saturation")]
        public double Saturation
        {
            get { return mSaturation; }
            set
            {
                mSaturation = value;
                if (value < 0)
                    mSaturation = 0;
                if (value > 1)
                {
                    mSaturation = 1;
                }
            }
        }
        /// <summary>
        /// Double between 0.0000 and 1.00000
        /// </summary>
        [JsonProperty(PropertyNames.BRIGHTNESS)]
        public double Brightness
        {
            get { return mBrightness; }
            set
            {
                mBrightness = value;
                if (value < 0)
                    mBrightness = 0;
                if (value > 1)
                {
                    mBrightness = 1;
                }
            }
        }

        /// <summary>
        /// Standardconstructor
        /// </summary>
        public Color()
        {

        }

        /// <summary>
        /// Inintialises Colorelement
        /// </summary>
        /// <param name="hue"></param>
        /// <param name="saturation"></param>
        /// <param name="brightness"></param>
        public Color(double hue, double saturation, double brightness)
        {
            Hue = hue;
            Saturation = saturation;
            Brightness = brightness;
        }
    }
}


text:
Aria.classDefinition({
    $classpath : "test.aria.widgets.wai.input.WaiInputTestSuite",
    $extends : "aria.jsunit.TestSuite",
    $constructor : function () {
        this.$TestSuite.constructor.call(this);
        this.addTests("test.aria.widgets.wai.input.checkbox.CheckboxTestCase");
        this.addTests("test.aria.widgets.wai.input.dateField.DateFieldTestCase");
        this.addTests("test.aria.widgets.wai.input.datePicker.DatePickerTestCase");
        this.addTests("test.aria.widgets.wai.input.link.LinkTestCase");
        this.addTests("test.aria.widgets.wai.input.multiSelect.MultiSelectTestCase");
        this.addTests("test.aria.widgets.wai.input.numberField.NumberFieldTestCase");
        this.addTests("test.aria.widgets.wai.input.passwordField.PasswordFieldTestCase");
        this.addTests("test.aria.widgets.wai.input.radiobutton.RadioButtonTestCase");
        this.addTests("test.aria.widgets.wai.input.select.SelectTestCase");
        this.addTests("test.aria.widgets.wai.input.selectBox.SelectBoxTestCase");
        this.addTests("test.aria.widgets.wai.input.textArea.TextAreaTestCase");
        this.addTests("test.aria.widgets.wai.input.textField.TextFieldTestCase");
        this.addTests("test.aria.widgets.wai.input.timeField.TimeFieldTestCase");
    }
});


text:
package it.randomtower.droneswarm.screen;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.viewport.StretchViewport;

import it.randomtower.droneswarm.G;

public class StoryScreen implements Screen {
	private Game game;
	private BitmapFont font;
	private SpriteBatch batch;
	private BitmapFont fontBig;
	private Texture menuBackground;
	private Stage stage;
	private OrthographicCamera cam;
	private StretchViewport viewport;
	private Skin skin;

	public StoryScreen(final Game game) {
		cam = new OrthographicCamera(G.WIDTH, G.HEIGHT);
		viewport = new StretchViewport(G.WIDTH, G.HEIGHT, cam);

		this.game = game;
		font = new BitmapFont(Gdx.files.internal("orbitron.fnt"), Gdx.files.internal("orbitron.png"), false);
		fontBig = new BitmapFont(Gdx.files.internal("orbitron_big_yellow.fnt"),
				Gdx.files.internal("orbitron_big_yellow.png"), false);
		batch = new SpriteBatch();
		menuBackground = new Texture(Gdx.files.internal("menu.png"));

		// ui
		stage = new Stage(viewport);
		Gdx.input.setInputProcessor(stage);
		skin = new Skin(Gdx.files.internal("defaultSkin/uiskin.json"));

		final TextButton lb = new TextButton("Start", skin, "default");
		lb.setWidth(150);
		lb.setHeight(30);
		lb.setPosition(250, 50);
		lb.addListener(new ClickListener() {
			public void clicked(com.badlogic.gdx.scenes.scene2d.InputEvent event, float x, float y) {
				// load level
				game.setScreen(new LevelSelectScreen(game));
			};
		});
		stage.addActor(lb);
	}

	@Override
	public void show() {
	}

	@Override
	public void render(float delta) {
		batch.begin();

		batch.setProjectionMatrix(cam.combined); // Important

		batch.draw(menuBackground, 0, 0);
		font.draw(batch, "After many wars, galaxy is without organic life", 50, 400);
		font.draw(batch, "Many weapons are still active", 50, 350);
		fontBig.draw(batch, "weapons like you", 150, 275);
		font.draw(batch, "drones factories are still active", 50, 200);
		font.draw(batch, "so take control of drone swarm and fight!", 50, 150);
		batch.end();

		stage.act(Gdx.graphics.getDeltaTime());
		stage.draw();

		if (Gdx.input.isKeyJustPressed(Keys.ESCAPE)) {
			game.setScreen(new MenuScreen(game));
		}
	}

	@Override
	public void resize(int width, int height) {
	}

	@Override
	public void pause() {
	}

	@Override
	public void resume() {
	}

	@Override
	public void hide() {
	}

	@Override
	public void dispose() {
	}
}


text:
/* General Demo Style */
@import url(http://fonts.googleapis.com/css?family=Lato:300,400,700|Satisfy);

@font-face {
	font-family: 'codropsicons';
	src:url('../fonts/codropsicons/codropsicons.eot');
	src:url('../fonts/codropsicons/codropsicons.eot?#iefix') format('embedded-opentype'),
		url('../fonts/codropsicons/codropsicons.woff') format('woff'),
		url('../fonts/codropsicons/codropsicons.ttf') format('truetype'),
		url('../fonts/codropsicons/codropsicons.svg#codropsicons') format('svg');
	font-weight: normal;
	font-style: normal;
}

*, *:after, *:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; }
body, html { font-size: 100%; padding: 0; margin: 0;}

/* Clearfix hack by Nicolas Gallagher: http://nicolasgallagher.com/micro-clearfix-hack/ */
.clearfix:before, .clearfix:after { content: " "; display: table; }
.clearfix:after { clear: both; }

body {
	font-family: 'Lato', Calibri, Arial, sans-serif;
	color: #fff;
	background: #333;
	overflow: hidden;
}

a {
	color: #ddd;
	text-decoration: none;
}

a:hover {
	color: #fff;
}


text:
package com.hazelcast.spi.discovery.integration;

/**
 * The <tt>DiscoveryServiceProvider</tt> interface provides the possibility to build {@link DiscoveryService}s.
 * <tt>DiscoveryService</tt> implementations should be immutable and therefore the provider is introduced to
 * provide this ability. Every service should have its own provider, however in rare cases a single provider might
 * create different <tt>DiscoveryService</tt> implementations based on the provided {@link DiscoveryMode} or other
 * configuration details.
 *
 * @since 3.6
 */
public interface DiscoveryServiceProvider {

    /**
     * Instantiates a new instance of the {@link DiscoveryService}.
     *
     * @param settings The settings to pass to creation of the <tt>DiscoveryService</tt>
     * @return a new instance of the discovery service
     */
    DiscoveryService newDiscoveryService(DiscoveryServiceSettings settings);

}


text:
package com.huang.config;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

/**
 * Description:
 * Created on 2017/8/11 14:52
 *
 * @author 黄渝贵
 * @version 1.0
 *
 */
//@Configurable
public class RabbitConfig {

    @Value("${rabbitmq.exchange.exception}")
    private String exceptionExchange;

    @Value("${rabbitmq.queue.exception}")
    private String exceptionQuque;

    @Value("${rabbitmq.queue.exception}")
    private String exceptionPushKey;

    @Bean
    public Queue exceptionQueue(){
        return new Queue(exceptionQuque);
    }

    @Bean
    public FanoutExchange exceptionExchange(){
        return new FanoutExchange(exceptionExchange);
    }

    @Bean
    public Binding bindingExchangePushMessage(DirectExchange exceptionExchange, Queue exceptionQueue){
        return BindingBuilder.bind(exceptionQueue).to(exceptionExchange).with(exceptionPushKey);
    }

}


text:
package org.apache.activemq.artemis.cli.commands.address;

import io.airlift.airline.Option;
import org.apache.activemq.artemis.cli.commands.AbstractAction;

public abstract class AddressAbstract extends AbstractAction {

   @Option(name = "--name", description = "The name of this address")
   private String name;

   @Option(name = "--anycast", description = "It will determine this address as anycast")
   private Boolean anycast;

   @Option(name = "--no-anycast", description = "It will not determine this address as anycast")
   private Boolean noAnycast;

   @Option(name = "--multicast", description = "It will determine this address as multicast")
   private Boolean multicast;

   @Option(name = "--no-multicast", description = "It will not determine this address as multicast")
   private Boolean noMulticast;

   public AbstractAction setName(String name) {
      this.name = name;
      return this;
   }

   public String getName(boolean requireInput) {
      if (name == null && requireInput) {
         name = input("--name", "Provide the name of the address", null);
      }
      return name;
   }

   public String getRoutingTypes(boolean useDefault) {
      StringBuffer buffer = new StringBuffer();

      if (isAnycast()) {
         buffer.append("ANYCAST");
      }

      if (isMulticast()) {
         if (isAnycast()) {
            buffer.append(",");
         }
         buffer.append("MULTICAST");
      }

      if (!isAnycast() && !isMulticast()) {
         if (useDefault) {
            return "MULTICAST"; // the default;
         } else {
            return null;
         }

      }

      return buffer.toString();
   }

   public boolean isAnycast() {
      if (noAnycast != null) {
         anycast = !noAnycast.booleanValue();
      }
      if (anycast == null) {
         anycast = inputBoolean("--anycast", "Will this address support anycast queues", false);
      }
      return anycast;
   }

   public AddressAbstract setAnycast(boolean anycast) {
      this.anycast = anycast;
      return this;
   }

   public boolean isMulticast() {
      if (noMulticast != null) {
         multicast = !noMulticast.booleanValue();
      }
      if (multicast == null) {
         multicast = inputBoolean("--multicast", "Will this address support multicast queues", true);
      }
      return multicast;
   }

   public AddressAbstract setMulticast(boolean multicast) {
      this.multicast = multicast;
      return this;
   }
}


text:
<?php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;
use ManhGiay\Manhgiay;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

        $this->call('ManhgiaysTableSeeder');
        $this->command->info("Created password slug for testing, done!");    }
}

class ManhgiaysTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('manhgiays')->delete();

        $manhgiay = new Manhgiay();
        $manhgiay->slug = 'password';
        $manhgiay->password = Hash::make('123456');
//        $manhgiay->password = '123456';
        $manhgiay->save();
    }
}


text:
package typeAnnotations;

public class GenericArrayNestedTypeAnnotations {
    @A V.U<String>.T<Boolean, Integer, Float> @A [] t1;
    V.@B U<String>.T<Boolean, Integer, Float>[] t2;
    V.U<String>.@C T<Boolean, Integer, Float> @B [] @D [] t3;
    V.U<@D String>.T<Boolean, Integer, Float> @F [] t4;
    @B V.@A U<@A String>.@A T<@E Boolean, @F Integer, Float>[] t5;
}


text:
import React from 'react';

import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as analytics from './../../../actions';

import { Nav } from 'react-bootstrap';
import Label from 'konux/common/components/Label';

class BreadCrumbs extends React.Component {
    constructor(props) {
        super(props);
        this.breadCrumbs = null;
    }
    onClick(){
        this.props.switchClick(null);
    }
    addCrumb(title, handler) {
        this.breadCrumbs.push({
            title:title,
            handler:handler
        });
    }
    render(){
        this.breadCrumbs = [];

        let { switches, activeSwitches, selectedSwitches, activeRegions, regions, selectedRoutes, activeRoutes, routes } = this.props;
        if (activeRegions && activeRegions.length === 1) {
            this.addCrumb(activeRegions[0].name, () => {
                    if (selectedRoutes && selectedRoutes.length > 0) {
                        this.props.routeClick(null);
                    } else {
                        this.props.switchClick(null);
                    }
                });
        } else if (regions && regions.length > 0 || activeRegions && activeRegions.length > 1) {
            let reg = activeRegions || regions;
            if (reg) {
                this.addCrumb(reg.length + ' Regions', () => {
                    if (selectedRoutes && selectedRoutes.length > 0) {
                        this.props.routeClick(null);
                    } else {
                        this.props.switchClick(null);
                    }
                });
            }
        }

        if (selectedRoutes && selectedRoutes.length > 0) {
            if (selectedRoutes.length === 1) {
                this.addCrumb(selectedRoutes[0].name, () => this.props.switchClick(null));
            } else {
                this.addCrumb(selectedRoutes.length + ' Routes', () => this.props.switchClick(null));
            }
        }

        if (selectedSwitches && selectedSwitches.length > 0) {
            if (selectedSwitches.length === 1) {
                this.addCrumb(selectedSwitches[0].name, null);
            } else {
                this.addCrumb(selectedSwitches.length + ' Switches', null);
            }
        }

        return(

                {this.breadCrumbs ? this.breadCrumbs.map((data, i) => {
                    return (

                                {data.title}

);
                    }) : null
                }

        );
    }
}

const stateMap = (state, props, ownProps) => {
    return {
        activeRegions: state.data.activeRegions,
        activeRoutes: state.data.activeRoutes,
        selectedRoutes: state.data.selectedRoutes,
        selectedSwitches: state.data.selectedSwitches,
        activeSwitches: state.data.activeSwitches,
        regions: state.data.regions.response,
        switches: state.data.switches,
        routes: state.data.routes.response
    };
};

function mapDispatchToProps(dispatch) {
    return bindActionCreators(analytics, dispatch);
};

export default connect(stateMap, mapDispatchToProps)(BreadCrumbs);


text:
class AddHoundToRepo < ManageHound
  def run
    if repo.organization
      add_user_to_org
    else
      add_collaborator_to_repo
    end
  end

  private

  def add_collaborator_to_repo
    github.add_collaborator(repo_name, github_username)
  end

  def add_user_to_org
    if team_with_admin_access
      github.add_user_to_team(team_with_admin_access.id, github_username)
    else
      add_user_and_repo_to_services_team
    end
  end

  def team_with_admin_access
    @team_with_admin_access ||= begin
      repo_teams = github.repo_teams(repo_name)
      token_bearer = GithubUser.new(github)

      repo_teams.detect do |repo_team|
        token_bearer.has_admin_access_through_team?(repo_team.id)
      end
    end
  end

  def add_user_and_repo_to_services_team
    if team = decorated_services_team
      team.add_repo(repo_name)
    else
      team = GithubTeam.new(create_team, github)
    end

    team.add_user(github_username)
  end

  def create_team
    github.create_team(
      team_name: GITHUB_TEAM_NAME,
      org_name: org_name,
      repo_name: repo_name
    )
  end
end