text:
package gini

import (
	"io"
	"time"

	"github.com/irifrance/gini/dimacs"
	"github.com/irifrance/gini/inter"
	"github.com/irifrance/gini/internal/xo"
	"github.com/irifrance/gini/z"
)

// Gini is a concrete implementation of solver
type Gini struct {
	xo *xo.S
}

// internal use
func newGiniXo(x *xo.S) *Gini {
	g := &Gini{
		xo: x}
	return g
}

// New creates a new gini solver.
func New() *Gini {
	g := &Gini{
		xo: xo.NewS()}
	return g
}

// NewDimacs create a new gini solver from
// dimacs formatted input.
func NewDimacs(r io.Reader) (*Gini, error) {
	vis := &xo.DimacsVis{}
	if e := dimacs.ReadCnf(r, vis); e != nil {
		return nil, e
	}
	g := &Gini{
		xo: vis.S()}
	return g, nil
}

// NewV creates a new Gini solver with
// hint for capacity of variables set to capHint.
func NewV(capHint int) *Gini {
	g := &Gini{
		xo: xo.NewSV(capHint)}
	return g
}

// NewVc creates a new Gini solver with
// hint for capacity of variables set to vCapHint,
// and likewise capacity of clauses set cCapHint
func NewVc(vCapHint, cCapHint int) *Gini {
	g := &Gini{
		xo: xo.NewSVc(vCapHint, cCapHint)}

	return g
}

// Copy makes a copy of the Gini g.
//
// every bit of g is copied except
//
//  1. Statistics for reporting, which are set to 0 instead of copied
//  2. Control mechanisms for Solve's resulting from GoSolve() so the
//     copied gini can make its own calls to GoSolve() (or Solve()) without
//     affecting the original.
func (g *Gini) Copy() *Gini {
	other := &Gini{
		xo: g.xo.Copy()}
	return other
}

// SCopy implements inter.S
func (g *Gini) SCopy() inter.S {
	return g.Copy()
}

// MaxVar returns the variable whose id is max.
func (g *Gini) MaxVar() z.Var {
	return g.xo.Vars.Max
}

// Lit produces a fresh variable and returns its positive literal, conforming
// to inter.Liter.
func (g *Gini) Lit() z.Lit {
	return g.xo.Lit()
}

// Add implements inter.S.  To add a clause (x + y + z),
// one calls
//
//  g.Add(x)
//  g.Add(y)
//  g.Add(z)
//  g.Add(0)
//
// If Add is called under a test scope, then Add will panic
// if `m` is 0/LitNull.
//
func (g *Gini) Add(m z.Lit) {
	g.xo.Add(m)
}

// Assume causes the solver to make the assumption
// that m is true in the next call to Solve() or the
// next call to Test().
//
// Solve() always consumes and forgets untested assumptions.
// tested assumptions are never forgotten, and may be popped
// with Untest().
func (g *Gini) Assume(ms ...z.Lit) {
	g.xo.Assume(ms...)
}

// Solve solves the constraints.  It returns 1 if
// sat, -1 if unsat, and 0 if canceled.
func (g *Gini) Solve() int {
	res := g.xo.Solve()
	return res
}

// Try solves with a timeout.  Try returns
//  1  if sat
//  -1 if unsat
//  0  if timeout
func (g *Gini) Try(dur time.Duration) int {
	return g.xo.Try(dur)
}

// GoSolve provides a connection to a single background
// solving goroutine, a goroutine which calls Solve()
func (g *Gini) GoSolve() inter.Solve {
	return g.xo.GoSolve()
}

// Value returns the truth value of the literal m.
// The meaning of the returned value is only defined
// if the previous call to sat was satisfiable.  In
// this case, the returned value is the value of m
// in a model of of the underlying problem, where that
// model is determined by the previous call to Solve().
func (g *Gini) Value(m z.Lit) bool {
	return g.xo.Vars.Vals[m] == 1
}

// Why returns the slice of failed assumptions, a minimized
// set of assumptions which are sufficient for the last
// UNSAT result (from a call to Test() or Solve()).
//
// Why tries to store the failed assumptions in ms, if
// there is sufficient space.
func (g *Gini) Why(ms []z.Lit) []z.Lit {
	return g.xo.Why(ms)
}

// Test tests whether the current assumptions are consistent under BCP
// and opens a scope for future assumptions.
//
// Test returns the result of BCP res
//  (1: SAT, -1: UNSAT: 0, UNKNOWN)
// And any associated data in out.  The data tries to use dst
// for storage if there is space.
//
// The associated data is
//
//  - All assigned literals since last test if SAT or UNKNOWN
//  - Either the literals of a clause which is unsat under BCP or an assumption
//    which is false under BCP, whichever is found first.
//
// When g is under a test scope, many operations are not
// possible, in particular: {Add,Activate,ActivateWith,Deactivate}
// are unsupported operations under a test scope.
func (g *Gini) Test(dst []z.Lit) (res int, out []z.Lit) {
	return g.xo.Test(dst)
}

// Untest removes a scope opened and sealed by Test, backtracking
// and removing assumptions.
//
// Untest returns whether the problem is consistent under BCP after
// removing assumptions from the last Test.  It can happen that
// a given set of assumptions becomes inconsistent under BCP
// as the underlying solver learns clauses.
func (g *Gini) Untest() int {
	return g.xo.Untest()
}

// Reasons give a set of literals which imply m by virtue of
// a single clause.
//
// Reasons only works if m was returned by some call to Test resulting in
// SAT or UNKNOWN.  Otherwise, Reasons is undefined and may panic.
//
// Additionally, Reasons returns a piece of an acyclic implication graph.
// The entire graph may be reconstructed by calling Reasons for every propagated
// literal returned by Test.  The underlying graph changes on calls to Test
// and Solve.  If the underlying graph does not change, then Reasons guarantees
// that it is acyclic.
func (g *Gini) Reasons(dst []z.Lit, m z.Lit) []z.Lit {
	return g.xo.Reasons(dst, m)
}

// Create a clause from the last (non 0-terminated, non-empty) sequence of Adds and
// `m.Not()`.  Activate panics if the last sequence of Adds since Add(0) is empty,
// in other words, don't try to use an activation literal for the empty clause.
//
// Additionally, in this case subsequent behavior of `g` is undefined.  The caller
// should verify a clause is not empty using `g.Value(m)` for all literals in in
// the clause to activate.
//
// To active the clause, assume `m`.
//
// Example:
//
//  if g.Value(a) != false || g.Value(b) != false {
//    g.Add(a)
//    g.Add(b)
//    m := g.Activate()  // don't call g.Add(0).
//    g.Assume(m) // now the clause (a + b)  is active
//    if g.Solve() == 1 {
//       // do something
//    }
//    // now the clause (a+b) is not active.
//    g.Deactivate(m)
//    // now `m` can be re-used and the solver can ignore
//    // clauses with `m`.
//  }
//
// Activation of all clauses can be used in conjunction with cardinality constraints
// to easily create a MAXSAT solver.
//
// Activate is an unsupported operation under a test scope
// and will panic if called under a test scope.
func (g *Gini) Activate() (m z.Lit) {
	return g.xo.Activate()
}

