text:
package parser

import (
	"errors"
	"fmt"
	"math"
	"reflect"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"

	"github.com/cockroachdb/cockroach/util"
)

var (
	errZeroModulus = errors.New("zero modulus")
	errDivByZero   = errors.New("division by zero")
)

// secondsInDay is the number of seconds in a day.
const secondsInDay = 24 * 60 * 60

type unaryOp struct {
	returnType Datum
	fn         func(Datum) (Datum, error)
}

type unaryArgs struct {
	op      UnaryOp
	argType reflect.Type
}

// unaryOps contains the unary operations indexed by operation type and
// argument type.
var unaryOps = map[unaryArgs]unaryOp{
	unaryArgs{UnaryPlus, intType}: {
		returnType: DummyInt,
		fn: func(d Datum) (Datum, error) {
			return d, nil
		},
	},
	unaryArgs{UnaryPlus, floatType}: {
		returnType: DummyFloat,
		fn: func(d Datum) (Datum, error) {
			return d, nil
		},
	},

	unaryArgs{UnaryMinus, intType}: {
		returnType: DummyInt,
		fn: func(d Datum) (Datum, error) {
			return -d.(DInt), nil
		},
	},
	unaryArgs{UnaryMinus, floatType}: {
		returnType: DummyFloat,
		fn: func(d Datum) (Datum, error) {
			return -d.(DFloat), nil
		},
	},

	unaryArgs{UnaryComplement, intType}: {
		returnType: DummyInt,
		fn: func(d Datum) (Datum, error) {
			return ^d.(DInt), nil
		},
	},
}

type binOp struct {
	returnType Datum
	fn         func(Datum, Datum) (Datum, error)
}

type binArgs struct {
	op        BinaryOp
	leftType  reflect.Type
	rightType reflect.Type
}

// binOps contains the binary operations indexed by operation type and argument
// types.
var binOps = map[binArgs]binOp{
	binArgs{Bitand, intType, intType}: {
		returnType: DummyInt,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DInt) & right.(DInt), nil
		},
	},

	binArgs{Bitor, intType, intType}: {
		returnType: DummyInt,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DInt) | right.(DInt), nil
		},
	},

	binArgs{Bitxor, intType, intType}: {
		returnType: DummyInt,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DInt) ^ right.(DInt), nil
		},
	},

	// TODO(pmattis): Overflow/underflow checks?

	binArgs{Plus, intType, intType}: {
		returnType: DummyInt,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DInt) + right.(DInt), nil
		},
	},
	binArgs{Plus, floatType, floatType}: {
		returnType: DummyFloat,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DFloat) + right.(DFloat), nil
		},
	},
	binArgs{Plus, dateType, intType}: {
		returnType: DummyDate,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DDate) + DDate(right.(DInt)), nil
		},
	},
	binArgs{Plus, intType, dateType}: {
		returnType: DummyDate,
		fn: func(left Datum, right Datum) (Datum, error) {
			return DDate(left.(DInt)) + right.(DDate), nil
		},
	},
	binArgs{Plus, timestampType, intervalType}: {
		returnType: DummyTimestamp,
		fn: func(left Datum, right Datum) (Datum, error) {
			return DTimestamp{Time: left.(DTimestamp).Add(right.(DInterval).Duration)}, nil
		},
	},
	binArgs{Plus, intervalType, timestampType}: {
		returnType: DummyTimestamp,
		fn: func(left Datum, right Datum) (Datum, error) {
			return DTimestamp{Time: right.(DTimestamp).Add(left.(DInterval).Duration)}, nil
		},
	},
	binArgs{Plus, intervalType, intervalType}: {
		returnType: DummyInterval,
		fn: func(left Datum, right Datum) (Datum, error) {
			return DInterval{Duration: left.(DInterval).Duration + right.(DInterval).Duration}, nil
		},
	},
	binArgs{Minus, intType, intType}: {
		returnType: DummyInt,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DInt) - right.(DInt), nil
		},
	},
	binArgs{Minus, floatType, floatType}: {
		returnType: DummyFloat,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DFloat) - right.(DFloat), nil
		},
	},
	binArgs{Minus, dateType, intType}: {
		returnType: DummyDate,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DDate) - DDate(right.(DInt)), nil
		},
	},
	binArgs{Minus, dateType, dateType}: {
		returnType: DummyInt,
		fn: func(left Datum, right Datum) (Datum, error) {
			return DInt(left.(DDate) - right.(DDate)), nil
		},
	},
	binArgs{Minus, timestampType, timestampType}: {
		returnType: DummyInterval,
		fn: func(left Datum, right Datum) (Datum, error) {
			return DInterval{Duration: left.(DTimestamp).Sub(right.(DTimestamp).Time)}, nil
		},
	},
	binArgs{Minus, timestampType, intervalType}: {
		returnType: DummyTimestamp,
		fn: func(left Datum, right Datum) (Datum, error) {
			return DTimestamp{Time: left.(DTimestamp).Add(-right.(DInterval).Duration)}, nil
		},
	},
	binArgs{Minus, intervalType, intervalType}: {
		returnType: DummyInterval,
		fn: func(left Datum, right Datum) (Datum, error) {
			return DInterval{Duration: left.(DInterval).Duration - right.(DInterval).Duration}, nil
		},
	},

	binArgs{Mult, intType, intType}: {
		returnType: DummyInt,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DInt) * right.(DInt), nil
		},
	},
	binArgs{Mult, floatType, floatType}: {
		returnType: DummyFloat,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DFloat) * right.(DFloat), nil
		},
	},
	binArgs{Mult, intType, intervalType}: {
		returnType: DummyInterval,
		fn: func(left Datum, right Datum) (Datum, error) {
			return DInterval{Duration: time.Duration(left.(DInt)) * right.(DInterval).Duration}, nil
		},
	},
	binArgs{Mult, intervalType, intType}: {
		returnType: DummyInterval,
		fn: func(left Datum, right Datum) (Datum, error) {
			return DInterval{Duration: left.(DInterval).Duration * time.Duration(right.(DInt))}, nil
		},
	},

	binArgs{Div, intType, intType}: {
		returnType: DummyFloat,
		fn: func(left Datum, right Datum) (Datum, error) {
			rInt := right.(DInt)
			if rInt == 0 {
				return nil, errDivByZero
			}
			return DFloat(left.(DInt)) / DFloat(rInt), nil
		},
	},
	binArgs{Div, floatType, floatType}: {
		returnType: DummyFloat,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DFloat) / right.(DFloat), nil
		},
	},
	binArgs{Div, intervalType, intType}: {
		returnType: DummyInterval,
		fn: func(left Datum, right Datum) (Datum, error) {
			rInt := right.(DInt)
			if rInt == 0 {
				return nil, errDivByZero
			}
			return DInterval{Duration: left.(DInterval).Duration / time.Duration(rInt)}, nil
		},
	},

	binArgs{Mod, intType, intType}: {
		returnType: DummyInt,
		fn: func(left Datum, right Datum) (Datum, error) {
			r := right.(DInt)
			if r == 0 {
				return nil, errZeroModulus
			}
			return left.(DInt) % r, nil
		},
	},
	binArgs{Mod, floatType, floatType}: {
		returnType: DummyFloat,
		fn: func(left Datum, right Datum) (Datum, error) {
			return DFloat(math.Mod(float64(left.(DFloat)), float64(right.(DFloat)))), nil
		},
	},

	binArgs{Concat, stringType, stringType}: {
		returnType: DummyString,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DString) + right.(DString), nil
		},
	},
	binArgs{Concat, bytesType, bytesType}: {
		returnType: DummyBytes,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DBytes) + right.(DBytes), nil
		},
	},

	// TODO(pmattis): Check that the shift is valid.
	binArgs{LShift, intType, intType}: {
		returnType: DummyInt,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DInt) << uint(right.(DInt)), nil
		},
	},
	binArgs{RShift, intType, intType}: {
		returnType: DummyInt,
		fn: func(left Datum, right Datum) (Datum, error) {
			return left.(DInt) >> uint(right.(DInt)), nil
		},
	},
}

type cmpArgs struct {
	op        ComparisonOp
	leftType  reflect.Type
	rightType reflect.Type
}

type cmpOp struct {
	fn func(Datum, Datum, *interface{}) (DBool, error)
}

var cmpOpResultType = reflect.New(reflect.TypeOf(cmpOp{}).Field(0).Type.Out(0)).Elem().Interface().(DBool)

// cmpOps contains the comparison operations indexed by operation type and
// argument types.
var cmpOps = map[cmpArgs]cmpOp{
	cmpArgs{EQ, stringType, stringType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DString) == right.(DString)), nil
		},
	},
	cmpArgs{EQ, bytesType, bytesType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DBytes) == right.(DBytes)), nil
		},
	},
	cmpArgs{EQ, boolType, boolType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DBool) == right.(DBool)), nil
		},
	},
	cmpArgs{EQ, intType, intType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DInt) == right.(DInt)), nil
		},
	},
	cmpArgs{EQ, floatType, floatType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DFloat) == right.(DFloat)), nil
		},
	},
	cmpArgs{EQ, dateType, dateType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DDate) == right.(DDate)), nil
		},
	},
	cmpArgs{EQ, timestampType, timestampType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DTimestamp).Equal(right.(DTimestamp).Time)), nil
		},
	},
	cmpArgs{EQ, intervalType, intervalType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DInterval) == right.(DInterval)), nil
		},
	},

	cmpArgs{LT, stringType, stringType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DString) < right.(DString)), nil
		},
	},
	cmpArgs{LT, bytesType, bytesType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DBytes) < right.(DBytes)), nil
		},
	},
	cmpArgs{LT, boolType, boolType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(!left.(DBool) && right.(DBool)), nil
		},
	},
	cmpArgs{LT, intType, intType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DInt) < right.(DInt)), nil
		},
	},
	cmpArgs{LT, floatType, floatType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DFloat) < right.(DFloat)), nil
		},
	},
	cmpArgs{LT, dateType, dateType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DDate) < right.(DDate)), nil
		},
	},
	cmpArgs{LT, timestampType, timestampType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DTimestamp).Before(right.(DTimestamp).Time)), nil
		},
	},
	cmpArgs{LT, intervalType, intervalType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DInterval).Duration < right.(DInterval).Duration), nil
		},
	},

	cmpArgs{LE, stringType, stringType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DString) <= right.(DString)), nil
		},
	},
	cmpArgs{LE, bytesType, bytesType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DBytes) <= right.(DBytes)), nil
		},
	},
	cmpArgs{LE, boolType, boolType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(!left.(DBool) || right.(DBool)), nil
		},
	},
	cmpArgs{LE, intType, intType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DInt) <= right.(DInt)), nil
		},
	},
	cmpArgs{LE, floatType, floatType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DFloat) <= right.(DFloat)), nil
		},
	},
	cmpArgs{LE, dateType, dateType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DDate) <= right.(DDate)), nil
		},
	},
	cmpArgs{LE, timestampType, timestampType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return !DBool(right.(DTimestamp).Before(left.(DTimestamp).Time)), nil
		},
	},
	cmpArgs{LE, intervalType, intervalType}: {
		fn: func(left Datum, right Datum, _ *interface{}) (DBool, error) {
			return DBool(left.(DInterval).Duration <= right.(DInterval).Duration), nil
		},
	},

	cmpArgs{Like, stringType, stringType}: {
		fn: func(left Datum, right Datum, cache *interface{}) (DBool, error) {
			var re *regexp.Regexp
			switch t := (*cache).(type) {
			case *regexp.Regexp:
				re = t
			default:
				pattern := regexp.QuoteMeta(string(right.(DString)))
				// Replace LIKE specific wildcards with standard wildcards
				pattern = strings.Replace(pattern, "%", ".*", -1)
				pattern = strings.Replace(pattern, "_", ".", -1)
				pattern = anchorPattern(pattern, false)

				re = regexp.MustCompile(pattern)
				*cache = re
			}
			return DBool(re.MatchString(string(left.(DString)))), nil
		},
	},

	cmpArgs{SimilarTo, stringType, stringType}: {
		fn: func(left Datum, right Datum, cache *interface{}) (DBool, error) {
			var re *regexp.Regexp
			switch t := (*cache).(type) {
			case *regexp.Regexp:
				re = t
			case error:
				return DBool(false), t
			default:
				pattern := SimilarEscape(string(right.(DString)))
				pattern = anchorPattern(pattern, false)

				var err error
				re, err = regexp.Compile(pattern)
				if err != nil {
					*cache = err
					return DBool(false), err
				}
				*cache = re
			}
			return DBool(re.MatchString(string(left.(DString)))), nil
		},
	},
}

