text:
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
   Written 2022 by Adrián Arroyo Calle (adrian.arroyocalle@gmail.com)
   Part of Scryer Prolog.

   http_open(+Address, -Stream, +Options)
   ======================================

   Yields Stream to read the body of an HTTP reply from Address.
   Address is a list of characters, and includes the method. Both HTTP
   and HTTPS are supported.

   Options supported:

     * method(+Method): Sets the HTTP method of the call. Method can be get (default), head, delete, post, put or patch.
     * data(+Data): Data to be sent in the request. Useful for POST, PUT and PATCH operations.
     * size(-Size): Unifies with the value of the Content-Length header
     * request_headers(+RequestHeaders): Headers to be used in the request
     * headers(-ListHeaders): Unifies with a list with all headers returned in the response
     * status_code(-Code): Unifies with the status code of the request (200, 201, 404, ...)

   Example:

       ?- http_open("https://github.com/mthom/scryer-prolog", S, []).
       %@    S = '$stream'(0x7fcfc9e00f00).

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

:- module(http_open, [http_open/3]).

:- use_module(library(lists)).

http_open(Address, Response, Options) :-
    parse_http_options(Options, OptionValues),
    ( member(method(Method), OptionValues) -> true; Method = get),
    ( member(data(Data), OptionValues) -> true; Data = []),
    ( member(request_headers(RequestHeaders), OptionValues) -> true; RequestHeaders = ['user-agent'("Scryer Prolog")]),
    ( member(status_code(Code), OptionValues) -> true; true),
    ( member(headers(Headers), OptionValues) -> true; true),
    ( member(size(Size), OptionValues) -> member('content-length'(Size), Headers); true),
    '$http_open'(Address, Response, Method, Code, Data, Headers, RequestHeaders).

parse_http_options(Options, OptionValues) :-
    maplist(parse_http_options_, Options, OptionValues).

parse_http_options_(method(Method), method(Method)) :-
    (  var(Method) ->
       throw(error(instantiation_error, http_open/3))
    ;
       member(Method, [get, post, put, delete, patch, head]) -> true
    ;
       throw(error(domain_error(http_option, method(Method)), _))
    ).

parse_http_options_(data(Data), data(Data)) :-
    (  var(Data) ->
       throw(error(instantiation_error, http_open/3))
    ;  true
    ).

parse_http_options_(request_headers(Headers), request_headers(Headers)) :-
    (  var(Headers) ->
       throw(error(instantiation_error, http_open/3))
    ;  true
    ).

parse_http_options_(size(Size), size(Size)).
parse_http_options_(status_code(Code), status_code(Code)).
parse_http_options_(headers(Headers), headers(Headers)).


text:
<?php

/* This document is meant to follow PSR-1 and PSR-2 php-fig standards
   http://www.php-fig.org/psr/psr-1/
   http://www.php-fig.org/psr/psr-2/ */

/**
 * Priority Class
 *
 * This file implements the Priority class.  Used mainly in PriorityQueue.
 *
 * A priority is a number specifying urgency assigned to a piece of data.
 *
 * @copyright Copyright 2016 Asher Wolfstein
 * @author Asher Wolfstein <asherwunk@gmail.com>
 * @link http://wunk.me/ The author's URL
 * @link http://wunk.me/programming-projects/phabstractic/ Framework URL
 * @license http://opensource.org/licenses/MIT
 * @package Data
 * @subpackage Structures
 *
 */

/**
 * Falcraft Libraries Data Types Namespace
 *
 */
namespace Phabstractic\Data\Types
{
    require_once(realpath( __DIR__ . '/../../') . '/falcraftLoad.php');

    /* This class contains a static function for returning unique values
       for an array that is more object compatible. */
    $includes = array(// implement priority interface
                      '/Data/Types/Resource/PriorityInterface.php',);

    falcraftLoad($includes, __FILE__);

    use Phabstractic\Data\Types\Resource as TypesResource;

    /**
     * Priority Class - Defines a basic priority
     *
     * This associates a piece of data with a priority
     *
     * The lower the priority the more urgent it is, is the idea
     *
     * @TODO Allow priorities to set themselves apart from list
     *
     * CHANGELOG
     *
     * 1.0: Created Priority May 26th, 2013
     * 2.0: Refactored and re-formatted for inclusion
     *          in primus - April 11th, 2015
     * 3.0: eliminated configuraiton (no options)
     *      implemented setPriority as per version 3 of the interface
     *      pass data as reference in constructor
     *      reformatted for inclusion in phabstractic - July 21st, 2016
     *
     * @link http://en.wikipedia.org/wiki/Priority_queue [English]
     *
     * @version 3.0
     *
     */
    class Priority implements TypesResource\PriorityInterface
    {
        /**
         * The data to be associated with the urgency
         *
         * @var mixed
         */
        private $data = null;

        /**
         * The urgency of the data, less is more
         *
         * @var int
         */
        private $priority = 0;

        /**
         * Priority class Constructor.
         *
         * Set the initial priority and associate the data object with it.
         *
         * NOTE: Data is passed and assigned as a reference in the constructor
         *
         * @param mixed $data The data associated with the priority
         * @param int $priority The urgency of the priority, less is more
         *
         */
        public function __construct(&$data, $priority = 0)
        {
            $this->data = &$data;
            $this->priority = $priority;
        }

        /**
         * Retrieve the data from the priority
		 *
         * @return mixed
         *
         */
        public function getData()
        {
            return $this->data;
        }

        /**
         * Retrieve the data as a reference from the priority
		 *
         * @return mixed
         *
         */
        public function &getDataReference()
        {
            return $this->data;
        }

        /**
         * Get the urgency of the priority object, less is more
		 *
         * @return int
         *
         */
        public function getPriority()
        {
            return $this->priority;
        }

        /**
         * Set the priority of the object
         *
         * Generally, 0 is most urgent.
         *
         * @return bool True if set
         *
         */
        public function setPriority($priority)
        {
            $this->priority = $priority;
        }

        /**
         * Construct a priority
         *
         * This is useful if you're not using a reference as data
         *
         * @param mixed $data
         * @param int priority
         *
         */
        public static function buildPriority($data, $priority = 0)
        {
            return new Priority($data, $priority);
        }

        /**
         * Debug Info (var_dump)
         *
         * Display debug info
         *
         * Requires PHP 5.6+
         *
         */
        public function __debugInfo()
        {
            return [
                'priority' => $this->priority,
                'data' => $this->data,
            ];
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Score',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('player_name', models.CharField(max_length=15)),
                ('player_score', models.IntegerField()),
            ],
        ),
    ]


text:
package models

import com.vividsolutions.jts.geom.Point
import org.joda.time.{LocalDateTime,DateTime}
import play.api.libs.json.JsValue

import myUtils.{WithMyDriver}
import myUtils.MyPostgresDriver.simple._

object ModelsConstants {
  val ROLE = "Role"
  val ADMIN = "Admin"
  val SUPER_ADMIN = "SuperAdmin"
}
import ModelsConstants._

trait Entity[PK] {
  def id: Option[PK]
}

trait EntityTable[I] {
  def id: scala.slick.lifted.Column[I]
}

trait Profile extends WithMyDriver {
  //val profile: scala.slick.driver.JdbcProfile
  val profile:scala.slick.driver.PostgresDriver
  val simple:profile.simple.type = profile.simple
}

trait CrudComponent extends WithMyDriver{
  import driver.simple._

    abstract class Crud[T <: Table[E] with EntityTable[PK], E <: Entity[PK], PK: BaseColumnType] {
      val query: TableQuery[T]
        private val byIdCompiled = Compiled{ (id: Column[PK]) => query.filter(_.id === id) }
        def count(implicit s: Session): Int = query.length.run
        def findAll(implicit s: Session): List[E] = query.list
        def queryById(id: PK)(implicit s: Session) = byIdCompiled(id)
        def findById(id: PK)(implicit s: Session): Option[E] = byIdCompiled(id).firstOption
        def findOne(id: PK)(implicit s: Session): Option[E] = queryById(id).firstOption
        def add(m: E)(implicit s: Session): PK = (query returning query.map(_.id)) += m
        def withId(model: E, id: PK)(implicit s: Session): E
        def extractId(m: E)(implicit s: Session): Option[PK] = m.id
        def save(m: E)(implicit s: Session): E = extractId(m) match {
          case Some(id) =>
            queryById(id).update(m)
            m
            case None => withId(m, add(m))
        }
        def saveAll(ms: E*)(implicit s: Session): Option[Int] = query ++= ms
        def deleteById(id: PK)(implicit s: Session): Int = queryById(id).delete
        def delete(m: E)(implicit s: Session): Int = extractId(m) match {
          case Some(id) => deleteById(id)
          case None => -1
        }
        def update(entity: E)(implicit s: Session): Unit      = entity.id.map{ id =>
              byIdCompiled(id).update(entity)
        }.getOrElse{
              throw new Exception("cannot update entity without id")
        }
    }
}

object AccountStatuses extends Enumeration {
  type AccountStatus = Value
  val NOT_REGISTERED, REGISTERED = Value
}
import AccountStatuses._

sealed trait Active
case object Enabled extends Active
case object Disabled extends Active

sealed trait BaseRole extends Entity[Int]{
  def code:String
  def name:String
  def isAdmin:Boolean
  def isSuperAdmin:Option[Boolean]
  def modelType:String
}

case class Role(val id:Option[Int] = None, val code:String, name:String, override val isAdmin:Boolean = false, final val isSuperAdmin:Option[Boolean] = None,final val modelType:String = ROLE) extends BaseRole
case class Admin(val id:Option[Int] = None, val code:String, name:String, override final val isAdmin:Boolean = true, final val isSuperAdmin:Option[Boolean] = None,final val modelType:String = ADMIN) extends BaseRole
case class SuperAdmin(val id:Option[Int] = None, val code:String, name:String, override final val isAdmin:Boolean = true, final val isSuperAdmin:Option[Boolean] = Some(true),final val modelType:String = SUPER_ADMIN) extends BaseRole