// ActivateWith allows the caller to specify the activation literal.  It is
// useful when the caller needs to activate many clauses with one literal.
// However, please note that activation literals are volatile and will be
// recycled on Deactivate.  As with Activate, ActivateWith should not
// be used to activate the empty clause.  In this case, ActivateWith
// panics and subsequent behavior of g is undefined.
//
// ActivateWith is an unsupported operation under a test scope
// and will panic if called under a test scope.
func (g *Gini) ActivateWith(act z.Lit) {
	g.xo.ActivateWith(act)
}

// ActivationLit returns a new literal to be used with ActivateWith().
//
// ActivationLit is an unsupported operation under a test scope and will
// panic if called under a test scope.
func (g *Gini) ActivationLit() z.Lit {
	return g.xo.ActivationLit()
}

// Deactivate deactivates a literal as returned by Activate.  Deactivation
// frees the literal for future Activations and removes all clauses, including
// learned clauses, which contain `m.Not()`.
//
// Deactivate is an unsupported operation under a test scope
// and will panic if called under a test scope.
func (g *Gini) Deactivate(m z.Lit) {
	g.xo.Deactivate(m)
}

// Write writes the underlying CNF in dimacs format to dst,
// returning any i/o error which occured in the process.
func (g *Gini) Write(dst io.Writer) error {
	return g.xo.Cdb.Write(dst)
}


text:
from warnings import warn

from mizani.palettes import manual_pal

from ..doctools import document
from ..exceptions import PlotnineError, PlotnineWarning
from ..utils import alias
from .scale import scale_discrete, scale_continuous

# All these shapes are filled
shapes = (
    'o',  # circle
    '^',  # triangle up
    's',  # square
    'D',  # Diamond
    'v',  # triangle down
    '*',  # star
    'p',  # pentagon
    '8',  # octagon
    '<',  # triangle left
    'h',  # hexagon1
    '>',  # triangle right
    'H',  # hexagon1
    'd',  # thin diamond
)

unfilled_shapes = (
    '+',  # plus
    'x',  # x
    '.',  # point
    '1',  # tri_down
    '2',  # tri_up
    '3',  # tri_left
    '4',  # tri_right
    ',',  # pixel
    '_',  # hline
    '|',  # vline
    0,    # tickleft
    1,    # tickright
    2,    # tickup
    3,    # tickdown
    4,    # caretleft
    5,    # caretright
    6,    # caretup
    7,    # caretdown
)

# For quick lookup
FILLED_SHAPES = set(shapes)
UNFILLED_SHAPES = set(unfilled_shapes)

@document
class scale_shape(scale_discrete):
    """
    Scale for shapes

    Parameters
    ----------
    unfilled : bool
        If ``True``, then all shapes will have no interiors
        that can be a filled.
    {superclass_parameters}
    """
    _aesthetics = ['shape']

    def __init__(self, unfilled=False, **kwargs):
        if unfilled:
            self.palette = manual_pal(unfilled_shapes)
        else:
            self.palette = manual_pal(shapes)
        scale_discrete.__init__(self, **kwargs)

@document
class scale_shape_ordinal(scale_shape):
    """
    Scale for shapes

    Parameters
    ----------
    {superclass_parameters}
    """
    _aesthetics = ['shape']

    def __init__(self, **kwargs):
        warn(
            "Using shapes for an ordinal variable is not advised.",
            PlotnineWarning
        )
        super().__init__(**kwargs)

class scale_shape_continuous(scale_continuous):
    """
    Continuous scale for shapes

    This is not a valid type of scale.
    """

    def __init__(self):
        raise PlotnineError(
            "A continuous variable can not be mapped to shape"
        )

alias('scale_shape_discrete', scale_shape)

redpajama_set_name: RedPajamaGithub


text:
#include "postgres.h"
#include "miscadmin.h"
#include "access/persistentendxactrec.h"
#include "storage/smgr.h"
#include "utils/guc.h"
#include "cdb/cdbpersistentstore.h"
#include "cdb/cdbpersistentfilesysobj.h"

char *PersistentXactObjKind_Name(
	PersistentEndXactObjKind objKind)
{
	switch (objKind)
	{
	case PersistentEndXactObjKind_FileSysAction: 				return "File-System Action";
	case PersistentEndXactObjKind_AppendOnlyMirrorResyncEofs:	return "Append-Only Mirror Resync EOFs";

	default:
		return "Unknown";
	}
}

char *EndXactRecKind_Name(
	EndXactRecKind endXactRecKind)
{
	switch (endXactRecKind)
	{
	case EndXactRecKind_Commit:		return "Commit";
	case EndXactRecKind_Abort:		return "Abort";
	case EndXactRecKind_Prepare:	return "Prepare";

	default:
		return "Unknown";
	}
}

/*
 * Need to comment on what's expected behavior for PREPARE or is this never called for the case
 */
bool EndXactRecKind_NeedsAction(
	EndXactRecKind 					endXactRecKind,

	PersistentEndXactFileSysAction 	action)
{
	switch (action)
	{
	case PersistentEndXactFileSysAction_Create:
		return true;		// Go to 'Created' state on commit, or 'Aborting Create' state and perform DROP on abort.

	case PersistentEndXactFileSysAction_Drop:
		return (endXactRecKind != EndXactRecKind_Abort);
							// Peform DROP on commit.

	case PersistentEndXactFileSysAction_AbortingCreateNeeded:
		return true;		// Clean-up required on commit or abort.

	default:
		elog(ERROR, "Unexpected persistent end transaction file-system action: %d",
			 action);
		return false;	// Not reached.
	}
}

char *PersistentEndXactFileSysAction_Name(
	PersistentEndXactFileSysAction action)
{
	switch (action)
	{
	case PersistentEndXactFileSysAction_Create:					return "CREATE";
	case PersistentEndXactFileSysAction_Drop:					return "DROP";
	case PersistentEndXactFileSysAction_AbortingCreateNeeded:	return "Aborting Create Needed";

	default:
		return "Unknown";
	}
}

/*
 * Structure containing an object.
 */
typedef struct PersistentEndXactRecObjHdr
{
	int32 	len;
	int16   objKind;

	union
	{
		uint8	data[0];
		uint64  align;
	} p;
} PersistentEndXactRecObjHdr;

void PersistentEndXactRec_Print(
	char 							*procName,

	PersistentEndXactRecObjects		*objects)
{
	int i;

	elog(Persistent_DebugPrintLevel(),
		 "%s: file-system action count %d, Append-Only mirror resync EOFs count %d",
		 procName,
		 objects->typed.fileSysActionInfosCount,
		 objects->typed.appendOnlyMirrorResyncEofsCount);

	for (i = 0; i < objects->typed.fileSysActionInfosCount; i++)
	{
		PersistentEndXactFileSysActionInfo	*fileSysActionInfos =
										&objects->typed.fileSysActionInfos[i];

		elog(Persistent_DebugPrintLevel(),
			 "%s: [%d] action '%s' %s, relation storage manager '%s', persistent serial num " INT64_FORMAT ", TID %s",
			 procName,
			 i,
			 PersistentEndXactFileSysAction_Name(fileSysActionInfos->action),
			 PersistentFileSysObjName_TypeAndObjectName(&fileSysActionInfos->fsObjName),
			 PersistentFileSysRelStorageMgr_Name(fileSysActionInfos->relStorageMgr),
			 fileSysActionInfos->persistentSerialNum,
			 ItemPointerToString(&fileSysActionInfos->persistentTid));

	}

	for (i = 0; i < objects->typed.appendOnlyMirrorResyncEofsCount; i++)
	{
		PersistentEndXactAppendOnlyMirrorResyncEofs *eofs =
					&objects->typed.appendOnlyMirrorResyncEofs[i];

		elog(Persistent_DebugPrintLevel(),
			 "%s: [%d] Append-Only Mirror Resync EOFs %u/%u/%u, segment file #%d -- persistent serial num " INT64_FORMAT ", TID %s, mirror loss EOF " INT64_FORMAT ", mirror new EOF " INT64_FORMAT,
			 procName,
			 i,
			 eofs->relFileNode.spcNode,
			 eofs->relFileNode.dbNode,
			 eofs->relFileNode.relNode,
			 eofs->segmentFileNum,
			 eofs->persistentSerialNum,
			 ItemPointerToString(&eofs->persistentTid),
			 eofs->mirrorLossEof,
			 eofs->mirrorNewEof);
	}
}

