_id
stringlengths 2
7
| title
stringlengths 1
118
| partition
stringclasses 3
values | text
stringlengths 52
85.5k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q6600
|
CompareDepth
|
train
|
func CompareDepth(op syntax.Token, x, y Value, depth int) (bool, error) {
if depth < 1 {
return false, fmt.Errorf("comparison exceeded maximum recursion depth")
}
if sameType(x, y) {
if xcomp, ok := x.(Comparable); ok {
return xcomp.CompareSameType(op, y, depth)
}
// use identity comparison
switch op {
case syntax.EQL:
return x == y, nil
case syntax.NEQ:
return x != y, nil
}
return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type())
}
// different types
// int/float ordered comparisons
switch x := x.(type) {
case Int:
if y, ok := y.(Float); ok {
if y != y {
return false, nil // y is NaN
}
var cmp int
if !math.IsInf(float64(y), 0) {
cmp = x.rational().Cmp(y.rational()) // y is finite
} else if y > 0 {
cmp = -1 // y is +Inf
} else {
cmp = +1 // y is -Inf
}
return threeway(op, cmp), nil
}
case Float:
if y, ok := y.(Int); ok {
if x != x {
return false, nil // x is NaN
}
var cmp int
if !math.IsInf(float64(x), 0) {
cmp = x.rational().Cmp(y.rational()) // x is finite
} else if x > 0 {
cmp = -1 // x is +Inf
} else {
cmp = +1 // x is -Inf
}
return threeway(op, cmp), nil
}
}
// All other values of different types compare unequal.
switch op {
case syntax.EQL:
return false, nil
case syntax.NEQ:
return true, nil
}
return false, fmt.Errorf("%s %s %s not implemented", x.Type(), op, y.Type())
}
|
go
|
{
"resource": ""
}
|
q6601
|
dump
|
train
|
func (ht *hashtable) dump() {
fmt.Printf("hashtable %p len=%d head=%p tailLink=%p",
ht, ht.len, ht.head, ht.tailLink)
if ht.tailLink != nil {
fmt.Printf(" *tailLink=%p", *ht.tailLink)
}
fmt.Println()
for j := range ht.table {
fmt.Printf("bucket chain %d\n", j)
for p := &ht.table[j]; p != nil; p = p.next {
fmt.Printf("bucket %p\n", p)
for i := range p.entries {
e := &p.entries[i]
fmt.Printf("\tentry %d @ %p hash=%d key=%v value=%v\n",
i, e, e.hash, e.key, e.value)
fmt.Printf("\t\tnext=%p &next=%p prev=%p",
e.next, &e.next, e.prevLink)
if e.prevLink != nil {
fmt.Printf(" *prev=%p", *e.prevLink)
}
fmt.Println()
}
}
}
}
|
go
|
{
"resource": ""
}
|
q6602
|
hashString
|
train
|
func hashString(s string) uint32 {
if len(s) >= 12 {
// Call the Go runtime's optimized hash implementation,
// which uses the AESENC instruction on amd64 machines.
return uint32(goStringHash(s, 0))
}
return softHashString(s)
}
|
go
|
{
"resource": ""
}
|
q6603
|
softHashString
|
train
|
func softHashString(s string) uint32 {
var h uint32
for i := 0; i < len(s); i++ {
h ^= uint32(s[i])
h *= 16777619
}
return h
}
|
go
|
{
"resource": ""
}
|
q6604
|
ParseExpr
|
train
|
func ParseExpr(filename string, src interface{}, mode Mode) (expr Expr, err error) {
in, err := newScanner(filename, src, mode&RetainComments != 0)
if err != nil {
return nil, err
}
p := parser{in: in}
defer p.in.recover(&err)
p.nextToken() // read first lookahead token
expr = p.parseTest()
// A following newline (e.g. "f()\n") appears outside any brackets,
// on a non-blank line, and thus results in a NEWLINE token.
if p.tok == NEWLINE {
p.nextToken()
}
if p.tok != EOF {
p.in.errorf(p.in.pos, "got %#v after expression, want EOF", p.tok)
}
p.assignComments(expr)
return expr, nil
}
|
go
|
{
"resource": ""
}
|
q6605
|
nextToken
|
train
|
func (p *parser) nextToken() Position {
oldpos := p.tokval.pos
p.tok = p.in.nextToken(&p.tokval)
// enable to see the token stream
if debug {
log.Printf("nextToken: %-20s%+v\n", p.tok, p.tokval.pos)
}
return oldpos
}
|
go
|
{
"resource": ""
}
|
q6606
|
parseLambda
|
train
|
func (p *parser) parseLambda(allowCond bool) Expr {
lambda := p.nextToken()
var params []Expr
if p.tok != COLON {
params = p.parseParams()
}
p.consume(COLON)
var body Expr
if allowCond {
body = p.parseTest()
} else {
body = p.parseTestNoCond()
}
return &LambdaExpr{
Lambda: lambda,
Function: Function{
StartPos: lambda,
Params: params,
Body: []Stmt{&ReturnStmt{Result: body}},
},
}
}
|
go
|
{
"resource": ""
}
|
q6607
|
parsePrimaryWithSuffix
|
train
|
func (p *parser) parsePrimaryWithSuffix() Expr {
x := p.parsePrimary()
for {
switch p.tok {
case DOT:
dot := p.nextToken()
id := p.parseIdent()
x = &DotExpr{Dot: dot, X: x, Name: id}
case LBRACK:
x = p.parseSliceSuffix(x)
case LPAREN:
x = p.parseCallSuffix(x)
default:
return x
}
}
}
|
go
|
{
"resource": ""
}
|
q6608
|
flattenAST
|
train
|
func flattenAST(root Node) (pre, post []Node) {
stack := []Node{}
Walk(root, func(n Node) bool {
if n != nil {
pre = append(pre, n)
stack = append(stack, n)
} else {
post = append(post, stack[len(stack)-1])
stack = stack[:len(stack)-1]
}
return true
})
return pre, post
}
|
go
|
{
"resource": ""
}
|
q6609
|
isCasedString
|
train
|
func isCasedString(s string) bool {
for _, r := range s {
if 'a' <= r && r <= 'z' || 'A' <= r && r <= 'Z' || unicode.SimpleFold(r) != r {
return true
}
}
return false
}
|
go
|
{
"resource": ""
}
|
q6610
|
MakeInt64
|
train
|
func MakeInt64(x int64) Int {
if 0 <= x && x < int64(len(smallint)) {
if !smallintok {
panic("MakeInt64 used before initialization")
}
return Int{&smallint[x]}
}
return Int{new(big.Int).SetInt64(x)}
}
|
go
|
{
"resource": ""
}
|
q6611
|
MakeUint64
|
train
|
func MakeUint64(x uint64) Int {
if x < uint64(len(smallint)) {
if !smallintok {
panic("MakeUint64 used before initialization")
}
return Int{&smallint[x]}
}
return Int{new(big.Int).SetUint64(uint64(x))}
}
|
go
|
{
"resource": ""
}
|
q6612
|
Int64
|
train
|
func (i Int) Int64() (_ int64, ok bool) {
x, acc := bigintToInt64(i.bigint)
if acc != big.Exact {
return // inexact
}
return x, true
}
|
go
|
{
"resource": ""
}
|
q6613
|
Uint64
|
train
|
func (i Int) Uint64() (_ uint64, ok bool) {
x, acc := bigintToUint64(i.bigint)
if acc != big.Exact {
return // inexact
}
return x, true
}
|
go
|
{
"resource": ""
}
|
q6614
|
Float
|
train
|
func (i Int) Float() Float {
// TODO(adonovan): opt: handle common values without allocation.
f, _ := new(big.Float).SetInt(i.bigint).Float64()
return Float(f)
}
|
go
|
{
"resource": ""
}
|
q6615
|
AsInt32
|
train
|
func AsInt32(x Value) (int, error) {
i, ok := x.(Int)
if !ok {
return 0, fmt.Errorf("got %s, want int", x.Type())
}
if i.bigint.BitLen() <= 32 {
v := i.bigint.Int64()
if v >= math.MinInt32 && v <= math.MaxInt32 {
return int(v), nil
}
}
return 0, fmt.Errorf("%s out of range", i)
}
|
go
|
{
"resource": ""
}
|
q6616
|
NumberToInt
|
train
|
func NumberToInt(x Value) (Int, error) {
switch x := x.(type) {
case Int:
return x, nil
case Float:
f := float64(x)
if math.IsInf(f, 0) {
return zero, fmt.Errorf("cannot convert float infinity to integer")
} else if math.IsNaN(f) {
return zero, fmt.Errorf("cannot convert float NaN to integer")
}
return finiteFloatToInt(x), nil
}
return zero, fmt.Errorf("cannot convert %s to int", x.Type())
}
|
go
|
{
"resource": ""
}
|
q6617
|
finiteFloatToInt
|
train
|
func finiteFloatToInt(f Float) Int {
var i big.Int
if math.MinInt64 <= f && f <= math.MaxInt64 {
// small values
i.SetInt64(int64(f))
} else {
rat := f.rational()
if rat == nil {
panic(f) // non-finite
}
i.Div(rat.Num(), rat.Denom())
}
return Int{&i}
}
|
go
|
{
"resource": ""
}
|
q6618
|
init
|
train
|
func init() {
flag.BoolVar(&resolve.AllowFloat, "fp", resolve.AllowFloat, "allow floating-point numbers")
flag.BoolVar(&resolve.AllowSet, "set", resolve.AllowSet, "allow set data type")
flag.BoolVar(&resolve.AllowLambda, "lambda", resolve.AllowLambda, "allow lambda expressions")
flag.BoolVar(&resolve.AllowNestedDef, "nesteddef", resolve.AllowNestedDef, "allow nested def statements")
flag.BoolVar(&resolve.AllowBitwise, "bitwise", resolve.AllowBitwise, "allow bitwise operations (&, |, ^, ~, <<, and >>)")
}
|
go
|
{
"resource": ""
}
|
q6619
|
SetLocal
|
train
|
func (thread *Thread) SetLocal(key string, value interface{}) {
if thread.locals == nil {
thread.locals = make(map[string]interface{})
}
thread.locals[key] = value
}
|
go
|
{
"resource": ""
}
|
q6620
|
errorf
|
train
|
func (fr *Frame) errorf(posn syntax.Position, format string, args ...interface{}) *EvalError {
fr.posn = posn
msg := fmt.Sprintf(format, args...)
return &EvalError{Msg: msg, Frame: fr}
}
|
go
|
{
"resource": ""
}
|
q6621
|
Position
|
train
|
func (fr *Frame) Position() syntax.Position {
if fr.posn.IsValid() {
return fr.posn // leaf frame only (the error)
}
if fn, ok := fr.callable.(*Function); ok {
return fn.funcode.Position(fr.callpc) // position of active call
}
return syntax.MakePosition(&builtinFilename, 1, 0)
}
|
go
|
{
"resource": ""
}
|
q6622
|
Backtrace
|
train
|
func (e *EvalError) Backtrace() string {
var buf bytes.Buffer
e.Frame.WriteBacktrace(&buf)
fmt.Fprintf(&buf, "Error: %s", e.Msg)
return buf.String()
}
|
go
|
{
"resource": ""
}
|
q6623
|
WriteBacktrace
|
train
|
func (fr *Frame) WriteBacktrace(out *bytes.Buffer) {
fmt.Fprintf(out, "Traceback (most recent call last):\n")
var print func(fr *Frame)
print = func(fr *Frame) {
if fr != nil {
print(fr.parent)
fmt.Fprintf(out, " %s: in %s\n", fr.Position(), fr.Callable().Name())
}
}
print(fr)
}
|
go
|
{
"resource": ""
}
|
q6624
|
Stack
|
train
|
func (e *EvalError) Stack() []*Frame {
var stack []*Frame
for fr := e.Frame; fr != nil; fr = fr.parent {
stack = append(stack, fr)
}
return stack
}
|
go
|
{
"resource": ""
}
|
q6625
|
SourceProgram
|
train
|
func SourceProgram(filename string, src interface{}, isPredeclared func(string) bool) (*syntax.File, *Program, error) {
f, err := syntax.Parse(filename, src, 0)
if err != nil {
return nil, nil, err
}
if err := resolve.File(f, isPredeclared, Universe.Has); err != nil {
return f, nil, err
}
compiled := compile.File(f.Stmts, f.Locals, f.Globals)
return f, &Program{compiled}, nil
}
|
go
|
{
"resource": ""
}
|
q6626
|
CompiledProgram
|
train
|
func CompiledProgram(in io.Reader) (*Program, error) {
prog, err := compile.ReadProgram(in)
if err != nil {
return nil, err
}
return &Program{prog}, nil
}
|
go
|
{
"resource": ""
}
|
q6627
|
Init
|
train
|
func (prog *Program) Init(thread *Thread, predeclared StringDict) (StringDict, error) {
toplevel := makeToplevelFunction(prog.compiled.Toplevel, predeclared)
_, err := Call(thread, toplevel, nil, nil)
// Convert the global environment to a map and freeze it.
// We return a (partial) map even in case of error.
return toplevel.Globals(), err
}
|
go
|
{
"resource": ""
}
|
q6628
|
listExtend
|
train
|
func listExtend(x *List, y Iterable) {
if ylist, ok := y.(*List); ok {
// fast path: list += list
x.elems = append(x.elems, ylist.elems...)
} else {
iter := y.Iterate()
defer iter.Done()
var z Value
for iter.Next(&z) {
x.elems = append(x.elems, z)
}
}
}
|
go
|
{
"resource": ""
}
|
q6629
|
getAttr
|
train
|
func getAttr(fr *Frame, x Value, name string) (Value, error) {
// field or method?
if x, ok := x.(HasAttrs); ok {
if v, err := x.Attr(name); v != nil || err != nil {
return v, err
}
}
return nil, fmt.Errorf("%s has no .%s field or method", x.Type(), name)
}
|
go
|
{
"resource": ""
}
|
q6630
|
setField
|
train
|
func setField(fr *Frame, x Value, name string, y Value) error {
if x, ok := x.(HasSetField); ok {
err := x.SetField(name, y)
return err
}
return fmt.Errorf("can't assign to .%s field of %s", name, x.Type())
}
|
go
|
{
"resource": ""
}
|
q6631
|
Call
|
train
|
func Call(thread *Thread, fn Value, args Tuple, kwargs []Tuple) (Value, error) {
c, ok := fn.(Callable)
if !ok {
return nil, fmt.Errorf("invalid call of non-function (%s)", fn.Type())
}
thread.frame = &Frame{parent: thread.frame, callable: c}
result, err := c.CallInternal(thread, args, kwargs)
thread.frame = thread.frame.parent
// Sanity check: nil is not a valid Skylark value.
if result == nil && err == nil {
return nil, fmt.Errorf("internal error: nil (not None) returned from %s", fn)
}
return result, err
}
|
go
|
{
"resource": ""
}
|
q6632
|
Expr
|
train
|
func Expr(expr syntax.Expr, isPredeclared, isUniversal func(name string) bool) ([]*syntax.Ident, error) {
r := newResolver(isPredeclared, isUniversal)
r.expr(expr)
r.env.resolveLocalUses()
r.resolveNonLocalUses(r.env) // globals & universals
if len(r.errors) > 0 {
return nil, r.errors
}
return r.moduleLocals, nil
}
|
go
|
{
"resource": ""
}
|
q6633
|
bind
|
train
|
func (r *resolver) bind(id *syntax.Ident, allowRebind bool) bool {
// Binding outside any local (comprehension/function) block?
if r.env.isModule() {
id.Scope = uint8(Global)
prev, ok := r.globals[id.Name]
if ok {
// Global reassignments are permitted only if
// they are of the form x += y. We can't tell
// statically whether it's a reassignment
// (e.g. int += int) or a mutation (list += list).
if !allowRebind && !AllowGlobalReassign {
r.errorf(id.NamePos, "cannot reassign global %s declared at %s", id.Name, prev.NamePos)
}
id.Index = prev.Index
} else {
// first global binding of this name
r.globals[id.Name] = id
id.Index = len(r.moduleGlobals)
r.moduleGlobals = append(r.moduleGlobals, id)
}
return ok
}
// Mark this name as local to current block.
// Assign it a new local (positive) index in the current container.
_, ok := r.env.bindings[id.Name]
if !ok {
var locals *[]*syntax.Ident
if fn := r.container().function; fn != nil {
locals = &fn.Locals
} else {
locals = &r.moduleLocals
}
r.env.bind(id.Name, binding{Local, len(*locals)})
*locals = append(*locals, id)
}
r.use(id)
return ok
}
|
go
|
{
"resource": ""
}
|
q6634
|
lookupLocal
|
train
|
func lookupLocal(use use) binding {
for env := use.env; env != nil; env = env.parent {
if bind, ok := env.bindings[use.id.Name]; ok {
if bind.scope == Free {
// shouldn't exist till later
log.Fatalf("%s: internal error: %s, %d", use.id.NamePos, use.id.Name, bind)
}
return bind // found
}
if env.function != nil {
break
}
}
return binding{} // not found in this function
}
|
go
|
{
"resource": ""
}
|
q6635
|
lookupLexical
|
train
|
func (r *resolver) lookupLexical(id *syntax.Ident, env *block) (bind binding) {
if debug {
fmt.Printf("lookupLexical %s in %s = ...\n", id.Name, env)
defer func() { fmt.Printf("= %d\n", bind) }()
}
// Is this the module block?
if env.isModule() {
return r.useGlobal(id) // global, predeclared, or not found
}
// Defined in this block?
bind, ok := env.bindings[id.Name]
if !ok {
// Defined in parent block?
bind = r.lookupLexical(id, env.parent)
if env.function != nil && (bind.scope == Local || bind.scope == Free) {
// Found in parent block, which belongs to enclosing function.
id := &syntax.Ident{
Name: id.Name,
Scope: uint8(bind.scope),
Index: bind.index,
}
bind.scope = Free
bind.index = len(env.function.FreeVars)
env.function.FreeVars = append(env.function.FreeVars, id)
if debug {
fmt.Printf("creating freevar %v in function at %s: %s\n",
len(env.function.FreeVars), fmt.Sprint(env.function.Span()), id.Name)
}
}
// Memoize, to avoid duplicate free vars
// and redundant global (failing) lookups.
env.bind(id.Name, bind)
}
return bind
}
|
go
|
{
"resource": ""
}
|
q6636
|
FromStringDict
|
train
|
func FromStringDict(constructor skylark.Value, d skylark.StringDict) *Struct {
if constructor == nil {
panic("nil constructor")
}
s := &Struct{
constructor: constructor,
entries: make(entries, 0, len(d)),
}
for k, v := range d {
s.entries = append(s.entries, entry{k, v})
}
sort.Sort(s.entries)
return s
}
|
go
|
{
"resource": ""
}
|
q6637
|
Attr
|
train
|
func (s *Struct) Attr(name string) (skylark.Value, error) {
// Binary search the entries.
// This implementation is a specialization of
// sort.Search that avoids dynamic dispatch.
n := len(s.entries)
i, j := 0, n
for i < j {
h := int(uint(i+j) >> 1)
if s.entries[h].name < name {
i = h + 1
} else {
j = h
}
}
if i < n && s.entries[i].name == name {
return s.entries[i].value, nil
}
// TODO(adonovan): there may be a nice feature for core
// skylark.Value here, especially for JSON, but the current
// features are incomplete and underspecified.
//
// to_{json,proto} are deprecated, appropriately; see Google issue b/36412967.
switch name {
case "to_json", "to_proto":
return skylark.NewBuiltin(name, func(thread *skylark.Thread, fn *skylark.Builtin, args skylark.Tuple, kwargs []skylark.Tuple) (skylark.Value, error) {
var buf bytes.Buffer
var err error
if name == "to_json" {
err = writeJSON(&buf, s)
} else {
err = writeProtoStruct(&buf, 0, s)
}
if err != nil {
// TODO(adonovan): improve error error messages
// to show the path through the object graph.
return nil, err
}
return skylark.String(buf.String()), nil
}), nil
}
var ctor string
if s.constructor != Default {
ctor = s.constructor.String() + " "
}
return nil, fmt.Errorf("%sstruct has no .%s attribute", ctor, name)
}
|
go
|
{
"resource": ""
}
|
q6638
|
Read
|
train
|
func Read(filename string, report Reporter) (chunks []Chunk) {
data, err := ioutil.ReadFile(filename)
if err != nil {
report.Errorf("%s", err)
return
}
linenum := 1
for i, chunk := range strings.Split(string(data), "\n---\n") {
chunk := string(chunk)
if debug {
fmt.Printf("chunk %d at line %d: %s\n", i, linenum, chunk)
}
// Pad with newlines so the line numbers match the original file.
src := strings.Repeat("\n", linenum-1) + chunk
wantErrs := make(map[int]*regexp.Regexp)
// Parse comments of the form:
// ### "expected error".
lines := strings.Split(chunk, "\n")
for j := 0; j < len(lines); j, linenum = j+1, linenum+1 {
line := lines[j]
hashes := strings.Index(line, "###")
if hashes < 0 {
continue
}
rest := strings.TrimSpace(line[hashes+len("###"):])
pattern, err := strconv.Unquote(rest)
if err != nil {
report.Errorf("%s:%d: not a quoted regexp: %s", filename, linenum, rest)
continue
}
rx, err := regexp.Compile(pattern)
if err != nil {
report.Errorf("%s:%d: %v", filename, linenum, err)
continue
}
wantErrs[linenum] = rx
if debug {
fmt.Printf("\t%d\t%s\n", linenum, rx)
}
}
linenum++
chunks = append(chunks, Chunk{src, filename, report, wantErrs})
}
return chunks
}
|
go
|
{
"resource": ""
}
|
q6639
|
GotError
|
train
|
func (chunk *Chunk) GotError(linenum int, msg string) {
if rx, ok := chunk.wantErrs[linenum]; ok {
delete(chunk.wantErrs, linenum)
if !rx.MatchString(msg) {
chunk.report.Errorf("%s:%d: error %q does not match pattern %q", chunk.filename, linenum, msg, rx)
}
} else {
chunk.report.Errorf("%s:%d: unexpected error: %v", chunk.filename, linenum, msg)
}
}
|
go
|
{
"resource": ""
}
|
q6640
|
Done
|
train
|
func (chunk *Chunk) Done() {
for linenum, rx := range chunk.wantErrs {
chunk.report.Errorf("%s:%d: expected error matching %q", chunk.filename, linenum, rx)
}
}
|
go
|
{
"resource": ""
}
|
q6641
|
add
|
train
|
func (p Position) add(s string) Position {
if n := strings.Count(s, "\n"); n > 0 {
p.Line += int32(n)
s = s[strings.LastIndex(s, "\n")+1:]
p.Col = 1
}
p.Col += int32(utf8.RuneCountInString(s))
return p
}
|
go
|
{
"resource": ""
}
|
q6642
|
peekRune
|
train
|
func (sc *scanner) peekRune() rune {
if len(sc.rest) == 0 {
return 0
}
// fast path: ASCII
if b := sc.rest[0]; b < utf8.RuneSelf {
if b == '\r' {
return '\n'
}
return rune(b)
}
r, _ := utf8.DecodeRune(sc.rest)
return r
}
|
go
|
{
"resource": ""
}
|
q6643
|
readRune
|
train
|
func (sc *scanner) readRune() rune {
if len(sc.rest) == 0 {
sc.error(sc.pos, "internal scanner error: readRune at EOF")
return 0 // unreachable but eliminates bounds-check below
}
// fast path: ASCII
if b := sc.rest[0]; b < utf8.RuneSelf {
r := rune(b)
sc.rest = sc.rest[1:]
if r == '\r' {
if len(sc.rest) > 0 && sc.rest[0] == '\n' {
sc.rest = sc.rest[1:]
}
r = '\n'
}
if r == '\n' {
sc.pos.Line++
sc.pos.Col = 1
} else {
sc.pos.Col++
}
return r
}
r, size := utf8.DecodeRune(sc.rest)
sc.rest = sc.rest[size:]
sc.pos.Col++
return r
}
|
go
|
{
"resource": ""
}
|
q6644
|
startToken
|
train
|
func (sc *scanner) startToken(val *tokenValue) {
sc.token = sc.rest
val.raw = ""
val.pos = sc.pos
}
|
go
|
{
"resource": ""
}
|
q6645
|
endToken
|
train
|
func (sc *scanner) endToken(val *tokenValue) {
if val.raw == "" {
val.raw = string(sc.token[:len(sc.token)-len(sc.rest)])
}
}
|
go
|
{
"resource": ""
}
|
q6646
|
PrintError
|
train
|
func PrintError(err error) {
if evalErr, ok := err.(*skylark.EvalError); ok {
fmt.Fprintln(os.Stderr, evalErr.Backtrace())
} else {
fmt.Fprintln(os.Stderr, err)
}
}
|
go
|
{
"resource": ""
}
|
q6647
|
MakeLoad
|
train
|
func MakeLoad() func(thread *skylark.Thread, module string) (skylark.StringDict, error) {
type entry struct {
globals skylark.StringDict
err error
}
var cache = make(map[string]*entry)
return func(thread *skylark.Thread, module string) (skylark.StringDict, error) {
e, ok := cache[module]
if e == nil {
if ok {
// request for package whose loading is in progress
return nil, fmt.Errorf("cycle in load graph")
}
// Add a placeholder to indicate "load in progress".
cache[module] = nil
// Load it.
thread := &skylark.Thread{Load: thread.Load}
globals, err := skylark.ExecFile(thread, module, nil, nil)
e = &entry{globals, err}
// Update the cache.
cache[module] = e
}
return e.globals, e.err
}
}
|
go
|
{
"resource": ""
}
|
q6648
|
Write
|
train
|
func (prog *Program) Write(out io.Writer) error {
out.Write([]byte(magic))
gobIdents := func(idents []Ident) []gobIdent {
res := make([]gobIdent, len(idents))
for i, id := range idents {
res[i].Name = id.Name
res[i].Line = id.Pos.Line
res[i].Col = id.Pos.Col
}
return res
}
gobFunc := func(fn *Funcode) gobFunction {
return gobFunction{
Id: gobIdent{
Name: fn.Name,
Line: fn.Pos.Line,
Col: fn.Pos.Col,
},
Code: fn.Code,
Pclinetab: fn.pclinetab,
Locals: gobIdents(fn.Locals),
Freevars: gobIdents(fn.Freevars),
MaxStack: fn.MaxStack,
NumParams: fn.NumParams,
HasVarargs: fn.HasVarargs,
HasKwargs: fn.HasKwargs,
}
}
gp := &gobProgram{
Version: Version,
Filename: prog.Toplevel.Pos.Filename(),
Loads: gobIdents(prog.Loads),
Names: prog.Names,
Constants: prog.Constants,
Functions: make([]gobFunction, len(prog.Functions)),
Globals: gobIdents(prog.Globals),
Toplevel: gobFunc(prog.Toplevel),
}
for i, f := range prog.Functions {
gp.Functions[i] = gobFunc(f)
}
return gob.NewEncoder(out).Encode(gp)
}
|
go
|
{
"resource": ""
}
|
q6649
|
ReadProgram
|
train
|
func ReadProgram(in io.Reader) (*Program, error) {
magicBuf := []byte(magic)
n, err := in.Read(magicBuf)
if err != nil {
return nil, err
}
if n != len(magic) {
return nil, fmt.Errorf("not a compiled module: no magic number")
}
if string(magicBuf) != magic {
return nil, fmt.Errorf("not a compiled module: got magic number %q, want %q",
magicBuf, magic)
}
dec := gob.NewDecoder(in)
var gp gobProgram
if err := dec.Decode(&gp); err != nil {
return nil, fmt.Errorf("decoding program: %v", err)
}
if gp.Version != Version {
return nil, fmt.Errorf("version mismatch: read %d, want %d",
gp.Version, Version)
}
file := gp.Filename // copy, to avoid keeping gp live
ungobIdents := func(idents []gobIdent) []Ident {
res := make([]Ident, len(idents))
for i, id := range idents {
res[i].Name = id.Name
res[i].Pos = syntax.MakePosition(&file, id.Line, id.Col)
}
return res
}
prog := &Program{
Loads: ungobIdents(gp.Loads),
Names: gp.Names,
Constants: gp.Constants,
Globals: ungobIdents(gp.Globals),
Functions: make([]*Funcode, len(gp.Functions)),
}
ungobFunc := func(gf *gobFunction) *Funcode {
pos := syntax.MakePosition(&file, gf.Id.Line, gf.Id.Col)
return &Funcode{
Prog: prog,
Pos: pos,
Name: gf.Id.Name,
Code: gf.Code,
pclinetab: gf.Pclinetab,
Locals: ungobIdents(gf.Locals),
Freevars: ungobIdents(gf.Freevars),
MaxStack: gf.MaxStack,
NumParams: gf.NumParams,
HasVarargs: gf.HasVarargs,
HasKwargs: gf.HasKwargs,
}
}
for i := range gp.Functions {
prog.Functions[i] = ungobFunc(&gp.Functions[i])
}
prog.Toplevel = ungobFunc(&gp.Toplevel)
return prog, nil
}
|
go
|
{
"resource": ""
}
|
q6650
|
idents
|
train
|
func idents(ids []*syntax.Ident) []Ident {
res := make([]Ident, len(ids))
for i, id := range ids {
res[i].Name = id.Name
res[i].Pos = id.NamePos
}
return res
}
|
go
|
{
"resource": ""
}
|
q6651
|
Expr
|
train
|
func Expr(expr syntax.Expr, locals []*syntax.Ident) *Funcode {
stmts := []syntax.Stmt{&syntax.ReturnStmt{Result: expr}}
return File(stmts, locals, nil).Toplevel
}
|
go
|
{
"resource": ""
}
|
q6652
|
File
|
train
|
func File(stmts []syntax.Stmt, locals, globals []*syntax.Ident) *Program {
pcomp := &pcomp{
prog: &Program{
Globals: idents(globals),
},
names: make(map[string]uint32),
constants: make(map[interface{}]uint32),
functions: make(map[*Funcode]uint32),
}
var pos syntax.Position
if len(stmts) > 0 {
pos = syntax.Start(stmts[0])
}
pcomp.prog.Toplevel = pcomp.function("<toplevel>", pos, stmts, locals, nil)
return pcomp.prog
}
|
go
|
{
"resource": ""
}
|
q6653
|
generate
|
train
|
func (fcomp *fcomp) generate(blocks []*block, codelen uint32) {
code := make([]byte, 0, codelen)
var pclinetab []uint16
var prev struct {
pc uint32
line int32
}
for _, b := range blocks {
if debug {
fmt.Fprintf(os.Stderr, "%d:\n", b.index)
}
pc := b.addr
for _, insn := range b.insns {
if insn.line != 0 {
// Instruction has a source position. Delta-encode it.
// See Funcode.Position for the encoding.
for {
var incomplete uint16
deltapc := pc - prev.pc
if deltapc > 0xff {
deltapc = 0xff
incomplete = 1
}
prev.pc += deltapc
deltaline := insn.line - prev.line
if deltaline > 0x3f {
deltaline = 0x3f
incomplete = 1
} else if deltaline < -0x40 {
deltaline = -0x40
incomplete = 1
}
prev.line += deltaline
entry := uint16(deltapc<<8) | uint16(uint8(deltaline<<1)) | incomplete
pclinetab = append(pclinetab, entry)
if incomplete == 0 {
break
}
}
if debug {
fmt.Fprintf(os.Stderr, "\t\t\t\t\t; %s %d\n",
filepath.Base(fcomp.fn.Pos.Filename()), insn.line)
}
}
if debug {
PrintOp(fcomp.fn, pc, insn.op, insn.arg)
}
code = append(code, byte(insn.op))
pc++
if insn.op >= OpcodeArgMin {
if insn.op == CJMP || insn.op == ITERJMP {
code = addUint32(code, insn.arg, 4) // pad arg to 4 bytes
} else {
code = addUint32(code, insn.arg, 0)
}
pc = uint32(len(code))
}
}
if b.jmp != nil && b.jmp.index != b.index+1 {
addr := b.jmp.addr
if debug {
fmt.Fprintf(os.Stderr, "\t%d\tjmp\t\t%d\t; block %d\n",
pc, addr, b.jmp.index)
}
code = append(code, byte(JMP))
code = addUint32(code, addr, 4)
}
}
if len(code) != int(codelen) {
panic("internal error: wrong code length")
}
fcomp.fn.pclinetab = pclinetab
fcomp.fn.Code = code
}
|
go
|
{
"resource": ""
}
|
q6654
|
PrintOp
|
train
|
func PrintOp(fn *Funcode, pc uint32, op Opcode, arg uint32) {
if op < OpcodeArgMin {
fmt.Fprintf(os.Stderr, "\t%d\t%s\n", pc, op)
return
}
var comment string
switch op {
case CONSTANT:
switch x := fn.Prog.Constants[arg].(type) {
case string:
comment = strconv.Quote(x)
default:
comment = fmt.Sprint(x)
}
case MAKEFUNC:
comment = fn.Prog.Functions[arg].Name
case SETLOCAL, LOCAL:
comment = fn.Locals[arg].Name
case SETGLOBAL, GLOBAL:
comment = fn.Prog.Globals[arg].Name
case ATTR, SETFIELD, PREDECLARED, UNIVERSAL:
comment = fn.Prog.Names[arg]
case FREE:
comment = fn.Freevars[arg].Name
case CALL, CALL_VAR, CALL_KW, CALL_VAR_KW:
comment = fmt.Sprintf("%d pos, %d named", arg>>8, arg&0xff)
default:
// JMP, CJMP, ITERJMP, MAKETUPLE, MAKELIST, LOAD, UNPACK:
// arg is just a number
}
var buf bytes.Buffer
fmt.Fprintf(&buf, "\t%d\t%-10s\t%d", pc, op, arg)
if comment != "" {
fmt.Fprint(&buf, "\t; ", comment)
}
fmt.Fprintln(&buf)
os.Stderr.Write(buf.Bytes())
}
|
go
|
{
"resource": ""
}
|
q6655
|
emit
|
train
|
func (fcomp *fcomp) emit(op Opcode) {
if op >= OpcodeArgMin {
panic("missing arg: " + op.String())
}
insn := insn{op: op, line: fcomp.pos.Line}
fcomp.block.insns = append(fcomp.block.insns, insn)
fcomp.pos.Line = 0
}
|
go
|
{
"resource": ""
}
|
q6656
|
emit1
|
train
|
func (fcomp *fcomp) emit1(op Opcode, arg uint32) {
if op < OpcodeArgMin {
panic("unwanted arg: " + op.String())
}
insn := insn{op: op, arg: arg, line: fcomp.pos.Line}
fcomp.block.insns = append(fcomp.block.insns, insn)
fcomp.pos.Line = 0
}
|
go
|
{
"resource": ""
}
|
q6657
|
jump
|
train
|
func (fcomp *fcomp) jump(b *block) {
if b == fcomp.block {
panic("self-jump") // unreachable: Skylark has no arbitrary looping constructs
}
fcomp.block.jmp = b
fcomp.block = nil
}
|
go
|
{
"resource": ""
}
|
q6658
|
nameIndex
|
train
|
func (pcomp *pcomp) nameIndex(name string) uint32 {
index, ok := pcomp.names[name]
if !ok {
index = uint32(len(pcomp.prog.Names))
pcomp.names[name] = index
pcomp.prog.Names = append(pcomp.prog.Names, name)
}
return index
}
|
go
|
{
"resource": ""
}
|
q6659
|
constantIndex
|
train
|
func (pcomp *pcomp) constantIndex(v interface{}) uint32 {
index, ok := pcomp.constants[v]
if !ok {
index = uint32(len(pcomp.prog.Constants))
pcomp.constants[v] = index
pcomp.prog.Constants = append(pcomp.prog.Constants, v)
}
return index
}
|
go
|
{
"resource": ""
}
|
q6660
|
functionIndex
|
train
|
func (pcomp *pcomp) functionIndex(fn *Funcode) uint32 {
index, ok := pcomp.functions[fn]
if !ok {
index = uint32(len(pcomp.prog.Functions))
pcomp.functions[fn] = index
pcomp.prog.Functions = append(pcomp.prog.Functions, fn)
}
return index
}
|
go
|
{
"resource": ""
}
|
q6661
|
string
|
train
|
func (fcomp *fcomp) string(s string) {
fcomp.emit1(CONSTANT, fcomp.pcomp.constantIndex(s))
}
|
go
|
{
"resource": ""
}
|
q6662
|
set
|
train
|
func (fcomp *fcomp) set(id *syntax.Ident) {
switch resolve.Scope(id.Scope) {
case resolve.Local:
fcomp.emit1(SETLOCAL, uint32(id.Index))
case resolve.Global:
fcomp.emit1(SETGLOBAL, uint32(id.Index))
default:
log.Fatalf("%s: set(%s): neither global nor local (%d)", id.NamePos, id.Name, id.Scope)
}
}
|
go
|
{
"resource": ""
}
|
q6663
|
lookup
|
train
|
func (fcomp *fcomp) lookup(id *syntax.Ident) {
switch resolve.Scope(id.Scope) {
case resolve.Local:
fcomp.setPos(id.NamePos)
fcomp.emit1(LOCAL, uint32(id.Index))
case resolve.Free:
fcomp.emit1(FREE, uint32(id.Index))
case resolve.Global:
fcomp.setPos(id.NamePos)
fcomp.emit1(GLOBAL, uint32(id.Index))
case resolve.Predeclared:
fcomp.setPos(id.NamePos)
fcomp.emit1(PREDECLARED, fcomp.pcomp.nameIndex(id.Name))
case resolve.Universal:
fcomp.emit1(UNIVERSAL, fcomp.pcomp.nameIndex(id.Name))
default:
log.Fatalf("%s: compiler.lookup(%s): scope = %d", id.NamePos, id.Name, id.Scope)
}
}
|
go
|
{
"resource": ""
}
|
q6664
|
assign
|
train
|
func (fcomp *fcomp) assign(pos syntax.Position, lhs syntax.Expr) {
switch lhs := lhs.(type) {
case *syntax.ParenExpr:
// (lhs) = rhs
fcomp.assign(pos, lhs.X)
case *syntax.Ident:
// x = rhs
fcomp.set(lhs)
case *syntax.TupleExpr:
// x, y = rhs
fcomp.assignSequence(pos, lhs.List)
case *syntax.ListExpr:
// [x, y] = rhs
fcomp.assignSequence(pos, lhs.List)
case *syntax.IndexExpr:
// x[y] = rhs
fcomp.expr(lhs.X)
fcomp.emit(EXCH)
fcomp.expr(lhs.Y)
fcomp.emit(EXCH)
fcomp.setPos(lhs.Lbrack)
fcomp.emit(SETINDEX)
case *syntax.DotExpr:
// x.f = rhs
fcomp.expr(lhs.X)
fcomp.emit(EXCH)
fcomp.setPos(lhs.Dot)
fcomp.emit1(SETFIELD, fcomp.pcomp.nameIndex(lhs.Name.Name))
default:
panic(lhs)
}
}
|
go
|
{
"resource": ""
}
|
q6665
|
add
|
train
|
func add(code rune, args []summand) syntax.Expr {
switch code {
case 's':
var buf bytes.Buffer
for _, arg := range args {
buf.WriteString(arg.x.(*syntax.Literal).Value.(string))
}
return &syntax.Literal{Token: syntax.STRING, Value: buf.String()}
case 'l':
var elems []syntax.Expr
for _, arg := range args {
elems = append(elems, arg.x.(*syntax.ListExpr).List...)
}
return &syntax.ListExpr{List: elems}
case 't':
var elems []syntax.Expr
for _, arg := range args {
elems = append(elems, arg.x.(*syntax.TupleExpr).List...)
}
return &syntax.TupleExpr{List: elems}
}
panic(code)
}
|
go
|
{
"resource": ""
}
|
q6666
|
ifelse
|
train
|
func (fcomp *fcomp) ifelse(cond syntax.Expr, t, f *block) {
switch cond := cond.(type) {
case *syntax.UnaryExpr:
if cond.Op == syntax.NOT {
// if not x then goto t else goto f
// =>
// if x then goto f else goto t
fcomp.ifelse(cond.X, f, t)
return
}
case *syntax.BinaryExpr:
switch cond.Op {
case syntax.AND:
// if x and y then goto t else goto f
// =>
// if x then ifelse(y, t, f) else goto f
fcomp.expr(cond.X)
y := fcomp.newBlock()
fcomp.condjump(CJMP, y, f)
fcomp.block = y
fcomp.ifelse(cond.Y, t, f)
return
case syntax.OR:
// if x or y then goto t else goto f
// =>
// if x then goto t else ifelse(y, t, f)
fcomp.expr(cond.X)
y := fcomp.newBlock()
fcomp.condjump(CJMP, t, y)
fcomp.block = y
fcomp.ifelse(cond.Y, t, f)
return
case syntax.NOT_IN:
// if x not in y then goto t else goto f
// =>
// if x in y then goto f else goto t
copy := *cond
copy.Op = syntax.IN
fcomp.expr(©)
fcomp.condjump(CJMP, f, t)
return
}
}
// general case
fcomp.expr(cond)
fcomp.condjump(CJMP, t, f)
}
|
go
|
{
"resource": ""
}
|
q6667
|
Error
|
train
|
func (e *Error) Error() string {
s := "[Error"
if e.Sender != "" {
s += " (where: " + e.Sender + ")"
}
if e.Filename != "" {
s += " in " + e.Filename
}
if e.Line > 0 {
s += fmt.Sprintf(" | Line %d Col %d", e.Line, e.Column)
if e.Token != nil {
s += fmt.Sprintf(" near '%s'", e.Token.Val)
}
}
s += "] "
s += e.OrigError.Error()
return s
}
|
go
|
{
"resource": ""
}
|
q6668
|
RawLine
|
train
|
func (e *Error) RawLine() (line string, available bool, outErr error) {
if e.Line <= 0 || e.Filename == "<string>" {
return "", false, nil
}
filename := e.Filename
if e.Template != nil {
filename = e.Template.set.resolveFilename(e.Template, e.Filename)
}
file, err := os.Open(filename)
if err != nil {
return "", false, err
}
defer func() {
err := file.Close()
if err != nil && outErr == nil {
outErr = err
}
}()
scanner := bufio.NewScanner(file)
l := 0
for scanner.Scan() {
l++
if l == e.Line {
return scanner.Text(), true, nil
}
}
return "", false, nil
}
|
go
|
{
"resource": ""
}
|
q6669
|
newParser
|
train
|
func newParser(name string, tokens []*Token, template *Template) *Parser {
p := &Parser{
name: name,
tokens: tokens,
template: template,
}
if len(tokens) > 0 {
p.lastToken = tokens[len(tokens)-1]
}
return p
}
|
go
|
{
"resource": ""
}
|
q6670
|
MatchType
|
train
|
func (p *Parser) MatchType(typ TokenType) *Token {
if t := p.PeekType(typ); t != nil {
p.Consume()
return t
}
return nil
}
|
go
|
{
"resource": ""
}
|
q6671
|
Match
|
train
|
func (p *Parser) Match(typ TokenType, val string) *Token {
if t := p.Peek(typ, val); t != nil {
p.Consume()
return t
}
return nil
}
|
go
|
{
"resource": ""
}
|
q6672
|
Peek
|
train
|
func (p *Parser) Peek(typ TokenType, val string) *Token {
return p.PeekN(0, typ, val)
}
|
go
|
{
"resource": ""
}
|
q6673
|
Error
|
train
|
func (p *Parser) Error(msg string, token *Token) *Error {
if token == nil {
// Set current token
token = p.Current()
if token == nil {
// Set to last token
if len(p.tokens) > 0 {
token = p.tokens[len(p.tokens)-1]
}
}
}
var line, col int
if token != nil {
line = token.Line
col = token.Col
}
return &Error{
Template: p.template,
Filename: p.name,
Sender: "parser",
Line: line,
Column: col,
Token: token,
OrigError: errors.New(msg),
}
}
|
go
|
{
"resource": ""
}
|
q6674
|
ExecuteWriterUnbuffered
|
train
|
func (tpl *Template) ExecuteWriterUnbuffered(context Context, writer io.Writer) error {
return tpl.newTemplateWriterAndExecute(context, writer)
}
|
go
|
{
"resource": ""
}
|
q6675
|
Execute
|
train
|
func (tpl *Template) Execute(context Context) (string, error) {
// Execute template
buffer, err := tpl.newBufferAndExecute(context)
if err != nil {
return "", err
}
return buffer.String(), nil
}
|
go
|
{
"resource": ""
}
|
q6676
|
MustNewLocalFileSystemLoader
|
train
|
func MustNewLocalFileSystemLoader(baseDir string) *LocalFilesystemLoader {
fs, err := NewLocalFileSystemLoader(baseDir)
if err != nil {
log.Panic(err)
}
return fs
}
|
go
|
{
"resource": ""
}
|
q6677
|
Get
|
train
|
func (fs *LocalFilesystemLoader) Get(path string) (io.Reader, error) {
buf, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return bytes.NewReader(buf), nil
}
|
go
|
{
"resource": ""
}
|
q6678
|
NewSandboxedFilesystemLoader
|
train
|
func NewSandboxedFilesystemLoader(baseDir string) (*SandboxedFilesystemLoader, error) {
fs, err := NewLocalFileSystemLoader(baseDir)
if err != nil {
return nil, err
}
return &SandboxedFilesystemLoader{
LocalFilesystemLoader: fs,
}, nil
}
|
go
|
{
"resource": ""
}
|
q6679
|
BanTag
|
train
|
func (set *TemplateSet) BanTag(name string) error {
_, has := tags[name]
if !has {
return errors.Errorf("tag '%s' not found", name)
}
if set.firstTemplateCreated {
return errors.New("you cannot ban any tags after you've added your first template to your template set")
}
_, has = set.bannedTags[name]
if has {
return errors.Errorf("tag '%s' is already banned", name)
}
set.bannedTags[name] = true
return nil
}
|
go
|
{
"resource": ""
}
|
q6680
|
BanFilter
|
train
|
func (set *TemplateSet) BanFilter(name string) error {
_, has := filters[name]
if !has {
return errors.Errorf("filter '%s' not found", name)
}
if set.firstTemplateCreated {
return errors.New("you cannot ban any filters after you've added your first template to your template set")
}
_, has = set.bannedFilters[name]
if has {
return errors.Errorf("filter '%s' is already banned", name)
}
set.bannedFilters[name] = true
return nil
}
|
go
|
{
"resource": ""
}
|
q6681
|
CleanCache
|
train
|
func (set *TemplateSet) CleanCache(filenames ...string) {
set.templateCacheMutex.Lock()
defer set.templateCacheMutex.Unlock()
if len(filenames) == 0 {
set.templateCache = make(map[string]*Template, len(set.templateCache))
}
for _, filename := range filenames {
delete(set.templateCache, set.resolveFilename(nil, filename))
}
}
|
go
|
{
"resource": ""
}
|
q6682
|
FromString
|
train
|
func (set *TemplateSet) FromString(tpl string) (*Template, error) {
set.firstTemplateCreated = true
return newTemplateString(set, []byte(tpl))
}
|
go
|
{
"resource": ""
}
|
q6683
|
FromBytes
|
train
|
func (set *TemplateSet) FromBytes(tpl []byte) (*Template, error) {
set.firstTemplateCreated = true
return newTemplateString(set, tpl)
}
|
go
|
{
"resource": ""
}
|
q6684
|
FromFile
|
train
|
func (set *TemplateSet) FromFile(filename string) (*Template, error) {
set.firstTemplateCreated = true
fd, err := set.loader.Get(set.resolveFilename(nil, filename))
if err != nil {
return nil, &Error{
Filename: filename,
Sender: "fromfile",
OrigError: err,
}
}
buf, err := ioutil.ReadAll(fd)
if err != nil {
return nil, &Error{
Filename: filename,
Sender: "fromfile",
OrigError: err,
}
}
return newTemplate(set, filename, false, buf)
}
|
go
|
{
"resource": ""
}
|
q6685
|
RenderTemplateString
|
train
|
func (set *TemplateSet) RenderTemplateString(s string, ctx Context) (string, error) {
set.firstTemplateCreated = true
tpl := Must(set.FromString(s))
result, err := tpl.Execute(ctx)
if err != nil {
return "", err
}
return result, nil
}
|
go
|
{
"resource": ""
}
|
q6686
|
RenderTemplateBytes
|
train
|
func (set *TemplateSet) RenderTemplateBytes(b []byte, ctx Context) (string, error) {
set.firstTemplateCreated = true
tpl := Must(set.FromBytes(b))
result, err := tpl.Execute(ctx)
if err != nil {
return "", err
}
return result, nil
}
|
go
|
{
"resource": ""
}
|
q6687
|
RenderTemplateFile
|
train
|
func (set *TemplateSet) RenderTemplateFile(fn string, ctx Context) (string, error) {
set.firstTemplateCreated = true
tpl := Must(set.FromFile(fn))
result, err := tpl.Execute(ctx)
if err != nil {
return "", err
}
return result, nil
}
|
go
|
{
"resource": ""
}
|
q6688
|
AsSafeValue
|
train
|
func AsSafeValue(i interface{}) *Value {
return &Value{
val: reflect.ValueOf(i),
safe: true,
}
}
|
go
|
{
"resource": ""
}
|
q6689
|
IsFloat
|
train
|
func (v *Value) IsFloat() bool {
return v.getResolvedValue().Kind() == reflect.Float32 ||
v.getResolvedValue().Kind() == reflect.Float64
}
|
go
|
{
"resource": ""
}
|
q6690
|
IsInteger
|
train
|
func (v *Value) IsInteger() bool {
return v.getResolvedValue().Kind() == reflect.Int ||
v.getResolvedValue().Kind() == reflect.Int8 ||
v.getResolvedValue().Kind() == reflect.Int16 ||
v.getResolvedValue().Kind() == reflect.Int32 ||
v.getResolvedValue().Kind() == reflect.Int64 ||
v.getResolvedValue().Kind() == reflect.Uint ||
v.getResolvedValue().Kind() == reflect.Uint8 ||
v.getResolvedValue().Kind() == reflect.Uint16 ||
v.getResolvedValue().Kind() == reflect.Uint32 ||
v.getResolvedValue().Kind() == reflect.Uint64
}
|
go
|
{
"resource": ""
}
|
q6691
|
Len
|
train
|
func (v *Value) Len() int {
switch v.getResolvedValue().Kind() {
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
return v.getResolvedValue().Len()
case reflect.String:
runes := []rune(v.getResolvedValue().String())
return len(runes)
default:
logf("Value.Len() not available for type: %s\n", v.getResolvedValue().Kind().String())
return 0
}
}
|
go
|
{
"resource": ""
}
|
q6692
|
Index
|
train
|
func (v *Value) Index(i int) *Value {
switch v.getResolvedValue().Kind() {
case reflect.Array, reflect.Slice:
if i >= v.Len() {
return AsValue(nil)
}
return AsValue(v.getResolvedValue().Index(i).Interface())
case reflect.String:
//return AsValue(v.getResolvedValue().Slice(i, i+1).Interface())
s := v.getResolvedValue().String()
runes := []rune(s)
if i < len(runes) {
return AsValue(string(runes[i]))
}
return AsValue("")
default:
logf("Value.Slice() not available for type: %s\n", v.getResolvedValue().Kind().String())
return AsValue([]int{})
}
}
|
go
|
{
"resource": ""
}
|
q6693
|
Interface
|
train
|
func (v *Value) Interface() interface{} {
if v.val.IsValid() {
return v.val.Interface()
}
return nil
}
|
go
|
{
"resource": ""
}
|
q6694
|
EqualValueTo
|
train
|
func (v *Value) EqualValueTo(other *Value) bool {
// comparison of uint with int fails using .Interface()-comparison (see issue #64)
if v.IsInteger() && other.IsInteger() {
return v.Integer() == other.Integer()
}
return v.Interface() == other.Interface()
}
|
go
|
{
"resource": ""
}
|
q6695
|
MustApplyFilter
|
train
|
func MustApplyFilter(name string, value *Value, param *Value) *Value {
val, err := ApplyFilter(name, value, param)
if err != nil {
panic(err)
}
return val
}
|
go
|
{
"resource": ""
}
|
q6696
|
NewMockCollectorReader
|
train
|
func NewMockCollectorReader(ctrl *gomock.Controller) *MockCollectorReader {
mock := &MockCollectorReader{ctrl: ctrl}
mock.recorder = &MockCollectorReaderMockRecorder{mock}
return mock
}
|
go
|
{
"resource": ""
}
|
q6697
|
GetAllRecords
|
train
|
func (mr *MockCollectorReaderMockRecorder) GetAllRecords() *gomock.Call {
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAllRecords", reflect.TypeOf((*MockCollectorReader)(nil).GetAllRecords))
}
|
go
|
{
"resource": ""
}
|
q6698
|
GetUserRecords
|
train
|
func (m *MockCollectorReader) GetUserRecords() map[string]*collector.UserRecord {
ret := m.ctrl.Call(m, "GetUserRecords")
ret0, _ := ret[0].(map[string]*collector.UserRecord)
return ret0
}
|
go
|
{
"resource": ""
}
|
q6699
|
NewMockCollector
|
train
|
func NewMockCollector(ctrl *gomock.Controller) *MockCollector {
mock := &MockCollector{ctrl: ctrl}
mock.recorder = &MockCollectorMockRecorder{mock}
return mock
}
|
go
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.