case class Address(line1:String, line2:Option[String], city:String)
case class Customer(
  id:Option[Int],
  name:String,
  email:String,
  address:Address,
  status:AccountStatus,
  active:Boolean,
  dob: LocalDateTime,
  interests: List[String],
  others: Option[JsValue],
  enabled:Active,
  createdOn:DateTime
) extends Entity[Int]

trait CustomerComponent extends CrudComponent{
  import driver.simple._
object ActiveImplicits {
  implicit val activeTypeMapper = MappedColumnType.base[Active, Boolean](
      {
        b => b match {
        case Enabled => true
        case Disabled => false
        }
      },
      {
        i => i match {
        case true => Enabled
        case false => Disabled
        }
      }
      )

}
  import ActiveImplicits._

  class Customers(tag: Tag) extends Table[Customer](tag, "users") with EntityTable[Int] {
    def id = column[Int]("id", O.AutoInc, O.PrimaryKey)
    def name = column[String]("name")
    def email = column[String]("email")
    def line1 = column[String]("line1")
    def line2 = column[Option[String]]("line2")
    def city = column[String]("city")
    def address = (line1,line2,city) <> (Address.tupled,Address.unapply)
    /**
    * Create the desired ENUM type in db using {{{create type account_status as enum ('NOT_REGISTERED','REGISTERED');}}}
    */
    def status = column[AccountStatus]("status",O.Default(NOT_REGISTERED))
    def active = column[Boolean]("active")
    def dob = column[LocalDateTime]("dob")
    def interests = column[List[String]]("interests")
    def others = column[Option[JsValue]]("others")
    def enabled = column[Active]("enabled")
    def createdOn = column[DateTime]("created_on")

    def * = (id.?, name, email, address, status, active, dob, interests, others, enabled, createdOn) <> (Customer.tupled, Customer.unapply)
  }

  object Customers extends Crud[Customers, Customer, Int] {
    val query = TableQuery[Customers]
    override def withId(user: Customer, id: Int)(implicit session: Session): Customer = user.copy(id = Option(id))
  }
}

trait CustomerRoleComponent extends WithMyDriver{
  import driver.simple._
  import models.current.dao._
  import scala.slick.lifted.{ProvenShape, ForeignKeyQuery}

  type CustomerToRoleType = Tuple2[Int,Int]
  class CustomeToRole(tag:Tag) extends Table[CustomerToRoleType](tag,"customers_roles") {
    def userId = column[Int]("user_id")
    def roleId = column[Int]("role_id")
    def * : ProvenShape[CustomerToRoleType] = (userId,roleId)
    def userIdFK:ForeignKeyQuery[Customers,Customer] = foreignKey("fk_user_id", userId, TableQuery[Customers])(a => a.id)
    def roleIdFK:ForeignKeyQuery[BaseRoles,BaseRole] = foreignKey("fk_role_id", roleId, baseroles)(a => a.id)
  }
}

trait RoleComponent extends CrudComponent{
  import driver.simple._
  import models.current.dao._
  import scala.slick.lifted.{Query, ProvenShape, ForeignKeyQuery}

  abstract class AbstractRoles[T](tag: Tag) extends Table[T](tag, "roles") with EntityTable[Int]{
    def id = column[Int]("id", O.AutoInc, O.PrimaryKey)
    def code = column[String]("code")
    def name = column[String]("name")
    def isAdmin = column[Boolean]("is_admin", O.Default(false))
    def isSuperAdmin = column[Option[Boolean]]("is_super_admin")
    def modelType = column[String]("model_type")
    def * :ProvenShape[T]
  }

  /*
  class Roles(tag:Tag) extends AbstractRoles[Role](tag) {
    def *  = (id.?,code,name,isAdmin,isSuperAdmin.?,modelType).shaped <> (Role.tupled, Role.unapply)
  }
  object Roles extends Crud[Roles, Role, Int] {
    val query = TableQuery[Roles]
    override def withId(role: Role, id: Int)(implicit session: Session): Role = role.copy(id = Option(id))
  }
  class Admins(tag:Tag) extends AbstractRoles[Admin](tag) {
    def *  = (id.?,code,name,isAdmin,isSuperAdmin,modelType).shaped <> (Admin.tupled, Admin.unapply)
  }
  object Admins extends Crud[Admins, Admin, Int] {
    val query = TableQuery[Admins]
    override def withId(role: Admin, id: Int)(implicit session: Session): Admin = role.copy(id = Option(id))
  }
  class SuperAdmins(tag:Tag) extends AbstractRoles[SuperAdmin](tag) {
    def *  = (id.?,code,name,isAdmin,isSuperAdmin,modelType).shaped <> (SuperAdmin.tupled, SuperAdmin.unapply)
  }
  */

  class BaseRoles(tag: Tag) extends AbstractRoles[BaseRole](tag) {
    def * :ProvenShape[BaseRole] = (id.?,code,name,isAdmin,isSuperAdmin,modelType).shaped <> ({ t => t match {
        case (a:Option[Int],b,c,d,x @ Some(true),y @ SUPER_ADMIN) => SuperAdmin(a,b,c):BaseRole
        case (a:Option[Int],b,c,d @ true,x @ None,y @ ADMIN) => Admin(a,b,c):BaseRole
        case (a:Option[Int],b,c,d,e,f) => Role(a,b,c,d,e,f):BaseRole
      }
    },
    {t:BaseRole => t match {
      case SuperAdmin(a,b,c,true,Some(true),SUPER_ADMIN) => Some((a,b,c,true,Some(true),SUPER_ADMIN))
      case Admin(a,b,c,true,None,ADMIN) => Some((a,b,c,true,None,ADMIN))
      case Role(a,b,c,d,None,ROLE) => Some((a,b,c,d,None,ROLE))
      case _ => None
      }
    }
    )
  }

  object BaseRoles extends Crud[BaseRoles, BaseRole, Int] {
    val query = TableQuery[BaseRoles]
    override def withId(role: BaseRole, id: Int)(implicit session: Session): BaseRole = role match {
      case x @ SuperAdmin(_,_,_,_,_,_) => x.copy(id = Option(id))
      case x @ Admin(_,_,_,_,_,_) => x.copy(id = Option(id))
      case x @ Role(_,_,_,_,_,_) => x.copy(id = Option(id))
    }
  }
}


text:
#ifndef OSMIUM_IO_DETAIL_XML_INPUT_FORMAT_HPP
#define OSMIUM_IO_DETAIL_XML_INPUT_FORMAT_HPP

#include <cassert>
#include <cstring>
#include <future>
#include <memory>
#include <string>
#include <utility>

#include <expat.h>

#include <osmium/builder/builder.hpp>
#include <osmium/builder/osm_object_builder.hpp>
#include <osmium/io/detail/input_format.hpp>
#include <osmium/io/detail/queue_util.hpp>
#include <osmium/io/error.hpp>
#include <osmium/io/file_format.hpp>
#include <osmium/io/header.hpp>
#include <osmium/memory/buffer.hpp>
#include <osmium/osm/box.hpp>
#include <osmium/osm/changeset.hpp>
#include <osmium/osm/entity_bits.hpp>
#include <osmium/osm/item_type.hpp>
#include <osmium/osm/location.hpp>
#include <osmium/osm/node.hpp>
#include <osmium/osm/node_ref.hpp>
#include <osmium/osm/object.hpp>
#include <osmium/osm/relation.hpp>
#include <osmium/osm/timestamp.hpp>
#include <osmium/osm/types.hpp>
#include <osmium/osm/types_from_string.hpp>
#include <osmium/osm/way.hpp>
#include <osmium/thread/util.hpp>
#include <osmium/util/cast.hpp>

namespace osmium {

    /**
     * Exception thrown when the XML parser failed. The exception contains
     * (if available) information about the place where the error happened
     * and the type of error.
     */
    struct xml_error : public io_error {

        unsigned long line;
        unsigned long column;
        XML_Error error_code;
        std::string error_string;

        explicit xml_error(const XML_Parser& parser) :
            io_error(std::string{"XML parsing error at line "}
                    + std::to_string(XML_GetCurrentLineNumber(parser))
                    + ", column "
                    + std::to_string(XML_GetCurrentColumnNumber(parser))
                    + ": "
                    + XML_ErrorString(XML_GetErrorCode(parser))),
            line(XML_GetCurrentLineNumber(parser)),
            column(XML_GetCurrentColumnNumber(parser)),
            error_code(XML_GetErrorCode(parser)),
            error_string(XML_ErrorString(error_code)) {
        }

        explicit xml_error(const std::string& message) :
            io_error(message),
            line(0),
            column(0),
            error_code(),
            error_string(message) {
        }

    }; // struct xml_error

    /**
     * Exception thrown when an OSM XML files contains no version attribute
     * on the 'osm' element or if the version is unknown.
     */
    struct format_version_error : public io_error {

        std::string version;

        explicit format_version_error() :
            io_error("Can not read file without version (missing version attribute on osm element)."),
            version() {
        }

        explicit format_version_error(const char* v) :
            io_error(std::string{"Can not read file with version "} + v),
            version(v) {
        }

    }; // struct format_version_error

    namespace io {

        namespace detail {

            class XMLParser : public Parser {

                static constexpr int buffer_size = 2 * 1000 * 1000;

                enum class context {
                    root,
                    top,
                    node,
                    way,
                    relation,
                    changeset,
                    discussion,
                    comment,
                    comment_text,
                    ignored_node,
                    ignored_way,
                    ignored_relation,
                    ignored_changeset,
                    in_object
                }; // enum class context

                context m_context;
                context m_last_context;

                /**
                 * This is used only for change files which contain create, modify,
                 * and delete sections.
                 */
                bool m_in_delete_section;

                osmium::io::Header m_header;

                osmium::memory::Buffer m_buffer;

                std::unique_ptr<osmium::builder::NodeBuilder>                m_node_builder;
                std::unique_ptr<osmium::builder::WayBuilder>                 m_way_builder;
                std::unique_ptr<osmium::builder::RelationBuilder>            m_relation_builder;
                std::unique_ptr<osmium::builder::ChangesetBuilder>           m_changeset_builder;
                std::unique_ptr<osmium::builder::ChangesetDiscussionBuilder> m_changeset_discussion_builder;