static int PersistentEndXactRec_CountForObject(
	PersistentEndXactObjKind objKind,

	int32 len)
{
	int count = 0;

	switch (objKind)
	{
	case PersistentEndXactObjKind_FileSysAction:
		count = len / sizeof(PersistentEndXactFileSysActionInfo);
		break;

	case PersistentEndXactObjKind_AppendOnlyMirrorResyncEofs:
		count = len / sizeof(PersistentEndXactAppendOnlyMirrorResyncEofs);
		break;

	default:
		elog(ERROR, "Unexpected persistent transaction object kind: %d",
			 objKind);
	}

	return count;
}

static void PersistentEndXactRec_SetObjectInfo(
	PersistentEndXactRecObjects	*objects,

	PersistentEndXactObjKind 	objKind,

	void *data,

	int count,

	int32 len)
{
	PeristentEndXaxtUntyped *untyped = &objects->untyped[objKind-1];

	untyped->data = data;
	untyped->count = count;
	untyped->len = len;
}

static void PersistentEndXactRec_GetObjectInfo(
	PersistentEndXactRecObjects	*objects,

	PersistentEndXactObjKind 	objKind,

	uint8 **data,

	int *count,

	int32 *len)
{
	PeristentEndXaxtUntyped *untyped = &objects->untyped[objKind-1];

	*data = untyped->data;
	*count = untyped->count;
	*len = untyped->len;
}

void PersistentEndXactRec_Init(
	PersistentEndXactRecObjects	*objects)
{
	MemSet(objects, 0, sizeof(PersistentEndXactRecObjects));
}

static void
PersistentEndXactRec_VerifyFileSysActionInfos(
	EndXactRecKind						endXactRecKind,

	PersistentEndXactFileSysActionInfo	*fileSysActionInfos,

	int 								count)
{
	int i;

	ItemPointerData maxTid;

	if (InRecovery || Persistent_BeforePersistenceWork())
		return;

	for (i = 0; i < count; i++)
	{
		PersistentTidIsKnownResult persistentTidIsKnownResult;

		if (!PersistentEndXactFileSysAction_IsValid(fileSysActionInfos[i].action))
			elog(ERROR, "Persistent file-system action is invalid (%d) (index %d, transaction kind '%s')",
				 fileSysActionInfos[i].action,
				 i,
				 EndXactRecKind_Name(endXactRecKind));

		if (!PersistentFsObjType_IsValid(fileSysActionInfos[i].fsObjName.type))
			elog(ERROR, "Persistent file-system object type is invalid (%d) (index %d, transaction kind '%s')",
				 fileSysActionInfos[i].fsObjName.type,
				 i,
				 EndXactRecKind_Name(endXactRecKind));

		if (PersistentStore_IsZeroTid(&fileSysActionInfos[i].persistentTid))
			elog(ERROR, "TID for persistent '%s' tuple is invalid (0,0) (index %d, transaction kind '%s')",
				 PersistentFileSysObjName_TypeAndObjectName(&fileSysActionInfos[i].fsObjName),
				 i,
				 EndXactRecKind_Name(endXactRecKind));

		persistentTidIsKnownResult = PersistentFileSysObj_TidIsKnown(
													fileSysActionInfos[i].fsObjName.type,
													&fileSysActionInfos[i].persistentTid,
													&maxTid);
		switch (persistentTidIsKnownResult)
		{
		case PersistentTidIsKnownResult_BeforePersistenceWork:
			elog(ERROR, "Shouldn't being trying to verify persistent TID before persistence work");
			break;

		case PersistentTidIsKnownResult_ScanNotPerformedYet:
			// UNDONE: For now, just debug log this.
			if (Debug_persistent_print)
				elog(Persistent_DebugPrintLevel(),
				     "Can't verify persistent TID if we haven't done the persistent scan yet");
			break;

		case PersistentTidIsKnownResult_MaxTidIsZero:
			// UNDONE: For now, just debug log this.
			if (Debug_persistent_print)
				elog(Persistent_DebugPrintLevel(),
					 "TID for persistent '%s' tuple TID %s and the last known TID zero (0,0) (index %d, transaction kind '%s')",
					 PersistentFileSysObjName_TypeAndObjectName(&fileSysActionInfos[i].fsObjName),
					 ItemPointerToString(&fileSysActionInfos[i].persistentTid),
					 i,
					 EndXactRecKind_Name(endXactRecKind));
			break;

		case PersistentTidIsKnownResult_NotKnown:
			// UNDONE: For now, just debug log this.
			if (Debug_persistent_print)
				elog(Persistent_DebugPrintLevel(),
					 "TID for persistent '%s' tuple TID %s is beyond the last known TID %s (index %d, transaction kind '%s')",
					 PersistentFileSysObjName_TypeAndObjectName(&fileSysActionInfos[i].fsObjName),
					 ItemPointerToString(&fileSysActionInfos[i].persistentTid),
					 ItemPointerToString2(&maxTid),
					 i,
					 EndXactRecKind_Name(endXactRecKind));
			break;

		case PersistentTidIsKnownResult_Known:
			/* OK */
			break;

		default:
			elog(ERROR, "Unexpected persistent file-system TID is known result: %d",
				 persistentTidIsKnownResult);
		}

		if (fileSysActionInfos[i].persistentSerialNum == 0)
			elog(ERROR, "Persistent '%s' serial number is invalid (0) (index %d, transaction kind '%s')",
				 PersistentFileSysObjName_TypeAndObjectName(&fileSysActionInfos[i].fsObjName),
				 i,
				 EndXactRecKind_Name(endXactRecKind));

		if (fileSysActionInfos[i].fsObjName.type == PersistentFsObjType_RelationFile &&
			!PersistentFileSysRelStorageMgr_IsValid(fileSysActionInfos[i].relStorageMgr))
			elog(ERROR, "Persistent '%s' relation storage manager has invalid value (%d) (index %d, transaction kind '%s')",
				 PersistentFileSysObjName_TypeAndObjectName(&fileSysActionInfos[i].fsObjName),
				 fileSysActionInfos[i].relStorageMgr,
				 i,
				 EndXactRecKind_Name(endXactRecKind));
	}
}

void PersistentEndXactRec_AddFileSysActionInfos(
	PersistentEndXactRecObjects			*objects,

	EndXactRecKind						endXactRecKind,

	PersistentEndXactFileSysActionInfo	*fileSysActionInfos,

	int									count)
{
	objects->typed.fileSysActionInfos = fileSysActionInfos;
	objects->typed.fileSysActionInfosCount = count;
	objects->typed.fileSysActionInfosLen = count * sizeof(PersistentEndXactFileSysActionInfo);

	PersistentEndXactRec_VerifyFileSysActionInfos(
										endXactRecKind,
										fileSysActionInfos,
										count);
}

