text:
package org.innovateuk.ifs.project.pendingpartner.populator;

import org.innovateuk.ifs.application.service.QuestionRestService;
import org.innovateuk.ifs.competition.publiccontent.resource.PublicContentItemResource;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.service.CompetitionRestService;
import org.innovateuk.ifs.finance.resource.ProjectFinanceResource;
import org.innovateuk.ifs.finance.service.GrantClaimMaximumRestService;
import org.innovateuk.ifs.organisation.resource.OrganisationResource;
import org.innovateuk.ifs.project.finance.service.ProjectFinanceRestService;
import org.innovateuk.ifs.project.pendingpartner.viewmodel.ProjectYourFundingViewModel;
import org.innovateuk.ifs.project.projectteam.PendingPartnerProgressRestService;
import org.innovateuk.ifs.project.resource.PartnerOrganisationResource;
import org.innovateuk.ifs.project.resource.PendingPartnerProgressResource;
import org.innovateuk.ifs.project.resource.ProjectResource;
import org.innovateuk.ifs.project.service.PartnerOrganisationRestService;
import org.innovateuk.ifs.project.service.ProjectRestService;
import org.innovateuk.ifs.publiccontent.service.PublicContentItemRestService;
import org.innovateuk.ifs.user.service.OrganisationRestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

import static java.util.Optional.empty;
import static java.util.Optional.of;
import static org.innovateuk.ifs.question.resource.QuestionSetupType.SUBSIDY_BASIS;

@Component
public class ProjectYourFundingViewModelPopulator {

    @Autowired
    private ProjectFinanceRestService projectFinanceRestService;

    @Autowired
    private PendingPartnerProgressRestService pendingPartnerProgressRestService;

    @Autowired
    private ProjectRestService projectRestService;

    @Autowired
    private OrganisationRestService organisationRestService;

    @Autowired
    private CompetitionRestService competitionRestService;

    @Autowired
    private GrantClaimMaximumRestService grantClaimMaximumRestService;

    @Autowired
    private PartnerOrganisationRestService partnerOrganisationRestService;

    @Autowired
    private QuestionRestService questionRestService;

    @Autowired
    private PublicContentItemRestService publicContentItemRestService;

    public ProjectYourFundingViewModel populate(long projectId, long organisationId) {

        PendingPartnerProgressResource progress = pendingPartnerProgressRestService.getPendingPartnerProgress(projectId, organisationId).getSuccess();
        ProjectFinanceResource projectFinance = projectFinanceRestService.getProjectFinance(projectId, organisationId).getSuccess();
        OrganisationResource organisation = organisationRestService.getOrganisationById(organisationId).getSuccess();
        ProjectResource project = projectRestService.getProjectById(projectId).getSuccess();
        CompetitionResource competition = competitionRestService.getCompetitionById(project.getCompetition()).getSuccess();
        PublicContentItemResource publicContentItem = publicContentItemRestService.getItemByCompetitionId(project.getCompetition()).getSuccess();

        boolean organisationSectionRequired = !competition.applicantShouldUseJesFinances(organisation.getOrganisationTypeEnum());
        boolean organisationRequiredAndNotCompleted = organisationSectionRequired && !progress.isYourOrganisationComplete();
        boolean fundingLevelConstant = grantClaimMaximumRestService.isMaximumFundingLevelConstant(competition.getId()).getSuccess();
        PartnerOrganisationResource partnerOrganisationResource = partnerOrganisationRestService.getPartnerOrganisation(projectId, organisationId).getSuccess();
        boolean subsidyBasisRequired = competition.isSubsidyControl();
        Optional<Long> subsidyQuestionId = subsidyBasisRequired
                ? of(questionRestService.getQuestionByCompetitionIdAndQuestionSetupType(competition.getId(), SUBSIDY_BASIS).getSuccess().getId())
                : empty();

        String hash = publicContentItem.getPublicContentResource().getHash();

        return new ProjectYourFundingViewModel(project,
                organisationId,
                progress.isYourFundingComplete(),
                projectFinance.getMaximumFundingLevel(),
                competition.getId(),
                fundingLevelConstant,
                competition.getFundingType(),
                organisation.getOrganisationTypeEnum(),
                partnerOrganisationResource.isLeadOrganisation(),
                subsidyBasisRequired && !progress.isSubsidyBasisComplete(),
                organisationRequiredAndNotCompleted,
                subsidyQuestionId,
                competition.isThirdPartyOfgem(),
                hash,
                projectFinance.isFixedFundingLevel(),
                competition.isCompTypeOfgemAndFundingTypeThirdParty(),
                competition.isThirdPartyFundingType(),
                competition.isKtp());

    }
}


text:
/* $OpenBSD: dirhash.h,v 1.3 2004/02/02 19:34:39 tedu Exp $	*/
/*
 * Copyright (c) 2001 Ian Dowse.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD: src/sys/ufs/ufs/dirhash.h,v 1.4 2003/01/01 18:48:59 schweikh Exp $
 */

#ifndef _UFS_UFS_DIRHASH_H_
#define _UFS_UFS_DIRHASH_H_

#include <sys/rwlock.h>

/*
 * For fast operations on large directories, we maintain a hash
 * that maps the file name to the offset of the directory entry within
 * the directory file.
 *
 * The hashing uses a dumb spillover to the next free slot on
 * collisions, so we must keep the utilisation low to avoid
 * long linear searches. Deleted entries that are not the last
 * in a chain must be marked DIRHASH_DEL.
 *
 * We also maintain information about free space in each block
 * to speed up creations.
 */
#define DIRHASH_EMPTY	(-1)	/* entry unused */
#define DIRHASH_DEL	(-2)	/* deleted entry; may be part of chain */

#define DIRALIGN	4
#define DH_NFSTATS	(DIRECTSIZ(MAXNAMLEN + 1) / DIRALIGN)
				 /* max DIRALIGN words in a directory entry */

/*
 * Dirhash uses a score mechanism to achieve a hybrid between a
 * least-recently-used and a least-often-used algorithm for entry
 * recycling. The score is incremented when a directory is used, and
 * decremented when the directory is a candidate for recycling. When
 * the score reaches zero, the hash is recycled. Hashes are linked
 * together on a TAILQ list, and hashes with higher scores filter
 * towards the tail (most recently used) end of the list.
 *
 * New hash entries are given an inital score of DH_SCOREINIT and are
 * placed at the most-recently-used end of the list. This helps a lot
 * in the worst-case case scenario where every directory access is
 * to a directory that is not hashed (i.e. the working set of hash
 * candidates is much larger than the configured memry limit). In this
 * case it limits the number of hash builds to 1/DH_SCOREINIT of the
 * number of accesses.
 */
#define DH_SCOREINIT	8	/* initial dh_score when dirhash built */
#define DH_SCOREMAX	64	/* max dh_score value */

/*
 * The main hash table has 2 levels. It is an array of pointers to
 * blocks of DH_NBLKOFF offsets.
 */
#define DH_BLKOFFSHIFT	8
#define DH_NBLKOFF	(1 << DH_BLKOFFSHIFT)
#define DH_BLKOFFMASK	(DH_NBLKOFF - 1)

#define DH_ENTRY(dh, slot) \
    ((dh)->dh_hash[(slot) >> DH_BLKOFFSHIFT][(slot) & DH_BLKOFFMASK])

struct dirhash {
	struct rwlock dh_mtx;	/* protects all fields except dh_list */

	doff_t	**dh_hash;	/* the hash array (2-level) */
	int	dh_narrays;	/* number of entries in dh_hash */
	int	dh_hlen;	/* total slots in the 2-level hash array */
	int	dh_hused;	/* entries in use */

	/* Free space statistics. XXX assumes DIRBLKSIZ is 512. */
	u_int8_t *dh_blkfree;	/* free DIRALIGN words in each dir block */
	int	dh_nblk;	/* size of dh_blkfree array */
	int	dh_dirblks;	/* number of DIRBLKSIZ blocks in dir */
	int	dh_firstfree[DH_NFSTATS + 1]; /* first blk with N words free */

	int	dh_seqopt;	/* sequential access optimisation enabled */
	doff_t	dh_seqoff;	/* sequential access optimisation offset */

	int	dh_score;	/* access count for this dirhash */

	int	dh_onlist;	/* true if on the ufsdirhash_list chain */

	/* Protected by ufsdirhash_mtx. */
	TAILQ_ENTRY(dirhash) dh_list;	/* chain of all dirhashes */
};

extern	int ufs_mindirhashsize;
extern	int ufs_dirhashmaxmem;
extern	int ufs_dirhashmem;

/*
 * Dirhash functions.
 */
void	ufsdirhash_init(void);
void	ufsdirhash_uninit(void);
int	ufsdirhash_build(struct inode *);
doff_t	ufsdirhash_findfree(struct inode *, int, int *);
doff_t	ufsdirhash_enduseful(struct inode *);
int	ufsdirhash_lookup(struct inode *, char *, int, doff_t *, struct buf **,
	    doff_t *);
void	ufsdirhash_newblk(struct inode *, doff_t);
void	ufsdirhash_add(struct inode *, struct direct *, doff_t);
void	ufsdirhash_remove(struct inode *, struct direct *, doff_t);
void	ufsdirhash_move(struct inode *, struct direct *, doff_t, doff_t);
void	ufsdirhash_dirtrunc(struct inode *, doff_t);
void	ufsdirhash_free(struct inode *);

void	ufsdirhash_checkblock(struct inode *, char *, doff_t);

#endif /* !_UFS_UFS_DIRHASH_H_ */

redpajama_set_name: RedPajamaGithub


text:
export interface IStorable {
    toStoreObject(): any;
}


text:
      Crawler ID
      Collection
      Success
      Failed
      Pending
      Schedule
      Execute crawler

          {{crawler.collection.label | characters:35 }}

            {{crawler.success | number}}

            {{crawler.fail | number}}

        {{crawler.pending | number}}

        {{crawler.schedule || '' }}

          Full

          Update

      <response-pager response="crawlers" load="loadOffset(offset)"></response-pager>

      Monitoring {{crawlers.total | number}} crawlers.


text:
//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// internal_types.h
//
// Identification: src/include/common/internal_types.h
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#pragma once

#include <unistd.h>
#include <bitset>
#include <climits>
#include <cstdint>
#include <functional>
#include <limits>
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>

#include "tbb/concurrent_unordered_map.h"
#include "tbb/concurrent_unordered_set.h"
#include "tbb/concurrent_vector.h"

#include "common/logger.h"
#include "common/macros.h"
#include "parser/pg_trigger.h"
#include "type/type_id.h"

// Impose Row-major to avoid confusion
#define EIGEN_DEFAULT_TO_ROW_MAJOR
#include "eigen3/Eigen/Dense"

namespace peloton {

class ItemPointer;
struct ItemPointerHasher;
class ItemPointerComparator;

// For all of the enums defined in this header, we will
// use this value to indicate that it is an invalid value
// I don't think it matters whether this is 0 or -1
#define INVALID_TYPE_ID 0

//===--------------------------------------------------------------------===//
// NULL-related Constants
//===--------------------------------------------------------------------===//

#define VALUE_COMPARE_LESSTHAN -1
#define VALUE_COMPARE_EQUAL 0
#define VALUE_COMPARE_GREATERTHAN 1
#define VALUE_COMPARE_INVALID -2
#define VALUE_COMPARE_NO_EQUAL \
  -3  // assigned when comparing array list and no element matching.

#define INVALID_RATIO -1

#define DEFAULT_DB_NAME "default_database"

extern int DEFAULT_TUPLES_PER_TILEGROUP;
extern int TEST_TUPLES_PER_TILEGROUP;

//===--------------------------------------------------------------------===//
// Other Constants
//===--------------------------------------------------------------------===//

#define VARCHAR_LENGTH_SHORT 16
#define VARCHAR_LENGTH_MID 256
#define VARCHAR_LENGTH_LONG 4096

//===--------------------------------------------------------------------===//
// Comparison Result
// This is used when comparing values with each other
//===--------------------------------------------------------------------===//
enum class CmpBool {
  CmpFalse = 0,
  CmpTrue = 1,
  NULL_ = 2  // Note the underscore suffix
};

//===--------------------------------------------------------------------===//
// Postgres Value Types
// This file defines all the types that we will support
// We do not allow for user-defined types, nor do we try to do anything dynamic.
//
// For more information, see 'pg_type.h' in Postgres
// https://github.com/postgres/postgres/blob/master/src/include/catalog/pg_type.h#L273
//===--------------------------------------------------------------------===//

enum class PostgresValueType {
  INVALID = INVALID_TYPE_ID,
  BOOLEAN = 16,
  TINYINT = 16,  // BOOLEAN is an alias for TINYINT
  SMALLINT = 21,
  INTEGER = 23,
  VARBINARY = 17,
  BIGINT = 20,
  REAL = 700,
  DOUBLE = 701,
  TEXT = 25,
  BPCHAR = 1042,
  BPCHAR2 = 1014,
  VARCHAR = 1015,
  VARCHAR2 = 1043,
  DATE = 1082,
  TIMESTAMPS = 1114,
  TIMESTAMPS2 = 1184,
  TEXT_ARRAY = 1009,     // TEXTARRAYOID in postgres code
  INT2_ARRAY = 1005,     // INT2ARRAYOID in postgres code
  INT4_ARRAY = 1007,     // INT4ARRAYOID in postgres code
  OID_ARRAY = 1028,      // OIDARRAYOID in postgres code
  FLOADT4_ARRAY = 1021,  // FLOADT4ARRAYOID in postgres code
  DECIMAL = 1700
};
std::string PostgresValueTypeToString(PostgresValueType type);
PostgresValueType StringToPostgresValueType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const PostgresValueType &type);