var evalTupleEQ = cmpOp{
	fn: func(ldatum, rdatum Datum, _ *interface{}) (DBool, error) {
		left := ldatum.(DTuple)
		right := rdatum.(DTuple)
		if len(left) != len(right) {
			return DBool(false), nil
		}
		for i := range left {
			d, err := evalComparison(EQ, left[i], right[i])
			if err != nil {
				return DummyBool, err
			}
			if v, err := getBool(d); err != nil {
				return DummyBool, err
			} else if !v {
				return v, nil
			}
		}
		return DBool(true), nil
	},
}

var evalTupleIN = cmpOp{
	fn: func(arg, values Datum, _ *interface{}) (DBool, error) {
		if arg == DNull {
			return DBool(false), nil
		}

		vtuple := values.(DTuple)
		i := sort.Search(len(vtuple), func(i int) bool { return vtuple[i].Compare(arg) >= 0 })
		found := i < len(vtuple) && vtuple[i].Compare(arg) == 0
		return DBool(found), nil
	},
}

func init() {
	// This avoids an init-loop if we try to initialize this operation when
	// cmpOps is declared. The loop is caused by evalTupleEQ using cmpOps
	// internally.
	cmpOps[cmpArgs{EQ, tupleType, tupleType}] = evalTupleEQ

	cmpOps[cmpArgs{In, boolType, tupleType}] = evalTupleIN
	cmpOps[cmpArgs{In, intType, tupleType}] = evalTupleIN
	cmpOps[cmpArgs{In, floatType, tupleType}] = evalTupleIN
	cmpOps[cmpArgs{In, stringType, tupleType}] = evalTupleIN
	cmpOps[cmpArgs{In, bytesType, tupleType}] = evalTupleIN
	cmpOps[cmpArgs{In, dateType, tupleType}] = evalTupleIN
	cmpOps[cmpArgs{In, timestampType, tupleType}] = evalTupleIN
	cmpOps[cmpArgs{In, intervalType, tupleType}] = evalTupleIN
	cmpOps[cmpArgs{In, tupleType, tupleType}] = evalTupleIN
}

// EvalContext defines the context in which to evaluate an expression, allowing
// the retrieval of state such as the node ID or statement start time.
type EvalContext struct {
	NodeID        uint32
	StmtTimestamp DTimestamp
	TxnTimestamp  DTimestamp
	GetLocation   func() (*time.Location, error)
}

var defaultContext = EvalContext{
	GetLocation: func() (*time.Location, error) {
		return time.UTC, nil
	},
}

// makeDDate constructs a DDate from a time.Time in the session time zone.
func (ctx EvalContext) makeDDate(t time.Time) (DDate, error) {
	loc, err := ctx.GetLocation()
	if err != nil {
		return DummyDate, err
	}
	year, month, day := t.In(loc).Date()
	secs := time.Date(year, month, day, 0, 0, 0, 0, time.UTC).Unix()
	return DDate(secs / secondsInDay), nil
}

// EvalExpr evaluates an SQL expression. Expression evaluation is a mostly
// straightforward walk over the parse tree. The only significant complexity is
// the handling of types and implicit conversions. See binOps and cmpOps for
// more details. Note that expression evaluation returns an error if certain
// node types are encountered: ValArg, QualifiedName or Subquery. These nodes
// should be replaced prior to expression evaluation by an appropriate
// WalkExpr. For example, ValArg should be replace by the argument passed from
// the client.
func (ctx EvalContext) EvalExpr(expr Expr) (Datum, error) {
	switch t := expr.(type) {
	case *AndExpr:
		return ctx.evalAndExpr(t)

	case *OrExpr:
		return ctx.evalOrExpr(t)

	case *NotExpr:
		return ctx.evalNotExpr(t)

	case Row:
		// NormalizeExpr transforms this into Tuple.

	case *ParenExpr:
		// NormalizeExpr unwraps this.

	case *ComparisonExpr:
		return ctx.evalComparisonExpr(t)

	case *RangeCond:
		// NormalizeExpr transforms this into an AndExpr.

	case *IsOfTypeExpr:
		return ctx.evalIsOfTypeExpr(t)

	case *ExistsExpr:
		// The subquery within the exists should have been executed before
		// expression evaluation and the exists nodes replaced with the result.

	case *IfExpr:
		return ctx.evalIfExpr(t)

	case *NullIfExpr:
		return ctx.evalNullIfExpr(t)

	case *CoalesceExpr:
		return ctx.evalCoalesceExpr(t)

	case IntVal:
		if t < 0 {
			return DNull, fmt.Errorf("integer value out of range: %s", t)
		}
		return DInt(t), nil

	case NumVal:
		v, err := strconv.ParseFloat(string(t), 64)
		if err != nil {
			return DNull, err
		}
		return DFloat(v), nil

	case ValArg:
		// Placeholders should have been replaced before expression evaluation.

	case *QualifiedName:
		return DNull, fmt.Errorf("qualified name \"%s\" not found", t)

	case Tuple:
		tuple := make(DTuple, 0, len(t))
		for _, v := range t {
			d, err := ctx.EvalExpr(v)
			if err != nil {
				return DNull, err
			}
			tuple = append(tuple, d)
		}
		return tuple, nil

	case DReference:
		return t.Datum(), nil

	case Datum:
		return t, nil

	case *Subquery:
		// The subquery should have been executed before expression evaluation and
		// the result placed into the expression tree.

	case *BinaryExpr:
		return ctx.evalBinaryExpr(t)

	case *UnaryExpr:
		return ctx.evalUnaryExpr(t)

	case *FuncExpr:
		return ctx.evalFuncExpr(t)

	case *CaseExpr:
		return ctx.evalCaseExpr(t)

	case *CastExpr:
		return ctx.evalCastExpr(t)

	default:
		return DNull, util.Errorf("eval: unsupported expression: %T", expr)
	}

	return DNull, util.Errorf("eval: unexpected expression: %T", expr)
}

func (ctx EvalContext) evalAndExpr(expr *AndExpr) (Datum, error) {
	left, err := ctx.EvalExpr(expr.Left)
	if err != nil {
		return DNull, err
	}
	if left != DNull {
		if v, err := getBool(left); err != nil {
			return DNull, err
		} else if !v {
			return v, nil
		}
	}
	right, err := ctx.EvalExpr(expr.Right)
	if err != nil {
		return DNull, err
	}
	if right == DNull {
		return DNull, nil
	}
	if v, err := getBool(right); err != nil {
		return DNull, err
	} else if !v {
		return v, nil
	}
	return left, nil
}

func (ctx EvalContext) evalOrExpr(expr *OrExpr) (Datum, error) {
	left, err := ctx.EvalExpr(expr.Left)
	if err != nil {
		return DNull, err
	}
	if left != DNull {
		if v, err := getBool(left); err != nil {
			return DNull, err
		} else if v {
			return v, nil
		}
	}
	right, err := ctx.EvalExpr(expr.Right)
	if err != nil {
		return DNull, err
	}
	if right == DNull {
		return DNull, nil
	}
	if v, err := getBool(right); err != nil {
		return DNull, err
	} else if v {
		return v, nil
	}
	if left == DNull {
		return DNull, nil
	}
	return DBool(false), nil
}

func (ctx EvalContext) evalNotExpr(expr *NotExpr) (Datum, error) {
	d, err := ctx.EvalExpr(expr.Expr)
	if err != nil {
		return DNull, err
	}
	if d == DNull {
		return DNull, nil
	}
	v, err := getBool(d)
	if err != nil {
		return DNull, err
	}
	return !v, nil
}

func (ctx EvalContext) evalIsOfTypeExpr(expr *IsOfTypeExpr) (Datum, error) {
	d, err := ctx.EvalExpr(expr.Expr)
	if err != nil {
		return DNull, err
	}

	result := DBool(true)
	if expr.Not {
		result = !result
	}

	switch d.(type) {
	case DBool:
		for _, t := range expr.Types {
			if _, ok := t.(*BoolType); ok {
				return result, nil
			}
		}

	case DInt:
		for _, t := range expr.Types {
			if _, ok := t.(*IntType); ok {
				return result, nil
			}
		}

	case DFloat:
		for _, t := range expr.Types {
			if _, ok := t.(*FloatType); ok {
				return result, nil
			}
		}

	case DString:
		for _, t := range expr.Types {
			if _, ok := t.(*StringType); ok {
				return result, nil
			}
		}

	case DBytes:
		for _, t := range expr.Types {
			if _, ok := t.(*BytesType); ok {
				return result, nil
			}
		}

	case DDate:
		for _, t := range expr.Types {
			if _, ok := t.(*DateType); ok {
				return result, nil
			}
		}

	case DTimestamp:
		for _, t := range expr.Types {
			if _, ok := t.(*TimestampType); ok {
				return result, nil
			}
		}

	case DInterval:
		for _, t := range expr.Types {
			if _, ok := t.(*IntervalType); ok {
				return result, nil
			}
		}
	}

	return !result, nil
}

func (ctx EvalContext) evalIfExpr(expr *IfExpr) (Datum, error) {
	cond, err := ctx.EvalExpr(expr.Cond)
	if err != nil {
		return DNull, err
	}
	if cond == DBool(true) {
		return ctx.EvalExpr(expr.True)
	}
	return ctx.EvalExpr(expr.Else)
}

func (ctx EvalContext) evalNullIfExpr(expr *NullIfExpr) (Datum, error) {
	expr1, err := ctx.EvalExpr(expr.Expr1)
	if err != nil {
		return DNull, err
	}
	expr2, err := ctx.EvalExpr(expr.Expr2)
	if err != nil {
		return DNull, err
	}
	cond, err := evalComparison(EQ, expr1, expr2)
	if err != nil {
		return DNull, err
	}
	if cond == DBool(true) {
		return DNull, nil
	}
	return expr1, nil
}

func (ctx EvalContext) evalCoalesceExpr(expr *CoalesceExpr) (Datum, error) {
	for _, e := range expr.Exprs {
		d, err := ctx.EvalExpr(e)
		if err != nil {
			return DNull, err
		}
		if d != DNull {
			return d, nil
		}
	}
	return DNull, nil
}

func (ctx EvalContext) evalComparisonExpr(expr *ComparisonExpr) (Datum, error) {
	left, err := ctx.EvalExpr(expr.Left)
	if err != nil {
		return DNull, err
	}
	right, err := ctx.EvalExpr(expr.Right)
	if err != nil {
		return DNull, err
	}

	if left == DNull || right == DNull {
		switch expr.Operator {
		case IsDistinctFrom:
			return !DBool(left == DNull && right == DNull), nil
		case IsNotDistinctFrom:
			return DBool(left == DNull && right == DNull), nil
		case Is:
			// IS and IS NOT can compare against NULL.
			return DBool(left == right), nil
		case IsNot:
			return DBool(left != right), nil
		default:
			return DNull, nil
		}
	}

	// Make sure the expression's cmpOp function is memoized
	if expr.fn.fn == nil {
		if _, err := typeCheckComparisonExpr(expr); err != nil {
			return DNull, err
		}

		// If cmpOp's function is still nil, return unsupported op error
		if expr.fn.fn == nil {
			return DNull, fmt.Errorf("unsupported comparison operator: <%s> %s <%s>",
				left.Type(), expr.Operator, right.Type())
		}
	}

	_, newLeft, newRight, not := foldComparisonExpr(expr.Operator, left, right)
	d, err := expr.fn.fn(newLeft, newRight, &expr.cache)
	if err == nil && not {
		return !d, nil
	}
	return d, err
}