int32 PersistentEndXactRec_FetchObjectsFromSmgr(
	PersistentEndXactRecObjects	*objects,

	EndXactRecKind				endXactRecKind,

	int16						*objectCount)
{
	int32 serializeLen;

	int objKind;
	void *data;
	int32 count;
	int32 len;

	MemSet(objects, 0, sizeof(PersistentEndXactRecObjects));
	*objectCount = 0;
	serializeLen = 0;

	for (objKind = 1; objKind < MaxPersistentEndXactObjKind; objKind++)
	{
		data = NULL;
		count = 0;
		len = 0;
		switch (objKind)
		{
		case PersistentEndXactObjKind_FileSysAction:
			count = smgrGetPendingFileSysWork(
									endXactRecKind,
									(PersistentEndXactFileSysActionInfo**)&data,
									NULL);
			len = count * sizeof(PersistentEndXactFileSysActionInfo);

			PersistentEndXactRec_VerifyFileSysActionInfos(
										endXactRecKind,
										(PersistentEndXactFileSysActionInfo*)data,
										count);
			break;

		case PersistentEndXactObjKind_AppendOnlyMirrorResyncEofs:
			count = smgrGetAppendOnlyMirrorResyncEofs(
									endXactRecKind,
									(PersistentEndXactAppendOnlyMirrorResyncEofs**)&data);
			len = count * sizeof(PersistentEndXactAppendOnlyMirrorResyncEofs);
			break;

		default:
			elog(ERROR, "Unexpected persistent transaction object kind: %d",
				 objKind);
		}

		if (len > 0)
		{
			(*objectCount)++;

			serializeLen += offsetof(PersistentEndXactRecObjHdr, p.data) + len;

			PersistentEndXactRec_SetObjectInfo(
										objects, objKind, data, count, len);
		}
	}

	return serializeLen;
}

bool PersistentEndXactRec_WillHaveObjectsFromSmgr(
	EndXactRecKind				endXactRecKind)
{
	int objKind;

	for (objKind = 1; objKind < MaxPersistentEndXactObjKind; objKind++)
	{
		switch (objKind)
		{
		case PersistentEndXactObjKind_FileSysAction:
			if (smgrIsPendingFileSysWork(endXactRecKind))
			{
				return true;
			}
			break;

		case PersistentEndXactObjKind_AppendOnlyMirrorResyncEofs:
			if (smgrIsAppendOnlyMirrorResyncEofs(endXactRecKind))
			{
				return true;
			}
			break;

		default:
			elog(ERROR, "Unexpected persistent transaction object kind: %d",
				 objKind);
		}
	}

	return false;
}

int16 PersistentEndXactRec_ObjectCount(
	PersistentEndXactRecObjects	*objects,

	EndXactRecKind				endXactRecKind)
{
	int16 objectCount;

	int objKind;
	uint8 *data;
	int count;
	int32 len;

	objectCount = 0;

	for (objKind = 1; objKind < MaxPersistentEndXactObjKind; objKind++)
	{
		PersistentEndXactRec_GetObjectInfo(
									objects, objKind, &data, &count, &len);
		if (len > 0)
		{
			objectCount++;
		}
	}

	return objectCount;
}

int32 PersistentEndXactRec_SerializeLen(
	PersistentEndXactRecObjects	*objects,

	EndXactRecKind				endXactRecKind)
{
	int32 fillLen;

	int objKind;
	uint8 *data;
	int count;
	int32 len;

	fillLen = 0;

	for (objKind = 1; objKind < MaxPersistentEndXactObjKind; objKind++)
	{
		PersistentEndXactRec_GetObjectInfo(
									objects, objKind, &data, &count, &len);
		if (len > 0)
		{
			fillLen += offsetof(PersistentEndXactRecObjHdr, p.data) + len;
		}
	}

	return fillLen;
}

static void PersistentEndXactRec_AddSection(
	uint8 						*buffer,

	int32						bufferLen,

	int32						*currentLen,

	PersistentEndXactObjKind	objKind,

	uint8						*data,

	int32						len)
{
	uint8 *next;
	PersistentEndXactRecObjHdr *header;
	const int headerLen = offsetof(PersistentEndXactRecObjHdr, p.data);

	Assert(len > 0);
	Assert(*currentLen + headerLen + len <= bufferLen);

	next = &buffer[*currentLen];

	header = (PersistentEndXactRecObjHdr*)next;
	MemSet(header, 0, headerLen);
	header->len = len;
	header->objKind = objKind;

	memcpy(header->p.data, data, len);

	(*currentLen) += headerLen + len;
}

void PersistentEndXactRec_Serialize(
	PersistentEndXactRecObjects	*objects,

	EndXactRecKind				endXactRecKind,

	int16						*numOfObjects,

	uint8 						*buffer,

	int32						bufferLen)

{
	int objKind;
	int32 currentLen;
	uint8 *data;
	int count;
	int32 len;

	*numOfObjects = 0;

	currentLen = 0;
	for (objKind = 1; objKind < MaxPersistentEndXactObjKind; objKind++)
	{
		PersistentEndXactRec_GetObjectInfo(
									objects, objKind, &data, &count, &len);
		if (len > 0)
		{
			PersistentEndXactRec_AddSection(
										buffer,
										bufferLen,
										&currentLen,
										objKind,
										data,
										len);
			(*numOfObjects)++;
		}
	}

	if (currentLen != bufferLen)
	{
		elog(ERROR, "Persistent end transaction serialize length mismatch (actual %d, supplied %d)",
		     currentLen, bufferLen);
	}
}

int32 PersistentEndXactRec_DeserializeLen(
	uint8						*buffer,

	int16						numOfObjects)
{
	int deserializeLen;

	int n;
	PersistentEndXactRecObjHdr *header;
	int32 len;

	deserializeLen = 0;
	header = (PersistentEndXactRecObjHdr*)buffer;
	for (n = 0; n < numOfObjects; n++)
	{
		len = header->len;

		deserializeLen += offsetof(PersistentEndXactRecObjHdr, p.data) + len;
		header = (PersistentEndXactRecObjHdr*)&buffer[deserializeLen];
	}

	return deserializeLen;
}

void PersistentEndXactRec_Deserialize(
	uint8						*buffer,

	int16						numOfObjects,

	PersistentEndXactRecObjects	*objects,

	uint8						**nextData)
{
	int32 currentLen;
	int n;
	int objKind;
	PersistentEndXactRecObjHdr *header;
	int32 len;
	uint8 *data;
	int count;

	MemSet(objects, 0, sizeof(PersistentEndXactRecObjects));

	currentLen = 0;
	header = (PersistentEndXactRecObjHdr*)buffer;
	for (n = 0; n < numOfObjects; n++)
	{

		len = header->len;
		objKind = header->objKind;
		data = header->p.data;

		count = PersistentEndXactRec_CountForObject(objKind, len);

		PersistentEndXactRec_SetObjectInfo(
									objects, objKind, data, count, len);

		currentLen += offsetof(PersistentEndXactRecObjHdr, p.data) + len;
		header = (PersistentEndXactRecObjHdr*)&buffer[currentLen];
	}

	*nextData = (uint8*)header;
}


text:
<?php

/* @var $this yii\web\View */
use yii\helpers\Html;
?>

Category

            <?= \app\components\MenuWidget::widget(['tpl' => 'menu'])?>