                std::unique_ptr<osmium::builder::TagListBuilder>             m_tl_builder;
                std::unique_ptr<osmium::builder::WayNodeListBuilder>         m_wnl_builder;
                std::unique_ptr<osmium::builder::RelationMemberListBuilder>  m_rml_builder;

                std::string m_comment_text;

                /**
                 * A C++ wrapper for the Expat parser that makes sure no memory is leaked.
                 */
                template <typename T>
                class ExpatXMLParser {

                    XML_Parser m_parser;

                    static void XMLCALL start_element_wrapper(void* data, const XML_Char* element, const XML_Char** attrs) {
                        static_cast<XMLParser*>(data)->start_element(element, attrs);
                    }

                    static void XMLCALL end_element_wrapper(void* data, const XML_Char* element) {
                        static_cast<XMLParser*>(data)->end_element(element);
                    }

                    static void XMLCALL character_data_wrapper(void* data, const XML_Char* text, int len) {
                        static_cast<XMLParser*>(data)->characters(text, len);
                    }

                    // This handler is called when there are any XML entities
                    // declared in the OSM file. Entities are normally not used,
                    // but they can be misused. See
                    // https://en.wikipedia.org/wiki/Billion_laughs
                    // The handler will just throw an error.
                    static void entity_declaration_handler(void*,
                            const XML_Char*, int, const XML_Char*, int, const XML_Char*,
                            const XML_Char*, const XML_Char*, const XML_Char*) {
                        throw osmium::xml_error{"XML entities are not supported"};
                    }

                public:

                    explicit ExpatXMLParser(T* callback_object) :
                        m_parser(XML_ParserCreate(nullptr)) {
                        if (!m_parser) {
                            throw osmium::io_error{"Internal error: Can not create parser"};
                        }
                        XML_SetUserData(m_parser, callback_object);
                        XML_SetElementHandler(m_parser, start_element_wrapper, end_element_wrapper);
                        XML_SetCharacterDataHandler(m_parser, character_data_wrapper);
                        XML_SetEntityDeclHandler(m_parser, entity_declaration_handler);
                    }

                    ExpatXMLParser(const ExpatXMLParser&) = delete;
                    ExpatXMLParser(ExpatXMLParser&&) = delete;

                    ExpatXMLParser& operator=(const ExpatXMLParser&) = delete;
                    ExpatXMLParser& operator=(ExpatXMLParser&&) = delete;

                    ~ExpatXMLParser() noexcept {
                        XML_ParserFree(m_parser);
                    }

                    void operator()(const std::string& data, bool last) {
                        if (XML_Parse(m_parser, data.data(), static_cast_with_assert<int>(data.size()), last) == XML_STATUS_ERROR) {
                            throw osmium::xml_error{m_parser};
                        }
                    }

                }; // class ExpatXMLParser

                template <typename T>
                static void check_attributes(const XML_Char** attrs, T check) {
                    while (*attrs) {
                        check(attrs[0], attrs[1]);
                        attrs += 2;
                    }
                }

                const char* init_object(osmium::OSMObject& object, const XML_Char** attrs) {
                    const char* user = "";

                    if (m_in_delete_section) {
                        object.set_visible(false);
                    }

                    osmium::Location location;

                    check_attributes(attrs, [&location, &user, &object](const XML_Char* name, const XML_Char* value) {
                        if (!std::strcmp(name, "lon")) {
                            location.set_lon(value);
                        } else if (!std::strcmp(name, "lat")) {
                            location.set_lat(value);
                        } else if (!std::strcmp(name, "user")) {
                            user = value;
                        } else {
                            object.set_attribute(name, value);
                        }
                    });

                    if (location && object.type() == osmium::item_type::node) {
                        static_cast<osmium::Node&>(object).set_location(location);
                    }

                    return user;
                }

                void init_changeset(osmium::builder::ChangesetBuilder& builder, const XML_Char** attrs) {
                    osmium::Box box;

                    check_attributes(attrs, [&builder, &box](const XML_Char* name, const XML_Char* value) {
                        if (!std::strcmp(name, "min_lon")) {
                            box.bottom_left().set_lon(value);
                        } else if (!std::strcmp(name, "min_lat")) {
                            box.bottom_left().set_lat(value);
                        } else if (!std::strcmp(name, "max_lon")) {
                            box.top_right().set_lon(value);
                        } else if (!std::strcmp(name, "max_lat")) {
                            box.top_right().set_lat(value);
                        } else if (!std::strcmp(name, "user")) {
                            builder.set_user(value);
                        } else {
                            builder.set_attribute(name, value);
                        }
                    });

                    builder.set_bounds(box);
                }

                void get_tag(osmium::builder::Builder& builder, const XML_Char** attrs) {
                    const char* k = "";
                    const char* v = "";

                    check_attributes(attrs, [&k, &v](const XML_Char* name, const XML_Char* value) {
                        if (name[0] == 'k' && name[1] == 0) {
                            k = value;
                        } else if (name[0] == 'v' && name[1] == 0) {
                            v = value;
                        }
                    });

                    if (!m_tl_builder) {
                        m_tl_builder.reset(new osmium::builder::TagListBuilder{builder});
                    }
                    m_tl_builder->add_tag(k, v);
                }

                void mark_header_as_done() {
                    set_header_value(m_header);
                }

                void start_element(const XML_Char* element, const XML_Char** attrs) {
                    switch (m_context) {
                        case context::root:
                            if (!std::strcmp(element, "osm") || !std::strcmp(element, "osmChange")) {
                                if (!std::strcmp(element, "osmChange")) {
                                    m_header.set_has_multiple_object_versions(true);
                                }
                                check_attributes(attrs, [this](const XML_Char* name, const XML_Char* value) {
                                    if (!std::strcmp(name, "version")) {
                                        m_header.set("version", value);
                                        if (std::strcmp(value, "0.6")) {
                                            throw osmium::format_version_error{value};
                                        }
                                    } else if (!std::strcmp(name, "generator")) {
                                        m_header.set("generator", value);
                                    }
                                });
                                if (m_header.get("version") == "") {
                                    throw osmium::format_version_error{};
                                }
                            } else {
                                throw osmium::xml_error{std::string{"Unknown top-level element: "} + element};
                            }
                            m_context = context::top;
                            break;
                        case context::top:
                            assert(!m_tl_builder);
                            if (!std::strcmp(element, "node")) {
                                mark_header_as_done();
                                if (read_types() & osmium::osm_entity_bits::node) {
                                    m_node_builder.reset(new osmium::builder::NodeBuilder{m_buffer});
                                    m_node_builder->set_user(init_object(m_node_builder->object(), attrs));
                                    m_context = context::node;
                                } else {
                                    m_context = context::ignored_node;
                                }
                            } else if (!std::strcmp(element, "way")) {
                                mark_header_as_done();
                                if (read_types() & osmium::osm_entity_bits::way) {
                                    m_way_builder.reset(new osmium::builder::WayBuilder{m_buffer});
                                    m_way_builder->set_user(init_object(m_way_builder->object(), attrs));
                                    m_context = context::way;
                                } else {
                                    m_context = context::ignored_way;
                                }
                            } else if (!std::strcmp(element, "relation")) {
                                mark_header_as_done();
                                if (read_types() & osmium::osm_entity_bits::relation) {
                                    m_relation_builder.reset(new osmium::builder::RelationBuilder{m_buffer});
                                    m_relation_builder->set_user(init_object(m_relation_builder->object(), attrs));
                                    m_context = context::relation;
                                } else {
                                    m_context = context::ignored_relation;
                                }
                            } else if (!std::strcmp(element, "changeset")) {
                                mark_header_as_done();
                                if (read_types() & osmium::osm_entity_bits::changeset) {
                                    m_changeset_builder.reset(new osmium::builder::ChangesetBuilder{m_buffer});
                                    init_changeset(*m_changeset_builder, attrs);
                                    m_context = context::changeset;
                                } else {
                                    m_context = context::ignored_changeset;
                                }
                            } else if (!std::strcmp(element, "bounds")) {
                                osmium::Location min;
                                osmium::Location max;
                                check_attributes(attrs, [&min, &max](const XML_Char* name, const XML_Char* value) {
                                    if (!std::strcmp(name, "minlon")) {
                                        min.set_lon(value);
                                    } else if (!std::strcmp(name, "minlat")) {
                                        min.set_lat(value);
                                    } else if (!std::strcmp(name, "maxlon")) {
                                        max.set_lon(value);
                                    } else if (!std::strcmp(name, "maxlat")) {
                                        max.set_lat(value);
                                    }
                                });
                                osmium::Box box;
                                box.extend(min).extend(max);
                                m_header.add_box(box);
                            } else if (!std::strcmp(element, "delete")) {
                                m_in_delete_section = true;
                            }
                            break;
                        case context::node:
                            m_last_context = context::node;
                            m_context = context::in_object;
                            if (!std::strcmp(element, "tag")) {
                                get_tag(*m_node_builder, attrs);
                            }
                            break;
                        case context::way:
                            m_last_context = context::way;
                            m_context = context::in_object;
                            if (!std::strcmp(element, "nd")) {
                                m_tl_builder.reset();

                                if (!m_wnl_builder) {
                                    m_wnl_builder.reset(new osmium::builder::WayNodeListBuilder{*m_way_builder});
                                }

                                NodeRef nr;
                                check_attributes(attrs, [this, &nr](const XML_Char* name, const XML_Char* value) {
                                    if (!std::strcmp(name, "ref")) {
                                        nr.set_ref(osmium::string_to_object_id(value));
                                    } else if (!std::strcmp(name, "lon")) {
                                        nr.location().set_lon(value);
                                    } else if (!std::strcmp(name, "lat")) {
                                        nr.location().set_lat(value);
                                    }
                                });
                                m_wnl_builder->add_node_ref(nr);
                            } else if (!std::strcmp(element, "tag")) {
                                m_wnl_builder.reset();
                                get_tag(*m_way_builder, attrs);
                            }
                            break;
                        case context::relation:
                            m_last_context = context::relation;
                            m_context = context::in_object;
                            if (!std::strcmp(element, "member")) {
                                m_tl_builder.reset();

                                if (!m_rml_builder) {
                                    m_rml_builder.reset(new osmium::builder::RelationMemberListBuilder{*m_relation_builder});
                                }

                                item_type type = item_type::undefined;
                                object_id_type ref = 0;
                                const char* role = "";
                                check_attributes(attrs, [&type, &ref, &role](const XML_Char* name, const XML_Char* value) {
                                    if (!std::strcmp(name, "type")) {
                                        type = char_to_item_type(value[0]);
                                    } else if (!std::strcmp(name, "ref")) {
                                        ref = osmium::string_to_object_id(value);
                                    } else if (!std::strcmp(name, "role")) {
                                        role = static_cast<const char*>(value);
                                    }
                                });
                                if (type != item_type::node && type != item_type::way && type != item_type::relation) {
                                    throw osmium::xml_error{"Unknown type on relation member"};
                                }
                                if (ref == 0) {
                                    throw osmium::xml_error{"Missing ref on relation member"};
                                }
                                m_rml_builder->add_member(type, ref, role);
                            } else if (!std::strcmp(element, "tag")) {
                                m_rml_builder.reset();
                                get_tag(*m_relation_builder, attrs);
                            }
                            break;
                        case context::changeset:
                            m_last_context = context::changeset;
                            if (!std::strcmp(element, "discussion")) {
                                m_context = context::discussion;
                                m_tl_builder.reset();
                                if (!m_changeset_discussion_builder) {
                                    m_changeset_discussion_builder.reset(new osmium::builder::ChangesetDiscussionBuilder{*m_changeset_builder});
                                }
                            } else if (!std::strcmp(element, "tag")) {
                                m_context = context::in_object;
                                m_changeset_discussion_builder.reset();
                                get_tag(*m_changeset_builder, attrs);
                            }
                            break;
                        case context::discussion:
                            if (!std::strcmp(element, "comment")) {
                                m_context = context::comment;
                                osmium::Timestamp date;
                                osmium::user_id_type uid = 0;
                                const char* user = "";
                                check_attributes(attrs, [&date, &uid, &user](const XML_Char* name, const XML_Char* value) {
                                    if (!std::strcmp(name, "date")) {
                                        date = osmium::Timestamp(value);
                                    } else if (!std::strcmp(name, "uid")) {
                                        uid = osmium::string_to_user_id(value);
                                    } else if (!std::strcmp(name, "user")) {
                                        user = static_cast<const char*>(value);
                                    }
                                });
                                m_changeset_discussion_builder->add_comment(date, uid, user);
                            }
                            break;
                        case context::comment:
                            if (!std::strcmp(element, "text")) {
                                m_context = context::comment_text;
                            }
                            break;
                        case context::comment_text:
                            break;
                        case context::ignored_node:
                            break;
                        case context::ignored_way:
                            break;
                        case context::ignored_relation:
                            break;
                        case context::ignored_changeset:
                            break;
                        case context::in_object:
                            assert(false); // should never be here
                            break;
                    }
                }