func (ctx EvalContext) evalBinaryExpr(expr *BinaryExpr) (Datum, error) {
	left, err := ctx.EvalExpr(expr.Left)
	if err != nil {
		return nil, err
	}
	if left == DNull {
		return DNull, nil
	}
	right, err := ctx.EvalExpr(expr.Right)
	if err != nil {
		return nil, err
	}
	if right == DNull {
		return DNull, nil
	}

	if expr.fn.fn == nil {
		if _, err := typeCheckBinaryExpr(expr); err != nil {
			return nil, err
		}
	}
	return expr.fn.fn(left, right)
}

func (ctx EvalContext) evalUnaryExpr(expr *UnaryExpr) (Datum, error) {
	d, err := ctx.EvalExpr(expr.Expr)
	if err != nil {
		return DNull, err
	}
	if expr.fn.fn == nil {
		if _, err := typeCheckUnaryExpr(expr); err != nil {
			return DNull, err
		}
	}
	if expr.dtype != reflect.TypeOf(d) {
		// The argument type no longer match the memoized function. This happens
		// when a non-NULL argument becomes NULL. For example, "SELECT -col FROM
		// table" where col is nullable. The SELECT does not error, but returns a
		// NULL value for that select expression.
		return DNull, nil
	}
	return expr.fn.fn(d)
}

func (ctx EvalContext) evalFuncExpr(expr *FuncExpr) (Datum, error) {
	args := make(DTuple, 0, len(expr.Exprs))
	types := make(typeList, 0, len(expr.Exprs))
	for _, e := range expr.Exprs {
		arg, err := ctx.EvalExpr(e)
		if err != nil {
			return DNull, err
		}
		args = append(args, arg)
		types = append(types, reflect.TypeOf(arg))
	}

	if expr.fn.fn == nil {
		if _, err := typeCheckFuncExpr(expr); err != nil {
			return DNull, err
		}
	}

	if !expr.fn.match(types) {
		// The argument types no longer match the memoized function. This happens
		// when a non-NULL argument becomes NULL and the function does not support
		// NULL arguments. For example, "SELECT LOWER(col) FROM TABLE" where col is
		// nullable. The SELECT does not error, but returns a NULL value for that
		// select expression.
		return DNull, nil
	}

	res, err := expr.fn.fn(ctx, args)
	if err != nil {
		return DNull, fmt.Errorf("%s: %v", expr.Name, err)
	}
	return res, nil
}

func (ctx EvalContext) evalCaseExpr(expr *CaseExpr) (Datum, error) {
	if expr.Expr != nil {
		// CASE <val> WHEN <expr> THEN ...
		//
		// For each "when" expression we compare for equality to <val>.
		val, err := ctx.EvalExpr(expr.Expr)
		if err != nil {
			return DNull, err
		}

		for _, when := range expr.Whens {
			arg, err := ctx.EvalExpr(when.Cond)
			if err != nil {
				return DNull, err
			}
			d, err := evalComparison(EQ, val, arg)
			if err != nil {
				return DNull, err
			}
			if v, err := getBool(d); err != nil {
				return DNull, err
			} else if v {
				return ctx.EvalExpr(when.Val)
			}
		}
	} else {
		// CASE WHEN <bool-expr> THEN ...
		for _, when := range expr.Whens {
			d, err := ctx.EvalExpr(when.Cond)
			if err != nil {
				return DNull, err
			}
			if v, err := getBool(d); err != nil {
				return DNull, err
			} else if v {
				return ctx.EvalExpr(when.Val)
			}
		}
	}

	if expr.Else != nil {
		return ctx.EvalExpr(expr.Else)
	}
	return DNull, nil
}

func (ctx EvalContext) evalCastExpr(expr *CastExpr) (Datum, error) {
	d, err := ctx.EvalExpr(expr.Expr)
	if err != nil {
		return DNull, err
	}

	switch expr.Type.(type) {
	case *BoolType:
		switch v := d.(type) {
		case DBool:
			return d, nil
		case DInt:
			return DBool(v != 0), nil
		case DFloat:
			return DBool(v != 0), nil
		case DString:
			// TODO(pmattis): strconv.ParseBool is more permissive than the SQL
			// spec. Is that ok?
			b, err := strconv.ParseBool(string(v))
			if err != nil {
				return DNull, err
			}
			return DBool(b), nil
		}

	case *IntType:
		switch v := d.(type) {
		case DBool:
			if v {
				return DInt(1), nil
			}
			return DInt(0), nil
		case DInt:
			return d, nil
		case DFloat:
			return DInt(v), nil
		case DString:
			i, err := strconv.ParseInt(string(v), 0, 64)
			if err != nil {
				return DNull, err
			}
			return DInt(i), nil
		}

	case *FloatType:
		switch v := d.(type) {
		case DBool:
			if v {
				return DFloat(1), nil
			}
			return DFloat(0), nil
		case DInt:
			return DFloat(v), nil
		case DFloat:
			return d, nil
		case DString:
			f, err := strconv.ParseFloat(string(v), 64)
			if err != nil {
				return DNull, err
			}
			return DFloat(f), nil
		}

	case *StringType:
		var s DString
		switch t := d.(type) {
		case DBool, DInt, DFloat, dNull:
			s = DString(d.String())
		case DString:
			s = t
		case DBytes:
			if !utf8.ValidString(string(t)) {
				return DNull, fmt.Errorf("invalid utf8: %q", string(t))
			}
			s = DString(t)
		}
		if c, ok := expr.Type.(*StringType); ok {
			// If the CHAR type specifies a limit we truncate to that limit:
			//   'hello'::CHAR(2) -> 'he'
			if c.N > 0 && c.N < len(s) {
				s = s[:c.N]
			}
		}
		return s, nil

	case *BytesType:
		switch t := d.(type) {
		case DString:
			return DBytes(t), nil
		case DBytes:
			return d, nil
		}

	case *DateType:
		switch d := d.(type) {
		case DString:
			return ParseDate(d)
		case DTimestamp:
			return ctx.makeDDate(d.Time)
		}

	case *TimestampType:
		switch d := d.(type) {
		case DString:
			return ctx.ParseTimestamp(d)
		case DDate:
			loc, err := ctx.GetLocation()
			if err != nil {
				return DNull, err
			}
			year, month, day := time.Unix(int64(d)*secondsInDay, 0).UTC().Date()
			return DTimestamp{Time: time.Date(year, month, day, 0, 0, 0, 0, loc)}, nil
		}

	case *IntervalType:
		switch d.(type) {
		case DString:
			// We use the Golang format for specifying duration.
			// TODO(vivek): we might consider using the postgres format as well.
			d, err := time.ParseDuration(string(d.(DString)))
			return DInterval{Duration: d}, err

		case DInt:
			// An integer duration represents a duration in nanoseconds.
			return DInterval{Duration: time.Duration(d.(DInt))}, nil
		}
		// TODO(pmattis): unimplemented.
		// case *DecimalType:
	}

	return DNull, fmt.Errorf("invalid cast: %s -> %s", d.Type(), expr.Type)
}

func evalComparison(op ComparisonOp, left, right Datum) (Datum, error) {
	if left == DNull || right == DNull {
		return DNull, nil
	}

	if f, ok := cmpOps[cmpArgs{op, reflect.TypeOf(left), reflect.TypeOf(right)}]; ok {
		return f.fn(left, right, nil)
	}

	return DNull, fmt.Errorf("unsupported comparison operator: <%s> %s <%s>",
		left.Type(), op, right.Type())
}

// foldComparisonExpr folds a given comparison operation and its datum into an
// equivalent operation that will hit in the cmpOps map, returning this new
// operation, along with potentially flipped operands and a "not" flag.
func foldComparisonExpr(op ComparisonOp, dummyLeft, dummyRight Datum) (ComparisonOp, Datum, Datum, bool) {
	switch op {
	case NE:
		// NE(left, right) is implemented as !EQ(left, right).
		return EQ, dummyLeft, dummyRight, true
	case GT:
		// GT(left, right) is implemented as LT(right, left)
		return LT, dummyRight, dummyLeft, false
	case GE:
		// GE(left, right) is implemented as LE(right, left)
		return LE, dummyRight, dummyLeft, false
	case NotIn:
		// NotIn(left, right) is implemented as !IN(left, right)
		return In, dummyLeft, dummyRight, true
	case NotLike:
		// NotLike(left, right) is implemented as !Like(left, right)
		return Like, dummyLeft, dummyRight, true
	case NotSimilarTo:
		// NotSimilarTo(left, right) is implemented as !SimilarTo(left, right)
		return SimilarTo, dummyLeft, dummyRight, true
	case IsDistinctFrom:
		// IsDistinctFrom(left, right) is implemented as !EQ(left, right)
		//
		// Note the special handling of NULLs and IS DISTINCT FROM is needed
		// before this expression fold.
		return EQ, dummyLeft, dummyRight, true
	case IsNotDistinctFrom:
		// IsNotDistinctFrom(left, right) is implemented as EQ(left, right)
		//
		// Note the special handling of NULLs and IS NOT DISTINCT FROM is needed
		// before this expression fold.
		return EQ, dummyLeft, dummyRight, false
	case Is:
		// Is(left, right) is implemented as EQ(left, right)
		//
		// Note the special handling of NULLs and IS is needed before this
		// expression fold.
		return EQ, dummyLeft, dummyRight, false
	case IsNot:
		// IsNot(left, right) is implemented as !EQ(left, right)
		//
		// Note the special handling of NULLs and IS NOT is needed before this
		// expression fold.
		return EQ, dummyLeft, dummyRight, true
	}
	return op, dummyLeft, dummyRight, false
}

// time.Time formats.
const (
	dateFormat                    = "2006-01-02"
	timestampFormat               = "2006-01-02 15:04:05.999999999"
	TimestampWithOffsetZoneFormat = "2006-01-02 15:04:05.999999999-07:00"
	timestampWithNamedZoneFormat  = "2006-01-02 15:04:05.999999999 MST"
)

// ParseDate parses a date.
func ParseDate(s DString) (DDate, error) {
	// No need to ParseInLocation here because we're only parsing dates.
	t, err := time.Parse(dateFormat, string(s))
	if err != nil {
		return DummyDate, err
	}
	return defaultContext.makeDDate(t)
}

// ParseTimestamp parses the timestamp.
func (ctx EvalContext) ParseTimestamp(s DString) (DTimestamp, error) {
	loc := time.UTC
	if ctx.GetLocation != nil {
		var err error
		if loc, err = ctx.GetLocation(); err != nil {
			return DummyTimestamp, err
		}
	}

	str := string(s)
	var err error

	for _, format := range []string{
		dateFormat,
		TimestampWithOffsetZoneFormat,
		timestampFormat,
		timestampWithNamedZoneFormat,
	} {
		var t time.Time
		if t, err = time.ParseInLocation(format, str, loc); err == nil {
			return DTimestamp{Time: t}, nil
		}
	}

	return DummyTimestamp, err
}

// SimilarEscape converts a SQL:2008 regexp pattern to POSIX style, so it can
// be used by our regexp engine.
func SimilarEscape(pattern string) string {
	return similarEscapeCustomChar(pattern, '\\')
}