Brands

 (50)Acne

 (56)Grüne Erde

 (27)Albiro

 (32)Ronhill

 (5)Oddmolly

 (9)Boudestijn

 (4)Rösch creative culture

Price Range

                <input type="text" class="span2" value="" data-slider-min="0" data-slider-max="600" data-slider-step="5" data-slider-value="[250,450]" id="sl2" >

                $ 0 $ 600

            <?= Html::img("@web/images/products/{$product->img}", ['alt' => $product->name])?>

ZOOM

            <?php if($product->new): ?>
                <?= Html::img("@web/images/home/new.png", ['alt' => 'Новинка', 'class' => 'newarrival'])?>
            <?php endif?>
            <?php if($product->sale): ?>
                <?= Html::img("@web/images/home/sale.png", ['alt' => 'Распродажа', 'class' => 'newarrival'])?>
            <?php endif?>

<?= $product->name?>

Web ID: 1089772

									US $<?= $product->price?>
									Quantity:
									<input type="text" value="1" id="qty"/>
									<a href="#" data-id="<?= $product->id ?>" class="btn btn-fefault cart add-to-cart">

                                        Add to cart

Availability: In Stock

Condition: New

Brand: <a href="<?= \yii\helpers\Url::to(['category/view', 'id' => $product->category->id]) ?>"><?= $product->category->name?>

<?= $product->content ?>

recommended items

<?php $count = count($hits); $i = 0;
foreach ($hits as $hit) : ?>
<?php if ($i % 3 == 0) : ?>
            <div class="item<?= $i === 0 ? ' active' : ''?>">
<?php endif; ?>

                                <?= Html::img("@web/images/products/".$hit->img, ['alt' => $hit->name]) ?>

$<?= $hit->price ?>

<a href="<?= \yii\helpers\Url::to(['product/view', 'id' => $hit->id]) ?>"><?= $hit->name ?>

                                <button type="button" class="btn btn-default add-to-cart">Add to cart</button>

<?php $i++; if ($i % 3 == 0 || $i == $count) : ?>

<?php endif; ?>
<?php endforeach; ?>


text:
namespace PhysBAM
{

#ifdef ENABLE_PTHREADS
class THREAD_CONDITION
{
private:
	pthread_cond_t cond;
public:

	THREAD_CONDITION()
	{
		pthread_cond_init (&cond, 0);
	}

	~THREAD_CONDITION()
	{
		pthread_cond_destroy (&cond);
	}

	void Wait (THREAD_LOCK& lock)
	{
		pthread_cond_wait (&cond, &lock.mutex);
	}

	void Signal()
	{
		pthread_cond_signal (&cond);
	}

	void Broadcast()
	{
		pthread_cond_broadcast (&cond);
	}
};
#else
class THREAD_CONDITION
{
public:
	THREAD_CONDITION()
	{}

	~THREAD_CONDITION()
	{}

	void Wait (THREAD_LOCK& lock)
	{}

	void Signal()
	{}

	void Broadcast()
	{}
};
#endif //ENABLE_PTHREADS
}
#endif


text:
<!DOCTYPE html>

		<title th:inline="text">Life Editor</title>

		<link th:href="@{ ${csapApp.versionedUrl('/js/editor/dialog-cluster.css')} }" rel="stylesheet"  type="text/css" media="screen" />
		<link th:href="@{ ${csapApp.versionedUrl('/js/editor/editor-dialog-service.css')} }" rel="stylesheet"  type="text/css" media="screen" />
		<link th:href="@{ ${csapApp.versionedUrl('/js/editor/dialog-settings.css')} }" rel="stylesheet"  type="text/css" media="screen" />

		<link th:href="@{ ${csapApp.versionedUrl('/js/editor/life-edit.css')} }" rel="stylesheet"  type="text/css" media="screen" />
		<link th:href="@{ ${csapApp.versionedUrl('/js/editor/editor.css')} }" rel="stylesheet"  type="text/css" media="screen" />

		<link th:href="@{/js/csapLibs/qtip/jquery.qtip.min.css}" rel="stylesheet"
			  type="text/css" media="screen" />

		<link th:href="@{/js/csapLibs/lineNums/jquery-linedtextarea.css}" rel="stylesheet"
			  type="text/css" media="screen" />

		Package Editor: <select
			class="releasePackage"
			style="width: 14em">
			<option
				th:each="name : ${packageNames}"
				th:selected="${name == selectedRelease }"
				th:value="${name}"
				th:text="${name}">package names updated here</option>
		</select>

			Application Environment:
				<select
					id="lifeEdit"
					class="lifeSelection"
					style="width: 14em">
					<option
						th:each="lifeName : ${ packageLifes }"
						th:selected="${lifeName == lifeToEdit }"
						th:value="${lifeName}"
						th:text="${lifeName}">Will be updated with dev/stage/lt/...</option>
				</select>

				<button id="editSettingsButton" class="pushButton"
						title="Click to modify service configuraion" >
					Edit Settings
				</button>

				Filter:
					<input id="clusterFilter" style="display: inline-block; margin-right: 0"
							title="Filter by lifecycle, servicename, version, etc. Hit enter key to apply filter" value=""/>

						Cluster

								Add

						Hosts: Click name to launch Host Dashboard

						Services: Click name to edit

								Add Service

					No clusters found.

					UnAssigned
					Selected Lifecycle

									[[ ${ clusterServiceName } ]]

									[[ ${ cluster } ]]

 [[ ${clusterDescriptionMap.get(cluster) } ]]

									[[ ${ clusterHostName } ]]

									[[ ${ clusterServiceName } ]]


text: import serial


text:
var extend = require('extend');
var _ = require('underscore');

_.str = require('underscore.string');

var prepare = function (server, ctx, tmpl, model, callback) {
    var bundle = require('./bundle.js')(server.app);
    var mdl = {
        baseHref: ctx.uri.getBaseHref(),
        language: ctx.language || 'en',
        meta: {
            title: '',
            keywords: [],
            description: ''
        },
        params: [],
        robots: ''
    };

    extend(true, mdl.meta, ctx.meta);
    extend(true, mdl, model);

    mdl.params = mdl.params || [];

    mdl.params = _.union([{
        name: 'generator',
        content: 'jsnbt content management'
    }, {
        name: 'layouts',
        content: ctx.layouts
    }, {
        name: 'page',
        content: (ctx.node || {}).id
    }, {
        name: 'pointer',
        content: (ctx.pointer || {}).id
    }], {
        name: 'hierarchy',
        content: ctx.hierarchy
    }, ctx.params);

    var isAdmin = ctx.uri.first === 'admin';

    if (isAdmin) {
        mdl.baseHref += 'admin/';
    }

    var robotNames = [];
    for (var robotName in ctx.robots) {
        if (ctx.robots[robotName] === true)
            robotNames.push(robotName);
    }

    if (robotNames.length > 0)
        mdl.robots = robotNames.join(',');

    var installedTemplate = _.find(server.app.config.templates, function (x) { return x.id === ctx.template; });

    var styleBundle = bundle.getStyleBundle(installedTemplate.styles);
    mdl.styles = styleBundle.items;

    var scriptBundle = bundle.getScriptBundle(installedTemplate.scripts);
    mdl.scripts = scriptBundle.items;

    if (!mdl.meta.title || mdl.meta.title === '') {
        mdl.meta.title = server.app.title;
    }
    else {
        mdl.meta.title = mdl.meta.title;
    }

    var preparsingContext = {
        model: mdl,
        tmpl: tmpl
    };

    callback(null, preparsingContext);
};