//===--------------------------------------------------------------------===//
// Predicate Expression Operation Types
//===--------------------------------------------------------------------===//

enum class ExpressionType {
  INVALID = INVALID_TYPE_ID,

  // -----------------------------
  // Arithmetic Operators
  // Implicit Numeric Casting: Trying to implement SQL-92.
  // Implicit Character Casting: Trying to implement SQL-92, but not easy...
  // Anyway, use explicit OPERATOR_CAST if you could.
  // -----------------------------

  // left + right (both must be number. implicitly casted)
  OPERATOR_PLUS = 1,
  // left - right (both must be number. implicitly casted)
  OPERATOR_MINUS = 2,
  // left * right (both must be number. implicitly casted)
  OPERATOR_MULTIPLY = 3,
  // left / right (both must be number. implicitly casted)
  OPERATOR_DIVIDE = 4,
  // left || right (both must be char/varchar)
  OPERATOR_CONCAT = 5,
  // left % right (both must be integer)
  OPERATOR_MOD = 6,
  // explicitly cast left as right (right is integer in ValueType enum)
  OPERATOR_CAST = 7,
  // logical not operator
  OPERATOR_NOT = 8,
  // is null operator
  OPERATOR_IS_NULL = 21,
  // is not null operator
  OPERATOR_IS_NOT_NULL = 22,
  // exists test.
  OPERATOR_EXISTS = 18,
  OPERATOR_UNARY_MINUS = 60,

  // -----------------------------
  // Comparison Operators
  // -----------------------------
  // equal operator between left and right
  COMPARE_EQUAL = 10,
  // inequal operator between left and right
  COMPARE_NOTEQUAL = 11,
  // less than operator between left and right
  COMPARE_LESSTHAN = 12,
  // greater than operator between left and right
  COMPARE_GREATERTHAN = 13,
  // less than equal operator between left and right
  COMPARE_LESSTHANOREQUALTO = 14,
  // greater than equal operator between left and right
  COMPARE_GREATERTHANOREQUALTO = 15,
  // LIKE operator (left LIKE right). Both children must be string.
  COMPARE_LIKE = 16,
  // NOT LIKE operator (left NOT LIKE right). Both children must be string.
  COMPARE_NOTLIKE = 17,
  // IN operator [left IN (right1, right2, ...)]
  COMPARE_IN = 19,
  // IS DISTINCT FROM operator
  COMPARE_DISTINCT_FROM = 20,

  // -----------------------------
  // Conjunction Operators
  // -----------------------------
  CONJUNCTION_AND = 30,
  CONJUNCTION_OR = 31,

  // -----------------------------
  // Values
  // -----------------------------
  VALUE_CONSTANT = 40,
  VALUE_PARAMETER = 41,
  VALUE_TUPLE = 42,
  VALUE_TUPLE_ADDRESS = 43,
  VALUE_NULL = 44,
  VALUE_VECTOR = 45,
  VALUE_SCALAR = 46,

  // -----------------------------
  // Aggregates
  // -----------------------------
  AGGREGATE_COUNT = 50,
  AGGREGATE_COUNT_STAR = 51,
  AGGREGATE_SUM = 52,
  AGGREGATE_MIN = 53,
  AGGREGATE_MAX = 54,
  AGGREGATE_AVG = 55,

  // -----------------------------
  // Functions
  // -----------------------------
  FUNCTION = 100,

  // -----------------------------
  // Internals added for Elastic
  // -----------------------------
  HASH_RANGE = 200,

  // -----------------------------
  // Operators
  // -----------------------------
  OPERATOR_CASE_EXPR = 302,
  OPERATOR_NULLIF = 304,
  OPERATOR_COALESCE = 305,

  // -----------------------------
  // Subquery IN/EXISTS
  // -----------------------------
  ROW_SUBQUERY = 400,
  SELECT_SUBQUERY = 401,

  // -----------------------------
  // Parser
  // -----------------------------
  STAR = 500,
  PLACEHOLDER = 501,
  COLUMN_REF = 502,
  FUNCTION_REF = 503,
  TABLE_REF = 504,

  // -----------------------------
  // Miscellaneous
  // -----------------------------
  CAST = 600
};

// When short_str is true, return a short version of ExpressionType string
// For example, + instead of Operator_Plus. It's used to generate the
// expression name
std::string ExpressionTypeToString(ExpressionType type, bool short_str = false);
ExpressionType StringToExpressionType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const ExpressionType &type);
ExpressionType ParserExpressionNameToExpressionType(const std::string &str);

// Note that we have some duplicate DatePartTypes with the 's' suffix
// They have to have the same value in order for it to work.
enum class DatePartType : uint32_t {
  INVALID = INVALID_TYPE_ID,
  CENTURY = 1,
  DAY = 2,
  DAYS = 2,
  DECADE = 3,
  DECADES = 3,
  DOW = 4,
  DOY = 5,
  HOUR = 7,
  HOURS = 7,
  MICROSECOND = 10,
  MICROSECONDS = 10,
  MILLENNIUM = 11,
  MILLISECOND = 12,
  MILLISECONDS = 12,
  MINUTE = 13,
  MINUTES = 13,
  MONTH = 14,
  MONTHS = 14,
  QUARTER = 15,
  QUARTERS = 15,
  SECOND = 16,
  SECONDS = 16,
  WEEK = 20,
  WEEKS = 20,
  YEAR = 21,
  YEARS = 21,
};
std::string DatePartTypeToString(DatePartType type);
DatePartType StringToDatePartType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const DatePartType &type);

// PAVLO: 2017-01-18
// I removed these DatePartTypes because I don't think that
// it's something we can easily support right now. Things get
// weird with timezones
//   EPOCH = 6,
//   ISODOW = 8,
//   ISOYEAR = 9,
//   TIMEZONE = 17,
//   TIMEZONE_HOUR = 18,
//   TIMEZONE_HOURS = 18,
//   TIMEZONE_MINUTE = 19,
//   TIMEZONE_MINUTES = 19,

//===--------------------------------------------------------------------===//
// Network Message Types
//===--------------------------------------------------------------------===//

enum class NetworkMessageType : unsigned char {
  // Important: The character '0' is treated as a null message
  // That means we cannot have an invalid type
  NULL_COMMAND = '0',

  // Responses
  PARSE_COMPLETE = '1',
  BIND_COMPLETE = '2',
  CLOSE_COMPLETE = '3',
  COMMAND_COMPLETE = 'C',
  PARAMETER_STATUS = 'S',
  AUTHENTICATION_REQUEST = 'R',
  ERROR_RESPONSE = 'E',
  EMPTY_QUERY_RESPONSE = 'I',
  NO_DATA_RESPONSE = 'n',
  READY_FOR_QUERY = 'Z',
  ROW_DESCRIPTION = 'T',
  DATA_ROW = 'D',
  // Errors
  HUMAN_READABLE_ERROR = 'M',
  SQLSTATE_CODE_ERROR = 'C',
  // Commands
  EXECUTE_COMMAND = 'E',
  SYNC_COMMAND = 'S',
  TERMINATE_COMMAND = 'X',
  DESCRIBE_COMMAND = 'D',
  BIND_COMMAND = 'B',
  PARSE_COMMAND = 'P',
  SIMPLE_QUERY_COMMAND = 'Q',
  CLOSE_COMMAND = 'C',
  // SSL willingness
  SSL_YES = 'S',
  SSL_NO = 'N',
};

enum class NetworkTransactionStateType : unsigned char {
  INVALID = static_cast<unsigned char>(INVALID_TYPE_ID),
  IDLE = 'I',
  BLOCK = 'T',
  FAIL = 'E',
};

enum class SqlStateErrorCode {
  SERIALIZATION_ERROR = '1',
};

//===--------------------------------------------------------------------===//
// Concurrency Control Types
//===--------------------------------------------------------------------===//

enum class ProtocolType {
  INVALID = INVALID_TYPE_ID,
  TIMESTAMP_ORDERING = 1  // timestamp ordering
};
std::string ProtocolTypeToString(ProtocolType type);
ProtocolType StringToProtocolType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const ProtocolType &type);

//===--------------------------------------------------------------------===//
// Epoch Types
//===--------------------------------------------------------------------===//

enum class EpochType {
  INVALID = INVALID_TYPE_ID,
  DECENTRALIZED_EPOCH = 1  // decentralized epoch manager
};
std::string EpochTypeToString(EpochType type);
EpochType StringToEpochType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const EpochType &type);

enum class TimestampType {
  INVALID = INVALID_TYPE_ID,
  SNAPSHOT_READ = 1,
  READ = 2,
  COMMIT = 3
};
std::string TimestampTypeToString(TimestampType type);
TimestampType StringToTimestampType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const TimestampType &type);

//===--------------------------------------------------------------------===//
// Visibility Types
//===--------------------------------------------------------------------===//

enum class VisibilityType {
  INVALID = INVALID_TYPE_ID,
  INVISIBLE = 1,
  DELETED = 2,
  OK = 3
};
std::string VisibilityTypeToString(VisibilityType type);
VisibilityType StringToVisibilityType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const VisibilityType &type);

enum class VisibilityIdType {
  INVALID = INVALID_TYPE_ID,
  READ_ID = 1,
  COMMIT_ID = 2
};
std::string VisibilityIdTypeToString(VisibilityIdType type);
VisibilityIdType StringToVisibilityIdType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const VisibilityIdType &type);

//===--------------------------------------------------------------------===//
// Isolation Levels
//===--------------------------------------------------------------------===//

enum class IsolationLevelType {
  INVALID = INVALID_TYPE_ID,
  SERIALIZABLE = 1,      // serializable
  SNAPSHOT = 2,          // snapshot isolation
  REPEATABLE_READS = 3,  // repeatable reads
  READ_COMMITTED = 4,    // read committed
};
std::string IsolationLevelTypeToString(IsolationLevelType type);
IsolationLevelType StringToIsolationLevelType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const IsolationLevelType &type);

//===--------------------------------------------------------------------===//
// Conflict Avoidance types
//===--------------------------------------------------------------------===//

enum class ConflictAvoidanceType {
  INVALID = INVALID_TYPE_ID,
  WAIT = 1,   // wait-based
  ABORT = 2,  // abort-based
};
std::string ConflictAvoidanceTypeToString(ConflictAvoidanceType type);
ConflictAvoidanceType StringToConflictAvoidanceType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const ConflictAvoidanceType &type);

//===--------------------------------------------------------------------===//
// Garbage Collection Types
//===--------------------------------------------------------------------===//

enum class GarbageCollectionType {
  INVALID = INVALID_TYPE_ID,
  OFF = 1,  // turn off GC
  ON = 2    // turn on GC
};
std::string GarbageCollectionTypeToString(GarbageCollectionType type);
GarbageCollectionType StringToGarbageCollectionType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const GarbageCollectionType &type);

//===--------------------------------------------------------------------===//
// Backend Types
//===--------------------------------------------------------------------===//