// similarEscapeCustomChar converts a SQL:2008 regexp pattern to POSIX style,
// so it can be used by our regexp engine. This version of the function allows
// for a custom escape character.
func similarEscapeCustomChar(pattern string, escapeChar rune) string {
	patternBuilder := make([]rune, 0, utf8.RuneCountInString(pattern))

	inCharClass := false
	afterEscape := false
	numQuotes := 0
	for _, c := range pattern {
		switch {
		case afterEscape:
			// For SUBSTRING patterns
			if c == '"' && !inCharClass {
				if numQuotes%2 == 0 {
					patternBuilder = append(patternBuilder, '(')
				} else {
					patternBuilder = append(patternBuilder, ')')
				}
				numQuotes++
			} else {
				patternBuilder = append(patternBuilder, '\\', c)
			}
			afterEscape = false
		case utf8.ValidRune(escapeChar) && c == escapeChar:
			// SQL99 escape character; do not immediately send to output
			afterEscape = true
		case inCharClass:
			if c == '\\' {
				patternBuilder = append(patternBuilder, '\\')
			}
			patternBuilder = append(patternBuilder, c)
			if c == ']' {
				inCharClass = false
			}
		case c == '[':
			patternBuilder = append(patternBuilder, c)
			inCharClass = true
		case c == '%':
			patternBuilder = append(patternBuilder, '.', '*')
		case c == '_':
			patternBuilder = append(patternBuilder, '.')
		case c == '(':
			// Convert to non-capturing parenthesis
			patternBuilder = append(patternBuilder, '(', '?', ':')
		case c == '\\', c == '.', c == '^', c == '$':
			// Escape these characters because they are NOT
			// metacharacters for SQL-style regexp
			patternBuilder = append(patternBuilder, '\\', c)
		default:
			patternBuilder = append(patternBuilder, c)
		}
	}

	return string(patternBuilder)
}

// anchorPattern surrounds the transformed input string with
//   ^(?: ... )$
// which requires some explanation.  We need "^" and "$" to force
// the pattern to match the entire input string as per SQL99 spec.
// The "(?:" and ")" are a non-capturing set of parens; we have to have
// parens in case the string contains "|", else the "^" and "$" will
// be bound into the first and last alternatives which is not what we
// want, and the parens must be non capturing because we don't want them
// to count when selecting output for SUBSTRING.
func anchorPattern(pattern string, caseInsensitive bool) string {
	if caseInsensitive {
		return fmt.Sprintf("^(?i:%s)$", pattern)
	}
	return fmt.Sprintf("^(?:%s)$", pattern)
}


text:
package org.apereo.cas.logging;

import org.apereo.cas.logging.web.ThreadContextMDCServletFilterTests;

import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;

/**
 * This is {@link CasLoggingTestsSuite}.
 *
 * @author Misagh Moayyed
 * @since 6.2.0
 */
@SelectClasses(
    ThreadContextMDCServletFilterTests.class
)
@Suite
public class CasLoggingTestsSuite {
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

exports.__esModule = true;

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * TODO: PropTypes
 * Isolate component from parent's model context.
 */
var Cage = function (_React$Component) {
  (0, _inherits3.default)(Cage, _React$Component);

  function Cage(props) {
    (0, _classCallCheck3.default)(this, Cage);

    var _this = (0, _possibleConstructorReturn3.default)(this, _React$Component.call(this, props));

    _this.displayName = 'Cage';
    return _this;
  }

  Cage.prototype.getChildContext = function getChildContext() {
    return {
      caquiRelatedForm: null,
      caquiModel: null
    };
  };

  Cage.prototype.render = function render() {
    return this.props.children;
  };

  return Cage;
}(_react2.default.Component);

Cage.childContextTypes = {
  caquiRelatedForm: _react2.default.PropTypes.string,
  caquiModel: _react2.default.PropTypes.any
};
exports.default = Cage;


text:
static int hash_str(void* key)
{
    return hashmapHash(key, strlen(key));
}

static bool hash_equal(void* a, void* b)
{
    return strcmp(a, b) == 0;
}

void test_hash_map()
{
    struct Hashmap* map = hashmapCreate(2, hash_str, hash_equal);
    const char* key = "test_key";
    const char* data = "test_data";

    hashmapPut(map, (void*)key, (void*)data);

    const char* d = hashmapGet(map, (void*)key);
    printf("d = %s\n", d);
}


text:
Para empezar servidor
php -S localhost:8080 -t public/


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W30554_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans693.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">CONTINENTAL RESOURCES INC.
EXHIBIT 1 VICINITY MAP
SECTIEIN 81. T155N, R98V WILLIAMS CIJUNTY, NIJRTH DAKIJTA


text:
<?php
namespace app\modules\posts\widgets;

use Yii;
use yii\helpers\Html;
use yii\data\ActiveDataProvider;
use app\modules\posts\models\WidgetConfig;
use app\modules\app\widgets\Portlet;

class WidgetBlogMapRender extends Portlet
{
	/**
	 * const WIDGET_NAME must be defined for all widgets!
	 */
	const WIDGET_NAME = 'MAPWIDGET';

	public $module = 0;
	public $id = 0;

	public function init() {
		parent::init();
	}

	protected function renderContent()
	{
		$dpLocations = WidgetConfig::findRelatedModels(self::WIDGET_NAME, $this->module, $this->id);

	  if(!is_null($dpLocations))
	  {
			//here we don't return the view, here we just echo it!
			echo $this->render('@app/modules/posts/widgets/views/_mapwidget_renderer',['dpLocations'=>$dpLocations]);
		}
		else
		{
			echo "";
		}
	}

}


text:
import React from 'react';
import { shallow, mount } from 'enzyme';
import Login from './login.js';

describe('<Login />', () => {
    it('renders without crashing', () => {
        const component = shallow(
            <Login />
        );
        expect(component).toMatchSnapshot();
    });
    it('should call callblack on form submit', () => {
        const submitCallback = jest.fn();
        const component = mount(
            <Login submitCallback={submitCallback} />
        );
        component.find('[type="submit"]').get(0).click();
        expect(submitCallback).toHaveBeenCalled();
    });
})


text:
from __future__ import (division, absolute_import, unicode_literals,
                        print_function)

from file_metadata._compat import which
from file_metadata.generic_file import GenericFile
from file_metadata.mixins import is_svg, FFProbeMixin
from tests import fetch_file, mock, unittest, which_sideeffect

class FFProbeTestFile(GenericFile, FFProbeMixin):
    pass

class FFProbeMixinTest(unittest.TestCase):
    __test__ = False

    def test_bin(self, mock_which):
        _file = FFProbeTestFile(fetch_file('file.bin'))
        data = _file.analyze_ffprobe()
        self.assertEqual(data, {})

    def test_multiline_value(self, mock_with):
        _file = FFProbeTestFile(fetch_file('multiline_ffprobe.ogg'))
        data = _file.analyze_ffprobe()
        self.assertIn('FFProbe:Format', data)
        self.assertEqual(data['FFProbe:Format'], 'ogg')
        self.assertEqual(int(data['FFProbe:Duration']), 224)
        self.assertEqual(data['FFProbe:NumStreams'], 1)

        stream = data['FFProbe:Streams'][0]
        self.assertEqual(stream['Format'], 'audio/vorbis')
        self.assertNotIn('Width', stream)
        self.assertNotIn('Height', stream)
        self.assertIn('44100', stream['Rate'])
        self.assertEqual(int(stream['Duration']), 224)

    def test_ogg(self, mock_which):
        _file = FFProbeTestFile(fetch_file('wikiexample.ogg'))
        data = _file.analyze_ffprobe()
        self.assertIn('FFProbe:Format', data)
        self.assertEqual(data['FFProbe:Format'], 'ogg')
        self.assertEqual(round(data['FFProbe:Duration']), 6)
        self.assertEqual(data['FFProbe:NumStreams'], 1)

        stream = data['FFProbe:Streams'][0]
        self.assertEqual(stream['Format'], 'audio/vorbis')
        self.assertNotIn('Width', stream)
        self.assertNotIn('Height', stream)
        self.assertIn('44100', stream['Rate'])
        self.assertEqual(round(stream['Duration']), 6)

    def test_wav(self, mock_which):
        _file = FFProbeTestFile(fetch_file('noise.wav'))
        data = _file.analyze_ffprobe()
        self.assertIn('FFProbe:Format', data)
        self.assertEqual(data['FFProbe:Format'], 'wav')
        self.assertEqual(data['FFProbe:Duration'], 1)
        self.assertEqual(data['FFProbe:NumStreams'], 1)

        stream = data['FFProbe:Streams'][0]
        self.assertEqual(stream['Format'], 'audio/pcm_s16le')
        self.assertNotIn('Width', stream)
        self.assertNotIn('Height', stream)
        self.assertIn('44100', stream['Rate'])
        self.assertEqual(round(stream['Duration']), 1)

    def test_ogv(self, mock_which):
        _file = FFProbeTestFile(fetch_file('veins.ogv'))
        data = _file.analyze_ffprobe()
        self.assertIn('FFProbe:Format', data)
        self.assertEqual(data['FFProbe:Format'], 'ogg')
        self.assertEqual(round(data['FFProbe:Duration']), 11)
        self.assertEqual(data['FFProbe:NumStreams'], 2)

        stream = data['FFProbe:Streams'][0]
        self.assertEqual(stream['Format'], 'data/unknown')
        self.assertNotIn('Width', stream)
        self.assertNotIn('Height', stream)
        self.assertNotIn('Rate', stream)

        stream = data['FFProbe:Streams'][1]
        self.assertEqual(stream['Format'], 'video/theora')
        self.assertEqual(stream['Width'], 320)
        self.assertEqual(stream['Height'], 240)
        self.assertEqual(round(stream['Duration']), 11)

@unittest.skipIf(which('ffprobe') is None, '`ffprobe` not found.')
@mock.patch('file_metadata.mixins.which',
            side_effect=which_sideeffect(['avprobe']))
class FFProbeMixinWithFFProbeTest(FFProbeMixinTest):
    __test__ = True

@unittest.skipIf(which('avprobe') is None, '`avprobe` not found.')
@mock.patch('file_metadata.mixins.which',
            side_effect=which_sideeffect(['ffprobe']))
class FFProbeMixinWithAVProbeTest(FFProbeMixinTest):
    __test__ = True

@mock.patch('file_metadata.mixins.which',
            side_effect=which_sideeffect(['ffprobe', 'avprobe']))
class FFProbeMixinWithoutBackendsTest(unittest.TestCase):
    def test_wav(self, mock_check_output, mock_system=None):
        _file = FFProbeTestFile(fetch_file('noise.wav'))
        self.assertRaises(OSError, _file.analyze_ffprobe)

class IsSvgTest(unittest.TestCase):

    def test_is_svg_application_xml(self):
        _file = GenericFile(fetch_file('application_xml.svg'))
        self.assertTrue(is_svg(_file))

    def test_is_svg_image_svg_xml(self):
        _file = GenericFile(fetch_file('image_svg_xml.svg'))
        self.assertTrue(is_svg(_file))

    def test_is_svg_text_plain(self):
        _file = GenericFile(fetch_file('text_plain.svg'))
        self.assertTrue(is_svg(_file))

    def test_is_svg_text_html(self):
        _file = GenericFile(fetch_file('text_html.svg'))
        self.assertTrue(is_svg(_file))

    def test_is_svg_binary(self):
        _file = GenericFile(fetch_file('file.bin'))
        self.assertFalse(is_svg(_file))

    def test_is_svg_png(self):
        _file = GenericFile(fetch_file('red.png'))
        self.assertFalse(is_svg(_file))


text:
const LetterState = {};
LetterState.UNKNOWN = 'empty';
LetterState.ABSENT = 'absent';
LetterState.ELSEWHERE = 'elsewhere';
LetterState.CORRECT = 'correct';
const START_HELP_TEXT = 'Enter a word for someone!\nOr choose a random word.';

const GuessState = {};
GuessState.UNKNOWN = 'empty';
GuessState.HIGHLIGHTED = 'elsewhere';

const GameState = {};
GameState.CHOOSING_WORD = 'choose';
GameState.GUESSING_WORD = 'guess';
GameState.COMPLETE = 'complete';

const CORRECT_COLOR = '#F7A8B8';
const ELSEWHERE_COLOR = '#55CDFC';

const DEFAULT_WORD_SIZE = 4;

const ENTER_KEY = '\u21A9';
const BACKSPACE_KEY = '\u232B';
const KEYS = ['qwertyuiop', 'asdfghjkl', ENTER_KEY + 'zxcvbnm' + BACKSPACE_KEY];
const COLOR_CYCLE = ['blueviolet', 'orange', 'yellow', 'green'];

//const NUMBERS = ['\u24EA', '\u2460', '\u2461', '\u2462', '\u2463', '\u2464', '\u2465', '\u2466', '\u2467', '\u2468'];
const NUMBERS = ['\u0030\uFE0F\u20E3',
'\u0031\uFE0F\u20E3',
'\u0032\uFE0F\u20E3',
'\u0033\uFE0F\u20E3',
'\u0034\uFE0F\u20E3',
'\u0035\uFE0F\u20E3',
'\u0036\uFE0F\u20E3',
'\u0037\uFE0F\u20E3',
'\u0038\uFE0F\u20E3',
'\u0039\uFE0F\u20E3'];

class Game {
  constructor() {
  }