var preparse = function (server, ctx, preparsingContext, callback) {
    if (!ctx.halt && ctx.uri.first !== 'admin') {
        var preparser = require('./parsing/preparser.js')(server);
        preparser.process(ctx, preparsingContext, function (preparsingContextResult) {
            callback(null, preparsingContextResult);
        });
    }
    else {
        callback(null, preparsingContext);
    }
};

var parse = function (server, ctx, preparsingContext, callback) {
    var html = '';
    try {
        html = _.template(preparsingContext.tmpl)(preparsingContext.model);
        callback(null, html);
    }
    catch (err) {
        callback(err);
    }
};

var postParse = function (server, ctx, html, callback) {
    var postparsingContext = {
        html: html
    };

    if ((ctx.uri.query.dbg || '').toLowerCase() === 'true' && server.app.dbg) {
        var injectedDbgHtml = '\t\n' +
            '\t';

        postparsingContext.html = postparsingContext.html.replace('', injectedDbgHtml + '\n');
    }

    if (!ctx.halt && ctx.uri.first !== 'admin') {
        var postparser = require('./parsing/postparser.js')(server);
        postparser.process(ctx, postparsingContext, function (postParsedContext) {
            callback(null, postParsedContext.html);
        });
    }
    else {
        callback(null, postparsingContext.html);
    }
};

var Parser = function (server) {
    this.server = server;
};

Parser.prototype.parse = function (ctx, tmpl, model, callback) {
    var self = this;

    prepare(self.server, ctx, tmpl, model, function (preparsingContextErr, preparsingContext) {
        if (preparsingContextErr)
            return callback(preparsingContextErr);

        preparse(self.server, ctx, preparsingContext, function (preparsedContextErr, preparsedContext) {
            if (preparsedContextErr)
                return callback(preparsedContextErr);

            parse(self.server, ctx, preparsedContext, function (parsedHtmlErr, parsedHtml) {
                if (parsedHtmlErr)
                    return callback(parsedHtmlErr);

                postParse(self.server, ctx, parsedHtml, function (postParsedHtmlErr, postParsedHtml) {
                    if (postParsedHtmlErr)
                        return callback(postParsedHtmlErr);
                    callback(null, postParsedHtml);

                });
            });
        });
    });
};

module.exports = function (server) {
    return new Parser(server);
};


text:
using System;
using System.Collections.Generic;
using System.Data;
using Smart.Core.DataAccess;

namespace Smart.Framework.IDAL
{
    /// <summary>
    /// 提供数据层使用,支持传入sql
    /// </summary>
    public interface IDataRepository
    {
        IDataBase Dbase { get; }

        IDbTransaction DbTransaction { get; }

        /// <summary>
        /// 根据条件筛选出数据集合
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="sql">sql语句</param>
        /// <param name="param">sql参数</param>
        /// <param name="buffered">是否缓存</param>
        /// <returns></returns>
        IEnumerable<T> Get<T>( string sql, dynamic param = null, bool buffered = true ) where T : class;

        /// <summary>
        /// 根据条件筛选数据集合(动态类型)
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <param name="param">参数</param>
        /// <param name="buffered">是否缓存</param>
        /// <returns></returns>
        IEnumerable<dynamic> Get( string sql, dynamic param = null, bool buffered = true );

        /// <summary>
        /// 根据表达式筛选(两表关联)
        /// </summary>
        /// <typeparam name="TFirst"></typeparam>
        /// <typeparam name="TSecond"></typeparam>
        /// <typeparam name="TReturn"></typeparam>
        /// <param name="sql"></param>
        /// <param name="map"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
        /// <param name="buffered"></param>
        /// <param name="splitOn"></param>
        /// <param name="commandTimeout"></param>
        /// <returns></returns>
        IEnumerable<TReturn> Get<TFirst, TSecond, TReturn>( string sql,
            Func<TFirst, TSecond, TReturn> map,
            dynamic param = null,
            bool buffered = true,
            string splitOn = "Id",
            int? commandTimeout = null );

        /// <summary>
        /// 根据表达式筛选(三表关联)
        /// </summary>
        /// <typeparam name="TFirst"></typeparam>
        /// <typeparam name="TSecond"></typeparam>
        /// <typeparam name="TReturn"></typeparam>
        /// <param name="sql"></param>
        /// <param name="map"></param>
        /// <param name="param"></param>
        /// <param name="transaction"></param>
        /// <param name="buffered"></param>
        /// <param name="splitOn"></param>
        /// <param name="commandTimeout"></param>
        /// <returns></returns>
        IEnumerable<TReturn> Get<TFirst, TSecond, TThird, TReturn>( string sql,
            Func<TFirst, TSecond, TThird, TReturn> map,
           dynamic param = null,
           bool buffered = true,
           string splitOn = "Id",
           int? commandTimeout = null );

        /// <summary>
        /// 分页查询
        /// TODO:需重写page方法
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="pageIndex">页索引</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="allRowsCount">全部数据总数</param>
        /// <param name="sql">sql语句</param>
        /// <param name="param">参数</param>
        /// <param name="allRowsCountSql">获取全部数据总数的SQL</param>
        /// <param name="allRowsCountParam">参数</param>
        /// <param name="buffered">是否缓存</param>
        /// <returns></returns>
        IEnumerable<T> GetPage<T>( int pageIndex,
            int pageSize,
            out long allRowsCount,
            string sql,
            dynamic param = null,
            string allRowsCountSql = null,
            dynamic allRowsCountParam = null,
            bool buffered = true ) where T : class;

        /// <summary>
        /// 执行sql操作
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        Int32 Execute( string sql, dynamic param = null );

        #region 存储过程
        /// <summary>
        /// 执行存储过程返回列表
        /// </summary>
        /// <param name="name">存储过程名称</param>
        /// <param name="param">参数</param>
        /// <param name="buffered">是否缓冲</param>
        /// <param name="commandTimeout">超时时间</param>
        /// <returns>查询结果泛型序列</returns>
        IEnumerable<T> StoredQuery<T>(string name, object param = null, bool buffered = true,
            int? commandTimeout = null);

        /// <summary>
        /// 存储过程取值
        /// </summary>
        /// <param name="name">存储过程名称</param>
        /// <param name="param">参数</param>
        /// <param name="commandTimeout">超时时间</param>
        /// <returns></returns>
        object StoredScalar(string name, object param = null, int? commandTimeout = null);

        /// <summary>
        /// 存储过程取值
        /// </summary>
        /// <typeparam name="T">返回值类型</typeparam>
        /// <param name="name">存储过程名称</param>
        /// <param name="param">参数</param>
        /// <param name="commandTimeout">超时时间</param>
        /// <returns></returns>
        T StoredScalar<T>(string name, object param = null, int? commandTimeout = null);

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="name">存储过程名称</param>
        /// <param name="param">参数</param>
        /// <param name="commandTimeout">超时时间</param>
        void StoredExecute(string name, object param = null, int? commandTimeout = null);
        #endregion
    }
}


text:
#include <config.h>
#include <linux/types.h>
#include <api_public.h>

#include <asm/u-boot.h>
#include <asm/global_data.h>

#include "api_private.h"

DECLARE_GLOBAL_DATA_PTR;

