_id
stringlengths
2
7
title
stringlengths
1
118
partition
stringclasses
3 values
text
stringlengths
52
85.5k
language
stringclasses
1 value
meta_information
dict
q33600
Set
train
func (q *TimeQuantum) Set(value string) error { *q = TimeQuantum(value) return nil }
go
{ "resource": "" }
q33601
viewByTimeUnit
train
func viewByTimeUnit(name string, t time.Time, unit rune) string { switch unit { case 'Y': return fmt.Sprintf("%s_%s", name, t.Format("2006")) case 'M': return fmt.Sprintf("%s_%s", name, t.Format("200601")) case 'D': return fmt.Sprintf("%s_%s", name, t.Format("20060102")) case 'H': return fmt.Sprintf("%s_%s...
go
{ "resource": "" }
q33602
viewsByTime
train
func viewsByTime(name string, t time.Time, q TimeQuantum) []string { // nolint: unparam a := make([]string, 0, len(q)) for _, unit := range q { view := viewByTimeUnit(name, t, unit) if view == "" { continue } a = append(a, view) } return a }
go
{ "resource": "" }
q33603
viewsByTimeRange
train
func viewsByTimeRange(name string, start, end time.Time, q TimeQuantum) []string { // nolint: unparam t := start // Save flags for performance. hasYear := q.HasYear() hasMonth := q.HasMonth() hasDay := q.HasDay() hasHour := q.HasHour() var results []string // Walk up from smallest units to largest units. if...
go
{ "resource": "" }
q33604
parseTime
train
func parseTime(t interface{}) (time.Time, error) { var err error var calcTime time.Time switch v := t.(type) { case string: if calcTime, err = time.Parse(TimeFormat, v); err != nil { return time.Time{}, errors.New("cannot parse string time") } case int64: calcTime = time.Unix(v, 0).UTC() default: retur...
go
{ "resource": "" }
q33605
timeOfView
train
func timeOfView(v string, adj bool) (time.Time, error) { if v == "" { return time.Time{}, nil } layout := "2006010203" timePart := viewTimePart(v) switch len(timePart) { case 4: // year t, err := time.Parse(layout[:4], timePart) if err != nil { return time.Time{}, err } if adj { t = t.AddDate(1,...
go
{ "resource": "" }
q33606
NewCmdIO
train
func NewCmdIO(stdin io.Reader, stdout, stderr io.Writer) *CmdIO { return &CmdIO{ Stdin: stdin, Stdout: stdout, Stderr: stderr, } }
go
{ "resource": "" }
q33607
newExecutor
train
func newExecutor(opts ...executorOption) *executor { e := &executor{ client: newNopInternalQueryClient(), } for _, opt := range opts { err := opt(e) if err != nil { panic(err) } } return e }
go
{ "resource": "" }
q33608
Execute
train
func (e *executor) Execute(ctx context.Context, index string, q *pql.Query, shards []uint64, opt *execOptions) (QueryResponse, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.Execute") defer span.Finish() resp := QueryResponse{} // Check for query cancellation. if err := validateQueryContext(ct...
go
{ "resource": "" }
q33609
readColumnAttrSets
train
func (e *executor) readColumnAttrSets(index *Index, ids []uint64) ([]*ColumnAttrSet, error) { if index == nil { return nil, nil } ax := make([]*ColumnAttrSet, 0, len(ids)) for _, id := range ids { // Read attributes for column. Skip column if empty. attrs, err := index.ColumnAttrStore().Attrs(id) if err !=...
go
{ "resource": "" }
q33610
validateCallArgs
train
func (e *executor) validateCallArgs(c *pql.Call) error { if _, ok := c.Args["ids"]; ok { switch v := c.Args["ids"].(type) { case []int64, []uint64: // noop case []interface{}: b := make([]int64, len(v)) for i := range v { b[i] = v[i].(int64) } c.Args["ids"] = b default: return fmt.Errorf(...
go
{ "resource": "" }
q33611
executeBitmapCall
train
func (e *executor) executeBitmapCall(ctx context.Context, index string, c *pql.Call, shards []uint64, opt *execOptions) (*Row, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeBitmapCall") defer span.Finish() // Execute calls in bulk on each remote node and merge. mapFn := func(shard uint64...
go
{ "resource": "" }
q33612
executeBitmapCallShard
train
func (e *executor) executeBitmapCallShard(ctx context.Context, index string, c *pql.Call, shard uint64) (*Row, error) { if err := validateQueryContext(ctx); err != nil { return nil, err } span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeBitmapCallShard") defer span.Finish() switch c.Name { case...
go
{ "resource": "" }
q33613
executeSumCountShard
train
func (e *executor) executeSumCountShard(ctx context.Context, index string, c *pql.Call, shard uint64) (ValCount, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeSumCountShard") defer span.Finish() var filter *Row if len(c.Children) == 1 { row, err := e.executeBitmapCallShard(ctx, index, ...
go
{ "resource": "" }
q33614
executeTopNShard
train
func (e *executor) executeTopNShard(ctx context.Context, index string, c *pql.Call, shard uint64) ([]Pair, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeTopNShard") defer span.Finish() field, _ := c.Args["_field"].(string) n, _, err := c.UintArg("n") if err != nil { return nil, fmt.Er...
go
{ "resource": "" }
q33615
MarshalJSON
train
func (fr FieldRow) MarshalJSON() ([]byte, error) { if fr.RowKey != "" { return json.Marshal(struct { Field string `json:"field"` RowKey string `json:"rowKey"` }{ Field: fr.Field, RowKey: fr.RowKey, }) } return json.Marshal(struct { Field string `json:"field"` RowID uint64 `json:"rowID"` }{ ...
go
{ "resource": "" }
q33616
String
train
func (fr FieldRow) String() string { return fmt.Sprintf("%s.%d.%s", fr.Field, fr.RowID, fr.RowKey) }
go
{ "resource": "" }
q33617
mergeGroupCounts
train
func mergeGroupCounts(a, b []GroupCount, limit int) []GroupCount { if limit > len(a)+len(b) { limit = len(a) + len(b) } ret := make([]GroupCount, 0, limit) i, j := 0, 0 for i < len(a) && j < len(b) && len(ret) < limit { switch a[i].Compare(b[j]) { case -1: ret = append(ret, a[i]) i++ case 0: a[i]....
go
{ "resource": "" }
q33618
Compare
train
func (g GroupCount) Compare(o GroupCount) int { for i := range g.Group { if g.Group[i].RowID < o.Group[i].RowID { return -1 } if g.Group[i].RowID > o.Group[i].RowID { return 1 } } return 0 }
go
{ "resource": "" }
q33619
remoteExec
train
func (e *executor) remoteExec(ctx context.Context, node *Node, index string, q *pql.Query, shards []uint64) (results []interface{}, err error) { // nolint: interfacer span, ctx := tracing.StartSpanFromContext(ctx, "Executor.executeExec") defer span.Finish() // Encode request object. pbreq := &QueryRequest{ Query...
go
{ "resource": "" }
q33620
shardsByNode
train
func (e *executor) shardsByNode(nodes []*Node, index string, shards []uint64) (map[*Node][]uint64, error) { m := make(map[*Node][]uint64) loop: for _, shard := range shards { for _, node := range e.Cluster.ShardNodes(index, shard) { if Nodes(nodes).Contains(node) { m[node] = append(m[node], shard) conti...
go
{ "resource": "" }
q33621
mapReduce
train
func (e *executor) mapReduce(ctx context.Context, index string, shards []uint64, c *pql.Call, opt *execOptions, mapFn mapFunc, reduceFn reduceFunc) (interface{}, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.mapReduce") defer span.Finish() ch := make(chan mapResponse) // Wrap context with a ca...
go
{ "resource": "" }
q33622
mapperLocal
train
func (e *executor) mapperLocal(ctx context.Context, shards []uint64, mapFn mapFunc, reduceFn reduceFunc) (interface{}, error) { span, ctx := tracing.StartSpanFromContext(ctx, "Executor.mapperLocal") defer span.Finish() ch := make(chan mapResponse, len(shards)) for _, shard := range shards { go func(shard uint64...
go
{ "resource": "" }
q33623
validateQueryContext
train
func validateQueryContext(ctx context.Context) error { select { case <-ctx.Done(): switch err := ctx.Err(); err { case context.Canceled: return ErrQueryCancelled case context.DeadlineExceeded: return ErrQueryTimeout default: return err } default: return nil } }
go
{ "resource": "" }
q33624
smaller
train
func (vc *ValCount) smaller(other ValCount) ValCount { if vc.Count == 0 || (other.Val < vc.Val && other.Count > 0) { return other } return ValCount{ Val: vc.Val, Count: vc.Count, } }
go
{ "resource": "" }
q33625
larger
train
func (vc *ValCount) larger(other ValCount) ValCount { if vc.Count == 0 || (other.Val > vc.Val && other.Count > 0) { return other } return ValCount{ Val: vc.Val, Count: vc.Count, } }
go
{ "resource": "" }
q33626
nextAtIdx
train
func (gbi *groupByIterator) nextAtIdx(i int) { // loop until we find a non-empty row. This is an optimization - the loop and if/break can be removed. for { nr, rowID, wrapped := gbi.rowIters[i].Next() if nr == nil { gbi.done = true return } if wrapped && i != 0 { gbi.nextAtIdx(i - 1) } if i == 0 ...
go
{ "resource": "" }
q33627
Next
train
func (gbi *groupByIterator) Next() (ret GroupCount, done bool) { // loop until we find a result with count > 0 for { if gbi.done { return ret, true } if len(gbi.rows) == 1 { ret.Count = gbi.rows[len(gbi.rows)-1].row.Count() } else { ret.Count = gbi.rows[len(gbi.rows)-1].row.intersectionCount(gbi.rows...
go
{ "resource": "" }
q33628
SetVersion
train
func (d *diagnosticsCollector) SetVersion(v string) { d.version = v d.Set("Version", v) }
go
{ "resource": "" }
q33629
Flush
train
func (d *diagnosticsCollector) Flush() error { d.mu.Lock() defer d.mu.Unlock() d.metrics["Uptime"] = (time.Now().Unix() - d.startTime) buf, err := d.encode() if err != nil { return errors.Wrap(err, "encoding") } req, err := http.NewRequest("POST", d.host, bytes.NewReader(buf)) if err != nil { return errors....
go
{ "resource": "" }
q33630
CheckVersion
train
func (d *diagnosticsCollector) CheckVersion() error { var rsp versionResponse req, err := http.NewRequest("GET", d.VersionURL, nil) if err != nil { return errors.Wrap(err, "making request") } resp, err := d.client.Do(req) if err != nil { return errors.Wrap(err, "getting version") } defer resp.Body.Close() ...
go
{ "resource": "" }
q33631
compareVersion
train
func (d *diagnosticsCollector) compareVersion(value string) error { currentVersion := versionSegments(value) localVersion := versionSegments(d.version) if localVersion[0] < currentVersion[0] { //Major return fmt.Errorf("you are running Pilosa %s, a newer version (%s) is available: https://github.com/pilosa/pilosa...
go
{ "resource": "" }
q33632
Set
train
func (d *diagnosticsCollector) Set(name string, value interface{}) { switch v := value.(type) { case string: if v == "" { // Do not set empty string return } } d.mu.Lock() defer d.mu.Unlock() d.metrics[name] = value }
go
{ "resource": "" }
q33633
logErr
train
func (d *diagnosticsCollector) logErr(err error) bool { if err != nil { d.Logger.Printf("%v", err) return true } return false }
go
{ "resource": "" }
q33634
EnrichWithOSInfo
train
func (d *diagnosticsCollector) EnrichWithOSInfo() { uptime, err := d.server.systemInfo.Uptime() if !d.logErr(err) { d.Set("HostUptime", uptime) } platform, err := d.server.systemInfo.Platform() if !d.logErr(err) { d.Set("OSPlatform", platform) } family, err := d.server.systemInfo.Family() if !d.logErr(err) ...
go
{ "resource": "" }
q33635
EnrichWithMemoryInfo
train
func (d *diagnosticsCollector) EnrichWithMemoryInfo() { memFree, err := d.server.systemInfo.MemFree() if !d.logErr(err) { d.Set("MemFree", memFree) } memTotal, err := d.server.systemInfo.MemTotal() if !d.logErr(err) { d.Set("MemTotal", memTotal) } memUsed, err := d.server.systemInfo.MemUsed() if !d.logErr(e...
go
{ "resource": "" }
q33636
EnrichWithSchemaProperties
train
func (d *diagnosticsCollector) EnrichWithSchemaProperties() { var numShards uint64 numFields := 0 numIndexes := 0 bsiFieldCount := 0 timeQuantumEnabled := false for _, index := range d.server.holder.Indexes() { numShards += index.AvailableShards().Count() numIndexes++ for _, field := range index.Fields() {...
go
{ "resource": "" }
q33637
versionSegments
train
func versionSegments(segments string) []int { segments = strings.Trim(segments, "v") segments = strings.Split(segments, "-")[0] s := strings.Split(segments, ".") segmentSlice := make([]int, len(s)) for i, v := range s { segmentSlice[i], _ = strconv.Atoi(v) } return segmentSlice }
go
{ "resource": "" }
q33638
NewContainer
train
func NewContainer() *Container { statsHit("NewContainer") c := &Container{typ: containerArray, len: 0, cap: stashedArraySize} c.pointer = (*uint16)(unsafe.Pointer(&c.data[0])) return c }
go
{ "resource": "" }
q33639
NewContainerBitmap
train
func NewContainerBitmap(n int32, bitmap []uint64) *Container { if bitmap == nil { bitmap = make([]uint64, bitmapN) } // pad to required length if len(bitmap) < bitmapN { bm2 := make([]uint64, bitmapN) copy(bm2, bitmap) bitmap = bm2 } c := &Container{typ: containerBitmap, n: n} c.setBitmap(bitmap) return...
go
{ "resource": "" }
q33640
NewContainerArray
train
func NewContainerArray(set []uint16) *Container { c := &Container{typ: containerArray, n: int32(len(set))} c.setArray(set) return c }
go
{ "resource": "" }
q33641
array
train
func (c *Container) array() []uint16 { if roaringParanoia { if c.typ != containerArray { panic("attempt to read non-array's array") } } return *(*[]uint16)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(c.pointer)), Len: int(c.len), Cap: int(c.cap)})) }
go
{ "resource": "" }
q33642
setArray
train
func (c *Container) setArray(array []uint16) { if roaringParanoia { if c.typ != containerArray { panic("attempt to write non-array's array") } } // no array: start with our default 5-value array if array == nil { c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), 0, stashedArraySize return ...
go
{ "resource": "" }
q33643
bitmap
train
func (c *Container) bitmap() []uint64 { if roaringParanoia { if c.typ != containerBitmap { panic("attempt to read non-bitmap's bitmap") } } return *(*[]uint64)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(c.pointer)), Len: int(c.len), Cap: int(c.cap)})) }
go
{ "resource": "" }
q33644
setBitmap
train
func (c *Container) setBitmap(bitmap []uint64) { if roaringParanoia { if c.typ != containerBitmap { panic("attempt to write non-bitmap's bitmap") } } h := (*reflect.SliceHeader)(unsafe.Pointer(&bitmap)) c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Len), int32(h.Cap) runtime.KeepAlive...
go
{ "resource": "" }
q33645
runs
train
func (c *Container) runs() []interval16 { if roaringParanoia { if c.typ != containerRun { panic("attempt to read non-run's runs") } } return *(*[]interval16)(unsafe.Pointer(&reflect.SliceHeader{Data: uintptr(unsafe.Pointer(c.pointer)), Len: int(c.len), Cap: int(c.cap)})) }
go
{ "resource": "" }
q33646
setRuns
train
func (c *Container) setRuns(runs []interval16) { if roaringParanoia { if c.typ != containerRun { panic("attempt to write non-run's runs") } } // no array: start with our default 2-value array if runs == nil { c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), 0, stashedRunSize return } h ...
go
{ "resource": "" }
q33647
Update
train
func (c *Container) Update(typ byte, n int32, mapped bool) { c.typ = typ c.n = n c.mapped = mapped // we don't know that any existing slice is usable, so let's ditch it switch c.typ { case containerArray: c.pointer, c.len, c.cap = (*uint16)(unsafe.Pointer(&c.data[0])), int32(0), stashedArraySize case container...
go
{ "resource": "" }
q33648
unmapArray
train
func (c *Container) unmapArray() { if !c.mapped { return } array := c.array() tmp := make([]uint16, c.len) copy(tmp, array) h := (*reflect.SliceHeader)(unsafe.Pointer(&tmp)) c.pointer, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Cap) runtime.KeepAlive(&tmp) c.mapped = false }
go
{ "resource": "" }
q33649
unmapRun
train
func (c *Container) unmapRun() { if !c.mapped { return } runs := c.runs() tmp := make([]interval16, c.len) copy(tmp, runs) h := (*reflect.SliceHeader)(unsafe.Pointer(&tmp)) c.pointer, c.cap = (*uint16)(unsafe.Pointer(h.Data)), int32(h.Cap) c.mapped = false }
go
{ "resource": "" }
q33650
NewConfig
train
func NewConfig() *Config { c := &Config{ DataDir: "~/.pilosa", Bind: ":10101", MaxWritesPerRequest: 5000, // We default these Max File/Map counts very high. This is basically a // backwards compatibility thing where we don't want to cause different // behavior for those who had ...
go
{ "resource": "" }
q33651
validateAddrs
train
func (cfg *Config) validateAddrs(ctx context.Context) error { // Validate the advertise address. advScheme, advHost, advPort, err := validateAdvertiseAddr(ctx, cfg.Advertise, cfg.Bind) if err != nil { return errors.Wrapf(err, "validating advertise address") } cfg.Advertise = schemeHostPortString(advScheme, advHo...
go
{ "resource": "" }
q33652
validateAdvertiseAddr
train
func validateAdvertiseAddr(ctx context.Context, advAddr, listenAddr string) (string, string, string, error) { listenScheme, listenHost, listenPort, err := splitAddr(listenAddr) if err != nil { return "", "", "", errors.Wrap(err, "getting listen address") } advScheme, advHostPort := splitScheme(advAddr) advHost,...
go
{ "resource": "" }
q33653
outboundIP
train
func outboundIP() net.IP { // This is not actually making a connection to 8.8.8.8. // net.Dial() selects the IP address that would be used // if an actual connection to 8.8.8.8 were made, so this // choice of address is just meant to ensure that an // external address is returned (as opposed to a local // address...
go
{ "resource": "" }
q33654
splitAddr
train
func splitAddr(addr string) (string, string, string, error) { scheme, hostPort := splitScheme(addr) host, port := "", "" if hostPort != "" { var err error host, port, err = net.SplitHostPort(hostPort) if err != nil { return "", "", "", errors.Wrapf(err, "splitting host port: %s", hostPort) } } // It's n...
go
{ "resource": "" }
q33655
NewGenerateConfigCommand
train
func NewGenerateConfigCommand(stdin io.Reader, stdout, stderr io.Writer) *GenerateConfigCommand { return &GenerateConfigCommand{ CmdIO: pilosa.NewCmdIO(stdin, stdout, stderr), } }
go
{ "resource": "" }
q33656
newServeCmd
train
func newServeCmd(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command { Server = server.NewCommand(stdin, stdout, stderr) serveCmd := &cobra.Command{ Use: "server", Short: "Run Pilosa.", Long: `pilosa server runs Pilosa. It will load existing data from the configured directory and start listening for cl...
go
{ "resource": "" }
q33657
Get
train
func (c *attrCache) Get(id uint64) map[string]interface{} { c.mu.RLock() defer c.mu.RUnlock() attrs := c.attrs[id] if attrs == nil { return nil } // Make a copy for safety ret := make(map[string]interface{}) for k, v := range attrs { ret[k] = v } return ret }
go
{ "resource": "" }
q33658
Set
train
func (c *attrCache) Set(id uint64, attrs map[string]interface{}) { c.mu.Lock() defer c.mu.Unlock() c.attrs[id] = attrs }
go
{ "resource": "" }
q33659
NewAttrStore
train
func NewAttrStore(path string) pilosa.AttrStore { return &attrStore{ path: path, attrCache: newAttrCache(), } }
go
{ "resource": "" }
q33660
Open
train
func (s *attrStore) Open() error { // Open storage. db, err := bolt.Open(s.path, 0666, &bolt.Options{Timeout: 1 * time.Second}) if err != nil { return errors.Wrap(err, "opening storage") } s.db = db // Initialize database. if err := s.db.Update(func(tx *bolt.Tx) error { _, err := tx.CreateBucketIfNotExists(...
go
{ "resource": "" }
q33661
Attrs
train
func (s *attrStore) Attrs(id uint64) (m map[string]interface{}, err error) { s.mu.RLock() defer s.mu.RUnlock() // Check cache for map. if m = s.attrCache.Get(id); m != nil { return m, nil } // Find attributes from storage. if err = s.db.View(func(tx *bolt.Tx) error { m, err = txAttrs(tx, id) return err ...
go
{ "resource": "" }
q33662
SetAttrs
train
func (s *attrStore) SetAttrs(id uint64, m map[string]interface{}) error { // Ignore empty maps. if len(m) == 0 { return nil } // Check if the attributes already exist under a read-only lock. if attr, err := s.Attrs(id); err != nil { return errors.Wrap(err, "checking attrs") } else if attr != nil && mapContai...
go
{ "resource": "" }
q33663
SetBulkAttrs
train
func (s *attrStore) SetBulkAttrs(m map[uint64]map[string]interface{}) error { s.mu.Lock() defer s.mu.Unlock() attrs := make(map[uint64]map[string]interface{}) if err := s.db.Update(func(tx *bolt.Tx) error { // Collect and sort keys. ids := make([]uint64, 0, len(m)) for id := range m { ids = append(ids, id...
go
{ "resource": "" }
q33664
Blocks
train
func (s *attrStore) Blocks() (blocks []pilosa.AttrBlock, err error) { err = s.db.View(func(tx *bolt.Tx) error { // Wrap cursor to segment by block. cur := newBlockCursor(tx.Bucket([]byte("attrs")).Cursor(), attrBlockSize) // Iterate over each block. for cur.nextBlock() { block := pilosa.AttrBlock{ID: cur.b...
go
{ "resource": "" }
q33665
BlockData
train
func (s *attrStore) BlockData(i uint64) (m map[uint64]map[string]interface{}, err error) { m = make(map[uint64]map[string]interface{}) // Start read-only transaction. err = s.db.View(func(tx *bolt.Tx) error { // Move to the start of the block. min := u64tob(i * attrBlockSize) max := u64tob((i + 1) * attrBlock...
go
{ "resource": "" }
q33666
txAttrs
train
func txAttrs(tx *bolt.Tx, id uint64) (map[string]interface{}, error) { v := tx.Bucket([]byte("attrs")).Get(u64tob(id)) if v == nil { return emptyMap, nil } return pilosa.DecodeAttrs(v) }
go
{ "resource": "" }
q33667
txUpdateAttrs
train
func txUpdateAttrs(tx *bolt.Tx, id uint64, m map[string]interface{}) (map[string]interface{}, error) { attr, err := txAttrs(tx, id) if err != nil { return nil, err } // Create a new map if it is empty so we don't update emptyMap. if len(attr) == 0 { attr = make(map[string]interface{}, len(m)) } // Merge at...
go
{ "resource": "" }
q33668
mapContains
train
func mapContains(m, subset map[string]interface{}) bool { for k, v := range subset { value, ok := m[k] if !ok || value != v { return false } } return true }
go
{ "resource": "" }
q33669
newBlockCursor
train
func newBlockCursor(c *bolt.Cursor, n int) blockCursor { // nolint: unparam cur := blockCursor{ cur: c, n: uint64(n), } cur.buf.key, cur.buf.value = c.First() cur.buf.filled = true return cur }
go
{ "resource": "" }
q33670
nextBlock
train
func (cur *blockCursor) nextBlock() bool { if cur.buf.key == nil { return false } cur.base = binary.BigEndian.Uint64(cur.buf.key) / cur.n return true }
go
{ "resource": "" }
q33671
NewImportCommand
train
func NewImportCommand(stdin io.Reader, stdout, stderr io.Writer) *ImportCommand { return &ImportCommand{ CmdIO: pilosa.NewCmdIO(stdin, stdout, stderr), BufferSize: 10000000, } }
go
{ "resource": "" }
q33672
Run
train
func (cmd *ImportCommand) Run(ctx context.Context) error { logger := log.New(cmd.Stderr, "", log.LstdFlags) // Validate arguments. // Index and field are validated early before the files are parsed. if cmd.Index == "" { return pilosa.ErrIndexRequired } else if cmd.Field == "" { return pilosa.ErrFieldRequired ...
go
{ "resource": "" }
q33673
importPath
train
func (cmd *ImportCommand) importPath(ctx context.Context, fieldType string, useColumnKeys, useRowKeys bool, path string) error { // If fieldType is `int`, treat the import data as values to be range-encoded. if fieldType == pilosa.FieldTypeInt { return cmd.bufferValues(ctx, useColumnKeys, path) } return cmd.buffe...
go
{ "resource": "" }
q33674
bufferBits
train
func (cmd *ImportCommand) bufferBits(ctx context.Context, useColumnKeys, useRowKeys bool, path string) error { a := make([]pilosa.Bit, 0, cmd.BufferSize) var r *csv.Reader if path != "-" { // Open file for reading. f, err := os.Open(path) if err != nil { return errors.Wrap(err, "opening file") } defer...
go
{ "resource": "" }
q33675
importBits
train
func (cmd *ImportCommand) importBits(ctx context.Context, useColumnKeys, useRowKeys bool, bits []pilosa.Bit) error { logger := log.New(cmd.Stderr, "", log.LstdFlags) // If keys are used, all bits are sent to the primary translate store (i.e. coordinator). if useColumnKeys || useRowKeys { logger.Printf("importing ...
go
{ "resource": "" }
q33676
bufferValues
train
func (cmd *ImportCommand) bufferValues(ctx context.Context, useColumnKeys bool, path string) error { a := make([]pilosa.FieldValue, 0, cmd.BufferSize) var r *csv.Reader if path != "-" { // Open file for reading. f, err := os.Open(path) if err != nil { return errors.Wrap(err, "opening file") } defer f....
go
{ "resource": "" }
q33677
importValues
train
func (cmd *ImportCommand) importValues(ctx context.Context, useColumnKeys bool, vals []pilosa.FieldValue) error { logger := log.New(cmd.Stderr, "", log.LstdFlags) // If keys are used, all values are sent to the primary translate store (i.e. coordinator). if useColumnKeys { logger.Printf("importing keyed values: n...
go
{ "resource": "" }
q33678
endCall
train
func (q *Query) endCall() *Call { elem := q.callStack[len(q.callStack)-1] q.callStack[len(q.callStack)-1] = nil q.callStack = q.callStack[:len(q.callStack)-1] return elem.call }
go
{ "resource": "" }
q33679
WriteCallN
train
func (q *Query) WriteCallN() int { var n int for _, call := range q.Calls { switch call.Name { case "Set", "Clear", "SetRowAttrs", "SetColumnAttrs": n++ } } return n }
go
{ "resource": "" }
q33680
String
train
func (q *Query) String() string { a := make([]string, len(q.Calls)) for i, call := range q.Calls { a[i] = call.String() } return strings.Join(a, "\n") }
go
{ "resource": "" }
q33681
UintArg
train
func (c *Call) UintArg(key string) (uint64, bool, error) { val, ok := c.Args[key] if !ok { return 0, false, nil } switch tval := val.(type) { case int64: if tval < 0 { return 0, true, fmt.Errorf("value for '%s' must be positive, but got %v", key, tval) } return uint64(tval), true, nil case uint64: re...
go
{ "resource": "" }
q33682
CallArg
train
func (c *Call) CallArg(key string) (*Call, bool, error) { val, ok := c.Args[key] if !ok { return nil, false, nil } switch tval := val.(type) { case *Call: return tval, true, nil default: return nil, true, fmt.Errorf("could not convert %v of type %T to Call in Call.CallArg", tval, tval) } }
go
{ "resource": "" }
q33683
keys
train
func (c *Call) keys() []string { a := make([]string, 0, len(c.Args)) for k := range c.Args { a = append(a, k) } sort.Strings(a) return a }
go
{ "resource": "" }
q33684
String
train
func (c *Call) String() string { var buf bytes.Buffer // Write name. if c.Name != "" { buf.WriteString(c.Name) } else { buf.WriteString("!UNNAMED") } // Write opening. buf.WriteByte('(') // Write child list. for i, child := range c.Children { if i > 0 { buf.WriteString(", ") } buf.WriteString(c...
go
{ "resource": "" }
q33685
HasConditionArg
train
func (c *Call) HasConditionArg() bool { for _, v := range c.Args { if _, ok := v.(*Condition); ok { return true } } return false }
go
{ "resource": "" }
q33686
String
train
func (cond *Condition) String() string { return fmt.Sprintf("%s %s", cond.Op.String(), formatValue(cond.Value)) }
go
{ "resource": "" }
q33687
CopyArgs
train
func CopyArgs(m map[string]interface{}) map[string]interface{} { other := make(map[string]interface{}, len(m)) for k, v := range m { other[k] = v } return other }
go
{ "resource": "" }
q33688
MarshalJSON
train
func (resp *QueryResponse) MarshalJSON() ([]byte, error) { if resp.Err != nil { return json.Marshal(struct { Err string `json:"error"` }{Err: resp.Err.Error()}) } return json.Marshal(struct { Results []interface{} `json:"results"` ColumnAttrSets []*ColumnAttrSet `json:"columnAttrs,omitempty"` ...
go
{ "resource": "" }
q33689
ParseString
train
func ParseString(s string) (*Query, error) { return NewParser(strings.NewReader(s)).Parse() }
go
{ "resource": "" }
q33690
Parse
train
func (p *parser) Parse() (*Query, error) { buf, err := ioutil.ReadAll(p.r) if err != nil { return nil, errors.Wrap(err, "reading buffer to parse") } p.PQL = PQL{ Buffer: string(buf), } p.Init() err = p.PQL.Parse() if err != nil { return nil, errors.Wrap(err, "parsing") } // Handle specific panics from ...
go
{ "resource": "" }
q33691
OptHandlerCloseTimeout
train
func OptHandlerCloseTimeout(d time.Duration) handlerOption { return func(h *Handler) error { h.closeTimeout = d return nil } }
go
{ "resource": "" }
q33692
NewHandler
train
func NewHandler(opts ...handlerOption) (*Handler, error) { handler := &Handler{ logger: logger.NopLogger, closeTimeout: time.Second * 30, } handler.Handler = newRouter(handler) handler.populateValidators() for _, opt := range opts { err := opt(handler) if err != nil { return nil, errors.Wrap(err,...
go
{ "resource": "" }
q33693
Close
train
func (h *Handler) Close() error { deadlineCtx, cancelFunc := context.WithDeadline(context.Background(), time.Now().Add(h.closeTimeout)) defer cancelFunc() err := h.server.Shutdown(deadlineCtx) if err != nil { err = h.server.Close() } return errors.Wrap(err, "shutdown/close http server") }
go
{ "resource": "" }
q33694
ServeHTTP
train
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { defer func() { if err := recover(); err != nil { w.WriteHeader(http.StatusInternalServerError) stack := debug.Stack() msg := "PANIC: %s\n%s" h.logger.Printf(msg, err, stack) fmt.Fprintf(w, msg, err, stack) } }() t := time.Now()...
go
{ "resource": "" }
q33695
check
train
func (r *successResponse) check(err error) (statusCode int) { if err == nil { r.Success = true return 0 } cause := errors.Cause(err) // Determine HTTP status code based on the error type. switch cause.(type) { case pilosa.BadRequestError: statusCode = http.StatusBadRequest case pilosa.ConflictError: st...
go
{ "resource": "" }
q33696
write
train
func (r *successResponse) write(w http.ResponseWriter, err error) { // Apply the error and get the status code. statusCode := r.check(err) // Marshal the json response. msg, err := json.Marshal(r) if err != nil { http.Error(w, string(msg), http.StatusInternalServerError) return } // Write the response. if...
go
{ "resource": "" }
q33697
UnmarshalJSON
train
func (p *postIndexRequest) UnmarshalJSON(b []byte) error { // m is an overflow map used to capture additional, unexpected keys. m := make(map[string]interface{}) if err := json.Unmarshal(b, &m); err != nil { return errors.Wrap(err, "unmarshalling unexpected values") } validIndexOptions := getValidOptions(pilos...
go
{ "resource": "" }
q33698
validateOptions
train
func validateOptions(data map[string]interface{}, validIndexOptions []string) error { for k, v := range data { switch k { case "options": options, ok := v.(map[string]interface{}) if !ok { return errors.New("options is not map[string]interface{}") } for kk, vv := range options { if !foundItem(v...
go
{ "resource": "" }
q33699
readQueryRequest
train
func (h *Handler) readQueryRequest(r *http.Request) (*pilosa.QueryRequest, error) { switch r.Header.Get("Content-Type") { case "application/x-protobuf": return h.readProtobufQueryRequest(r) default: return h.readURLQueryRequest(r) } }
go
{ "resource": "" }