enum class BackendType {
  INVALID = INVALID_TYPE_ID,  // invalid backend type
  MM = 1,                     // on volatile memory
  NVM = 2,                    // on non-volatile memory
  SSD = 3,                    // on ssd
  HDD = 4                     // on hdd
};
std::string BackendTypeToString(BackendType type);
BackendType StringToBackendType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const BackendType &type);

//===--------------------------------------------------------------------===//
// Index Types
//===--------------------------------------------------------------------===//

enum class IndexType {
  INVALID = INVALID_TYPE_ID,  // invalid index type
  BWTREE = 1,                 // bwtree
  HASH = 2,                   // hash
  SKIPLIST = 3,               // skiplist
  ART = 4,                    // ART
};
std::string IndexTypeToString(IndexType type);
IndexType StringToIndexType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const IndexType &type);

enum class IndexConstraintType {
  // invalid index constraint type
  INVALID = INVALID_TYPE_ID,
  // default type - not used to enforce constraints
  DEFAULT = 1,
  // used to enforce primary key constraint
  PRIMARY_KEY = 2,
  // used for unique constraint
  UNIQUE = 3
};
std::string IndexConstraintTypeToString(IndexConstraintType type);
IndexConstraintType StringToIndexConstraintType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const IndexConstraintType &type);

//===--------------------------------------------------------------------===//
// Hybrid Scan Types
//===--------------------------------------------------------------------===//

enum class HybridScanType {
  INVALID = INVALID_TYPE_ID,
  SEQUENTIAL = 1,
  INDEX = 2,
  HYBRID = 3
};
std::string HybridScanTypeToString(HybridScanType type);
HybridScanType StringToHybridScanType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const HybridScanType &type);

//===--------------------------------------------------------------------===//
// Parse Node Types
//===--------------------------------------------------------------------===//

enum class ParseNodeType {
  INVALID = INVALID_TYPE_ID,  // invalid parse node type

  // Scan Nodes
  SCAN = 10,

  // DDL Nodes
  CREATE = 20,
  DROP = 21,

  // Mutator Nodes
  UPDATE = 30,
  INSERT = 31,
  DELETE = 32,

  // Prepared Nodes
  PREPARE = 40,
  EXECUTE = 41,

  // Select Nodes
  SELECT = 50,
  JOIN_EXPR = 51,  // a join tree
  TABLE = 52,      // a single table

  // Test
  MOCK = 80
};
std::string ParseNodeTypeToString(ParseNodeType type);
ParseNodeType StringToParseNodeType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const ParseNodeType &type);

//===--------------------------------------------------------------------===//
// Plan Node Types
//===--------------------------------------------------------------------===//

enum class PlanNodeType {
  INVALID = INVALID_TYPE_ID,  // invalid plan node type

  // Scan Nodes
  SEQSCAN = 10,
  INDEXSCAN = 11,
  CSVSCAN = 12,

  // Join Nodes
  NESTLOOP = 20,
  NESTLOOPINDEX = 21,
  MERGEJOIN = 22,
  HASHJOIN = 23,

  // Mutator Nodes
  UPDATE = 30,
  INSERT = 31,
  DELETE = 32,

  // DDL Nodes
  DROP = 33,
  CREATE = 34,
  POPULATE_INDEX = 35,
  ANALYZE = 36,

  // Communication Nodes
  SEND = 40,
  RECEIVE = 41,
  PRINT = 42,

  // Algebra Nodes
  AGGREGATE = 50,
  UNION = 52,
  ORDERBY = 53,
  PROJECTION = 54,
  MATERIALIZE = 55,
  LIMIT = 56,
  DISTINCT = 57,
  SETOP = 58,   // set operation
  APPEND = 59,  // append
  AGGREGATE_V2 = 61,
  HASH = 62,

  // Utility
  RESULT = 70,
  EXPORT_EXTERNAL_FILE = 71,
  CREATE_FUNC = 72,

  // Test
  MOCK = 80
};
std::string PlanNodeTypeToString(PlanNodeType type);
PlanNodeType StringToPlanNodeType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const PlanNodeType &type);

//===--------------------------------------------------------------------===//
// Create Types
//===--------------------------------------------------------------------===//

enum class CreateType {
  INVALID = INVALID_TYPE_ID,  // invalid create type
  DB = 1,                     // db create type
  TABLE = 2,                  // table create type
  INDEX = 3,                  // index create type
  CONSTRAINT = 4,             // constraint create type
  TRIGGER = 5,                // trigger create type
  SCHEMA = 6,                 // schema create type
};
std::string CreateTypeToString(CreateType type);
CreateType StringToCreateType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const CreateType &type);

//===--------------------------------------------------------------------===//
// Drop Types
//===--------------------------------------------------------------------===//

enum class DropType {
  INVALID = INVALID_TYPE_ID,  // invalid drop type
  DB = 1,                     // db drop type
  TABLE = 2,                  // table drop type
  INDEX = 3,                  // index drop type
  CONSTRAINT = 4,             // constraint drop type
  TRIGGER = 5,                // trigger drop type
  SCHEMA = 6,                 // trigger drop type
};
std::string DropTypeToString(DropType type);
DropType StringToDropType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const DropType &type);

template <class E>
class EnumHash {
 public:
  size_t operator()(const E &e) const {
    return std::hash<typename std::underlying_type<E>::type>()(
        static_cast<typename std::underlying_type<E>::type>(e));
  }
};

//===--------------------------------------------------------------------===//
// Language Types for UDFs
//===--------------------------------------------------------------------===//

enum class PLType {
  PL_PGSQL = 0,  // UDF language: Pl_PGSQL
  PL_C = 1       // UDF language: PL_C
};

//===--------------------------------------------------------------------===//
// Statement Types
//===--------------------------------------------------------------------===//

enum class StatementType {
  INVALID = INVALID_TYPE_ID,  // invalid statement type
  SELECT = 1,                 // select statement type
  INSERT = 3,                 // insert statement type
  UPDATE = 4,                 // update statement type
  DELETE = 5,                 // delete statement type
  CREATE = 6,                 // create statement type
  DROP = 7,                   // drop statement type
  PREPARE = 8,                // prepare statement type
  EXECUTE = 9,                // execute statement type
  RENAME = 11,                // rename statement type
  ALTER = 12,                 // alter statement type
  TRANSACTION = 13,           // transaction statement type,
  COPY = 14,                  // copy type
  ANALYZE = 15,               // analyze type
  VARIABLE_SET = 16,          // variable set statement type
  CREATE_FUNC = 17,           // create func statement type
  EXPLAIN = 18                // explain statement type
};
std::string StatementTypeToString(StatementType type);
StatementType StringToStatementType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const StatementType &type);

//===--------------------------------------------------------------------===//
// Query Types
//===--------------------------------------------------------------------===//

enum class QueryType {
  QUERY_BEGIN = 0,         // begin query
  QUERY_COMMIT = 1,        // commit query
  QUERY_ROLLBACK = 2,      // rollback query
  QUERY_CREATE_TABLE = 3,  // create query
  QUERY_CREATE_DB = 4,
  QUERY_CREATE_INDEX = 5,
  QUERY_DROP = 6,     // other queries
  QUERY_INSERT = 7,   // insert query
  QUERY_PREPARE = 8,  // prepare query
  QUERY_EXECUTE = 9,  // execute query
  QUERY_UPDATE = 10,
  QUERY_DELETE = 11,
  QUERY_RENAME = 12,
  QUERY_ALTER = 13,
  QUERY_COPY = 14,
  QUERY_ANALYZE = 15,
  QUERY_SET = 16,   // set query
  QUERY_SHOW = 17,  // show query
  QUERY_SELECT = 18,
  QUERY_OTHER = 19,
  QUERY_INVALID = 20,
  QUERY_CREATE_TRIGGER = 21,
  QUERY_CREATE_SCHEMA = 22,
  QUERY_CREATE_VIEW = 23,
  QUERY_EXPLAIN = 24
};
std::string QueryTypeToString(QueryType query_type);
QueryType StringToQueryType(std::string str);
namespace parser {
class SQLStatement;
}
QueryType StatementTypeToQueryType(StatementType stmt_type,
                                   const parser::SQLStatement *sql_stmt);
//===--------------------------------------------------------------------===//
// Scan Direction Types
//===--------------------------------------------------------------------===//

enum class ScanDirectionType {
  INVALID = INVALID_TYPE_ID,  // invalid scan direction
  FORWARD = 1,                // forward
  BACKWARD = 2                // backward
};

//===--------------------------------------------------------------------===//
// Join Types
//===--------------------------------------------------------------------===//

enum class JoinType {
  INVALID = INVALID_TYPE_ID,  // invalid join type
  LEFT = 1,                   // left
  RIGHT = 2,                  // right
  INNER = 3,                  // inner
  OUTER = 4,                  // outer
  SEMI = 5                    // IN+Subquery is SEMI
};
std::string JoinTypeToString(JoinType type);
JoinType StringToJoinType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const JoinType &type);

//===--------------------------------------------------------------------===//
// Aggregate Types
//===--------------------------------------------------------------------===//

enum class AggregateType {
  INVALID = INVALID_TYPE_ID,
  SORTED = 1,
  HASH = 2,
  PLAIN = 3  // no group-by
};
std::string AggregateTypeToString(AggregateType type);
AggregateType StringToAggregateType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const AggregateType &type);

// ------------------------------------------------------------------
// Expression Quantifier Types
// ------------------------------------------------------------------
enum class QuantifierType {
  NONE = 0,
  ANY = 1,
  ALL = 2,
};
std::string QuantifierTypeToString(QuantifierType type);
QuantifierType StringToQuantifierType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const QuantifierType &type);

//===--------------------------------------------------------------------===//
// Table Reference Types
//===--------------------------------------------------------------------===//

enum class TableReferenceType {
  INVALID = INVALID_TYPE_ID,  // invalid table reference type
  NAME = 1,                   // table name
  SELECT = 2,                 // output of select
  JOIN = 3,                   // output of join
  CROSS_PRODUCT = 4           // out of cartesian product
};
std::string TableReferenceTypeToString(TableReferenceType type);
TableReferenceType StringToTableReferenceType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const TableReferenceType &type);

//===--------------------------------------------------------------------===//
// Insert Types
//===--------------------------------------------------------------------===//

enum class InsertType {
  INVALID = INVALID_TYPE_ID,  // invalid insert type
  VALUES = 1,                 // values
  SELECT = 2                  // select
};
std::string InsertTypeToString(InsertType type);
InsertType StringToInsertType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const InsertType &type);

//===--------------------------------------------------------------------===//
// Copy Types
//===--------------------------------------------------------------------===//

enum class CopyType {
  INVALID = INVALID_TYPE_ID,  // Invalid copy type
  IMPORT_CSV,                 // Import csv data to database
  IMPORT_TSV,                 // Import tsv data to database
  EXPORT_CSV,                 // Export data to csv file
  EXPORT_STDOUT,              // Export data to std out
  EXPORT_OTHER                // Export data to other file format
};
std::string CopyTypeToString(CopyType type);
CopyType StringToCopyType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const CopyType &type);

enum class ExternalFileFormat {
  CSV,
};
std::string ExternalFileFormatToString(ExternalFileFormat format);
ExternalFileFormat StringToExternalFileFormat(const std::string &str);
std::ostream &operator<<(std::ostream &os, const ExternalFileFormat &format);

//===--------------------------------------------------------------------===//
// Payload Types
//===--------------------------------------------------------------------===//

enum class PayloadType {
  INVALID = INVALID_TYPE_ID,  // invalid message type
  CLIENT_REQUEST = 1,         // request
  CLIENT_RESPONSE = 2,        // response
  STOP = 3                    // stop loop
};
std::string PayloadTypeToString(PayloadType type);
PayloadType StringToPayloadType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const PayloadType &type);

//===--------------------------------------------------------------------===//
// Task Priority Types
//===--------------------------------------------------------------------===//

enum class TaskPriorityType {
  INVALID = INVALID_TYPE_ID,  // invalid priority
  LOW = 10,
  NORMAL = 11,
  HIGH = 12
};
std::string TaskPriorityTypeToString(TaskPriorityType type);
TaskPriorityType StringToTaskPriorityType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const TaskPriorityType &type);

//===--------------------------------------------------------------------===//
// Result Types
//===--------------------------------------------------------------------===//