/*
 * Important notice: handling of individual fields MUST be kept in sync with
 * include/asm-ppc/u-boot.h and include/asm-ppc/global_data.h, so any changes
 * need to reflect their current state and layout of structures involved!
 */
int platform_sys_info(struct sys_info *si)
{
	si->clk_bus = gd->bus_clk;
	si->clk_cpu = gd->cpu_clk;

#if defined(CONFIG_5xx) || defined(CONFIG_8xx) || defined(CONFIG_MPC8260) || \
    defined(CONFIG_E500) || defined(CONFIG_MPC86xx)
#define bi_bar	bi_immr_base
#elif defined(CONFIG_MPC5xxx)
#define bi_bar	bi_mbar_base
#elif defined(CONFIG_MPC83xx)
#define bi_bar	bi_immrbar
#endif

#if defined(bi_bar)
	si->bar = gd->bd->bi_bar;
#undef bi_bar
#else
	si->bar = 0;
#endif

	platform_set_mr(si, gd->bd->bi_memstart, gd->bd->bi_memsize, MR_ATTR_DRAM);
	platform_set_mr(si, gd->bd->bi_flashstart, gd->bd->bi_flashsize, MR_ATTR_FLASH);
	platform_set_mr(si, gd->bd->bi_sramstart, gd->bd->bi_sramsize, MR_ATTR_SRAM);

	return 1;
}


text:
/* connection.js
 * Manages a socket.io connection for a user in a room.
 */
/*jshint es5: true */

var rooms = require('../room/rooms');
var winston = require('winston');
var user_model = require('../../models/user');
var _ = require('underscore');
var Backbone = require('backbone');
var queues = require('../song/queues');
var song_sources = require('../../song_sources');
var songs = require('../song/songs');