                void end_element(const XML_Char* element) {
                    switch (m_context) {
                        case context::root:
                            assert(false); // should never be here
                            break;
                        case context::top:
                            if (!std::strcmp(element, "osm") || !std::strcmp(element, "osmChange")) {
                                mark_header_as_done();
                                m_context = context::root;
                            } else if (!std::strcmp(element, "delete")) {
                                m_in_delete_section = false;
                            }
                            break;
                        case context::node:
                            assert(!std::strcmp(element, "node"));
                            m_tl_builder.reset();
                            m_node_builder.reset();
                            m_buffer.commit();
                            m_context = context::top;
                            flush_buffer();
                            break;
                        case context::way:
                            assert(!std::strcmp(element, "way"));
                            m_tl_builder.reset();
                            m_wnl_builder.reset();
                            m_way_builder.reset();
                            m_buffer.commit();
                            m_context = context::top;
                            flush_buffer();
                            break;
                        case context::relation:
                            assert(!std::strcmp(element, "relation"));
                            m_tl_builder.reset();
                            m_rml_builder.reset();
                            m_relation_builder.reset();
                            m_buffer.commit();
                            m_context = context::top;
                            flush_buffer();
                            break;
                        case context::changeset:
                            assert(!std::strcmp(element, "changeset"));
                            m_tl_builder.reset();
                            m_changeset_discussion_builder.reset();
                            m_changeset_builder.reset();
                            m_buffer.commit();
                            m_context = context::top;
                            flush_buffer();
                            break;
                        case context::discussion:
                            assert(!std::strcmp(element, "discussion"));
                            m_context = context::changeset;
                            break;
                        case context::comment:
                            assert(!std::strcmp(element, "comment"));
                            m_context = context::discussion;
                            break;
                        case context::comment_text:
                            assert(!std::strcmp(element, "text"));
                            m_context = context::comment;
                            m_changeset_discussion_builder->add_comment_text(m_comment_text);
                            break;
                        case context::in_object:
                            m_context = m_last_context;
                            break;
                        case context::ignored_node:
                            if (!std::strcmp(element, "node")) {
                                m_context = context::top;
                            }
                            break;
                        case context::ignored_way:
                            if (!std::strcmp(element, "way")) {
                                m_context = context::top;
                            }
                            break;
                        case context::ignored_relation:
                            if (!std::strcmp(element, "relation")) {
                                m_context = context::top;
                            }
                            break;
                        case context::ignored_changeset:
                            if (!std::strcmp(element, "changeset")) {
                                m_context = context::top;
                            }
                            break;
                    }
                }

                void characters(const XML_Char* text, int len) {
                    if (m_context == context::comment_text) {
                        m_comment_text.append(text, len);
                    } else {
                        m_comment_text.resize(0);
                    }
                }

                void flush_buffer() {
                    if (m_buffer.committed() > buffer_size / 10 * 9) {
                        send_to_output_queue(std::move(m_buffer));
                        osmium::memory::Buffer buffer(buffer_size);
                        using std::swap;
                        swap(m_buffer, buffer);
                    }
                }

            public:

                XMLParser(future_string_queue_type& input_queue,
                          future_buffer_queue_type& output_queue,
                          std::promise<osmium::io::Header>& header_promise,
                          osmium::io::detail::reader_options options) :
                    Parser(input_queue, output_queue, header_promise, options),
                    m_context(context::root),
                    m_last_context(context::root),
                    m_in_delete_section(false),
                    m_header(),
                    m_buffer(buffer_size),
                    m_node_builder(),
                    m_way_builder(),
                    m_relation_builder(),
                    m_changeset_builder(),
                    m_changeset_discussion_builder(),
                    m_tl_builder(),
                    m_wnl_builder(),
                    m_rml_builder() {
                }

                ~XMLParser() noexcept final = default;

                void run() final {
                    osmium::thread::set_thread_name("_osmium_xml_in");

                    ExpatXMLParser<XMLParser> parser(this);

                    while (!input_done()) {
                        const std::string data{get_input()};
                        parser(data, input_done());
                        if (read_types() == osmium::osm_entity_bits::nothing && header_is_done()) {
                            break;
                        }
                    }

                    mark_header_as_done();

                    if (m_buffer.committed() > 0) {
                        send_to_output_queue(std::move(m_buffer));
                    }
                }

            }; // class XMLParser

            // we want the register_parser() function to run, setting
            // the variable is only a side-effect, it will never be used
            const bool registered_xml_parser = ParserFactory::instance().register_parser(
                file_format::xml,
                [](future_string_queue_type& input_queue,
                    future_buffer_queue_type& output_queue,
                    std::promise<osmium::io::Header>& header_promise,
                    osmium::io::detail::reader_options options) {
                    return std::unique_ptr<Parser>(new XMLParser{input_queue, output_queue, header_promise, options});
            });

            // dummy function to silence the unused variable warning from above
            inline bool get_registered_xml_parser() noexcept {
                return registered_xml_parser;
            }

        } // namespace detail

    } // namespace io

} // namespace osmium

#endif // OSMIUM_IO_DETAIL_XML_INPUT_FORMAT_HPP


text:
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Windows.Forms;
using MaterialSkin.Animations;

namespace MaterialSkin.Controls
{
    public class MaterialRaisedButton : Button, IMaterialControl
    {
        [Browsable(false)]
        public int Depth { get; set; }
        [Browsable(false)]
        public MaterialSkinManager SkinManager { get { return MaterialSkinManager.Instance; } }
        [Browsable(false)]
        public MouseState MouseState { get; set; }
        public bool Primary { get; set; }

        private readonly AnimationManager animationManager;

        public MaterialRaisedButton()
        {
            Primary = true;

            animationManager = new AnimationManager(false)
            {
                Increment = 0.03,
                AnimationType = AnimationType.EaseOut
            };
            animationManager.OnAnimationProgress += sender => Invalidate();
        }

        protected override void OnMouseUp(MouseEventArgs mevent)
        {
            base.OnMouseUp(mevent);

            animationManager.StartNewAnimation(AnimationDirection.In, mevent.Location);
        }