  newGame() {
    document.activeElement.blur();
    this.stateList = [];
    this.logicList = [];
    this.guessList = [];
    this.keyStates = {};
    this.letterStates = {};
    this.letterColors = {};
    this.pendingTarget = '';
    this.guess = '';
    this.board = document.getElementsByClassName('board')[0];
    while (this.board.firstChild) {
      this.board.removeChild(this.board.firstChild);
    }
    this.board.className = 'board';
    const share = document.getElementById('share');
    share.className = 'share';
    this.gameState = GameState.CHOOSING_WORD;
    document.getElementById('head').innerText = 'Friendl';

    const row = document.createElement('div');
    row.className = 'row';
    this.board.appendChild(row);
    document.getElementById('random').style.display = 'unset';
    document.getElementById('enterword').style.display = 'unset';
    document.getElementsByClassName('keys')[0].style.display = 'none';
    row.innerText = START_HELP_TEXT;
    this.updateKeys();
    this.showNotification(null);
  }

  forceNewGame() {
    window.location.hash = '';
    this.newGame();
  }

  chooseWord(target) {
    if (words.indexOf(target) < 0) {
      if (target.length == 0) {
        this.showNotification(START_HELP_TEXT);
      } else {
        this.showNotification('Unknown word ' + target.toUpperCase() + '');
      }
      return null;
    }
    this.pendingTarget = '';
    this.size = target.length;
    this.target = target;
    window.location.hash = '#' + encode(target);
    this.targetWordList = wordsByLength[this.target.length];
    this.board.removeChild(this.board.firstChild);
    this.startNewRow();
    this.gameState = GameState.GUESSING_WORD;
    document.getElementById('head').innerText = 'Friendl';
    this.logicList.push([]);
    this.hideButtons();
    this.updateGuess();
  }

  chooseRandomWord(size) {
    let target = '';
    if (size == 4) {
      // for (let i = 0; i < freq.length; i++) {
      //   let all = freq[i];
      //   if (wordsByLength[size].indexOf(all) < 0) {
      //     console.log(all);
      //   }
      // }
      let attemptedTarget = null;
      while (!attemptedTarget) {
        attemptedTarget = freq[Math.floor(Math.random() * freq.length)];
        if (wordsByLength[size].indexOf(attemptedTarget) < 0) {
          attemptedTarget = null;
        }
      }
      target = attemptedTarget;
    } else {
      const max = wordsByLength[size].length;
      target = wordsByLength[size][Math.floor(Math.random() * max)];
    }
    this.chooseWord(target);
  }

  startNewRow() {
    const row = document.createElement('div');
    row.className = 'row';
    this.board.appendChild(row);
    this.updateGuess();
  }

  letterCounts(word) {
    const counts = {};
    for (let i = 0; i < word.length; i++) {
      let count = counts[word[i]] || 0;
      counts[word[i]] = count + 1;
    }
    return counts;
  }

  showNotification(text, timeout = 10000) {
    const notif = document.getElementsByClassName('notification')[0];
    if (!text || text === '') {
      notif.style.display = 'none';
      if (this.timer_) {
        clearTimeout(this.timer_);
      }
    } else {
      notif.innerText = text;
      notif.style.display = 'unset';
      if (this.timer_) {
        clearTimeout(this.timer_);
      }
      this.timer_ = setTimeout(() => notif.style.display = 'none', timeout);
    }
  }
  commitWord() {
    this.chooseWord(this.pendingTarget);
    this.showNotification('Press Share to send a link with this word!');
  }

  guessWord() {
    document.activeElement.blur();
    const input = this.guess.toLowerCase();
    if (input.length !== this.size) {
      return;
    }
    const states = this.wordStates(input);
    if (states == null) {
      // Invalid word
      this.showNotification('Unknown word ' + input.toUpperCase());
      return;
    }
    this.showNotification(null);
    this.updateGuess(states);
    this.guessList.push(this.guess);
    this.stateList.push(states);
    this.logicList.push([]);

    this.updateKeys();
    if (this.guess === this.target) {
      this.board.className = 'board won';
      const share = document.getElementById('share');
      share.className = 'share won';
      document.getElementById('head').innerText = 'In ' + this.stateList.length + (this.stateList.length > 9 ? '...' : '!');
      this.gameState = GameState.COMPLETE;
      window.location.hash = '';
      this.showNotification('Got it in ' + this.stateList.length +'! Press R or Enter to restart.');
    } else {
      this.guess = '';
      this.startNewRow();
      window.scrollTo(0, document.body.scrollHeight);
    }
  }

  updateKeys() {
    for (let key in keyMap) {
      keyMap[key].className = 'key';
    }
    for (let i = 0; i < this.guessList.length; i++) {
      const guess = this.guessList[i];
      for (let j = 0; j < guess.length; j++) {
        const letter = guess.charAt(j);
        keyMap[letter].className = 'key used';
      }
    }
  }

  toggleLetterState(state) {
    if (!state) {
      state = GuessState.UNKNOWN;
    }
    switch (state) {
      case GuessState.UNKNOWN:
        return GuessState.HIGHLIGHTED;
      case GuessState.HIGHLIGHTED:
        return GuessState.UNKNOWN;
    }
  }

  getNewColor() {
    let used = [];
    for (let i = 0; i < COLOR_CYCLE.length; i++) {
      used[i] = 0;
    }
    for (let k in this.letterColors) {
      if (this.letterColors[k] !== undefined) {
        used[this.letterColors[k]]++;
      }
    }
    for (let i = 0; i < used.length - 1; i++) {
      if (used[i] < used[i + 1]) {
        return i;
      }
      if (used[i] > used[i + 1]) {
        return i + 1;
      }
    }
    return 0;
  }

  updateAllLetters() {
      const letters = document.getElementsByClassName('letter');
      for (let p = 0; p < letters.length; p++) {
        const letter = letters[p];
        const l = letter.innerText.toLowerCase();
        let state = this.letterStates[l];
        if (state === LetterState.ELSEWHERE) {
          let color = this.letterColors[l];
          if (color === undefined) {
            color = this.getNewColor();
            this.letterColors[l] = color;
          }
          letter.style.backgroundColor = COLOR_CYCLE[color];
        } else {
          letter.style.backgroundColor = null;
          this.letterColors[l] = undefined;
        }
        if (!state) {
          state = LetterState.UNKNOWN;
        }
        letter.className = 'letter ' + state;
      }
  }

  makeLetter(state, l) {
    const letter = document.createElement('button');
    letter.className = 'letter ' + state;
    if (l) {
      letter.appendChild(document.createTextNode(l.toUpperCase()));
    }
    // const row = r;
    // const index = i;
    const le = l;

    letter.addEventListener('click', (event) => {
      if (le) {
        const lower = le.toLowerCase();
        const newState = this.toggleLetterState(this.letterStates[lower]);
        this.letterStates[lower] = newState;
        this.updateAllLetters();
      }
    }, false);
    return letter;
  }

  typeLetter(letter) {
    if (this.gameState == GameState.CHOOSING_WORD) {
      this.pendingTarget += letter;
    } else {
      if (this.guess.length < this.size) {
        this.guess += letter;
      }
    }
    this.updateGuess();
  }

  deleteLetterTarget() {
    if (this.pendingTarget.length >= 1) {
      this.pendingTarget = this.pendingTarget.substring(0, this.pendingTarget.length - 1);
    }
    this.updateGuess();
    if (this.pendingTarget.length === 0) {
      const row = this.board.lastChild;
      row.innerText = START_HELP_TEXT;
    }
  }

  deleteLetterGuess() {
    if (this.guess.length >= 1) {
      this.guess = this.guess.substring(0, this.guess.length - 1);
    }
    this.updateGuess();
  }

  updateGuess(states) {
    const row = this.board.lastChild;
    while (row.firstChild) {
      row.removeChild(row.firstChild);
    }
    if (this.gameState == GameState.CHOOSING_WORD) {
      for (let i = 0; i < this.pendingTarget.length; i++) {
        row.appendChild(this.makeLetter(GuessState.UNKNOWN, this.pendingTarget[i]));
      }
      return;
    }
    // const player = document.createElement('div');
    // player.className = 'counter';
    // player.appendChild(document.createTextNode(this.stateList.length + 1));
    // row.appendChild(player);
    const r = this.logicList.length - 1;
    for (let i = 0; i < this.target.length; i++) {
      const l = this.guess[i];
      // const state = this.logicList[r][i];
      // row.appendChild(this.makeLetter(states ? states[i] : LetterState.UNKNOWN, this.guess[i]));
      //row.appendChild(this.makeLetter(state ? state : LetterState.UNKNOWN, this.guess[i], r, i));
      row.appendChild(this.makeLetter(this.letterStates[l] ? this.letterStates[l] : LetterState.UNKNOWN, l));
    }
    let correct = '!';
    let elsewhere = '?';
    let pendingRow = ' pending';
    if (states) {
      pendingRow = '';
      correct = 0;
      elsewhere = 0;
      for (let i = 0; i < states.length; i++) {
        if (states[i] === LetterState.CORRECT) {
          correct++;
        } else if (states[i] === LetterState.ELSEWHERE) {
          elsewhere++;
        }
      }
    }
    row.appendChild(this.createCountNode(correct, 'right' + pendingRow));
    row.appendChild(this.createCountNode(elsewhere, 'else' + pendingRow));
    this.updateAllLetters();
  }

  createCountNode(count, kind) {
    const player = document.createElement('button');
    player.className = 'state ' + kind;
    player.appendChild(document.createTextNode(count));
    return player;
  }

  wordStates(input) {
    if (input.length !== this.target.length) {
      return null;
    } else if (this.targetWordList.indexOf(input)<0) {
      return null;
    }
    return this.wordMatches(input, this.target);
  }

  wordMatches(input, target) {
    const states = [];
    for (let i = 0; i < input.length; i++) {
      states[i] = LetterState.ABSENT;
    }
    const countsByLetter = this.letterCounts(this.target);
    // First check for exact matches
    for (let i = 0; i < input.length; i++) {
      if (input[i] === this.target[i]) {
        states[i] = LetterState.CORRECT;
        countsByLetter[input[i]]--;
      }
    }
    // Then check for right-letter-wrong-place
    for (let i = 0; i < input.length; i++) {
      if (countsByLetter[input[i]] > 0 && states[i] !== LetterState.CORRECT) {
        states[i] = LetterState.ELSEWHERE;
        countsByLetter[input[i]]--;
      }
    }
    return states;
  }

  showHelp(event) {
    if (this.gameState === GameState.CHOOSING_WORD) {
      this.showNotification('Enter a word for someone else to guess, or choose a random word.');
    } else if (this.gameState === GameState.GUESSING_WORD) {
      this.showNotification(
        'Green (left !): correct letter, correct location\n' +
        'Yellow (right ?): correct letter, wrong location');
    }
  }

  share(event) {
    let text = '';
    if (this.gameState === GameState.GUESSING_WORD) {
      text = 'Here you go! ' + window.location;
    } else if (this.gameState == GameState.COMPLETE) {
      for (let i = 0; i < this.stateList.length; i++) {
        const states = this.stateList[i];
        let correct = 0;
        let elsewhere = 0;
        for (let i = 0; i < states.length; i++) {
          if (states[i] === LetterState.CORRECT) {
            correct++;
          } else if (states[i] === LetterState.ELSEWHERE) {
            elsewhere++;
          }
        }
        text += NUMBERS[correct];
        text += NUMBERS[elsewhere];
        text += '\n';
      }
      text += '\n';
      text += 'https://jkadams.github.io/friendl/#' + encode(this.target);
    }
    if (navigator) {
      if (navigator.share) {
        navigator.share({
          title: 'Friendl',
          text: text
          // url: window.location + '#' + encode(this.target)
        });
      } else if (navigator.clipboard) {
        navigator.clipboard.writeText(text);
        this.showNotification('Copied to clipboard!');
      } else {
        g.showNotification(text, 1000000);
      }
    }
  }

