id int32 0 167k | repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1 value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
16,600 | pilosa/pdk | map.go | ID | func (m FloatMapper) ID(fi ...interface{}) (rowIDs []int64, err error) {
f := fi[0].(float64)
externalID := int64(len(m.Buckets))
if f < m.Buckets[0] || f > m.Buckets[len(m.Buckets)-1] {
if m.allowExternal {
return []int64{externalID}, nil
}
return []int64{0}, fmt.Errorf("float %v out of range", f)
}
// TODO: make clear decision about which way the equality goes, and document it
// TODO: use binary search if there are a lot of buckets
for i, v := range m.Buckets {
if f < v {
return []int64{int64(i)}, nil
}
}
// this should be unreachable (TODO test)
return []int64{0}, nil
} | go | func (m FloatMapper) ID(fi ...interface{}) (rowIDs []int64, err error) {
f := fi[0].(float64)
externalID := int64(len(m.Buckets))
if f < m.Buckets[0] || f > m.Buckets[len(m.Buckets)-1] {
if m.allowExternal {
return []int64{externalID}, nil
}
return []int64{0}, fmt.Errorf("float %v out of range", f)
}
// TODO: make clear decision about which way the equality goes, and document it
// TODO: use binary search if there are a lot of buckets
for i, v := range m.Buckets {
if f < v {
return []int64{int64(i)}, nil
}
}
// this should be unreachable (TODO test)
return []int64{0}, nil
} | [
"func",
"(",
"m",
"FloatMapper",
")",
"ID",
"(",
"fi",
"...",
"interface",
"{",
"}",
")",
"(",
"rowIDs",
"[",
"]",
"int64",
",",
"err",
"error",
")",
"{",
"f",
":=",
"fi",
"[",
"0",
"]",
".",
"(",
"float64",
")",
"\n",
"externalID",
":=",
"int6... | // ID maps floats to arbitrary buckets | [
"ID",
"maps",
"floats",
"to",
"arbitrary",
"buckets"
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/map.go#L288-L307 |
16,601 | pilosa/pdk | map.go | ID | func (m GridMapper) ID(xyi ...interface{}) (rowIDs []int64, err error) {
x := xyi[0].(float64)
y := xyi[1].(float64)
externalID := m.Xres * m.Yres
// bounds check
if x < m.Xmin || x > m.Xmax || y < m.Ymin || y > m.Ymax {
if m.allowExternal {
return []int64{externalID}, nil
}
return []int64{0}, fmt.Errorf("point (%v, %v) out of range", x, y)
}
// compute x bin
xInt := int64(float64(m.Xres) * (x - m.Xmin) / (m.Xmax - m.Xmin))
// compute y bin
yInt := int64(float64(m.Yres) * (y - m.Ymin) / (m.Ymax - m.Ymin))
rowID := (m.Yres * xInt) + yInt
return []int64{rowID}, nil
} | go | func (m GridMapper) ID(xyi ...interface{}) (rowIDs []int64, err error) {
x := xyi[0].(float64)
y := xyi[1].(float64)
externalID := m.Xres * m.Yres
// bounds check
if x < m.Xmin || x > m.Xmax || y < m.Ymin || y > m.Ymax {
if m.allowExternal {
return []int64{externalID}, nil
}
return []int64{0}, fmt.Errorf("point (%v, %v) out of range", x, y)
}
// compute x bin
xInt := int64(float64(m.Xres) * (x - m.Xmin) / (m.Xmax - m.Xmin))
// compute y bin
yInt := int64(float64(m.Yres) * (y - m.Ymin) / (m.Ymax - m.Ymin))
rowID := (m.Yres * xInt) + yInt
return []int64{rowID}, nil
} | [
"func",
"(",
"m",
"GridMapper",
")",
"ID",
"(",
"xyi",
"...",
"interface",
"{",
"}",
")",
"(",
"rowIDs",
"[",
"]",
"int64",
",",
"err",
"error",
")",
"{",
"x",
":=",
"xyi",
"[",
"0",
"]",
".",
"(",
"float64",
")",
"\n",
"y",
":=",
"xyi",
"[",... | // ID maps pairs of floats to regular buckets | [
"ID",
"maps",
"pairs",
"of",
"floats",
"to",
"regular",
"buckets"
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/map.go#L316-L337 |
16,602 | pilosa/pdk | boltdb/translator.go | Close | func (bt *Translator) Close() error {
err := bt.Db.Sync()
if err != nil {
return errors.Wrap(err, "syncing db")
}
return bt.Db.Close()
} | go | func (bt *Translator) Close() error {
err := bt.Db.Sync()
if err != nil {
return errors.Wrap(err, "syncing db")
}
return bt.Db.Close()
} | [
"func",
"(",
"bt",
"*",
"Translator",
")",
"Close",
"(",
")",
"error",
"{",
"err",
":=",
"bt",
".",
"Db",
".",
"Sync",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}"... | // Close syncs and closes the underlying boltdb. | [
"Close",
"syncs",
"and",
"closes",
"the",
"underlying",
"boltdb",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/boltdb/translator.go#L63-L69 |
16,603 | pilosa/pdk | boltdb/translator.go | NewTranslator | func NewTranslator(filename string, fields ...string) (bt *Translator, err error) {
bt = &Translator{
fields: make(map[string]struct{}),
}
bt.Db, err = bolt.Open(filename, 0600, &bolt.Options{Timeout: 1 * time.Second, InitialMmapSize: 50000000, NoGrowSync: true})
if err != nil {
return nil, errors.Wrapf(err, "opening db file '%v'", filename)
}
bt.Db.MaxBatchDelay = 400 * time.Microsecond
err = bt.Db.Update(func(tx *bolt.Tx) error {
ib, err := tx.CreateBucketIfNotExists(idBucket)
if err != nil {
return errors.Wrap(err, "creating idKey bucket")
}
vb, err := tx.CreateBucketIfNotExists(valBucket)
if err != nil {
return errors.Wrap(err, "creating valKey bucket")
}
for _, field := range fields {
_, _, err = bt.addField(ib, vb, field)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, errors.Wrap(err, "ensuring bucket existence")
}
return bt, nil
} | go | func NewTranslator(filename string, fields ...string) (bt *Translator, err error) {
bt = &Translator{
fields: make(map[string]struct{}),
}
bt.Db, err = bolt.Open(filename, 0600, &bolt.Options{Timeout: 1 * time.Second, InitialMmapSize: 50000000, NoGrowSync: true})
if err != nil {
return nil, errors.Wrapf(err, "opening db file '%v'", filename)
}
bt.Db.MaxBatchDelay = 400 * time.Microsecond
err = bt.Db.Update(func(tx *bolt.Tx) error {
ib, err := tx.CreateBucketIfNotExists(idBucket)
if err != nil {
return errors.Wrap(err, "creating idKey bucket")
}
vb, err := tx.CreateBucketIfNotExists(valBucket)
if err != nil {
return errors.Wrap(err, "creating valKey bucket")
}
for _, field := range fields {
_, _, err = bt.addField(ib, vb, field)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, errors.Wrap(err, "ensuring bucket existence")
}
return bt, nil
} | [
"func",
"NewTranslator",
"(",
"filename",
"string",
",",
"fields",
"...",
"string",
")",
"(",
"bt",
"*",
"Translator",
",",
"err",
"error",
")",
"{",
"bt",
"=",
"&",
"Translator",
"{",
"fields",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
... | // NewTranslator gets a new Translator | [
"NewTranslator",
"gets",
"a",
"new",
"Translator"
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/boltdb/translator.go#L72-L102 |
16,604 | pilosa/pdk | boltdb/translator.go | BulkAdd | func (bt *Translator) BulkAdd(field string, values [][]byte) error {
var batchSize uint64 = 10000
var batch uint64
for batch*batchSize < uint64(len(values)) {
err := bt.Db.Batch(func(tx *bolt.Tx) error {
fib := tx.Bucket(idBucket).Bucket([]byte(field))
fvb := tx.Bucket(valBucket).Bucket([]byte(field))
for i := batch * batchSize; i < (batch+1)*batchSize && i < uint64(len(values)); i++ {
idBytes := make([]byte, 8)
binary.BigEndian.PutUint64(idBytes, i)
valBytes := values[i]
err := fib.Put(idBytes, valBytes)
if err != nil {
return errors.Wrap(err, "putting into idKey bucket")
}
err = fvb.Put(valBytes, idBytes)
if err != nil {
return errors.Wrap(err, "putting into valKey bucket")
}
}
return nil
})
if err != nil {
return errors.Wrap(err, "inserting batch")
}
batch++
}
return nil
} | go | func (bt *Translator) BulkAdd(field string, values [][]byte) error {
var batchSize uint64 = 10000
var batch uint64
for batch*batchSize < uint64(len(values)) {
err := bt.Db.Batch(func(tx *bolt.Tx) error {
fib := tx.Bucket(idBucket).Bucket([]byte(field))
fvb := tx.Bucket(valBucket).Bucket([]byte(field))
for i := batch * batchSize; i < (batch+1)*batchSize && i < uint64(len(values)); i++ {
idBytes := make([]byte, 8)
binary.BigEndian.PutUint64(idBytes, i)
valBytes := values[i]
err := fib.Put(idBytes, valBytes)
if err != nil {
return errors.Wrap(err, "putting into idKey bucket")
}
err = fvb.Put(valBytes, idBytes)
if err != nil {
return errors.Wrap(err, "putting into valKey bucket")
}
}
return nil
})
if err != nil {
return errors.Wrap(err, "inserting batch")
}
batch++
}
return nil
} | [
"func",
"(",
"bt",
"*",
"Translator",
")",
"BulkAdd",
"(",
"field",
"string",
",",
"values",
"[",
"]",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"batchSize",
"uint64",
"=",
"10000",
"\n",
"var",
"batch",
"uint64",
"\n",
"for",
"batch",
"*",
"batchS... | // BulkAdd adds many values to a field at once, allocating ids. | [
"BulkAdd",
"adds",
"many",
"values",
"to",
"a",
"field",
"at",
"once",
"allocating",
"ids",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/boltdb/translator.go#L206-L235 |
16,605 | pilosa/pdk | kafka/source.go | Record | func (s *Source) Record() (interface{}, error) {
if s.MaxMsgs > 0 {
s.numMsgs++
if s.numMsgs > s.MaxMsgs {
return nil, io.EOF
}
}
msg, ok := <-s.consumer.Messages()
if ok {
var ret interface{}
switch s.Type {
case "json":
parsed := make(map[string]interface{})
err := json.Unmarshal(msg.Value, &parsed)
if err != nil {
return nil, errors.Wrap(err, "unmarshaling json")
}
ret = parsed
case "raw":
ret = msg
default:
return nil, errors.Errorf("unsupported kafka message type: '%v'", s.Type)
}
s.consumer.MarkOffset(msg, "") // mark message as processed
return ret, nil
}
return nil, errors.New("messages channel closed")
} | go | func (s *Source) Record() (interface{}, error) {
if s.MaxMsgs > 0 {
s.numMsgs++
if s.numMsgs > s.MaxMsgs {
return nil, io.EOF
}
}
msg, ok := <-s.consumer.Messages()
if ok {
var ret interface{}
switch s.Type {
case "json":
parsed := make(map[string]interface{})
err := json.Unmarshal(msg.Value, &parsed)
if err != nil {
return nil, errors.Wrap(err, "unmarshaling json")
}
ret = parsed
case "raw":
ret = msg
default:
return nil, errors.Errorf("unsupported kafka message type: '%v'", s.Type)
}
s.consumer.MarkOffset(msg, "") // mark message as processed
return ret, nil
}
return nil, errors.New("messages channel closed")
} | [
"func",
"(",
"s",
"*",
"Source",
")",
"Record",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"s",
".",
"MaxMsgs",
">",
"0",
"{",
"s",
".",
"numMsgs",
"++",
"\n",
"if",
"s",
".",
"numMsgs",
">",
"s",
".",
"MaxMsgs",
"{",... | // Record returns the value of the next kafka message. | [
"Record",
"returns",
"the",
"value",
"of",
"the",
"next",
"kafka",
"message",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/kafka/source.go#L75-L102 |
16,606 | pilosa/pdk | kafka/source.go | Open | func (s *Source) Open() error {
// init (custom) config, enable errors and notifications
sarama.Logger = log.New(ioutil.Discard, "", 0)
config := cluster.NewConfig()
config.Config.Version = sarama.V0_10_0_0
config.Consumer.Return.Errors = true
config.Consumer.Offsets.Initial = sarama.OffsetOldest
config.Group.Return.Notifications = true
var err error
s.consumer, err = cluster.NewConsumer(s.Hosts, s.Group, s.Topics, config)
if err != nil {
return errors.Wrap(err, "getting new consumer")
}
s.messages = s.consumer.Messages()
// consume errors
go func() {
for err := range s.consumer.Errors() {
log.Printf("Error: %s\n", err.Error())
}
}()
// consume notifications
go func() {
for ntf := range s.consumer.Notifications() {
log.Printf("Rebalanced: %+v\n", ntf)
}
}()
return nil
} | go | func (s *Source) Open() error {
// init (custom) config, enable errors and notifications
sarama.Logger = log.New(ioutil.Discard, "", 0)
config := cluster.NewConfig()
config.Config.Version = sarama.V0_10_0_0
config.Consumer.Return.Errors = true
config.Consumer.Offsets.Initial = sarama.OffsetOldest
config.Group.Return.Notifications = true
var err error
s.consumer, err = cluster.NewConsumer(s.Hosts, s.Group, s.Topics, config)
if err != nil {
return errors.Wrap(err, "getting new consumer")
}
s.messages = s.consumer.Messages()
// consume errors
go func() {
for err := range s.consumer.Errors() {
log.Printf("Error: %s\n", err.Error())
}
}()
// consume notifications
go func() {
for ntf := range s.consumer.Notifications() {
log.Printf("Rebalanced: %+v\n", ntf)
}
}()
return nil
} | [
"func",
"(",
"s",
"*",
"Source",
")",
"Open",
"(",
")",
"error",
"{",
"// init (custom) config, enable errors and notifications",
"sarama",
".",
"Logger",
"=",
"log",
".",
"New",
"(",
"ioutil",
".",
"Discard",
",",
"\"",
"\"",
",",
"0",
")",
"\n",
"config"... | // Open initializes the kafka source. | [
"Open",
"initializes",
"the",
"kafka",
"source",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/kafka/source.go#L105-L135 |
16,607 | pilosa/pdk | kafka/source.go | Close | func (s *Source) Close() error {
err := s.consumer.Close()
return errors.Wrap(err, "closing kafka consumer")
} | go | func (s *Source) Close() error {
err := s.consumer.Close()
return errors.Wrap(err, "closing kafka consumer")
} | [
"func",
"(",
"s",
"*",
"Source",
")",
"Close",
"(",
")",
"error",
"{",
"err",
":=",
"s",
".",
"consumer",
".",
"Close",
"(",
")",
"\n",
"return",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // Close closes the underlying kafka consumer. | [
"Close",
"closes",
"the",
"underlying",
"kafka",
"consumer",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/kafka/source.go#L138-L141 |
16,608 | pilosa/pdk | kafka/source.go | NewConfluentSource | func NewConfluentSource() *ConfluentSource {
src := &ConfluentSource{
cache: make(map[int32]avro.Schema),
}
src.Type = "raw"
return src
} | go | func NewConfluentSource() *ConfluentSource {
src := &ConfluentSource{
cache: make(map[int32]avro.Schema),
}
src.Type = "raw"
return src
} | [
"func",
"NewConfluentSource",
"(",
")",
"*",
"ConfluentSource",
"{",
"src",
":=",
"&",
"ConfluentSource",
"{",
"cache",
":",
"make",
"(",
"map",
"[",
"int32",
"]",
"avro",
".",
"Schema",
")",
",",
"}",
"\n",
"src",
".",
"Type",
"=",
"\"",
"\"",
"\n",... | // NewConfluentSource returns a new ConfluentSource. | [
"NewConfluentSource",
"returns",
"a",
"new",
"ConfluentSource",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/kafka/source.go#L153-L159 |
16,609 | pilosa/pdk | kafka/source.go | Record | func (s *ConfluentSource) Record() (interface{}, error) {
rec, err := s.Source.Record()
if err != nil {
return rec, err
}
msg, ok := rec.(*sarama.ConsumerMessage)
if !ok {
return rec, errors.Errorf("record is not a raw kafka record, but a %T", rec)
}
val := msg.Value
return s.decodeAvroValueWithSchemaRegistry(val)
} | go | func (s *ConfluentSource) Record() (interface{}, error) {
rec, err := s.Source.Record()
if err != nil {
return rec, err
}
msg, ok := rec.(*sarama.ConsumerMessage)
if !ok {
return rec, errors.Errorf("record is not a raw kafka record, but a %T", rec)
}
val := msg.Value
return s.decodeAvroValueWithSchemaRegistry(val)
} | [
"func",
"(",
"s",
"*",
"ConfluentSource",
")",
"Record",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"rec",
",",
"err",
":=",
"s",
".",
"Source",
".",
"Record",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"rec",
"... | // Record returns the next value from kafka. | [
"Record",
"returns",
"the",
"next",
"value",
"from",
"kafka",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/kafka/source.go#L162-L173 |
16,610 | pilosa/pdk | entity.go | Literal | func (e *Entity) Literal(path ...string) (Literal, error) {
var cur = e
var ok bool
var lit Literal
for i, prop := range path {
var val Object
val, ok = cur.Objects[Property(prop)]
if !ok {
return nil, ErrPathNotFound
}
if i == len(path)-1 {
lit, ok = val.(Literal)
if !ok {
return nil, errors.Wrapf(ErrNotALiteral, "%#v", cur)
}
return lit, nil
}
cur, ok = val.(*Entity)
if !ok {
return nil, ErrPathNotFound
}
}
return nil, ErrEmptyPath
} | go | func (e *Entity) Literal(path ...string) (Literal, error) {
var cur = e
var ok bool
var lit Literal
for i, prop := range path {
var val Object
val, ok = cur.Objects[Property(prop)]
if !ok {
return nil, ErrPathNotFound
}
if i == len(path)-1 {
lit, ok = val.(Literal)
if !ok {
return nil, errors.Wrapf(ErrNotALiteral, "%#v", cur)
}
return lit, nil
}
cur, ok = val.(*Entity)
if !ok {
return nil, ErrPathNotFound
}
}
return nil, ErrEmptyPath
} | [
"func",
"(",
"e",
"*",
"Entity",
")",
"Literal",
"(",
"path",
"...",
"string",
")",
"(",
"Literal",
",",
"error",
")",
"{",
"var",
"cur",
"=",
"e",
"\n",
"var",
"ok",
"bool",
"\n",
"var",
"lit",
"Literal",
"\n",
"for",
"i",
",",
"prop",
":=",
"... | // Literal gets the literal at the path in the Entity. | [
"Literal",
"gets",
"the",
"literal",
"at",
"the",
"path",
"in",
"the",
"Entity",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/entity.go#L123-L146 |
16,611 | pilosa/pdk | entity.go | F64 | func (e *Entity) F64(path ...string) (F64, error) {
lit, err := e.Literal(path...)
if err != nil {
return 0, errors.Wrap(err, "getting literal")
}
f64, ok := lit.(F64)
if !ok {
return 0, errors.Wrapf(ErrUnexpectedType, "%#v not a float64", lit)
}
return f64, nil
} | go | func (e *Entity) F64(path ...string) (F64, error) {
lit, err := e.Literal(path...)
if err != nil {
return 0, errors.Wrap(err, "getting literal")
}
f64, ok := lit.(F64)
if !ok {
return 0, errors.Wrapf(ErrUnexpectedType, "%#v not a float64", lit)
}
return f64, nil
} | [
"func",
"(",
"e",
"*",
"Entity",
")",
"F64",
"(",
"path",
"...",
"string",
")",
"(",
"F64",
",",
"error",
")",
"{",
"lit",
",",
"err",
":=",
"e",
".",
"Literal",
"(",
"path",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
","... | // F64 tries to get a float64 at the given path in the Entity. | [
"F64",
"tries",
"to",
"get",
"a",
"float64",
"at",
"the",
"given",
"path",
"in",
"the",
"Entity",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/entity.go#L149-L159 |
16,612 | pilosa/pdk | entity.go | SetPath | func (e *Entity) SetPath(path ...string) (*Entity, error) {
var cur = e
for i, prop := range path {
val, ok := cur.Objects[Property(prop)]
if !ok {
cur.Objects[Property(prop)] = NewEntity()
cur = cur.Objects[Property(prop)].(*Entity)
continue
}
cur, ok = val.(*Entity)
if !ok {
return nil, errors.Wrapf(ErrPathNotFound, "depth %d property %v, not an entity %#v", i, prop, val)
}
}
return cur, nil
} | go | func (e *Entity) SetPath(path ...string) (*Entity, error) {
var cur = e
for i, prop := range path {
val, ok := cur.Objects[Property(prop)]
if !ok {
cur.Objects[Property(prop)] = NewEntity()
cur = cur.Objects[Property(prop)].(*Entity)
continue
}
cur, ok = val.(*Entity)
if !ok {
return nil, errors.Wrapf(ErrPathNotFound, "depth %d property %v, not an entity %#v", i, prop, val)
}
}
return cur, nil
} | [
"func",
"(",
"e",
"*",
"Entity",
")",
"SetPath",
"(",
"path",
"...",
"string",
")",
"(",
"*",
"Entity",
",",
"error",
")",
"{",
"var",
"cur",
"=",
"e",
"\n",
"for",
"i",
",",
"prop",
":=",
"range",
"path",
"{",
"val",
",",
"ok",
":=",
"cur",
... | // SetPath ensures that a path exists, creating Entities along the way if
// necessary. If it encounters a non-Entity, it will return an error. | [
"SetPath",
"ensures",
"that",
"a",
"path",
"exists",
"creating",
"Entities",
"along",
"the",
"way",
"if",
"necessary",
".",
"If",
"it",
"encounters",
"a",
"non",
"-",
"Entity",
"it",
"will",
"return",
"an",
"error",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/entity.go#L170-L185 |
16,613 | pilosa/pdk | cmd/s3.go | NewS3Command | func NewS3Command(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
var err error
S3Main = s3.NewMain()
s3Command := &cobra.Command{
Use: "s3",
Short: "Index line separated json from objects in an S3 bucket.",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
err = S3Main.Run()
if err != nil {
return err
}
log.Println("Done: ", time.Since(start))
select {}
},
}
flags := s3Command.Flags()
err = commandeer.Flags(flags, S3Main)
if err != nil {
panic(err)
}
return s3Command
} | go | func NewS3Command(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
var err error
S3Main = s3.NewMain()
s3Command := &cobra.Command{
Use: "s3",
Short: "Index line separated json from objects in an S3 bucket.",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
err = S3Main.Run()
if err != nil {
return err
}
log.Println("Done: ", time.Since(start))
select {}
},
}
flags := s3Command.Flags()
err = commandeer.Flags(flags, S3Main)
if err != nil {
panic(err)
}
return s3Command
} | [
"func",
"NewS3Command",
"(",
"stdin",
"io",
".",
"Reader",
",",
"stdout",
",",
"stderr",
"io",
".",
"Writer",
")",
"*",
"cobra",
".",
"Command",
"{",
"var",
"err",
"error",
"\n",
"S3Main",
"=",
"s3",
".",
"NewMain",
"(",
")",
"\n",
"s3Command",
":=",... | // NewS3Command returns a new cobra command wrapping S3Main. | [
"NewS3Command",
"returns",
"a",
"new",
"cobra",
"command",
"wrapping",
"S3Main",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/cmd/s3.go#L49-L71 |
16,614 | pilosa/pdk | json/source.go | NewSource | func NewSource(r io.Reader) *Source {
return &Source{
dec: json.NewDecoder(r),
}
} | go | func NewSource(r io.Reader) *Source {
return &Source{
dec: json.NewDecoder(r),
}
} | [
"func",
"NewSource",
"(",
"r",
"io",
".",
"Reader",
")",
"*",
"Source",
"{",
"return",
"&",
"Source",
"{",
"dec",
":",
"json",
".",
"NewDecoder",
"(",
"r",
")",
",",
"}",
"\n",
"}"
] | // NewSource gets a new json source which will decode from the given reader. | [
"NewSource",
"gets",
"a",
"new",
"json",
"source",
"which",
"will",
"decode",
"from",
"the",
"given",
"reader",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/json/source.go#L14-L18 |
16,615 | pilosa/pdk | termstat/termstat.go | NewCollector | func NewCollector(out io.Writer) *Collector {
ts := &Collector{
indexes: make(map[string]int),
out: out,
}
go func() {
tick := time.NewTicker(time.Second * 2)
for ; ; <-tick.C {
ts.write()
}
}()
return ts
} | go | func NewCollector(out io.Writer) *Collector {
ts := &Collector{
indexes: make(map[string]int),
out: out,
}
go func() {
tick := time.NewTicker(time.Second * 2)
for ; ; <-tick.C {
ts.write()
}
}()
return ts
} | [
"func",
"NewCollector",
"(",
"out",
"io",
".",
"Writer",
")",
"*",
"Collector",
"{",
"ts",
":=",
"&",
"Collector",
"{",
"indexes",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"int",
")",
",",
"out",
":",
"out",
",",
"}",
"\n",
"go",
"func",
"(",... | // NewCollector initializes and returns a new TermStat. | [
"NewCollector",
"initializes",
"and",
"returns",
"a",
"new",
"TermStat",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/termstat/termstat.go#L60-L72 |
16,616 | pilosa/pdk | termstat/termstat.go | Count | func (t *Collector) Count(name string, value int64, rate float64, tags ...string) {
t.lock.Lock()
t.changed = true
defer t.lock.Unlock()
idx, ok := t.indexes[name]
if !ok {
idx = len(t.stats)
t.stats = append(t.stats, 0)
t.names = append(t.names, name)
t.indexes[name] = idx
}
if rate < 1 {
if rand.Float64() > rate {
return
}
}
t.stats[idx] += value
} | go | func (t *Collector) Count(name string, value int64, rate float64, tags ...string) {
t.lock.Lock()
t.changed = true
defer t.lock.Unlock()
idx, ok := t.indexes[name]
if !ok {
idx = len(t.stats)
t.stats = append(t.stats, 0)
t.names = append(t.names, name)
t.indexes[name] = idx
}
if rate < 1 {
if rand.Float64() > rate {
return
}
}
t.stats[idx] += value
} | [
"func",
"(",
"t",
"*",
"Collector",
")",
"Count",
"(",
"name",
"string",
",",
"value",
"int64",
",",
"rate",
"float64",
",",
"tags",
"...",
"string",
")",
"{",
"t",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"t",
".",
"changed",
"=",
"true",
"\n",... | // Count adds value to the named stat at the specified rate. | [
"Count",
"adds",
"value",
"to",
"the",
"named",
"stat",
"at",
"the",
"specified",
"rate",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/termstat/termstat.go#L75-L93 |
16,617 | pilosa/pdk | walker.go | Walk | func Walk(e *Entity, call func(path []string, l Literal) error) error {
for prop, val := range e.Objects {
err := walkObj(val, []string{string(prop)}, call)
if err != nil {
return errors.Wrap(err, "walking object")
}
}
return nil
} | go | func Walk(e *Entity, call func(path []string, l Literal) error) error {
for prop, val := range e.Objects {
err := walkObj(val, []string{string(prop)}, call)
if err != nil {
return errors.Wrap(err, "walking object")
}
}
return nil
} | [
"func",
"Walk",
"(",
"e",
"*",
"Entity",
",",
"call",
"func",
"(",
"path",
"[",
"]",
"string",
",",
"l",
"Literal",
")",
"error",
")",
"error",
"{",
"for",
"prop",
",",
"val",
":=",
"range",
"e",
".",
"Objects",
"{",
"err",
":=",
"walkObj",
"(",
... | // Walk recursively visits every Object in the Entity and calls "call" with
// every Literal and it's path. | [
"Walk",
"recursively",
"visits",
"every",
"Object",
"in",
"the",
"Entity",
"and",
"calls",
"call",
"with",
"every",
"Literal",
"and",
"it",
"s",
"path",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/walker.go#L43-L51 |
16,618 | pilosa/pdk | http/command.go | NewMain | func NewMain() *Main {
return &Main{
Bind: ":12121",
PilosaHosts: []string{"localhost:10101"},
Index: "jsonhttp",
BatchSize: 10,
Framer: pdk.DashField{},
Proxy: ":13131",
}
} | go | func NewMain() *Main {
return &Main{
Bind: ":12121",
PilosaHosts: []string{"localhost:10101"},
Index: "jsonhttp",
BatchSize: 10,
Framer: pdk.DashField{},
Proxy: ":13131",
}
} | [
"func",
"NewMain",
"(",
")",
"*",
"Main",
"{",
"return",
"&",
"Main",
"{",
"Bind",
":",
"\"",
"\"",
",",
"PilosaHosts",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"Index",
":",
"\"",
"\"",
",",
"BatchSize",
":",
"10",
",",
"Framer",
":... | // NewMain gets a new Main with default values. | [
"NewMain",
"gets",
"a",
"new",
"Main",
"with",
"default",
"values",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/http/command.go#L66-L75 |
16,619 | pilosa/pdk | http/command.go | Run | func (m *Main) Run() error {
src, err := NewJSONSource(WithAddr(m.Bind))
if err != nil {
return errors.Wrap(err, "getting json source")
}
if m.TranslatorDir == "" {
m.TranslatorDir, err = ioutil.TempDir("", "pdk")
if err != nil {
return errors.Wrap(err, "creating temp directory")
}
}
log.Println("listening on", src.Addr())
translateColumns := true
parser := pdk.NewDefaultGenericParser()
if len(m.SubjectPath) == 0 {
parser.Subjecter = pdk.BlankSubjecter{}
translateColumns = false
} else {
parser.EntitySubjecter = pdk.SubjectPath(m.SubjectPath)
}
mapper := pdk.NewCollapsingMapper()
mapper.Translator, err = leveldb.NewTranslator(m.TranslatorDir)
if err != nil {
return errors.Wrap(err, "creating translator")
}
mapper.Framer = &m.Framer
if translateColumns {
log.Println("translating columns")
mapper.ColTranslator, err = leveldb.NewFieldTranslator(m.TranslatorDir, "__columns")
if err != nil {
return errors.Wrap(err, "creating column translator")
}
} else {
log.Println("not translating columns")
}
indexer, err := pdk.SetupPilosa(m.PilosaHosts, m.Index, nil, m.BatchSize)
if err != nil {
return errors.Wrap(err, "setting up Pilosa")
}
ingester := pdk.NewIngester(src, parser, mapper, indexer)
if len(m.AllowedFields) > 0 {
ingester.AllowedFields = make(map[string]bool)
for _, fram := range m.AllowedFields {
ingester.AllowedFields[fram] = true
}
}
m.proxy = http.Server{
Addr: m.Proxy,
Handler: pdk.NewPilosaForwarder(m.PilosaHosts[0], mapper.Translator, mapper.ColTranslator),
}
go func() {
err := m.proxy.ListenAndServe()
if err != nil {
log.Printf("proxy closed: %v", err)
}
}()
return errors.Wrap(ingester.Run(), "running ingester")
} | go | func (m *Main) Run() error {
src, err := NewJSONSource(WithAddr(m.Bind))
if err != nil {
return errors.Wrap(err, "getting json source")
}
if m.TranslatorDir == "" {
m.TranslatorDir, err = ioutil.TempDir("", "pdk")
if err != nil {
return errors.Wrap(err, "creating temp directory")
}
}
log.Println("listening on", src.Addr())
translateColumns := true
parser := pdk.NewDefaultGenericParser()
if len(m.SubjectPath) == 0 {
parser.Subjecter = pdk.BlankSubjecter{}
translateColumns = false
} else {
parser.EntitySubjecter = pdk.SubjectPath(m.SubjectPath)
}
mapper := pdk.NewCollapsingMapper()
mapper.Translator, err = leveldb.NewTranslator(m.TranslatorDir)
if err != nil {
return errors.Wrap(err, "creating translator")
}
mapper.Framer = &m.Framer
if translateColumns {
log.Println("translating columns")
mapper.ColTranslator, err = leveldb.NewFieldTranslator(m.TranslatorDir, "__columns")
if err != nil {
return errors.Wrap(err, "creating column translator")
}
} else {
log.Println("not translating columns")
}
indexer, err := pdk.SetupPilosa(m.PilosaHosts, m.Index, nil, m.BatchSize)
if err != nil {
return errors.Wrap(err, "setting up Pilosa")
}
ingester := pdk.NewIngester(src, parser, mapper, indexer)
if len(m.AllowedFields) > 0 {
ingester.AllowedFields = make(map[string]bool)
for _, fram := range m.AllowedFields {
ingester.AllowedFields[fram] = true
}
}
m.proxy = http.Server{
Addr: m.Proxy,
Handler: pdk.NewPilosaForwarder(m.PilosaHosts[0], mapper.Translator, mapper.ColTranslator),
}
go func() {
err := m.proxy.ListenAndServe()
if err != nil {
log.Printf("proxy closed: %v", err)
}
}()
return errors.Wrap(ingester.Run(), "running ingester")
} | [
"func",
"(",
"m",
"*",
"Main",
")",
"Run",
"(",
")",
"error",
"{",
"src",
",",
"err",
":=",
"NewJSONSource",
"(",
"WithAddr",
"(",
"m",
".",
"Bind",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
","... | // Run runs the http command. | [
"Run",
"runs",
"the",
"http",
"command",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/http/command.go#L78-L141 |
16,620 | pilosa/pdk | file/source.go | OptSrcPath | func OptSrcPath(pathname string) SrcOption {
return func(s *Source) error {
info, err := os.Stat(pathname)
if err != nil {
return errors.Wrap(err, "statting path")
}
if info.IsDir() {
infos, err := ioutil.ReadDir(pathname)
if err != nil {
return errors.Wrap(err, "reading directory")
}
s.files = make([]string, 0, len(infos))
for _, info = range infos {
s.files = append(s.files, path.Join(pathname, info.Name()))
}
} else {
s.files = []string{pathname}
}
return nil
}
} | go | func OptSrcPath(pathname string) SrcOption {
return func(s *Source) error {
info, err := os.Stat(pathname)
if err != nil {
return errors.Wrap(err, "statting path")
}
if info.IsDir() {
infos, err := ioutil.ReadDir(pathname)
if err != nil {
return errors.Wrap(err, "reading directory")
}
s.files = make([]string, 0, len(infos))
for _, info = range infos {
s.files = append(s.files, path.Join(pathname, info.Name()))
}
} else {
s.files = []string{pathname}
}
return nil
}
} | [
"func",
"OptSrcPath",
"(",
"pathname",
"string",
")",
"SrcOption",
"{",
"return",
"func",
"(",
"s",
"*",
"Source",
")",
"error",
"{",
"info",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"pathname",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // OptSrcPath sets the path name for the file or directory to use for source
// data. | [
"OptSrcPath",
"sets",
"the",
"path",
"name",
"for",
"the",
"file",
"or",
"directory",
"to",
"use",
"for",
"source",
"data",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/file/source.go#L35-L55 |
16,621 | pilosa/pdk | file/source.go | NewSource | func NewSource(opts ...SrcOption) (*Source, error) {
s := &Source{
records: make(chan record, 100),
}
for _, opt := range opts {
err := opt(s)
if err != nil {
return nil, err
}
}
go s.run()
return s, nil
} | go | func NewSource(opts ...SrcOption) (*Source, error) {
s := &Source{
records: make(chan record, 100),
}
for _, opt := range opts {
err := opt(s)
if err != nil {
return nil, err
}
}
go s.run()
return s, nil
} | [
"func",
"NewSource",
"(",
"opts",
"...",
"SrcOption",
")",
"(",
"*",
"Source",
",",
"error",
")",
"{",
"s",
":=",
"&",
"Source",
"{",
"records",
":",
"make",
"(",
"chan",
"record",
",",
"100",
")",
",",
"}",
"\n",
"for",
"_",
",",
"opt",
":=",
... | // NewSource gets a new file source which will index json data from a file or
// all files in a directory. | [
"NewSource",
"gets",
"a",
"new",
"file",
"source",
"which",
"will",
"index",
"json",
"data",
"from",
"a",
"file",
"or",
"all",
"files",
"in",
"a",
"directory",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/file/source.go#L82-L94 |
16,622 | pilosa/pdk | cmd/weather.go | NewWeatherCommand | func NewWeatherCommand(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
WeatherMain = weather.NewMain()
weatherCommand := &cobra.Command{
Use: "weather",
Short: "Add weather data to taxi index.",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
err := WeatherMain.Run()
if err != nil {
return err
}
log.Println("Done: ", time.Since(start))
select {}
},
}
flags := weatherCommand.Flags()
flags.IntVarP(&WeatherMain.Concurrency, "concurrency", "c", 8, "Number of goroutines fetching and parsing")
flags.IntVarP(&WeatherMain.BufferSize, "buffer-size", "b", 1000000, "Size of buffer for importers - heavily affects memory usage")
flags.StringVarP(&WeatherMain.PilosaHost, "pilosa", "p", "localhost:10101", "Pilosa host")
flags.StringVarP(&WeatherMain.Index, "index", "i", "taxi", "Pilosa db to write to")
flags.StringVarP(&WeatherMain.WeatherCache.URLFile, "url-file", "f", "usecase/weather/urls.txt", "File to get raw data urls from. Urls may be http or local files.")
return weatherCommand
} | go | func NewWeatherCommand(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
WeatherMain = weather.NewMain()
weatherCommand := &cobra.Command{
Use: "weather",
Short: "Add weather data to taxi index.",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
err := WeatherMain.Run()
if err != nil {
return err
}
log.Println("Done: ", time.Since(start))
select {}
},
}
flags := weatherCommand.Flags()
flags.IntVarP(&WeatherMain.Concurrency, "concurrency", "c", 8, "Number of goroutines fetching and parsing")
flags.IntVarP(&WeatherMain.BufferSize, "buffer-size", "b", 1000000, "Size of buffer for importers - heavily affects memory usage")
flags.StringVarP(&WeatherMain.PilosaHost, "pilosa", "p", "localhost:10101", "Pilosa host")
flags.StringVarP(&WeatherMain.Index, "index", "i", "taxi", "Pilosa db to write to")
flags.StringVarP(&WeatherMain.WeatherCache.URLFile, "url-file", "f", "usecase/weather/urls.txt", "File to get raw data urls from. Urls may be http or local files.")
return weatherCommand
} | [
"func",
"NewWeatherCommand",
"(",
"stdin",
"io",
".",
"Reader",
",",
"stdout",
",",
"stderr",
"io",
".",
"Writer",
")",
"*",
"cobra",
".",
"Command",
"{",
"WeatherMain",
"=",
"weather",
".",
"NewMain",
"(",
")",
"\n",
"weatherCommand",
":=",
"&",
"cobra"... | // NewWeatherCommand wraps weather.Main with cobra.Command for use from a CLI. | [
"NewWeatherCommand",
"wraps",
"weather",
".",
"Main",
"with",
"cobra",
".",
"Command",
"for",
"use",
"from",
"a",
"CLI",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/cmd/weather.go#L48-L71 |
16,623 | pilosa/pdk | pilosa.go | AddColumnTimestamp | func (i *Index) AddColumnTimestamp(field string, row, col uint64OrString, ts time.Time) {
i.addColumn(field, row, col, ts.UnixNano())
} | go | func (i *Index) AddColumnTimestamp(field string, row, col uint64OrString, ts time.Time) {
i.addColumn(field, row, col, ts.UnixNano())
} | [
"func",
"(",
"i",
"*",
"Index",
")",
"AddColumnTimestamp",
"(",
"field",
"string",
",",
"row",
",",
"col",
"uint64OrString",
",",
"ts",
"time",
".",
"Time",
")",
"{",
"i",
".",
"addColumn",
"(",
"field",
",",
"row",
",",
"col",
",",
"ts",
".",
"Uni... | // AddColumnTimestamp adds a column to be imported to Pilosa with a timestamp. | [
"AddColumnTimestamp",
"adds",
"a",
"column",
"to",
"be",
"imported",
"to",
"Pilosa",
"with",
"a",
"timestamp",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/pilosa.go#L68-L70 |
16,624 | pilosa/pdk | pilosa.go | AddColumn | func (i *Index) AddColumn(field string, col, row uint64OrString) {
i.addColumn(field, col, row, 0)
} | go | func (i *Index) AddColumn(field string, col, row uint64OrString) {
i.addColumn(field, col, row, 0)
} | [
"func",
"(",
"i",
"*",
"Index",
")",
"AddColumn",
"(",
"field",
"string",
",",
"col",
",",
"row",
"uint64OrString",
")",
"{",
"i",
".",
"addColumn",
"(",
"field",
",",
"col",
",",
"row",
",",
"0",
")",
"\n",
"}"
] | // AddColumn adds a column to be imported to Pilosa. | [
"AddColumn",
"adds",
"a",
"column",
"to",
"be",
"imported",
"to",
"Pilosa",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/pilosa.go#L73-L75 |
16,625 | pilosa/pdk | pilosa.go | AddValue | func (i *Index) AddValue(fieldName string, col uint64OrString, val int64) {
var c chanRecordIterator
var ok bool
if !validUint64OrString(col) {
panic(fmt.Sprintf("a %T was passed, must be eithe uint64 or string", col))
}
i.lock.RLock()
if c, ok = i.recordChans[fieldName]; !ok {
i.lock.RUnlock()
i.lock.Lock()
defer i.lock.Unlock()
field := i.index.Field(fieldName, gopilosa.OptFieldTypeInt(0, 1<<31-1))
err := i.setupField(field)
if err != nil {
log.Println(errors.Wrap(err, "setting up field"))
return
}
c = i.recordChans[fieldName]
} else {
i.lock.RUnlock()
}
c <- gopilosa.FieldValue{ColumnID: uint64Cast(col), ColumnKey: stringCast(col), Value: val}
} | go | func (i *Index) AddValue(fieldName string, col uint64OrString, val int64) {
var c chanRecordIterator
var ok bool
if !validUint64OrString(col) {
panic(fmt.Sprintf("a %T was passed, must be eithe uint64 or string", col))
}
i.lock.RLock()
if c, ok = i.recordChans[fieldName]; !ok {
i.lock.RUnlock()
i.lock.Lock()
defer i.lock.Unlock()
field := i.index.Field(fieldName, gopilosa.OptFieldTypeInt(0, 1<<31-1))
err := i.setupField(field)
if err != nil {
log.Println(errors.Wrap(err, "setting up field"))
return
}
c = i.recordChans[fieldName]
} else {
i.lock.RUnlock()
}
c <- gopilosa.FieldValue{ColumnID: uint64Cast(col), ColumnKey: stringCast(col), Value: val}
} | [
"func",
"(",
"i",
"*",
"Index",
")",
"AddValue",
"(",
"fieldName",
"string",
",",
"col",
"uint64OrString",
",",
"val",
"int64",
")",
"{",
"var",
"c",
"chanRecordIterator",
"\n",
"var",
"ok",
"bool",
"\n\n",
"if",
"!",
"validUint64OrString",
"(",
"col",
"... | // AddValue adds a value to be imported to Pilosa. | [
"AddValue",
"adds",
"a",
"value",
"to",
"be",
"imported",
"to",
"Pilosa",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/pilosa.go#L135-L159 |
16,626 | pilosa/pdk | pilosa.go | Close | func (i *Index) Close() error {
for _, cbi := range i.recordChans {
close(cbi)
}
i.importWG.Wait()
return nil
} | go | func (i *Index) Close() error {
for _, cbi := range i.recordChans {
close(cbi)
}
i.importWG.Wait()
return nil
} | [
"func",
"(",
"i",
"*",
"Index",
")",
"Close",
"(",
")",
"error",
"{",
"for",
"_",
",",
"cbi",
":=",
"range",
"i",
".",
"recordChans",
"{",
"close",
"(",
"cbi",
")",
"\n",
"}",
"\n",
"i",
".",
"importWG",
".",
"Wait",
"(",
")",
"\n",
"return",
... | // Close ensures that all ongoing imports have finished and cleans up internal
// state. | [
"Close",
"ensures",
"that",
"all",
"ongoing",
"imports",
"have",
"finished",
"and",
"cleans",
"up",
"internal",
"state",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/pilosa.go#L163-L169 |
16,627 | pilosa/pdk | pilosa.go | SetupPilosa | func SetupPilosa(hosts []string, indexName string, schema *gopilosa.Schema, batchsize uint) (Indexer, error) {
if schema == nil {
schema = gopilosa.NewSchema()
}
indexer := newIndex()
indexer.batchSize = batchsize
client, err := gopilosa.NewClient(hosts,
gopilosa.OptClientSocketTimeout(time.Minute*60),
gopilosa.OptClientConnectTimeout(time.Second*60))
if err != nil {
return nil, errors.Wrap(err, "creating pilosa cluster client")
}
indexer.client = client
indexer.index = schema.Index(indexName)
err = client.SyncSchema(schema)
if err != nil {
return nil, errors.Wrap(err, "synchronizing schema")
}
for _, field := range indexer.index.Fields() {
err := indexer.setupField(field)
if err != nil {
return nil, errors.Wrapf(err, "setting up field '%s'", field.Name())
}
}
return indexer, nil
} | go | func SetupPilosa(hosts []string, indexName string, schema *gopilosa.Schema, batchsize uint) (Indexer, error) {
if schema == nil {
schema = gopilosa.NewSchema()
}
indexer := newIndex()
indexer.batchSize = batchsize
client, err := gopilosa.NewClient(hosts,
gopilosa.OptClientSocketTimeout(time.Minute*60),
gopilosa.OptClientConnectTimeout(time.Second*60))
if err != nil {
return nil, errors.Wrap(err, "creating pilosa cluster client")
}
indexer.client = client
indexer.index = schema.Index(indexName)
err = client.SyncSchema(schema)
if err != nil {
return nil, errors.Wrap(err, "synchronizing schema")
}
for _, field := range indexer.index.Fields() {
err := indexer.setupField(field)
if err != nil {
return nil, errors.Wrapf(err, "setting up field '%s'", field.Name())
}
}
return indexer, nil
} | [
"func",
"SetupPilosa",
"(",
"hosts",
"[",
"]",
"string",
",",
"indexName",
"string",
",",
"schema",
"*",
"gopilosa",
".",
"Schema",
",",
"batchsize",
"uint",
")",
"(",
"Indexer",
",",
"error",
")",
"{",
"if",
"schema",
"==",
"nil",
"{",
"schema",
"=",
... | // SetupPilosa returns a new Indexer after creating the given fields and starting importers. | [
"SetupPilosa",
"returns",
"a",
"new",
"Indexer",
"after",
"creating",
"the",
"given",
"fields",
"and",
"starting",
"importers",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/pilosa.go#L204-L229 |
16,628 | pilosa/pdk | cmd/kafka.go | NewKafkaCommand | func NewKafkaCommand(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
var err error
KafkaMain = kafka.NewMain()
kafkaCommand := &cobra.Command{
Use: "kafka",
Short: "Index data from kafka in Pilosa.",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
err = KafkaMain.Run()
if err != nil {
return err
}
log.Println("Done: ", time.Since(start))
select {}
},
}
flags := kafkaCommand.Flags()
err = commandeer.Flags(flags, KafkaMain)
if err != nil {
panic(err)
}
return kafkaCommand
} | go | func NewKafkaCommand(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
var err error
KafkaMain = kafka.NewMain()
kafkaCommand := &cobra.Command{
Use: "kafka",
Short: "Index data from kafka in Pilosa.",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
err = KafkaMain.Run()
if err != nil {
return err
}
log.Println("Done: ", time.Since(start))
select {}
},
}
flags := kafkaCommand.Flags()
err = commandeer.Flags(flags, KafkaMain)
if err != nil {
panic(err)
}
return kafkaCommand
} | [
"func",
"NewKafkaCommand",
"(",
"stdin",
"io",
".",
"Reader",
",",
"stdout",
",",
"stderr",
"io",
".",
"Writer",
")",
"*",
"cobra",
".",
"Command",
"{",
"var",
"err",
"error",
"\n",
"KafkaMain",
"=",
"kafka",
".",
"NewMain",
"(",
")",
"\n",
"kafkaComma... | // NewKafkaCommand returns a new cobra command wrapping KafkaMain. | [
"NewKafkaCommand",
"returns",
"a",
"new",
"cobra",
"command",
"wrapping",
"KafkaMain",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/cmd/kafka.go#L50-L72 |
16,629 | pilosa/pdk | usecase/ssb/cmd.go | NewMain | func NewMain() (*Main, error) {
return &Main{
Index: "ssb",
ReadConcurrency: 1,
MapConcurrency: 4,
RecordBuf: 1000000,
nexter: pdk.NewNexter(),
}, nil
} | go | func NewMain() (*Main, error) {
return &Main{
Index: "ssb",
ReadConcurrency: 1,
MapConcurrency: 4,
RecordBuf: 1000000,
nexter: pdk.NewNexter(),
}, nil
} | [
"func",
"NewMain",
"(",
")",
"(",
"*",
"Main",
",",
"error",
")",
"{",
"return",
"&",
"Main",
"{",
"Index",
":",
"\"",
"\"",
",",
"ReadConcurrency",
":",
"1",
",",
"MapConcurrency",
":",
"4",
",",
"RecordBuf",
":",
"1000000",
",",
"nexter",
":",
"p... | // NewMain crates a new Main with default values. | [
"NewMain",
"crates",
"a",
"new",
"Main",
"with",
"default",
"values",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/usecase/ssb/cmd.go#L67-L76 |
16,630 | pilosa/pdk | usecase/ssb/cmd.go | Run | func (m *Main) Run() (err error) {
m.trans, err = newTranslator("ssdbmapping")
if err != nil {
return errors.Wrap(err, "getting new translator")
}
log.Println("setting up pilosa")
schema, err := m.schema()
if err != nil {
return errors.Wrap(err, "describing schema")
}
m.index, err = pdk.SetupPilosa(m.Hosts, m.Index, schema, 1000000)
if err != nil {
return errors.Wrap(err, "setting up Pilosa")
}
log.Println("reading in edge tables.")
custs, parts, supps, dates, err := m.setupEdgeTables()
if err != nil {
return errors.Wrap(err, "setting up edge tables")
}
log.Println("reading lineorder table.")
rc := make(chan *record, m.RecordBuf) // TODO tweak for perf
go func() {
err := m.runReaders(rc, custs, parts, supps, dates)
if err != nil {
log.Println(errors.Wrap(err, "running readers"))
}
close(rc)
}()
log.Println("running mappers")
err = m.runMappers(rc)
if err != nil {
return errors.Wrap(err, "running mappers")
}
log.Println("mappers finished - starting proxy")
ph := pdk.NewPilosaForwarder("localhost:10101", m.trans)
return pdk.StartMappingProxy("localhost:3456", ph)
} | go | func (m *Main) Run() (err error) {
m.trans, err = newTranslator("ssdbmapping")
if err != nil {
return errors.Wrap(err, "getting new translator")
}
log.Println("setting up pilosa")
schema, err := m.schema()
if err != nil {
return errors.Wrap(err, "describing schema")
}
m.index, err = pdk.SetupPilosa(m.Hosts, m.Index, schema, 1000000)
if err != nil {
return errors.Wrap(err, "setting up Pilosa")
}
log.Println("reading in edge tables.")
custs, parts, supps, dates, err := m.setupEdgeTables()
if err != nil {
return errors.Wrap(err, "setting up edge tables")
}
log.Println("reading lineorder table.")
rc := make(chan *record, m.RecordBuf) // TODO tweak for perf
go func() {
err := m.runReaders(rc, custs, parts, supps, dates)
if err != nil {
log.Println(errors.Wrap(err, "running readers"))
}
close(rc)
}()
log.Println("running mappers")
err = m.runMappers(rc)
if err != nil {
return errors.Wrap(err, "running mappers")
}
log.Println("mappers finished - starting proxy")
ph := pdk.NewPilosaForwarder("localhost:10101", m.trans)
return pdk.StartMappingProxy("localhost:3456", ph)
} | [
"func",
"(",
"m",
"*",
"Main",
")",
"Run",
"(",
")",
"(",
"err",
"error",
")",
"{",
"m",
".",
"trans",
",",
"err",
"=",
"newTranslator",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrap",
"(",
"err",
"... | // Run runs Main. | [
"Run",
"runs",
"Main",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/usecase/ssb/cmd.go#L79-L120 |
16,631 | pilosa/pdk | cmd/file.go | NewFileCommand | func NewFileCommand(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
var err error
FileMain = file.NewMain()
fileCommand := &cobra.Command{
Use: "file",
Short: "Index line separated json from objects from a file or all files in a directory.",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
err = FileMain.Run()
if err != nil {
return err
}
log.Println("Done: ", time.Since(start))
select {}
},
}
flags := fileCommand.Flags()
err = commandeer.Flags(flags, FileMain)
if err != nil {
panic(err)
}
return fileCommand
} | go | func NewFileCommand(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
var err error
FileMain = file.NewMain()
fileCommand := &cobra.Command{
Use: "file",
Short: "Index line separated json from objects from a file or all files in a directory.",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
err = FileMain.Run()
if err != nil {
return err
}
log.Println("Done: ", time.Since(start))
select {}
},
}
flags := fileCommand.Flags()
err = commandeer.Flags(flags, FileMain)
if err != nil {
panic(err)
}
return fileCommand
} | [
"func",
"NewFileCommand",
"(",
"stdin",
"io",
".",
"Reader",
",",
"stdout",
",",
"stderr",
"io",
".",
"Writer",
")",
"*",
"cobra",
".",
"Command",
"{",
"var",
"err",
"error",
"\n",
"FileMain",
"=",
"file",
".",
"NewMain",
"(",
")",
"\n",
"fileCommand",... | // NewFileCommand returns a new cobra command wrapping FileMain. | [
"NewFileCommand",
"returns",
"a",
"new",
"cobra",
"command",
"wrapping",
"FileMain",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/cmd/file.go#L17-L39 |
16,632 | pilosa/pdk | fake/event.go | NewEventGenerator | func NewEventGenerator(seed int64) *EventGenerator {
return &EventGenerator{
r: rand.New(rand.NewSource(seed)),
g: gen.NewGenerator(seed + 1),
}
} | go | func NewEventGenerator(seed int64) *EventGenerator {
return &EventGenerator{
r: rand.New(rand.NewSource(seed)),
g: gen.NewGenerator(seed + 1),
}
} | [
"func",
"NewEventGenerator",
"(",
"seed",
"int64",
")",
"*",
"EventGenerator",
"{",
"return",
"&",
"EventGenerator",
"{",
"r",
":",
"rand",
".",
"New",
"(",
"rand",
".",
"NewSource",
"(",
"seed",
")",
")",
",",
"g",
":",
"gen",
".",
"NewGenerator",
"("... | // NewEventGenerator gets a new EventGenerator. | [
"NewEventGenerator",
"gets",
"a",
"new",
"EventGenerator",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/fake/event.go#L120-L125 |
16,633 | pilosa/pdk | fake/event.go | Event | func (g *EventGenerator) Event() *Event {
active, alive := g.r.Intn(2) > 0, g.r.Intn(2) > 0
return &Event{
ID: fmt.Sprintf("%d", g.r.Uint64()),
Station: g.g.String(6, 2000),
UserID: int(g.g.Uint64(100000000)) + 1,
Timestamp: g.g.Time(time.Date(2017, time.January, 1, 0, 0, 0, 0, time.UTC), time.Second*3).Format(time.RFC3339),
Favorites: g.genFavorites(),
Items: g.genItems(),
Ranking: g.genItems(),
IfaceThing: String(g.g.String(5, 5)),
Velocity: g.r.Intn(1000) + 2500,
Active: active,
Alive: alive,
DeceasedBoolean: alive,
Geo: g.genGeo(),
}
} | go | func (g *EventGenerator) Event() *Event {
active, alive := g.r.Intn(2) > 0, g.r.Intn(2) > 0
return &Event{
ID: fmt.Sprintf("%d", g.r.Uint64()),
Station: g.g.String(6, 2000),
UserID: int(g.g.Uint64(100000000)) + 1,
Timestamp: g.g.Time(time.Date(2017, time.January, 1, 0, 0, 0, 0, time.UTC), time.Second*3).Format(time.RFC3339),
Favorites: g.genFavorites(),
Items: g.genItems(),
Ranking: g.genItems(),
IfaceThing: String(g.g.String(5, 5)),
Velocity: g.r.Intn(1000) + 2500,
Active: active,
Alive: alive,
DeceasedBoolean: alive,
Geo: g.genGeo(),
}
} | [
"func",
"(",
"g",
"*",
"EventGenerator",
")",
"Event",
"(",
")",
"*",
"Event",
"{",
"active",
",",
"alive",
":=",
"g",
".",
"r",
".",
"Intn",
"(",
"2",
")",
">",
"0",
",",
"g",
".",
"r",
".",
"Intn",
"(",
"2",
")",
">",
"0",
"\n",
"return",... | // Event generates a random event. | [
"Event",
"generates",
"a",
"random",
"event",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/fake/event.go#L128-L147 |
16,634 | pilosa/pdk | parse.go | Parse | func (p IntParser) Parse(field string) (result interface{}, err error) {
return strconv.ParseInt(field, 10, 64)
} | go | func (p IntParser) Parse(field string) (result interface{}, err error) {
return strconv.ParseInt(field, 10, 64)
} | [
"func",
"(",
"p",
"IntParser",
")",
"Parse",
"(",
"field",
"string",
")",
"(",
"result",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"return",
"strconv",
".",
"ParseInt",
"(",
"field",
",",
"10",
",",
"64",
")",
"\n",
"}"
] | // Parse parses an integer string to an int64 value | [
"Parse",
"parses",
"an",
"integer",
"string",
"to",
"an",
"int64",
"value"
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/parse.go#L67-L69 |
16,635 | pilosa/pdk | parse.go | Parse | func (p FloatParser) Parse(field string) (result interface{}, err error) {
return strconv.ParseFloat(field, 64)
} | go | func (p FloatParser) Parse(field string) (result interface{}, err error) {
return strconv.ParseFloat(field, 64)
} | [
"func",
"(",
"p",
"FloatParser",
")",
"Parse",
"(",
"field",
"string",
")",
"(",
"result",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"return",
"strconv",
".",
"ParseFloat",
"(",
"field",
",",
"64",
")",
"\n",
"}"
] | // Parse parses a float string to a float64 value | [
"Parse",
"parses",
"a",
"float",
"string",
"to",
"a",
"float64",
"value"
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/parse.go#L72-L74 |
16,636 | pilosa/pdk | parse.go | Parse | func (p StringParser) Parse(field string) (result interface{}, err error) {
return field, nil
} | go | func (p StringParser) Parse(field string) (result interface{}, err error) {
return field, nil
} | [
"func",
"(",
"p",
"StringParser",
")",
"Parse",
"(",
"field",
"string",
")",
"(",
"result",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"return",
"field",
",",
"nil",
"\n",
"}"
] | // Parse is an identity parser for strings | [
"Parse",
"is",
"an",
"identity",
"parser",
"for",
"strings"
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/parse.go#L77-L79 |
16,637 | pilosa/pdk | parse.go | Parse | func (p TimeParser) Parse(field string) (result interface{}, err error) {
return time.Parse(p.Layout, field)
} | go | func (p TimeParser) Parse(field string) (result interface{}, err error) {
return time.Parse(p.Layout, field)
} | [
"func",
"(",
"p",
"TimeParser",
")",
"Parse",
"(",
"field",
"string",
")",
"(",
"result",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"return",
"time",
".",
"Parse",
"(",
"p",
".",
"Layout",
",",
"field",
")",
"\n",
"}"
] | // Parse parses a timestamp string to a time.Time value | [
"Parse",
"parses",
"a",
"timestamp",
"string",
"to",
"a",
"time",
".",
"Time",
"value"
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/parse.go#L82-L84 |
16,638 | pilosa/pdk | leveldb/translator.go | Close | func (lt *Translator) Close() error {
errs := make(errorList, 0)
for f, lft := range lt.fields {
err := lft.Close()
if err != nil {
errs = append(errs, errors.Wrapf(err, "field : %v", f))
}
}
if len(errs) > 0 {
return errs
}
return nil
} | go | func (lt *Translator) Close() error {
errs := make(errorList, 0)
for f, lft := range lt.fields {
err := lft.Close()
if err != nil {
errs = append(errs, errors.Wrapf(err, "field : %v", f))
}
}
if len(errs) > 0 {
return errs
}
return nil
} | [
"func",
"(",
"lt",
"*",
"Translator",
")",
"Close",
"(",
")",
"error",
"{",
"errs",
":=",
"make",
"(",
"errorList",
",",
"0",
")",
"\n",
"for",
"f",
",",
"lft",
":=",
"range",
"lt",
".",
"fields",
"{",
"err",
":=",
"lft",
".",
"Close",
"(",
")"... | // Close closes all of the underlying leveldb instances. | [
"Close",
"closes",
"all",
"of",
"the",
"underlying",
"leveldb",
"instances",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/leveldb/translator.go#L79-L91 |
16,639 | pilosa/pdk | leveldb/translator.go | Close | func (lft *FieldTranslator) Close() error {
errs := make(errorList, 0)
err := lft.idMap.Close()
if err != nil {
errs = append(errs, errors.Wrap(err, "closing idMap"))
}
err = lft.valMap.Close()
if err != nil {
errs = append(errs, errors.Wrap(err, "closing valMap"))
}
if len(errs) > 0 {
return errs
}
return nil
} | go | func (lft *FieldTranslator) Close() error {
errs := make(errorList, 0)
err := lft.idMap.Close()
if err != nil {
errs = append(errs, errors.Wrap(err, "closing idMap"))
}
err = lft.valMap.Close()
if err != nil {
errs = append(errs, errors.Wrap(err, "closing valMap"))
}
if len(errs) > 0 {
return errs
}
return nil
} | [
"func",
"(",
"lft",
"*",
"FieldTranslator",
")",
"Close",
"(",
")",
"error",
"{",
"errs",
":=",
"make",
"(",
"errorList",
",",
"0",
")",
"\n",
"err",
":=",
"lft",
".",
"idMap",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errs",
... | // Close closes the two leveldbs used by the FieldTranslator. | [
"Close",
"closes",
"the",
"two",
"leveldbs",
"used",
"by",
"the",
"FieldTranslator",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/leveldb/translator.go#L94-L108 |
16,640 | pilosa/pdk | leveldb/translator.go | getFieldTranslator | func (lt *Translator) getFieldTranslator(field string) (*FieldTranslator, error) {
lt.lock.RLock()
if tr, ok := lt.fields[field]; ok {
lt.lock.RUnlock()
return tr, nil
}
lt.lock.RUnlock()
lt.lock.Lock()
defer lt.lock.Unlock()
if tr, ok := lt.fields[field]; ok {
return tr, nil
}
lft, err := NewFieldTranslator(lt.dirname, field)
if err != nil {
return nil, errors.Wrap(err, "creating new FieldTranslator")
}
lt.fields[field] = lft
return lft, nil
} | go | func (lt *Translator) getFieldTranslator(field string) (*FieldTranslator, error) {
lt.lock.RLock()
if tr, ok := lt.fields[field]; ok {
lt.lock.RUnlock()
return tr, nil
}
lt.lock.RUnlock()
lt.lock.Lock()
defer lt.lock.Unlock()
if tr, ok := lt.fields[field]; ok {
return tr, nil
}
lft, err := NewFieldTranslator(lt.dirname, field)
if err != nil {
return nil, errors.Wrap(err, "creating new FieldTranslator")
}
lt.fields[field] = lft
return lft, nil
} | [
"func",
"(",
"lt",
"*",
"Translator",
")",
"getFieldTranslator",
"(",
"field",
"string",
")",
"(",
"*",
"FieldTranslator",
",",
"error",
")",
"{",
"lt",
".",
"lock",
".",
"RLock",
"(",
")",
"\n",
"if",
"tr",
",",
"ok",
":=",
"lt",
".",
"fields",
"[... | // getFieldTranslator retrieves or creates a FieldTranslator for the given field. | [
"getFieldTranslator",
"retrieves",
"or",
"creates",
"a",
"FieldTranslator",
"for",
"the",
"given",
"field",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/leveldb/translator.go#L111-L129 |
16,641 | pilosa/pdk | leveldb/translator.go | NewFieldTranslator | func NewFieldTranslator(dirname string, field string) (*FieldTranslator, error) {
err := os.MkdirAll(dirname, 0700)
if err != nil {
return nil, errors.Wrap(err, "making directory")
}
var initialID uint64
mdbs := &FieldTranslator{
curID: &initialID,
lock: newBucketVLock(),
}
mdbs.idMap, err = leveldb.OpenFile(dirname+"/"+field+"-id", &opt.Options{})
if err != nil {
return nil, errors.Wrapf(err, "opening leveldb at %v", dirname+"/"+field+"-id")
}
iter := mdbs.idMap.NewIterator(nil, nil)
if iter.Last() {
key := iter.Key()
*mdbs.curID = binary.BigEndian.Uint64(key) + 1
}
mdbs.valMap, err = leveldb.OpenFile(dirname+"/"+field+"-val", &opt.Options{})
if err != nil {
return nil, errors.Wrapf(err, "opening leveldb at %v", dirname+"/"+field+"-val")
}
return mdbs, nil
} | go | func NewFieldTranslator(dirname string, field string) (*FieldTranslator, error) {
err := os.MkdirAll(dirname, 0700)
if err != nil {
return nil, errors.Wrap(err, "making directory")
}
var initialID uint64
mdbs := &FieldTranslator{
curID: &initialID,
lock: newBucketVLock(),
}
mdbs.idMap, err = leveldb.OpenFile(dirname+"/"+field+"-id", &opt.Options{})
if err != nil {
return nil, errors.Wrapf(err, "opening leveldb at %v", dirname+"/"+field+"-id")
}
iter := mdbs.idMap.NewIterator(nil, nil)
if iter.Last() {
key := iter.Key()
*mdbs.curID = binary.BigEndian.Uint64(key) + 1
}
mdbs.valMap, err = leveldb.OpenFile(dirname+"/"+field+"-val", &opt.Options{})
if err != nil {
return nil, errors.Wrapf(err, "opening leveldb at %v", dirname+"/"+field+"-val")
}
return mdbs, nil
} | [
"func",
"NewFieldTranslator",
"(",
"dirname",
"string",
",",
"field",
"string",
")",
"(",
"*",
"FieldTranslator",
",",
"error",
")",
"{",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"dirname",
",",
"0700",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return... | // NewFieldTranslator creates a new FieldTranslator which uses LevelDB as
// backing storage. | [
"NewFieldTranslator",
"creates",
"a",
"new",
"FieldTranslator",
"which",
"uses",
"LevelDB",
"as",
"backing",
"storage",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/leveldb/translator.go#L133-L157 |
16,642 | pilosa/pdk | leveldb/translator.go | NewTranslator | func NewTranslator(dirname string, fields ...string) (lt *Translator, err error) {
lt = &Translator{
dirname: dirname,
fields: make(map[string]*FieldTranslator),
}
for _, field := range fields {
lft, err := NewFieldTranslator(dirname, field)
if err != nil {
return nil, errors.Wrap(err, "making FieldTranslator")
}
lt.fields[field] = lft
}
return lt, err
} | go | func NewTranslator(dirname string, fields ...string) (lt *Translator, err error) {
lt = &Translator{
dirname: dirname,
fields: make(map[string]*FieldTranslator),
}
for _, field := range fields {
lft, err := NewFieldTranslator(dirname, field)
if err != nil {
return nil, errors.Wrap(err, "making FieldTranslator")
}
lt.fields[field] = lft
}
return lt, err
} | [
"func",
"NewTranslator",
"(",
"dirname",
"string",
",",
"fields",
"...",
"string",
")",
"(",
"lt",
"*",
"Translator",
",",
"err",
"error",
")",
"{",
"lt",
"=",
"&",
"Translator",
"{",
"dirname",
":",
"dirname",
",",
"fields",
":",
"make",
"(",
"map",
... | // NewTranslator gets a new Translator. | [
"NewTranslator",
"gets",
"a",
"new",
"Translator",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/leveldb/translator.go#L160-L173 |
16,643 | pilosa/pdk | ingest.go | NewIngester | func NewIngester(source Source, parser RecordParser, mapper RecordMapper, indexer Indexer) *Ingester {
return &Ingester{
ParseConcurrency: 1,
src: source,
parser: parser,
mapper: mapper,
indexer: indexer,
// Reasonable defaults for crosscutting dependencies.
Stats: termstat.NewCollector(os.Stdout),
Log: StdLogger{log.New(os.Stderr, "Ingest", log.LstdFlags)},
}
} | go | func NewIngester(source Source, parser RecordParser, mapper RecordMapper, indexer Indexer) *Ingester {
return &Ingester{
ParseConcurrency: 1,
src: source,
parser: parser,
mapper: mapper,
indexer: indexer,
// Reasonable defaults for crosscutting dependencies.
Stats: termstat.NewCollector(os.Stdout),
Log: StdLogger{log.New(os.Stderr, "Ingest", log.LstdFlags)},
}
} | [
"func",
"NewIngester",
"(",
"source",
"Source",
",",
"parser",
"RecordParser",
",",
"mapper",
"RecordMapper",
",",
"indexer",
"Indexer",
")",
"*",
"Ingester",
"{",
"return",
"&",
"Ingester",
"{",
"ParseConcurrency",
":",
"1",
",",
"src",
":",
"source",
",",
... | // NewIngester gets a new Ingester. | [
"NewIngester",
"gets",
"a",
"new",
"Ingester",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/ingest.go#L65-L78 |
16,644 | pilosa/pdk | ingest.go | Run | func (n *Ingester) Run() error {
pwg := sync.WaitGroup{}
for i := 0; i < n.ParseConcurrency; i++ {
pwg.Add(1)
go func() {
defer pwg.Done()
var recordErr error
for {
// Source
var rec interface{}
rec, recordErr = n.src.Record()
if recordErr != nil {
break
}
n.Stats.Count("ingest.Record", 1, 1)
// Parse
val, err := n.parser.Parse(rec)
if err != nil {
n.Log.Printf("couldn't parse record %s, err: %v", rec, err)
n.Stats.Count("ingest.ParseError", 1, 1)
continue
}
n.Stats.Count("ingest.Parse", 1, 1)
// Transform
for _, tr := range n.Transformers {
err := tr.Transform(val)
if err != nil {
n.Log.Printf("Problem with transformer %#v: %v", tr, err)
n.Stats.Count("ingest.TransformError", 1, 1)
}
}
n.Stats.Count("ingest.Transform", 1, 1)
// Map
pr, err := n.mapper.Map(val)
if err != nil {
n.Log.Printf("couldn't map val: %s, err: %v", val, err)
n.Stats.Count("ingest.MapError", 1, 1)
continue
}
// Index
n.Stats.Count("ingest.Map", 1, 1)
for _, row := range pr.Rows {
if n.AllowedFields == nil || n.AllowedFields[row.Field] {
n.indexer.AddColumn(row.Field, pr.Col, row.ID)
n.Stats.Count("ingest.AddBit", 1, 1)
}
}
for _, val := range pr.Vals {
if n.AllowedFields == nil || n.AllowedFields[val.Field] {
n.indexer.AddValue(val.Field, pr.Col, val.Value)
n.Stats.Count("ingest.AddValue", 1, 1)
}
}
}
if recordErr != io.EOF && recordErr != nil {
n.Log.Printf("error in ingest run loop: %v", recordErr)
}
}()
}
pwg.Wait()
return n.indexer.Close()
} | go | func (n *Ingester) Run() error {
pwg := sync.WaitGroup{}
for i := 0; i < n.ParseConcurrency; i++ {
pwg.Add(1)
go func() {
defer pwg.Done()
var recordErr error
for {
// Source
var rec interface{}
rec, recordErr = n.src.Record()
if recordErr != nil {
break
}
n.Stats.Count("ingest.Record", 1, 1)
// Parse
val, err := n.parser.Parse(rec)
if err != nil {
n.Log.Printf("couldn't parse record %s, err: %v", rec, err)
n.Stats.Count("ingest.ParseError", 1, 1)
continue
}
n.Stats.Count("ingest.Parse", 1, 1)
// Transform
for _, tr := range n.Transformers {
err := tr.Transform(val)
if err != nil {
n.Log.Printf("Problem with transformer %#v: %v", tr, err)
n.Stats.Count("ingest.TransformError", 1, 1)
}
}
n.Stats.Count("ingest.Transform", 1, 1)
// Map
pr, err := n.mapper.Map(val)
if err != nil {
n.Log.Printf("couldn't map val: %s, err: %v", val, err)
n.Stats.Count("ingest.MapError", 1, 1)
continue
}
// Index
n.Stats.Count("ingest.Map", 1, 1)
for _, row := range pr.Rows {
if n.AllowedFields == nil || n.AllowedFields[row.Field] {
n.indexer.AddColumn(row.Field, pr.Col, row.ID)
n.Stats.Count("ingest.AddBit", 1, 1)
}
}
for _, val := range pr.Vals {
if n.AllowedFields == nil || n.AllowedFields[val.Field] {
n.indexer.AddValue(val.Field, pr.Col, val.Value)
n.Stats.Count("ingest.AddValue", 1, 1)
}
}
}
if recordErr != io.EOF && recordErr != nil {
n.Log.Printf("error in ingest run loop: %v", recordErr)
}
}()
}
pwg.Wait()
return n.indexer.Close()
} | [
"func",
"(",
"n",
"*",
"Ingester",
")",
"Run",
"(",
")",
"error",
"{",
"pwg",
":=",
"sync",
".",
"WaitGroup",
"{",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"n",
".",
"ParseConcurrency",
";",
"i",
"++",
"{",
"pwg",
".",
"Add",
"(",
"1"... | // Run runs the ingest. | [
"Run",
"runs",
"the",
"ingest",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/ingest.go#L81-L146 |
16,645 | pilosa/pdk | aws/s3/main.go | NewMain | func NewMain() *Main {
return &Main{
Bucket: "pdk-test-bucket",
Region: "us-east-1",
PilosaHosts: []string{"localhost:10101"},
Index: "pdk",
BatchSize: 1000,
SubjectAt: "#@!pdksubj",
SubjectPath: []string{},
Proxy: ":13131",
}
} | go | func NewMain() *Main {
return &Main{
Bucket: "pdk-test-bucket",
Region: "us-east-1",
PilosaHosts: []string{"localhost:10101"},
Index: "pdk",
BatchSize: 1000,
SubjectAt: "#@!pdksubj",
SubjectPath: []string{},
Proxy: ":13131",
}
} | [
"func",
"NewMain",
"(",
")",
"*",
"Main",
"{",
"return",
"&",
"Main",
"{",
"Bucket",
":",
"\"",
"\"",
",",
"Region",
":",
"\"",
"\"",
",",
"PilosaHosts",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"Index",
":",
"\"",
"\"",
",",
"BatchS... | // NewMain gets a new Main with the default configuration. | [
"NewMain",
"gets",
"a",
"new",
"Main",
"with",
"the",
"default",
"configuration",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/aws/s3/main.go#L57-L68 |
16,646 | pilosa/pdk | fake/gen/generator.go | NewGenerator | func NewGenerator(seed int64) *Generator {
r := rand.New(rand.NewSource(seed))
return &Generator{
r: r,
zs: make(map[int]*rand.Zipf),
times: make(map[time.Time]time.Duration),
hsh: sha1.New(),
}
} | go | func NewGenerator(seed int64) *Generator {
r := rand.New(rand.NewSource(seed))
return &Generator{
r: r,
zs: make(map[int]*rand.Zipf),
times: make(map[time.Time]time.Duration),
hsh: sha1.New(),
}
} | [
"func",
"NewGenerator",
"(",
"seed",
"int64",
")",
"*",
"Generator",
"{",
"r",
":=",
"rand",
".",
"New",
"(",
"rand",
".",
"NewSource",
"(",
"seed",
")",
")",
"\n",
"return",
"&",
"Generator",
"{",
"r",
":",
"r",
",",
"zs",
":",
"make",
"(",
"map... | // NewGenerator gets a new Generator | [
"NewGenerator",
"gets",
"a",
"new",
"Generator"
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/fake/gen/generator.go#L54-L62 |
16,647 | pilosa/pdk | fake/gen/generator.go | String | func (g *Generator) String(length, cardinality int) string {
if length > 32 {
length = 32
}
val := g.Uint64(cardinality)
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, val)
_, _ = g.hsh.Write(b) // no need to check err
hashed := g.hsh.Sum(nil)
g.hsh.Reset()
return base32.StdEncoding.EncodeToString(hashed)[:length]
} | go | func (g *Generator) String(length, cardinality int) string {
if length > 32 {
length = 32
}
val := g.Uint64(cardinality)
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, val)
_, _ = g.hsh.Write(b) // no need to check err
hashed := g.hsh.Sum(nil)
g.hsh.Reset()
return base32.StdEncoding.EncodeToString(hashed)[:length]
} | [
"func",
"(",
"g",
"*",
"Generator",
")",
"String",
"(",
"length",
",",
"cardinality",
"int",
")",
"string",
"{",
"if",
"length",
">",
"32",
"{",
"length",
"=",
"32",
"\n",
"}",
"\n\n",
"val",
":=",
"g",
".",
"Uint64",
"(",
"cardinality",
")",
"\n\n... | // String gets a zipfian random string from a set with the given cardinality. | [
"String",
"gets",
"a",
"zipfian",
"random",
"string",
"from",
"a",
"set",
"with",
"the",
"given",
"cardinality",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/fake/gen/generator.go#L65-L78 |
16,648 | pilosa/pdk | fake/gen/generator.go | NewPermutationGenerator | func NewPermutationGenerator(m int64, seed int64) *PermutationGenerator {
// figure out 'a' and 'c', return PermutationGenerator
a := multiplierFromModulus(m, seed)
c := int64(22695479)
return &PermutationGenerator{a, c, m}
} | go | func NewPermutationGenerator(m int64, seed int64) *PermutationGenerator {
// figure out 'a' and 'c', return PermutationGenerator
a := multiplierFromModulus(m, seed)
c := int64(22695479)
return &PermutationGenerator{a, c, m}
} | [
"func",
"NewPermutationGenerator",
"(",
"m",
"int64",
",",
"seed",
"int64",
")",
"*",
"PermutationGenerator",
"{",
"// figure out 'a' and 'c', return PermutationGenerator",
"a",
":=",
"multiplierFromModulus",
"(",
"m",
",",
"seed",
")",
"\n",
"c",
":=",
"int64",
"("... | // NewPermutationGenerator returns a PermutationGenerator which will permute
// numbers in 0-n. | [
"NewPermutationGenerator",
"returns",
"a",
"PermutationGenerator",
"which",
"will",
"permute",
"numbers",
"in",
"0",
"-",
"n",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/fake/gen/generator.go#L159-L164 |
16,649 | pilosa/pdk | fake/gen/generator.go | Permute | func (p *PermutationGenerator) Permute(n int64) int64 {
// run one step of the LCG
return (n*p.a + p.c) % p.m
} | go | func (p *PermutationGenerator) Permute(n int64) int64 {
// run one step of the LCG
return (n*p.a + p.c) % p.m
} | [
"func",
"(",
"p",
"*",
"PermutationGenerator",
")",
"Permute",
"(",
"n",
"int64",
")",
"int64",
"{",
"// run one step of the LCG",
"return",
"(",
"n",
"*",
"p",
".",
"a",
"+",
"p",
".",
"c",
")",
"%",
"p",
".",
"m",
"\n",
"}"
] | // Permute gets the permuted value for n. | [
"Permute",
"gets",
"the",
"permuted",
"value",
"for",
"n",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/fake/gen/generator.go#L167-L170 |
16,650 | pilosa/pdk | cmd/gen.go | NewGenCommand | func NewGenCommand(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
var err error
GenMain = gen.NewMain()
genCommand := &cobra.Command{
Use: "gen",
Short: "Generate and index fake event data.",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
err = GenMain.Run()
if err != nil {
return err
}
log.Println("Done: ", time.Since(start))
select {}
},
}
flags := genCommand.Flags()
err = commandeer.Flags(flags, GenMain)
if err != nil {
panic(err)
}
return genCommand
} | go | func NewGenCommand(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
var err error
GenMain = gen.NewMain()
genCommand := &cobra.Command{
Use: "gen",
Short: "Generate and index fake event data.",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
err = GenMain.Run()
if err != nil {
return err
}
log.Println("Done: ", time.Since(start))
select {}
},
}
flags := genCommand.Flags()
err = commandeer.Flags(flags, GenMain)
if err != nil {
panic(err)
}
return genCommand
} | [
"func",
"NewGenCommand",
"(",
"stdin",
"io",
".",
"Reader",
",",
"stdout",
",",
"stderr",
"io",
".",
"Writer",
")",
"*",
"cobra",
".",
"Command",
"{",
"var",
"err",
"error",
"\n",
"GenMain",
"=",
"gen",
".",
"NewMain",
"(",
")",
"\n",
"genCommand",
"... | // NewGenCommand returns a new cobra command wrapping GenMain. | [
"NewGenCommand",
"returns",
"a",
"new",
"cobra",
"command",
"wrapping",
"GenMain",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/cmd/gen.go#L17-L39 |
16,651 | pilosa/pdk | fake/user.go | NewUserSource | func NewUserSource(seed int64, max uint64) *UserSource {
if max == 0 {
max = math.MaxUint64
}
var n uint64
s := &UserSource{
n: &n,
max: max,
ug: NewUserGenerator(seed),
}
return s
} | go | func NewUserSource(seed int64, max uint64) *UserSource {
if max == 0 {
max = math.MaxUint64
}
var n uint64
s := &UserSource{
n: &n,
max: max,
ug: NewUserGenerator(seed),
}
return s
} | [
"func",
"NewUserSource",
"(",
"seed",
"int64",
",",
"max",
"uint64",
")",
"*",
"UserSource",
"{",
"if",
"max",
"==",
"0",
"{",
"max",
"=",
"math",
".",
"MaxUint64",
"\n",
"}",
"\n",
"var",
"n",
"uint64",
"\n",
"s",
":=",
"&",
"UserSource",
"{",
"n"... | // NewUserSource creates a new Source with the given random seed. Using the same
// seed should give the same series of events on a given version of Go. | [
"NewUserSource",
"creates",
"a",
"new",
"Source",
"with",
"the",
"given",
"random",
"seed",
".",
"Using",
"the",
"same",
"seed",
"should",
"give",
"the",
"same",
"series",
"of",
"events",
"on",
"a",
"given",
"version",
"of",
"Go",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/fake/user.go#L21-L33 |
16,652 | pilosa/pdk | fake/user.go | Record | func (s *UserSource) Record() (interface{}, error) {
next := atomic.AddUint64(s.n, 1)
if next > s.max {
return nil, io.EOF
}
user := s.ug.Record()
user.ID = next - 1
return user, nil
} | go | func (s *UserSource) Record() (interface{}, error) {
next := atomic.AddUint64(s.n, 1)
if next > s.max {
return nil, io.EOF
}
user := s.ug.Record()
user.ID = next - 1
return user, nil
} | [
"func",
"(",
"s",
"*",
"UserSource",
")",
"Record",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"next",
":=",
"atomic",
".",
"AddUint64",
"(",
"s",
".",
"n",
",",
"1",
")",
"\n",
"if",
"next",
">",
"s",
".",
"max",
"{",
"ret... | // Record implements pdk.Source and returns a randomly generated user. | [
"Record",
"implements",
"pdk",
".",
"Source",
"and",
"returns",
"a",
"randomly",
"generated",
"user",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/fake/user.go#L36-L44 |
16,653 | pilosa/pdk | fake/user.go | NewUserGenerator | func NewUserGenerator(seed int64) *UserGenerator {
return &UserGenerator{
g: gen.NewGenerator(seed),
r: rand.New(rand.NewSource(seed)),
}
} | go | func NewUserGenerator(seed int64) *UserGenerator {
return &UserGenerator{
g: gen.NewGenerator(seed),
r: rand.New(rand.NewSource(seed)),
}
} | [
"func",
"NewUserGenerator",
"(",
"seed",
"int64",
")",
"*",
"UserGenerator",
"{",
"return",
"&",
"UserGenerator",
"{",
"g",
":",
"gen",
".",
"NewGenerator",
"(",
"seed",
")",
",",
"r",
":",
"rand",
".",
"New",
"(",
"rand",
".",
"NewSource",
"(",
"seed"... | // NewUserGenerator initializes a new UserGenerator. | [
"NewUserGenerator",
"initializes",
"a",
"new",
"UserGenerator",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/fake/user.go#L63-L68 |
16,654 | pilosa/pdk | fake/user.go | Record | func (u *UserGenerator) Record() *User {
return &User{
Age: u.r.Intn(110),
FirstName: u.g.String(8, 10000),
LastName: u.g.String(10, 50000),
Allergies: u.genAllergies(),
Title: titleList[u.g.Uint64(len(titleList))],
}
} | go | func (u *UserGenerator) Record() *User {
return &User{
Age: u.r.Intn(110),
FirstName: u.g.String(8, 10000),
LastName: u.g.String(10, 50000),
Allergies: u.genAllergies(),
Title: titleList[u.g.Uint64(len(titleList))],
}
} | [
"func",
"(",
"u",
"*",
"UserGenerator",
")",
"Record",
"(",
")",
"*",
"User",
"{",
"return",
"&",
"User",
"{",
"Age",
":",
"u",
".",
"r",
".",
"Intn",
"(",
"110",
")",
",",
"FirstName",
":",
"u",
".",
"g",
".",
"String",
"(",
"8",
",",
"10000... | // Record returns a random User record with realistic-ish values. | [
"Record",
"returns",
"a",
"random",
"User",
"record",
"with",
"realistic",
"-",
"ish",
"values",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/fake/user.go#L71-L79 |
16,655 | pilosa/pdk | usecase/weather/main.go | Run | func (m *Main) Run() (err error) {
go func() {
fmt.Println(http.ListenAndServe("localhost:6060", nil))
}()
schema := gopilosa.NewSchema()
m.index = schema.Index(m.Index)
pdk.NewRankedField(m.index, "weather_condition", 0)
pdk.NewRankedField(m.index, "precipitation_type", 0)
pdk.NewRankedField(m.index, "precipitation_inches", 0)
pdk.NewRankedField(m.index, "temp_f", 0)
pdk.NewRankedField(m.index, "pressure_i", 0)
pdk.NewRankedField(m.index, "humidity", 0)
m.importer, err = pdk.SetupPilosa([]string{m.PilosaHost}, m.Index, schema, uint(m.BufferSize))
if err != nil {
return errors.Wrap(err, "setting up pilosa")
}
pilosaURI, err := gopilosa.NewURIFromAddress(m.PilosaHost)
if err != nil {
return fmt.Errorf("interpreting pilosaHost '%v': %v", m.PilosaHost, err)
}
setupClient, err := gopilosa.NewClient(pilosaURI)
if err != nil {
return fmt.Errorf("setting up client: %v", err)
}
m.client = setupClient
readFieldNames := []string{"cab_type", "passenger_count", "total_amount_dollars", "pickup_time", "pickup_day", "pickup_mday", "pickup_month", "pickup_year", "drop_time", "drop_day", "drop_mday", "drop_month", "drop_year", "dist_miles", "duration_minutes", "speed_mph", "pickup_grid_id", "drop_grid_id"}
for _, fieldName := range readFieldNames {
m.index.Field(fieldName)
}
err = setupClient.SyncSchema(schema)
if err != nil {
return errors.Wrap(err, "synchronizing schema")
}
err = m.WeatherCache.ReadAll()
if err != nil {
return errors.Wrap(err, "reading weather cache")
}
err = m.appendWeatherData()
if err != nil {
return errors.Wrap(err, "appending weather data")
}
return errors.Wrap(m.importer.Close(), "closing indexer")
} | go | func (m *Main) Run() (err error) {
go func() {
fmt.Println(http.ListenAndServe("localhost:6060", nil))
}()
schema := gopilosa.NewSchema()
m.index = schema.Index(m.Index)
pdk.NewRankedField(m.index, "weather_condition", 0)
pdk.NewRankedField(m.index, "precipitation_type", 0)
pdk.NewRankedField(m.index, "precipitation_inches", 0)
pdk.NewRankedField(m.index, "temp_f", 0)
pdk.NewRankedField(m.index, "pressure_i", 0)
pdk.NewRankedField(m.index, "humidity", 0)
m.importer, err = pdk.SetupPilosa([]string{m.PilosaHost}, m.Index, schema, uint(m.BufferSize))
if err != nil {
return errors.Wrap(err, "setting up pilosa")
}
pilosaURI, err := gopilosa.NewURIFromAddress(m.PilosaHost)
if err != nil {
return fmt.Errorf("interpreting pilosaHost '%v': %v", m.PilosaHost, err)
}
setupClient, err := gopilosa.NewClient(pilosaURI)
if err != nil {
return fmt.Errorf("setting up client: %v", err)
}
m.client = setupClient
readFieldNames := []string{"cab_type", "passenger_count", "total_amount_dollars", "pickup_time", "pickup_day", "pickup_mday", "pickup_month", "pickup_year", "drop_time", "drop_day", "drop_mday", "drop_month", "drop_year", "dist_miles", "duration_minutes", "speed_mph", "pickup_grid_id", "drop_grid_id"}
for _, fieldName := range readFieldNames {
m.index.Field(fieldName)
}
err = setupClient.SyncSchema(schema)
if err != nil {
return errors.Wrap(err, "synchronizing schema")
}
err = m.WeatherCache.ReadAll()
if err != nil {
return errors.Wrap(err, "reading weather cache")
}
err = m.appendWeatherData()
if err != nil {
return errors.Wrap(err, "appending weather data")
}
return errors.Wrap(m.importer.Close(), "closing indexer")
} | [
"func",
"(",
"m",
"*",
"Main",
")",
"Run",
"(",
")",
"(",
"err",
"error",
")",
"{",
"go",
"func",
"(",
")",
"{",
"fmt",
".",
"Println",
"(",
"http",
".",
"ListenAndServe",
"(",
"\"",
"\"",
",",
"nil",
")",
")",
"\n",
"}",
"(",
")",
"\n\n",
... | // Run runs the weather usecase. | [
"Run",
"runs",
"the",
"weather",
"usecase",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/usecase/weather/main.go#L143-L193 |
16,656 | pilosa/pdk | geohash/geohash.go | Transform | func (t *Transformer) Transform(e *pdk.Entity) error {
latitude, err := e.F64(t.LatPath...)
if err != nil {
return errors.Wrap(err, "getting latidude")
}
longitude, err := e.F64(t.LonPath...)
if err != nil {
return errors.Wrap(err, "getting longitude")
}
hsh := geoHash(float64(latitude), float64(longitude), t.Precision)
err = e.SetString(hsh, t.ResultPath...)
return errors.Wrap(err, "setting result")
} | go | func (t *Transformer) Transform(e *pdk.Entity) error {
latitude, err := e.F64(t.LatPath...)
if err != nil {
return errors.Wrap(err, "getting latidude")
}
longitude, err := e.F64(t.LonPath...)
if err != nil {
return errors.Wrap(err, "getting longitude")
}
hsh := geoHash(float64(latitude), float64(longitude), t.Precision)
err = e.SetString(hsh, t.ResultPath...)
return errors.Wrap(err, "setting result")
} | [
"func",
"(",
"t",
"*",
"Transformer",
")",
"Transform",
"(",
"e",
"*",
"pdk",
".",
"Entity",
")",
"error",
"{",
"latitude",
",",
"err",
":=",
"e",
".",
"F64",
"(",
"t",
".",
"LatPath",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // Transform hashes the latitude and longitude at the given paths and sets the
// resulting string at the result path on the Entity. | [
"Transform",
"hashes",
"the",
"latitude",
"and",
"longitude",
"at",
"the",
"given",
"paths",
"and",
"sets",
"the",
"resulting",
"string",
"at",
"the",
"result",
"path",
"on",
"the",
"Entity",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/geohash/geohash.go#L51-L63 |
16,657 | pilosa/pdk | mock/stats.go | Count | func (r *RecordingStatter) Count(name string, value int64, rate float64, tags ...string) {
if r.Counts == nil {
r.Counts = make(map[string]int64)
}
r.Counts[name] += value
} | go | func (r *RecordingStatter) Count(name string, value int64, rate float64, tags ...string) {
if r.Counts == nil {
r.Counts = make(map[string]int64)
}
r.Counts[name] += value
} | [
"func",
"(",
"r",
"*",
"RecordingStatter",
")",
"Count",
"(",
"name",
"string",
",",
"value",
"int64",
",",
"rate",
"float64",
",",
"tags",
"...",
"string",
")",
"{",
"if",
"r",
".",
"Counts",
"==",
"nil",
"{",
"r",
".",
"Counts",
"=",
"make",
"(",... | // Count implements Count. | [
"Count",
"implements",
"Count",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/mock/stats.go#L45-L50 |
16,658 | pilosa/pdk | translator.go | GetID | func (m *MapTranslator) GetID(field string, val interface{}) (id uint64, err error) {
return m.getFieldTranslator(field).GetID(val)
} | go | func (m *MapTranslator) GetID(field string, val interface{}) (id uint64, err error) {
return m.getFieldTranslator(field).GetID(val)
} | [
"func",
"(",
"m",
"*",
"MapTranslator",
")",
"GetID",
"(",
"field",
"string",
",",
"val",
"interface",
"{",
"}",
")",
"(",
"id",
"uint64",
",",
"err",
"error",
")",
"{",
"return",
"m",
".",
"getFieldTranslator",
"(",
"field",
")",
".",
"GetID",
"(",
... | // GetID returns the integer id associated with the given value in the given
// field. It allocates a new ID if the value is not found. | [
"GetID",
"returns",
"the",
"integer",
"id",
"associated",
"with",
"the",
"given",
"value",
"in",
"the",
"given",
"field",
".",
"It",
"allocates",
"a",
"new",
"ID",
"if",
"the",
"value",
"is",
"not",
"found",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/translator.go#L98-L100 |
16,659 | pilosa/pdk | translator.go | GetID | func (n *NexterFrameTranslator) GetID(val interface{}) (id uint64, err error) {
return n.n.Next(), nil
} | go | func (n *NexterFrameTranslator) GetID(val interface{}) (id uint64, err error) {
return n.n.Next(), nil
} | [
"func",
"(",
"n",
"*",
"NexterFrameTranslator",
")",
"GetID",
"(",
"val",
"interface",
"{",
"}",
")",
"(",
"id",
"uint64",
",",
"err",
"error",
")",
"{",
"return",
"n",
".",
"n",
".",
"Next",
"(",
")",
",",
"nil",
"\n",
"}"
] | // GetID for the NexterFrameTranslator increments the internal id counter
// atomically and returns the next id - it ignores the val argument entirely. | [
"GetID",
"for",
"the",
"NexterFrameTranslator",
"increments",
"the",
"internal",
"id",
"counter",
"atomically",
"and",
"returns",
"the",
"next",
"id",
"-",
"it",
"ignores",
"the",
"val",
"argument",
"entirely",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/translator.go#L181-L183 |
16,660 | pilosa/pdk | csv/source.go | WithURLs | func WithURLs(urls []string) Option {
return func(s *Source) {
if s.files == nil {
s.files = make([]*file, 0)
}
for _, url := range urls {
s.files = append(s.files, &file{OpenStringer: urlOpener(url)})
}
}
} | go | func WithURLs(urls []string) Option {
return func(s *Source) {
if s.files == nil {
s.files = make([]*file, 0)
}
for _, url := range urls {
s.files = append(s.files, &file{OpenStringer: urlOpener(url)})
}
}
} | [
"func",
"WithURLs",
"(",
"urls",
"[",
"]",
"string",
")",
"Option",
"{",
"return",
"func",
"(",
"s",
"*",
"Source",
")",
"{",
"if",
"s",
".",
"files",
"==",
"nil",
"{",
"s",
".",
"files",
"=",
"make",
"(",
"[",
"]",
"*",
"file",
",",
"0",
")"... | // WithURLs returns an Option which adds the slice of URLs to the set of data
// sources a Source will read from. The URLs may be HTTP or local files. | [
"WithURLs",
"returns",
"an",
"Option",
"which",
"adds",
"the",
"slice",
"of",
"URLs",
"to",
"the",
"set",
"of",
"data",
"sources",
"a",
"Source",
"will",
"read",
"from",
".",
"The",
"URLs",
"may",
"be",
"HTTP",
"or",
"local",
"files",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/csv/source.go#L86-L95 |
16,661 | pilosa/pdk | csv/source.go | WithOpenStringers | func WithOpenStringers(os []OpenStringer) Option {
return func(s *Source) {
if s.files == nil {
s.files = make([]*file, 0)
}
for _, os := range os {
s.files = append(s.files, &file{OpenStringer: os})
}
}
} | go | func WithOpenStringers(os []OpenStringer) Option {
return func(s *Source) {
if s.files == nil {
s.files = make([]*file, 0)
}
for _, os := range os {
s.files = append(s.files, &file{OpenStringer: os})
}
}
} | [
"func",
"WithOpenStringers",
"(",
"os",
"[",
"]",
"OpenStringer",
")",
"Option",
"{",
"return",
"func",
"(",
"s",
"*",
"Source",
")",
"{",
"if",
"s",
".",
"files",
"==",
"nil",
"{",
"s",
".",
"files",
"=",
"make",
"(",
"[",
"]",
"*",
"file",
",",... | // WithOpenStringers returns an Option which adds the slice of OpenStringers to
// the set of data sources a Source will read from. | [
"WithOpenStringers",
"returns",
"an",
"Option",
"which",
"adds",
"the",
"slice",
"of",
"OpenStringers",
"to",
"the",
"set",
"of",
"data",
"sources",
"a",
"Source",
"will",
"read",
"from",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/csv/source.go#L99-L108 |
16,662 | pilosa/pdk | csv/source.go | WithConcurrency | func WithConcurrency(c int) Option {
return func(s *Source) {
if c > 0 {
s.concurrency = c
}
}
} | go | func WithConcurrency(c int) Option {
return func(s *Source) {
if c > 0 {
s.concurrency = c
}
}
} | [
"func",
"WithConcurrency",
"(",
"c",
"int",
")",
"Option",
"{",
"return",
"func",
"(",
"s",
"*",
"Source",
")",
"{",
"if",
"c",
">",
"0",
"{",
"s",
".",
"concurrency",
"=",
"c",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // WithConcurrency returns an Option which sets the number of goroutines fetching
// files simultaneously. | [
"WithConcurrency",
"returns",
"an",
"Option",
"which",
"sets",
"the",
"number",
"of",
"goroutines",
"fetching",
"files",
"simultaneously",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/csv/source.go#L120-L126 |
16,663 | pilosa/pdk | usecase/taxi/main.go | NewMain | func NewMain() *Main {
m := &Main{
Concurrency: 1,
FetchConcurrency: 1,
Index: "taxi",
nexter: pdk.NewNexter(),
urls: make([]string, 0),
totalRecs: &counter{},
skippedRecs: &counter{},
nullLocs: &counter{},
badLocs: &counter{},
badSpeeds: &counter{},
badTotalAmnts: &counter{},
badDurations: &counter{},
badPassCounts: &counter{},
badDist: &counter{},
badUnknowns: &counter{},
}
return m
} | go | func NewMain() *Main {
m := &Main{
Concurrency: 1,
FetchConcurrency: 1,
Index: "taxi",
nexter: pdk.NewNexter(),
urls: make([]string, 0),
totalRecs: &counter{},
skippedRecs: &counter{},
nullLocs: &counter{},
badLocs: &counter{},
badSpeeds: &counter{},
badTotalAmnts: &counter{},
badDurations: &counter{},
badPassCounts: &counter{},
badDist: &counter{},
badUnknowns: &counter{},
}
return m
} | [
"func",
"NewMain",
"(",
")",
"*",
"Main",
"{",
"m",
":=",
"&",
"Main",
"{",
"Concurrency",
":",
"1",
",",
"FetchConcurrency",
":",
"1",
",",
"Index",
":",
"\"",
"\"",
",",
"nexter",
":",
"pdk",
".",
"NewNexter",
"(",
")",
",",
"urls",
":",
"make"... | // NewMain returns a new instance of Main with default values. | [
"NewMain",
"returns",
"a",
"new",
"instance",
"of",
"Main",
"with",
"default",
"values",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/usecase/taxi/main.go#L100-L121 |
16,664 | pilosa/pdk | usecase/taxi/main.go | getNextURL | func getNextURL(urls <-chan string, failedURLs map[string]int) (string, bool) {
url, open := <-urls
if !open {
for url := range failedURLs {
return url, true
}
return "", false
}
return url, true
} | go | func getNextURL(urls <-chan string, failedURLs map[string]int) (string, bool) {
url, open := <-urls
if !open {
for url := range failedURLs {
return url, true
}
return "", false
}
return url, true
} | [
"func",
"getNextURL",
"(",
"urls",
"<-",
"chan",
"string",
",",
"failedURLs",
"map",
"[",
"string",
"]",
"int",
")",
"(",
"string",
",",
"bool",
")",
"{",
"url",
",",
"open",
":=",
"<-",
"urls",
"\n",
"if",
"!",
"open",
"{",
"for",
"url",
":=",
"... | // getNextURL fetches the next url from the channel, or if it is emtpy, gets a
// url from the failedURLs map after 10 seconds of waiting on the channel. As
// long as it gets a url, its boolean return value is true - if it does not get
// a url, it returns false. | [
"getNextURL",
"fetches",
"the",
"next",
"url",
"from",
"the",
"channel",
"or",
"if",
"it",
"is",
"emtpy",
"gets",
"a",
"url",
"from",
"the",
"failedURLs",
"map",
"after",
"10",
"seconds",
"of",
"waiting",
"on",
"the",
"channel",
".",
"As",
"long",
"as",
... | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/usecase/taxi/main.go#L253-L262 |
16,665 | pilosa/pdk | nexter.go | NexterStartFrom | func NexterStartFrom(s uint64) func(n *Nexter) {
return func(n *Nexter) {
*(n.id) = s
}
} | go | func NexterStartFrom(s uint64) func(n *Nexter) {
return func(n *Nexter) {
*(n.id) = s
}
} | [
"func",
"NexterStartFrom",
"(",
"s",
"uint64",
")",
"func",
"(",
"n",
"*",
"Nexter",
")",
"{",
"return",
"func",
"(",
"n",
"*",
"Nexter",
")",
"{",
"*",
"(",
"n",
".",
"id",
")",
"=",
"s",
"\n",
"}",
"\n",
"}"
] | // NexterStartFrom returns an option which makes a Nexter start from integer
// "s". | [
"NexterStartFrom",
"returns",
"an",
"option",
"which",
"makes",
"a",
"Nexter",
"start",
"from",
"integer",
"s",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/nexter.go#L56-L60 |
16,666 | pilosa/pdk | nexter.go | NewNexter | func NewNexter(opts ...NexterOption) *Nexter {
var id uint64
n := &Nexter{
id: &id,
}
for _, opt := range opts {
opt(n)
}
return n
} | go | func NewNexter(opts ...NexterOption) *Nexter {
var id uint64
n := &Nexter{
id: &id,
}
for _, opt := range opts {
opt(n)
}
return n
} | [
"func",
"NewNexter",
"(",
"opts",
"...",
"NexterOption",
")",
"*",
"Nexter",
"{",
"var",
"id",
"uint64",
"\n",
"n",
":=",
"&",
"Nexter",
"{",
"id",
":",
"&",
"id",
",",
"}",
"\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"opt",
"(",
... | // NewNexter creates a new id generator starting at 0 - can be modified by
// options. | [
"NewNexter",
"creates",
"a",
"new",
"id",
"generator",
"starting",
"at",
"0",
"-",
"can",
"be",
"modified",
"by",
"options",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/nexter.go#L64-L73 |
16,667 | pilosa/pdk | nexter.go | Next | func (n *Nexter) Next() (nextID uint64) {
nextID = atomic.AddUint64(n.id, 1)
return nextID - 1
} | go | func (n *Nexter) Next() (nextID uint64) {
nextID = atomic.AddUint64(n.id, 1)
return nextID - 1
} | [
"func",
"(",
"n",
"*",
"Nexter",
")",
"Next",
"(",
")",
"(",
"nextID",
"uint64",
")",
"{",
"nextID",
"=",
"atomic",
".",
"AddUint64",
"(",
"n",
".",
"id",
",",
"1",
")",
"\n",
"return",
"nextID",
"-",
"1",
"\n",
"}"
] | // Next generates a new id and returns it | [
"Next",
"generates",
"a",
"new",
"id",
"and",
"returns",
"it"
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/nexter.go#L76-L79 |
16,668 | pilosa/pdk | nexter.go | Last | func (n *Nexter) Last() (lastID uint64) {
lastID = atomic.LoadUint64(n.id) - 1
return
} | go | func (n *Nexter) Last() (lastID uint64) {
lastID = atomic.LoadUint64(n.id) - 1
return
} | [
"func",
"(",
"n",
"*",
"Nexter",
")",
"Last",
"(",
")",
"(",
"lastID",
"uint64",
")",
"{",
"lastID",
"=",
"atomic",
".",
"LoadUint64",
"(",
"n",
".",
"id",
")",
"-",
"1",
"\n",
"return",
"\n",
"}"
] | // Last returns the most recently generated id | [
"Last",
"returns",
"the",
"most",
"recently",
"generated",
"id"
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/nexter.go#L82-L85 |
16,669 | pilosa/pdk | proxy.go | NewPilosaForwarder | func NewPilosaForwarder(phost string, t Translator, colTranslator ...FieldTranslator) *pilosaForwarder {
if !strings.HasPrefix(phost, "http://") {
phost = "http://" + phost
}
f := &pilosaForwarder{
phost: phost,
km: NewPilosaKeyMapper(t, colTranslator...),
}
f.proxy = NewPilosaProxy(phost, &f.client)
return f
} | go | func NewPilosaForwarder(phost string, t Translator, colTranslator ...FieldTranslator) *pilosaForwarder {
if !strings.HasPrefix(phost, "http://") {
phost = "http://" + phost
}
f := &pilosaForwarder{
phost: phost,
km: NewPilosaKeyMapper(t, colTranslator...),
}
f.proxy = NewPilosaProxy(phost, &f.client)
return f
} | [
"func",
"NewPilosaForwarder",
"(",
"phost",
"string",
",",
"t",
"Translator",
",",
"colTranslator",
"...",
"FieldTranslator",
")",
"*",
"pilosaForwarder",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"phost",
",",
"\"",
"\"",
")",
"{",
"phost",
"=",
"... | // NewPilosaForwarder returns a new pilosaForwarder which forwards all requests
// to `phost`. It inspects pilosa responses and runs the row ids through the
// Translator `t` to translate them to whatever they were mapped from. | [
"NewPilosaForwarder",
"returns",
"a",
"new",
"pilosaForwarder",
"which",
"forwards",
"all",
"requests",
"to",
"phost",
".",
"It",
"inspects",
"pilosa",
"responses",
"and",
"runs",
"the",
"row",
"ids",
"through",
"the",
"Translator",
"t",
"to",
"translate",
"them... | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/proxy.go#L85-L95 |
16,670 | pilosa/pdk | proxy.go | NewPilosaProxy | func NewPilosaProxy(host string, client *http.Client) *pilosaProxy {
return &pilosaProxy{
host: host,
client: client,
}
} | go | func NewPilosaProxy(host string, client *http.Client) *pilosaProxy {
return &pilosaProxy{
host: host,
client: client,
}
} | [
"func",
"NewPilosaProxy",
"(",
"host",
"string",
",",
"client",
"*",
"http",
".",
"Client",
")",
"*",
"pilosaProxy",
"{",
"return",
"&",
"pilosaProxy",
"{",
"host",
":",
"host",
",",
"client",
":",
"client",
",",
"}",
"\n",
"}"
] | // NewPilosaProxy returns a pilosaProxy based on `host` and `client`. | [
"NewPilosaProxy",
"returns",
"a",
"pilosaProxy",
"based",
"on",
"host",
"and",
"client",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/proxy.go#L180-L185 |
16,671 | pilosa/pdk | proxy.go | ProxyRequest | func (p *pilosaProxy) ProxyRequest(orig *http.Request, origbody []byte) (*http.Response, error) {
reqURL, err := url.Parse(p.host + orig.URL.String())
if err != nil {
log.Printf("error parsing url: %v, err: %v", p.host+orig.URL.String(), err)
return nil, errors.Wrapf(err, "parsing url: %v", p.host+orig.URL.String())
}
orig.URL = reqURL
orig.Host = ""
orig.RequestURI = ""
orig.Body = ioutil.NopCloser(bytes.NewBuffer(origbody))
orig.ContentLength = int64(len(origbody))
resp, err := p.client.Do(orig)
return resp, err
} | go | func (p *pilosaProxy) ProxyRequest(orig *http.Request, origbody []byte) (*http.Response, error) {
reqURL, err := url.Parse(p.host + orig.URL.String())
if err != nil {
log.Printf("error parsing url: %v, err: %v", p.host+orig.URL.String(), err)
return nil, errors.Wrapf(err, "parsing url: %v", p.host+orig.URL.String())
}
orig.URL = reqURL
orig.Host = ""
orig.RequestURI = ""
orig.Body = ioutil.NopCloser(bytes.NewBuffer(origbody))
orig.ContentLength = int64(len(origbody))
resp, err := p.client.Do(orig)
return resp, err
} | [
"func",
"(",
"p",
"*",
"pilosaProxy",
")",
"ProxyRequest",
"(",
"orig",
"*",
"http",
".",
"Request",
",",
"origbody",
"[",
"]",
"byte",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"reqURL",
",",
"err",
":=",
"url",
".",
"Parse",... | // proxyRequest modifies the http.Request object in place to change it from a
// server side request object to the proxy server to a client side request and
// sends it to pilosa, returning the response. | [
"proxyRequest",
"modifies",
"the",
"http",
".",
"Request",
"object",
"in",
"place",
"to",
"change",
"it",
"from",
"a",
"server",
"side",
"request",
"object",
"to",
"the",
"proxy",
"server",
"to",
"a",
"client",
"side",
"request",
"and",
"sends",
"it",
"to"... | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/proxy.go#L190-L203 |
16,672 | pilosa/pdk | proxy.go | NewPilosaKeyMapper | func NewPilosaKeyMapper(t Translator, colTranslator ...FieldTranslator) *PilosaKeyMapper {
pkm := &PilosaKeyMapper{
t: t,
}
if len(colTranslator) > 0 {
pkm.c = colTranslator[0]
}
return pkm
} | go | func NewPilosaKeyMapper(t Translator, colTranslator ...FieldTranslator) *PilosaKeyMapper {
pkm := &PilosaKeyMapper{
t: t,
}
if len(colTranslator) > 0 {
pkm.c = colTranslator[0]
}
return pkm
} | [
"func",
"NewPilosaKeyMapper",
"(",
"t",
"Translator",
",",
"colTranslator",
"...",
"FieldTranslator",
")",
"*",
"PilosaKeyMapper",
"{",
"pkm",
":=",
"&",
"PilosaKeyMapper",
"{",
"t",
":",
"t",
",",
"}",
"\n",
"if",
"len",
"(",
"colTranslator",
")",
">",
"0... | // NewPilosaKeyMapper returns a PilosaKeyMapper. | [
"NewPilosaKeyMapper",
"returns",
"a",
"PilosaKeyMapper",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/proxy.go#L212-L220 |
16,673 | pilosa/pdk | proxy.go | MapRequest | func (p *PilosaKeyMapper) MapRequest(body []byte) ([]byte, error) {
log.Printf("mapping request: '%s'", body)
query, err := pql.ParseString(string(body))
if err != nil {
return nil, errors.Wrap(err, "parsing string")
}
for _, call := range query.Calls {
err := p.mapCall(call)
if err != nil {
return nil, errors.Wrap(err, "mapping call")
}
}
log.Printf("mapped request: '%s'", query.String())
return []byte(query.String()), nil
} | go | func (p *PilosaKeyMapper) MapRequest(body []byte) ([]byte, error) {
log.Printf("mapping request: '%s'", body)
query, err := pql.ParseString(string(body))
if err != nil {
return nil, errors.Wrap(err, "parsing string")
}
for _, call := range query.Calls {
err := p.mapCall(call)
if err != nil {
return nil, errors.Wrap(err, "mapping call")
}
}
log.Printf("mapped request: '%s'", query.String())
return []byte(query.String()), nil
} | [
"func",
"(",
"p",
"*",
"PilosaKeyMapper",
")",
"MapRequest",
"(",
"body",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"body",
")",
"\n",
"query",
",",
"err",
":=",
"pql",
"."... | // MapRequest takes a request body and returns a mapped version of that body. | [
"MapRequest",
"takes",
"a",
"request",
"body",
"and",
"returns",
"a",
"mapped",
"version",
"of",
"that",
"body",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/proxy.go#L335-L349 |
16,674 | pilosa/pdk | proxy.go | GetFields | func GetFields(body []byte) ([]string, error) {
query, err := pql.ParseString(string(body))
if err != nil {
return nil, fmt.Errorf("parsing query: %v", err.Error())
}
fields := make([]string, len(query.Calls))
for i, call := range query.Calls {
if field, ok := call.Args["field"].(string); ok {
fields[i] = field
} else if field, ok := call.Args["_field"].(string); ok {
fields[i] = field
} else {
fields[i] = ""
}
}
return fields, nil
} | go | func GetFields(body []byte) ([]string, error) {
query, err := pql.ParseString(string(body))
if err != nil {
return nil, fmt.Errorf("parsing query: %v", err.Error())
}
fields := make([]string, len(query.Calls))
for i, call := range query.Calls {
if field, ok := call.Args["field"].(string); ok {
fields[i] = field
} else if field, ok := call.Args["_field"].(string); ok {
fields[i] = field
} else {
fields[i] = ""
}
}
return fields, nil
} | [
"func",
"GetFields",
"(",
"body",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"query",
",",
"err",
":=",
"pql",
".",
"ParseString",
"(",
"string",
"(",
"body",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // GetFields interprets body as pql queries and then tries to determine the
// field of each. Some queries do not have fields, and the empty string will be
// returned for these. | [
"GetFields",
"interprets",
"body",
"as",
"pql",
"queries",
"and",
"then",
"tries",
"to",
"determine",
"the",
"field",
"of",
"each",
".",
"Some",
"queries",
"do",
"not",
"have",
"fields",
"and",
"the",
"empty",
"string",
"will",
"be",
"returned",
"for",
"th... | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/proxy.go#L383-L401 |
16,675 | pilosa/pdk | filesplitter.go | NewFileFragment | func NewFileFragment(f *os.File, startLoc, endLoc int64) (*FileFragment, error) {
thisF, err := os.Open(f.Name())
if err != nil {
return nil, errors.Wrap(err, "opening file fragment")
}
_, err = thisF.Seek(startLoc, io.SeekStart)
if err != nil {
return nil, errors.Wrap(err, "seeking to start location in new file handle")
}
return &FileFragment{
file: thisF,
startLoc: startLoc,
endLoc: endLoc,
}, nil
} | go | func NewFileFragment(f *os.File, startLoc, endLoc int64) (*FileFragment, error) {
thisF, err := os.Open(f.Name())
if err != nil {
return nil, errors.Wrap(err, "opening file fragment")
}
_, err = thisF.Seek(startLoc, io.SeekStart)
if err != nil {
return nil, errors.Wrap(err, "seeking to start location in new file handle")
}
return &FileFragment{
file: thisF,
startLoc: startLoc,
endLoc: endLoc,
}, nil
} | [
"func",
"NewFileFragment",
"(",
"f",
"*",
"os",
".",
"File",
",",
"startLoc",
",",
"endLoc",
"int64",
")",
"(",
"*",
"FileFragment",
",",
"error",
")",
"{",
"thisF",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"f",
".",
"Name",
"(",
")",
")",
"\n",... | // NewFileFragment returns a FileFragment which will read only from startLoc to
// endLoc in a file. | [
"NewFileFragment",
"returns",
"a",
"FileFragment",
"which",
"will",
"read",
"only",
"from",
"startLoc",
"to",
"endLoc",
"in",
"a",
"file",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/filesplitter.go#L51-L65 |
16,676 | pilosa/pdk | filesplitter.go | Read | func (ff *FileFragment) Read(b []byte) (n int, err error) {
offset, err := ff.file.Seek(0, io.SeekCurrent)
if err != nil {
return 0, err
}
if int64(len(b)) > ff.endLoc-offset {
n, err := ff.file.Read(b[:ff.endLoc-offset])
if int64(n) == ff.endLoc-offset {
return n, io.EOF
}
return n, err
}
return ff.file.Read(b)
} | go | func (ff *FileFragment) Read(b []byte) (n int, err error) {
offset, err := ff.file.Seek(0, io.SeekCurrent)
if err != nil {
return 0, err
}
if int64(len(b)) > ff.endLoc-offset {
n, err := ff.file.Read(b[:ff.endLoc-offset])
if int64(n) == ff.endLoc-offset {
return n, io.EOF
}
return n, err
}
return ff.file.Read(b)
} | [
"func",
"(",
"ff",
"*",
"FileFragment",
")",
"Read",
"(",
"b",
"[",
"]",
"byte",
")",
"(",
"n",
"int",
",",
"err",
"error",
")",
"{",
"offset",
",",
"err",
":=",
"ff",
".",
"file",
".",
"Seek",
"(",
"0",
",",
"io",
".",
"SeekCurrent",
")",
"\... | // Read implements io.Reader for FileFragment. | [
"Read",
"implements",
"io",
".",
"Reader",
"for",
"FileFragment",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/filesplitter.go#L68-L82 |
16,677 | pilosa/pdk | filesplitter.go | SplitFileLines | func SplitFileLines(f *os.File, numParts int64) ([]*FileFragment, error) {
stats, err := f.Stat()
if err != nil {
return nil, err
}
splitSize := stats.Size() / numParts
ret := make([]*FileFragment, 0)
var startLoc int64
for {
endLoc, errSeek := seekAndSearch(f, splitSize, '\n')
if errSeek != nil && errSeek != io.EOF {
return nil, errors.Wrap(errSeek, "searching for next split location")
}
ff, err := NewFileFragment(f, startLoc, endLoc)
if err != nil {
return nil, errors.Wrap(err, "creating new file fragment")
}
ret = append(ret, ff)
if errSeek == io.EOF {
break
}
startLoc = endLoc
}
return ret, nil
} | go | func SplitFileLines(f *os.File, numParts int64) ([]*FileFragment, error) {
stats, err := f.Stat()
if err != nil {
return nil, err
}
splitSize := stats.Size() / numParts
ret := make([]*FileFragment, 0)
var startLoc int64
for {
endLoc, errSeek := seekAndSearch(f, splitSize, '\n')
if errSeek != nil && errSeek != io.EOF {
return nil, errors.Wrap(errSeek, "searching for next split location")
}
ff, err := NewFileFragment(f, startLoc, endLoc)
if err != nil {
return nil, errors.Wrap(err, "creating new file fragment")
}
ret = append(ret, ff)
if errSeek == io.EOF {
break
}
startLoc = endLoc
}
return ret, nil
} | [
"func",
"SplitFileLines",
"(",
"f",
"*",
"os",
".",
"File",
",",
"numParts",
"int64",
")",
"(",
"[",
"]",
"*",
"FileFragment",
",",
"error",
")",
"{",
"stats",
",",
"err",
":=",
"f",
".",
"Stat",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"... | // SplitFileLines returns a slice of file fragments which is numParts in length.
// Each FileFragment will read a different section of the file, but the split
// points are guaranteed to be on line breaks. | [
"SplitFileLines",
"returns",
"a",
"slice",
"of",
"file",
"fragments",
"which",
"is",
"numParts",
"in",
"length",
".",
"Each",
"FileFragment",
"will",
"read",
"a",
"different",
"section",
"of",
"the",
"file",
"but",
"the",
"split",
"points",
"are",
"guaranteed"... | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/filesplitter.go#L92-L117 |
16,678 | pilosa/pdk | filesplitter.go | searchReader | func searchReader(r io.Reader, b byte) (idx int64, err error) {
buf := make([]byte, 1000)
idx = 0
var n int
for err == nil {
n, err = r.Read(buf)
for i := 0; i < n; i++ {
if buf[i] == b {
idx += int64(i) + 1
return idx, nil
}
}
idx += int64(n)
}
if err == io.EOF {
return idx, io.EOF
}
return 0, err
} | go | func searchReader(r io.Reader, b byte) (idx int64, err error) {
buf := make([]byte, 1000)
idx = 0
var n int
for err == nil {
n, err = r.Read(buf)
for i := 0; i < n; i++ {
if buf[i] == b {
idx += int64(i) + 1
return idx, nil
}
}
idx += int64(n)
}
if err == io.EOF {
return idx, io.EOF
}
return 0, err
} | [
"func",
"searchReader",
"(",
"r",
"io",
".",
"Reader",
",",
"b",
"byte",
")",
"(",
"idx",
"int64",
",",
"err",
"error",
")",
"{",
"buf",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"1000",
")",
"\n",
"idx",
"=",
"0",
"\n",
"var",
"n",
"int",
"\... | // searchReader returns the number of bytes until byte b or io.EOF is
// encountered in Reader r. It is not idempotent and is not guaranteed to leave
// the reader in any particular state. The returned error will be io.EOF, only
// if EOF was encountered idx bytes into the Reader. | [
"searchReader",
"returns",
"the",
"number",
"of",
"bytes",
"until",
"byte",
"b",
"or",
"io",
".",
"EOF",
"is",
"encountered",
"in",
"Reader",
"r",
".",
"It",
"is",
"not",
"idempotent",
"and",
"is",
"not",
"guaranteed",
"to",
"leave",
"the",
"reader",
"in... | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/filesplitter.go#L141-L159 |
16,679 | pilosa/pdk | cmd/http.go | NewHTTPCommand | func NewHTTPCommand(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
com, err := cobrafy.Command(http.NewMain())
if err != nil {
panic(err)
}
com.Use = `http`
com.Short = `listens for and indexes arbitrary JSON data in Pilosa`
com.Long = `
pdk http listens for and indexes arbitrary JSON data in Pilosa.
It starts an HTTP server and tries to decode JSON data from any post request
made to it. Every path to a value in the JSON data becomes a Pilosa field.
`[1:]
return com
} | go | func NewHTTPCommand(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
com, err := cobrafy.Command(http.NewMain())
if err != nil {
panic(err)
}
com.Use = `http`
com.Short = `listens for and indexes arbitrary JSON data in Pilosa`
com.Long = `
pdk http listens for and indexes arbitrary JSON data in Pilosa.
It starts an HTTP server and tries to decode JSON data from any post request
made to it. Every path to a value in the JSON data becomes a Pilosa field.
`[1:]
return com
} | [
"func",
"NewHTTPCommand",
"(",
"stdin",
"io",
".",
"Reader",
",",
"stdout",
",",
"stderr",
"io",
".",
"Writer",
")",
"*",
"cobra",
".",
"Command",
"{",
"com",
",",
"err",
":=",
"cobrafy",
".",
"Command",
"(",
"http",
".",
"NewMain",
"(",
")",
")",
... | // NewHTTPCommand returns a new cobra command which wraps http.Main | [
"NewHTTPCommand",
"returns",
"a",
"new",
"cobra",
"command",
"which",
"wraps",
"http",
".",
"Main"
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/cmd/http.go#L44-L59 |
16,680 | pilosa/pdk | cmd/fakeusers.go | NewFakeusersCommand | func NewFakeusersCommand(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
var err error
FakeusersMain = fakeusers.NewMain()
fakeusersCommand := &cobra.Command{
Use: "fakeusers",
Short: "Generate and index fake user data.",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
err = FakeusersMain.Run()
if err != nil {
return err
}
log.Println("Done: ", time.Since(start))
return nil
},
}
flags := fakeusersCommand.Flags()
err = commandeer.Flags(flags, FakeusersMain)
if err != nil {
panic(err)
}
return fakeusersCommand
} | go | func NewFakeusersCommand(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
var err error
FakeusersMain = fakeusers.NewMain()
fakeusersCommand := &cobra.Command{
Use: "fakeusers",
Short: "Generate and index fake user data.",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
err = FakeusersMain.Run()
if err != nil {
return err
}
log.Println("Done: ", time.Since(start))
return nil
},
}
flags := fakeusersCommand.Flags()
err = commandeer.Flags(flags, FakeusersMain)
if err != nil {
panic(err)
}
return fakeusersCommand
} | [
"func",
"NewFakeusersCommand",
"(",
"stdin",
"io",
".",
"Reader",
",",
"stdout",
",",
"stderr",
"io",
".",
"Writer",
")",
"*",
"cobra",
".",
"Command",
"{",
"var",
"err",
"error",
"\n",
"FakeusersMain",
"=",
"fakeusers",
".",
"NewMain",
"(",
")",
"\n",
... | // NewFakeusersCommand returns a new cobra command wrapping FakeusersMain. | [
"NewFakeusersCommand",
"returns",
"a",
"new",
"cobra",
"command",
"wrapping",
"FakeusersMain",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/cmd/fakeusers.go#L17-L39 |
16,681 | pilosa/pdk | aws/s3/s3.go | OptSrcBufSize | func OptSrcBufSize(bufsize int) SrcOption {
return func(s *Source) {
s.records = make(chan map[string]interface{}, bufsize)
}
} | go | func OptSrcBufSize(bufsize int) SrcOption {
return func(s *Source) {
s.records = make(chan map[string]interface{}, bufsize)
}
} | [
"func",
"OptSrcBufSize",
"(",
"bufsize",
"int",
")",
"SrcOption",
"{",
"return",
"func",
"(",
"s",
"*",
"Source",
")",
"{",
"s",
".",
"records",
"=",
"make",
"(",
"chan",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"bufsize",
")",
"\n",
... | // OptSrcBufSize sets the number of records to buffer while waiting for Record
// to be called. | [
"OptSrcBufSize",
"sets",
"the",
"number",
"of",
"records",
"to",
"buffer",
"while",
"waiting",
"for",
"Record",
"to",
"be",
"called",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/aws/s3/s3.go#L65-L69 |
16,682 | pilosa/pdk | aws/s3/s3.go | NewSource | func NewSource(opts ...SrcOption) (*Source, error) {
s := &Source{
records: make(chan map[string]interface{}, 100),
errors: make(chan error),
}
for _, opt := range opts {
opt(s)
}
var err error
s.sess, err = session.NewSession(&aws.Config{
Region: aws.String(s.region)},
)
if err != nil {
return nil, errors.Wrap(err, "getting new source")
}
s.s3 = s3.New(s.sess)
resp, err := s.s3.ListObjects(&s3.ListObjectsInput{Bucket: aws.String(s.bucket), Prefix: aws.String(s.prefix)})
if err != nil {
return nil, errors.Wrap(err, "listing objects")
}
s.objects = resp.Contents
go s.populateRecords()
return s, nil
} | go | func NewSource(opts ...SrcOption) (*Source, error) {
s := &Source{
records: make(chan map[string]interface{}, 100),
errors: make(chan error),
}
for _, opt := range opts {
opt(s)
}
var err error
s.sess, err = session.NewSession(&aws.Config{
Region: aws.String(s.region)},
)
if err != nil {
return nil, errors.Wrap(err, "getting new source")
}
s.s3 = s3.New(s.sess)
resp, err := s.s3.ListObjects(&s3.ListObjectsInput{Bucket: aws.String(s.bucket), Prefix: aws.String(s.prefix)})
if err != nil {
return nil, errors.Wrap(err, "listing objects")
}
s.objects = resp.Contents
go s.populateRecords()
return s, nil
} | [
"func",
"NewSource",
"(",
"opts",
"...",
"SrcOption",
")",
"(",
"*",
"Source",
",",
"error",
")",
"{",
"s",
":=",
"&",
"Source",
"{",
"records",
":",
"make",
"(",
"chan",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"100",
")",
",",
"er... | // NewSource returns a new Source with the options applied. | [
"NewSource",
"returns",
"a",
"new",
"Source",
"with",
"the",
"options",
"applied",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/aws/s3/s3.go#L103-L128 |
16,683 | pilosa/pdk | kafkagen/kafkagen.go | Length | func (e JSONEvent) Length() int {
bytes, _ := e.Encode()
return len(bytes)
} | go | func (e JSONEvent) Length() int {
bytes, _ := e.Encode()
return len(bytes)
} | [
"func",
"(",
"e",
"JSONEvent",
")",
"Length",
"(",
")",
"int",
"{",
"bytes",
",",
"_",
":=",
"e",
".",
"Encode",
"(",
")",
"\n",
"return",
"len",
"(",
"bytes",
")",
"\n",
"}"
] | // Length returns the length of the marshalled json. | [
"Length",
"returns",
"the",
"length",
"of",
"the",
"marshalled",
"json",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/kafkagen/kafkagen.go#L76-L79 |
16,684 | pilosa/pdk | kafkagen/kafkagen.go | Run | func (m *Main) Run() error {
conf := sarama.NewConfig()
conf.Version = sarama.V0_10_0_0
conf.Producer.Return.Successes = true
producer, err := sarama.NewSyncProducer(m.Hosts, conf)
if err != nil {
return errors.Wrap(err, "getting new producer")
}
defer producer.Close()
for ticker := time.NewTicker(m.Rate); true; <-ticker.C {
ev := fake.GenEvent()
msg := &sarama.ProducerMessage{Topic: m.Topic, Value: JSONEvent(*ev)}
_, _, err := producer.SendMessage(msg)
if err != nil {
log.Printf("Error sending message: '%v', backing off", err)
time.Sleep(time.Second * 10)
}
}
return nil
} | go | func (m *Main) Run() error {
conf := sarama.NewConfig()
conf.Version = sarama.V0_10_0_0
conf.Producer.Return.Successes = true
producer, err := sarama.NewSyncProducer(m.Hosts, conf)
if err != nil {
return errors.Wrap(err, "getting new producer")
}
defer producer.Close()
for ticker := time.NewTicker(m.Rate); true; <-ticker.C {
ev := fake.GenEvent()
msg := &sarama.ProducerMessage{Topic: m.Topic, Value: JSONEvent(*ev)}
_, _, err := producer.SendMessage(msg)
if err != nil {
log.Printf("Error sending message: '%v', backing off", err)
time.Sleep(time.Second * 10)
}
}
return nil
} | [
"func",
"(",
"m",
"*",
"Main",
")",
"Run",
"(",
")",
"error",
"{",
"conf",
":=",
"sarama",
".",
"NewConfig",
"(",
")",
"\n",
"conf",
".",
"Version",
"=",
"sarama",
".",
"V0_10_0_0",
"\n",
"conf",
".",
"Producer",
".",
"Return",
".",
"Successes",
"=... | // Run runs the kafka generator. | [
"Run",
"runs",
"the",
"kafka",
"generator",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/kafkagen/kafkagen.go#L82-L102 |
16,685 | pilosa/pdk | parser.go | Subject | func (p SubjectPath) Subject(e *Entity) (string, error) {
var next Object = e
var prev *Entity
var item string
for _, item = range p {
ent, ok := next.(*Entity)
if !ok {
return "", errors.Errorf("can't get '%v' out of non-entity %#v.", item, next)
}
prev = ent
next = ent.Objects[Property(item)]
}
delete(prev.Objects, Property(item)) // remove the subject from the entity so that it isn't indexed
switch next.(type) {
case I, I8, I16, I32, I64, U, U8, U16, U32, U64:
return fmt.Sprintf("%d", next), nil
case F32, F64:
return fmt.Sprintf("%f", next), nil
case S:
return string(next.(S)), nil
default:
return "", fmt.Errorf("can't make %v of type %T an IRI", next, next)
}
} | go | func (p SubjectPath) Subject(e *Entity) (string, error) {
var next Object = e
var prev *Entity
var item string
for _, item = range p {
ent, ok := next.(*Entity)
if !ok {
return "", errors.Errorf("can't get '%v' out of non-entity %#v.", item, next)
}
prev = ent
next = ent.Objects[Property(item)]
}
delete(prev.Objects, Property(item)) // remove the subject from the entity so that it isn't indexed
switch next.(type) {
case I, I8, I16, I32, I64, U, U8, U16, U32, U64:
return fmt.Sprintf("%d", next), nil
case F32, F64:
return fmt.Sprintf("%f", next), nil
case S:
return string(next.(S)), nil
default:
return "", fmt.Errorf("can't make %v of type %T an IRI", next, next)
}
} | [
"func",
"(",
"p",
"SubjectPath",
")",
"Subject",
"(",
"e",
"*",
"Entity",
")",
"(",
"string",
",",
"error",
")",
"{",
"var",
"next",
"Object",
"=",
"e",
"\n",
"var",
"prev",
"*",
"Entity",
"\n",
"var",
"item",
"string",
"\n",
"for",
"_",
",",
"it... | // Subject implements EntitySubjecter. | [
"Subject",
"implements",
"EntitySubjecter",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/parser.go#L73-L96 |
16,686 | pilosa/pdk | parser.go | NewDefaultGenericParser | func NewDefaultGenericParser() *GenericParser {
return &GenericParser{
Subjecter: BlankSubjecter{},
// Reasonable defaults for crosscutting dependencies.
Stats: termstat.NewCollector(os.Stdout),
Log: StdLogger{log.New(os.Stderr, "Ingest", log.LstdFlags)},
}
} | go | func NewDefaultGenericParser() *GenericParser {
return &GenericParser{
Subjecter: BlankSubjecter{},
// Reasonable defaults for crosscutting dependencies.
Stats: termstat.NewCollector(os.Stdout),
Log: StdLogger{log.New(os.Stderr, "Ingest", log.LstdFlags)},
}
} | [
"func",
"NewDefaultGenericParser",
"(",
")",
"*",
"GenericParser",
"{",
"return",
"&",
"GenericParser",
"{",
"Subjecter",
":",
"BlankSubjecter",
"{",
"}",
",",
"// Reasonable defaults for crosscutting dependencies.",
"Stats",
":",
"termstat",
".",
"NewCollector",
"(",
... | // NewDefaultGenericParser returns a GenericParser with basic implementations of
// its components. In order to track the mapping of Pilosa columns to records,
// you must replace the Subjecter with something other than a BlankSubjecter. | [
"NewDefaultGenericParser",
"returns",
"a",
"GenericParser",
"with",
"basic",
"implementations",
"of",
"its",
"components",
".",
"In",
"order",
"to",
"track",
"the",
"mapping",
"of",
"Pilosa",
"columns",
"to",
"records",
"you",
"must",
"replace",
"the",
"Subjecter"... | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/parser.go#L121-L129 |
16,687 | pilosa/pdk | parser.go | Parse | func (m *GenericParser) Parse(data interface{}) (e *Entity, err error) {
val := reflect.ValueOf(data)
// dereference pointers, and get concrete values from interfaces
val = deref(val)
// Map and Struct are the only valid Kinds at the top level.
switch val.Kind() {
case reflect.Map:
e, err = m.parseMap(val)
case reflect.Struct:
e, err = m.parseStruct(val)
default:
e, err = nil, errors.Errorf("unsupported kind, '%v' in GenericParser: %v", val.Kind(), data)
}
if err != nil {
return e, err
}
var subj string
if !m.SubjectAll {
if m.EntitySubjecter != nil {
subj, err = m.EntitySubjecter.Subject(e)
} else {
subj, err = m.Subjecter.Subject(data)
}
e.Subject = IRI(subj)
}
return e, err
} | go | func (m *GenericParser) Parse(data interface{}) (e *Entity, err error) {
val := reflect.ValueOf(data)
// dereference pointers, and get concrete values from interfaces
val = deref(val)
// Map and Struct are the only valid Kinds at the top level.
switch val.Kind() {
case reflect.Map:
e, err = m.parseMap(val)
case reflect.Struct:
e, err = m.parseStruct(val)
default:
e, err = nil, errors.Errorf("unsupported kind, '%v' in GenericParser: %v", val.Kind(), data)
}
if err != nil {
return e, err
}
var subj string
if !m.SubjectAll {
if m.EntitySubjecter != nil {
subj, err = m.EntitySubjecter.Subject(e)
} else {
subj, err = m.Subjecter.Subject(data)
}
e.Subject = IRI(subj)
}
return e, err
} | [
"func",
"(",
"m",
"*",
"GenericParser",
")",
"Parse",
"(",
"data",
"interface",
"{",
"}",
")",
"(",
"e",
"*",
"Entity",
",",
"err",
"error",
")",
"{",
"val",
":=",
"reflect",
".",
"ValueOf",
"(",
"data",
")",
"\n",
"// dereference pointers, and get concr... | // Parse of the GenericParser tries to parse any value into a pdk.Entity. | [
"Parse",
"of",
"the",
"GenericParser",
"tries",
"to",
"parse",
"any",
"value",
"into",
"a",
"pdk",
".",
"Entity",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/parser.go#L132-L158 |
16,688 | pilosa/pdk | parser.go | parseContainer | func (m *GenericParser) parseContainer(val reflect.Value) (Object, error) {
if dtype := val.Type(); dtype.Elem().Kind() == reflect.Uint8 {
if dtype.Kind() == reflect.Slice {
return S(val.Bytes()), nil
} else if dtype.Kind() == reflect.Array {
ret := make([]byte, dtype.Len())
for i := 0; i < dtype.Len(); i++ {
ret[i] = val.Index(i).Interface().(byte)
}
return S(ret), nil
} else {
panic("should only be slice or array")
}
}
ret := make(Objects, val.Len())
for i := 0; i < val.Len(); i++ {
ival := val.Index(i)
ival = deref(ival)
iobj, err := m.parseValue(ival)
if err != nil {
return nil, errors.Wrap(err, "parsing value")
}
ret[i] = iobj
}
return ret, nil
} | go | func (m *GenericParser) parseContainer(val reflect.Value) (Object, error) {
if dtype := val.Type(); dtype.Elem().Kind() == reflect.Uint8 {
if dtype.Kind() == reflect.Slice {
return S(val.Bytes()), nil
} else if dtype.Kind() == reflect.Array {
ret := make([]byte, dtype.Len())
for i := 0; i < dtype.Len(); i++ {
ret[i] = val.Index(i).Interface().(byte)
}
return S(ret), nil
} else {
panic("should only be slice or array")
}
}
ret := make(Objects, val.Len())
for i := 0; i < val.Len(); i++ {
ival := val.Index(i)
ival = deref(ival)
iobj, err := m.parseValue(ival)
if err != nil {
return nil, errors.Wrap(err, "parsing value")
}
ret[i] = iobj
}
return ret, nil
} | [
"func",
"(",
"m",
"*",
"GenericParser",
")",
"parseContainer",
"(",
"val",
"reflect",
".",
"Value",
")",
"(",
"Object",
",",
"error",
")",
"{",
"if",
"dtype",
":=",
"val",
".",
"Type",
"(",
")",
";",
"dtype",
".",
"Elem",
"(",
")",
".",
"Kind",
"... | // parseContainer parses arrays and slices. | [
"parseContainer",
"parses",
"arrays",
"and",
"slices",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/parser.go#L264-L290 |
16,689 | pilosa/pdk | parser.go | anyImplements | func anyImplements(thing reflect.Value, iface reflect.Type) (reflect.Value, bool) {
if thing.Type().Implements(iface) {
return thing, true
} else if thing.CanAddr() && reflect.PtrTo(thing.Type()).Implements(iface) {
return thing.Addr(), true
}
return reflect.Value{}, false
} | go | func anyImplements(thing reflect.Value, iface reflect.Type) (reflect.Value, bool) {
if thing.Type().Implements(iface) {
return thing, true
} else if thing.CanAddr() && reflect.PtrTo(thing.Type()).Implements(iface) {
return thing.Addr(), true
}
return reflect.Value{}, false
} | [
"func",
"anyImplements",
"(",
"thing",
"reflect",
".",
"Value",
",",
"iface",
"reflect",
".",
"Type",
")",
"(",
"reflect",
".",
"Value",
",",
"bool",
")",
"{",
"if",
"thing",
".",
"Type",
"(",
")",
".",
"Implements",
"(",
"iface",
")",
"{",
"return",... | // anyImplements determines whether an interface is implemented by a value, or a
// pointer to that value. It returns a potentially new value which can be cast
// to the interface, and a boolean. If the boolean is false, the value will be
// the zero value, and cannot be cast to the interface. | [
"anyImplements",
"determines",
"whether",
"an",
"interface",
"is",
"implemented",
"by",
"a",
"value",
"or",
"a",
"pointer",
"to",
"that",
"value",
".",
"It",
"returns",
"a",
"potentially",
"new",
"value",
"which",
"can",
"be",
"cast",
"to",
"the",
"interface... | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/parser.go#L360-L367 |
16,690 | pilosa/pdk | parser.go | getProperty | func (m *GenericParser) getProperty(mapKey reflect.Value) (Property, error) {
properteerType := reflect.TypeOf(new(Properteer)).Elem()
stringerType := reflect.TypeOf(new(fmt.Stringer)).Elem()
// if mapKey implements the pdk.Properteer interface, use that.
if k2, ok := anyImplements(mapKey, properteerType); ok {
return k2.Interface().(Properteer).Property(), nil
}
// if mapKey implements fmt.Stringer, use that.
if k2, ok := anyImplements(mapKey, stringerType); ok {
return Property(k2.Interface().(fmt.Stringer).String()), nil
}
// Otherwise, handle all comparable types (see https://golang.org/ref/spec#Comparison_operators):
mapKey = deref(mapKey)
switch k := mapKey.Kind(); k {
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
return Property(fmt.Sprintf("%v", mapKey)), nil
case reflect.Chan:
m.Stats.Count("parser.getProperty.Chan", 1, 1)
return "", errors.New("channel cannot be converted to property")
case reflect.Array:
m.Stats.Count("parser.getProperty."+k.String(), 1, 1)
return "", errors.New("array cannot be converted to property")
case reflect.Struct:
m.Stats.Count("parser.getProperty."+k.String(), 1, 1)
return "", errors.New("struct cannot be converted to property")
case reflect.Complex128, reflect.Complex64:
m.Stats.Count("parser.getProperty."+k.String(), 1, 1)
return "", errors.New("complex value cannot be converted to property")
default:
m.Stats.Count("parser.getProperty."+k.String(), 1, 1)
return "", errors.Errorf("unexpected kind: %v mapKey: %v", mapKey.Kind(), mapKey)
}
} | go | func (m *GenericParser) getProperty(mapKey reflect.Value) (Property, error) {
properteerType := reflect.TypeOf(new(Properteer)).Elem()
stringerType := reflect.TypeOf(new(fmt.Stringer)).Elem()
// if mapKey implements the pdk.Properteer interface, use that.
if k2, ok := anyImplements(mapKey, properteerType); ok {
return k2.Interface().(Properteer).Property(), nil
}
// if mapKey implements fmt.Stringer, use that.
if k2, ok := anyImplements(mapKey, stringerType); ok {
return Property(k2.Interface().(fmt.Stringer).String()), nil
}
// Otherwise, handle all comparable types (see https://golang.org/ref/spec#Comparison_operators):
mapKey = deref(mapKey)
switch k := mapKey.Kind(); k {
case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
return Property(fmt.Sprintf("%v", mapKey)), nil
case reflect.Chan:
m.Stats.Count("parser.getProperty.Chan", 1, 1)
return "", errors.New("channel cannot be converted to property")
case reflect.Array:
m.Stats.Count("parser.getProperty."+k.String(), 1, 1)
return "", errors.New("array cannot be converted to property")
case reflect.Struct:
m.Stats.Count("parser.getProperty."+k.String(), 1, 1)
return "", errors.New("struct cannot be converted to property")
case reflect.Complex128, reflect.Complex64:
m.Stats.Count("parser.getProperty."+k.String(), 1, 1)
return "", errors.New("complex value cannot be converted to property")
default:
m.Stats.Count("parser.getProperty."+k.String(), 1, 1)
return "", errors.Errorf("unexpected kind: %v mapKey: %v", mapKey.Kind(), mapKey)
}
} | [
"func",
"(",
"m",
"*",
"GenericParser",
")",
"getProperty",
"(",
"mapKey",
"reflect",
".",
"Value",
")",
"(",
"Property",
",",
"error",
")",
"{",
"properteerType",
":=",
"reflect",
".",
"TypeOf",
"(",
"new",
"(",
"Properteer",
")",
")",
".",
"Elem",
"(... | // getProperty turns anything that can be a map key into a string. Exceptions
// are channels, interface values whose dynamic types are channels, structs
// which contain channels, and pointers to any of these things. | [
"getProperty",
"turns",
"anything",
"that",
"can",
"be",
"a",
"map",
"key",
"into",
"a",
"string",
".",
"Exceptions",
"are",
"channels",
"interface",
"values",
"whose",
"dynamic",
"types",
"are",
"channels",
"structs",
"which",
"contain",
"channels",
"and",
"p... | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/parser.go#L372-L406 |
16,691 | pilosa/pdk | cmd/userid.go | NewUseridCommand | func NewUseridCommand(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
var err error
UseridMain = userid.NewMain()
useridCommand := &cobra.Command{
Use: "userid",
Short: "Adds a user ID field to an existing index and associates an ID with each column.",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
err = UseridMain.Run()
if err != nil {
return err
}
log.Println("Done: ", time.Since(start))
return nil
},
}
flags := useridCommand.Flags()
err = commandeer.Flags(flags, UseridMain)
if err != nil {
panic(err)
}
return useridCommand
} | go | func NewUseridCommand(stdin io.Reader, stdout, stderr io.Writer) *cobra.Command {
var err error
UseridMain = userid.NewMain()
useridCommand := &cobra.Command{
Use: "userid",
Short: "Adds a user ID field to an existing index and associates an ID with each column.",
RunE: func(cmd *cobra.Command, args []string) error {
start := time.Now()
err = UseridMain.Run()
if err != nil {
return err
}
log.Println("Done: ", time.Since(start))
return nil
},
}
flags := useridCommand.Flags()
err = commandeer.Flags(flags, UseridMain)
if err != nil {
panic(err)
}
return useridCommand
} | [
"func",
"NewUseridCommand",
"(",
"stdin",
"io",
".",
"Reader",
",",
"stdout",
",",
"stderr",
"io",
".",
"Writer",
")",
"*",
"cobra",
".",
"Command",
"{",
"var",
"err",
"error",
"\n",
"UseridMain",
"=",
"userid",
".",
"NewMain",
"(",
")",
"\n",
"useridC... | // NewUseridCommand returns a new cobra command wrapping UseridMain. | [
"NewUseridCommand",
"returns",
"a",
"new",
"cobra",
"command",
"wrapping",
"UseridMain",
"."
] | bba49352d71e5c23dc4a2c0d3ea08d8560678e1a | https://github.com/pilosa/pdk/blob/bba49352d71e5c23dc4a2c0d3ea08d8560678e1a/cmd/userid.go#L17-L39 |
16,692 | qedus/nds | put.go | PutMulti | func PutMulti(c context.Context,
keys []*datastore.Key, vals interface{}) ([]*datastore.Key, error) {
if len(keys) == 0 {
return nil, nil
}
v := reflect.ValueOf(vals)
if err := checkKeysValues(keys, v); err != nil {
return nil, err
}
callCount := (len(keys)-1)/putMultiLimit + 1
putKeys := make([][]*datastore.Key, callCount)
errs := make([]error, callCount)
var wg sync.WaitGroup
wg.Add(callCount)
for i := 0; i < callCount; i++ {
lo := i * putMultiLimit
hi := (i + 1) * putMultiLimit
if hi > len(keys) {
hi = len(keys)
}
go func(i int, keys []*datastore.Key, vals reflect.Value) {
putKeys[i], errs[i] = putMulti(c, keys, vals.Interface())
wg.Done()
}(i, keys[lo:hi], v.Slice(lo, hi))
}
wg.Wait()
if isErrorsNil(errs) {
groupedKeys := make([]*datastore.Key, len(keys))
for i, k := range putKeys {
lo := i * putMultiLimit
hi := (i + 1) * putMultiLimit
if hi > len(keys) {
hi = len(keys)
}
copy(groupedKeys[lo:hi], k)
}
return groupedKeys, nil
}
groupedKeys := make([]*datastore.Key, len(keys))
groupedErrs := make(appengine.MultiError, len(keys))
for i, err := range errs {
lo := i * putMultiLimit
hi := (i + 1) * putMultiLimit
if hi > len(keys) {
hi = len(keys)
}
if me, ok := err.(appengine.MultiError); ok {
for j, e := range me {
if e == nil {
groupedKeys[lo+j] = putKeys[i][j]
} else {
groupedErrs[lo+j] = e
}
}
} else if err != nil {
for j := lo; j < hi; j++ {
groupedErrs[j] = err
}
}
}
return groupedKeys, groupedErrs
} | go | func PutMulti(c context.Context,
keys []*datastore.Key, vals interface{}) ([]*datastore.Key, error) {
if len(keys) == 0 {
return nil, nil
}
v := reflect.ValueOf(vals)
if err := checkKeysValues(keys, v); err != nil {
return nil, err
}
callCount := (len(keys)-1)/putMultiLimit + 1
putKeys := make([][]*datastore.Key, callCount)
errs := make([]error, callCount)
var wg sync.WaitGroup
wg.Add(callCount)
for i := 0; i < callCount; i++ {
lo := i * putMultiLimit
hi := (i + 1) * putMultiLimit
if hi > len(keys) {
hi = len(keys)
}
go func(i int, keys []*datastore.Key, vals reflect.Value) {
putKeys[i], errs[i] = putMulti(c, keys, vals.Interface())
wg.Done()
}(i, keys[lo:hi], v.Slice(lo, hi))
}
wg.Wait()
if isErrorsNil(errs) {
groupedKeys := make([]*datastore.Key, len(keys))
for i, k := range putKeys {
lo := i * putMultiLimit
hi := (i + 1) * putMultiLimit
if hi > len(keys) {
hi = len(keys)
}
copy(groupedKeys[lo:hi], k)
}
return groupedKeys, nil
}
groupedKeys := make([]*datastore.Key, len(keys))
groupedErrs := make(appengine.MultiError, len(keys))
for i, err := range errs {
lo := i * putMultiLimit
hi := (i + 1) * putMultiLimit
if hi > len(keys) {
hi = len(keys)
}
if me, ok := err.(appengine.MultiError); ok {
for j, e := range me {
if e == nil {
groupedKeys[lo+j] = putKeys[i][j]
} else {
groupedErrs[lo+j] = e
}
}
} else if err != nil {
for j := lo; j < hi; j++ {
groupedErrs[j] = err
}
}
}
return groupedKeys, groupedErrs
} | [
"func",
"PutMulti",
"(",
"c",
"context",
".",
"Context",
",",
"keys",
"[",
"]",
"*",
"datastore",
".",
"Key",
",",
"vals",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"*",
"datastore",
".",
"Key",
",",
"error",
")",
"{",
"if",
"len",
"(",
"keys",
... | // PutMulti is a batch version of Put. It works just like datastore.PutMulti
// except it interacts appropriately with NDS's caching strategy. It also
// removes the API limit of 500 entities per request by calling the datastore as
// many times as required to put all the keys. It does this efficiently and
// concurrently. | [
"PutMulti",
"is",
"a",
"batch",
"version",
"of",
"Put",
".",
"It",
"works",
"just",
"like",
"datastore",
".",
"PutMulti",
"except",
"it",
"interacts",
"appropriately",
"with",
"NDS",
"s",
"caching",
"strategy",
".",
"It",
"also",
"removes",
"the",
"API",
"... | 304641cf4f9b2d8041f40a5c804e9ffca11fc746 | https://github.com/qedus/nds/blob/304641cf4f9b2d8041f40a5c804e9ffca11fc746/put.go#L23-L92 |
16,693 | qedus/nds | put.go | Put | func Put(c context.Context,
key *datastore.Key, val interface{}) (*datastore.Key, error) {
keys := []*datastore.Key{key}
vals := []interface{}{val}
if err := checkKeysValues(keys, reflect.ValueOf(vals)); err != nil {
return nil, err
}
keys, err := putMulti(c, keys, vals)
switch e := err.(type) {
case nil:
return keys[0], nil
case appengine.MultiError:
return nil, e[0]
default:
return nil, err
}
} | go | func Put(c context.Context,
key *datastore.Key, val interface{}) (*datastore.Key, error) {
keys := []*datastore.Key{key}
vals := []interface{}{val}
if err := checkKeysValues(keys, reflect.ValueOf(vals)); err != nil {
return nil, err
}
keys, err := putMulti(c, keys, vals)
switch e := err.(type) {
case nil:
return keys[0], nil
case appengine.MultiError:
return nil, e[0]
default:
return nil, err
}
} | [
"func",
"Put",
"(",
"c",
"context",
".",
"Context",
",",
"key",
"*",
"datastore",
".",
"Key",
",",
"val",
"interface",
"{",
"}",
")",
"(",
"*",
"datastore",
".",
"Key",
",",
"error",
")",
"{",
"keys",
":=",
"[",
"]",
"*",
"datastore",
".",
"Key",... | // Put saves the entity val into the datastore with key. val must be a struct
// pointer; if a struct pointer then any unexported fields of that struct will
// be skipped. If key is an incomplete key, the returned key will be a unique
// key generated by the datastore. | [
"Put",
"saves",
"the",
"entity",
"val",
"into",
"the",
"datastore",
"with",
"key",
".",
"val",
"must",
"be",
"a",
"struct",
"pointer",
";",
"if",
"a",
"struct",
"pointer",
"then",
"any",
"unexported",
"fields",
"of",
"that",
"struct",
"will",
"be",
"skip... | 304641cf4f9b2d8041f40a5c804e9ffca11fc746 | https://github.com/qedus/nds/blob/304641cf4f9b2d8041f40a5c804e9ffca11fc746/put.go#L98-L116 |
16,694 | qedus/nds | put.go | putMulti | func putMulti(c context.Context,
keys []*datastore.Key, vals interface{}) ([]*datastore.Key, error) {
lockMemcacheKeys := make([]string, 0, len(keys))
lockMemcacheItems := make([]*memcache.Item, 0, len(keys))
for _, key := range keys {
if !key.Incomplete() {
item := &memcache.Item{
Key: createMemcacheKey(key),
Flags: lockItem,
Value: itemLock(),
Expiration: memcacheLockTime,
}
lockMemcacheItems = append(lockMemcacheItems, item)
lockMemcacheKeys = append(lockMemcacheKeys, item.Key)
}
}
memcacheCtx, err := memcacheContext(c)
if err != nil {
return nil, err
}
defer func() {
if _, ok := transactionFromContext(c); !ok {
// Remove the locks.
if err := memcacheDeleteMulti(memcacheCtx,
lockMemcacheKeys); err != nil {
log.Warningf(c, "putMulti memcache.DeleteMulti %s", err)
}
}
}()
if tx, ok := transactionFromContext(c); ok {
tx.Lock()
tx.lockMemcacheItems = append(tx.lockMemcacheItems,
lockMemcacheItems...)
tx.Unlock()
} else if err := memcacheSetMulti(memcacheCtx,
lockMemcacheItems); err != nil {
return nil, err
}
// Save to the datastore.
return datastorePutMulti(c, keys, vals)
} | go | func putMulti(c context.Context,
keys []*datastore.Key, vals interface{}) ([]*datastore.Key, error) {
lockMemcacheKeys := make([]string, 0, len(keys))
lockMemcacheItems := make([]*memcache.Item, 0, len(keys))
for _, key := range keys {
if !key.Incomplete() {
item := &memcache.Item{
Key: createMemcacheKey(key),
Flags: lockItem,
Value: itemLock(),
Expiration: memcacheLockTime,
}
lockMemcacheItems = append(lockMemcacheItems, item)
lockMemcacheKeys = append(lockMemcacheKeys, item.Key)
}
}
memcacheCtx, err := memcacheContext(c)
if err != nil {
return nil, err
}
defer func() {
if _, ok := transactionFromContext(c); !ok {
// Remove the locks.
if err := memcacheDeleteMulti(memcacheCtx,
lockMemcacheKeys); err != nil {
log.Warningf(c, "putMulti memcache.DeleteMulti %s", err)
}
}
}()
if tx, ok := transactionFromContext(c); ok {
tx.Lock()
tx.lockMemcacheItems = append(tx.lockMemcacheItems,
lockMemcacheItems...)
tx.Unlock()
} else if err := memcacheSetMulti(memcacheCtx,
lockMemcacheItems); err != nil {
return nil, err
}
// Save to the datastore.
return datastorePutMulti(c, keys, vals)
} | [
"func",
"putMulti",
"(",
"c",
"context",
".",
"Context",
",",
"keys",
"[",
"]",
"*",
"datastore",
".",
"Key",
",",
"vals",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"*",
"datastore",
".",
"Key",
",",
"error",
")",
"{",
"lockMemcacheKeys",
":=",
"m... | // putMulti puts the entities into the datastore and then its local cache. | [
"putMulti",
"puts",
"the",
"entities",
"into",
"the",
"datastore",
"and",
"then",
"its",
"local",
"cache",
"."
] | 304641cf4f9b2d8041f40a5c804e9ffca11fc746 | https://github.com/qedus/nds/blob/304641cf4f9b2d8041f40a5c804e9ffca11fc746/put.go#L119-L164 |
16,695 | qedus/nds | delete.go | DeleteMulti | func DeleteMulti(c context.Context, keys []*datastore.Key) error {
callCount := (len(keys)-1)/deleteMultiLimit + 1
errs := make([]error, callCount)
var wg sync.WaitGroup
wg.Add(callCount)
for i := 0; i < callCount; i++ {
lo := i * deleteMultiLimit
hi := (i + 1) * deleteMultiLimit
if hi > len(keys) {
hi = len(keys)
}
go func(i int, keys []*datastore.Key) {
errs[i] = deleteMulti(c, keys)
wg.Done()
}(i, keys[lo:hi])
}
wg.Wait()
if isErrorsNil(errs) {
return nil
}
return groupErrors(errs, len(keys), deleteMultiLimit)
} | go | func DeleteMulti(c context.Context, keys []*datastore.Key) error {
callCount := (len(keys)-1)/deleteMultiLimit + 1
errs := make([]error, callCount)
var wg sync.WaitGroup
wg.Add(callCount)
for i := 0; i < callCount; i++ {
lo := i * deleteMultiLimit
hi := (i + 1) * deleteMultiLimit
if hi > len(keys) {
hi = len(keys)
}
go func(i int, keys []*datastore.Key) {
errs[i] = deleteMulti(c, keys)
wg.Done()
}(i, keys[lo:hi])
}
wg.Wait()
if isErrorsNil(errs) {
return nil
}
return groupErrors(errs, len(keys), deleteMultiLimit)
} | [
"func",
"DeleteMulti",
"(",
"c",
"context",
".",
"Context",
",",
"keys",
"[",
"]",
"*",
"datastore",
".",
"Key",
")",
"error",
"{",
"callCount",
":=",
"(",
"len",
"(",
"keys",
")",
"-",
"1",
")",
"/",
"deleteMultiLimit",
"+",
"1",
"\n",
"errs",
":=... | // DeleteMulti works just like datastore.DeleteMulti except it maintains
// cache consistency with other NDS methods. It also removes the API limit of
// 500 entities per request by calling the datastore as many times as required
// to put all the keys. It does this efficiently and concurrently. | [
"DeleteMulti",
"works",
"just",
"like",
"datastore",
".",
"DeleteMulti",
"except",
"it",
"maintains",
"cache",
"consistency",
"with",
"other",
"NDS",
"methods",
".",
"It",
"also",
"removes",
"the",
"API",
"limit",
"of",
"500",
"entities",
"per",
"request",
"by... | 304641cf4f9b2d8041f40a5c804e9ffca11fc746 | https://github.com/qedus/nds/blob/304641cf4f9b2d8041f40a5c804e9ffca11fc746/delete.go#L20-L46 |
16,696 | qedus/nds | transaction.go | RunInTransaction | func RunInTransaction(c context.Context, f func(tc context.Context) error,
opts *datastore.TransactionOptions) error {
return datastore.RunInTransaction(c, func(tc context.Context) error {
tx := &transaction{}
tc = context.WithValue(tc, &transactionKey, tx)
if err := f(tc); err != nil {
return err
}
// tx.Unlock() is not called as the tx context should never be called
//again so we rather block than allow people to misuse the context.
tx.Lock()
memcacheCtx, err := memcacheContext(tc)
if err != nil {
return err
}
return memcacheSetMulti(memcacheCtx, tx.lockMemcacheItems)
}, opts)
} | go | func RunInTransaction(c context.Context, f func(tc context.Context) error,
opts *datastore.TransactionOptions) error {
return datastore.RunInTransaction(c, func(tc context.Context) error {
tx := &transaction{}
tc = context.WithValue(tc, &transactionKey, tx)
if err := f(tc); err != nil {
return err
}
// tx.Unlock() is not called as the tx context should never be called
//again so we rather block than allow people to misuse the context.
tx.Lock()
memcacheCtx, err := memcacheContext(tc)
if err != nil {
return err
}
return memcacheSetMulti(memcacheCtx, tx.lockMemcacheItems)
}, opts)
} | [
"func",
"RunInTransaction",
"(",
"c",
"context",
".",
"Context",
",",
"f",
"func",
"(",
"tc",
"context",
".",
"Context",
")",
"error",
",",
"opts",
"*",
"datastore",
".",
"TransactionOptions",
")",
"error",
"{",
"return",
"datastore",
".",
"RunInTransaction"... | // RunInTransaction works just like datastore.RunInTransaction however it
// interacts correctly with memcache. You should always use this method for
// transactions if you are using the NDS package. | [
"RunInTransaction",
"works",
"just",
"like",
"datastore",
".",
"RunInTransaction",
"however",
"it",
"interacts",
"correctly",
"with",
"memcache",
".",
"You",
"should",
"always",
"use",
"this",
"method",
"for",
"transactions",
"if",
"you",
"are",
"using",
"the",
... | 304641cf4f9b2d8041f40a5c804e9ffca11fc746 | https://github.com/qedus/nds/blob/304641cf4f9b2d8041f40a5c804e9ffca11fc746/transaction.go#L26-L45 |
16,697 | qedus/nds | get.go | Get | func Get(c context.Context, key *datastore.Key, val interface{}) error {
// GetMulti catches nil interface; we need to catch nil ptr here.
if val == nil {
return datastore.ErrInvalidEntityType
}
err := GetMulti(c, []*datastore.Key{key}, []interface{}{val})
if me, ok := err.(appengine.MultiError); ok {
return me[0]
}
return err
} | go | func Get(c context.Context, key *datastore.Key, val interface{}) error {
// GetMulti catches nil interface; we need to catch nil ptr here.
if val == nil {
return datastore.ErrInvalidEntityType
}
err := GetMulti(c, []*datastore.Key{key}, []interface{}{val})
if me, ok := err.(appengine.MultiError); ok {
return me[0]
}
return err
} | [
"func",
"Get",
"(",
"c",
"context",
".",
"Context",
",",
"key",
"*",
"datastore",
".",
"Key",
",",
"val",
"interface",
"{",
"}",
")",
"error",
"{",
"// GetMulti catches nil interface; we need to catch nil ptr here.",
"if",
"val",
"==",
"nil",
"{",
"return",
"d... | // Get loads the entity stored for key into val, which must be a struct pointer.
// Currently PropertyLoadSaver is not implemented. If there is no such entity
// for the key, Get returns ErrNoSuchEntity.
//
// The values of val's unmatched struct fields are not modified, and matching
// slice-typed fields are not reset before appending to them. In particular, it
// is recommended to pass a pointer to a zero valued struct on each Get call.
//
// ErrFieldMismatch is returned when a field is to be loaded into a different
// type than the one it was stored from, or when a field is missing or
// unexported in the destination struct. ErrFieldMismatch is only returned if
// val is a struct pointer. | [
"Get",
"loads",
"the",
"entity",
"stored",
"for",
"key",
"into",
"val",
"which",
"must",
"be",
"a",
"struct",
"pointer",
".",
"Currently",
"PropertyLoadSaver",
"is",
"not",
"implemented",
".",
"If",
"there",
"is",
"no",
"such",
"entity",
"for",
"the",
"key... | 304641cf4f9b2d8041f40a5c804e9ffca11fc746 | https://github.com/qedus/nds/blob/304641cf4f9b2d8041f40a5c804e9ffca11fc746/get.go#L107-L118 |
16,698 | hekmon/transmissionrpc | torrent_accessors.go | TorrentGetAll | func (c *Client) TorrentGetAll() (torrents []*Torrent, err error) {
// Send already validated fields to the low level fx
return c.torrentGet(validTorrentFields, nil)
} | go | func (c *Client) TorrentGetAll() (torrents []*Torrent, err error) {
// Send already validated fields to the low level fx
return c.torrentGet(validTorrentFields, nil)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"TorrentGetAll",
"(",
")",
"(",
"torrents",
"[",
"]",
"*",
"Torrent",
",",
"err",
"error",
")",
"{",
"// Send already validated fields to the low level fx",
"return",
"c",
".",
"torrentGet",
"(",
"validTorrentFields",
",",
... | // TorrentGetAll returns all the known fields for all the torrents. | [
"TorrentGetAll",
"returns",
"all",
"the",
"known",
"fields",
"for",
"all",
"the",
"torrents",
"."
] | 4352aea9f1b8457261dc9b03e8d32ced8fa1a471 | https://github.com/hekmon/transmissionrpc/blob/4352aea9f1b8457261dc9b03e8d32ced8fa1a471/torrent_accessors.go#L27-L30 |
16,699 | hekmon/transmissionrpc | torrent_accessors.go | TorrentGetAllFor | func (c *Client) TorrentGetAllFor(ids []int64) (torrents []*Torrent, err error) {
return c.torrentGet(validTorrentFields, ids)
} | go | func (c *Client) TorrentGetAllFor(ids []int64) (torrents []*Torrent, err error) {
return c.torrentGet(validTorrentFields, ids)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"TorrentGetAllFor",
"(",
"ids",
"[",
"]",
"int64",
")",
"(",
"torrents",
"[",
"]",
"*",
"Torrent",
",",
"err",
"error",
")",
"{",
"return",
"c",
".",
"torrentGet",
"(",
"validTorrentFields",
",",
"ids",
")",
"\n"... | // TorrentGetAllFor returns all known fields for the given torrent's ids. | [
"TorrentGetAllFor",
"returns",
"all",
"known",
"fields",
"for",
"the",
"given",
"torrent",
"s",
"ids",
"."
] | 4352aea9f1b8457261dc9b03e8d32ced8fa1a471 | https://github.com/hekmon/transmissionrpc/blob/4352aea9f1b8457261dc9b03e8d32ced8fa1a471/torrent_accessors.go#L33-L35 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.