        protected override void OnPaint(PaintEventArgs pevent)
        {
            var g = pevent.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.TextRenderingHint = TextRenderingHint.AntiAlias;

            g.Clear(Parent.BackColor);

            using (var backgroundPath = DrawHelper.CreateRoundRect(ClientRectangle.X,
                ClientRectangle.Y,
                ClientRectangle.Width - 1,
                ClientRectangle.Height - 1,
                1f))
            {
                g.FillPath(Primary ? SkinManager.ColorScheme.PrimaryBrush : SkinManager.GetRaisedButtonBackgroundBrush(), backgroundPath);
            }

            if (animationManager.IsAnimating())
            {
                for (int i = 0; i < animationManager.GetAnimationCount(); i++)
                {
                    var animationValue = animationManager.GetProgress(i);
                    var animationSource = animationManager.GetSource(i);
                    var rippleBrush = new SolidBrush(Color.FromArgb((int)(51 - (animationValue * 50)), Color.White));
                    var rippleSize = (int)(animationValue * Width * 2);
                    g.FillEllipse(rippleBrush, new Rectangle(animationSource.X - rippleSize / 2, animationSource.Y - rippleSize / 2, rippleSize, rippleSize));
                }
            }

            g.DrawString(
                Text.ToUpper(),
                SkinManager.ROBOTO_MEDIUM_10,
                SkinManager.GetRaisedButtonTextBrush(Primary),
                ClientRectangle,
                new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center });
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace RaptorDB.Common
{
    public delegate List<object> ServerSideFunc(IRaptorDB rap, string filter);

    public class HistoryInfo
    {
        public int Version;
        public DateTime ChangeDate;
    }

    /// <summary>
    /// High frequency mode Key/Value store with recycled storage file.
    /// <para>Use for rapid saves of the same key.</para>
    /// <para>Views are not effected by saves in this storage.</para>
    /// <para>NOTE : You do not have history of changes in this storage.</para>
    /// </summary>
    public interface IKeyStoreHF
    {
        object GetObjectHF(string key);
        bool SetObjectHF(string key, object obj);
        bool DeleteKeyHF(string key);
        int CountHF();
        bool ContainsHF(string key);
        string[] GetKeysHF();
        void CompactStorageHF();
        int Increment(string key, int amount);
        decimal Increment(string key, decimal amount);
        int Decrement(string key, int amount);
        decimal Decrement(string key, decimal amount);
        //T Increment<T>(string key, T amount);
        //T Decrement<T>(string key, T amount);
        //IEnumerable<object> EnumerateObjects();
        //string[] SearchKeys(string contains); // FIX : implement
    }

    public interface IRaptorDB
    {
        /// <summary>
        /// Save Bytes (files) to RptorDB storage
        /// </summary>
        /// <param name="docID"></param>
        /// <param name="bytes"></param>
        /// <returns></returns>
        bool SaveBytes(Guid fileID, byte[] bytes);

        /// <summary>
        /// Save a Document to RaptorDB
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="docID"></param>
        /// <param name="document"></param>
        /// <returns></returns>
        bool Save<T>(Guid docID, T document);

        /// <summary>
        /// Query all data in a view
        /// </summary>
        /// <param name="viewname"></param>
        /// <returns></returns>
        Result<object> Query(string viewname);

        /// <summary>
        /// Query all data in a view with paging
        /// </summary>
        /// <param name="viewname"></param>
        /// <param name="start"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        Result<object> Query(string viewname, int start, int count);

        /// <summary>
        /// Query a View with a string filter
        /// </summary>
        /// <param name="viewname"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        Result<object> Query(string viewname, string filter);

        /// <summary>
        /// Query a View with a string filter with paging
        /// </summary>
        /// <param name="viewname"></param>
        /// <param name="filter"></param>
        /// <param name="start"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        Result<object> Query(string viewname, string filter, int start, int count);

        /// <summary>
        /// Query a view with filter, paging and sorting
        /// </summary>
        /// <param name="viewname"></param>
        /// <param name="filter"></param>
        /// <param name="start"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        Result<object> Query(string viewname, string filter, int start, int count, string orderby);

        /// <summary>
        /// Count all data associated with View name
        /// </summary>
        /// <param name="viewname"></param>
        /// <returns></returns>
        int Count(string viewname);

        /// <summary>
        /// Count all data associated with View name and string filter
        /// </summary>
        /// <param name="viewname"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        int Count(string viewname, string filter);

        /// <summary>
        /// Fetch a Document
        /// </summary>
        /// <param name="docID"></param>
        /// <returns></returns>
        object Fetch(Guid docID);

        /// <summary>
        /// Fetch a file bytes
        /// </summary>
        /// <param name="fileID"></param>
        /// <returns></returns>
        byte[] FetchBytes(Guid fileID);

        ///// <summary>
        ///// Shutdown RaptorDB and flush all data to disk
        ///// </summary>
        //void Shutdown();

        /// <summary>
        /// Backup the document storage file incrementally to "Backup" folder
        /// </summary>
        /// <returns>True = done</returns>
        bool Backup();

        /// <summary>
        /// Start background restore of backups in the "Restore" folder
        /// </summary>
        void Restore();

        /// <summary>
        /// Delete a Document
        /// </summary>
        /// <param name="docid"></param>
        /// <returns></returns>
        bool Delete(Guid docid);

        /// <summary>
        /// Delete a File
        /// </summary>
        /// <param name="fileid"></param>
        /// <returns></returns>
        bool DeleteBytes(Guid fileid);

        /// <summary>
        /// Add users
        /// </summary>
        /// <param name="username"></param>
        /// <param name="oldpassword"></param>
        /// <param name="newpassword"></param>
        /// <returns></returns>
        bool AddUser(string username, string oldpassword, string newpassword);

        /// <summary>
        /// Do server side data aggregate queries, so you don't transfer large data rows to clients for processing
        /// </summary>
        /// <param name="func"></param>
        /// <returns></returns>
        object[] ServerSide(ServerSideFunc func, string filter);

        /// <summary>
        /// Do server side data aggregate queries, so you don't transfer large data rows to clients for processing
        /// </summary>
        /// <param name="func"></param>
        /// <returns></returns>
        object[] ServerSide<TRowSchema>(ServerSideFunc func, Expression<Predicate<TRowSchema>> filter);

        /// <summary>
        /// Full text search the entire original document
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        int[] FullTextSearch(string filter);

        // new query model
        /// <summary>
        /// Query a view with linq filter
        /// </summary>
        /// <typeparam name="TRowSchema">Use the Row Schema type for your view</typeparam>
        /// <param name="filter"></param>
        /// <returns></returns>
        Result<TRowSchema> Query<TRowSchema>(Expression<Predicate<TRowSchema>> filter);

        /// <summary>
        /// Query a view with paging
        /// </summary>
        /// <typeparam name="TRowSchema">Use the Row Schema type for your view</typeparam>
        /// <param name="filter"></param>
        /// <param name="start"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        Result<TRowSchema> Query<TRowSchema>(Expression<Predicate<TRowSchema>> filter, int start, int count);

        /// <summary>
        /// Query a view with linq filter, paging and sorting
        /// </summary>
        /// <typeparam name="TRowSchema">Use the Row Schema type for your view</typeparam>
        /// <param name="filter"></param>
        /// <param name="start"></param>
        /// <param name="count"></param>
        /// <param name="orderby"></param>
        /// <returns></returns>
        Result<TRowSchema> Query<TRowSchema>(Expression<Predicate<TRowSchema>> filter, int start, int count, string orderby);

        /// <summary>
        /// Query a view with a string filter
        /// </summary>
        /// <typeparam name="TRowSchema">Use the Row Schema type for your view</typeparam>
        /// <param name="filter"></param>
        /// <returns></returns>
        Result<TRowSchema> Query<TRowSchema>(string filter);

        /// <summary>
        /// Query a view with string filter and paging
        /// </summary>
        /// <typeparam name="TRowSchema">Use the Row Schema type for your view</typeparam>
        /// <param name="filter"></param>
        /// <param name="start"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        Result<TRowSchema> Query<TRowSchema>(string filter, int start, int count);

        /// <summary>
        /// Query a view with string filter, paging and sorting
        /// </summary>
        /// <typeparam name="TRowSchema">Use the Row Schema type for your view</typeparam>
        /// <param name="filter"></param>
        /// <param name="start"></param>
        /// <param name="count"></param>
        /// <param name="orderby"></param>
        /// <returns></returns>
        Result<TRowSchema> Query<TRowSchema>(string filter, int start, int count, string orderby);

        /// <summary>
        /// Count rows with a linq filter
        /// </summary>
        /// <typeparam name="TRowSchema"></typeparam>
        /// <param name="filter"></param>
        /// <returns></returns>
        int Count<TRowSchema>(Expression<Predicate<TRowSchema>> filter);

        /// <summary>
        /// Fetch the change history for a document
        /// </summary>
        /// <param name="docid"></param>
        /// <returns></returns>
        int[] FetchHistory(Guid docid);

        /// <summary>
        /// Fetch the change history for a document with dates
        /// </summary>
        /// <param name="docid"></param>
        /// <returns></returns>
        HistoryInfo[] FetchHistoryInfo(Guid docid);

        /// <summary>
        /// Fetch a change history for a file
        /// </summary>
        /// <param name="fileid"></param>
        /// <returns></returns>
        int[] FetchBytesHistory(Guid fileid);

        /// <summary>
        /// Fetch a change history for a file with dates
        /// </summary>
        /// <param name="docid"></param>
        /// <returns></returns>
        HistoryInfo[] FetchBytesHistoryInfo(Guid docid);

        /// <summary>
        /// Fetch the specific document version
        /// </summary>
        /// <param name="versionNumber"></param>
        /// <returns></returns>
        object FetchVersion(int versionNumber);

        /// <summary>
        /// Fetch the specific file version
        /// </summary>
        /// <param name="versionNumber"></param>
        /// <returns></returns>
        byte[] FetchBytesVersion(int versionNumber);

        /// <summary>
        /// Delete rows from a view
        /// </summary>
        /// <typeparam name="TRowSchema"></typeparam>
        /// <param name="filter"></param>
        /// <returns>Number of rows deleted</returns>
        int ViewDelete<TRowSchema>(Expression<Predicate<TRowSchema>> filter);

        /// <summary>
        /// Delete rows from a view
        /// </summary>
        /// <param name="viewname"></param>
        /// <param name="filter"></param>
        /// <returns>Number of rows deleted</returns>
        int ViewDelete(string viewname, string filter);

        /// <summary>
        /// Insert directly into a view
        /// </summary>
        /// <typeparam name="TRowSchema"></typeparam>
        /// <param name="id"></param>
        /// <param name="row"></param>
        /// <returns></returns>
        bool ViewInsert<TRowSchema>(Guid id, TRowSchema row);

        /// <summary>
        /// Insert directly into a view
        /// </summary>
        /// <param name="viewname"></param>
        /// <param name="id"></param>
        /// <param name="row"></param>
        /// <returns></returns>
        bool ViewInsert(string viewname, Guid id, object row);

        /// <summary>
        /// Get the number of documents in the storage file regardless of versions
        /// </summary>
        /// <returns></returns>
        long DocumentCount();

        /// <summary>
        /// High frequency mode Key/Value store with recycled storage file.
        /// <para>Use for rapid saves of the same key.</para>
        /// <para>Views are not effected by saves in this storage.</para>
        /// <para>NOTE : You do not have history of changes in this storage.</para>
        /// </summary>
        IKeyStoreHF GetKVHF();

        void Shutdown();
    }
}


text:
var util = require('util'),
    https = require('https'),
    querystring = require('querystring'),
    uuid = require('node-uuid'),
    oauth = require('oauth-sign'),
    ReadableStream = require('stream').Readable;

var Twitstream = function (options) {
  var body = {},
      signature, params, track, follow;

  ReadableStream.call(this, {
    objectMode: true
  });

  params = {
    oauth_version: '1.0',
    oauth_consumer_key: options.auth.consumerKey,
    oauth_timestamp: Math.floor(Date.now() / 1000).toString(),
    oauth_nonce: uuid().replace(/-/g, ''),
    oauth_signature_method: 'HMAC-SHA1',
    oauth_token: options.auth.token
  };

  if (options.track) {
    track = options.track.join(',');
    body.track = track;
    params.track = track;
  }

  if (options.follow) {
    follow = options.follow.join(',');
    body.follow = follow;
    params.follow = follow;
  }

  signature = oauth.hmacsign(
    'POST',
    'https://stream.twitter.com/1.1/statuses/filter.json',
    params,
    options.auth.consumerSecret,
    options.auth.tokenSecret
  );

  delete params.track;
  delete params.follow;

  this.request = https.request({
    host: 'stream.twitter.com',
    headers: {
      authorization: 'OAuth ' + Object.keys(params).sort().map(function (key) {
        return key + '="' + oauth.rfc3986(params[key]) + '"';
      }).join(',') + ',oauth_signature="' + oauth.rfc3986(signature) + '"',
      'content-type': 'application/x-www-form-urlencoded'
    },
    path: '/1.1/statuses/filter.json',
    method: 'POST'
  });

  this.request.write(querystring.encode(body) + '\n');
  this.request.end();

  this.request.on('response', this._onResponse.bind(this));
};
util.inherits(Twitstream, ReadableStream);

Twitstream.prototype._onResponse = function (res) {
  var data = '',
      self = this;

  res.on('readable', function () {
    var chunk = res.read(),
        split;

    data += chunk;
    split = data.split('\n');
    data = split.pop();

    function parseJson (line) {
      try {
        return JSON.parse(line);
      }
      catch (ex) {
        self.emit('error', ex);
        return '';
      }
    }

    split.forEach(function (line) {
      self.push(parseJson(line));
    });
  });
};

Twitstream.prototype._read = function () {
};

module.exports = function (options) {
  return new Twitstream(options);
};

module.exports.Twitstream = Twitstream;


text:
import { fromHexcodeToCodepoint, Hexcode } from 'emojibase';
import { formatHexcode } from '../helpers/formatHexcode';

export function spreadHexcode(hexcode: string, map: (hex: Hexcode, range: boolean) => void) {
	if (hexcode.includes('..')) {
		const [lowCodepoint, highCodepoint] = fromHexcodeToCodepoint(hexcode, '..');

		for (let codepoint = lowCodepoint; codepoint <= highCodepoint; codepoint += 1) {
			map(formatHexcode(codepoint.toString(16).padStart(4, '0').toUpperCase()), true);
		}
	} else {
		map(formatHexcode(hexcode), false);
	}
}


text:
function [patterns, targets] = encode_data()
patterns = eye(8) * 2 - 1;
targets = patterns;

end


text:
#include "jcontext.h"
#include "ecma-alloc.h"
#include "ecma-boolean-object.h"
#include "ecma-builtins.h"
#include "ecma-exceptions.h"
#include "ecma-gc.h"
#include "ecma-globals.h"
#include "ecma-helpers.h"
#include "ecma-objects.h"
#include "ecma-objects-general.h"
#include "ecma-function-object.h"

/** \addtogroup ecma ECMA
 * @{
 *
 * \addtogroup ecmabooleanobject ECMA Boolean object related routines
 * @{
 */

/**
 * Boolean object creation operation.
 *
 * See also: ECMA-262 v5, 15.6.2.1
 *
 * @return ecma value
 *         Returned value must be freed with ecma_free_value
 */
ecma_value_t
ecma_op_create_boolean_object (ecma_value_t arg) /**< argument passed to the Boolean constructor */
{
  bool boolean_value = ecma_op_to_boolean (arg);
  ecma_builtin_id_t proto_id;

#if JERRY_BUILTIN_BOOLEAN
  proto_id = ECMA_BUILTIN_ID_BOOLEAN_PROTOTYPE;
#else /* JERRY_BUILTIN_BOOLEAN */
  proto_id = ECMA_BUILTIN_ID_OBJECT_PROTOTYPE;
#endif /* !(JERRY_BUILTIN_BOOLEAN */

  ecma_object_t *prototype_obj_p = ecma_builtin_get (proto_id);

#if JERRY_ESNEXT
  ecma_object_t *new_target = JERRY_CONTEXT (current_new_target_p);
  if (new_target)
  {
    prototype_obj_p = ecma_op_get_prototype_from_constructor (new_target, proto_id);

    if (JERRY_UNLIKELY (prototype_obj_p == NULL))
    {
      return ECMA_VALUE_ERROR;
    }
  }
#endif /* JERRY_ESNEXT */
  ecma_object_t *object_p = ecma_create_object (prototype_obj_p,
                                                sizeof (ecma_extended_object_t),
                                                ECMA_OBJECT_TYPE_CLASS);

  ecma_extended_object_t *ext_object_p = (ecma_extended_object_t *) object_p;
  ext_object_p->u.cls.type = ECMA_OBJECT_CLASS_BOOLEAN;
  ext_object_p->u.cls.u3.value = ecma_make_boolean_value (boolean_value);

#if JERRY_ESNEXT
  if (new_target)
  {
    ecma_deref_object (prototype_obj_p);
  }
#endif /* JERRY_ESNEXT */

  return ecma_make_object_value (object_p);
} /* ecma_op_create_boolean_object */

/**
 * @}
 * @}
 */


text:
<?php

$table = new PhabricatorAuthSSHKey();
$conn_w = $table->establishConnection('w');

foreach (new LiskMigrationIterator($table) as $cursor) {
  if (strlen($cursor->getPHID())) {
    continue;
  }

  queryfx(
    $conn_w,
    'UPDATE %T SET phid = %s WHERE id = %d',
    $table->getTableName(),
    $table->generatePHID(),
    $cursor->getID());
}


text:
package org.innovateuk.ifs.competition.builder;

import org.innovateuk.ifs.competition.resource.SiteTermsAndConditionsResource;

import java.util.List;
import java.util.function.BiConsumer;

import static java.util.Collections.emptyList;
import static org.innovateuk.ifs.base.amend.BaseBuilderAmendFunctions.uniqueIds;

public class SiteTermsAndConditionsResourceBuilder extends
        AbstractTermsAndConditionsResourceBuilder<SiteTermsAndConditionsResource, SiteTermsAndConditionsResourceBuilder> {

    private SiteTermsAndConditionsResourceBuilder(List<BiConsumer<Integer, SiteTermsAndConditionsResource>> newMultiActions) {
        super(newMultiActions);
    }

    @Override
    protected SiteTermsAndConditionsResourceBuilder createNewBuilderWithActions(final List<BiConsumer<Integer,
            SiteTermsAndConditionsResource>> actions) {
        return new SiteTermsAndConditionsResourceBuilder(actions);
    }

    @Override
    protected SiteTermsAndConditionsResource createInitial() {
        return new SiteTermsAndConditionsResource();
    }

    public static SiteTermsAndConditionsResourceBuilder newSiteTermsAndConditionsResource() {
        return new SiteTermsAndConditionsResourceBuilder(emptyList()).with(uniqueIds());
    }
}


text:
var Twig = Twig || require("../twig"),
    twig = twig || Twig.twig;

describe("Twig.js Functions ->", function() {
    // Add some test functions to work with
	Twig.extendFunction("echo", function(a) {
	    return a;
	});
    Twig.extendFunction("square", function(a) {
        return a * a;
    });
    Twig.extendFunction("list", function() {
        return Array.prototype.slice.call(arguments);
    });

    it("should allow you to define a function", function() {
        twig({data: '{{ square(a) }}'}).render({a:4}).should.equal("16");
    });
    it("should chain with other expressions", function() {
        twig({data: '{{ square(a) + 4 }}'}).render({a:4}).should.equal("20");
    });
    it("should chain with filters", function() {
        twig({data: '{{ echo(a)|default("foo") }}'}).render().should.equal("foo");
    });
    it("should work in for loop expressions", function() {
        twig({data: '{% for i in list(1, 2, 3) %}{{ i }},{% endfor %}'}).render().should.equal("1,2,3,");
    });
    it("should be able to differentiate between a function and a variable", function() {
        twig({data: '{{ square ( square ) + square }}'}).render({square: 2}).should.equal("6");
    });
    it("should work with boolean operations", function() {
        twig({data: '{% if echo(true) or echo(false) %}yes{% endif %}'}).render().should.equal("yes");
    });

    it("should execute functions passed as context values", function() {
        twig({
            data: '{{ value }}'
        }).render({
            value: function() {
                return "test";
            }
        }).should.equal("test");
    });
    it("should execute functions passed as context values with this mapped to the context", function() {
        twig({
            data: '{{ value }}'
        }).render({
            test: "value",
            value: function() {
                return this.test;
            }
        }).should.equal("value");
    });
    it("should execute functions passed as context values with arguments", function() {
        twig({
            data: '{{ value(1, "test") }}'
        }).render({
            value: function(a, b, c) {
                return a + "-" + b + "-" + (c===undefined?"true":"false");
            }
        }).should.equal("1-test-true");
    });
    it("should execute functions passed as context value parameters with this mapped to the context", function() {
        twig({
            data: '{{ value }}'
        }).render({
            test: "value",
            value: function() {
                return this.test;
            }
        }).should.equal("value");
    });

    it("should execute functions passed as context object parameters", function() {
        twig({
            data: '{{ obj.value }}'
        }).render({
            obj: {
                 value: function() {
                    return "test";
                }
            }
        }).should.equal("test");
    });
    it("should execute functions passed as context object parameters with arguments", function() {
        twig({
            data: '{{ obj.value(1, "test") }}'
        }).render({
            obj: {
                 value: function(a, b, c) {
                    return a + "-" + b + "-" + (c===undefined?"true":"false");
                }
            }
        }).should.equal("1-test-true");
    });

    it("should execute functions passed as context object parameters", function() {
        twig({
            data: '{{ obj["value"] }}'
        }).render({
            obj: {
                 value: function() {
                    return "test";
                }
            }
        }).should.equal("test");
    });
    it("should execute functions passed as context object parameters with arguments", function() {
        twig({
            data: '{{ obj["value"](1, "test") }}'
        }).render({
            obj: {
                 value: function(a, b, c) {
                    return a + "-" + b + "-" + (c===undefined?"true":"false");
                }
            }
        }).should.equal("1-test-true");
    });

    describe("Built-in Functions ->", function() {
        describe("range ->", function() {
            it("should work over a range of numbers", function() {
                twig({data: '{% for i in range(0, 3) %}{{ i }},{% endfor %}'}).render().should.equal("0,1,2,3,");
            });
            it("should work over a range of letters", function() {
                twig({data: '{% for i in range("a", "c") %}{{ i }},{% endfor %}'}).render().should.equal("a,b,c,");
            });
            it("should work with an interval", function() {
                twig({data: '{% for i in range(1, 15, 3) %}{{ i }},{% endfor %}'}).render().should.equal("1,4,7,10,13,");
            });

            it("should work with .. invocation", function() {
                twig({data: '{% for i in 0..3 %}{{ i }},{% endfor %}'}).render().should.equal("0,1,2,3,");
                twig({data: '{% for i in "a" .. "c" %}{{ i }},{% endfor %}'}).render().should.equal("a,b,c,");
            });
        });
        describe("cycle ->", function() {
            it("should cycle through an array of values", function() {
                twig({data: '{% for i in range(0, 3) %}{{ cycle(["odd", "even"], i) }};{% endfor %}'}).render().should.equal("odd;even;odd;even;");
            });
        });
        describe("date ->", function() {
            function pad(num) {return num<10?'0'+num:num;}
            function stringDate(date){
                return pad(date.getDate()) + "/" + pad(date.getMonth()+1) + "/" + date.getFullYear()
                                         + " @ " + pad(date.getHours()) + ":" + pad(date.getMinutes()) + ":" + pad(date.getSeconds());
            }

            it("should understand timestamps", function() {
                var date = new Date(946706400 * 1000);
                twig({data: '{{ date(946706400)|date("d/m/Y @ H:i:s") }}'}).render().should.equal(stringDate(date));
            });
            it("should understand relative dates", function() {
                twig({data: '{{ date("+1 day") > date() }}'}).render().should.equal("true");
                twig({data: '{{ date("-1 day") > date() }}'}).render().should.equal("false");
            });
            it("should support 'now' as a date parameter", function() {
                twig({data: '{{ date("now") }}' }).render().should.equal(new Date().toString());
            });
            it("should understand exact dates", function() {
                var date = new Date("June 20, 2010 UTC");

                twig({data: '{{ date("June 20, 2010 UTC")|date("d/m/Y @ H:i:s") }}'}).render().should.equal(stringDate(date));
            });
        });
        describe("dump ->", function() {
            var EOL = '\n';
            it("should output formatted number", function() {
                twig({data: '{{ dump(test) }}' }).render({ test: 5 }).should.equal('number(5)' + EOL);
            });
            it("should output formatted string", function() {
                twig({data: '{{ dump(test) }}' }).render({ test: "String" }).should.equal('string(6) "String"' + EOL);
            });
            it("should output formatted boolean", function() {
                twig({data: '{{ dump(test) }}' }).render({ test: true }).should.equal('bool(true)' + EOL);
            });
            it("should output formatted null", function() {
                twig({data: '{{ dump(test) }}' }).render({ test: null }).should.equal('NULL' + EOL);
            });
            it("should output formatted object", function() {
                twig({data: '{{ dump(test) }}' }).render({ test: {} }).should.equal('object(0) {' + EOL + '}' + EOL);
            });
            it("should output formatted array", function() {
                twig({data: '{{ dump(test) }}' }).render({ test: [] }).should.equal('object(0) {' + EOL + '}' + EOL);
            });
            it("should output formatted undefined", function() {
                twig({data: '{{ dump(test) }}' }).render({ test: undefined }).should.equal('undefined' + EOL);
            });
        });

        describe("block ->", function() {
            it("should render the content of blocks", function() {
                twig({data: '{% block title %}Content - {{ val }}{% endblock %} Title: {{ block("title") }}'}).render({ val: "test" })
                    .should.equal("Content - test Title: Content - test");
            });

            it("shouldn't escape the content of blocks twice", function() {
                twig({
                    autoescape: true,
                    data: '{% block test %}{{ val }}{% endblock %} {{ block("test") }}'
                }).render({
                    val: "te&st"
                }).should.equal("te&st te&st");
            });
        });

        describe("attribute ->", function() {
            it("should access attribute of an object", function() {
                twig({data: '{{ attribute(obj, key) }}' }).render({
                    obj: { name: "Twig.js"},
                    key: "name"
                })
                .should.equal("Twig.js");
            });

            it("should call function of attribute of an object", function() {
                twig({data: '{{ attribute(obj, key, params) }}' }).render({
                    obj: {
                        name: function(first, last) {
                            return first+'.'+last;
                        }
                    },
                    key: "name",
                    params: ['Twig', 'js']
                  })
                  .should.equal("Twig.js");
            });

            it("should return undefined for missing attribute of an object", function() {
                twig({data: '{{ attribute(obj, key, params) }}' }).render({
                    obj: {
                        name: function(first, last) {
                            return first+'.'+last;
                        }
                    },
                    key: "missing",
                    params: ['Twig', 'js']
                  })
                  .should.equal("");
            });

            it("should return element of an array", function() {
                twig({data: '{{ attribute(arr, 0) }}' }).render({
                    arr: ['Twig', 'js']
                  })
                  .should.equal("Twig");
            });

            it("should return undef for array beyond index size", function() {
                twig({data: '{{ attribute(arr, 100) }}' }).render({
                    arr: ['Twig', 'js']
                  })
                  .should.equal("");
            });

        });
        describe("template_from_string ->", function() {
            it("should load a template from a string", function() {
                twig({data: '{% include template_from_string("{{ value }}") %}'}).render({
                    value: 'test'
                })
                .should.equal('test');
            });
            it("should load a template from a variable", function() {
                twig({data: '{% include template_from_string(template) %}'}).render({
                    template: '{{ value }}',
                    value: 'test'
                })
                .should.equal('test');
            });
        });

        describe("random ->", function() {
          this.timeout(500);

            it("should return a random item from a traversable or array", function() {
                var arr = "bcdefghij".split("");

                for (var i = 1; i <= 1000; i++) {
                    arr.should.containEql(twig({data: '{{ random(arr) }}'}).render({arr: arr}));
                }
            });

            it("should return a random character from a string", function() {
                var str = "abcdefghij";

                for (var i = 1; i <= 1000; i++) {
                    str.should.containEql(twig({data: '{{ random(str) }}'}).render({str: str}));
                }
            });

            it("should return a random integer between 0 and the integer parameter", function() {
                for (var i = 1; i <= 1000; i++) {
                    twig({data: '{{ random(10) }}'}).render().should.be.within(0, 10);
                }
            });

            it("should return a random integer between 0 and 2147483647 when no parameters are passed", function() {
                for (var i = 1; i <= 1000; i++) {
                    twig({data: '{{ random() }}'}).render().should.be.within(0, 2147483647);
                }
            });
        });

        describe("min, max ->", function() {
            it("should support the 'min' function", function() {
                twig({data: '{{ min(2, 1, 3, 5, 4) }}'}).render().should.equal('1');
                twig({data: '{{ min([2, 1, 3, 5, 4]) }}'}).render().should.equal('1');
                twig({data: '{{ min({2:"two", 1:"one", 3:"three", 5:"five", 4:"four"}) }}'}).render().should.equal('five');
            });

            it("should support the 'max' function", function() {
                twig({data: '{{ max([2, 1, 3, 5, 4]) }}'}).render().should.equal('5');
                twig({data: '{{ max(2, 1, 3, 5, 4) }}'}).render().should.equal('5');
                twig({data: '{{ max({2:"two", 1:"one", 3:"three", 5:"five", 4:"four"}) }}'}).render().should.equal('two');
            });
        });
    });
});


text:
package com.limemobile.app.blog.weibo.tencent.api.lbs;

import android.view.ViewGroup;

import com.limemobile.app.blog.weibo.TencentWeibo;
import com.limemobile.app.blog.weibo.tencent.api.ILoadListener;
import com.limemobile.app.blog.weibo.tencent.api.IResultListener;
import com.limemobile.app.blog.weibo.tencent.api.Result;
import com.limemobile.app.blog.weibo.tencent.api.TAsyncTask;
import com.limemobile.app.blog.weibo.tencent.entity.Entity;
import com.limemobile.app.blog.weibo.tencent.entity.TObject;
import com.limemobile.app.blog.weibo.tencent.entity.lbs.PoiInfo;
import com.loopj.android.http.JSONObjectProxy;
import com.tencent.weibo.api.LBSAPI;

/**
 * 获取POI(Point of Interest)
 *
 * @param longitude String 经度,例如:22.541321
 * @param latitude String 纬度,例如:13.935558
 * @param reqnum Integer 每次请求记录的条数(1-25条)
 * @param radius Integer POI的半径(单位为米),取值范围为100-1000,为达到比较好的搜索结果,建议设置为200
 * @param position Integer 上次查询返回的位置,用于翻页(第一次请求时填0)
 */
public class GetPoiTask extends TAsyncTask<PoiInfo> {
    public GetPoiTask(ILoadListener loadListener, IResultListener successListener) {
        this(null, loadListener, successListener);
    }