enum class ResultType {
  INVALID = INVALID_TYPE_ID,  // invalid result type
  SUCCESS = 1,
  FAILURE = 2,
  ABORTED = 3,  // aborted
  NOOP = 4,     // no op
  UNKNOWN = 5,
  QUEUING = 6,
  TO_ABORT = 7,
};
std::string ResultTypeToString(ResultType type);
ResultType StringToResultType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const ResultType &type);

//===--------------------------------------------------------------------===//
// Constraint Types
//===--------------------------------------------------------------------===//

enum class PostgresConstraintType {
  NOT_NULL, /* not standard SQL, but a lot of people * expect it */
  NOTNULL,
  DEFAULT,
  CHECK,
  PRIMARY,
  UNIQUE,
  EXCLUSION,
  FOREIGN,
  ATTR_DEFERRABLE, /* attributes for previous constraint node */
  ATTR_NOT_DEFERRABLE,
  ATTR_DEFERRED,
  ATTR_IMMEDIATE
};

enum class ConstraintType {
  INVALID = INVALID_TYPE_ID,  // invalid
  NOT_NULL = 1,               // notnull
  NOTNULL = 2,                // notnull
  DEFAULT = 3,                // default
  CHECK = 4,                  // check
  PRIMARY = 5,                // primary key
  UNIQUE = 6,                 // unique
  FOREIGN = 7,                // foreign key
  EXCLUSION = 8               // foreign key
};
std::string ConstraintTypeToString(ConstraintType type);
ConstraintType StringToConstraintType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const ConstraintType &type);

enum class FKConstrActionType {
  NOACTION = 0,
  RESTRICT = 1,
  CASCADE = 2,
  SETNULL = 3,
  SETDEFAULT = 4
};

enum class FKConstrMatchType { SIMPLE = 0, PARTIAL = 1, FULL = 2 };

//===--------------------------------------------------------------------===//
// Set Operation Types
//===--------------------------------------------------------------------===//

enum class SetOpType {
  INVALID = INVALID_TYPE_ID,
  INTERSECT = 1,
  INTERSECT_ALL = 2,
  EXCEPT = 3,
  EXCEPT_ALL = 4
};
std::string SetOpTypeToString(SetOpType type);
SetOpType StringToSetOpType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const SetOpType &type);

//===--------------------------------------------------------------------===//
// Logging + Recovery Types
//===--------------------------------------------------------------------===//

enum class LoggingType {
  INVALID = INVALID_TYPE_ID,
  OFF = 1,  // turn off GC
  ON = 2    // turn on GC
};
std::string LoggingTypeToString(LoggingType type);
LoggingType StringToLoggingType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const LoggingType &type);

enum class LogRecordType {
  INVALID = INVALID_TYPE_ID,

  // TransactionContext-related records
  TRANSACTION_BEGIN = 1,
  TRANSACTION_COMMIT = 2,

  // Generic dml records
  TUPLE_INSERT = 11,
  TUPLE_DELETE = 12,
  TUPLE_UPDATE = 13,

  // Epoch related records
  EPOCH_BEGIN = 21,
  EPOCH_END = 22,
};
std::string LogRecordTypeToString(LogRecordType type);
LogRecordType StringToLogRecordType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const LogRecordType &type);

enum class CheckpointingType {
  INVALID = INVALID_TYPE_ID,
  OFF = 1,  // turn off GC
  ON = 2    // turn on GC
};
std::string CheckpointingTypeToString(CheckpointingType type);
CheckpointingType StringToCheckpointingType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const CheckpointingType &type);

/* Possible values for peloton_tilegroup_layout GUC */
enum class LayoutType {
  INVALID = INVALID_TYPE_ID,
  ROW = 1,    /* Pure row layout */
  COLUMN = 2, /* Pure column layout */
  HYBRID = 3  /* Hybrid layout */
};
std::string LayoutTypeToString(LayoutType type);
std::ostream &operator<<(std::ostream &os, const LayoutType &type);

//===--------------------------------------------------------------------===//
// Trigger Types
//===--------------------------------------------------------------------===//

enum class TriggerType {
  BEFORE_INSERT_ROW =
      TRIGGER_TYPE_BEFORE | TRIGGER_TYPE_INSERT | TRIGGER_TYPE_ROW,
  BEFORE_INSERT_STATEMENT =
      TRIGGER_TYPE_BEFORE | TRIGGER_TYPE_INSERT | TRIGGER_TYPE_STATEMENT,
  BEFORE_UPDATE_ROW =
      TRIGGER_TYPE_BEFORE | TRIGGER_TYPE_UPDATE | TRIGGER_TYPE_ROW,
  BEFORE_UPDATE_STATEMENT =
      TRIGGER_TYPE_BEFORE | TRIGGER_TYPE_UPDATE | TRIGGER_TYPE_STATEMENT,
  BEFORE_DELETE_ROW =
      TRIGGER_TYPE_BEFORE | TRIGGER_TYPE_DELETE | TRIGGER_TYPE_ROW,
  BEFORE_DELETE_STATEMENT =
      TRIGGER_TYPE_BEFORE | TRIGGER_TYPE_DELETE | TRIGGER_TYPE_STATEMENT,
  AFTER_INSERT_ROW =
      TRIGGER_TYPE_AFTER | TRIGGER_TYPE_INSERT | TRIGGER_TYPE_ROW,
  AFTER_INSERT_STATEMENT =
      TRIGGER_TYPE_AFTER | TRIGGER_TYPE_INSERT | TRIGGER_TYPE_STATEMENT,
  AFTER_UPDATE_ROW =
      TRIGGER_TYPE_AFTER | TRIGGER_TYPE_UPDATE | TRIGGER_TYPE_ROW,
  AFTER_UPDATE_STATEMENT =
      TRIGGER_TYPE_AFTER | TRIGGER_TYPE_UPDATE | TRIGGER_TYPE_STATEMENT,
  AFTER_DELETE_ROW =
      TRIGGER_TYPE_AFTER | TRIGGER_TYPE_DELETE | TRIGGER_TYPE_ROW,
  AFTER_DELETE_STATEMENT =
      TRIGGER_TYPE_AFTER | TRIGGER_TYPE_DELETE | TRIGGER_TYPE_STATEMENT,
  ON_COMMIT_INSERT_ROW =
      TRIGGER_TYPE_COMMIT | TRIGGER_TYPE_INSERT | TRIGGER_TYPE_ROW,
  ON_COMMIT_INSERT_STATEMENT =
      TRIGGER_TYPE_COMMIT | TRIGGER_TYPE_INSERT | TRIGGER_TYPE_STATEMENT,
  ON_COMMIT_UPDATE_ROW =
      TRIGGER_TYPE_COMMIT | TRIGGER_TYPE_UPDATE | TRIGGER_TYPE_ROW,
  ON_COMMIT_UPDATE_STATEMENT =
      TRIGGER_TYPE_COMMIT | TRIGGER_TYPE_UPDATE | TRIGGER_TYPE_STATEMENT,
  ON_COMMIT_DELETE_ROW =
      TRIGGER_TYPE_COMMIT | TRIGGER_TYPE_DELETE | TRIGGER_TYPE_ROW,
  ON_COMMIT_DELETE_STATEMENT =
      TRIGGER_TYPE_COMMIT | TRIGGER_TYPE_DELETE | TRIGGER_TYPE_STATEMENT,
};

const int TRIGGER_TYPE_MAX = TRIGGER_TYPE_ROW | TRIGGER_TYPE_STATEMENT |
                             TRIGGER_TYPE_BEFORE | TRIGGER_TYPE_AFTER |
                             TRIGGER_TYPE_COMMIT | TRIGGER_TYPE_INSERT |
                             TRIGGER_TYPE_DELETE | TRIGGER_TYPE_UPDATE;

//===--------------------------------------------------------------------===//
// Statistics Types
//===--------------------------------------------------------------------===//

// Statistics Collection Type
// Disable or enable
// TODO: This should probably be a collection level and not a boolean
// (enable/disable)
enum class StatsType {
  // Disable statistics collection
  INVALID = INVALID_TYPE_ID,
  // Enable statistics collection
  ENABLE = 1,
};

enum class MetricType {
  // Metric type is invalid
  INVALID = INVALID_TYPE_ID,
  // Metric to count a number
  COUNTER = 1,
  // Access information, e.g., # tuples read, inserted, updated, deleted
  ACCESS = 2,
  // Life time of a object
  LIFETIME = 3,
  // Statistics for a specific database
  DATABASE = 4,
  // Statistics for a specific table
  TABLE = 5,
  // Statistics for a specific index
  INDEX = 6,
  // Latency of transactions
  LATENCY = 7,
  // Timestamp, e.g., creation time of a table/index
  TEMPORAL = 8,
  // Statistics for a specific table
  QUERY = 9,
  // Statistics for CPU
  PROCESSOR = 10,
};

// All builtin operators we currently support
enum class OperatorId : uint32_t {
  Negation = 0,
  Abs,
  Add,
  Sub,
  Mul,
  Div,
  Mod,
  LogicalAnd,
  LogicalOr,
  Ascii,
  Chr,
  Concat,
  Substr,
  CharLength,
  OctetLength,
  Length,
  Repeat,
  Replace,
  LTrim,
  RTrim,
  BTrim,
  Trim,
  Sqrt,
  Ceil,
  Round,
  DatePart,
  Floor,
  DateTrunc,
  Like,
  Now,

  // Add more operators here, before the last "Invalid" entry
  Invalid
};
std::string OperatorIdToString(OperatorId op_id);

enum class OnError : uint32_t { ReturnNull, Exception };

static const int INVALID_FILE_DESCRIPTOR = -1;

// ------------------------------------------------------------------
// Tuple serialization formats
// ------------------------------------------------------------------

enum class TupleSerializationFormat { NATIVE = 0, DR = 1 };

// ------------------------------------------------------------------
// Entity types
// ------------------------------------------------------------------

enum class EntityType {
  INVALID = INVALID_TYPE_ID,
  TABLE = 1,
  SCHEMA = 2,
  INDEX = 3,
  VIEW = 4,
  PREPARED_STATEMENT = 5,
};
std::string EntityTypeToString(EntityType type);
EntityType StringToEntityType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const EntityType &type);

//===--------------------------------------------------------------------===//
// Type definitions.
//===--------------------------------------------------------------------===//

typedef size_t hash_t;

typedef uint32_t oid_t;

static const oid_t START_OID = 0;

static const oid_t INVALID_OID = std::numeric_limits<oid_t>::max();

static const oid_t MAX_OID = std::numeric_limits<oid_t>::max() - 1;

#define NULL_OID MAX_OID

// For transaction id

typedef uint64_t txn_id_t;

static const txn_id_t INVALID_TXN_ID = 0;

static const txn_id_t INITIAL_TXN_ID = 1;

static const txn_id_t MAX_TXN_ID = std::numeric_limits<txn_id_t>::max();

// For commit id

typedef uint64_t cid_t;

static const cid_t INVALID_CID = 0;

static const cid_t MAX_CID = std::numeric_limits<cid_t>::max();

// For epoch id

typedef uint64_t eid_t;

static const cid_t INVALID_EID = 0;

static const cid_t MAX_EID = std::numeric_limits<eid_t>::max();

// For epoch
static const size_t EPOCH_LENGTH = 40;

// For threads
extern size_t CONNECTION_THREAD_COUNT;
extern size_t LOGGING_THREAD_COUNT;
extern size_t GC_THREAD_COUNT;
extern size_t EPOCH_THREAD_COUNT;

//===--------------------------------------------------------------------===//
// TupleMetadata
//===--------------------------------------------------------------------===//
struct TupleMetadata {
  oid_t table_id = 0;
  oid_t tile_group_id = 0;
  oid_t tuple_slot_id = 0;
  cid_t tuple_end_cid = 0;
};

//===--------------------------------------------------------------------===//
// Column Bitmap
//===--------------------------------------------------------------------===//
static const size_t max_col_count = 128;
typedef std::bitset<max_col_count> ColBitmap;

//===--------------------------------------------------------------------===//
// read-write set
//===--------------------------------------------------------------------===//

// this enum is to identify the operations performed by the transaction.
enum class RWType {
  INVALID,
  READ,
  READ_OWN,  // select for update
  UPDATE,
  INSERT,
  DELETE,
  INS_DEL,  // delete after insert.
};
std::string RWTypeToString(RWType type);
RWType StringToRWType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const RWType &type);