module.exports = Backbone.Model.extend({
  defaults: {
    authenticated: false
  },

  initialize: function() {
    this.on('change:socket', this.bindSocketHandlers, this);
    this.bindSocketHandlers();
    this.on('change:queue', this.queueChanged, this);
    this.on('change:room', this.roomChanged, this);

    // Store username locally for faster lookups in collections
    this.on('change:user', function() {
      if (this.has('user'))
        this.set({ username: this.user().username });
    }, this);
  },

  bindSocketHandlers: function() {
    var socket = this.socket();

    socket.on('auth', _.bind(this.handleAuthRequest, this));
    socket.on('room:join', _.bind(this.handleRoomJoinRequest, this));
    socket.on('room:leave', _.bind(this.handleRoomLeaveRequest, this));
    socket.on('room:dj:begin', _.bind(this.handleBeginDJ, this));
    socket.on('room:dj:end', _.bind(this.handleEndDJ, this));
    socket.on(
      'room:activity:enqueue', _.bind(this.handleActivityEnqueue, this));
    socket.on('search', _.bind(this.handleSearch, this));
    socket.on('search:source', _.bind(this.handleSourceSearch, this));
    socket.on('search:add', _.bind(this.handleSearchAdd, this));
    socket.on('queue:change:order', _.bind(this.handleQueuedSongOrder, this));
    socket.on('queue:change:escalate', _.bind(this.handleEscalation, this));
    socket.on('queue:remove', _.bind(this.handleRemoveFromQueue, this));
    socket.on('skip', _.bind(this.handleSkip, this));
    socket.on('skipvote', _.bind(this.handleSkipVote, this));
    socket.on('like', _.bind(this.handleLike, this));
    socket.on('disconnect', _.bind(this.handleDisconnect, this));
    socket.on('error', _.bind(this.handleError, this));

    // Set our id
    this.set({ id: socket.id });
  },

  watchSongAdd: function(song_add) {
    var socket = this.socket(),
        promise = song_add.promise;

    promise.then(function(song) {
      socket.emit('song:add:added', {
        job_id: song_add.job_id,
        song_id: song.id
      });
    });

    promise.catch(function(err) {
      socket.emit('song:add:failed', {
        job_id: song_add.job_id,
        error: err.message
      });
    });

    promise.progress(function(stage) {
      socket.emit('song:add:status', {
        job_id: song_add.job_id,
        status: stage
      });
    });
  },

  roomChanged: function() {
    var oldRoom = this.previous('room');
    if (oldRoom) {
      oldRoom.off(null, null, this);
      oldRoom.get('playback').off(null, null, this);
    }

    var room = this.get('room');
    if (room) {
      room.get('playback').on('play', function() {
        this.sendSongPlayback(room.get('playback'));
      }, this);
      room.get('playback').on('stop', function() {
        this.sendSongPlaybackStopped();
      }, this);
      if (room.get('playback').playing()) {
        this.sendSongPlayback(room.get('playback'));
      }
    }
  },

  /* Convienence Getters */

  socket: function() {
    return this.get('socket');
  },

  authenticated: function() {
    return this.get('authenticated');
  },

  user: function() {
    return this.get('user') || null;
  },

  getLogName: function() {
    var user = this.user();
    return user ? user.getLogName() : null;
  },

  /* Utilities */

  ensureAuth: function(fn) {
    if (this.authenticated()) {
      return true;
    } else {
      if (typeof fn === 'function')
        fn({ error: 'You are not authenticated.' });
      return false;
    }
  },

  ensureRoom: function(fn) {
    if (this.has('room')) {
      return true;
    } else {
      if (typeof fn === 'function')
        fn({ error: 'You\'re not in a room.' });
      return false;
    }
  },

  // Returns an object with sendable user data.
  toJSON: function() {
    var user = this.user() || {};

    return {
      username: user.username,
      firstName: user.firstName,
      lastName: user.lastName,
      fullName: user.fullName,
      liked: this.get('liked') || false,
      skipVoted: this.get('skipVoted') || false,
      dj: this.get('isDJ') || false,
      djOrder: this.get('djOrder'),
      admin: user.admin
    };
  },

  /* Queue */

  fetchQueue: function() {
    queues
    .getQueue(this.user().id)
    .then(_.bind(function(ret) {
      if (ret instanceof Error) {
        winston.error('Failed to fetch queue: ' + ret.message);
        this.socket().emit('error', 'Failed to get queue.');
      } else {
        this.set({ queue: ret });
      }
    }, this));
  },

  queueChanged: function() {
    var queue = this.get('queue');
    if (!queue) return;
    queue.on('reset', function() {
      this.sendQueue(queue);
    }, this);
    queue.on('songChanged add', this.sendQueuedSong, this);
    queue.on('remove', this.sendQueuedSongRemoved, this);
    queue.on('remove', function() {
      if (this.get('isDJ') && queue.length === 0) {
        var room = this.get('room');
        if (room) {
          room.endDJ(this);
        }
      }
    }, this);
    this.sendQueue(queue);
  },

  /* Socket Commands */

  // Kicks the client from their room.
  kick: function(msg) {
    this.socket().emit('kick', msg);

    if (this.has('room'))
      this.get('room').removeConnection(this);
  },

  // Sends the number of anonymous users in their room.
  sendNumAnonymous: function(num) {
    this.socket().emit('room:num_anonymous', num);
  },

  // Sends a user that joined their room.
  sendJoinedUser: function(conn) {
    this.socket().emit('room:user:join', conn.toJSON());
  },

  // Sends a user that left their room.
  sendLeftUser: function(conn) {
    this.socket().emit('room:user:leave', conn.toJSON());
  },

  // Sends a user that was updated in their room.
  sendUpdatedUser: function(conn) {
    this.socket().emit('room:user:update', conn.toJSON());
  },

  // Sends a list of all users in their room.
  sendUserList: function(conns) {
    this.socket().emit('room:users', _.map(conns, function(conn) {
      return conn.toJSON();
    }));
  },

  // Sends a room activity.
  sendRoomActivity: function(activity) {
    this.socket().emit('room:activity', activity.toJSON());
  },

  // Sends the list of room activities.
  sendRoomActivities: function(activities) {
    this.socket().emit('room:activities', activities.toJSON());
  },

  // Sends a queue to the user.
  sendQueue: function(queue) {
    this.socket().emit('queue', queue.toJSON());
  },

  // Sends a queued song that was added or updated.
  sendQueuedSong: function(queued_song) {
    this.socket().emit('queue:song', queued_song.toJSON());
  },

  // Sends an alert that a queued song was removed from the queue.
  sendQueuedSongRemoved: function(queued_song) {
    this.socket().emit('queue:song:remove', queued_song.id);
  },

  // Sends a currently playing song.
  sendSongPlayback: function(playback) {
    this.socket().emit('room:song:update', playback.toJSON());
  },

  // Sends an indication that the playing song has stopped.
  sendSongPlaybackStopped: function() {
    this.socket().emit('room:song:stop');
  },

  // Sends the current voting numbers.
  sendVotes: function(skipVotes, skipVotesNeeded, likes) {
    this.socket().emit('room:votes', {
      skipVotes: skipVotes,
      skipVotesNeeded: skipVotesNeeded,
      likes: likes,
    });
  },

  /* Sockets Handlers */

  // Handle client auth request.
  handleAuthRequest: function(data, fn) {
    if (!data || !fn) return;

    if (this.authenticated()) {
      fn({ error: 'You are already authenticated.' });
    } else if (this.has('room')) {
      fn({ error: 'You\'re already anonymously in a room.' });
    } else if (!data.username || !data.hash) {
      fn({ error: 'Missing auth data.' });
    } else if (data.hash !== user_model.Model.hashUsername(data.username)) {
      fn({ error: 'Failed to authenticate. Please reload.' });
      this.socket().disconnect();
    } else {
      user_model.Model.find({
        where: {
          username: data.username
        }
      }).then(_.bind(function(user) {
        if (user) {
          this.set({
            authenticated: true,
            user: user
          });
          winston.info(this.user().getLogName() + ' connected.');
          fn({ success: true });
          this.fetchQueue();
        } else {
          fn({ error: 'User not found.' });
        }
      }, this)).catch(function(err) {
        winston.error('Error fetching user for auth request: ' + err.message);
        fn(err.message);
      });
    }
  },

  // Handle request to join room.
  handleRoomJoinRequest: function(shortname, fn) {
    if (!shortname || !fn) return;

    var room = rooms.roomForShortname(shortname);
    if (this.has('room')) {
      fn({ error: 'You are already in a room.' });
    } else if (room) {
      fn({ name: room.get('name'), shortname: room.get('shortname') });
      room.addConnection(this);
    } else {
      fn({ error: 'Room not found.' });
    }
  },

  // Handle request to leave room.
  handleRoomLeaveRequest: function(fn) {
    if (!fn) return;

    if (this.has('room')) {
      this.get('room').removeConnection(this);
      fn();
    } else {
      fn({ error: 'You are not in a room.' });
    }
  },

  // Handle request to become DJ.
  handleBeginDJ: function(fn) {
    if (!fn) return;

    if (!this.ensureAuth(fn)) return;
    if (!this.ensureRoom(fn)) return;

    var err = this.get('room').makeDJ(this);
    fn( err ? { error: err } : {} );
  },

  // Handle request to stop being a DJ.
  handleEndDJ: function(fn) {
    if (!fn) return;
    if (!this.ensureAuth(fn)) return;
    if (!this.ensureRoom(fn)) return;

    var err = this.get('room').endDJ(this);
    fn( err ? { error: err } : {} );
  },

  // Handle notification that a song has been enqueued from an activity.
  handleActivityEnqueue: function(activity_id) {
    this.get('room').activityEnqueued(activity_id, this);
  },

  // Handle request for search results.
  handleSearch: function(query, fn) {
    if (!query || !source || !fn) return;
    if (!this.ensureAuth(fn)) return;
    song_sources.search(query.substr(0, 50)).done(fn);
  },

  // Handle request for search results for a particular song source.
  handleSourceSearch: function(data, fn) {
    if (typeof data !== 'object') return;
    var source = data.source;
    var query = data.query;
    if (!query || !source || !fn) return;
    if (!this.ensureAuth(fn)) return;
    song_sources.searchSource(source, query.substr(0, 50)).done(fn);
  },

  // Handle adding a search result to queue.
  handleSearchAdd: function(data, fn) {
    if (!data || !fn) return;
    if (!this.ensureAuth(fn)) return;

    var source = data.source,
        source_id = data.source_id;

    var job = songs.addFromSearch(source, source_id, this.user());

    if (fn) fn({ job_id: job.job_id });
    this.watchSongAdd(job);
  },

  // Handle client disconnect.
  handleDisconnect: function() {
    if (this.has('room'))
      this.get('room').removeConnection(this);

    if (this.has('user'))
      winston.info(this.user().getLogName() + ' disconnected.');
    else
      winston.info('Anonymous listener disconnected.');

    this.trigger('disconnect');
  },

  // Handle queue song order change.
  handleQueuedSongOrder: function(data, fn) {
    if (!data) return;
    if (!this.ensureAuth(fn)) return;
    this.get('queue').updateSongOrder(data[0], data[1]);
  },

  handleEscalation: function(queued_song_id, fn) {
    if (!queued_song_id) return;
    if (!this.ensureAuth(fn)) return;
    this.get('queue').escalateSong(queued_song_id);
  },

  // Handle command to skip current song.
  handleSkip: function(fn) {
    if (!this.ensureAuth(fn)) return;
    if (!this.ensureRoom(fn)) return;

    var room = this.get('room');
    if (room.getCurrentDJ() === this) {
      room.skipSong();
      if (fn) fn();
    } else if (fn) {
      fn({ error: 'You\'re not the current DJ. You can\'t skip this song.' });
    }
  },

  // Handle command to vote to skip the current song.
  handleSkipVote: function(fn) {
    if (!this.ensureAuth(fn)) return;
    if (!this.ensureRoom(fn)) return;

    var err = this.get('room').postSkipVote(this);

    if (err) {
      winston.warn(this.getLogName() + ' skipvote failed: ' + err.message);
      if (fn) fn({ error: 'Failed to skip vote.' });
    } else if (fn) {
      fn();
    }
  },

  // Handle command to like the current song.
  handleLike: function(fn) {
    if (!this.ensureAuth(fn)) return;
    if (!this.ensureRoom(fn)) return;

    var err = this.get('room').postLike(this);

    if (err) {
      winston.warn(this.getLogName() + ' song like failed: ' + err.message);
      if (fn) fn({ error: 'Failed to like song.' });
    } else if (fn) {
      fn();
    }
  },

  // Handle command to remove a song from the user's queue.
  handleRemoveFromQueue: function(queued_song_id) {
    if (!queued_song_id) return;

    var queued_song = this.get('queue').get(queued_song_id);
    if (queued_song && !queued_song.get('playing'))
      this.get('queue').remove(queued_song_id);
  },

  // Handle socket error.
  handleError: function() {
    winston.error('Socket error; disconnecting.');
    this.socket().disconnect();
  }
});