    public GetPoiTask(ViewGroup container, ILoadListener loadListener,
            IResultListener successListener) {
        super(container, loadListener, successListener);
    }

    @Override
    public String callAPI(Object... params) {
        assert (params.length == 5);
        String longitude = (String) params[0];
        String latitude = (String) params[1];
        String reqnum = Integer.toString((Integer) params[2]);
        String radius = Integer.toString((Integer) params[3]);
        String position = Integer.toString((Integer) params[4]);

        LBSAPI lbsAPI = new LBSAPI(TencentWeibo.getInstance().getOauthVersion());
        String response = null;
        try {
            response = lbsAPI.get_poi(TencentWeibo.getInstance(), TencentWeibo.JSON, longitude, latitude,
                    reqnum, radius, position);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lbsAPI.shutdownConnection();
        }
        return response;
    }

    @Override
    public boolean parse(Entity<TObject> data, JSONObjectProxy object) {
        JSONObjectProxy dataObject = object.getJSONObjectOrNull(Result.DATA_KEY);
        if (dataObject != null) {
            data.data = new PoiInfo();
            data.data.parse(dataObject);

            return true;
        }
        return false;
    }
}


text:
<?php

//matriz mapa / contas / ajeitamento.

include('minimap.php');

$template = <<<THEVERYENDOFYOU

Use os botões de direção para se movimentar:

$minimap
Ver Mapa Completo

<form action="index.php?do=move" method="post">

<input name="north" type="submit" value="Norte" />

<input name="west" type="submit" value="Oeste" /><input name="east" type="submit" value="Leste" />

<input name="south" type="submit" style="width:53px" value="Sul" />

</form>
Latitude: {{latitude}}

Longitude: {{longitude}}

{{townslist}}

{{forumslink}}
{{adminlink}}

Funções Gerais

{{pergaminho}}	{{diamante}}

Último Inimigo Morto:

{{ultmonstro}}
Seu browser não suporta frames.

Atualizar Histórico.

{{pmsnovas}}

THEVERYENDOFYOU;
?>


text:
@interface PodsDummy_Pods_XKKeychain : NSObject
@end
@implementation PodsDummy_Pods_XKKeychain
@end


text:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const InfractionSchema = require("./infractions");
const SettingSchema = require('./settings');
const RoleSchema = require('./role');
const CommandSchema = require('./command');

var GuildSchema = new Schema({
    guildID: {
        type: Number,
        required: true
    },
    settings: {
        type: [SettingSchema],
        required: true
    },
    infractions: {
        type: [InfractionSchema],
        required: true
    },
    roles: {
        type: [RoleSchema],
        required: true
    },
    commands: {
        type: [CommandSchema],
        required: true
    }
});

module.exports = mongoose.model('GuildConfig', GuildSchema);


text:
package com.gemstone.gemfire.internal.lang;

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.gemstone.gemfire.test.junit.categories.UnitTest;

/**
 * The InOutParameterJUnitTest class is a test suite with test cases to test the contract and functionality of the
 * InOutParameter class.
 * <p/>
 * @author John Blum
 * @see com.gemstone.gemfire.internal.lang.InOutParameter
 * @see org.junit.Test
 * @since 6.8
 */
@Category(UnitTest.class)
public class InOutParameterJUnitTest {