// ItemPointer -> type
typedef tbb::concurrent_unordered_map<ItemPointer, RWType, ItemPointerHasher,
                                      ItemPointerComparator>
    ReadWriteSet;

typedef tbb::concurrent_unordered_set<ItemPointer, ItemPointerHasher,
                                      ItemPointerComparator>
    WriteSet;

// this enum is to identify why the version should be GC'd.
enum class GCVersionType {
  INVALID,
  COMMIT_UPDATE,   // a version that is updated during txn commit.
  COMMIT_DELETE,   // a version that is deleted during txn commit.
  COMMIT_INS_DEL,  // a version that is inserted and deleted during txn commit.
  ABORT_UPDATE,    // a version that is updated during txn abort.
  ABORT_DELETE,    // a version that is deleted during txn abort.
  ABORT_INSERT,    // a version that is inserted during txn abort.
  ABORT_INS_DEL,   // a version that is inserted and deleted during txn commit.
};
std::string GCVersionTypeToString(GCVersionType type);
GCVersionType StringToGCVersionType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const GCVersionType &type);

// block -> offset -> type
typedef std::unordered_map<oid_t, std::unordered_map<oid_t, GCVersionType>>
    GCSet;

enum class DDLType {
  INVALID,
  CREATE,
  DROP,
};
typedef tbb::concurrent_vector<std::tuple<oid_t, oid_t, oid_t, DDLType>>
    CreateDropSet;
typedef std::vector<std::tuple<oid_t, oid_t, oid_t>> GCObjectSet;

//===--------------------------------------------------------------------===//
// File Handle
//===--------------------------------------------------------------------===//
struct FileHandle {
  // FILE pointer
  FILE *file = nullptr;

  // File descriptor
  int fd;

  // Size of the file
  size_t size;

  FileHandle() : file(nullptr), fd(INVALID_FILE_DESCRIPTOR), size(0) {}

  FileHandle(FILE *file, int fd, size_t size)
      : file(file), fd(fd), size(size) {}
};
extern FileHandle INVALID_FILE_HANDLE;

//===--------------------------------------------------------------------===//
// Transformers
//===--------------------------------------------------------------------===//

std::string TypeIdToString(type::TypeId type);
type::TypeId StringToTypeId(const std::string &str);
std::string TypeIdArrayToString(const std::vector<type::TypeId> &types);
std::vector<type::TypeId> StringToTypeArray(const std::string &types);

type::TypeId PostgresValueTypeToPelotonValueType(PostgresValueType type);
ConstraintType PostgresConstraintTypeToPelotonConstraintType(
    PostgresConstraintType type);

std::string SqlStateErrorCodeToString(SqlStateErrorCode code);

namespace expression {
class AbstractExpression;
}

/**
 * @brief Generic specification of a projection target:
 *        < DEST_column_id , expression >
 */

namespace planner {
struct DerivedAttribute;
}

typedef std::pair<oid_t, const planner::DerivedAttribute> Target;

typedef std::vector<Target> TargetList;

/**
 * @brief Generic specification of a direct map:
 *        < NEW_col_id , <tuple_index (left or right tuple), OLD_col_id>    >
 */
typedef std::pair<oid_t, std::pair<oid_t, oid_t>> DirectMap;

typedef std::vector<DirectMap> DirectMapList;

//===--------------------------------------------------------------------===//
// Optimizer
//===--------------------------------------------------------------------===//

enum class PropertyType {
  INVALID = INVALID_TYPE_ID,
  COLUMNS,
  DISTINCT,
  SORT,
  LIMIT,
};
std::string PropertyTypeToString(PropertyType type);
PropertyType StringToPropertyType(const std::string &str);
std::ostream &operator<<(std::ostream &os, const PropertyType &type);

enum class RuleType : uint32_t {
  // Transformation rules (logical -> logical)
  INNER_JOIN_COMMUTE = 0,
  INNER_JOIN_ASSOCIATE,

  // Don't move this one
  LogicalPhysicalDelimiter,

  // Implementation rules (logical -> physical)
  GET_TO_DUMMY_SCAN,
  GET_TO_SEQ_SCAN,
  GET_TO_INDEX_SCAN,
  QUERY_DERIVED_GET_TO_PHYSICAL,
  EXTERNAL_FILE_GET_TO_PHYSICAL,
  DELETE_TO_PHYSICAL,
  UPDATE_TO_PHYSICAL,
  INSERT_TO_PHYSICAL,
  INSERT_SELECT_TO_PHYSICAL,
  AGGREGATE_TO_HASH_AGGREGATE,
  AGGREGATE_TO_PLAIN_AGGREGATE,
  INNER_JOIN_TO_NL_JOIN,
  INNER_JOIN_TO_HASH_JOIN,
  IMPLEMENT_DISTINCT,
  IMPLEMENT_LIMIT,
  EXPORT_EXTERNAL_FILE_TO_PHYSICAL,

  // Don't move this one
  RewriteDelimiter,

  // Rewrite rules (logical -> logical)
  PUSH_FILTER_THROUGH_JOIN,
  COMBINE_CONSECUTIVE_FILTER,
  EMBED_FILTER_INTO_GET,
  MARK_JOIN_GET_TO_INNER_JOIN,
  MARK_JOIN_INNER_JOIN_TO_INNER_JOIN,
  MARK_JOIN_FILTER_TO_INNER_JOIN,
  PULL_FILTER_THROUGH_MARK_JOIN,
  PULL_FILTER_THROUGH_AGGREGATION,

  // Place holder to generate number of rules compile time
  NUM_RULES

};

namespace expression {
class AbstractExpression;
class ExprHasher;
class ExprEqualCmp;
}  // namespace expression

// Augment abstract expression with a table alias set
struct AnnotatedExpression {
  AnnotatedExpression(std::shared_ptr<expression::AbstractExpression> i_expr,
                      std::unordered_set<std::string> &i_set)
      : expr(i_expr), table_alias_set(i_set) {}
  AnnotatedExpression(const AnnotatedExpression &mt_expr)
      : expr(mt_expr.expr), table_alias_set(mt_expr.table_alias_set) {}
  std::shared_ptr<expression::AbstractExpression> expr;
  std::unordered_set<std::string> table_alias_set;
};

typedef std::vector<AnnotatedExpression> MultiTablePredicates;
typedef std::unordered_map<
    std::string, std::vector<std::shared_ptr<expression::AbstractExpression>>>
    SingleTablePredicatesMap;

// TODO(boweic): use raw ptr
// Mapping of Expression -> Column Offset created by operator
typedef std::unordered_map<expression::AbstractExpression *, unsigned,
                           expression::ExprHasher, expression::ExprEqualCmp>
    ExprMap;
// Used in optimizer to speed up expression comparsion
typedef std::unordered_set<expression::AbstractExpression *,
                           expression::ExprHasher, expression::ExprEqualCmp>
    ExprSet;

//===--------------------------------------------------------------------===//
// Storage
//===--------------------------------------------------------------------===//

/* column_map_type used to store the layout of a tile_group
 * <column offset> to <tile offset, tile column offset>
 */
typedef std::map<oid_t, std::pair<oid_t, oid_t>> column_map_type;

//===--------------------------------------------------------------------===//
// Wire protocol typedefs
//===--------------------------------------------------------------------===//
#define SOCKET_BUFFER_SIZE 8192

/* byte type */
typedef unsigned char uchar;

/* type for buffer of bytes */
typedef std::vector<uchar> ByteBuf;

//===--------------------------------------------------------------------===//
// Packet Manager: ProcessResult
//===--------------------------------------------------------------------===//
enum class ProcessResult {
  COMPLETE,
  TERMINATE,
  PROCESSING,
  MORE_DATA_REQUIRED,
  NEED_SSL_HANDSHAKE,
};

enum class NetworkProtocolType {
  POSTGRES_JDBC,
  POSTGRES_PSQL,
};

enum class SSLLevel {
  SSL_DISABLE = 0,
  SSL_PREFER = 1,
  SSL_VERIIFY = 2,
};

// Eigen/Matrix types used in brain
// TODO(saatvik): Generalize Eigen utilities across all types
typedef std::vector<std::vector<float>> matrix_t;
typedef Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>
    matrix_eig;

}  // namespace peloton


text:
var worker = function(operation, num) {
	if(num <= 0)
		return;
	operation();
	worker(operation, --num);
};

module.exports = worker;


text:
.menu-button {
  opacity: 0;
  transition: all 500ms ease-in-out;
  margin: 0px 10px;
  position: relative;
  font-family: 'Segoe UI', Arial, Helvetica, sans-serif;
  font-size: large;
  cursor: pointer;
  user-select: none;
}

.button-show {
  opacity: .5;
  top: 0px;
}

.button-highlight {
  opacity: 1;
  top: 0px;
}

.button-show:hover {
  opacity: 1;
  transition: all 50ms ease-in-out;
}