  hideButtons() {
    document.getElementById('random').style.display = 'none';
    document.getElementById('enterword').style.display = 'none';
    document.getElementsByClassName('keys')[0].style.display = 'unset';
  }

  setup() {
    const help = document.getElementById('help');
    help.addEventListener('click', (event) => this.showHelp(), false);
    const share = document.getElementById('share');
    share.addEventListener('click', (event) => this.share(), false);
    const restart = document.getElementById('restart');
    restart.addEventListener('click', (event) => this.forceNewGame(), false);
    const randomButton = document.getElementById('random');
    randomButton.addEventListener('click',
    (event) => this.chooseRandomWord(DEFAULT_WORD_SIZE), false);
    const enterWordButton = document.getElementById('enterword');
    enterWordButton.addEventListener('click',
    (event) => this.hideButtons(), false);
  }

  handleKeyPress(letter) {
    if (g.gameState == GameState.COMPLETE) {
      if (letter === 'r' || letter === ENTER_KEY) {
        g.newGame(DEFAULT_WORD_SIZE);
      }
    } else if (g.gameState == GameState.GUESSING_WORD) {
      if (letter === BACKSPACE_KEY) {
        g.deleteLetterGuess();
      } else if (letter === ENTER_KEY) {
        g.guessWord();
      } else {
        g.typeLetter(letter);
      }
    } else {
      if (letter === BACKSPACE_KEY) {
        g.deleteLetterTarget();
      } else if (letter === ENTER_KEY) {
        g.commitWord();
      } else {
        g.typeLetter(letter);
      }
    }
  }
}

function createKey(letter) {
  const singleKey = document.createElement('button');
  singleKey.innerText = letter;
  singleKey.className = 'key';
  if (letter === BACKSPACE_KEY || letter === ENTER_KEY) {
      singleKey.style.width = '70px';
  }
  singleKey.addEventListener('click', (event) => g.handleKeyPress(letter), false);
  return singleKey;
}

const keyMap = {};
function showKeyboard() {
  const keyboard = document.getElementsByClassName('keys')[0];
  for (var i = 0; i < KEYS.length; i++) {
    const row = document.createElement('div');
    row.className = 'keyrow';
    for (var j = 0; j < KEYS[i].length; j++) {
      const character = KEYS[i].charAt(j);
      const element = createKey(character);
      row.appendChild(element);
      keyMap[character] = element;
    }
    keyboard.appendChild(row);
  }
}

function encode(word) {
  let encoded = '';
  let achar = 'a'.charCodeAt(0);
  word = word.toLowerCase();
  for (let i = 0; i < word.length; i++) {
    let newLet = ((word.charCodeAt(i) - achar) + 11 + 13 * i + 17 * i * i) % 26;
    if (newLet < 10) {
      encoded += '0' + newLet;
    } else {
      encoded += newLet;
    }
  }
  return encoded;
}

function decode(word) {
  let decoded = '';
  let achar = 'a'.charCodeAt(0);
  word = word.toLowerCase();
  try {
    for (let i = 0; i < word.length; i += 2) {
      let newLet = (parseInt(word.substring(i, i + 2), 10) - 11 - 13 * (i / 2) - 17 * (i / 2) * (i / 2) + 260) % 26;
      decoded += String.fromCharCode(achar + newLet);
    }
  } catch (e) {
    return null;
  }
  return decoded;
}

const g = new Game();
function start() {
  showKeyboard();
  g.setup();
  g.newGame();
  if (window.location.hash) {
    const decoded = decode(window.location.hash.substring(1));
    if (decoded) {
      g.chooseWord(decoded);
    }
  }
  // g.chooseRandomWord(DEFAULT_WORD_SIZE);
}

document.addEventListener('keydown', (event) => {
  const keyName = event.key.toLowerCase();
  if (event.ctrlKey || event.metaKey || event.altKey) {
    return;
  }
  let letter = '';
  if (keyName.length === 1 && keyName[0] >= 'a' && keyName[0] <= 'z') {
    letter = keyName;
  } else if (keyName === 'backspace') {
    letter = BACKSPACE_KEY;
  } else if (keyName === 'enter') {
    letter = ENTER_KEY;
  }
  if (letter !== '') {
    g.handleKeyPress(letter);
  }
}, false);


text:
package net.sf.mmm.util.lang.api;

/**
 * This is the interface for a generic visitor that may {@link #visit(Object)} values of a specific type.
 *
 * @param <V> is the generic type to {@link #visit(Object) visit}.
 * @author Joerg Hohwiller (hohwille at users.sourceforge.net)
 * @since 2.0.0
 */
public interface Visitor<V> {

  /**
   * This method is called to let the visitor inspect the given {@code value}.
   *
   * @param value is the value to visit. An API that offers a {@link Visitor} as argument should specify further details
   *        about the value - especially if it may be {@code null}.
   */
  void visit(V value);

}


text:
"""
This example covers the following:
    - Create deployment
    - Annotate deployment
"""

from kubernetes import client, config
import time

def create_deployment_object():
    container = client.V1Container(
        name="nginx-sample",
        image="nginx",
        image_pull_policy="IfNotPresent",
        ports=[client.V1ContainerPort(container_port=80)],
    )
    # Template
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={"app": "nginx"}),
        spec=client.V1PodSpec(containers=[container]))
    # Spec
    spec = client.V1DeploymentSpec(
        replicas=1,
        selector=client.V1LabelSelector(
            match_labels={"app": "nginx"}
        ),
        template=template)
    # Deployment
    deployment = client.V1Deployment(
        api_version="apps/v1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name="deploy-nginx"),
        spec=spec)

    return deployment

def create_deployment(apps_v1_api, deployment_object):
    # Create the Deployment in default namespace
    # You can replace the namespace with you have created
    apps_v1_api.create_namespaced_deployment(
        namespace="default", body=deployment_object
    )

def annotate_deployment(apps_v1_api, deployment_name, annotations):
    # Annotate the Deployment in default namespace
    # You can replace the namespace with you have created
    apps_v1_api.patch_namespaced_deployment(
        name=deployment_name, namespace='default', body=annotations)

def main():
    # Loading the local kubeconfig
    config.load_kube_config()
    apps_v1_api = client.AppsV1Api()
    deployment_obj = create_deployment_object()

    create_deployment(apps_v1_api, deployment_obj)
    time.sleep(1)
    before_annotating = apps_v1_api.read_namespaced_deployment(
        'deploy-nginx', 'default')
    print('Before annotating, annotations: %s' %
          before_annotating.metadata.annotations)

    annotations = [
        {
            'op': 'add',  # You can try different operations like 'replace', 'add' and 'remove'
            'path': '/metadata/annotations',
            'value': {
                'deployment.kubernetes.io/str': 'nginx',
                'deployment.kubernetes.io/int': '5'
            }
        }
    ]

    annotate_deployment(apps_v1_api, 'deploy-nginx', annotations)
    time.sleep(1)
    after_annotating = apps_v1_api.read_namespaced_deployment(
        name='deploy-nginx', namespace='default')
    print('After annotating, annotations: %s' %
          after_annotating.metadata.annotations)

if __name__ == "__main__":
    main()


text:
package org.springframework.social.linkedin.api.impl.json;

import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

final class StringListDeserializer extends JsonDeserializer<List<String>>  {

	public List<String> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		return DeserializationUtils.deserializeFromDataNode(jp, ctxt, "values", new TypeReference<List<String>>() {});
	}

}


text:
package io.cdap.wrangler.proto.workspace;

/**
 * The DataModelRequest object contains the properties for adding a DataModel to the workspace.
 */
public final class DataModelRequest {

  private final String id;
  private final Long revision;

  public DataModelRequest(String id, Long revision) {
    this.id = id;
    this.revision = revision;
  }

  public String getId() {
    return this.id;
  }

  public Long getRevision() {
    return this.revision;
  }
}


text:
classdef  MovieObject < hgsetget
    % Abstract interface defining the analyis tools for movie objects
    % (movies, movie lists...)