  @Test
  public void testEquals() {
    assertEquals(new InOutParameter<Object>(null), new InOutParameter<Object>(null));
    assertEquals(new InOutParameter<Object>(null), null);
    assertEquals(new InOutParameter<Object>("test"), new InOutParameter<Object>("test"));
    assertEquals(new InOutParameter<Object>("test"), "test");
    assertEquals(new InOutParameter<Object>(Math.PI), new InOutParameter<Object>(Math.PI));
    assertEquals(new InOutParameter<Object>(Math.PI), Math.PI);
    assertEquals(new InOutParameter<Object>(true), new InOutParameter<Object>(true));
    assertEquals(new InOutParameter<Object>(true), true);
  }

  @Test
  public void testNotEqual() {
    assertFalse(new InOutParameter<Object>("null").equals(new InOutParameter<Object>(null)));
    assertFalse(new InOutParameter<Object>(Math.PI).equals(3.14159d));
    assertFalse(new InOutParameter<Object>("test").equals("TEST"));
  }

  @Test
  public void testHashCode() {
    assertEquals(0, new InOutParameter<Object>(null).hashCode());
    assertEquals("test".hashCode(), new InOutParameter<Object>("test").hashCode());
    assertEquals(new Double(Math.PI).hashCode(), new InOutParameter<Object>(Math.PI).hashCode());
    assertEquals(Boolean.TRUE.hashCode(), new InOutParameter<Object>(true).hashCode());
  }