text:
"""Keras string lookup preprocessing layer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.framework import dtypes
from tensorflow.python.keras.engine import base_preprocessing_layer
from tensorflow.python.keras.layers.preprocessing import index_lookup
from tensorflow.python.keras.layers.preprocessing import table_utils
from tensorflow.python.util.tf_export import keras_export

@keras_export("keras.layers.experimental.preprocessing.IntegerLookup", v1=[])
class IntegerLookup(index_lookup.IndexLookup):
  """Maps integers from a vocabulary to integer indices.

  This layer translates a set of arbitrary integers into an integer output via a
  table-based lookup, with optional out-of-vocabulary handling.

  If desired, the user can call this layer's `adapt()` method on a data set,
  which will analyze the data set, determine the frequency of individual string
  values, and create a vocabulary from them. This vocabulary can have
  unlimited size or be capped, depending on the configuration options for this
  layer; if there are more unique values in the input than the maximum
  vocabulary size, the most frequent terms will be used to create the
  vocabulary.

  Attributes:
    max_values: The maximum size of the vocabulary for this layer. If None,
      there is no cap on the size of the vocabulary. Note that this vocabulary
      includes the OOV and mask values, so the effective number of values is
      (max_values - num_oov_values - (1 if mask_token else 0))
    num_oov_indices: The number of out-of-vocabulary values to use; defaults to
      1. If this value is more than 1, OOV inputs are modulated to determine
      their OOV value; if this value is 0, passing an OOV input will result in
      a '-1' being returned for that value in the output tensor. (Note that,
      because the value is -1 and not 0, this will allow you to effectively drop
      OOV values from categorical encodings.)
    mask_value: A value that represents masked inputs, and which is mapped to
      index 0. Defaults to 0. If set to None, no mask term will be added and the
      OOV values, if any, will be indexed from (0...num_oov_values) instead of
      (1...num_oov_values+1).
    oov_value: The value representing an out-of-vocabulary value. Defaults to
      -1.
    vocabulary: An optional list of values, or a path to a text file containing
      a vocabulary to load into this layer. The file should contain one value
      per line. If the list or file contains the same token multiple times, an
      error will be thrown.
    invert: If true, this layer will map indices to vocabulary items instead
      of mapping vocabulary items to indices.

  Examples:

  Creating a lookup layer with a known vocabulary

  This example creates a lookup layer with a pre-existing vocabulary.

  >>> vocab = [12, 36, 1138, 42]
  >>> data = tf.constant([[12, 1138, 42], [42, 1000, 36]])
  >>> layer = IntegerLookup(vocabulary=vocab)
  >>> layer(data)
  <tf.Tensor: shape=(2, 3), dtype=int64, numpy=
  array([[2, 4, 5],
         [5, 1, 3]])>

  Creating a lookup layer with an adapted vocabulary

  This example creates a lookup layer and generates the vocabulary by analyzing
  the dataset.

  >>> data = tf.constant([[12, 1138, 42], [42, 1000, 36]])
  >>> layer = IntegerLookup()
  >>> layer.adapt(data)
  >>> layer.get_vocabulary()
  [0, -1, 42, 1138, 1000, 36, 12]

  Note how the mask value 0 and the OOV value -1 have been added to the
  vocabulary. The remaining values are sorted by frequency (1138, which has
  2 occurrences, is first) then by inverse sort order.

  >>> data = tf.constant([[12, 1138, 42], [42, 1000, 36]])
  >>> layer = IntegerLookup()
  >>> layer.adapt(data)
  >>> layer(data)
  <tf.Tensor: shape=(2, 3), dtype=int64, numpy=
  array([[6, 3, 2],
         [2, 4, 5]])>

  Lookups with multiple OOV tokens.

  This example demonstrates how to use a lookup layer with multiple OOV tokens.
  When a layer is created with more than one OOV token, any OOV values are
  hashed into the number of OOV buckets, distributing OOV values in a
  deterministic fashion across the set.

  >>> vocab = [12, 36, 1138, 42]
  >>> data = tf.constant([[12, 1138, 42], [37, 1000, 36]])
  >>> layer = IntegerLookup(vocabulary=vocab, num_oov_indices=2)
  >>> layer(data)
  <tf.Tensor: shape=(2, 3), dtype=int64, numpy=
  array([[3, 5, 6],
         [2, 1, 4]])>

  Note that the output for OOV value 37 is 2, while the output for OOV value
  1000 is 1. The in-vocab terms have their output index increased by 1 from
  earlier examples (12 maps to 3, etc) in order to make space for the extra OOV
  value.

  Inverse lookup

  This example demonstrates how to map indices to values using this layer. (You
  can also use adapt() with inverse=True, but for simplicity we'll pass the
  vocab in this example.)

  >>> vocab = [12, 36, 1138, 42]
  >>> data = tf.constant([[1, 3, 4], [4, 5, 2]])
  >>> layer = IntegerLookup(vocabulary=vocab, invert=True)
  >>> layer(data)
  <tf.Tensor: shape=(2, 3), dtype=int64, numpy=
  array([[  12, 1138,   42],
         [  42,   -1,   36]])>

  Note that the integer 5, which is out of the vocabulary space, returns an OOV
  token.

  Forward and inverse lookup pairs

  This example demonstrates how to use the vocabulary of a standard lookup
  layer to create an inverse lookup layer.

  >>> vocab = [12, 36, 1138, 42]
  >>> data = tf.constant([[12, 1138, 42], [42, 1000, 36]])
  >>> layer = IntegerLookup(vocabulary=vocab)
  >>> i_layer = IntegerLookup(vocabulary=layer.get_vocabulary(), invert=True)
  >>> int_data = layer(data)
  >>> i_layer(int_data)
  <tf.Tensor: shape=(2, 3), dtype=int64, numpy=
  array([[  12, 1138,   42],
         [  42,   -1,   36]])>

  In this example, the input value 1000 resulted in an output of -1, since
  1000 was not in the vocabulary - it got represented as an OOV, and all OOV
  values are returned as -1 in the inverse layer. Also, note that for the
  inverse to work, you must have already set the forward layer vocabulary
  either directly or via fit() before calling get_vocabulary().
  """

  def __init__(self,
               max_values=None,
               num_oov_indices=1,
               mask_value=0,
               oov_value=-1,
               vocabulary=None,
               invert=False,
               **kwargs):
    allowed_dtypes = [dtypes.int64]

    if "dtype" in kwargs and kwargs["dtype"] not in allowed_dtypes:
      raise ValueError("IntegerLookup may only have a dtype in %s." %
                       allowed_dtypes)

    if "dtype" not in kwargs:
      kwargs["dtype"] = dtypes.int64

    # If max_values is set, the value must be greater than 1 - otherwise we
    # are creating a 0-element vocab, which doesn't make sense.
    if max_values is not None and max_values <= 1:
      raise ValueError("If set, max_values must be greater than 1.")

    if num_oov_indices < 0:
      raise ValueError("num_oov_indices must be greater than 0. You passed %s" %
                       num_oov_indices)

    if vocabulary is not None:
      if isinstance(vocabulary, str):
        vocabulary = table_utils.get_vocabulary_from_file(vocabulary)
        vocabulary = [int(v) for v in vocabulary]

    super(IntegerLookup, self).__init__(
        max_tokens=max_values,
        num_oov_indices=num_oov_indices,
        mask_token=mask_value,
        oov_token=oov_value,
        vocabulary=vocabulary,
        invert=invert,
        **kwargs)
    base_preprocessing_layer._kpl_gauge.get_cell("V2").set("IntegerLookup")

  def get_config(self):
    base_config = super(IntegerLookup, self).get_config()
    # Because the super config has a bunch of args we're also passing,
    # we need to rename and remove them from the config dict.
    base_config["max_values"] = base_config["max_tokens"]
    del base_config["max_tokens"]

    base_config["mask_value"] = base_config["mask_token"]
    del base_config["mask_token"]

    base_config["oov_value"] = base_config["oov_token"]
    del base_config["oov_token"]
    return base_config

  def set_vocabulary(self, vocab):
    if isinstance(vocab, str):
      vocab = table_utils.get_vocabulary_from_file(vocab)
      vocab = [int(v) for v in vocab]
    super().set_vocabulary(vocab)


text:
How to create an Iris tutorial

        This will explain to you how to create a tutorial for Iris. It's easy and fun!

Create your HTML page

An Iris tutorial can live anywhere you want, it's just an HTML page which is well formatted in the following way:

                <div id = 'tutorial'>
                    <h1>This is the name of the tutorial</h1>
                    <div>
                        This is the summary of the tutorial and may contain any content/HTML you would like.
                    </div>
                    <!-- the next div tag contains all subsequent pages -->
                    <div>
                        <div>
                            <h2>This is the name of the first step</h2>
                            <div>
                                This is the text of the step and may contain any content/HTML you would like. It does not have to be in a div tag.
                                Anything after the h2 is considered content.
                            </div>
                        </div>
                        <div>
                            <h2>This is the name of the second step</h2>
                            <div>
                                This is the text of the step and may contain any content/HTML you would like.
                            </div>
                        </div>
                        <div>
                            <h2>This is the name of the third step</h2>
                            <div>
                                This is the text of the step and may contain any content/HTML you would like.
                            </div>
                        </div>
                        <!-- and on and on as many times as necessary -->
                    </div>
                </div>

BE CAREFUL - please make all links, images, and other references FULLY QUALIFIED URLS. Relative links will not work when embedded into Iris.

Upload your content somewhere.

Your page may be placed anywhere you want. Note the URL.

Register in Iris

Contact the appropriate person to register your tutorial into Iris. Currently, that'd be Jim Thomason (thomason@cshl.edu)

Tell them the name to use when selecting the tutorial in Iris, as well as the URL to pick up the content.

Sit back and relax.

You're done. Just kick back and wait for the changes to be deployed, with your new tutorial in place.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.Research.Dryad.Channel
{
    internal class BufferQueue
    {
        private Queue<Buffer> queue;
        private TaskCompletionSource<Buffer> waiter;

        public BufferQueue()
        {
            queue = new Queue<Buffer>();
            waiter = null;
        }

        public int Enqueue(Buffer b)
        {
            lock (this)
            {
                if (waiter == null)
                {
                    queue.Enqueue(b);
                }
                else
                {
                    waiter.SetResult(b);
                    waiter = null;
                }
                return queue.Count;
            }
        }

        public Task<Buffer> Dequeue()
        {
            lock (this)
            {
                if (queue.Count == 0)
                {
                    waiter = new TaskCompletionSource<Buffer>();
                    // add a continuation to make sure that SetResult doesn't synchronously
                    // execute the caller awaiting the queue
                    return waiter.Task.ContinueWith((t) => t.Result);
                }
                else
                {
                    return Task.FromResult(queue.Dequeue());
                }
            }
        }

        public List<Buffer> Shutdown()
        {
            lock (this)
            {
                if (waiter != null)
                {
                    throw new ApplicationException();
                }

                var list = new List<Buffer>();
                while (queue.Count > 0)
                {
                    list.Add(queue.Dequeue());
                }
                queue = null;
                return list;
            }
        }
    }
}


text:
localForage is a handy library that improves the offline experience of your web
app by using asynchronous storage (via IndexedDB or WebSQL where available) but
with a simple, `localStorage`-like API.

localForage includes a localStorage-backed fallback store for browsers with no
IndexedDB or WebSQL support. This means that asynchronous storage is available
in Chrome, Firefox, and Safari (including Safari Mobile).

## Browser Support

Basically all modern browsers (IE 8 and above). _Asynchronous storage_ is
available in all browsers **in bold**, with their version that supports
localStorage in parentheses.

* **Android Browser 2.1**
* **Blackberry 7**
* **Chrome 23** (Chrome 4.0 with localStorage)
* **Chrome for Android 32**
* **Firefox 10** (Firefox 3.5 with localStorage)
* **Firefox for Android 25**
* **IE 10** (IE 8 with localStorage)
* **IE Mobile 10**
* **Opera 15** (Opera 10.5 with localStorage)
* **Opera Mobile 11**
* **Phonegap/Apache Cordova 1.2.0**
* **Safari 3.1**

Note that, because of WebSQL support, apps packaged with Phonegap will also
use asynchronous storage. Pretty slick!

## Support

Lost? Need help? This README has some simple guides and the code has decent
documentation, but I'm working on a real API guide. In the meantime, if you're
stuck using the library, running the tests, or want to contribute, you can
visit [irc.mozilla.org](https://wiki.mozilla.org/IRC) and head to the `#apps`
channel to ask questions about localForage.

# How to use localForage

## Callbacks

Because localForage uses async storage, it has an async API. It's otherwise
exactly the same as the
[localStorage API](https://hacks.mozilla.org/2009/06/localstorage/).

```javascript
// In localStorage, we would do:
localStorage.setItem('key', JSON.stringify('value'));
doSomethingElse();

// With localForage, we use callbacks:
localforage.setItem('key', 'value', doSomethingElse);
```

Similarly, please don't expect a return value from calls to
`localforage.getItem()`. Instead, use a callback:

```javascript
// Synchronous; slower!
var value = JSON.parse(localStorage.getItem('key'));
alert(value);

// Async, fast, and non-blocking!
localforage.getItem('key', alert);
```

You can store any type in localForage; you aren't limited to strings like in
localStorage. Even if localStorage is your storage backend, localForage
automatically does `JSON.parse()` and `JSON.stringify()` when getting/setting
values.

## Promises

Promises are pretty cool! If you'd rather use promises than callbacks,
localForage supports that too:

```javascript
function doSomethingElse(value) {
    console.log(value);
}

// With localForage, we allow promises:
localforage.setItem('key', 'value').then(doSomethingElse);
```

localForage relies on native [ES6 Promises](http://www.promisejs.org/), but
[ships with an awesome polyfill](https://github.com/jakearchibald/ES6-Promises)
for browsers that don't yet support ES6 Promises natively.

## Driver Selection (i.e. forcing localStorage)

For development, it can be easier to use the
slower--but easier to debug--localStorage driver (mostly because localStorage
can easily be inspected from the console). You can use the `setDriver()` method
to change the driver localForage is using at any time.

```javascript
// If you aren't using JS modules, things are loaded synchronously.
localforage.setDriver('localStorageWrapper');
alert(localforage.driver);
  => 'localStorageWrapper'

// If you're using modules, things load asynchronously, so you should use
// callbacks or promises to ensure things have loaded.
localforage.setDriver('localStorageWrapper', function() {
    alert(localforage.driver);
});
  => 'localStorageWrapper'

// The promises version:
localforage.setDriver('localStorageWrapper').then(function() {
    alert(localforage.driver);
});
  => 'localStorageWrapper'
```

You can actually force any available driver with this method, but given that
the best driver will be selected automatically when the library is loaded, this
method is mostly useful in forcing localStorage.

Note that trying to load a driver unavailable on the current browser (like
trying to load WebSQL in Gecko) will fail and the previously loaded "best
choice" will continue to be used.

## Backbone.js

localForage includes a [Backbone.js](http://backbonejs.org/) storage library
that you can use to store your Backbone collections offline with only a few
lines of really simple code.

Of course, Backbone.js is entirely optional and you can use localForage
without it!

# Running Tests

localForage is designed to run in the browser, so the tests explicitly require
a browser environment instead of any JavaScript environment (i.e. node.js).
The tests are run on both a headless WebKit (using
[PhantomJS](http://phantomjs.org)) and
["headless" Gecko](http://slimerjs.org/faq.html) (using
[SlimerJS](http://slimerjs.org/)). The tests are written using
[CasperJS's tester module](http://docs.casperjs.org/en/latest/modules/tester.html).
We run tests against Gecko and WebKit to ensure that IndexedDB and WebSQL
support is functioning as-expected.

On Mac OS X, you'll need to install both PhantomJS and SlimerJS like so:

```
brew install phantomjs slimerjs
```

If you're using Windows or Linux, you can get
[get PhantomJS](http://phantomjs.org/download) and
[get SlimerJS](http://slimerjs.org/download) from their websites. I haven't
tried it myself, but it seems easy enough.

Also, you need to initialize the git submodule under `vendor/casperjs`:

```
git submodule init
git submodule update --recursive
```

Generally you'll need a version of Firefox or XULRunner installed for SlimerJS
to run your tests. The exact steps how to install and setup SlimerJS are
described on the
[project homepage](http://slimerjs.org/install.html#install-firefox).

Once everything is installed you can simply type `make test`
to make sure the code is working as expected.

TODO: Provide Windows/Linux instructions; check into XULRunner setup.

# Frequently Asked Questions

### Will you add (or accept) support for X storage?

Maybe. If it's legacy storage (< IE 8), for a dead platform (WebOS), or
_really_ obscure (Apple Newton), I'm going to say "no". If it's for a new
browser technology or a platform-specific driver like Chrome Web Apps or
Firefox OS, then "yes" is probably the answer.

### Will you add (or accept) support for storage in X framework?

**Yes**. If you have an adapter for EmberJS, Angular, whatever, please add it,
along with tests, and submit a pull request. The more frameworks this library
can support, the better.

### Will you add support for node.js?

No. This is a library focused on offline storage inside a web browser. Node.js
already has lots of storage solutions. The problem this library aims to solve
is that web browsers differ greatly in their support for a common API for
dealing with the same kind of data. Node.js doesn't have that problem; if you
want to use an API, you just add a library to your `package.json`.

# License

This program is free software; it is distributed under an
[Apache License](http://github.com/mozilla/localForage/blob/master/LICENSE).

---

Copyright (c) 2013-2014 [Mozilla](https://mozilla.org)
([Contributors](https://github.com/mozilla/localForage/graphs/contributors)).


text:
#ifndef MN_BasicMinimumParameters_H_
#define MN_BasicMinimumParameters_H_

#include "MnMatrix.h"

#include "StackAllocator.h"

//extern StackAllocator gStackAllocator;

class BasicMinimumParameters {

public:

  BasicMinimumParameters(unsigned int n) : theParameters(MnAlgebraicVector(n)), theStepSize(MnAlgebraicVector(n)), theFVal(0.), theValid(false), theHasStep(false) {}

  BasicMinimumParameters(const MnAlgebraicVector& avec, double fval) :
    theParameters(avec), theStepSize(avec.size()), theFVal(fval), theValid(true), theHasStep(false) {}

  BasicMinimumParameters(const MnAlgebraicVector& avec, const MnAlgebraicVector& dirin, double fval) : theParameters(avec), theStepSize(dirin), theFVal(fval), theValid(true), theHasStep(true) {}

  ~BasicMinimumParameters() {}

  BasicMinimumParameters(const BasicMinimumParameters& par) : theParameters(par.theParameters), theStepSize(par.theStepSize), theFVal(par.theFVal), theValid(par.theValid), theHasStep(par.theHasStep) {}

  BasicMinimumParameters& operator=(const BasicMinimumParameters& par) {
    theParameters = par.theParameters;
    theStepSize = par.theStepSize;
    theFVal = par.theFVal;
    theValid = par.theValid;
    theHasStep = par.theHasStep;
    return *this;
  }

  void* operator new(size_t nbytes) {
    return StackAllocatorHolder::get().allocate(nbytes);
  }

  void operator delete(void* p, size_t /*nbytes*/) {
    StackAllocatorHolder::get().deallocate(p);
  }

  const MnAlgebraicVector& vec() const {return theParameters;}
  const MnAlgebraicVector& dirin() const {return theStepSize;}
  double fval() const {return theFVal;}
  bool isValid() const {return theValid;}
  bool hasStepSize() const {return theHasStep;}

private:

  MnAlgebraicVector theParameters;
  MnAlgebraicVector theStepSize;
  double theFVal;
  bool theValid;
  bool theHasStep;
};

#endif //MN_BasicMinimumParameters_H_


text:
option(UNIT_TEST "Unit Test Build" OFF)
if (NOT UNIT_TEST AND CMAKE_BUILD_TYPE STREQUAL "UnitTest")
    set(UNIT_TEST ON CACHE BOOL "Always on for UnitTest" FORCE)
endif()


text:
//
//  CFIComposeWindow.m
//  Mail
//
//  Created by Robert Widmann on 7/11/12.
//  Copyright (c) 2012 CodaFi Inc. All rights reserved.
//

#import "DMComposeWindowController.h"
#import "DMComposeViewController.h"
#import "DMFontMenu.h"
#import "DMTokenizingEmailField.h"
#import "DMAppDelegate.h"

#import <AddressBook/AddressBook.h>

@interface DMComposeWindowController ()

@property (nonatomic, assign) BOOL loadingStarted;
@property (nonatomic, assign) BOOL saving;
@property (nonatomic, assign) BOOL pendingSave;
@property (nonatomic, assign) BOOL scheduledSave;
@property (nonatomic, assign) BOOL disableAutomaticSave;
@property (nonatomic, assign) BOOL shouldWarnOnClose;

@property (nonatomic, assign) int progressCount;

@property (nonatomic, strong) PSTLocalMessage *draftMessage;
@property (nonatomic, strong) PSTLocalMessage *messageToSave;

@end

@implementation DMComposeWindowController

- (instancetype)init {
	self = [super init];

	NSUInteger windowMask = (NSTitledWindowMask  | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask);
	self.window = [[NSWindow alloc]initWithContentRect:(NSRect){ .origin = { 196, 240 }, .size = { 750, 500 } } styleMask:windowMask backing:NSBackingStoreBuffered defer:NO];
	self.window.minSize = NSMakeSize(750, 500);
	self.window.animationBehavior = NSWindowAnimationBehaviorNone;
	_composeViewController = [[DMComposeViewController alloc]initWithContentRect:[self.window.contentView frame] inWindow:self.window];
	self.window.contentView = _composeViewController.view;
//	[self.window setLevel:CGWindowLevelForKey([self.delegate windowLevelForCurrentState])];
	self.shouldCascadeWindows = YES;
	self.shouldCloseDocument = YES;

	return self;
}

- (instancetype)initWithMode:(DMComposerMode)mode {
	self = [self init];

	return self;
}

- (instancetype)initWithFilename:(NSString*)filename {
	self = [self init];

	MCOMessageParser *msgparser = [[MCOMessageParser alloc]initWithData:[NSData dataWithContentsOfFile:filename]];
//	[msgparser htmlRenderingWithDelegate:nil];
	[self.subjectField setStringValue:msgparser.header.subject ? msgparser.header.subject : @""];
	return self;
}

- (NSString *)windowNibName {
	return @"CFIComposeWindow";
}

/*
 TODO: Make category on MCOIMAPMessage that loads the appropriate mustache.
 */
- (void)_loadWebview {
	NSString *htmlToLoad = nil;
	if (self.mode > 6) {
		return;
	}
	switch (self.mode) {
		case DMComposerModeDraft:
	//			htmlToLoad = [MCOIMAPMessage dmHTMLRenderingWithUUID:self.signatureUUID];
			break;
		case DMComposerModeReply:
	//			htmlToLoad = [MCOIMAPMessage dmHTMLRenderingWithUUID:self.signatureUUID];
			break;
		case DMComposerModeForward:
	//			htmlToLoad = [self.messageToReply dmForwardHTMLRenderingWithAccount:[self _replyAccount] withUUID:self.signatureUUID];
			break;
		case DMComposerModeForURL:
	//			htmlToLoad = [self.messageToReply dmHTMLRenderingWithAccount:[self _replyAccount] withUUID:self.signatureUUID];
			break;
		case DMComposerModeForScript:
	//			htmlToLoad = [MCOIMAPMessage dmHTMLRenderingWithUUID:self.signatureUUID];
			break;
		case DMComposerModeForDebug:
			break;
		default:
			break;
	}
	if (htmlToLoad == nil) {
		return;
	} else {
//		[[self.webView mainFrame]loadHTMLString:htmlToLoad baseURL:[NSURL fileURLWithPath:NSFileManager.defaultManager.resourcePath]];
	}
}

/*
 TODO: These can be replicated in JavaScript.
 */

- (IBAction)toggleBoldSelectedText:(NSControl *)sender {
	NSMenuItem *boldMenu = [(DMAppDelegate *)[NSApp delegate] boldButton];
	[boldMenu.menu cancelTracking];
	[boldMenu.menu performActionForItemAtIndex:1];
}

- (IBAction)toggleItalicSelectedText:(id)sender {
	NSMenuItem *boldMenu = [(DMAppDelegate *)[NSApp delegate] boldButton];
	[boldMenu.menu cancelTracking];
	[boldMenu.menu performActionForItemAtIndex:2];
}

- (IBAction)addLink:(id)sender {

}

- (void)textViewDidChangeSelection:(NSNotification *)notification {
//	NSMutableAttributedString *text = [self.textView textStorage];
//	NSRange letterRange;
//	if (!text.length) return;
//	NSFont *attr = [text attribute:NSFontAttributeName atIndex:(self.textView.selectedRange.location - 1) effectiveRange:&letterRange];
//	if (![attr.displayName isEqualToString:self.fontButton.titleOfSelectedItem]) {
//		[self.fontButton selectItemWithTitle:attr.displayName];
//	}
//	if (roundtol(attr.pointSize) != self.fontSizePopupButton.titleOfSelectedItem.longLongValue) {
//		[self.fontSizePopupButton selectItemWithTitle:[NSString stringWithFormat:@"%lu", roundtol(attr.pointSize)]];
//	}
}

- (NSArray*)control:(NSControl *)control textView:(NSTextView *)textView completions:(NSArray *)words forPartialWordRange:(NSRange)charRange indexOfSelectedItem:(NSInteger *)index {
	return nil;
}

//- (void)controlTextDidChange:(NSNotification *)notification {
//	id obj = notification.object;
//	if (obj != self.toField && obj != self.ccField) {
//		if (obj != self.bccField) {
//			if (obj == self.subjectField) {
//				[self setDocumentEdited:YES];
//				if (self.loadingStarted) {
//					return;
//				} else {
//					[self _scheduleSave];
//				}
//			}
//			return;
//		}
//	}
//}

//- (void)_scheduleSave {
//	if (self.loadingStarted == NO) {
//		if (self.saving) {
//			self.pendingSave = YES;
//			return;
//		}
//		if (self.scheduledSave) return;
//		if (self.disableAutomaticSave) self.pendingSave = YES; return;
//		self.loadingStarted = YES;
//		[self performSelector:@selector(_saveAfterDelay) withObject:nil afterDelay:0];
//	}
//	self.pendingSave = YES;
//	return;
//}
//
//- (void)_saveAfterDelay {
//	self.scheduledSave = NO;
//	[self _saveMessage];
//}

//- (void)_saveMessage {
//	if ([self currentAccount] != nil) {
//		[self _startProgress];
//		[self performSelector:@selector(_stopProgress) withObject:nil afterDelay:0];
//	}
//	if (!self.saving) {
//		[self.document updateChangeCount:NSChangeDone];
//		[self _cancelScheduledSave];
//		self.saving = YES;
//		self.messageToSave = [self _renderMessageForSending:YES];
//		self.messageID = self.messageToSave.header.messageID;
////		[[self currentAccount]saveMessageToLocalDrafts:self.messageToSave completion:^{
////			[self.document updateChangeCount:NSChangeAutosaved];
////		}];
//		return;
//	}
////	self.immediateSave = YES;
//	self.pendingSave = YES;
//	return;
//}
//
//- (void)_startProgress {
//	self.progressCount += 1;
//	if (self.progressCount != 1) {
//		return;
//	} else {
//		[self.saveProgressIndicator setHidden:NO];
//		[self.saveProgressIndicator startAnimation:nil];
//	}
//}
//
//- (void)_stopProgress {
//	self.progressCount -= 1;
//	if (self.progressCount != 0) {
//		return;
//	} else {
//		[self.saveProgressIndicator stopAnimation:nil];
//		[self.saveProgressIndicator setHidden:YES];
//	}
//}

//- (void)_cancelScheduledSave {
//	if (self.scheduledSave) {
//
//	}
//	self.scheduledSave = NO;
//	[NSObject cancelPreviousPerformRequestsWithTarget:self  selector:@selector(_saveAfterDelay) object:nil];
//}
//
//
@end


text:
package nl.github.martijn9612.fishy.models;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.TrueTypeFont;
import org.newdawn.slick.gui.GUIContext;
import org.newdawn.slick.gui.TextField;
import org.newdawn.slick.state.StateBasedGame;

import nl.github.martijn9612.fishy.ScoreController;
import nl.github.martijn9612.fishy.position.DrawRectangle;
import nl.github.martijn9612.fishy.position.MousePosition;
import nl.github.martijn9612.fishy.position.MouseRectangle;

public class SubmitScoreWidget {
	private static int INPUT_WIDTH = 200;
	private static int BUTTON_WIDTH = 84;
	private static int WIDGET_HEIGHT = 25;
	private static int TEXT_OFFSET_Y = 1;
	private static int TEXT_SUBMIT_X = INPUT_WIDTH + 18;
	private static int TEXT_SUBMITTED_X = INPUT_WIDTH + 7;

	private TextField scoreInput;
	private DrawRectangle submitDR;
	private MouseRectangle submitMR;
	private boolean hasSubmitted = false;
	private boolean mouseOver = false;
	private TrueTypeFont textFont;
	private int x;
	private int y;

	public SubmitScoreWidget(GUIContext container, int x, int y) {
		this.x = x;
		this.y = y;
		createTextInput(container);
		submitDR = new DrawRectangle(x + INPUT_WIDTH + 2, y, BUTTON_WIDTH, WIDGET_HEIGHT);
		submitMR = submitDR.getMouseRectangle();
	}

	private void createTextInput(GUIContext container) {
		textFont = new TrueTypeFont(new java.awt.Font("Calibri", java.awt.Font.PLAIN, 18), true);
		scoreInput = new TextField(container, textFont, x, y, INPUT_WIDTH, WIDGET_HEIGHT);
	}

	public void render(GUIContext container, Graphics g) {
		scoreInput.render(container, g);
		g.setColor(Color.gray);

		if(hasSubmitted) {
			g.fillRect(submitDR.getPositionX(), submitDR.getPositionY(), submitDR.getWidth(), submitDR.getHeight());
			textFont.drawString(x + TEXT_SUBMITTED_X, y + TEXT_OFFSET_Y, "Submitted", Color.white);
		} else {
			g.drawRect(submitDR.getPositionX(), submitDR.getPositionY(), submitDR.getWidth(), submitDR.getHeight());
			textFont.drawString(x + TEXT_SUBMIT_X, y + TEXT_OFFSET_Y, "Submit", mouseOver ? Color.black : Color.gray);
		}
	}

	public void update(GameContainer gc, StateBasedGame game, MousePosition mouse) {
		mouseOver = mouse.isInRectangle(submitMR);

		if (mouseOver && mouse.isLeftButtonDown()) {
			submitScore();
		}
    }

	public void submitScore() {
		String playerName = scoreInput.getText();
		if(!hasSubmitted && playerName.length() > 0) {
			ScoreController.getInstance().savedStoredScore(playerName);
			hasSubmitted = true;
		}
	}
}


text:
package org.jboss.resteasy.test.regression;

import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.mock.MockDispatcherFactory;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.jboss.resteasy.plugins.server.resourcefactory.POJOResourceFactory;
import org.junit.Assert;
import org.junit.Test;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

/**
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class DateFormatPathTest
{
   @Path("/")
   public static class DateResource
   {
      @Path("/widget/{date}")
      @GET
      @Produces("text/plain")
      public String get(@PathParam("date") String date)
      {
         return date;
      }
   }

   @Test
   public void testDate() throws Exception
   {
      Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();

      POJOResourceFactory noDefaults = new POJOResourceFactory(DateResource.class);
      dispatcher.getRegistry().addResourceFactory(noDefaults);

      {
         MockHttpRequest request = MockHttpRequest.get("/widget/08%2F26%2F2009");
         MockHttpResponse response = new MockHttpResponse();

         dispatcher.invoke(request, response);

         Assert.assertEquals(200, response.getStatus());

         // XXX Should this be SC_NOT_FOUND?
         // Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, response.getStatus());
         Assert.assertEquals("08/26/2009", response.getContentAsString());
      }

   }

}


text:
<?php
/**
 * Datespan with a custom start and end date.
 *
 * @package     stubbles
 * @subpackage  util_datespan
 * @version     $Id: stubDateSpanCustom.php 3230 2011-11-23 17:04:19Z mikey $
 */
stubClassLoader::load('net::stubbles::util::datespan::stubDateSpan');
/**
 * Datespan with a custom start and end date.
 *
 * @package     stubbles
 * @subpackage  util_datespan
 */
class stubDateSpanCustom extends stubSerializableObject implements stubDateSpan
{
    /**
     * start date of the span
     *
     * @var  stubDate
     */
    protected $from;
    /**
     * end date of the span
     *
     * @var  stubDate
     */
    protected $to;
    /**
     * The interval of the span (e.g. day, week, month)
     *
     * @var  string
     * @see  DateSpan::INTERVAL_*
     */
    protected $interval;

    /**
     * constructor
     *
     * @param  string|stubDate  $from      start date of the span
     * @param  string|stubDate  $to        end date of the span
     * @param  string           $interval  optional  interval of the span
     */
    public function __construct($from, $to, $interval = stubDateSpan::INTERVAL_DAY)
    {
        if (($from instanceof stubDate) === false) {
            $from = new stubDate($from);
        }

        if (($to instanceof stubDate) === false) {
            $to = new stubDate($to);
        }

        $this->from     = $from;
        $this->to       = $to;
        $this->interval = $interval;
    }

    /**
     * returns the start date
     *
     * @return  stubDate
     */
    public function getStartDate()
    {
        return $this->from;
    }

    /**
     * returns the end date
     *
     * @return  stubDate
     */
    public function getEndDate()
    {
        return $this->to;
    }

    /**
     * returns the spans between the start date and the end date
     *
     * @return  array<stubDateSpan>
     */
    public function getDateSpans()
    {
        $spans = array();
        switch ($this->interval) {
            case stubDateSpan::INTERVAL_DAY:
                stubClassLoader::load('net::stubbles::util::datespan::stubDateSpanDay');
                $day   = $this->from;
                $end   = $this->to->format('U');
                while ($day->format('U') <= $end) {
                    $spans[] = new stubDateSpanDay(clone $day);
                    $day = $day->change()->to('+1 day');
                }
                break;

            case stubDateSpan::INTERVAL_WEEK:
                stubClassLoader::load('net::stubbles::util::datespan::stubDateSpanWeek');
                $day   = $this->from;
                $end   = $this->to->format('U');
                while ($day->format('U') <= $end) {
                    $spans[] = new stubDateSpanWeek(clone $day);
                    $day = $day->change()->to('+7 days');
                }
                break;

            case stubDateSpan::INTERVAL_MONTH:
                stubClassLoader::load('net::stubbles::util::datespan::stubDateSpanMonth');
                $day = $this->from;
                $end = $this->to->format('U');
                while ($day->format('U') <= $end) {
                    $spans[] = new stubDateSpanMonth($day->format('Y'), $day->format('m'));
                    $day = $day->change()->to('+1 month');
                }
                break;

            default:
                // intentionally empty
        }

        return $spans;
    }

    /**
     * returns a string representation of the date object
     *
     * @return  string
     */
    public function asString()
    {
        return $this->from->format('d.m.Y') . ' - ' . $this->to->format('d.m.Y');
    }

    /**
     * checks whether the DateSpan is in the future
     *
     * @return  bool
     */
    public function isFuture()
    {
        $today = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
        if ($this->from->format('U') > $today) {
            return true;
        }

        return false;
    }

    /**
     * checks whether the span contains the given date
     *
     * @param   stubDate  $date
     * @return  bool
     */
    public function contains(stubDate $date)
    {
        if ($this->from->isBefore($date) === false && $this->from->equals($date) === false) {
            return false;
        }

        if ($this->to->isAfter($date) === false && $this->to->equals($date) === false) {
            return false;
        }

        return true;
    }

    /**
     * takes care of serializing the value
     *
     * @param  array   &$propertiesToSerialize  list of properties to serialize
     * @param  string  $name                    name of the property to serialize
     * @param  mixed   $value                   value to serialize
     */
    protected function __doSerialize(&$propertiesToSerialize, $name, $value)
    {
        if ('from' == $name || 'to' == $name) {
            $this->_serializedProperties[$name] = $value->format('c');
            return;
        }

        parent::__doSerialize($propertiesToSerialize, $name, $value);
    }

    /**
     * takes care of unserializing the value
     *
     * @param  string  $name             name of the property
     * @param  mixed   $serializedValue  value of the property
     */
    protected function __doUnserialize($name, $serializedValue)
    {
        if ('from' == $name || 'to' == $name) {
            $this->$name = new stubDate($serializedValue);
            return;
        }

        parent::__doUnserialize($name, $serializedValue);
    }
}
?>


text:
import Ember from "ember";
import ResetScrollMixin from '../mixins/reset-scroll';

export default Ember.Route.extend(ResetScrollMixin, {
  ajax: Ember.inject.service(),
  errorHandler: Ember.inject.service(),

  queryParams: {
    page: {
      refreshModel: true
    }
  },

  model(params) {
    var page = params.page || 1;
    var lastCount = page * 10;

    page = Number(page);
    if (page < 1) {
      this.get('toast').error(page + ' is not a valid page!');
      return {infections: [], nextPage: null, previousPage: null};
    }

    return this.get('ajax').request('/status/infections', {
      data: {
        limit: 10,
        skip: (page - 1) * 10
      }
    }).then(function (result) {
      return {
        infections: result.infections.map(function (inf) {
          return {human: inf.human, zombie: inf.zombie, time: new Date(inf.time)};
        }),

        nextPage: lastCount < result.total ? (page + 1) : null,
        previousPage: page > 1 ? (page - 1) : null
      };
    }).catch((err) => {
      this.get('errorHandler').handleError(err, 'Unable to retrieve list of infections.');
      return {infections: []};
    });
  }
});


text:
class AddAttachmentViewOfLocationToIconups < ActiveRecord::Migration
  def self.up
    change_table :iconups do |t|
      t.attachment :view_of_location
    end
  end

  def self.down
    drop_attached_file :iconups, :view_of_location
  end
end


text:
#ifndef AX_INPUT_OUTPUT_H
#define AX_INPUT_OUTPUT_H
#include <iostream>
#include "Dimension.hpp"

namespace ax
{

template<class T_vec, typename std::enable_if<
    is_vector_expression<typename T_vec::tag>::value>::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const T_vec& vec)
{
    for(std::size_t i = 0; i<dimension(vec); ++i)
        os << vec[i] << " ";
    return os;
}

template<class T_vec, typename std::enable_if<
    is_vector_expression<typename T_vec::tag>::value>::type*& = enabler>
std::istream& operator>>(std::istream& is, T_vec& vec)
{
    for(std::size_t i = 0; i<dimension(vec); ++i)
        is >> vec[i];
    return is;
}

// template<class V,
//          typename std::enable_if<
//                  is_AVXVectorExpression<typename V::value_trait>::value
//              >::type*& = enabler>
// std::ostream& operator<<(std::ostream& os, const V& vec)
// {
//     std::array<double, V::size> val = vec.get();
//     for(auto i(0); i<V::size; ++i)
//         os << val[i] << " ";
//     return os;
// }

template<class T_mat, typename std::enable_if<
    is_matrix_expression<typename T_mat::tag>::value>::type*& = enabler>
std::ostream& operator<<(std::ostream& os, const T_mat& mat)
{
    for(std::size_t i = 0; i<dimension_row(mat); ++i)
    {
        for(std::size_t j = 0; j<dimension_col(mat); ++j)
            os << mat(i,j) << " ";
        std::cout << std::endl;
    }
    return os;
}

template<class T_mat, typename std::enable_if<
    is_matrix_expression<typename T_mat::tag>::value>::type*& = enabler>
std::istream& operator>>(std::istream& is, T_mat& mat)
{
    for(std::size_t i = 0; i<dimension_row(mat); ++i)
        for(std::size_t j = 0; j<dimension_col(mat); ++j)
            is >> mat(i,j);
    return is;
}

}
#endif /*AX_INPUT_OUTPUT_H*/