repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
prometheus/tsdb | chunks/chunks.go | NewWriter | func NewWriter(dir string) (*Writer, error) {
if err := os.MkdirAll(dir, 0777); err != nil {
return nil, err
}
dirFile, err := fileutil.OpenDir(dir)
if err != nil {
return nil, err
}
cw := &Writer{
dirFile: dirFile,
n: 0,
crc32: newCRC32(),
segmentSize: defaultChunkSegmentSize,
}
return cw, nil
} | go | func NewWriter(dir string) (*Writer, error) {
if err := os.MkdirAll(dir, 0777); err != nil {
return nil, err
}
dirFile, err := fileutil.OpenDir(dir)
if err != nil {
return nil, err
}
cw := &Writer{
dirFile: dirFile,
n: 0,
crc32: newCRC32(),
segmentSize: defaultChunkSegmentSize,
}
return cw, nil
} | [
"func",
"NewWriter",
"(",
"dir",
"string",
")",
"(",
"*",
"Writer",
",",
"error",
")",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"dir",
",",
"0777",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"dir... | // NewWriter returns a new writer against the given directory. | [
"NewWriter",
"returns",
"a",
"new",
"writer",
"against",
"the",
"given",
"directory",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/chunks/chunks.go#L107-L122 | train |
prometheus/tsdb | chunks/chunks.go | finalizeTail | func (w *Writer) finalizeTail() error {
tf := w.tail()
if tf == nil {
return nil
}
if err := w.wbuf.Flush(); err != nil {
return err
}
if err := tf.Sync(); err != nil {
return err
}
// As the file was pre-allocated, we truncate any superfluous zero bytes.
off, err := tf.Seek(0, io.SeekCurrent)
if err != nil {
return err
}
if err := tf.Truncate(off); err != nil {
return err
}
return tf.Close()
} | go | func (w *Writer) finalizeTail() error {
tf := w.tail()
if tf == nil {
return nil
}
if err := w.wbuf.Flush(); err != nil {
return err
}
if err := tf.Sync(); err != nil {
return err
}
// As the file was pre-allocated, we truncate any superfluous zero bytes.
off, err := tf.Seek(0, io.SeekCurrent)
if err != nil {
return err
}
if err := tf.Truncate(off); err != nil {
return err
}
return tf.Close()
} | [
"func",
"(",
"w",
"*",
"Writer",
")",
"finalizeTail",
"(",
")",
"error",
"{",
"tf",
":=",
"w",
".",
"tail",
"(",
")",
"\n",
"if",
"tf",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"w",
".",
"wbuf",
".",
"Flush",
"("... | // finalizeTail writes all pending data to the current tail file,
// truncates its size, and closes it. | [
"finalizeTail",
"writes",
"all",
"pending",
"data",
"to",
"the",
"current",
"tail",
"file",
"truncates",
"its",
"size",
"and",
"closes",
"it",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/chunks/chunks.go#L133-L155 | train |
prometheus/tsdb | chunks/chunks.go | MergeChunks | func MergeChunks(a, b chunkenc.Chunk) (*chunkenc.XORChunk, error) {
newChunk := chunkenc.NewXORChunk()
app, err := newChunk.Appender()
if err != nil {
return nil, err
}
ait := a.Iterator()
bit := b.Iterator()
aok, bok := ait.Next(), bit.Next()
for aok && bok {
at, av := ait.At()
bt, bv := bit.At()
if at < bt {
app.Append(at, av)
aok = ait.Next()
} else if bt < at {
app.Append(bt, bv)
bok = bit.Next()
} else {
app.Append(bt, bv)
aok = ait.Next()
bok = bit.Next()
}
}
for aok {
at, av := ait.At()
app.Append(at, av)
aok = ait.Next()
}
for bok {
bt, bv := bit.At()
app.Append(bt, bv)
bok = bit.Next()
}
if ait.Err() != nil {
return nil, ait.Err()
}
if bit.Err() != nil {
return nil, bit.Err()
}
return newChunk, nil
} | go | func MergeChunks(a, b chunkenc.Chunk) (*chunkenc.XORChunk, error) {
newChunk := chunkenc.NewXORChunk()
app, err := newChunk.Appender()
if err != nil {
return nil, err
}
ait := a.Iterator()
bit := b.Iterator()
aok, bok := ait.Next(), bit.Next()
for aok && bok {
at, av := ait.At()
bt, bv := bit.At()
if at < bt {
app.Append(at, av)
aok = ait.Next()
} else if bt < at {
app.Append(bt, bv)
bok = bit.Next()
} else {
app.Append(bt, bv)
aok = ait.Next()
bok = bit.Next()
}
}
for aok {
at, av := ait.At()
app.Append(at, av)
aok = ait.Next()
}
for bok {
bt, bv := bit.At()
app.Append(bt, bv)
bok = bit.Next()
}
if ait.Err() != nil {
return nil, ait.Err()
}
if bit.Err() != nil {
return nil, bit.Err()
}
return newChunk, nil
} | [
"func",
"MergeChunks",
"(",
"a",
",",
"b",
"chunkenc",
".",
"Chunk",
")",
"(",
"*",
"chunkenc",
".",
"XORChunk",
",",
"error",
")",
"{",
"newChunk",
":=",
"chunkenc",
".",
"NewXORChunk",
"(",
")",
"\n",
"app",
",",
"err",
":=",
"newChunk",
".",
"Appe... | // MergeChunks vertically merges a and b, i.e., if there is any sample
// with same timestamp in both a and b, the sample in a is discarded. | [
"MergeChunks",
"vertically",
"merges",
"a",
"and",
"b",
"i",
".",
"e",
".",
"if",
"there",
"is",
"any",
"sample",
"with",
"same",
"timestamp",
"in",
"both",
"a",
"and",
"b",
"the",
"sample",
"in",
"a",
"is",
"discarded",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/chunks/chunks.go#L240-L281 | train |
prometheus/tsdb | chunks/chunks.go | NewDirReader | func NewDirReader(dir string, pool chunkenc.Pool) (*Reader, error) {
files, err := sequenceFiles(dir)
if err != nil {
return nil, err
}
if pool == nil {
pool = chunkenc.NewPool()
}
var (
bs []ByteSlice
cs []io.Closer
merr tsdb_errors.MultiError
)
for _, fn := range files {
f, err := fileutil.OpenMmapFile(fn)
if err != nil {
merr.Add(errors.Wrap(err, "mmap files"))
merr.Add(closeAll(cs))
return nil, merr
}
cs = append(cs, f)
bs = append(bs, realByteSlice(f.Bytes()))
}
reader, err := newReader(bs, cs, pool)
if err != nil {
merr.Add(err)
merr.Add(closeAll(cs))
return nil, merr
}
return reader, nil
} | go | func NewDirReader(dir string, pool chunkenc.Pool) (*Reader, error) {
files, err := sequenceFiles(dir)
if err != nil {
return nil, err
}
if pool == nil {
pool = chunkenc.NewPool()
}
var (
bs []ByteSlice
cs []io.Closer
merr tsdb_errors.MultiError
)
for _, fn := range files {
f, err := fileutil.OpenMmapFile(fn)
if err != nil {
merr.Add(errors.Wrap(err, "mmap files"))
merr.Add(closeAll(cs))
return nil, merr
}
cs = append(cs, f)
bs = append(bs, realByteSlice(f.Bytes()))
}
reader, err := newReader(bs, cs, pool)
if err != nil {
merr.Add(err)
merr.Add(closeAll(cs))
return nil, merr
}
return reader, nil
} | [
"func",
"NewDirReader",
"(",
"dir",
"string",
",",
"pool",
"chunkenc",
".",
"Pool",
")",
"(",
"*",
"Reader",
",",
"error",
")",
"{",
"files",
",",
"err",
":=",
"sequenceFiles",
"(",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
... | // NewDirReader returns a new Reader against sequentially numbered files in the
// given directory. | [
"NewDirReader",
"returns",
"a",
"new",
"Reader",
"against",
"sequentially",
"numbered",
"files",
"in",
"the",
"given",
"directory",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/chunks/chunks.go#L401-L433 | train |
prometheus/tsdb | chunks/chunks.go | Chunk | func (s *Reader) Chunk(ref uint64) (chunkenc.Chunk, error) {
var (
sgmSeq = int(ref >> 32)
sgmOffset = int((ref << 32) >> 32)
)
if sgmSeq >= len(s.bs) {
return nil, errors.Errorf("reference sequence %d out of range", sgmSeq)
}
chkS := s.bs[sgmSeq]
if sgmOffset >= chkS.Len() {
return nil, errors.Errorf("offset %d beyond data size %d", sgmOffset, chkS.Len())
}
// With the minimum chunk length this should never cause us reading
// over the end of the slice.
chk := chkS.Range(sgmOffset, sgmOffset+binary.MaxVarintLen32)
chkLen, n := binary.Uvarint(chk)
if n <= 0 {
return nil, errors.Errorf("reading chunk length failed with %d", n)
}
chk = chkS.Range(sgmOffset+n, sgmOffset+n+1+int(chkLen))
return s.pool.Get(chunkenc.Encoding(chk[0]), chk[1:1+chkLen])
} | go | func (s *Reader) Chunk(ref uint64) (chunkenc.Chunk, error) {
var (
sgmSeq = int(ref >> 32)
sgmOffset = int((ref << 32) >> 32)
)
if sgmSeq >= len(s.bs) {
return nil, errors.Errorf("reference sequence %d out of range", sgmSeq)
}
chkS := s.bs[sgmSeq]
if sgmOffset >= chkS.Len() {
return nil, errors.Errorf("offset %d beyond data size %d", sgmOffset, chkS.Len())
}
// With the minimum chunk length this should never cause us reading
// over the end of the slice.
chk := chkS.Range(sgmOffset, sgmOffset+binary.MaxVarintLen32)
chkLen, n := binary.Uvarint(chk)
if n <= 0 {
return nil, errors.Errorf("reading chunk length failed with %d", n)
}
chk = chkS.Range(sgmOffset+n, sgmOffset+n+1+int(chkLen))
return s.pool.Get(chunkenc.Encoding(chk[0]), chk[1:1+chkLen])
} | [
"func",
"(",
"s",
"*",
"Reader",
")",
"Chunk",
"(",
"ref",
"uint64",
")",
"(",
"chunkenc",
".",
"Chunk",
",",
"error",
")",
"{",
"var",
"(",
"sgmSeq",
"=",
"int",
"(",
"ref",
">>",
"32",
")",
"\n",
"sgmOffset",
"=",
"int",
"(",
"(",
"ref",
"<<"... | // Chunk returns a chunk from a given reference. | [
"Chunk",
"returns",
"a",
"chunk",
"from",
"a",
"given",
"reference",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/chunks/chunks.go#L445-L469 | train |
prometheus/tsdb | chunkenc/xor.go | NewXORChunk | func NewXORChunk() *XORChunk {
b := make([]byte, 2, 128)
return &XORChunk{b: bstream{stream: b, count: 0}}
} | go | func NewXORChunk() *XORChunk {
b := make([]byte, 2, 128)
return &XORChunk{b: bstream{stream: b, count: 0}}
} | [
"func",
"NewXORChunk",
"(",
")",
"*",
"XORChunk",
"{",
"b",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"2",
",",
"128",
")",
"\n",
"return",
"&",
"XORChunk",
"{",
"b",
":",
"bstream",
"{",
"stream",
":",
"b",
",",
"count",
":",
"0",
"}",
"}",
... | // NewXORChunk returns a new chunk with XOR encoding of the given size. | [
"NewXORChunk",
"returns",
"a",
"new",
"chunk",
"with",
"XOR",
"encoding",
"of",
"the",
"given",
"size",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/chunkenc/xor.go#L58-L61 | train |
prometheus/tsdb | chunkenc/xor.go | NumSamples | func (c *XORChunk) NumSamples() int {
return int(binary.BigEndian.Uint16(c.Bytes()))
} | go | func (c *XORChunk) NumSamples() int {
return int(binary.BigEndian.Uint16(c.Bytes()))
} | [
"func",
"(",
"c",
"*",
"XORChunk",
")",
"NumSamples",
"(",
")",
"int",
"{",
"return",
"int",
"(",
"binary",
".",
"BigEndian",
".",
"Uint16",
"(",
"c",
".",
"Bytes",
"(",
")",
")",
")",
"\n",
"}"
] | // NumSamples returns the number of samples in the chunk. | [
"NumSamples",
"returns",
"the",
"number",
"of",
"samples",
"in",
"the",
"chunk",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/chunkenc/xor.go#L74-L76 | train |
prometheus/tsdb | chunkenc/xor.go | Appender | func (c *XORChunk) Appender() (Appender, error) {
it := c.iterator()
// To get an appender we must know the state it would have if we had
// appended all existing data from scratch.
// We iterate through the end and populate via the iterator's state.
for it.Next() {
}
if err := it.Err(); err != nil {
return nil, err
}
a := &xorAppender{
b: &c.b,
t: it.t,
v: it.val,
tDelta: it.tDelta,
leading: it.leading,
trailing: it.trailing,
}
if binary.BigEndian.Uint16(a.b.bytes()) == 0 {
a.leading = 0xff
}
return a, nil
} | go | func (c *XORChunk) Appender() (Appender, error) {
it := c.iterator()
// To get an appender we must know the state it would have if we had
// appended all existing data from scratch.
// We iterate through the end and populate via the iterator's state.
for it.Next() {
}
if err := it.Err(); err != nil {
return nil, err
}
a := &xorAppender{
b: &c.b,
t: it.t,
v: it.val,
tDelta: it.tDelta,
leading: it.leading,
trailing: it.trailing,
}
if binary.BigEndian.Uint16(a.b.bytes()) == 0 {
a.leading = 0xff
}
return a, nil
} | [
"func",
"(",
"c",
"*",
"XORChunk",
")",
"Appender",
"(",
")",
"(",
"Appender",
",",
"error",
")",
"{",
"it",
":=",
"c",
".",
"iterator",
"(",
")",
"\n",
"for",
"it",
".",
"Next",
"(",
")",
"{",
"}",
"\n",
"if",
"err",
":=",
"it",
".",
"Err",
... | // Appender implements the Chunk interface. | [
"Appender",
"implements",
"the",
"Chunk",
"interface",
"."
] | 3ccab17f5dc60de1bea3e5cfc807cb63a287078f | https://github.com/prometheus/tsdb/blob/3ccab17f5dc60de1bea3e5cfc807cb63a287078f/chunkenc/xor.go#L79-L103 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/export.go | DeleteRegistrationByName | func (mc MongoClient) DeleteRegistrationByName(name string) error {
return mc.deleteRegistration(bson.M{"name": name})
} | go | func (mc MongoClient) DeleteRegistrationByName(name string) error {
return mc.deleteRegistration(bson.M{"name": name})
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"DeleteRegistrationByName",
"(",
"name",
"string",
")",
"error",
"{",
"return",
"mc",
".",
"deleteRegistration",
"(",
"bson",
".",
"M",
"{",
"\"name\"",
":",
"name",
"}",
")",
"\n",
"}"
] | // Delete a registration by name
// UnexpectedError - problem getting in database
// NotFound - no registration with the ID was found | [
"Delete",
"a",
"registration",
"by",
"name",
"UnexpectedError",
"-",
"problem",
"getting",
"in",
"database",
"NotFound",
"-",
"no",
"registration",
"with",
"the",
"ID",
"was",
"found"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/export.go#L120-L122 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/export.go | getRegistrations | func (mc MongoClient) getRegistrations(q bson.M) ([]models.Registration, error) {
s := mc.getSessionCopy()
defer s.Close()
var regs []models.Registration
err := s.DB(mc.database.Name).C(db.ExportCollection).Find(q).All(®s)
if err != nil {
return []models.Registration{}, errorMap(err)
}
return regs, nil
} | go | func (mc MongoClient) getRegistrations(q bson.M) ([]models.Registration, error) {
s := mc.getSessionCopy()
defer s.Close()
var regs []models.Registration
err := s.DB(mc.database.Name).C(db.ExportCollection).Find(q).All(®s)
if err != nil {
return []models.Registration{}, errorMap(err)
}
return regs, nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"getRegistrations",
"(",
"q",
"bson",
".",
"M",
")",
"(",
"[",
"]",
"models",
".",
"Registration",
",",
"error",
")",
"{",
"s",
":=",
"mc",
".",
"getSessionCopy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
"(... | // Get registrations for the passed query | [
"Get",
"registrations",
"for",
"the",
"passed",
"query"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/export.go#L134-L145 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/export.go | getRegistration | func (mc MongoClient) getRegistration(q bson.M) (models.Registration, error) {
s := mc.getSessionCopy()
defer s.Close()
var reg models.Registration
err := s.DB(mc.database.Name).C(db.ExportCollection).Find(q).One(®)
if err != nil {
return models.Registration{}, errorMap(err)
}
return reg, nil
} | go | func (mc MongoClient) getRegistration(q bson.M) (models.Registration, error) {
s := mc.getSessionCopy()
defer s.Close()
var reg models.Registration
err := s.DB(mc.database.Name).C(db.ExportCollection).Find(q).One(®)
if err != nil {
return models.Registration{}, errorMap(err)
}
return reg, nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"getRegistration",
"(",
"q",
"bson",
".",
"M",
")",
"(",
"models",
".",
"Registration",
",",
"error",
")",
"{",
"s",
":=",
"mc",
".",
"getSessionCopy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
"(",
")",
"\n... | // Get a single registration for the passed query | [
"Get",
"a",
"single",
"registration",
"for",
"the",
"passed",
"query"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/export.go#L148-L158 | train |
edgexfoundry/edgex-go | internal/core/data/init.go | newDBClient | func newDBClient(dbType string) (interfaces.DBClient, error) {
switch dbType {
case db.MongoDB:
dbConfig := db.Configuration{
Host: Configuration.Databases["Primary"].Host,
Port: Configuration.Databases["Primary"].Port,
Timeout: Configuration.Databases["Primary"].Timeout,
DatabaseName: Configuration.Databases["Primary"].Name,
Username: Configuration.Databases["Primary"].Username,
Password: Configuration.Databases["Primary"].Password,
}
return mongo.NewClient(dbConfig)
case db.RedisDB:
dbConfig := db.Configuration{
Host: Configuration.Databases["Primary"].Host,
Port: Configuration.Databases["Primary"].Port,
}
return redis.NewClient(dbConfig) //TODO: Verify this also connects to Redis
default:
return nil, db.ErrUnsupportedDatabase
}
} | go | func newDBClient(dbType string) (interfaces.DBClient, error) {
switch dbType {
case db.MongoDB:
dbConfig := db.Configuration{
Host: Configuration.Databases["Primary"].Host,
Port: Configuration.Databases["Primary"].Port,
Timeout: Configuration.Databases["Primary"].Timeout,
DatabaseName: Configuration.Databases["Primary"].Name,
Username: Configuration.Databases["Primary"].Username,
Password: Configuration.Databases["Primary"].Password,
}
return mongo.NewClient(dbConfig)
case db.RedisDB:
dbConfig := db.Configuration{
Host: Configuration.Databases["Primary"].Host,
Port: Configuration.Databases["Primary"].Port,
}
return redis.NewClient(dbConfig) //TODO: Verify this also connects to Redis
default:
return nil, db.ErrUnsupportedDatabase
}
} | [
"func",
"newDBClient",
"(",
"dbType",
"string",
")",
"(",
"interfaces",
".",
"DBClient",
",",
"error",
")",
"{",
"switch",
"dbType",
"{",
"case",
"db",
".",
"MongoDB",
":",
"dbConfig",
":=",
"db",
".",
"Configuration",
"{",
"Host",
":",
"Configuration",
... | // Return the dbClient interface | [
"Return",
"the",
"dbClient",
"interface"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/data/init.go#L152-L173 | train |
edgexfoundry/edgex-go | internal/system/agent/utils.go | pingHandler | func pingHandler(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("pong"))
} | go | func pingHandler(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("pong"))
} | [
"func",
"pingHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"_",
"*",
"http",
".",
"Request",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Content-Type\"",
",",
"\"text/plain\"",
")",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
... | // Test if the service is working | [
"Test",
"if",
"the",
"service",
"is",
"working"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/system/agent/utils.go#L25-L28 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | EventsWithLimit | func (mc MongoClient) EventsWithLimit(limit int) ([]contract.Event, error) {
return mc.mapEvents(mc.getEventsLimit(bson.M{}, limit))
} | go | func (mc MongoClient) EventsWithLimit(limit int) ([]contract.Event, error) {
return mc.mapEvents(mc.getEventsLimit(bson.M{}, limit))
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"EventsWithLimit",
"(",
"limit",
"int",
")",
"(",
"[",
"]",
"contract",
".",
"Event",
",",
"error",
")",
"{",
"return",
"mc",
".",
"mapEvents",
"(",
"mc",
".",
"getEventsLimit",
"(",
"bson",
".",
"M",
"{",
"}",
... | // Return events up to the max number specified
// UnexpectedError - failed to retrieve events from the database
// Sort the events in descending order by ID | [
"Return",
"events",
"up",
"to",
"the",
"max",
"number",
"specified",
"UnexpectedError",
"-",
"failed",
"to",
"retrieve",
"events",
"from",
"the",
"database",
"Sort",
"the",
"events",
"in",
"descending",
"order",
"by",
"ID"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L42-L44 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | EventCount | func (mc MongoClient) EventCount() (int, error) {
s := mc.getSessionCopy()
defer s.Close()
count, err := s.DB(mc.database.Name).C(db.EventsCollection).Find(nil).Count()
if err != nil {
return 0, errorMap(err)
}
return count, nil
} | go | func (mc MongoClient) EventCount() (int, error) {
s := mc.getSessionCopy()
defer s.Close()
count, err := s.DB(mc.database.Name).C(db.EventsCollection).Find(nil).Count()
if err != nil {
return 0, errorMap(err)
}
return count, nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"EventCount",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"s",
":=",
"mc",
".",
"getSessionCopy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
"(",
")",
"\n",
"count",
",",
"err",
":=",
"s",
".",
"DB",
"(... | // Get the number of events in Mongo | [
"Get",
"the",
"number",
"of",
"events",
"in",
"Mongo"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L121-L130 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | EventCountByDeviceId | func (mc MongoClient) EventCountByDeviceId(id string) (int, error) {
s := mc.getSessionCopy()
defer s.Close()
query := bson.M{"device": id}
count, err := s.DB(mc.database.Name).C(db.EventsCollection).Find(query).Count()
if err != nil {
return 0, errorMap(err)
}
return count, nil
} | go | func (mc MongoClient) EventCountByDeviceId(id string) (int, error) {
s := mc.getSessionCopy()
defer s.Close()
query := bson.M{"device": id}
count, err := s.DB(mc.database.Name).C(db.EventsCollection).Find(query).Count()
if err != nil {
return 0, errorMap(err)
}
return count, nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"EventCountByDeviceId",
"(",
"id",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"s",
":=",
"mc",
".",
"getSessionCopy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
"(",
")",
"\n",
"query",
":=",
"bson",
... | // Get the number of events in Mongo for the device | [
"Get",
"the",
"number",
"of",
"events",
"in",
"Mongo",
"for",
"the",
"device"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L133-L143 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | DeleteEventById | func (mc MongoClient) DeleteEventById(id string) error {
return mc.deleteById(db.EventsCollection, id)
} | go | func (mc MongoClient) DeleteEventById(id string) error {
return mc.deleteById(db.EventsCollection, id)
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"DeleteEventById",
"(",
"id",
"string",
")",
"error",
"{",
"return",
"mc",
".",
"deleteById",
"(",
"db",
".",
"EventsCollection",
",",
"id",
")",
"\n",
"}"
] | // Delete an event by ID and all of its readings
// 404 - Event not found
// 503 - Unexpected problems | [
"Delete",
"an",
"event",
"by",
"ID",
"and",
"all",
"of",
"its",
"readings",
"404",
"-",
"Event",
"not",
"found",
"503",
"-",
"Unexpected",
"problems"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L148-L150 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | EventsForDeviceLimit | func (mc MongoClient) EventsForDeviceLimit(id string, limit int) ([]contract.Event, error) {
return mc.mapEvents(mc.getEventsLimit(bson.M{"device": id}, limit))
} | go | func (mc MongoClient) EventsForDeviceLimit(id string, limit int) ([]contract.Event, error) {
return mc.mapEvents(mc.getEventsLimit(bson.M{"device": id}, limit))
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"EventsForDeviceLimit",
"(",
"id",
"string",
",",
"limit",
"int",
")",
"(",
"[",
"]",
"contract",
".",
"Event",
",",
"error",
")",
"{",
"return",
"mc",
".",
"mapEvents",
"(",
"mc",
".",
"getEventsLimit",
"(",
"bso... | // Get a list of events based on the device id and limit | [
"Get",
"a",
"list",
"of",
"events",
"based",
"on",
"the",
"device",
"id",
"and",
"limit"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L153-L155 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | EventsByCreationTime | func (mc MongoClient) EventsByCreationTime(startTime, endTime int64, limit int) ([]contract.Event, error) {
query := bson.M{"created": bson.M{
"$gte": startTime,
"$lte": endTime,
}}
return mc.mapEvents(mc.getEventsLimit(query, limit))
} | go | func (mc MongoClient) EventsByCreationTime(startTime, endTime int64, limit int) ([]contract.Event, error) {
query := bson.M{"created": bson.M{
"$gte": startTime,
"$lte": endTime,
}}
return mc.mapEvents(mc.getEventsLimit(query, limit))
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"EventsByCreationTime",
"(",
"startTime",
",",
"endTime",
"int64",
",",
"limit",
"int",
")",
"(",
"[",
"]",
"contract",
".",
"Event",
",",
"error",
")",
"{",
"query",
":=",
"bson",
".",
"M",
"{",
"\"created\"",
":... | // Return a list of events whose creation time is between startTime and endTime
// Limit the number of results by limit | [
"Return",
"a",
"list",
"of",
"events",
"whose",
"creation",
"time",
"is",
"between",
"startTime",
"and",
"endTime",
"Limit",
"the",
"number",
"of",
"results",
"by",
"limit"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L164-L170 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | EventsPushed | func (mc MongoClient) EventsPushed() ([]contract.Event, error) {
return mc.mapEvents(mc.getEvents(bson.M{"pushed": bson.M{"$gt": int64(0)}}))
} | go | func (mc MongoClient) EventsPushed() ([]contract.Event, error) {
return mc.mapEvents(mc.getEvents(bson.M{"pushed": bson.M{"$gt": int64(0)}}))
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"EventsPushed",
"(",
")",
"(",
"[",
"]",
"contract",
".",
"Event",
",",
"error",
")",
"{",
"return",
"mc",
".",
"mapEvents",
"(",
"mc",
".",
"getEvents",
"(",
"bson",
".",
"M",
"{",
"\"pushed\"",
":",
"bson",
... | // Get all of the events that have been pushed | [
"Get",
"all",
"of",
"the",
"events",
"that",
"have",
"been",
"pushed"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L179-L181 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | ScrubAllEvents | func (mc MongoClient) ScrubAllEvents() error {
s := mc.getSessionCopy()
defer s.Close()
_, err := s.DB(mc.database.Name).C(db.ReadingsCollection).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
_, err = s.DB(mc.database.Name).C(db.EventsCollection).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
return nil
} | go | func (mc MongoClient) ScrubAllEvents() error {
s := mc.getSessionCopy()
defer s.Close()
_, err := s.DB(mc.database.Name).C(db.ReadingsCollection).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
_, err = s.DB(mc.database.Name).C(db.EventsCollection).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
return nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"ScrubAllEvents",
"(",
")",
"error",
"{",
"s",
":=",
"mc",
".",
"getSessionCopy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"s",
".",
"DB",
"(",
"mc",
".",
"database"... | // Delete all of the readings and all of the events | [
"Delete",
"all",
"of",
"the",
"readings",
"and",
"all",
"of",
"the",
"events"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L184-L199 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | getEvents | func (mc MongoClient) getEvents(q bson.M) (me []models.Event, err error) {
s := mc.getSessionCopy()
defer s.Close()
err = s.DB(mc.database.Name).C(db.EventsCollection).Find(q).All(&me)
if err != nil {
return []models.Event{}, errorMap(err)
}
return
} | go | func (mc MongoClient) getEvents(q bson.M) (me []models.Event, err error) {
s := mc.getSessionCopy()
defer s.Close()
err = s.DB(mc.database.Name).C(db.EventsCollection).Find(q).All(&me)
if err != nil {
return []models.Event{}, errorMap(err)
}
return
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"getEvents",
"(",
"q",
"bson",
".",
"M",
")",
"(",
"me",
"[",
"]",
"models",
".",
"Event",
",",
"err",
"error",
")",
"{",
"s",
":=",
"mc",
".",
"getSessionCopy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
... | // Get events for the passed query | [
"Get",
"events",
"for",
"the",
"passed",
"query"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L202-L211 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | getEventsLimit | func (mc MongoClient) getEventsLimit(q bson.M, limit int) (me []models.Event, err error) {
s := mc.getSessionCopy()
defer s.Close()
// Check if limit is 0
if limit == 0 {
return []models.Event{}, nil
}
err = s.DB(mc.database.Name).C(db.EventsCollection).Find(q).Sort("-modified").Limit(limit).All(&me)
if err != nil {
return []models.Event{}, errorMap(err)
}
return
} | go | func (mc MongoClient) getEventsLimit(q bson.M, limit int) (me []models.Event, err error) {
s := mc.getSessionCopy()
defer s.Close()
// Check if limit is 0
if limit == 0 {
return []models.Event{}, nil
}
err = s.DB(mc.database.Name).C(db.EventsCollection).Find(q).Sort("-modified").Limit(limit).All(&me)
if err != nil {
return []models.Event{}, errorMap(err)
}
return
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"getEventsLimit",
"(",
"q",
"bson",
".",
"M",
",",
"limit",
"int",
")",
"(",
"me",
"[",
"]",
"models",
".",
"Event",
",",
"err",
"error",
")",
"{",
"s",
":=",
"mc",
".",
"getSessionCopy",
"(",
")",
"\n",
"de... | // Get events with a limit
// Sort the list before applying the limit so we can return the most recent events | [
"Get",
"events",
"with",
"a",
"limit",
"Sort",
"the",
"list",
"before",
"applying",
"the",
"limit",
"so",
"we",
"can",
"return",
"the",
"most",
"recent",
"events"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L215-L229 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | Readings | func (mc MongoClient) Readings() ([]contract.Reading, error) {
readings, err := mc.getReadings(nil)
if err != nil {
return []contract.Reading{}, err
}
mapped := make([]contract.Reading, 0)
for _, r := range readings {
mapped = append(mapped, r.ToContract())
}
return mapped, nil
} | go | func (mc MongoClient) Readings() ([]contract.Reading, error) {
readings, err := mc.getReadings(nil)
if err != nil {
return []contract.Reading{}, err
}
mapped := make([]contract.Reading, 0)
for _, r := range readings {
mapped = append(mapped, r.ToContract())
}
return mapped, nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"Readings",
"(",
")",
"(",
"[",
"]",
"contract",
".",
"Reading",
",",
"error",
")",
"{",
"readings",
",",
"err",
":=",
"mc",
".",
"getReadings",
"(",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
... | // Return a list of readings sorted by reading id | [
"Return",
"a",
"list",
"of",
"readings",
"sorted",
"by",
"reading",
"id"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L260-L271 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | AddReading | func (mc MongoClient) AddReading(r contract.Reading) (string, error) {
s := mc.getSessionCopy()
defer s.Close()
var mapped models.Reading
id, err := mapped.FromContract(r)
if err != nil {
return "", err
}
mapped.TimestampForAdd()
err = s.DB(mc.database.Name).C(db.ReadingsCollection).Insert(&mapped)
if err != nil {
return "", errorMap(err)
}
return id, err
} | go | func (mc MongoClient) AddReading(r contract.Reading) (string, error) {
s := mc.getSessionCopy()
defer s.Close()
var mapped models.Reading
id, err := mapped.FromContract(r)
if err != nil {
return "", err
}
mapped.TimestampForAdd()
err = s.DB(mc.database.Name).C(db.ReadingsCollection).Insert(&mapped)
if err != nil {
return "", errorMap(err)
}
return id, err
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"AddReading",
"(",
"r",
"contract",
".",
"Reading",
")",
"(",
"string",
",",
"error",
")",
"{",
"s",
":=",
"mc",
".",
"getSessionCopy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
"(",
")",
"\n",
"var",
"mappe... | // Post a new reading | [
"Post",
"a",
"new",
"reading"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L274-L291 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | ReadingCount | func (mc MongoClient) ReadingCount() (int, error) {
s := mc.getSessionCopy()
defer s.Close()
count, err := s.DB(mc.database.Name).C(db.ReadingsCollection).Find(bson.M{}).Count()
if err != nil {
return 0, errorMap(err)
}
return count, nil
} | go | func (mc MongoClient) ReadingCount() (int, error) {
s := mc.getSessionCopy()
defer s.Close()
count, err := s.DB(mc.database.Name).C(db.ReadingsCollection).Find(bson.M{}).Count()
if err != nil {
return 0, errorMap(err)
}
return count, nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"ReadingCount",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"s",
":=",
"mc",
".",
"getSessionCopy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
"(",
")",
"\n",
"count",
",",
"err",
":=",
"s",
".",
"DB",
... | // Get the count of readings in Mongo | [
"Get",
"the",
"count",
"of",
"readings",
"in",
"Mongo"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L335-L344 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | ReadingsByValueDescriptor | func (mc MongoClient) ReadingsByValueDescriptor(name string, limit int) ([]contract.Reading, error) {
return mapReadings(mc.getReadingsLimit(bson.M{"name": name}, limit))
} | go | func (mc MongoClient) ReadingsByValueDescriptor(name string, limit int) ([]contract.Reading, error) {
return mapReadings(mc.getReadingsLimit(bson.M{"name": name}, limit))
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"ReadingsByValueDescriptor",
"(",
"name",
"string",
",",
"limit",
"int",
")",
"(",
"[",
"]",
"contract",
".",
"Reading",
",",
"error",
")",
"{",
"return",
"mapReadings",
"(",
"mc",
".",
"getReadingsLimit",
"(",
"bson"... | // Return a list of readings for the given value descriptor
// Limit by the given limit | [
"Return",
"a",
"list",
"of",
"readings",
"for",
"the",
"given",
"value",
"descriptor",
"Limit",
"by",
"the",
"given",
"limit"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L360-L362 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | ReadingsByValueDescriptorNames | func (mc MongoClient) ReadingsByValueDescriptorNames(names []string, limit int) ([]contract.Reading, error) {
return mapReadings(mc.getReadingsLimit(bson.M{"name": bson.M{"$in": names}}, limit))
} | go | func (mc MongoClient) ReadingsByValueDescriptorNames(names []string, limit int) ([]contract.Reading, error) {
return mapReadings(mc.getReadingsLimit(bson.M{"name": bson.M{"$in": names}}, limit))
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"ReadingsByValueDescriptorNames",
"(",
"names",
"[",
"]",
"string",
",",
"limit",
"int",
")",
"(",
"[",
"]",
"contract",
".",
"Reading",
",",
"error",
")",
"{",
"return",
"mapReadings",
"(",
"mc",
".",
"getReadingsLim... | // Return a list of readings whose name is in the list of value descriptor names | [
"Return",
"a",
"list",
"of",
"readings",
"whose",
"name",
"is",
"in",
"the",
"list",
"of",
"value",
"descriptor",
"names"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L365-L367 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | ReadingsByCreationTime | func (mc MongoClient) ReadingsByCreationTime(start, end int64, limit int) ([]contract.Reading, error) {
return mapReadings(mc.getReadingsLimit(bson.M{"created": bson.M{"$gte": start, "$lte": end}}, limit))
} | go | func (mc MongoClient) ReadingsByCreationTime(start, end int64, limit int) ([]contract.Reading, error) {
return mapReadings(mc.getReadingsLimit(bson.M{"created": bson.M{"$gte": start, "$lte": end}}, limit))
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"ReadingsByCreationTime",
"(",
"start",
",",
"end",
"int64",
",",
"limit",
"int",
")",
"(",
"[",
"]",
"contract",
".",
"Reading",
",",
"error",
")",
"{",
"return",
"mapReadings",
"(",
"mc",
".",
"getReadingsLimit",
... | // Return a list of readings whose creation time is in-between start and end
// Limit by the limit parameter | [
"Return",
"a",
"list",
"of",
"readings",
"whose",
"creation",
"time",
"is",
"in",
"-",
"between",
"start",
"and",
"end",
"Limit",
"by",
"the",
"limit",
"parameter"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L371-L373 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | getReadingsLimit | func (mc MongoClient) getReadingsLimit(q bson.M, limit int) ([]models.Reading, error) {
s := mc.getSessionCopy()
defer s.Close()
// Check if limit is 0
if limit == 0 {
return []models.Reading{}, nil
}
var readings []models.Reading
if err := s.DB(mc.database.Name).C(db.ReadingsCollection).Find(q).Sort("-modified").Limit(limit).All(&readings); err != nil {
return []models.Reading{}, errorMap(err)
}
return readings, nil
} | go | func (mc MongoClient) getReadingsLimit(q bson.M, limit int) ([]models.Reading, error) {
s := mc.getSessionCopy()
defer s.Close()
// Check if limit is 0
if limit == 0 {
return []models.Reading{}, nil
}
var readings []models.Reading
if err := s.DB(mc.database.Name).C(db.ReadingsCollection).Find(q).Sort("-modified").Limit(limit).All(&readings); err != nil {
return []models.Reading{}, errorMap(err)
}
return readings, nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"getReadingsLimit",
"(",
"q",
"bson",
".",
"M",
",",
"limit",
"int",
")",
"(",
"[",
"]",
"models",
".",
"Reading",
",",
"error",
")",
"{",
"s",
":=",
"mc",
".",
"getSessionCopy",
"(",
")",
"\n",
"defer",
"s",
... | // Return a list of readings that match.
// Sort the list before applying the limit so we can return the most recent readings | [
"Return",
"a",
"list",
"of",
"readings",
"that",
"match",
".",
"Sort",
"the",
"list",
"before",
"applying",
"the",
"limit",
"so",
"we",
"can",
"return",
"the",
"most",
"recent",
"readings"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L383-L397 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | getReading | func (mc MongoClient) getReading(q bson.M) (models.Reading, error) {
s := mc.getSessionCopy()
defer s.Close()
var res models.Reading
if err := s.DB(mc.database.Name).C(db.ReadingsCollection).Find(q).One(&res); err != nil {
return models.Reading{}, errorMap(err)
}
return res, nil
} | go | func (mc MongoClient) getReading(q bson.M) (models.Reading, error) {
s := mc.getSessionCopy()
defer s.Close()
var res models.Reading
if err := s.DB(mc.database.Name).C(db.ReadingsCollection).Find(q).One(&res); err != nil {
return models.Reading{}, errorMap(err)
}
return res, nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"getReading",
"(",
"q",
"bson",
".",
"M",
")",
"(",
"models",
".",
"Reading",
",",
"error",
")",
"{",
"s",
":=",
"mc",
".",
"getSessionCopy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
"(",
")",
"\n",
"var"... | // Get a reading from the database with the passed query | [
"Get",
"a",
"reading",
"from",
"the",
"database",
"with",
"the",
"passed",
"query"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L412-L421 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | DeleteValueDescriptorById | func (mc MongoClient) DeleteValueDescriptorById(id string) error {
return mc.deleteById(db.ValueDescriptorCollection, id)
} | go | func (mc MongoClient) DeleteValueDescriptorById(id string) error {
return mc.deleteById(db.ValueDescriptorCollection, id)
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"DeleteValueDescriptorById",
"(",
"id",
"string",
")",
"error",
"{",
"return",
"mc",
".",
"deleteById",
"(",
"db",
".",
"ValueDescriptorCollection",
",",
"id",
")",
"\n",
"}"
] | // Delete the value descriptor based on the id
// Not found error if there isn't a value descriptor for the ID
// ValueDescriptorStillInUse if the value descriptor is still referenced by readings | [
"Delete",
"the",
"value",
"descriptor",
"based",
"on",
"the",
"id",
"Not",
"found",
"error",
"if",
"there",
"isn",
"t",
"a",
"value",
"descriptor",
"for",
"the",
"ID",
"ValueDescriptorStillInUse",
"if",
"the",
"value",
"descriptor",
"is",
"still",
"referenced"... | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L496-L498 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | ValueDescriptorByName | func (mc MongoClient) ValueDescriptorByName(name string) (contract.ValueDescriptor, error) {
mvd, err := mc.getValueDescriptor(bson.M{"name": name})
if err != nil {
return contract.ValueDescriptor{}, err
}
return mvd.ToContract(), nil
} | go | func (mc MongoClient) ValueDescriptorByName(name string) (contract.ValueDescriptor, error) {
mvd, err := mc.getValueDescriptor(bson.M{"name": name})
if err != nil {
return contract.ValueDescriptor{}, err
}
return mvd.ToContract(), nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"ValueDescriptorByName",
"(",
"name",
"string",
")",
"(",
"contract",
".",
"ValueDescriptor",
",",
"error",
")",
"{",
"mvd",
",",
"err",
":=",
"mc",
".",
"getValueDescriptor",
"(",
"bson",
".",
"M",
"{",
"\"name\"",
... | // Return a value descriptor based on the name
// Can return null if no value descriptor is found | [
"Return",
"a",
"value",
"descriptor",
"based",
"on",
"the",
"name",
"Can",
"return",
"null",
"if",
"no",
"value",
"descriptor",
"is",
"found"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L502-L508 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | ValueDescriptorsByName | func (mc MongoClient) ValueDescriptorsByName(names []string) ([]contract.ValueDescriptor, error) {
vList := make([]contract.ValueDescriptor, 0)
for _, name := range names {
v, err := mc.ValueDescriptorByName(name)
if err != nil && err != db.ErrNotFound {
return []contract.ValueDescriptor{}, err
}
if err == nil {
vList = append(vList, v)
}
}
return vList, nil
} | go | func (mc MongoClient) ValueDescriptorsByName(names []string) ([]contract.ValueDescriptor, error) {
vList := make([]contract.ValueDescriptor, 0)
for _, name := range names {
v, err := mc.ValueDescriptorByName(name)
if err != nil && err != db.ErrNotFound {
return []contract.ValueDescriptor{}, err
}
if err == nil {
vList = append(vList, v)
}
}
return vList, nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"ValueDescriptorsByName",
"(",
"names",
"[",
"]",
"string",
")",
"(",
"[",
"]",
"contract",
".",
"ValueDescriptor",
",",
"error",
")",
"{",
"vList",
":=",
"make",
"(",
"[",
"]",
"contract",
".",
"ValueDescriptor",
"... | // Return all of the value descriptors based on the names | [
"Return",
"all",
"of",
"the",
"value",
"descriptors",
"based",
"on",
"the",
"names"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L511-L524 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | ValueDescriptorById | func (mc MongoClient) ValueDescriptorById(id string) (contract.ValueDescriptor, error) {
query, err := idToBsonM(id)
if err != nil {
return contract.ValueDescriptor{}, err
}
mvd, err := mc.getValueDescriptor(query)
if err != nil {
return contract.ValueDescriptor{}, err
}
return mvd.ToContract(), nil
} | go | func (mc MongoClient) ValueDescriptorById(id string) (contract.ValueDescriptor, error) {
query, err := idToBsonM(id)
if err != nil {
return contract.ValueDescriptor{}, err
}
mvd, err := mc.getValueDescriptor(query)
if err != nil {
return contract.ValueDescriptor{}, err
}
return mvd.ToContract(), nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"ValueDescriptorById",
"(",
"id",
"string",
")",
"(",
"contract",
".",
"ValueDescriptor",
",",
"error",
")",
"{",
"query",
",",
"err",
":=",
"idToBsonM",
"(",
"id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"retur... | // Return a value descriptor based on the id
// Return NotFoundError if there is no value descriptor for the id | [
"Return",
"a",
"value",
"descriptor",
"based",
"on",
"the",
"id",
"Return",
"NotFoundError",
"if",
"there",
"is",
"no",
"value",
"descriptor",
"for",
"the",
"id"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L528-L539 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | ValueDescriptorsByUomLabel | func (mc MongoClient) ValueDescriptorsByUomLabel(uomLabel string) ([]contract.ValueDescriptor, error) {
return mapValueDescriptors(mc.getValueDescriptors(bson.M{"uomLabel": uomLabel}))
} | go | func (mc MongoClient) ValueDescriptorsByUomLabel(uomLabel string) ([]contract.ValueDescriptor, error) {
return mapValueDescriptors(mc.getValueDescriptors(bson.M{"uomLabel": uomLabel}))
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"ValueDescriptorsByUomLabel",
"(",
"uomLabel",
"string",
")",
"(",
"[",
"]",
"contract",
".",
"ValueDescriptor",
",",
"error",
")",
"{",
"return",
"mapValueDescriptors",
"(",
"mc",
".",
"getValueDescriptors",
"(",
"bson",
... | // Return all the value descriptors that match the UOM label | [
"Return",
"all",
"the",
"value",
"descriptors",
"that",
"match",
"the",
"UOM",
"label"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L542-L544 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | ValueDescriptorsByLabel | func (mc MongoClient) ValueDescriptorsByLabel(label string) ([]contract.ValueDescriptor, error) {
return mapValueDescriptors(mc.getValueDescriptors(bson.M{"labels": label}))
} | go | func (mc MongoClient) ValueDescriptorsByLabel(label string) ([]contract.ValueDescriptor, error) {
return mapValueDescriptors(mc.getValueDescriptors(bson.M{"labels": label}))
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"ValueDescriptorsByLabel",
"(",
"label",
"string",
")",
"(",
"[",
"]",
"contract",
".",
"ValueDescriptor",
",",
"error",
")",
"{",
"return",
"mapValueDescriptors",
"(",
"mc",
".",
"getValueDescriptors",
"(",
"bson",
".",
... | // Return value descriptors based on if it has the label | [
"Return",
"value",
"descriptors",
"based",
"on",
"if",
"it",
"has",
"the",
"label"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L547-L549 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | ValueDescriptorsByType | func (mc MongoClient) ValueDescriptorsByType(t string) ([]contract.ValueDescriptor, error) {
return mapValueDescriptors(mc.getValueDescriptors(bson.M{"type": t}))
} | go | func (mc MongoClient) ValueDescriptorsByType(t string) ([]contract.ValueDescriptor, error) {
return mapValueDescriptors(mc.getValueDescriptors(bson.M{"type": t}))
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"ValueDescriptorsByType",
"(",
"t",
"string",
")",
"(",
"[",
"]",
"contract",
".",
"ValueDescriptor",
",",
"error",
")",
"{",
"return",
"mapValueDescriptors",
"(",
"mc",
".",
"getValueDescriptors",
"(",
"bson",
".",
"M"... | // Return value descriptors based on the type | [
"Return",
"value",
"descriptors",
"based",
"on",
"the",
"type"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L552-L554 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | ScrubAllValueDescriptors | func (mc MongoClient) ScrubAllValueDescriptors() error {
s := mc.getSessionCopy()
defer s.Close()
if _, err := s.DB(mc.database.Name).C(db.ValueDescriptorCollection).RemoveAll(nil); err != nil {
return errorMap(err)
}
return nil
} | go | func (mc MongoClient) ScrubAllValueDescriptors() error {
s := mc.getSessionCopy()
defer s.Close()
if _, err := s.DB(mc.database.Name).C(db.ValueDescriptorCollection).RemoveAll(nil); err != nil {
return errorMap(err)
}
return nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"ScrubAllValueDescriptors",
"(",
")",
"error",
"{",
"s",
":=",
"mc",
".",
"getSessionCopy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
"(",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"s",
".",
"DB",
"(",
"mc",
... | // Delete all of the value descriptors | [
"Delete",
"all",
"of",
"the",
"value",
"descriptors"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L557-L565 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | getValueDescriptors | func (mc MongoClient) getValueDescriptors(q bson.M) ([]models.ValueDescriptor, error) {
s := mc.getSessionCopy()
defer s.Close()
var v []models.ValueDescriptor
if err := s.DB(mc.database.Name).C(db.ValueDescriptorCollection).Find(q).All(&v); err != nil {
return []models.ValueDescriptor{}, errorMap(err)
}
return v, nil
} | go | func (mc MongoClient) getValueDescriptors(q bson.M) ([]models.ValueDescriptor, error) {
s := mc.getSessionCopy()
defer s.Close()
var v []models.ValueDescriptor
if err := s.DB(mc.database.Name).C(db.ValueDescriptorCollection).Find(q).All(&v); err != nil {
return []models.ValueDescriptor{}, errorMap(err)
}
return v, nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"getValueDescriptors",
"(",
"q",
"bson",
".",
"M",
")",
"(",
"[",
"]",
"models",
".",
"ValueDescriptor",
",",
"error",
")",
"{",
"s",
":=",
"mc",
".",
"getSessionCopy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close"... | // Get value descriptors based on the query | [
"Get",
"value",
"descriptors",
"based",
"on",
"the",
"query"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L568-L577 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/data.go | getValueDescriptor | func (mc MongoClient) getValueDescriptor(q bson.M) (models.ValueDescriptor, error) {
s := mc.getSessionCopy()
defer s.Close()
var m models.ValueDescriptor
if err := s.DB(mc.database.Name).C(db.ValueDescriptorCollection).Find(q).One(&m); err != nil {
return models.ValueDescriptor{}, errorMap(err)
}
return m, nil
} | go | func (mc MongoClient) getValueDescriptor(q bson.M) (models.ValueDescriptor, error) {
s := mc.getSessionCopy()
defer s.Close()
var m models.ValueDescriptor
if err := s.DB(mc.database.Name).C(db.ValueDescriptorCollection).Find(q).One(&m); err != nil {
return models.ValueDescriptor{}, errorMap(err)
}
return m, nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"getValueDescriptor",
"(",
"q",
"bson",
".",
"M",
")",
"(",
"models",
".",
"ValueDescriptor",
",",
"error",
")",
"{",
"s",
":=",
"mc",
".",
"getSessionCopy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
"(",
")",... | // Get a value descriptor based on the query | [
"Get",
"a",
"value",
"descriptor",
"based",
"on",
"the",
"query"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/data.go#L592-L601 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/notifications.go | GetSubscriptions | func (mc MongoClient) GetSubscriptions() ([]contract.Subscription, error) {
return mc.getSubscriptions(bson.M{})
} | go | func (mc MongoClient) GetSubscriptions() ([]contract.Subscription, error) {
return mc.getSubscriptions(bson.M{})
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"GetSubscriptions",
"(",
")",
"(",
"[",
"]",
"contract",
".",
"Subscription",
",",
"error",
")",
"{",
"return",
"mc",
".",
"getSubscriptions",
"(",
"bson",
".",
"M",
"{",
"}",
")",
"\n",
"}"
] | // Return all the subscriptions
// UnexpectedError - failed to retrieve subscriptions from the database | [
"Return",
"all",
"the",
"subscriptions",
"UnexpectedError",
"-",
"failed",
"to",
"retrieve",
"subscriptions",
"from",
"the",
"database"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/notifications.go#L288-L290 | train |
edgexfoundry/edgex-go | internal/export/client/server.go | encode | func encode(i interface{}, w http.ResponseWriter) {
w.Header().Add("Content-Type", "application/json")
enc := json.NewEncoder(w)
err := enc.Encode(i)
// Problems encoding
if err != nil {
LoggingClient.Error("Error encoding the data: " + err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
} | go | func encode(i interface{}, w http.ResponseWriter) {
w.Header().Add("Content-Type", "application/json")
enc := json.NewEncoder(w)
err := enc.Encode(i)
// Problems encoding
if err != nil {
LoggingClient.Error("Error encoding the data: " + err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
} | [
"func",
"encode",
"(",
"i",
"interface",
"{",
"}",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Add",
"(",
"\"Content-Type\"",
",",
"\"application/json\"",
")",
"\n",
"enc",
":=",
"json",
".",
"NewEncoder",
"("... | // Helper function for encoding things for returning from REST calls | [
"Helper",
"function",
"for",
"encoding",
"things",
"for",
"returning",
"from",
"REST",
"calls"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/export/client/server.go#L32-L43 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_provisionwatcher.go | deleteProvisionWatcher | func deleteProvisionWatcher(pw models.ProvisionWatcher, w http.ResponseWriter) error {
if err := dbClient.DeleteProvisionWatcherById(pw.Id); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
if err := notifyProvisionWatcherAssociates(pw, http.MethodDelete); err != nil {
LoggingClient.Error("Problem notifying associated device services to provision watcher: " + err.Error())
}
return nil
} | go | func deleteProvisionWatcher(pw models.ProvisionWatcher, w http.ResponseWriter) error {
if err := dbClient.DeleteProvisionWatcherById(pw.Id); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
if err := notifyProvisionWatcherAssociates(pw, http.MethodDelete); err != nil {
LoggingClient.Error("Problem notifying associated device services to provision watcher: " + err.Error())
}
return nil
} | [
"func",
"deleteProvisionWatcher",
"(",
"pw",
"models",
".",
"ProvisionWatcher",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"if",
"err",
":=",
"dbClient",
".",
"DeleteProvisionWatcherById",
"(",
"pw",
".",
"Id",
")",
";",
"err",
"!=",
"nil",
... | // Delete the provision watcher | [
"Delete",
"the",
"provision",
"watcher"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_provisionwatcher.go#L104-L115 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_provisionwatcher.go | restUpdateProvisionWatcher | func restUpdateProvisionWatcher(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var from models.ProvisionWatcher
if err := json.NewDecoder(r.Body).Decode(&from); err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
// Check if the provision watcher exists
// Try by ID
to, err := dbClient.GetProvisionWatcherById(from.Id)
if err != nil {
// Try by name
if to, err = dbClient.GetProvisionWatcherByName(from.Name); err != nil {
if err == db.ErrNotFound {
http.Error(w, "Provision watcher not found", http.StatusNotFound)
LoggingClient.Error("Provision watcher not found: " + err.Error())
} else {
LoggingClient.Error("Problem getting provision watcher: " + err.Error())
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
return
}
}
if err := updateProvisionWatcherFields(from, &to, w); err != nil {
LoggingClient.Error("Problem updating provision watcher: " + err.Error())
return
}
if err := dbClient.UpdateProvisionWatcher(to); err != nil {
LoggingClient.Error("Problem updating provision watcher: " + err.Error())
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
// Notify Associates
if err := notifyProvisionWatcherAssociates(to, http.MethodPut); err != nil {
LoggingClient.Error("Problem notifying associated device services for provision watcher: " + err.Error())
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte("true"))
} | go | func restUpdateProvisionWatcher(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var from models.ProvisionWatcher
if err := json.NewDecoder(r.Body).Decode(&from); err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
// Check if the provision watcher exists
// Try by ID
to, err := dbClient.GetProvisionWatcherById(from.Id)
if err != nil {
// Try by name
if to, err = dbClient.GetProvisionWatcherByName(from.Name); err != nil {
if err == db.ErrNotFound {
http.Error(w, "Provision watcher not found", http.StatusNotFound)
LoggingClient.Error("Provision watcher not found: " + err.Error())
} else {
LoggingClient.Error("Problem getting provision watcher: " + err.Error())
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
return
}
}
if err := updateProvisionWatcherFields(from, &to, w); err != nil {
LoggingClient.Error("Problem updating provision watcher: " + err.Error())
return
}
if err := dbClient.UpdateProvisionWatcher(to); err != nil {
LoggingClient.Error("Problem updating provision watcher: " + err.Error())
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
// Notify Associates
if err := notifyProvisionWatcherAssociates(to, http.MethodPut); err != nil {
LoggingClient.Error("Problem notifying associated device services for provision watcher: " + err.Error())
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte("true"))
} | [
"func",
"restUpdateProvisionWatcher",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"defer",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"var",
"from",
"models",
".",
"ProvisionWatcher",
"\n",
"if",
"err",
... | // Update the provision watcher object
// ID is used first for identification, then name
// The service and profile cannot be updated | [
"Update",
"the",
"provision",
"watcher",
"object",
"ID",
"is",
"used",
"first",
"for",
"identification",
"then",
"name",
"The",
"service",
"and",
"profile",
"cannot",
"be",
"updated"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_provisionwatcher.go#L385-L429 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_provisionwatcher.go | updateProvisionWatcherFields | func updateProvisionWatcherFields(from models.ProvisionWatcher, to *models.ProvisionWatcher, w http.ResponseWriter) error {
if from.Identifiers != nil {
to.Identifiers = from.Identifiers
}
if from.Origin != 0 {
to.Origin = from.Origin
}
if from.Name != "" {
// Check that the name is unique
checkPW, err := dbClient.GetProvisionWatcherByName(from.Name)
if err != nil {
if err != db.ErrNotFound {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
}
// Found one, compare the IDs to see if its another provision watcher
if err != db.ErrNotFound {
if checkPW.Id != to.Id {
err = errors.New("Duplicate name for the provision watcher")
http.Error(w, err.Error(), http.StatusConflict)
return err
}
}
to.Name = from.Name
}
return nil
} | go | func updateProvisionWatcherFields(from models.ProvisionWatcher, to *models.ProvisionWatcher, w http.ResponseWriter) error {
if from.Identifiers != nil {
to.Identifiers = from.Identifiers
}
if from.Origin != 0 {
to.Origin = from.Origin
}
if from.Name != "" {
// Check that the name is unique
checkPW, err := dbClient.GetProvisionWatcherByName(from.Name)
if err != nil {
if err != db.ErrNotFound {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
}
// Found one, compare the IDs to see if its another provision watcher
if err != db.ErrNotFound {
if checkPW.Id != to.Id {
err = errors.New("Duplicate name for the provision watcher")
http.Error(w, err.Error(), http.StatusConflict)
return err
}
}
to.Name = from.Name
}
return nil
} | [
"func",
"updateProvisionWatcherFields",
"(",
"from",
"models",
".",
"ProvisionWatcher",
",",
"to",
"*",
"models",
".",
"ProvisionWatcher",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"if",
"from",
".",
"Identifiers",
"!=",
"nil",
"{",
"to",
"... | // Update the relevant fields of the provision watcher | [
"Update",
"the",
"relevant",
"fields",
"of",
"the",
"provision",
"watcher"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_provisionwatcher.go#L432-L460 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_provisionwatcher.go | notifyProvisionWatcherAssociates | func notifyProvisionWatcherAssociates(pw models.ProvisionWatcher, action string) error {
// Get the device service for the provision watcher
ds, err := dbClient.GetDeviceServiceById(pw.Service.Id)
if err != nil {
return err
}
// Notify the service
if err = notifyAssociates([]models.DeviceService{ds}, pw.Id, action, models.PROVISIONWATCHER); err != nil {
return err
}
return nil
} | go | func notifyProvisionWatcherAssociates(pw models.ProvisionWatcher, action string) error {
// Get the device service for the provision watcher
ds, err := dbClient.GetDeviceServiceById(pw.Service.Id)
if err != nil {
return err
}
// Notify the service
if err = notifyAssociates([]models.DeviceService{ds}, pw.Id, action, models.PROVISIONWATCHER); err != nil {
return err
}
return nil
} | [
"func",
"notifyProvisionWatcherAssociates",
"(",
"pw",
"models",
".",
"ProvisionWatcher",
",",
"action",
"string",
")",
"error",
"{",
"ds",
",",
"err",
":=",
"dbClient",
".",
"GetDeviceServiceById",
"(",
"pw",
".",
"Service",
".",
"Id",
")",
"\n",
"if",
"err... | // Notify the associated device services for the provision watcher | [
"Notify",
"the",
"associated",
"device",
"services",
"for",
"the",
"provision",
"watcher"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_provisionwatcher.go#L463-L476 | train |
edgexfoundry/edgex-go | internal/core/data/device.go | updateDeviceLastReportedConnected | func updateDeviceLastReportedConnected(device string) {
// Config set to skip update last reported
if !Configuration.Writable.DeviceUpdateLastConnected {
LoggingClient.Debug("Skipping update of device connected/reported times for: " + device)
return
}
d, err := mdc.CheckForDevice(device, context.Background())
if err != nil {
LoggingClient.Error("Error getting device " + device + ": " + err.Error())
return
}
// Couldn't find device
if len(d.Name) == 0 {
LoggingClient.Error("Error updating device connected/reported times. Unknown device with identifier of: " + device)
return
}
t := db.MakeTimestamp()
// Found device, now update lastReported
//Use of context.Background because this function is invoked asynchronously from a channel
err = mdc.UpdateLastConnectedByName(d.Name, t, context.Background())
if err != nil {
LoggingClient.Error("Problems updating last connected value for device: " + d.Name)
return
}
err = mdc.UpdateLastReportedByName(d.Name, t, context.Background())
if err != nil {
LoggingClient.Error("Problems updating last reported value for device: " + d.Name)
}
return
} | go | func updateDeviceLastReportedConnected(device string) {
// Config set to skip update last reported
if !Configuration.Writable.DeviceUpdateLastConnected {
LoggingClient.Debug("Skipping update of device connected/reported times for: " + device)
return
}
d, err := mdc.CheckForDevice(device, context.Background())
if err != nil {
LoggingClient.Error("Error getting device " + device + ": " + err.Error())
return
}
// Couldn't find device
if len(d.Name) == 0 {
LoggingClient.Error("Error updating device connected/reported times. Unknown device with identifier of: " + device)
return
}
t := db.MakeTimestamp()
// Found device, now update lastReported
//Use of context.Background because this function is invoked asynchronously from a channel
err = mdc.UpdateLastConnectedByName(d.Name, t, context.Background())
if err != nil {
LoggingClient.Error("Problems updating last connected value for device: " + d.Name)
return
}
err = mdc.UpdateLastReportedByName(d.Name, t, context.Background())
if err != nil {
LoggingClient.Error("Problems updating last reported value for device: " + d.Name)
}
return
} | [
"func",
"updateDeviceLastReportedConnected",
"(",
"device",
"string",
")",
"{",
"if",
"!",
"Configuration",
".",
"Writable",
".",
"DeviceUpdateLastConnected",
"{",
"LoggingClient",
".",
"Debug",
"(",
"\"Skipping update of device connected/reported times for: \"",
"+",
"dev... | // Update when the device was last reported connected | [
"Update",
"when",
"the",
"device",
"was",
"last",
"reported",
"connected"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/data/device.go#L23-L55 | train |
edgexfoundry/edgex-go | internal/core/data/device.go | updateDeviceServiceLastReportedConnected | func updateDeviceServiceLastReportedConnected(device string) {
if !Configuration.Writable.ServiceUpdateLastConnected {
LoggingClient.Debug("Skipping update of device service connected/reported times for: " + device)
return
}
t := db.MakeTimestamp()
// Get the device
d, err := mdc.CheckForDevice(device, context.Background())
if err != nil {
LoggingClient.Error("Error getting device " + device + ": " + err.Error())
return
}
// Couldn't find device
if len(d.Name) == 0 {
LoggingClient.Error("Error updating device connected/reported times. Unknown device with identifier of: " + device)
return
}
// Get the device service
s := d.Service
if &s == nil {
LoggingClient.Error("Error updating device service connected/reported times. Unknown device service in device: " + d.Name)
return
}
//Use of context.Background because this function is invoked asynchronously from a channel
msc.UpdateLastConnected(s.Id, t, context.Background())
msc.UpdateLastReported(s.Id, t, context.Background())
} | go | func updateDeviceServiceLastReportedConnected(device string) {
if !Configuration.Writable.ServiceUpdateLastConnected {
LoggingClient.Debug("Skipping update of device service connected/reported times for: " + device)
return
}
t := db.MakeTimestamp()
// Get the device
d, err := mdc.CheckForDevice(device, context.Background())
if err != nil {
LoggingClient.Error("Error getting device " + device + ": " + err.Error())
return
}
// Couldn't find device
if len(d.Name) == 0 {
LoggingClient.Error("Error updating device connected/reported times. Unknown device with identifier of: " + device)
return
}
// Get the device service
s := d.Service
if &s == nil {
LoggingClient.Error("Error updating device service connected/reported times. Unknown device service in device: " + d.Name)
return
}
//Use of context.Background because this function is invoked asynchronously from a channel
msc.UpdateLastConnected(s.Id, t, context.Background())
msc.UpdateLastReported(s.Id, t, context.Background())
} | [
"func",
"updateDeviceServiceLastReportedConnected",
"(",
"device",
"string",
")",
"{",
"if",
"!",
"Configuration",
".",
"Writable",
".",
"ServiceUpdateLastConnected",
"{",
"LoggingClient",
".",
"Debug",
"(",
"\"Skipping update of device service connected/reported times for: \"... | // Update when the device service was last reported connected | [
"Update",
"when",
"the",
"device",
"service",
"was",
"last",
"reported",
"connected"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/data/device.go#L58-L89 | train |
edgexfoundry/edgex-go | internal/pkg/db/redis/queries.go | getObjectsByRangeFilter | func getObjectsByRangeFilter(conn redis.Conn, key string, filter string, start, end int) (objects [][]byte, err error) {
ids, err := redis.Values(conn.Do("ZRANGE", key, start, end))
if err != nil && err != redis.ErrNil {
return nil, err
}
// https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating
fids := ids[:0]
if len(ids) > 0 {
for _, id := range ids {
err := conn.Send("ZSCORE", filter, id)
if err != nil {
return nil, err
}
}
scores, err := redis.Strings(conn.Do(""))
if err != nil {
return nil, err
}
for i, score := range scores {
if score != "" {
fids = append(fids, ids[i])
}
}
objects, err = redis.ByteSlices(conn.Do("MGET", fids...))
if err != nil {
return nil, err
}
}
return objects, nil
} | go | func getObjectsByRangeFilter(conn redis.Conn, key string, filter string, start, end int) (objects [][]byte, err error) {
ids, err := redis.Values(conn.Do("ZRANGE", key, start, end))
if err != nil && err != redis.ErrNil {
return nil, err
}
// https://github.com/golang/go/wiki/SliceTricks#filtering-without-allocating
fids := ids[:0]
if len(ids) > 0 {
for _, id := range ids {
err := conn.Send("ZSCORE", filter, id)
if err != nil {
return nil, err
}
}
scores, err := redis.Strings(conn.Do(""))
if err != nil {
return nil, err
}
for i, score := range scores {
if score != "" {
fids = append(fids, ids[i])
}
}
objects, err = redis.ByteSlices(conn.Do("MGET", fids...))
if err != nil {
return nil, err
}
}
return objects, nil
} | [
"func",
"getObjectsByRangeFilter",
"(",
"conn",
"redis",
".",
"Conn",
",",
"key",
"string",
",",
"filter",
"string",
",",
"start",
",",
"end",
"int",
")",
"(",
"objects",
"[",
"]",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"ids",
",",
"err",
... | // Return objects by a score from a zset
// if limit is 0, all are returned
// if end is negative, it is considered as positive infinity | [
"Return",
"objects",
"by",
"a",
"score",
"from",
"a",
"zset",
"if",
"limit",
"is",
"0",
"all",
"are",
"returned",
"if",
"end",
"is",
"negative",
"it",
"is",
"considered",
"as",
"positive",
"infinity"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/queries.go#L132-L164 | train |
edgexfoundry/edgex-go | internal/pkg/db/redis/queries.go | addObject | func addObject(data []byte, adder models.Adder, id string, conn redis.Conn) {
_ = conn.Send("SET", id, data)
for _, cmd := range adder.Add() {
switch cmd.Command {
case "ZADD":
_ = conn.Send(cmd.Command, cmd.Hash, cmd.Rank, cmd.Key)
case "SADD":
_ = conn.Send(cmd.Command, cmd.Hash, cmd.Key)
case "HSET":
_ = conn.Send(cmd.Command, cmd.Hash, cmd.Key, cmd.Value)
}
}
} | go | func addObject(data []byte, adder models.Adder, id string, conn redis.Conn) {
_ = conn.Send("SET", id, data)
for _, cmd := range adder.Add() {
switch cmd.Command {
case "ZADD":
_ = conn.Send(cmd.Command, cmd.Hash, cmd.Rank, cmd.Key)
case "SADD":
_ = conn.Send(cmd.Command, cmd.Hash, cmd.Key)
case "HSET":
_ = conn.Send(cmd.Command, cmd.Hash, cmd.Key, cmd.Value)
}
}
} | [
"func",
"addObject",
"(",
"data",
"[",
"]",
"byte",
",",
"adder",
"models",
".",
"Adder",
",",
"id",
"string",
",",
"conn",
"redis",
".",
"Conn",
")",
"{",
"_",
"=",
"conn",
".",
"Send",
"(",
"\"SET\"",
",",
"id",
",",
"data",
")",
"\n",
"for",
... | // addObject is responsible for setting the object's primary record and then sending the appropriate
// follow-on commands as provided by the caller.
// Transactions are managed outside of this function. | [
"addObject",
"is",
"responsible",
"for",
"setting",
"the",
"object",
"s",
"primary",
"record",
"and",
"then",
"sending",
"the",
"appropriate",
"follow",
"-",
"on",
"commands",
"as",
"provided",
"by",
"the",
"caller",
".",
"Transactions",
"are",
"managed",
"out... | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/queries.go#L196-L209 | train |
edgexfoundry/edgex-go | internal/pkg/db/redis/queries.go | deleteObject | func deleteObject(remover models.Remover, id string, conn redis.Conn) {
_ = conn.Send("DEL", id)
for _, cmd := range remover.Remove() {
switch cmd.Command {
case "ZREM":
case "SREM":
case "HDEL":
_ = conn.Send(cmd.Command, cmd.Hash, cmd.Key)
}
}
} | go | func deleteObject(remover models.Remover, id string, conn redis.Conn) {
_ = conn.Send("DEL", id)
for _, cmd := range remover.Remove() {
switch cmd.Command {
case "ZREM":
case "SREM":
case "HDEL":
_ = conn.Send(cmd.Command, cmd.Hash, cmd.Key)
}
}
} | [
"func",
"deleteObject",
"(",
"remover",
"models",
".",
"Remover",
",",
"id",
"string",
",",
"conn",
"redis",
".",
"Conn",
")",
"{",
"_",
"=",
"conn",
".",
"Send",
"(",
"\"DEL\"",
",",
"id",
")",
"\n",
"for",
"_",
",",
"cmd",
":=",
"range",
"remover... | // deleteObject is responsible for removing the object's primary record and then sending the appropriate
// follow-on commands as provided by the caller.
//
// Transactions are managed outside of this function. | [
"deleteObject",
"is",
"responsible",
"for",
"removing",
"the",
"object",
"s",
"primary",
"record",
"and",
"then",
"sending",
"the",
"appropriate",
"follow",
"-",
"on",
"commands",
"as",
"provided",
"by",
"the",
"caller",
".",
"Transactions",
"are",
"managed",
... | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/queries.go#L215-L226 | train |
edgexfoundry/edgex-go | internal/core/command/get.go | NewGetCommand | func NewGetCommand(device contract.Device, command contract.Command, context context.Context, httpCaller internal.HttpCaller) (Executor, error) {
url := device.Service.Addressable.GetBaseURL() + strings.Replace(command.Get.Action.Path, DEVICEIDURLPARAM, device.Id, -1)
request, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return serviceCommand{}, err
}
correlationID := context.Value(clients.CorrelationHeader)
if correlationID != nil {
request.Header.Set(clients.CorrelationHeader, correlationID.(string))
}
return serviceCommand{
Device: device,
HttpCaller: httpCaller,
Request: request,
}, nil
} | go | func NewGetCommand(device contract.Device, command contract.Command, context context.Context, httpCaller internal.HttpCaller) (Executor, error) {
url := device.Service.Addressable.GetBaseURL() + strings.Replace(command.Get.Action.Path, DEVICEIDURLPARAM, device.Id, -1)
request, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return serviceCommand{}, err
}
correlationID := context.Value(clients.CorrelationHeader)
if correlationID != nil {
request.Header.Set(clients.CorrelationHeader, correlationID.(string))
}
return serviceCommand{
Device: device,
HttpCaller: httpCaller,
Request: request,
}, nil
} | [
"func",
"NewGetCommand",
"(",
"device",
"contract",
".",
"Device",
",",
"command",
"contract",
".",
"Command",
",",
"context",
"context",
".",
"Context",
",",
"httpCaller",
"internal",
".",
"HttpCaller",
")",
"(",
"Executor",
",",
"error",
")",
"{",
"url",
... | // NewGetCommand creates and Executor which can be used to execute the GET related command. | [
"NewGetCommand",
"creates",
"and",
"Executor",
"which",
"can",
"be",
"used",
"to",
"execute",
"the",
"GET",
"related",
"command",
"."
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/command/get.go#L26-L43 | train |
edgexfoundry/edgex-go | internal/export/distro/httpsender.go | newHTTPSender | func newHTTPSender(addr contract.Addressable) sender {
sender := httpSender{
url: addr.Protocol + "://" + addr.Address + ":" + strconv.Itoa(addr.Port) + addr.Path,
method: addr.HTTPMethod,
}
return sender
} | go | func newHTTPSender(addr contract.Addressable) sender {
sender := httpSender{
url: addr.Protocol + "://" + addr.Address + ":" + strconv.Itoa(addr.Port) + addr.Path,
method: addr.HTTPMethod,
}
return sender
} | [
"func",
"newHTTPSender",
"(",
"addr",
"contract",
".",
"Addressable",
")",
"sender",
"{",
"sender",
":=",
"httpSender",
"{",
"url",
":",
"addr",
".",
"Protocol",
"+",
"\"://\"",
"+",
"addr",
".",
"Address",
"+",
"\":\"",
"+",
"strconv",
".",
"Itoa",
"(",... | // newHTTPSender - create http sender | [
"newHTTPSender",
"-",
"create",
"http",
"sender"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/export/distro/httpsender.go#L34-L41 | train |
edgexfoundry/edgex-go | internal/export/distro/httpsender.go | Send | func (sender httpSender) Send(data []byte, event *models.Event) bool {
switch sender.method {
case http.MethodPost:
ctx := context.WithValue(context.Background(), clients.CorrelationHeader, event.CorrelationId)
req, err := http.NewRequest(http.MethodPost, sender.url, bytes.NewReader(data))
if err != nil {
return false
}
req.Header.Set("Content-Type", mimeTypeJSON)
c := clients.NewCorrelatedRequest(req, ctx)
client := &http.Client{}
begin := time.Now()
response, err := client.Do(c.Request)
if err != nil {
LoggingClient.Error(err.Error(), clients.CorrelationHeader, event.CorrelationId, internal.LogDurationKey, time.Since(begin).String())
return false
}
defer response.Body.Close()
LoggingClient.Info(fmt.Sprintf("Response: %s", response.Status), clients.CorrelationHeader, event.CorrelationId, internal.LogDurationKey, time.Since(begin).String())
default:
LoggingClient.Info(fmt.Sprintf("Unsupported method: %s", sender.method))
return false
}
LoggingClient.Info(fmt.Sprintf("Sent data: %X", data))
return true
} | go | func (sender httpSender) Send(data []byte, event *models.Event) bool {
switch sender.method {
case http.MethodPost:
ctx := context.WithValue(context.Background(), clients.CorrelationHeader, event.CorrelationId)
req, err := http.NewRequest(http.MethodPost, sender.url, bytes.NewReader(data))
if err != nil {
return false
}
req.Header.Set("Content-Type", mimeTypeJSON)
c := clients.NewCorrelatedRequest(req, ctx)
client := &http.Client{}
begin := time.Now()
response, err := client.Do(c.Request)
if err != nil {
LoggingClient.Error(err.Error(), clients.CorrelationHeader, event.CorrelationId, internal.LogDurationKey, time.Since(begin).String())
return false
}
defer response.Body.Close()
LoggingClient.Info(fmt.Sprintf("Response: %s", response.Status), clients.CorrelationHeader, event.CorrelationId, internal.LogDurationKey, time.Since(begin).String())
default:
LoggingClient.Info(fmt.Sprintf("Unsupported method: %s", sender.method))
return false
}
LoggingClient.Info(fmt.Sprintf("Sent data: %X", data))
return true
} | [
"func",
"(",
"sender",
"httpSender",
")",
"Send",
"(",
"data",
"[",
"]",
"byte",
",",
"event",
"*",
"models",
".",
"Event",
")",
"bool",
"{",
"switch",
"sender",
".",
"method",
"{",
"case",
"http",
".",
"MethodPost",
":",
"ctx",
":=",
"context",
".",... | // Send will send the optionally filtered, compressed, encypted contract.Event via HTTP POST
// The model.Event is provided in order to obtain the necessary correlation-id. | [
"Send",
"will",
"send",
"the",
"optionally",
"filtered",
"compressed",
"encypted",
"contract",
".",
"Event",
"via",
"HTTP",
"POST",
"The",
"model",
".",
"Event",
"is",
"provided",
"in",
"order",
"to",
"obtain",
"the",
"necessary",
"correlation",
"-",
"id",
"... | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/export/distro/httpsender.go#L45-L73 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/client.go | NewClient | func NewClient(config db.Configuration) (MongoClient, error) {
m := MongoClient{}
// Create the dial info for the Mongo session
connectionString := config.Host + ":" + strconv.Itoa(config.Port)
mongoDBDialInfo := &mgo.DialInfo{
Addrs: []string{connectionString},
Timeout: time.Duration(config.Timeout) * time.Millisecond,
Database: config.DatabaseName,
Username: config.Username,
Password: config.Password,
}
session, err := mgo.DialWithInfo(mongoDBDialInfo)
if err != nil {
return m, err
}
m.session = session
m.database = session.DB(config.DatabaseName)
currentMongoClient = m // Set the singleton
return m, nil
} | go | func NewClient(config db.Configuration) (MongoClient, error) {
m := MongoClient{}
// Create the dial info for the Mongo session
connectionString := config.Host + ":" + strconv.Itoa(config.Port)
mongoDBDialInfo := &mgo.DialInfo{
Addrs: []string{connectionString},
Timeout: time.Duration(config.Timeout) * time.Millisecond,
Database: config.DatabaseName,
Username: config.Username,
Password: config.Password,
}
session, err := mgo.DialWithInfo(mongoDBDialInfo)
if err != nil {
return m, err
}
m.session = session
m.database = session.DB(config.DatabaseName)
currentMongoClient = m // Set the singleton
return m, nil
} | [
"func",
"NewClient",
"(",
"config",
"db",
".",
"Configuration",
")",
"(",
"MongoClient",
",",
"error",
")",
"{",
"m",
":=",
"MongoClient",
"{",
"}",
"\n",
"connectionString",
":=",
"config",
".",
"Host",
"+",
"\":\"",
"+",
"strconv",
".",
"Itoa",
"(",
... | // Return a pointer to the MongoClient | [
"Return",
"a",
"pointer",
"to",
"the",
"MongoClient"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/client.go#L32-L54 | train |
edgexfoundry/edgex-go | internal/support/logging/types.go | SetLogLevel | func (l privLogger) SetLogLevel(logLevel string) error {
if logger.IsValidLogLevel(logLevel) == true {
*l.logLevel = logLevel
return nil
}
return types.ErrNotFound{}
} | go | func (l privLogger) SetLogLevel(logLevel string) error {
if logger.IsValidLogLevel(logLevel) == true {
*l.logLevel = logLevel
return nil
}
return types.ErrNotFound{}
} | [
"func",
"(",
"l",
"privLogger",
")",
"SetLogLevel",
"(",
"logLevel",
"string",
")",
"error",
"{",
"if",
"logger",
".",
"IsValidLogLevel",
"(",
"logLevel",
")",
"==",
"true",
"{",
"*",
"l",
".",
"logLevel",
"=",
"logLevel",
"\n",
"return",
"nil",
"\n",
... | // SetLogLevel sets logger log level | [
"SetLogLevel",
"sets",
"logger",
"log",
"level"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/logging/types.go#L105-L111 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/metadata.go | GetDeviceProfilesByCommandId | func (mc MongoClient) GetDeviceProfilesByCommandId(id string) ([]contract.DeviceProfile, error) {
command, err := mc.getCommandById(id)
if err != nil {
return []contract.DeviceProfile{}, err
}
dps, err := mc.getDeviceProfiles(bson.M{"commands.$id": command.Id})
if err != nil {
return []contract.DeviceProfile{}, err
}
return dps, nil
} | go | func (mc MongoClient) GetDeviceProfilesByCommandId(id string) ([]contract.DeviceProfile, error) {
command, err := mc.getCommandById(id)
if err != nil {
return []contract.DeviceProfile{}, err
}
dps, err := mc.getDeviceProfiles(bson.M{"commands.$id": command.Id})
if err != nil {
return []contract.DeviceProfile{}, err
}
return dps, nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"GetDeviceProfilesByCommandId",
"(",
"id",
"string",
")",
"(",
"[",
"]",
"contract",
".",
"DeviceProfile",
",",
"error",
")",
"{",
"command",
",",
"err",
":=",
"mc",
".",
"getCommandById",
"(",
"id",
")",
"\n",
"if"... | // Get the device profiles that are currently using the command | [
"Get",
"the",
"device",
"profiles",
"that",
"are",
"currently",
"using",
"the",
"command"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/metadata.go#L393-L404 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/metadata.go | DeleteCommandById | func (mc MongoClient) DeleteCommandById(id string) error {
s := mc.session.Copy()
defer s.Close()
col := s.DB(mc.database.Name).C(db.Command)
// Check if the command is still in use
findParameters, err := idToBsonM(id)
if err != nil {
return err
}
query := bson.M{"commands": bson.M{"$elemMatch": findParameters}}
count, err := s.DB(mc.database.Name).C(db.DeviceProfile).Find(query).Count()
if err != nil {
return errorMap(err)
}
if count > 0 {
return db.ErrCommandStillInUse
}
// remove the command
n, v, err := idToQueryParameters(id)
if err != nil {
return err
}
return errorMap(col.Remove(bson.D{{Name: n, Value: v}}))
} | go | func (mc MongoClient) DeleteCommandById(id string) error {
s := mc.session.Copy()
defer s.Close()
col := s.DB(mc.database.Name).C(db.Command)
// Check if the command is still in use
findParameters, err := idToBsonM(id)
if err != nil {
return err
}
query := bson.M{"commands": bson.M{"$elemMatch": findParameters}}
count, err := s.DB(mc.database.Name).C(db.DeviceProfile).Find(query).Count()
if err != nil {
return errorMap(err)
}
if count > 0 {
return db.ErrCommandStillInUse
}
// remove the command
n, v, err := idToQueryParameters(id)
if err != nil {
return err
}
return errorMap(col.Remove(bson.D{{Name: n, Value: v}}))
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"DeleteCommandById",
"(",
"id",
"string",
")",
"error",
"{",
"s",
":=",
"mc",
".",
"session",
".",
"Copy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
"(",
")",
"\n",
"col",
":=",
"s",
".",
"DB",
"(",
"mc",
... | // Delete the command by ID
// Check if the command is still in use by device profiles | [
"Delete",
"the",
"command",
"by",
"ID",
"Check",
"if",
"the",
"command",
"is",
"still",
"in",
"use",
"by",
"device",
"profiles"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/metadata.go#L999-L1024 | train |
edgexfoundry/edgex-go | internal/pkg/db/mongo/metadata.go | ScrubMetadata | func (mc MongoClient) ScrubMetadata() error {
s := mc.session.Copy()
defer s.Close()
_, err := s.DB(mc.database.Name).C(db.Addressable).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
_, err = s.DB(mc.database.Name).C(db.DeviceService).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
_, err = s.DB(mc.database.Name).C(db.DeviceProfile).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
_, err = s.DB(mc.database.Name).C(db.DeviceReport).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
_, err = s.DB(mc.database.Name).C(db.Device).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
_, err = s.DB(mc.database.Name).C(db.ProvisionWatcher).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
return nil
} | go | func (mc MongoClient) ScrubMetadata() error {
s := mc.session.Copy()
defer s.Close()
_, err := s.DB(mc.database.Name).C(db.Addressable).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
_, err = s.DB(mc.database.Name).C(db.DeviceService).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
_, err = s.DB(mc.database.Name).C(db.DeviceProfile).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
_, err = s.DB(mc.database.Name).C(db.DeviceReport).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
_, err = s.DB(mc.database.Name).C(db.Device).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
_, err = s.DB(mc.database.Name).C(db.ProvisionWatcher).RemoveAll(nil)
if err != nil {
return errorMap(err)
}
return nil
} | [
"func",
"(",
"mc",
"MongoClient",
")",
"ScrubMetadata",
"(",
")",
"error",
"{",
"s",
":=",
"mc",
".",
"session",
".",
"Copy",
"(",
")",
"\n",
"defer",
"s",
".",
"Close",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"s",
".",
"DB",
"(",
"mc",
".",
"... | // Scrub all metadata | [
"Scrub",
"all",
"metadata"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/mongo/metadata.go#L1042-L1072 | train |
edgexfoundry/edgex-go | internal/pkg/db/redis/notifications.go | GetNotifications | func (c Client) GetNotifications() (n []contract.Notification, err error) {
conn := c.Pool.Get()
defer conn.Close()
objects, err := getObjectsByRange(conn, db.Notification, 0, -1)
if err != nil {
return nil, err
}
n, err = unmarshalNotifications(objects)
if err != nil {
return n, err
}
return n, nil
} | go | func (c Client) GetNotifications() (n []contract.Notification, err error) {
conn := c.Pool.Get()
defer conn.Close()
objects, err := getObjectsByRange(conn, db.Notification, 0, -1)
if err != nil {
return nil, err
}
n, err = unmarshalNotifications(objects)
if err != nil {
return n, err
}
return n, nil
} | [
"func",
"(",
"c",
"Client",
")",
"GetNotifications",
"(",
")",
"(",
"n",
"[",
"]",
"contract",
".",
"Notification",
",",
"err",
"error",
")",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")"... | // Get all notifications | [
"Get",
"all",
"notifications"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/notifications.go#L51-L66 | train |
edgexfoundry/edgex-go | internal/pkg/db/redis/notifications.go | DeleteNotificationsOld | func (c Client) DeleteNotificationsOld(age int) error {
conn := c.Pool.Get()
defer conn.Close()
currentTime := db.MakeTimestamp()
end := int64(int(currentTime) - age)
objects, err := getObjectsByScore(conn, db.Notification+":modified", 0, end, 0)
for _, object := range objects {
if len(object) > 0 {
var n contract.Notification
err := unmarshalObject(object, &n)
if err != nil {
return err
}
// Delete processed notification
if n.Status != contract.Processed {
continue
}
err = deleteNotification(conn, n.ID)
if err != nil {
return err
}
}
}
return err
} | go | func (c Client) DeleteNotificationsOld(age int) error {
conn := c.Pool.Get()
defer conn.Close()
currentTime := db.MakeTimestamp()
end := int64(int(currentTime) - age)
objects, err := getObjectsByScore(conn, db.Notification+":modified", 0, end, 0)
for _, object := range objects {
if len(object) > 0 {
var n contract.Notification
err := unmarshalObject(object, &n)
if err != nil {
return err
}
// Delete processed notification
if n.Status != contract.Processed {
continue
}
err = deleteNotification(conn, n.ID)
if err != nil {
return err
}
}
}
return err
} | [
"func",
"(",
"c",
"Client",
")",
"DeleteNotificationsOld",
"(",
"age",
"int",
")",
"error",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"currentTime",
":=",
"db",
".",
"MakeTimestamp... | // DeleteNotificationsOld remove all the notifications that are older than the given age | [
"DeleteNotificationsOld",
"remove",
"all",
"the",
"notifications",
"that",
"are",
"older",
"than",
"the",
"given",
"age"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/notifications.go#L265-L292 | train |
edgexfoundry/edgex-go | internal/pkg/db/redis/notifications.go | DeleteTransmission | func (c Client) DeleteTransmission(age int64, status contract.TransmissionStatus) error {
conn := c.Pool.Get()
defer conn.Close()
currentTime := db.MakeTimestamp()
end := currentTime - age
objects, err := getObjectsByRangeFilter(conn, db.Transmission+":modified", db.Transmission+":status:"+fmt.Sprintf("%s", status), 0, int(end))
if err != nil {
return err
}
transmissions, err := unmarshalTransmissions(objects)
if err != nil {
return err
}
for _, transmission := range transmissions {
err = deleteTransmission(conn, transmission.ID)
if err != nil {
return err
}
}
return err
} | go | func (c Client) DeleteTransmission(age int64, status contract.TransmissionStatus) error {
conn := c.Pool.Get()
defer conn.Close()
currentTime := db.MakeTimestamp()
end := currentTime - age
objects, err := getObjectsByRangeFilter(conn, db.Transmission+":modified", db.Transmission+":status:"+fmt.Sprintf("%s", status), 0, int(end))
if err != nil {
return err
}
transmissions, err := unmarshalTransmissions(objects)
if err != nil {
return err
}
for _, transmission := range transmissions {
err = deleteTransmission(conn, transmission.ID)
if err != nil {
return err
}
}
return err
} | [
"func",
"(",
"c",
"Client",
")",
"DeleteTransmission",
"(",
"age",
"int64",
",",
"status",
"contract",
".",
"TransmissionStatus",
")",
"error",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
... | // DeleteTransmission delete old transmission with specified status | [
"DeleteTransmission",
"delete",
"old",
"transmission",
"with",
"specified",
"status"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/notifications.go#L572-L595 | train |
edgexfoundry/edgex-go | internal/pkg/db/redis/notifications.go | Cleanup | func (c Client) Cleanup() error {
//conn := c.Pool.Get()
//defer conn.Close()
//
//cols := []string{
// db.Transmission, db.Notification,
//}
//
//for _, col := range cols {
// err := unlinkCollection(conn, col)
// if err != nil {
// return err
// }
//}
err := c.CleanupOld(0)
if err != nil {
return err
}
return nil
} | go | func (c Client) Cleanup() error {
//conn := c.Pool.Get()
//defer conn.Close()
//
//cols := []string{
// db.Transmission, db.Notification,
//}
//
//for _, col := range cols {
// err := unlinkCollection(conn, col)
// if err != nil {
// return err
// }
//}
err := c.CleanupOld(0)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"c",
"Client",
")",
"Cleanup",
"(",
")",
"error",
"{",
"err",
":=",
"c",
".",
"CleanupOld",
"(",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Cleanup delete all notifications and associated transmissions | [
"Cleanup",
"delete",
"all",
"notifications",
"and",
"associated",
"transmissions"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/notifications.go#L598-L617 | train |
edgexfoundry/edgex-go | internal/pkg/db/redis/notifications.go | CleanupOld | func (c Client) CleanupOld(age int) error {
conn := c.Pool.Get()
defer conn.Close()
currentTime := db.MakeTimestamp()
end := currentTime - int64(age)
objects, err := getObjectsByScore(conn, db.Notification+":created", 0, end, -1)
if err != nil {
return err
}
notifications, err := unmarshalNotifications(objects)
if err != nil {
return err
}
for _, notification := range notifications {
err = c.DeleteNotificationById(notification.ID)
if err != nil {
return err
}
transmissions, err := c.GetTransmissionsByNotificationSlug(notification.Slug, -1)
if err != nil {
return err
}
for _, transmission := range transmissions {
err = deleteTransmission(conn, transmission.ID)
if err != nil {
return err
}
}
}
return nil
} | go | func (c Client) CleanupOld(age int) error {
conn := c.Pool.Get()
defer conn.Close()
currentTime := db.MakeTimestamp()
end := currentTime - int64(age)
objects, err := getObjectsByScore(conn, db.Notification+":created", 0, end, -1)
if err != nil {
return err
}
notifications, err := unmarshalNotifications(objects)
if err != nil {
return err
}
for _, notification := range notifications {
err = c.DeleteNotificationById(notification.ID)
if err != nil {
return err
}
transmissions, err := c.GetTransmissionsByNotificationSlug(notification.Slug, -1)
if err != nil {
return err
}
for _, transmission := range transmissions {
err = deleteTransmission(conn, transmission.ID)
if err != nil {
return err
}
}
}
return nil
} | [
"func",
"(",
"c",
"Client",
")",
"CleanupOld",
"(",
"age",
"int",
")",
"error",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"currentTime",
":=",
"db",
".",
"MakeTimestamp",
"(",
... | // Cleanup delete old notifications and associated transmissions | [
"Cleanup",
"delete",
"old",
"notifications",
"and",
"associated",
"transmissions"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/notifications.go#L620-L654 | train |
edgexfoundry/edgex-go | internal/seed/config/populate.go | ImportProperties | func ImportProperties(root string) error {
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Skip directories & unacceptable property extension
if info.IsDir() || !isAcceptablePropertyExtensions(info.Name()) {
return nil
}
dir, file := filepath.Split(path)
appKey := parseDirectoryName(dir)
LoggingClient.Debug(fmt.Sprintf("dir: %s file: %s", appKey, file))
props, err := readPropertiesFile(path)
if err != nil {
return err
}
registryConfig := types.Config{
Host: Configuration.Registry.Host,
Port: Configuration.Registry.Port,
Type: Configuration.Registry.Type,
Stem: Configuration.GlobalPrefix + "/",
ServiceKey: appKey,
}
Registry, err = registry.NewRegistryClient(registryConfig)
for key := range props {
if err := Registry.PutConfigurationValue(key, []byte(props[key])); err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
return nil
} | go | func ImportProperties(root string) error {
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Skip directories & unacceptable property extension
if info.IsDir() || !isAcceptablePropertyExtensions(info.Name()) {
return nil
}
dir, file := filepath.Split(path)
appKey := parseDirectoryName(dir)
LoggingClient.Debug(fmt.Sprintf("dir: %s file: %s", appKey, file))
props, err := readPropertiesFile(path)
if err != nil {
return err
}
registryConfig := types.Config{
Host: Configuration.Registry.Host,
Port: Configuration.Registry.Port,
Type: Configuration.Registry.Type,
Stem: Configuration.GlobalPrefix + "/",
ServiceKey: appKey,
}
Registry, err = registry.NewRegistryClient(registryConfig)
for key := range props {
if err := Registry.PutConfigurationValue(key, []byte(props[key])); err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
return nil
} | [
"func",
"ImportProperties",
"(",
"root",
"string",
")",
"error",
"{",
"err",
":=",
"filepath",
".",
"Walk",
"(",
"root",
",",
"func",
"(",
"path",
"string",
",",
"info",
"os",
".",
"FileInfo",
",",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"!="... | // Import properties files for support of legacy Java services. | [
"Import",
"properties",
"files",
"for",
"support",
"of",
"legacy",
"Java",
"services",
"."
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/seed/config/populate.go#L34-L74 | train |
edgexfoundry/edgex-go | internal/seed/config/populate.go | listDirectories | func listDirectories() [9]string {
var names = [9]string{internal.CoreMetaDataServiceKey, internal.CoreCommandServiceKey, internal.CoreDataServiceKey,
internal.ExportDistroServiceKey, internal.ExportClientServiceKey, internal.SupportLoggingServiceKey,
internal.SupportSchedulerServiceKey, internal.SupportNotificationsServiceKey, internal.SystemManagementAgentServiceKey}
for i, name := range names {
names[i] = strings.Replace(name, internal.ServiceKeyPrefix, "", 1)
}
return names
} | go | func listDirectories() [9]string {
var names = [9]string{internal.CoreMetaDataServiceKey, internal.CoreCommandServiceKey, internal.CoreDataServiceKey,
internal.ExportDistroServiceKey, internal.ExportClientServiceKey, internal.SupportLoggingServiceKey,
internal.SupportSchedulerServiceKey, internal.SupportNotificationsServiceKey, internal.SystemManagementAgentServiceKey}
for i, name := range names {
names[i] = strings.Replace(name, internal.ServiceKeyPrefix, "", 1)
}
return names
} | [
"func",
"listDirectories",
"(",
")",
"[",
"9",
"]",
"string",
"{",
"var",
"names",
"=",
"[",
"9",
"]",
"string",
"{",
"internal",
".",
"CoreMetaDataServiceKey",
",",
"internal",
".",
"CoreCommandServiceKey",
",",
"internal",
".",
"CoreDataServiceKey",
",",
"... | // As services are converted to utilize V2 types, add them to this list and remove from the one above. | [
"As",
"services",
"are",
"converted",
"to",
"utilize",
"V2",
"types",
"add",
"them",
"to",
"this",
"list",
"and",
"remove",
"from",
"the",
"one",
"above",
"."
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/seed/config/populate.go#L134-L144 | train |
edgexfoundry/edgex-go | internal/seed/config/populate.go | readPropertiesFile | func readPropertiesFile(filePath string) (map[string]string, error) {
props, err := properties.LoadFile(filePath, properties.UTF8)
if err != nil {
return nil, err
}
return props.Map(), nil
} | go | func readPropertiesFile(filePath string) (map[string]string, error) {
props, err := properties.LoadFile(filePath, properties.UTF8)
if err != nil {
return nil, err
}
return props.Map(), nil
} | [
"func",
"readPropertiesFile",
"(",
"filePath",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"props",
",",
"err",
":=",
"properties",
".",
"LoadFile",
"(",
"filePath",
",",
"properties",
".",
"UTF8",
")",
"\n",
"if",
... | // Parse a properties file to a map. | [
"Parse",
"a",
"properties",
"file",
"to",
"a",
"map",
"."
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/seed/config/populate.go#L189-L196 | train |
edgexfoundry/edgex-go | internal/seed/config/populate.go | traverse | func traverse(path string, j interface{}) ([]*pair, error) {
kvs := make([]*pair, 0)
pathPre := ""
if path != "" {
pathPre = path + "/"
}
switch j.(type) {
case []interface{}:
for sk, sv := range j.([]interface{}) {
skvs, err := traverse(pathPre+strconv.Itoa(sk), sv)
if err != nil {
return nil, err
}
kvs = append(kvs, skvs...)
}
case map[string]interface{}:
for sk, sv := range j.(map[string]interface{}) {
skvs, err := traverse(pathPre+sk, sv)
if err != nil {
return nil, err
}
kvs = append(kvs, skvs...)
}
case int:
kvs = append(kvs, &pair{Key: path, Value: strconv.Itoa(j.(int))})
case int64:
var y int = int(j.(int64))
kvs = append(kvs, &pair{Key: path, Value: strconv.Itoa(y)})
case float64:
kvs = append(kvs, &pair{Key: path, Value: strconv.FormatFloat(j.(float64), 'f', -1, 64)})
case bool:
kvs = append(kvs, &pair{Key: path, Value: strconv.FormatBool(j.(bool))})
case nil:
kvs = append(kvs, &pair{Key: path, Value: ""})
default:
kvs = append(kvs, &pair{Key: path, Value: j.(string)})
}
return kvs, nil
} | go | func traverse(path string, j interface{}) ([]*pair, error) {
kvs := make([]*pair, 0)
pathPre := ""
if path != "" {
pathPre = path + "/"
}
switch j.(type) {
case []interface{}:
for sk, sv := range j.([]interface{}) {
skvs, err := traverse(pathPre+strconv.Itoa(sk), sv)
if err != nil {
return nil, err
}
kvs = append(kvs, skvs...)
}
case map[string]interface{}:
for sk, sv := range j.(map[string]interface{}) {
skvs, err := traverse(pathPre+sk, sv)
if err != nil {
return nil, err
}
kvs = append(kvs, skvs...)
}
case int:
kvs = append(kvs, &pair{Key: path, Value: strconv.Itoa(j.(int))})
case int64:
var y int = int(j.(int64))
kvs = append(kvs, &pair{Key: path, Value: strconv.Itoa(y)})
case float64:
kvs = append(kvs, &pair{Key: path, Value: strconv.FormatFloat(j.(float64), 'f', -1, 64)})
case bool:
kvs = append(kvs, &pair{Key: path, Value: strconv.FormatBool(j.(bool))})
case nil:
kvs = append(kvs, &pair{Key: path, Value: ""})
default:
kvs = append(kvs, &pair{Key: path, Value: j.(string)})
}
return kvs, nil
} | [
"func",
"traverse",
"(",
"path",
"string",
",",
"j",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"*",
"pair",
",",
"error",
")",
"{",
"kvs",
":=",
"make",
"(",
"[",
"]",
"*",
"pair",
",",
"0",
")",
"\n",
"pathPre",
":=",
"\"\"",
"\n",
"if",
"p... | // Traverse or walk hierarchical configuration in preparation for loading into Registry | [
"Traverse",
"or",
"walk",
"hierarchical",
"configuration",
"in",
"preparation",
"for",
"loading",
"into",
"Registry"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/seed/config/populate.go#L229-L272 | train |
edgexfoundry/edgex-go | internal/export/distro/registrations.go | Loop | func Loop() {
go func() {
p := fmt.Sprintf(":%d", Configuration.Service.Port)
LoggingClient.Info(fmt.Sprintf("Starting Export Distro %s", p))
messageErrors <- http.ListenAndServe(p, httpServer())
}()
registrations := make(map[string]*registrationInfo)
allRegs, err := getRegistrations()
for allRegs == nil {
LoggingClient.Info("Waiting for client microservice")
select {
case e := <-messageErrors:
LoggingClient.Error(fmt.Sprintf("exit msg: %s", e.Error()))
if err != nil {
LoggingClient.Error(fmt.Sprintf("with error: %s", err.Error()))
}
return
case <-time.After(time.Second):
}
allRegs, err = getRegistrations()
}
// Create new goroutines for each registration
for _, reg := range allRegs {
regInfo := newRegistrationInfo()
if regInfo.update(reg) {
registrations[reg.Name] = regInfo
go registrationLoop(regInfo)
}
}
LoggingClient.Info("Starting registration loop")
for {
select {
case e := <-messageErrors:
// kill all registration goroutines
for k, reg := range registrations {
if !reg.deleteFlag {
// Do not write in channel that will not be read
reg.chRegistration <- nil
}
delete(registrations, k)
}
LoggingClient.Error(fmt.Sprintf("exit msg: %s", e.Error()))
return
case update := <-registrationChanges:
LoggingClient.Info("Registration changes")
err := updateRunningRegistrations(registrations, update)
if err != nil {
LoggingClient.Error(err.Error())
LoggingClient.Warn(fmt.Sprintf("Error updating registration %s", update.Name))
}
case msgEnvelope := <-messageEnvelopes:
LoggingClient.Info(fmt.Sprintf("Event received on message queue. Topic: %s, Correlation-id: %s ", Configuration.MessageQueue.Topic, msgEnvelope.CorrelationID))
if msgEnvelope.ContentType != clients.ContentTypeJSON {
LoggingClient.Error(fmt.Sprintf("Incorrect content type for event message. Received: %s, Expected: %s", msgEnvelope.ContentType, clients.ContentTypeJSON))
continue
}
str := string(msgEnvelope.Payload)
event := parseEvent(str)
if event == nil {
continue
}
for k, reg := range registrations {
if reg.deleteFlag {
delete(registrations, k)
} else {
// TODO only sent event if it is not blocking
reg.chEvent <- event
}
}
}
}
} | go | func Loop() {
go func() {
p := fmt.Sprintf(":%d", Configuration.Service.Port)
LoggingClient.Info(fmt.Sprintf("Starting Export Distro %s", p))
messageErrors <- http.ListenAndServe(p, httpServer())
}()
registrations := make(map[string]*registrationInfo)
allRegs, err := getRegistrations()
for allRegs == nil {
LoggingClient.Info("Waiting for client microservice")
select {
case e := <-messageErrors:
LoggingClient.Error(fmt.Sprintf("exit msg: %s", e.Error()))
if err != nil {
LoggingClient.Error(fmt.Sprintf("with error: %s", err.Error()))
}
return
case <-time.After(time.Second):
}
allRegs, err = getRegistrations()
}
// Create new goroutines for each registration
for _, reg := range allRegs {
regInfo := newRegistrationInfo()
if regInfo.update(reg) {
registrations[reg.Name] = regInfo
go registrationLoop(regInfo)
}
}
LoggingClient.Info("Starting registration loop")
for {
select {
case e := <-messageErrors:
// kill all registration goroutines
for k, reg := range registrations {
if !reg.deleteFlag {
// Do not write in channel that will not be read
reg.chRegistration <- nil
}
delete(registrations, k)
}
LoggingClient.Error(fmt.Sprintf("exit msg: %s", e.Error()))
return
case update := <-registrationChanges:
LoggingClient.Info("Registration changes")
err := updateRunningRegistrations(registrations, update)
if err != nil {
LoggingClient.Error(err.Error())
LoggingClient.Warn(fmt.Sprintf("Error updating registration %s", update.Name))
}
case msgEnvelope := <-messageEnvelopes:
LoggingClient.Info(fmt.Sprintf("Event received on message queue. Topic: %s, Correlation-id: %s ", Configuration.MessageQueue.Topic, msgEnvelope.CorrelationID))
if msgEnvelope.ContentType != clients.ContentTypeJSON {
LoggingClient.Error(fmt.Sprintf("Incorrect content type for event message. Received: %s, Expected: %s", msgEnvelope.ContentType, clients.ContentTypeJSON))
continue
}
str := string(msgEnvelope.Payload)
event := parseEvent(str)
if event == nil {
continue
}
for k, reg := range registrations {
if reg.deleteFlag {
delete(registrations, k)
} else {
// TODO only sent event if it is not blocking
reg.chEvent <- event
}
}
}
}
} | [
"func",
"Loop",
"(",
")",
"{",
"go",
"func",
"(",
")",
"{",
"p",
":=",
"fmt",
".",
"Sprintf",
"(",
"\":%d\"",
",",
"Configuration",
".",
"Service",
".",
"Port",
")",
"\n",
"LoggingClient",
".",
"Info",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"Starting Exp... | // Loop - registration loop | [
"Loop",
"-",
"registration",
"loop"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/export/distro/registrations.go#L275-L354 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceprofile.go | checkDuplicateProfileNames | func checkDuplicateProfileNames(dp models.DeviceProfile, w http.ResponseWriter) error {
profiles, err := dbClient.GetAllDeviceProfiles()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
for _, p := range profiles {
if p.Name == dp.Name && p.Id != dp.Id {
err = errors.New("Duplicate profile name")
http.Error(w, err.Error(), http.StatusConflict)
return err
}
}
return nil
} | go | func checkDuplicateProfileNames(dp models.DeviceProfile, w http.ResponseWriter) error {
profiles, err := dbClient.GetAllDeviceProfiles()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
for _, p := range profiles {
if p.Name == dp.Name && p.Id != dp.Id {
err = errors.New("Duplicate profile name")
http.Error(w, err.Error(), http.StatusConflict)
return err
}
}
return nil
} | [
"func",
"checkDuplicateProfileNames",
"(",
"dp",
"models",
".",
"DeviceProfile",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"profiles",
",",
"err",
":=",
"dbClient",
".",
"GetAllDeviceProfiles",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",... | // Check for duplicate names in device profiles | [
"Check",
"for",
"duplicate",
"names",
"in",
"device",
"profiles"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceprofile.go#L192-L208 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceprofile.go | checkDuplicateCommands | func checkDuplicateCommands(dp models.DeviceProfile, w http.ResponseWriter) error {
// Check if there are duplicate names in the device profile command list
for _, c1 := range dp.CoreCommands {
count := 0
for _, c2 := range dp.CoreCommands {
if c1.Name == c2.Name {
count += 1
}
}
if count > 1 {
err := errors.New("Error adding device profile: Duplicate names in the commands")
http.Error(w, err.Error(), http.StatusConflict)
return err
}
}
return nil
} | go | func checkDuplicateCommands(dp models.DeviceProfile, w http.ResponseWriter) error {
// Check if there are duplicate names in the device profile command list
for _, c1 := range dp.CoreCommands {
count := 0
for _, c2 := range dp.CoreCommands {
if c1.Name == c2.Name {
count += 1
}
}
if count > 1 {
err := errors.New("Error adding device profile: Duplicate names in the commands")
http.Error(w, err.Error(), http.StatusConflict)
return err
}
}
return nil
} | [
"func",
"checkDuplicateCommands",
"(",
"dp",
"models",
".",
"DeviceProfile",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"for",
"_",
",",
"c1",
":=",
"range",
"dp",
".",
"CoreCommands",
"{",
"count",
":=",
"0",
"\n",
"for",
"_",
",",
"c... | // Check for duplicate command names in the device profile | [
"Check",
"for",
"duplicate",
"command",
"names",
"in",
"the",
"device",
"profile"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceprofile.go#L211-L228 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceprofile.go | deleteCommands | func deleteCommands(dp models.DeviceProfile, w http.ResponseWriter) error {
for _, command := range dp.CoreCommands {
err := dbClient.DeleteCommandById(command.Id)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
}
return nil
} | go | func deleteCommands(dp models.DeviceProfile, w http.ResponseWriter) error {
for _, command := range dp.CoreCommands {
err := dbClient.DeleteCommandById(command.Id)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
}
return nil
} | [
"func",
"deleteCommands",
"(",
"dp",
"models",
".",
"DeviceProfile",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"for",
"_",
",",
"command",
":=",
"range",
"dp",
".",
"CoreCommands",
"{",
"err",
":=",
"dbClient",
".",
"DeleteCommandById",
"... | // Delete all of the commands that are a part of the device profile | [
"Delete",
"all",
"of",
"the",
"commands",
"that",
"are",
"a",
"part",
"of",
"the",
"device",
"profile"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceprofile.go#L231-L241 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceprofile.go | addCommands | func addCommands(dp *models.DeviceProfile, w http.ResponseWriter) error {
for i := range dp.CoreCommands {
if newId, err := dbClient.AddCommand(dp.CoreCommands[i]); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
} else {
dp.CoreCommands[i].Id = newId
}
}
return nil
} | go | func addCommands(dp *models.DeviceProfile, w http.ResponseWriter) error {
for i := range dp.CoreCommands {
if newId, err := dbClient.AddCommand(dp.CoreCommands[i]); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
} else {
dp.CoreCommands[i].Id = newId
}
}
return nil
} | [
"func",
"addCommands",
"(",
"dp",
"*",
"models",
".",
"DeviceProfile",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"for",
"i",
":=",
"range",
"dp",
".",
"CoreCommands",
"{",
"if",
"newId",
",",
"err",
":=",
"dbClient",
".",
"AddCommand",
... | // Add all of the commands that are a part of the device profile | [
"Add",
"all",
"of",
"the",
"commands",
"that",
"are",
"a",
"part",
"of",
"the",
"device",
"profile"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceprofile.go#L244-L255 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceprofile.go | restDeleteProfileByName | func restDeleteProfileByName(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
n, err := url.QueryUnescape(vars[NAME])
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Check if the device profile exists
dp, err := dbClient.GetDeviceProfileByName(n)
if err != nil {
if err == db.ErrNotFound {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
LoggingClient.Error(err.Error())
return
}
// Delete the device profile
if err = deleteDeviceProfile(dp, w); err != nil {
LoggingClient.Error(err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte("true"))
} | go | func restDeleteProfileByName(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
n, err := url.QueryUnescape(vars[NAME])
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Check if the device profile exists
dp, err := dbClient.GetDeviceProfileByName(n)
if err != nil {
if err == db.ErrNotFound {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
LoggingClient.Error(err.Error())
return
}
// Delete the device profile
if err = deleteDeviceProfile(dp, w); err != nil {
LoggingClient.Error(err.Error())
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte("true"))
} | [
"func",
"restDeleteProfileByName",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"vars",
":=",
"mux",
".",
"Vars",
"(",
"r",
")",
"\n",
"n",
",",
"err",
":=",
"url",
".",
"QueryUnescape",
"(",
"vars",
"[",
... | // Delete the device profile based on its name | [
"Delete",
"the",
"device",
"profile",
"based",
"on",
"its",
"name"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceprofile.go#L302-L331 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceprofile.go | deleteDeviceProfile | func deleteDeviceProfile(dp models.DeviceProfile, w http.ResponseWriter) error {
// Check if the device profile is still in use by devices
d, err := dbClient.GetDevicesByProfileId(dp.Id)
// XXX ErrNotFound should always be returned but this is not consistent in the implementations
if err == db.ErrNotFound {
err = nil
d = []models.Device{}
} else if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
if len(d) > 0 {
err = errors.New("Can't delete device profile, the profile is still in use by a device")
http.Error(w, err.Error(), http.StatusConflict)
return err
}
// Check if the device profile is still in use by provision watchers
pw, err := dbClient.GetProvisionWatchersByProfileId(dp.Id)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
if len(pw) > 0 {
err = errors.New("Cant delete device profile, the profile is still in use by a provision watcher")
http.Error(w, err.Error(), http.StatusConflict)
return err
}
// Delete the profile
if err := dbClient.DeleteDeviceProfileById(dp.Id); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
return nil
} | go | func deleteDeviceProfile(dp models.DeviceProfile, w http.ResponseWriter) error {
// Check if the device profile is still in use by devices
d, err := dbClient.GetDevicesByProfileId(dp.Id)
// XXX ErrNotFound should always be returned but this is not consistent in the implementations
if err == db.ErrNotFound {
err = nil
d = []models.Device{}
} else if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
if len(d) > 0 {
err = errors.New("Can't delete device profile, the profile is still in use by a device")
http.Error(w, err.Error(), http.StatusConflict)
return err
}
// Check if the device profile is still in use by provision watchers
pw, err := dbClient.GetProvisionWatchersByProfileId(dp.Id)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
if len(pw) > 0 {
err = errors.New("Cant delete device profile, the profile is still in use by a provision watcher")
http.Error(w, err.Error(), http.StatusConflict)
return err
}
// Delete the profile
if err := dbClient.DeleteDeviceProfileById(dp.Id); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
return nil
} | [
"func",
"deleteDeviceProfile",
"(",
"dp",
"models",
".",
"DeviceProfile",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"d",
",",
"err",
":=",
"dbClient",
".",
"GetDevicesByProfileId",
"(",
"dp",
".",
"Id",
")",
"\n",
"if",
"err",
"==",
"db... | // Delete the device profile
// Make sure there are no devices still using it
// Delete the associated commands | [
"Delete",
"the",
"device",
"profile",
"Make",
"sure",
"there",
"are",
"no",
"devices",
"still",
"using",
"it",
"Delete",
"the",
"associated",
"commands"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceprofile.go#L336-L373 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceprofile.go | restAddProfileByYamlRaw | func restAddProfileByYamlRaw(w http.ResponseWriter, r *http.Request) {
// Get the YAML string
body, err := ioutil.ReadAll(r.Body)
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
addDeviceProfileYaml(body, w)
} | go | func restAddProfileByYamlRaw(w http.ResponseWriter, r *http.Request) {
// Get the YAML string
body, err := ioutil.ReadAll(r.Body)
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
addDeviceProfileYaml(body, w)
} | [
"func",
"restAddProfileByYamlRaw",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"Logging... | // Add a device profile with YAML content
// The YAML content is passed as a string in the http request | [
"Add",
"a",
"device",
"profile",
"with",
"YAML",
"content",
"The",
"YAML",
"content",
"is",
"passed",
"as",
"a",
"string",
"in",
"the",
"http",
"request"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceprofile.go#L408-L418 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceprofile.go | notifyProfileAssociates | func notifyProfileAssociates(dp models.DeviceProfile, action string) error {
// Get the devices
d, err := dbClient.GetDevicesByProfileId(dp.Id)
if err != nil {
LoggingClient.Error(err.Error())
return err
}
// Get the services for each device
// Use map as a Set
dsMap := map[string]models.DeviceService{}
ds := []models.DeviceService{}
for _, device := range d {
// Only add if not there
if _, ok := dsMap[device.Service.Id]; !ok {
dsMap[device.Service.Id] = device.Service
ds = append(ds, device.Service)
}
}
if err := notifyAssociates(ds, dp.Id, action, models.PROFILE); err != nil {
LoggingClient.Error(err.Error())
return err
}
return nil
} | go | func notifyProfileAssociates(dp models.DeviceProfile, action string) error {
// Get the devices
d, err := dbClient.GetDevicesByProfileId(dp.Id)
if err != nil {
LoggingClient.Error(err.Error())
return err
}
// Get the services for each device
// Use map as a Set
dsMap := map[string]models.DeviceService{}
ds := []models.DeviceService{}
for _, device := range d {
// Only add if not there
if _, ok := dsMap[device.Service.Id]; !ok {
dsMap[device.Service.Id] = device.Service
ds = append(ds, device.Service)
}
}
if err := notifyAssociates(ds, dp.Id, action, models.PROFILE); err != nil {
LoggingClient.Error(err.Error())
return err
}
return nil
} | [
"func",
"notifyProfileAssociates",
"(",
"dp",
"models",
".",
"DeviceProfile",
",",
"action",
"string",
")",
"error",
"{",
"d",
",",
"err",
":=",
"dbClient",
".",
"GetDevicesByProfileId",
"(",
"dp",
".",
"Id",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"Lo... | // Notify the associated device services for changes in the device profile | [
"Notify",
"the",
"associated",
"device",
"services",
"for",
"changes",
"in",
"the",
"device",
"profile"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceprofile.go#L649-L675 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_command.go | restUpdateCommand | func restUpdateCommand(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var c contract.Command
if err := json.NewDecoder(r.Body).Decode(&c); err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Check if command exists (By ID)
former, err := dbClient.GetCommandById(c.Id)
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusNotFound)
return
}
// Name is changed, make sure the new name doesn't conflict with device profile
if c.Name != "" {
dps, err := dbClient.GetDeviceProfilesByCommandId(c.Id)
if err == db.ErrNotFound {
err = nil
dps = []contract.DeviceProfile{}
} else if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Loop through matched device profiles to ensure the name isn't duplicate
for _, profile := range dps {
for _, command := range profile.CoreCommands {
if command.Name == c.Name {
err = errors.New("Error updating command: duplicate command name in device profile")
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusConflict)
return
}
}
}
}
// Update the fields
if c.Name != "" {
former.Name = c.Name
}
if (c.Get.String() != contract.Get{}.String()) {
former.Get = c.Get
}
if (c.Put.String() != contract.Put{}.String()) {
former.Put = c.Put
}
if err := dbClient.UpdateCommand(c); err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("true"))
} | go | func restUpdateCommand(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var c contract.Command
if err := json.NewDecoder(r.Body).Decode(&c); err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Check if command exists (By ID)
former, err := dbClient.GetCommandById(c.Id)
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusNotFound)
return
}
// Name is changed, make sure the new name doesn't conflict with device profile
if c.Name != "" {
dps, err := dbClient.GetDeviceProfilesByCommandId(c.Id)
if err == db.ErrNotFound {
err = nil
dps = []contract.DeviceProfile{}
} else if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Loop through matched device profiles to ensure the name isn't duplicate
for _, profile := range dps {
for _, command := range profile.CoreCommands {
if command.Name == c.Name {
err = errors.New("Error updating command: duplicate command name in device profile")
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusConflict)
return
}
}
}
}
// Update the fields
if c.Name != "" {
former.Name = c.Name
}
if (c.Get.String() != contract.Get{}.String()) {
former.Get = c.Get
}
if (c.Put.String() != contract.Put{}.String()) {
former.Put = c.Put
}
if err := dbClient.UpdateCommand(c); err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("true"))
} | [
"func",
"restUpdateCommand",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"defer",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"var",
"c",
"contract",
".",
"Command",
"\n",
"if",
"err",
":=",
"json",
... | // Update a command
// 404 if the command can't be found by ID
// 409 if the name of the command changes and its not unique to the device profile | [
"Update",
"a",
"command",
"404",
"if",
"the",
"command",
"can",
"t",
"be",
"found",
"by",
"ID",
"409",
"if",
"the",
"name",
"of",
"the",
"command",
"changes",
"and",
"its",
"not",
"unique",
"to",
"the",
"device",
"profile"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_command.go#L69-L130 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_command.go | restDeleteCommandById | func restDeleteCommandById(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
var id string = vars[ID]
// Check if the command exists
_, err := dbClient.GetCommandById(id)
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusNotFound)
return
}
// Check if the command is still in use by a device profile
isStillInUse, err := isCommandStillInUse(id)
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if isStillInUse {
err = errors.New("Can't delete command. Its still in use by Device Profiles")
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusConflict)
return
}
if err := dbClient.DeleteCommandById(id); err != nil {
LoggingClient.Error(err.Error())
if err == db.ErrCommandStillInUse {
http.Error(w, err.Error(), http.StatusConflict)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte("true"))
} | go | func restDeleteCommandById(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
var id string = vars[ID]
// Check if the command exists
_, err := dbClient.GetCommandById(id)
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusNotFound)
return
}
// Check if the command is still in use by a device profile
isStillInUse, err := isCommandStillInUse(id)
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if isStillInUse {
err = errors.New("Can't delete command. Its still in use by Device Profiles")
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusConflict)
return
}
if err := dbClient.DeleteCommandById(id); err != nil {
LoggingClient.Error(err.Error())
if err == db.ErrCommandStillInUse {
http.Error(w, err.Error(), http.StatusConflict)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte("true"))
} | [
"func",
"restDeleteCommandById",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"vars",
":=",
"mux",
".",
"Vars",
"(",
"r",
")",
"\n",
"var",
"id",
"string",
"=",
"vars",
"[",
"ID",
"]",
"\n",
"_",
",",
... | // Delete a command by its ID | [
"Delete",
"a",
"command",
"by",
"its",
"ID"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_command.go#L175-L213 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_command.go | isCommandStillInUse | func isCommandStillInUse(id string) (bool, error) {
dp, err := dbClient.GetDeviceProfilesByCommandId(id)
if err == db.ErrNotFound { // XXX Inconsistent return values. Should be ErrNotFound
err = nil
} else if err != nil {
return false, err
}
if len(dp) == 0 {
return false, err
}
return true, err
} | go | func isCommandStillInUse(id string) (bool, error) {
dp, err := dbClient.GetDeviceProfilesByCommandId(id)
if err == db.ErrNotFound { // XXX Inconsistent return values. Should be ErrNotFound
err = nil
} else if err != nil {
return false, err
}
if len(dp) == 0 {
return false, err
}
return true, err
} | [
"func",
"isCommandStillInUse",
"(",
"id",
"string",
")",
"(",
"bool",
",",
"error",
")",
"{",
"dp",
",",
"err",
":=",
"dbClient",
".",
"GetDeviceProfilesByCommandId",
"(",
"id",
")",
"\n",
"if",
"err",
"==",
"db",
".",
"ErrNotFound",
"{",
"err",
"=",
"... | // Helper function to determine if the command is still in use by device profiles | [
"Helper",
"function",
"to",
"determine",
"if",
"the",
"command",
"is",
"still",
"in",
"use",
"by",
"device",
"profiles"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_command.go#L216-L230 | train |
edgexfoundry/edgex-go | internal/pkg/usage/usage.go | HelpCallback | func HelpCallback() {
msg := fmt.Sprintf(usageStr, os.Args[0])
fmt.Printf("%s\n", msg)
os.Exit(0)
} | go | func HelpCallback() {
msg := fmt.Sprintf(usageStr, os.Args[0])
fmt.Printf("%s\n", msg)
os.Exit(0)
} | [
"func",
"HelpCallback",
"(",
")",
"{",
"msg",
":=",
"fmt",
".",
"Sprintf",
"(",
"usageStr",
",",
"os",
".",
"Args",
"[",
"0",
"]",
")",
"\n",
"fmt",
".",
"Printf",
"(",
"\"%s\\n\"",
",",
"\\n",
")",
"\n",
"msg",
"\n",
"}"
] | // usage will print out the flag options for the server. | [
"usage",
"will",
"print",
"out",
"the",
"flag",
"options",
"for",
"the",
"server",
"."
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/usage/usage.go#L42-L46 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_devicereport.go | updateDeviceReportFields | func updateDeviceReportFields(from models.DeviceReport, to *models.DeviceReport, w http.ResponseWriter) error {
if from.Device != "" {
to.Device = from.Device
if err := validateDevice(to.Device, w); err != nil {
return err
}
}
if from.Action != "" {
to.Action = from.Action
}
if from.Expected != nil {
to.Expected = from.Expected
// TODO: Someday find a way to check the value descriptors
}
if from.Name != "" {
to.Name = from.Name
}
if from.Origin != 0 {
to.Origin = from.Origin
}
return nil
} | go | func updateDeviceReportFields(from models.DeviceReport, to *models.DeviceReport, w http.ResponseWriter) error {
if from.Device != "" {
to.Device = from.Device
if err := validateDevice(to.Device, w); err != nil {
return err
}
}
if from.Action != "" {
to.Action = from.Action
}
if from.Expected != nil {
to.Expected = from.Expected
// TODO: Someday find a way to check the value descriptors
}
if from.Name != "" {
to.Name = from.Name
}
if from.Origin != 0 {
to.Origin = from.Origin
}
return nil
} | [
"func",
"updateDeviceReportFields",
"(",
"from",
"models",
".",
"DeviceReport",
",",
"to",
"*",
"models",
".",
"DeviceReport",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"if",
"from",
".",
"Device",
"!=",
"\"\"",
"{",
"to",
".",
"Device",
... | // Update the relevant fields for the device report | [
"Update",
"the",
"relevant",
"fields",
"for",
"the",
"device",
"report"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_devicereport.go#L139-L161 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_devicereport.go | validateDevice | func validateDevice(d string, w http.ResponseWriter) error {
if _, err := dbClient.GetDeviceByName(d); err != nil {
if err == db.ErrNotFound {
http.Error(w, "Device was not found", http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
return err
}
return nil
} | go | func validateDevice(d string, w http.ResponseWriter) error {
if _, err := dbClient.GetDeviceByName(d); err != nil {
if err == db.ErrNotFound {
http.Error(w, "Device was not found", http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
}
return err
}
return nil
} | [
"func",
"validateDevice",
"(",
"d",
"string",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"if",
"_",
",",
"err",
":=",
"dbClient",
".",
"GetDeviceByName",
"(",
"d",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"db",
".",
"E... | // Validate that the device exists | [
"Validate",
"that",
"the",
"device",
"exists"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_devicereport.go#L164-L175 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_devicereport.go | restGetValueDescriptorsForDeviceName | func restGetValueDescriptorsForDeviceName(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
n, err := url.QueryUnescape(vars[DEVICENAME])
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
LoggingClient.Error(err.Error())
return
}
// Get all the associated device reports
reports, err := dbClient.GetDeviceReportByDeviceName(n)
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
valueDescriptors := []string{}
for _, report := range reports {
for _, e := range report.Expected {
valueDescriptors = append(valueDescriptors, e)
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(valueDescriptors)
} | go | func restGetValueDescriptorsForDeviceName(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
n, err := url.QueryUnescape(vars[DEVICENAME])
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
LoggingClient.Error(err.Error())
return
}
// Get all the associated device reports
reports, err := dbClient.GetDeviceReportByDeviceName(n)
if err != nil {
LoggingClient.Error(err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
valueDescriptors := []string{}
for _, report := range reports {
for _, e := range report.Expected {
valueDescriptors = append(valueDescriptors, e)
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(valueDescriptors)
} | [
"func",
"restGetValueDescriptorsForDeviceName",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"vars",
":=",
"mux",
".",
"Vars",
"(",
"r",
")",
"\n",
"n",
",",
"err",
":=",
"url",
".",
"QueryUnescape",
"(",
"v... | // Get a list of value descriptor names
// The names are a union of all the value descriptors from the device reports for the given device | [
"Get",
"a",
"list",
"of",
"value",
"descriptor",
"names",
"The",
"names",
"are",
"a",
"union",
"of",
"all",
"the",
"value",
"descriptors",
"from",
"the",
"device",
"reports",
"for",
"the",
"given",
"device"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_devicereport.go#L221-L247 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_devicereport.go | notifyDeviceReportAssociates | func notifyDeviceReportAssociates(dr models.DeviceReport, action string) error {
// Get the device of the report
d, err := dbClient.GetDeviceByName(dr.Device)
if err != nil {
return err
}
// Get the device service for the device
ds, err := dbClient.GetDeviceServiceById(d.Service.Id)
if err != nil {
return err
}
// Notify the associating device services
if err = notifyAssociates([]models.DeviceService{ds}, dr.Id, action, models.REPORT); err != nil {
return err
}
return nil
} | go | func notifyDeviceReportAssociates(dr models.DeviceReport, action string) error {
// Get the device of the report
d, err := dbClient.GetDeviceByName(dr.Device)
if err != nil {
return err
}
// Get the device service for the device
ds, err := dbClient.GetDeviceServiceById(d.Service.Id)
if err != nil {
return err
}
// Notify the associating device services
if err = notifyAssociates([]models.DeviceService{ds}, dr.Id, action, models.REPORT); err != nil {
return err
}
return nil
} | [
"func",
"notifyDeviceReportAssociates",
"(",
"dr",
"models",
".",
"DeviceReport",
",",
"action",
"string",
")",
"error",
"{",
"d",
",",
"err",
":=",
"dbClient",
".",
"GetDeviceByName",
"(",
"dr",
".",
"Device",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"... | // Notify the associated device services to the device report | [
"Notify",
"the",
"associated",
"device",
"services",
"to",
"the",
"device",
"report"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_devicereport.go#L338-L357 | train |
edgexfoundry/edgex-go | internal/pkg/config/types.go | HealthCheck | func (s ServiceInfo) HealthCheck() string {
hc := fmt.Sprintf("%s://%s:%v%s", s.Protocol, s.Host, s.Port, clients.ApiPingRoute)
return hc
} | go | func (s ServiceInfo) HealthCheck() string {
hc := fmt.Sprintf("%s://%s:%v%s", s.Protocol, s.Host, s.Port, clients.ApiPingRoute)
return hc
} | [
"func",
"(",
"s",
"ServiceInfo",
")",
"HealthCheck",
"(",
")",
"string",
"{",
"hc",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s://%s:%v%s\"",
",",
"s",
".",
"Protocol",
",",
"s",
".",
"Host",
",",
"s",
".",
"Port",
",",
"clients",
".",
"ApiPingRoute",
")... | // HealthCheck is a URL specifying a healthcheck REST endpoint used by the Registry to determine if the
// service is available. | [
"HealthCheck",
"is",
"a",
"URL",
"specifying",
"a",
"healthcheck",
"REST",
"endpoint",
"used",
"by",
"the",
"Registry",
"to",
"determine",
"if",
"the",
"service",
"is",
"available",
"."
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/config/types.go#L50-L53 | train |
edgexfoundry/edgex-go | internal/pkg/config/types.go | Url | func (s ServiceInfo) Url() string {
url := fmt.Sprintf("%s://%s:%v", s.Protocol, s.Host, s.Port)
return url
} | go | func (s ServiceInfo) Url() string {
url := fmt.Sprintf("%s://%s:%v", s.Protocol, s.Host, s.Port)
return url
} | [
"func",
"(",
"s",
"ServiceInfo",
")",
"Url",
"(",
")",
"string",
"{",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s://%s:%v\"",
",",
"s",
".",
"Protocol",
",",
"s",
".",
"Host",
",",
"s",
".",
"Port",
")",
"\n",
"return",
"url",
"\n",
"}"
] | // Url provides a way to obtain the full url of the host service for use in initialization or, in some cases,
// responses to a caller. | [
"Url",
"provides",
"a",
"way",
"to",
"obtain",
"the",
"full",
"url",
"of",
"the",
"host",
"service",
"for",
"use",
"in",
"initialization",
"or",
"in",
"some",
"cases",
"responses",
"to",
"a",
"caller",
"."
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/config/types.go#L57-L60 | train |
edgexfoundry/edgex-go | internal/pkg/config/types.go | Url | func (e IntervalActionInfo) Url() string {
url := fmt.Sprintf("%s://%s:%v", e.Protocol, e.Host, e.Port)
return url
} | go | func (e IntervalActionInfo) Url() string {
url := fmt.Sprintf("%s://%s:%v", e.Protocol, e.Host, e.Port)
return url
} | [
"func",
"(",
"e",
"IntervalActionInfo",
")",
"Url",
"(",
")",
"string",
"{",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s://%s:%v\"",
",",
"e",
".",
"Protocol",
",",
"e",
".",
"Host",
",",
"e",
".",
"Port",
")",
"\n",
"return",
"url",
"\n",
"}"
] | // ScheduleEventInfo helper function | [
"ScheduleEventInfo",
"helper",
"function"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/config/types.go#L142-L145 | train |
edgexfoundry/edgex-go | internal/support/scheduler/utils.go | msToTime | func msToTime(ms string) (time.Time, error) {
msInt, err := strconv.ParseInt(ms, 10, 64)
if err != nil {
// todo: support-scheduler will be removed later issue_650a
t, err := time.Parse(TIMELAYOUT, ms)
if err == nil {
return t, nil
}
return time.Time{}, err
}
return time.Unix(0, msInt*int64(time.Millisecond)), nil
} | go | func msToTime(ms string) (time.Time, error) {
msInt, err := strconv.ParseInt(ms, 10, 64)
if err != nil {
// todo: support-scheduler will be removed later issue_650a
t, err := time.Parse(TIMELAYOUT, ms)
if err == nil {
return t, nil
}
return time.Time{}, err
}
return time.Unix(0, msInt*int64(time.Millisecond)), nil
} | [
"func",
"msToTime",
"(",
"ms",
"string",
")",
"(",
"time",
".",
"Time",
",",
"error",
")",
"{",
"msInt",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"ms",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"t",
",",
"err",
... | // Convert millisecond string to Time | [
"Convert",
"millisecond",
"string",
"to",
"Time"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/support/scheduler/utils.go#L37-L49 | train |
edgexfoundry/edgex-go | internal/pkg/db/redis/export.go | DeleteRegistrationByName | func (c *Client) DeleteRegistrationByName(name string) error {
conn := c.Pool.Get()
defer conn.Close()
id, err := redis.String(conn.Do("HGET", db.ExportCollection+":name", name))
if err == redis.ErrNil {
return db.ErrNotFound
} else if err != nil {
return err
}
return deleteRegistration(conn, id)
} | go | func (c *Client) DeleteRegistrationByName(name string) error {
conn := c.Pool.Get()
defer conn.Close()
id, err := redis.String(conn.Do("HGET", db.ExportCollection+":name", name))
if err == redis.ErrNil {
return db.ErrNotFound
} else if err != nil {
return err
}
return deleteRegistration(conn, id)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"DeleteRegistrationByName",
"(",
"name",
"string",
")",
"error",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"id",
",",
"err",
":=",
"redis",
... | // Delete a registration by name
// UnexpectedError - problem getting in database
// NotFound - no registration with the name was found | [
"Delete",
"a",
"registration",
"by",
"name",
"UnexpectedError",
"-",
"problem",
"getting",
"in",
"database",
"NotFound",
"-",
"no",
"registration",
"with",
"the",
"name",
"was",
"found"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/export.go#L115-L127 | train |
edgexfoundry/edgex-go | internal/pkg/db/redis/export.go | ScrubAllRegistrations | func (c *Client) ScrubAllRegistrations() (err error) {
conn := c.Pool.Get()
defer conn.Close()
return unlinkCollection(conn, db.ExportCollection)
} | go | func (c *Client) ScrubAllRegistrations() (err error) {
conn := c.Pool.Get()
defer conn.Close()
return unlinkCollection(conn, db.ExportCollection)
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"ScrubAllRegistrations",
"(",
")",
"(",
"err",
"error",
")",
"{",
"conn",
":=",
"c",
".",
"Pool",
".",
"Get",
"(",
")",
"\n",
"defer",
"conn",
".",
"Close",
"(",
")",
"\n",
"return",
"unlinkCollection",
"(",
"c... | // ScrubAllRegistrations deletes all export related data | [
"ScrubAllRegistrations",
"deletes",
"all",
"export",
"related",
"data"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/pkg/db/redis/export.go#L130-L135 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceservice.go | updateDeviceServiceFields | func updateDeviceServiceFields(from models.DeviceService, to *models.DeviceService, w http.ResponseWriter) error {
// Use .String() to compare empty structs (not ideal, but there is no .equals method)
if (from.Addressable.String() != models.Addressable{}.String()) {
var addr models.Addressable
var err error
if from.Addressable.Id != "" {
addr, err = dbClient.GetAddressableById(from.Addressable.Id)
}
if from.Addressable.Id == "" || err != nil {
addr, err = dbClient.GetAddressableByName(from.Addressable.Name)
if err != nil {
return err
}
}
to.Addressable = addr
}
to.AdminState = from.AdminState
if from.Description != "" {
to.Description = from.Description
}
if from.Labels != nil {
to.Labels = from.Labels
}
if from.LastConnected != 0 {
to.LastConnected = from.LastConnected
}
if from.LastReported != 0 {
to.LastReported = from.LastReported
}
if from.Name != "" {
to.Name = from.Name
// Check if the new name is unique
checkDS, err := dbClient.GetDeviceServiceByName(from.Name)
if err != nil {
// A problem occurred accessing database
if err != db.ErrNotFound {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
}
// Found a device service, make sure its the one we're trying to update
if err != db.ErrNotFound {
// Different IDs -> Name is not unique
if checkDS.Id != to.Id {
err = errors.New("Duplicate name for Device Service")
http.Error(w, err.Error(), http.StatusConflict)
return err
}
}
}
to.OperatingState = from.OperatingState
if from.Origin != 0 {
to.Origin = from.Origin
}
return nil
} | go | func updateDeviceServiceFields(from models.DeviceService, to *models.DeviceService, w http.ResponseWriter) error {
// Use .String() to compare empty structs (not ideal, but there is no .equals method)
if (from.Addressable.String() != models.Addressable{}.String()) {
var addr models.Addressable
var err error
if from.Addressable.Id != "" {
addr, err = dbClient.GetAddressableById(from.Addressable.Id)
}
if from.Addressable.Id == "" || err != nil {
addr, err = dbClient.GetAddressableByName(from.Addressable.Name)
if err != nil {
return err
}
}
to.Addressable = addr
}
to.AdminState = from.AdminState
if from.Description != "" {
to.Description = from.Description
}
if from.Labels != nil {
to.Labels = from.Labels
}
if from.LastConnected != 0 {
to.LastConnected = from.LastConnected
}
if from.LastReported != 0 {
to.LastReported = from.LastReported
}
if from.Name != "" {
to.Name = from.Name
// Check if the new name is unique
checkDS, err := dbClient.GetDeviceServiceByName(from.Name)
if err != nil {
// A problem occurred accessing database
if err != db.ErrNotFound {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
}
// Found a device service, make sure its the one we're trying to update
if err != db.ErrNotFound {
// Different IDs -> Name is not unique
if checkDS.Id != to.Id {
err = errors.New("Duplicate name for Device Service")
http.Error(w, err.Error(), http.StatusConflict)
return err
}
}
}
to.OperatingState = from.OperatingState
if from.Origin != 0 {
to.Origin = from.Origin
}
return nil
} | [
"func",
"updateDeviceServiceFields",
"(",
"from",
"models",
".",
"DeviceService",
",",
"to",
"*",
"models",
".",
"DeviceService",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"if",
"(",
"from",
".",
"Addressable",
".",
"String",
"(",
")",
"!... | // Update the relevant device service fields | [
"Update",
"the",
"relevant",
"device",
"service",
"fields"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceservice.go#L142-L202 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceservice.go | deleteDeviceService | func deleteDeviceService(ds models.DeviceService, w http.ResponseWriter, ctx context.Context) error {
// Delete the associated devices
devices, err := dbClient.GetDevicesByServiceId(ds.Id)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
for _, device := range devices {
if err = deleteDevice(device, w, ctx); err != nil {
return err
}
}
// Delete the associated provision watchers
watchers, err := dbClient.GetProvisionWatchersByServiceId(ds.Id)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
for _, watcher := range watchers {
if err = deleteProvisionWatcher(watcher, w); err != nil {
return err
}
}
// Delete the device service
if err = dbClient.DeleteDeviceServiceById(ds.Id); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
return nil
} | go | func deleteDeviceService(ds models.DeviceService, w http.ResponseWriter, ctx context.Context) error {
// Delete the associated devices
devices, err := dbClient.GetDevicesByServiceId(ds.Id)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
for _, device := range devices {
if err = deleteDevice(device, w, ctx); err != nil {
return err
}
}
// Delete the associated provision watchers
watchers, err := dbClient.GetProvisionWatchersByServiceId(ds.Id)
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
for _, watcher := range watchers {
if err = deleteProvisionWatcher(watcher, w); err != nil {
return err
}
}
// Delete the device service
if err = dbClient.DeleteDeviceServiceById(ds.Id); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
return nil
} | [
"func",
"deleteDeviceService",
"(",
"ds",
"models",
".",
"DeviceService",
",",
"w",
"http",
".",
"ResponseWriter",
",",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"devices",
",",
"err",
":=",
"dbClient",
".",
"GetDevicesByServiceId",
"(",
"ds",
"."... | // Delete the device service
// Delete the associated devices
// Delete the associated provision watchers | [
"Delete",
"the",
"device",
"service",
"Delete",
"the",
"associated",
"devices",
"Delete",
"the",
"associated",
"provision",
"watchers"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceservice.go#L367-L399 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceservice.go | updateServiceLastConnected | func updateServiceLastConnected(ds models.DeviceService, lc int64, w http.ResponseWriter) error {
ds.LastConnected = lc
if err := dbClient.UpdateDeviceService(ds); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
return nil
} | go | func updateServiceLastConnected(ds models.DeviceService, lc int64, w http.ResponseWriter) error {
ds.LastConnected = lc
if err := dbClient.UpdateDeviceService(ds); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
return nil
} | [
"func",
"updateServiceLastConnected",
"(",
"ds",
"models",
".",
"DeviceService",
",",
"lc",
"int64",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"ds",
".",
"LastConnected",
"=",
"lc",
"\n",
"if",
"err",
":=",
"dbClient",
".",
"UpdateDeviceSer... | // Update the last connected value of the device service | [
"Update",
"the",
"last",
"connected",
"value",
"of",
"the",
"device",
"service"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceservice.go#L472-L481 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceservice.go | updateServiceOpState | func updateServiceOpState(ds models.DeviceService, os models.OperatingState, w http.ResponseWriter) error {
ds.OperatingState = os
if err := dbClient.UpdateDeviceService(ds); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
return nil
} | go | func updateServiceOpState(ds models.DeviceService, os models.OperatingState, w http.ResponseWriter) error {
ds.OperatingState = os
if err := dbClient.UpdateDeviceService(ds); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
return nil
} | [
"func",
"updateServiceOpState",
"(",
"ds",
"models",
".",
"DeviceService",
",",
"os",
"models",
".",
"OperatingState",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"ds",
".",
"OperatingState",
"=",
"os",
"\n",
"if",
"err",
":=",
"dbClient",
... | // Update the OpState for the device service | [
"Update",
"the",
"OpState",
"for",
"the",
"device",
"service"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceservice.go#L578-L586 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceservice.go | updateServiceAdminState | func updateServiceAdminState(ds models.DeviceService, as models.AdminState, w http.ResponseWriter) error {
ds.AdminState = as
if err := dbClient.UpdateDeviceService(ds); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
return nil
} | go | func updateServiceAdminState(ds models.DeviceService, as models.AdminState, w http.ResponseWriter) error {
ds.AdminState = as
if err := dbClient.UpdateDeviceService(ds); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
return nil
} | [
"func",
"updateServiceAdminState",
"(",
"ds",
"models",
".",
"DeviceService",
",",
"as",
"models",
".",
"AdminState",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"ds",
".",
"AdminState",
"=",
"as",
"\n",
"if",
"err",
":=",
"dbClient",
".",
... | // Update the admin state for the device service | [
"Update",
"the",
"admin",
"state",
"for",
"the",
"device",
"service"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceservice.go#L666-L674 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceservice.go | updateServiceLastReported | func updateServiceLastReported(ds models.DeviceService, lr int64, w http.ResponseWriter) error {
ds.LastReported = lr
if err := dbClient.UpdateDeviceService(ds); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
return nil
} | go | func updateServiceLastReported(ds models.DeviceService, lr int64, w http.ResponseWriter) error {
ds.LastReported = lr
if err := dbClient.UpdateDeviceService(ds); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return err
}
return nil
} | [
"func",
"updateServiceLastReported",
"(",
"ds",
"models",
".",
"DeviceService",
",",
"lr",
"int64",
",",
"w",
"http",
".",
"ResponseWriter",
")",
"error",
"{",
"ds",
".",
"LastReported",
"=",
"lr",
"\n",
"if",
"err",
":=",
"dbClient",
".",
"UpdateDeviceServi... | // Update the last reported value for the device service | [
"Update",
"the",
"last",
"reported",
"value",
"for",
"the",
"device",
"service"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceservice.go#L746-L754 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceservice.go | callback | func callback(service models.DeviceService, id string, action string, actionType models.ActionType) error {
client := &http.Client{}
url := service.Addressable.GetCallbackURL()
if len(url) > 0 {
body, err := getBody(id, actionType)
if err != nil {
return err
}
req, err := http.NewRequest(string(action), url, bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/json")
go makeRequest(client, req)
} else {
LoggingClient.Info("callback::no addressable for " + service.Name)
}
return nil
} | go | func callback(service models.DeviceService, id string, action string, actionType models.ActionType) error {
client := &http.Client{}
url := service.Addressable.GetCallbackURL()
if len(url) > 0 {
body, err := getBody(id, actionType)
if err != nil {
return err
}
req, err := http.NewRequest(string(action), url, bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/json")
go makeRequest(client, req)
} else {
LoggingClient.Info("callback::no addressable for " + service.Name)
}
return nil
} | [
"func",
"callback",
"(",
"service",
"models",
".",
"DeviceService",
",",
"id",
"string",
",",
"action",
"string",
",",
"actionType",
"models",
".",
"ActionType",
")",
"error",
"{",
"client",
":=",
"&",
"http",
".",
"Client",
"{",
"}",
"\n",
"url",
":=",
... | // Make the callback for the device service | [
"Make",
"the",
"callback",
"for",
"the",
"device",
"service"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceservice.go#L769-L788 | train |
edgexfoundry/edgex-go | internal/core/metadata/rest_deviceservice.go | getBody | func getBody(id string, actionType models.ActionType) ([]byte, error) {
return json.Marshal(models.CallbackAlert{ActionType: actionType, Id: id})
} | go | func getBody(id string, actionType models.ActionType) ([]byte, error) {
return json.Marshal(models.CallbackAlert{ActionType: actionType, Id: id})
} | [
"func",
"getBody",
"(",
"id",
"string",
",",
"actionType",
"models",
".",
"ActionType",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"json",
".",
"Marshal",
"(",
"models",
".",
"CallbackAlert",
"{",
"ActionType",
":",
"actionType",
",",
... | // Turn the ID and ActionType into the JSON body that will be passed | [
"Turn",
"the",
"ID",
"and",
"ActionType",
"into",
"the",
"JSON",
"body",
"that",
"will",
"be",
"passed"
] | c67086fe10c4d34caeefffaee5379490103dd63f | https://github.com/edgexfoundry/edgex-go/blob/c67086fe10c4d34caeefffaee5379490103dd63f/internal/core/metadata/rest_deviceservice.go#L803-L805 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.