  @Test
  public void testToString() {
    assertEquals("null", new InOutParameter<Object>(null).toString());
    assertEquals("null", new InOutParameter<Object>("null").toString());
    assertEquals("test", new InOutParameter<Object>("test").toString());
    assertEquals(String.valueOf(Math.PI), new InOutParameter<Object>(Math.PI).toString());
    assertEquals("true", new InOutParameter<Object>(Boolean.TRUE).toString());
  }

}


text:
import json
from django.conf import settings

from devilry.apps.gradeeditors import (gradeeditor_registry, JsonRegistryItem,
                                       DraftValidationError, ConfigValidationError)
from devilry.apps.markup.parse_markdown import markdown_full

class Autograde(JsonRegistryItem):
    """
    Serves as a minimal example of a grade editor, and as a well suited grade
    editor for use in test cases.
    """
    gradeeditorid = 'autograde'
    title = 'Automatic grading'
    description = 'You define a range of grades, (I.E.: F-A or 0-6), and the points required to get each grade.

Examiners only fill in the number of points and an optional feedback text. The grade is calculated from your definition.
'
    config_editor_url = settings.DEVILRY_STATIC_URL + '/autograde_gradeeditor/configeditor.js'
    draft_editor_url = settings.DEVILRY_STATIC_URL + '/autograde_gradeeditor/drafteditor.js'

    @classmethod
    def getGrade(cls, points, grades):
        retval = ''
        retpoints = 0
        for grade in grades:
            if points >= int(grade[1]) and int(grade[1]) >= retpoints:
                retval = grade[0]
                retpoints = int(grade[1])

        return retval

    @classmethod
    def validate_config(cls, configstring):
        config = cls.decode_configstring(configstring)

        if config['maxpoints'] < 0:
            raise ConfigValidationError('Maximum points must be a number higher than 0')

        if config['approvedlimit'] < 0:
            raise ConfigValidationError('Points to pass must be a number higher than 0')

        if config['approvedlimit'] > config['maxpoints']:
            raise ConfigValidationError('Maximum points must be smaller than points to pass')

        if len(config['grades']) == 0:
            raise ConfigValidationError('You have to enter at least one grade')

        hasZeroGrade = False

        for grade in config['grades']:
            if grade[0] == '':
                raise ConfigValidationError('Grade-name cannot be empty')

            if grade[1] == '':
                raise ConfigValidationError('Grade-value cannot be empty')

            if int(grade[1]) > config['maxpoints']:
                raise ConfigValidationError("Grade-value cannot be higher than maxpoints, grade-value = '{}' , maxpoints = '{}' ".format(grade[1], config['maxpoints']))

            if grade[1] < 0:
                raise ConfigValidationError('Grade-value cannot be smaller than 0')

            if int(grade[1]) == 0:
                hasZeroGrade = True

        if not hasZeroGrade:
            raise ConfigValidationError("You have to enter a grade with pointlimit 0")

    @classmethod
    def validate_draft(cls, draftstring, configstring):
        config = cls.decode_configstring(configstring)
        draft = json.loads(draftstring)
        points = draft['points']
        feedback = draft['feedback']

        cls.validate_dict(draft, DraftValidationError, {'points': int,
                                                        'feedback': basestring})
        cls.validate_gradeeditor_key(draft, 'autograde')

        if points > config['maxpoints'] or points < 0:
            raise DraftValidationError('The points-field must be a value between 0 and {}'.format(config['maxpoints']))

    @classmethod
    def draft_to_staticfeedback_kwargs(cls, draftstring, configstring):
        config = cls.decode_configstring(configstring)
        buf = json.loads(draftstring)
        points = buf['points']
        feedback = buf['feedback']

        grade = cls.getGrade(points, config['grades'])

        is_approved = False
        if points >= config['approvedlimit']:
            is_approved = True

        return dict(is_passing_grade=is_approved,
                    grade=grade,
                    points=points,
                    rendered_view=markdown_full(feedback))

gradeeditor_registry.register(Autograde)


text:
using namespace IECoreMaya;
using namespace boost::python;

void IECoreMaya::bindFromMayaInstancerConverter()
{
	IECorePython::RunTimeTypedClass<FromMayaInstancerConverter>()
		.def( init<const MDagPath &>() )
		;
}


text:
package cn.byhieg.threadtutorialtest.char02test;

import cn.byhieg.threadtutorial.char02.SonSynTread;
import junit.framework.TestCase;

/**
 * Created by shiqifeng on 2017/1/3.
 * Mail byhieg@gmail.com
 */
public class SonSynTreadTest extends TestCase {
    public void testRun() throws Exception {
        SonSynTread thread = new SonSynTread();
        thread.start();

        Thread.sleep(1000 * 10);
    }
}