%
% Copyright (C) 2014 LCCB
%
% This file is part of u-track.
%
% u-track is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% u-track is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with u-track.  If not, see <http://www.gnu.org/licenses/>.
%
%

    % Sebastien Besson, Jan 2012

    properties (SetAccess = protected)
        createTime_             % Object creation time
        processes_ = {};        % Cell array of process objects
        packages_ = {};         % Cell array of process packaged
    end

    properties
        outputDirectory_  ='';      % Default output directory for all processes
        notes_                  % User's notes

        % For OMERO objects
        omeroId_
        omeroSave_ = false
    end

    properties (Transient =true)
        omeroSession_
    end

    methods
        %% Set/get methods
        function set.outputDirectory_(obj, path)
            % Set the ouput
            endingFilesepToken = [regexptranslate('escape',filesep) '$'];
            path = regexprep(path,endingFilesepToken,'');
            obj.checkPropertyValue('outputDirectory_',path);
            obj.outputDirectory_=path;
        end

        function checkPropertyValue(obj,property, value)
            % Check if a property/value pair can be set up

            % Test if the property is unchanged
            if isequal(obj.(property),value), return; end

            propName = regexprep(regexprep(property,'(_\>)',''),'([A-Z])',' ${lower($1)}');
            % Test if the property is writable
            assert(obj.checkProperty(property),'lccb:set:readonly',...
                ['The ' propName ' has been set previously and cannot be changed!']);

            % Test if the supplied value is valid
            assert(obj.checkValue(property,value),'lccb:set:invalid',...
                ['The supplied ' propName ' is invalid!']);
        end

        function status = checkProperty(obj,property)
            % Returns true/false if the non-empty property is writable
            status = isempty(obj.(property));
            if status, return; end

            % Allow user to rewrite on some properties (paths, outputDirectory, notes)
            switch property
                case {'notes_'};
                    status = true;
                case {'outputDirectory_',obj.getPathProperty,obj.getFilenameProperty};
                    stack = dbstack;
                    if any(cellfun(@(x)strcmp(x,[class(obj) '.sanityCheck']),{stack.name})),
                        status  = true;
                    end
            end
        end

        function set.notes_(obj, value)
            obj.checkPropertyValue('notes_',value);
            obj.notes_=value;
        end

        function value = getPath(obj)
            value = obj.(obj.getPathProperty);
        end

        function setPath(obj, value)
            obj.(obj.getPathProperty) = value;
        end

        function value = getFilename(obj)
            value = obj.(obj.getFilenameProperty);
        end

        function setFilename(obj, value)
            obj.(obj.getFilenameProperty) = value;
        end

        function fullPath = getFullPath(obj, askUser)
            % Return full path of the movie object

            if nargin < 2, askUser = true; end
            hasEmptyComponent = isempty(obj.getPath) || isempty(obj.getFilename);
            hasDisplay = feature('ShowFigureWindows');

            if any(hasEmptyComponent) && askUser && hasDisplay
                if ~isempty(obj.getPath),
                    defaultDir = obj.getPath;
                elseif ~isempty(obj.outputDirectory_)
                    defaultDir = obj.outputDirectory_;
                else
                    defaultDir = pwd;
                end

                % Open a dialog box asking where to save the movie object
                movieClass = class(obj);
                objName = regexprep(movieClass,'([A-Z])',' ${lower($1)}');
                defaultName = regexprep(movieClass,'(^[A-Z])','${lower($1)}');
                [filename,path] = uiputfile('*.mat',['Find a place to save your' objName],...
                    [defaultDir filesep defaultName '.mat']);

                if ~any([filename,path]),
                    fullPath=[];
                else
                    fullPath = [path, filename];
                    % Set new path and filename
                    obj.setPath(path);
                    obj.setFilename(filename);
                end
            else
                if all(hasEmptyComponent),
                    fullPath = '';
                else
                    fullPath = fullfile(obj.getPath(), obj.getFilename());
                end
            end

        end
        %% Functions to manipulate process object array
        function addProcess(obj, newprocess)
            % Add new process in process list
            assert(isa(newprocess,'Process'));
            obj.processes_ = horzcat(obj.processes_, {newprocess});
        end

        function proc = getProcess(obj, i)
            assert(isscalar(i) && ismember(i,1:numel(obj.processes_)));
            proc = obj.processes_{i};
        end

        function deleteProcess(obj, process)
            % Delete given process object in process list
            %
            % Input:
            %        process - Process object or index of process to be
            %                  deleted in movie data's process list

            % Check input
            if isa(process, 'Process')
                pid = obj.getProcessIndex(process,1,Inf,false);
                assert(~isempty(pid),'The given process is not in current movie processes list.')
                assert(length(pid)==1,'More than one process of this type exists in movie processes list.')
            elseif isscalar(process) && ismember(process,1:numel(obj.processes_))
                pid = process;
            else
                error('Please provide a Process object or a valid process index of movie data processes list.')
            end

            % Check process validity
            process = obj.processes_{pid};
            isValid = ~isempty(process) && process.isvalid;

            if isValid
                % Unassociate process from parent packages
                [packageID procID] = process.getPackage();
                for i=1:numel(packageID)
                    obj.packages_{packageID(i)}.setProcess(procID(i),[]);
                end
            end

            if isValid && isa(process.owner_, 'MovieData')
                % Remove process from list for owner and descendants
                for movie = [process.owner_ process.owner_.getDescendants()]
                    id = find(cellfun(@(x) isequal(x,process), movie.processes_),1);
                    if ~isempty(id), movie.processes_(id) = [ ]; end
                end
            else
                obj.processes_(pid) = [ ];
            end

            % Delete process object
            if isValid, delete(process); end
        end

        function replaceProcess(obj, pid, newprocess)
            % Replace process object by another in the analysis list

            % Input check
            ip=inputParser;
            ip.addRequired('pid', @(x) isa(x,'Process') || ...
                isnumeric(x) && ismember(x, 1:numel(obj.processes_)));
            ip.addRequired('newprocess', @(x) isa(x,'Process'));
            ip.parse(pid, newprocess);

            % Retrieve process index if input is of process type
            if isa(pid, 'Process')
                pid = find(cellfun(@(x)(isequal(x,pid)), obj.processes_));
                assert(isscalar(pid))
            end

            [packageID, procID] = obj.getProcess(pid).getPackage;

            % Check new process is compatible with parent packages
            if ~isempty(packageID)
                for i=1:numel(packageID)
                    isValid = isa(newprocess,...
                        obj.getPackage(packageID(i)).getProcessClassNames{procID(i)});
                    assert(isValid, 'Package class compatibility prevents process process replacement');
                end
            end

            % Delete old process and replace it by the new one
            oldprocess = obj.getProcess(pid);
            if isa(oldprocess.owner_, 'MovieData')
                % Remove process from list for owner and descendants
                for movie = [oldprocess.owner_ oldprocess.owner_.getDescendants()]
                    id = find(cellfun(@(x) isequal(x, oldprocess), movie.processes_),1);
                    if ~isempty(id), movie.processes_{id} = newprocess; end
                end
            else
                obj.processes_{pid} = newprocess;
            end
            delete(oldprocess);

            % Associate new process in parent packages
            if ~isempty(packageID),
                for i=1:numel(packageID)
                    obj.getPackage(packageID(i)).setProcess(procID(i),newprocess);
                end
            end
        end

        function iProc = getProcessIndex(obj, type, varargin)
            if isa(type, 'Process'), type = class(type); end
            iProc = getIndex(obj.processes_, type, varargin{:});
        end

        %% Functions to manipulate package object array
        function addPackage(obj, newpackage)
            % Add package object to the package list
            assert(isa(newpackage,'Package'));
            obj.packages_ = horzcat(obj.packages_ , {newpackage});
        end

        function package = getPackage(obj, i)
            assert(isscalar(i) && ismember(i,1:numel(obj.packages_)));
            package = obj.packages_{i};
        end

        function deletePackage(obj, package)
            % Remove package object from the package list

            % Check input
            if isa(package, 'Package')
                pid = find(cellfun(@(x)isequal(x, package), obj.packages_));
                assert(~isempty(pid),'The given package is not in current movie packages list.')
                assert(length(pid)==1,'More than one package of this type exists in movie packages list.')
            elseif isscalar(package) && ismember(package,1:numel(obj.packages_))
                pid = package;
            else
                error('Please provide a Package object or a valid package index of movie data processes list.')
            end

            % Check package validity
            package = obj.packages_{pid};
            isValid = ~isempty(package) && package.isvalid;

            if isValid && isa(package.owner_, 'MovieData')
                % Remove package from list for owner and descendants
                for movie = [package.owner_ package.owner_.getDescendants()]
                    id = find(cellfun(@(x) isequal(x,package), movie.packages_),1);
                    if ~isempty(id), movie.packages_(id) = [ ]; end
                end
            else
                obj.packages_(pid) = [ ];
            end

            % Delete package object
            if isValid, delete(package); end
        end

        function iPackage = getPackageIndex(obj, type, varargin)
            if isa(type, 'Package'), type = class(type); end
            iPackage = getIndex(obj.packages_, type, varargin{:});
        end
        %% Miscellaneous functions
        function askUser = sanityCheck(obj, path, filename,askUser)
            % Check sanity of movie object
            %
            % Check if the path and filename stored in the movie object are
            % the same as the input if any. If they differ, call the
            % movie object relocation routine. Use a dialog interface to ask
            % for relocation if askUser is set as true and return askUser.

            if nargin < 4, askUser = true; end
            if nargin > 1 && ~isempty(path)
                % Remove ending file separators from paths
                endingFilesepToken = [regexptranslate('escape',filesep) '$'];
                oldPath = regexprep(obj.getPath(),endingFilesepToken,'');
                newPath = regexprep(path,endingFilesepToken,'');

                % If different path
                if ~strcmp(oldPath, newPath)
                    confirmRelocate = 'Yes to all';
                    if askUser
                        if isa(obj,'MovieData')
                            type='movie';
                            components='channels';
                        elseif isa(obj,'MovieList')
                            type='movie list';
                            components='movies';
                        else
                            error('Non supported movie object');
                        end
                        relocateMsg=sprintf(['The %s and its analysis will be relocated from \n%s to \n%s.\n'...
                            'Should I relocate its %s as well?'],type,oldPath,newPath,components);
                        confirmRelocate = questdlg(relocateMsg,['Relocation - ' type],'Yes to all','Yes','No','Yes');
                    end

                    full = ~strcmp(confirmRelocate,'No');
                    askUser = ~strcmp(confirmRelocate,'Yes to all');
                    % Get old and new relocation directories
                    [oldRootDir newRootDir]=getRelocationDirs(oldPath,newPath);
                    oldRootDir = regexprep(oldRootDir,endingFilesepToken,'');
                    newRootDir = regexprep(newRootDir,endingFilesepToken,'');

                    % Relocate the object
                    fprintf(1,'Relocating analysis from %s to %s\n',oldRootDir,newRootDir);
                    obj.relocate(oldRootDir,newRootDir,full);
                end
            end
            if nargin > 2 && ~isempty(filename), obj.setFilename(filename); end

            if isempty(obj.outputDirectory_), warning('lccb:MovieObject:sanityCheck',...
                    'Empty output directory!'); end
        end

        function relocate(obj,oldRootDir,newRootDir)
            % Relocate all analysis paths of the movie object
            %
            % The relocate method automatically relocates the output directory,
            % as well as the paths in each process and package of the movie
            % assuming the internal architecture of the  project is conserved.

            % Relocate output directory and set the ne movie path
            obj.outputDirectory_=relocatePath(obj.outputDirectory_,oldRootDir,newRootDir);
            obj.setPath(relocatePath(obj.getPath,oldRootDir,newRootDir));

            % Relocate the processes
            for i=1:numel(obj.processes_), obj.processes_{i}.relocate(oldRootDir,newRootDir); end

            % Relocate the packages
            for i=1:numel(obj.packages_), obj.packages_{i}.relocate(oldRootDir,newRootDir); end
        end

        function reset(obj)
            % Reset the analysis of the movie object
            obj.processes_={};
            obj.packages_={};
        end

        %% OMERO functions
        function status = isOmero(obj)
            status = ~isempty(obj.omeroId_);
        end

        function setOmeroSession(obj,session)
            obj.omeroSession_ = session;
        end

        function session = getOmeroSession(obj)
            session = obj.omeroSession_;
        end

        function setOmeroSave(obj, status)
            obj.omeroSave_ = status;
        end

        function id = getOmeroId(obj)
            id = obj.omeroId_;
        end

        function setOmeroId(obj, id)
            obj.checkPropertyValue('omeroId_', id);
            obj.omeroId_ = id;
        end

        function status = canUpload(obj)
            status = obj.omeroSave_ && ~isempty(obj.getOmeroSession());
        end

    end

    methods(Static)
        function obj = load(varargin)
            % Load/reaload a movie object

            assert(nargin > 0);
            assert(MovieObject.isOmeroSession(varargin{1}) || ...
                exist(varargin{1}, 'file') == 2)

            if MovieObject.isOmeroSession(varargin{1}),
                obj = MovieObject.loadOmero(varargin{:});
            else
                isMatFile = strcmpi(varargin{1}(end-3:end), '.mat');
                if isMatFile,
                    obj = MovieObject.loadMatFile(varargin{:});
                else
                    obj = MovieObject.loadImageFile(varargin{:});
                end
            end
        end

        function obj = loadMatFile(filepath, varargin)

            % Retrieve the absolute path
            [~, f] = fileattrib(filepath);
            filepath = f.Name;

            % Import movie object from MAT file
            try
                % List variables in the path
                vars = whos('-file', filepath);
            catch whosException
                ME = MException('lccb:movieObject:load', 'Fail to open file. Make sure it is a MAT file.');
                ME = ME.addCause(whosException);
                throw(ME);
            end

            % Check if a single movie object is in the variables
            isMovie = cellfun(@(x) any(strcmp(superclasses(x),'MovieObject')),{vars.class});
            assert(any(isMovie),'lccb:movieObject:load', ...
                'No movie object is found in selected MAT file.');
            assert(sum(isMovie)==1,'lccb:movieObject:load', ...
                'Multiple movie objects are found in selected MAT file.');

            % Load movie object
            data = load(filepath, '-mat', vars(isMovie).name);
            obj= data.(vars(isMovie).name);

            % Perform sanityCheck using the input path
            [moviePath,movieName,movieExt]=fileparts(filepath);
            if nargin>1 &&  MovieObject.isOmeroSession(varargin{1}),
                obj.setOmeroSession(varargin{1});
                obj.sanityCheck(moviePath,[movieName movieExt], varargin{2:end});
            else
                obj.sanityCheck(moviePath,[movieName movieExt], varargin{:});
            end
        end

        function obj = loadImageFile(imagepath, varargin)
            % Retrieve the absolute path
            [~, f] = fileattrib(imagepath);
            imagepath = f.Name;

            obj = bfImport(imagepath, varargin{:});
        end

        function obj = loadOmero(session, varargin)
            obj = getOmeroMovies(session, varargin{:});
        end

        function validator = getPropertyValidator(property)
            validator=[];
            if ismember(property,{'outputDirectory_','notes_'})
                validator=@ischar;
            elseif strcmp(property, 'omeroId_')
                validator = @isposint;
            end
        end

        function status = isOmeroSession(session)
            status = isa(session, 'omero.api.ServiceFactoryPrxHelper');
        end

    end
    methods (Static,Abstract)
        getPathProperty()
        getFilenameProperty()
    end
end

function iProc = getIndex(list, type, varargin)
% Find the index of a object of given class

% Input check
ip = inputParser;
ip.addRequired('list',@iscell);
ip.addRequired('type',@ischar);
ip.addOptional('nDesired',1,@isscalar);
ip.addOptional('askUser',true,@isscalar);
ip.parse(list, type, varargin{:});
nDesired = ip.Results.nDesired;
askUser = ip.Results.askUser;

iProc = find(cellfun(@(x) isa(x,type), list));
nProc = numel(iProc);

%If there are only nDesired or less processes found, return
if nProc <= nDesired, return; end

% If more than nDesired processes
if askUser
    isMultiple = nDesired > 1;
    names = cellfun(@(x) (x.getName()), list(iProc), 'UniformOutput', false);
    iSelected = listdlg('ListString', names,...
        'SelectionMode', isMultiple, 'ListSize', [400,400],...
        'PromptString', ['Select the desired ' type ':']);
    iProc = iProc(iSelected);
    assert(~isempty(iProc), 'You must select a process to continue!');
else
    warning('lccb:process', ['More than ' num2str(nDesired) ' objects '...
        'of class ' type ' were found! Returning most recent!'])
    iProc = iProc(end:-1:(end-nDesired+1));
end
end


text:
module.exports.twitterUrl = function twitterUrl(username) {
    // Creates the canonical twitter URL without the '@'
    return 'https://twitter.com/' + username.replace(/^@/, '');
};

module.exports.facebookUrl = function facebookUrl(username) {
    // Handles a starting slash, this shouldn't happen, but just in case
    return 'https://www.facebook.com/' + username.replace(/^\//, '');
};

module.exports.weiboUrl = function weiboUrl(username) {
    // Handles a starting slash, this shouldn't happen, but just in case
    return 'https://www.weibo.com/' + username.replace(/^\//, '');
};


text:
package com.pw.ord.dao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SQLInsertBuilder {

    private final List<String> columns;
    private final List<Object> params;
    private final String table;

    public SQLInsertBuilder(String tableName) {
        this.columns = new ArrayList<String>();
        this.params = new ArrayList<Object>();
        this.table = tableName;
    }

    public SQLInsertBuilder appendColumn(String column, Object value) {
        this.columns.add(column);
        this.params.add(value);
        return this;
    }

    public String getSQL() {
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT INTO ").append(table).append(" (");

        StringBuilder values = new StringBuilder();
        values.append("values (");
        for (Iterator<String> iterator = columns.iterator(); iterator.hasNext();) {
            String column = (String) iterator.next();
            sql.append(column);
            values.append("?");
            if (iterator.hasNext()) {
                sql.append(", ");
                values.append(", ");
            } else {
                sql.append(") ");
                values.append(") ");
            }
        }
        return sql.append(values).toString();
    }

    public Object[] getParams() {
        return params.toArray();
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>All Classes</title>
<meta name="date" content="2013-10-20">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

BenchHtml

Benchmarks

ChartTrend

Combo

Config

dalHelper

db_Helper

Email

ExternalCmd

fsdalHelper

Html

LineXYDataset

Main

oracledalHelper

PlatformHtml

Platforms

ScatterXYDataset

statsUtils

SummaryHtml

TopLevelHtml

TrendDefaultType

TrendResultsHelper

TrendStruct

TTest

TTestHelper

Util

VersionHtml

WorkloadHtml


text:
using NDepthFirst::Bipartile;

TEST_F(TEmptyGraph, Bipartile) {
    TBipartilePtr b {Bipartile(*Graph)};
    EXPECT_FALSE(b->Bipartile());
    EXPECT_THROW(b->Color(0), std::out_of_range);
}

TEST_F(TSingleVertex, Bipartile) {
    TBipartilePtr b {Bipartile(*Graph)};
    EXPECT_FALSE(b->Bipartile());
}

TEST_F(TLoop, Bipartile) {
    TBipartilePtr b {Bipartile(*Graph)};
    EXPECT_FALSE(b->Bipartile());
}

TEST_F(TTwoVertices, Bipartile) {
    TBipartilePtr b {Bipartile(*Graph)};
    EXPECT_TRUE(b->Bipartile());
    EXPECT_TRUE(b->Color(0));
    EXPECT_TRUE(b->Color(1));
}

TEST_F(TTwoConnectedVertices, Bipartile) {
    TBipartilePtr b {Bipartile(*Graph)};
    EXPECT_TRUE(b->Bipartile());
    EXPECT_TRUE(b->Color(0));
    EXPECT_FALSE(b->Color(1));
}

TEST_F(TTriangle, Bipartile) {
    TBipartilePtr b {Bipartile(*Graph)};
    EXPECT_FALSE(b->Bipartile());
    EXPECT_TRUE(b->Color(0));
    EXPECT_FALSE(b->Color(1));
    EXPECT_TRUE(b->Color(2));
}

TEST_F(TThreeConnectedVertices, Bipartile) {
    TBipartilePtr b {Bipartile(*Graph)};
    EXPECT_TRUE(b->Bipartile());
    EXPECT_TRUE(b->Color(0));
    EXPECT_FALSE(b->Color(1));
    EXPECT_TRUE(b->Color(2));
}

int main(int argc, char *argv[]) {
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


text:
package com.amazonaws.services.devicefarm.model;

import javax.annotation.Generated;

/**
 * <p>
 * The requested object could not be deleted.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CannotDeleteException extends com.amazonaws.services.devicefarm.model.AWSDeviceFarmException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new CannotDeleteException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public CannotDeleteException(String message) {
        super(message);
    }

}


text:
package endtoend.objc;

import static org.hamcrest.MatcherAssert.assertThat;
import static utils.matchers.ResultContainsErrorInMethod.contains;
import static utils.matchers.ResultContainsNoErrorInMethod.doesNotContain;

import com.google.common.collect.ImmutableList;

import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;

import java.io.IOException;

import utils.DebuggableTemporaryFolder;
import utils.InferException;
import utils.InferResults;
import utils.InferRunner;

public class NoMemoryLeakBlockIteratorTest {

  public static final String block_file =
      "infer/tests/codetoanalyze/objc/frontend/block/block-it.m";

  private static ImmutableList<String> inferCmd;

  public static final String MEMORY_LEAK = "MEMORY_LEAK";

  @ClassRule
  public static DebuggableTemporaryFolder folder = new DebuggableTemporaryFolder();

  @BeforeClass
  public static void runInfer() throws InterruptedException, IOException {
    inferCmd = InferRunner.createObjCInferCommandWithMLBuckets(
        folder,
        block_file,
        "cf",
        false);
  }

  @Test
  public void whenInferRunsOnLayoutSubviewsThenMLIsNotFound()
      throws InterruptedException, IOException, InferException {
    InferResults inferResults = InferRunner.runInferObjC(inferCmd);
    assertThat(
        "Results should not contain memory leak",
        inferResults,
        doesNotContain(
            MEMORY_LEAK,
            block_file,
            "array"));
  }
}


text:
define(['backbone', 'interactioncoordinator'], function(Backbone, coordinator) {

  var View = Backbone.View.extend({

    initialize: function() {
      this.showing = true;
      this.render();
      this.toggle();
      $('body').append(this.$el);
      coordinator.on('keyup', this.keyup, this);
    },

    render: function() {
      var stats = new Stats();
      stats.setMode(0);
      stats.domElement.style.position = 'absolute';
      stats.domElement.style.left = '0px';
      stats.domElement.style.bottom = '0px';
      this.$el = $(stats.domElement);
      setInterval( function () {
        stats.begin();
        stats.end();
      }, 1000 / 60 );
    },

    keyup: function(event) {
      if (event.keyCode === 68) {
        this.toggle();
      }
    },

    toggle: function() {
      if (this.showing) {
        this.$el.hide();
      } else {
        this.$el.show();
      }
      this.showing = !this.showing;
    },

  });

  return View;

});


text:
use strict;
use 5.6.1;
use Irssi;
use Irssi::TextUI;

my $VERSION = "1.4";

my %IRSSI = (
    authors     => "Peter 'kinlo' Leurs",
    contact     => "peter\@pfoe.be",
    name        => "trackbar",
    description => "Shows a bar where you've last read a window",
    license     => "GPLv2",
    url         => "http://www.pfoe.be/~peter/trackbar/",
    changed     => "Thu Feb 20 16:18:08 2003",
);

my %config;

Irssi::settings_add_str('trackbar', 'trackbar_string' => '_');
$config{'trackbar_string'} = Irssi::settings_get_str('trackbar_string');

Irssi::settings_add_str('trackbar', 'trackbar_style' => '%K');
$config{'trackbar_style'} = Irssi::settings_get_str('trackbar_style');

Irssi::signal_add(
    'setup changed' => sub {
        $config{'trackbar_string'} = Irssi::settings_get_str('trackbar_string');
        $config{'trackbar_style'}  = Irssi::settings_get_str('trackbar_style');
        if ($config{'trackbar_style'} =~ /(?<!%)[^%]|%%|%$/) {
            Irssi::print(
                "trackbar: %RWarning!%n 'trackbar_style' seems to contain "
                . "printable characters. Only use format codes (read "
                . "formats.txt).", MSGLEVEL_CLIENTERROR);
        }
    }
);

Irssi::signal_add(
    'window changed' => sub {
        my (undef, $oldwindow) = @_;

        if ($oldwindow) {
            my $line = $oldwindow->view()->get_bookmark('trackbar');
            $oldwindow->view()->remove_line($line) if defined $line;
            $oldwindow->print(line($oldwindow->{'width'}), MSGLEVEL_NEVER);
            $oldwindow->view()->set_bookmark_bottom('trackbar');
        }
    }
);

sub line {
    my $width  = shift;
    my $string = $config{'trackbar_string'};
    $string = '-' unless defined $string;

    # There is a bug in irssi's utf-8 handling on config file settings, as you
    # can reproduce/see yourself by the following code sniplet:
    #
    #   my $quake = pack 'U*', 8364;    # EUR symbol
    #   Irssi::settings_add_str 'temp', 'temp_foo' => $quake;
    #   Irssi::print length $quake;
    #       # prints 1
    #   Irssi::print length Irssi::settings_get_str 'temp_foo';
    #       # prints 3
    #
    #
    # Trackbar used to have a workaround, but on recent versions of perl/irssi
    # it does no longer work.  Therefore, if you want your trackbar to contain
    # unicode characters, uncomment the line below for a nice full line, or set
    # the string to whatever char you want.

    # $string = pack('U*', 0x2500);

    my $length = length $string;

    if ($length == 0) {
        $string = '-';
        $length = 1;
    }

    my $times = $width / $length;
    $times = int(1 + $times) if $times != int($times);
    $string =~ s/%/%%/g;
    return $config{'trackbar_style'} . substr($string x $times, 0, $width);
}

# Remove trackbars on upgrade - but this doesn't really work if the scripts are not loaded in the correct order... watch out!

Irssi::signal_add_first( 'session save' => sub {
	    for my $window (Irssi::windows) {
		next unless defined $window;
		my $line = $window->view()->get_bookmark('trackbar');
		$window->view()->remove_line($line) if defined $line;
	    }
	}
);

sub cmd_mark {
    my $window = Irssi::active_win();
#    return unless defined $window;
    my $line = $window->view()->get_bookmark('trackbar');
    $window->view()->remove_line($line) if defined $line;
    $window->print(line($window->{'width'}), MSGLEVEL_NEVER);
    $window->view()->set_bookmark_bottom('trackbar');
    Irssi::command("redraw");
}

Irssi::command_bind('mark',   'cmd_mark');


text:
angular.module('myApp.controllers')
	.controller('listingController', ['$scope', 'settings', 'courseProvider',
		function($scope, settings, courseProvider) {

			$scope.maxLength = settings.maxDescriptionLength;
			$scope.maxResults = settings.maxResults;

			/*courseProvider.getCourses().success(function (data){
				$scope.courses = data;
			});*/
	 courseProvider.getCourses().$promise.then(function(data){
	 		$scope.courses=data;
	});
			/*$scope.showCourseDetails = function(course){
				courseProvider.selectedCourse = course;
				$nonsense.url('/details');
			}*/
		}
	]);