repo stringlengths 5 54 | path stringlengths 4 155 | func_name stringlengths 1 118 | original_string stringlengths 52 85.5k | language stringclasses 1 value | code stringlengths 52 85.5k | code_tokens list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
TheThingsNetwork/ttn | core/router/router.go | getBroker | func (r *router) getBroker(brokerAnnouncement *pb_discovery.Announcement) (*broker, error) {
// We're going to be optimistic and guess that the broker is already active
r.brokersLock.RLock()
brk, ok := r.brokers[brokerAnnouncement.ID]
r.brokersLock.RUnlock()
if ok {
return brk, nil
}
// If it doesn't we still have to lock
r.brokersLock.Lock()
defer r.brokersLock.Unlock()
if _, ok := r.brokers[brokerAnnouncement.ID]; !ok {
var err error
brk := &broker{
uplink: make(chan *pb_broker.UplinkMessage),
}
// Connect to the server
brk.conn, err = brokerAnnouncement.Dial(r.Pool)
if err != nil {
return nil, err
}
// Set up the non-streaming client
brk.client = pb_broker.NewBrokerClient(brk.conn)
// Set up the streaming client
config := brokerclient.DefaultClientConfig
config.BackgroundContext = r.Component.Context
cli := brokerclient.NewClient(config)
cli.AddServer(brokerAnnouncement.ID, brk.conn)
brk.association = cli.NewRouterStreams(r.Identity.ID, "")
go func() {
downlinkStream := brk.association.Downlink()
refreshDownlinkStream := time.NewTicker(time.Second)
for {
select {
case message := <-brk.uplink:
brk.association.Uplink(message)
case <-refreshDownlinkStream.C:
downlinkStream = brk.association.Downlink()
case message, ok := <-downlinkStream:
if ok {
go r.HandleDownlink(message)
} else {
r.Ctx.WithField("broker", brokerAnnouncement.ID).Error("Downlink Stream errored")
downlinkStream = nil
}
}
}
}()
r.brokers[brokerAnnouncement.ID] = brk
}
return r.brokers[brokerAnnouncement.ID], nil
} | go | func (r *router) getBroker(brokerAnnouncement *pb_discovery.Announcement) (*broker, error) {
// We're going to be optimistic and guess that the broker is already active
r.brokersLock.RLock()
brk, ok := r.brokers[brokerAnnouncement.ID]
r.brokersLock.RUnlock()
if ok {
return brk, nil
}
// If it doesn't we still have to lock
r.brokersLock.Lock()
defer r.brokersLock.Unlock()
if _, ok := r.brokers[brokerAnnouncement.ID]; !ok {
var err error
brk := &broker{
uplink: make(chan *pb_broker.UplinkMessage),
}
// Connect to the server
brk.conn, err = brokerAnnouncement.Dial(r.Pool)
if err != nil {
return nil, err
}
// Set up the non-streaming client
brk.client = pb_broker.NewBrokerClient(brk.conn)
// Set up the streaming client
config := brokerclient.DefaultClientConfig
config.BackgroundContext = r.Component.Context
cli := brokerclient.NewClient(config)
cli.AddServer(brokerAnnouncement.ID, brk.conn)
brk.association = cli.NewRouterStreams(r.Identity.ID, "")
go func() {
downlinkStream := brk.association.Downlink()
refreshDownlinkStream := time.NewTicker(time.Second)
for {
select {
case message := <-brk.uplink:
brk.association.Uplink(message)
case <-refreshDownlinkStream.C:
downlinkStream = brk.association.Downlink()
case message, ok := <-downlinkStream:
if ok {
go r.HandleDownlink(message)
} else {
r.Ctx.WithField("broker", brokerAnnouncement.ID).Error("Downlink Stream errored")
downlinkStream = nil
}
}
}
}()
r.brokers[brokerAnnouncement.ID] = brk
}
return r.brokers[brokerAnnouncement.ID], nil
} | [
"func",
"(",
"r",
"*",
"router",
")",
"getBroker",
"(",
"brokerAnnouncement",
"*",
"pb_discovery",
".",
"Announcement",
")",
"(",
"*",
"broker",
",",
"error",
")",
"{",
"// We're going to be optimistic and guess that the broker is already active",
"r",
".",
"brokersLock",
".",
"RLock",
"(",
")",
"\n",
"brk",
",",
"ok",
":=",
"r",
".",
"brokers",
"[",
"brokerAnnouncement",
".",
"ID",
"]",
"\n",
"r",
".",
"brokersLock",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"ok",
"{",
"return",
"brk",
",",
"nil",
"\n",
"}",
"\n\n",
"// If it doesn't we still have to lock",
"r",
".",
"brokersLock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"brokersLock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"r",
".",
"brokers",
"[",
"brokerAnnouncement",
".",
"ID",
"]",
";",
"!",
"ok",
"{",
"var",
"err",
"error",
"\n\n",
"brk",
":=",
"&",
"broker",
"{",
"uplink",
":",
"make",
"(",
"chan",
"*",
"pb_broker",
".",
"UplinkMessage",
")",
",",
"}",
"\n\n",
"// Connect to the server",
"brk",
".",
"conn",
",",
"err",
"=",
"brokerAnnouncement",
".",
"Dial",
"(",
"r",
".",
"Pool",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Set up the non-streaming client",
"brk",
".",
"client",
"=",
"pb_broker",
".",
"NewBrokerClient",
"(",
"brk",
".",
"conn",
")",
"\n\n",
"// Set up the streaming client",
"config",
":=",
"brokerclient",
".",
"DefaultClientConfig",
"\n",
"config",
".",
"BackgroundContext",
"=",
"r",
".",
"Component",
".",
"Context",
"\n",
"cli",
":=",
"brokerclient",
".",
"NewClient",
"(",
"config",
")",
"\n",
"cli",
".",
"AddServer",
"(",
"brokerAnnouncement",
".",
"ID",
",",
"brk",
".",
"conn",
")",
"\n",
"brk",
".",
"association",
"=",
"cli",
".",
"NewRouterStreams",
"(",
"r",
".",
"Identity",
".",
"ID",
",",
"\"",
"\"",
")",
"\n\n",
"go",
"func",
"(",
")",
"{",
"downlinkStream",
":=",
"brk",
".",
"association",
".",
"Downlink",
"(",
")",
"\n",
"refreshDownlinkStream",
":=",
"time",
".",
"NewTicker",
"(",
"time",
".",
"Second",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"message",
":=",
"<-",
"brk",
".",
"uplink",
":",
"brk",
".",
"association",
".",
"Uplink",
"(",
"message",
")",
"\n",
"case",
"<-",
"refreshDownlinkStream",
".",
"C",
":",
"downlinkStream",
"=",
"brk",
".",
"association",
".",
"Downlink",
"(",
")",
"\n",
"case",
"message",
",",
"ok",
":=",
"<-",
"downlinkStream",
":",
"if",
"ok",
"{",
"go",
"r",
".",
"HandleDownlink",
"(",
"message",
")",
"\n",
"}",
"else",
"{",
"r",
".",
"Ctx",
".",
"WithField",
"(",
"\"",
"\"",
",",
"brokerAnnouncement",
".",
"ID",
")",
".",
"Error",
"(",
"\"",
"\"",
")",
"\n",
"downlinkStream",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"r",
".",
"brokers",
"[",
"brokerAnnouncement",
".",
"ID",
"]",
"=",
"brk",
"\n",
"}",
"\n",
"return",
"r",
".",
"brokers",
"[",
"brokerAnnouncement",
".",
"ID",
"]",
",",
"nil",
"\n",
"}"
] | // getBroker gets or creates a broker association and returns the broker
// the first time it also starts a goroutine that receives downlink from the broker | [
"getBroker",
"gets",
"or",
"creates",
"a",
"broker",
"association",
"and",
"returns",
"the",
"broker",
"the",
"first",
"time",
"it",
"also",
"starts",
"a",
"goroutine",
"that",
"receives",
"downlink",
"from",
"the",
"broker"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/router/router.go#L151-L209 | train |
TheThingsNetwork/ttn | mqtt/downlink.go | PublishDownlink | func (c *DefaultClient) PublishDownlink(dataDown types.DownlinkMessage) Token {
topic := DeviceTopic{dataDown.AppID, dataDown.DevID, DeviceDownlink, ""}
dataDown.AppID = ""
dataDown.DevID = ""
msg, err := json.Marshal(dataDown)
if err != nil {
return &simpleToken{fmt.Errorf("Unable to marshal the message payload: %s", err)}
}
return c.publish(topic.String(), msg)
} | go | func (c *DefaultClient) PublishDownlink(dataDown types.DownlinkMessage) Token {
topic := DeviceTopic{dataDown.AppID, dataDown.DevID, DeviceDownlink, ""}
dataDown.AppID = ""
dataDown.DevID = ""
msg, err := json.Marshal(dataDown)
if err != nil {
return &simpleToken{fmt.Errorf("Unable to marshal the message payload: %s", err)}
}
return c.publish(topic.String(), msg)
} | [
"func",
"(",
"c",
"*",
"DefaultClient",
")",
"PublishDownlink",
"(",
"dataDown",
"types",
".",
"DownlinkMessage",
")",
"Token",
"{",
"topic",
":=",
"DeviceTopic",
"{",
"dataDown",
".",
"AppID",
",",
"dataDown",
".",
"DevID",
",",
"DeviceDownlink",
",",
"\"",
"\"",
"}",
"\n",
"dataDown",
".",
"AppID",
"=",
"\"",
"\"",
"\n",
"dataDown",
".",
"DevID",
"=",
"\"",
"\"",
"\n",
"msg",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"dataDown",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"simpleToken",
"{",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"}",
"\n",
"}",
"\n",
"return",
"c",
".",
"publish",
"(",
"topic",
".",
"String",
"(",
")",
",",
"msg",
")",
"\n",
"}"
] | // PublishDownlink publishes a downlink message | [
"PublishDownlink",
"publishes",
"a",
"downlink",
"message"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/downlink.go#L18-L27 | train |
TheThingsNetwork/ttn | mqtt/downlink.go | UnsubscribeDeviceDownlink | func (c *DefaultClient) UnsubscribeDeviceDownlink(appID string, devID string) Token {
topic := DeviceTopic{appID, devID, DeviceDownlink, ""}
return c.unsubscribe(topic.String())
} | go | func (c *DefaultClient) UnsubscribeDeviceDownlink(appID string, devID string) Token {
topic := DeviceTopic{appID, devID, DeviceDownlink, ""}
return c.unsubscribe(topic.String())
} | [
"func",
"(",
"c",
"*",
"DefaultClient",
")",
"UnsubscribeDeviceDownlink",
"(",
"appID",
"string",
",",
"devID",
"string",
")",
"Token",
"{",
"topic",
":=",
"DeviceTopic",
"{",
"appID",
",",
"devID",
",",
"DeviceDownlink",
",",
"\"",
"\"",
"}",
"\n",
"return",
"c",
".",
"unsubscribe",
"(",
"topic",
".",
"String",
"(",
")",
")",
"\n",
"}"
] | // UnsubscribeDeviceDownlink unsubscribes from the downlink messages for the given application and device | [
"UnsubscribeDeviceDownlink",
"unsubscribes",
"from",
"the",
"downlink",
"messages",
"for",
"the",
"given",
"application",
"and",
"device"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/downlink.go#L66-L69 | train |
TheThingsNetwork/ttn | core/storage/redis_set_store.go | NewRedisSetStore | func NewRedisSetStore(client *redis.Client, prefix string) *RedisSetStore {
if !strings.HasSuffix(prefix, ":") {
prefix += ":"
}
return &RedisSetStore{
RedisStore: NewRedisStore(client, prefix),
}
} | go | func NewRedisSetStore(client *redis.Client, prefix string) *RedisSetStore {
if !strings.HasSuffix(prefix, ":") {
prefix += ":"
}
return &RedisSetStore{
RedisStore: NewRedisStore(client, prefix),
}
} | [
"func",
"NewRedisSetStore",
"(",
"client",
"*",
"redis",
".",
"Client",
",",
"prefix",
"string",
")",
"*",
"RedisSetStore",
"{",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"prefix",
",",
"\"",
"\"",
")",
"{",
"prefix",
"+=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"&",
"RedisSetStore",
"{",
"RedisStore",
":",
"NewRedisStore",
"(",
"client",
",",
"prefix",
")",
",",
"}",
"\n",
"}"
] | // NewRedisSetStore creates a new RedisSetStore | [
"NewRedisSetStore",
"creates",
"a",
"new",
"RedisSetStore"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_set_store.go#L21-L28 | train |
TheThingsNetwork/ttn | core/storage/redis_set_store.go | GetAll | func (s *RedisSetStore) GetAll(keys []string, options *ListOptions) (map[string][]string, error) {
if len(keys) == 0 {
return map[string][]string{}, nil
}
for i, key := range keys {
if !strings.HasPrefix(key, s.prefix) {
keys[i] = s.prefix + key
}
}
sort.Strings(keys)
selectedKeys := selectKeys(keys, options)
if len(selectedKeys) == 0 {
return map[string][]string{}, nil
}
pipe := s.client.Pipeline()
defer pipe.Close()
// Add all commands to pipeline
cmds := make(map[string]*redis.StringSliceCmd)
for _, key := range selectedKeys {
cmds[key] = pipe.SMembers(key)
}
// Execute pipeline
_, err := pipe.Exec()
if err != nil {
return nil, err
}
// Get all results from pipeline
data := make(map[string][]string)
for key, cmd := range cmds {
res, err := cmd.Result()
if err == nil {
sort.Strings(res)
data[strings.TrimPrefix(key, s.prefix)] = res
}
}
return data, nil
} | go | func (s *RedisSetStore) GetAll(keys []string, options *ListOptions) (map[string][]string, error) {
if len(keys) == 0 {
return map[string][]string{}, nil
}
for i, key := range keys {
if !strings.HasPrefix(key, s.prefix) {
keys[i] = s.prefix + key
}
}
sort.Strings(keys)
selectedKeys := selectKeys(keys, options)
if len(selectedKeys) == 0 {
return map[string][]string{}, nil
}
pipe := s.client.Pipeline()
defer pipe.Close()
// Add all commands to pipeline
cmds := make(map[string]*redis.StringSliceCmd)
for _, key := range selectedKeys {
cmds[key] = pipe.SMembers(key)
}
// Execute pipeline
_, err := pipe.Exec()
if err != nil {
return nil, err
}
// Get all results from pipeline
data := make(map[string][]string)
for key, cmd := range cmds {
res, err := cmd.Result()
if err == nil {
sort.Strings(res)
data[strings.TrimPrefix(key, s.prefix)] = res
}
}
return data, nil
} | [
"func",
"(",
"s",
"*",
"RedisSetStore",
")",
"GetAll",
"(",
"keys",
"[",
"]",
"string",
",",
"options",
"*",
"ListOptions",
")",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"len",
"(",
"keys",
")",
"==",
"0",
"{",
"return",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"key",
":=",
"range",
"keys",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"key",
",",
"s",
".",
"prefix",
")",
"{",
"keys",
"[",
"i",
"]",
"=",
"s",
".",
"prefix",
"+",
"key",
"\n",
"}",
"\n",
"}",
"\n\n",
"sort",
".",
"Strings",
"(",
"keys",
")",
"\n\n",
"selectedKeys",
":=",
"selectKeys",
"(",
"keys",
",",
"options",
")",
"\n",
"if",
"len",
"(",
"selectedKeys",
")",
"==",
"0",
"{",
"return",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"{",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"pipe",
":=",
"s",
".",
"client",
".",
"Pipeline",
"(",
")",
"\n",
"defer",
"pipe",
".",
"Close",
"(",
")",
"\n\n",
"// Add all commands to pipeline",
"cmds",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"redis",
".",
"StringSliceCmd",
")",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"selectedKeys",
"{",
"cmds",
"[",
"key",
"]",
"=",
"pipe",
".",
"SMembers",
"(",
"key",
")",
"\n",
"}",
"\n\n",
"// Execute pipeline",
"_",
",",
"err",
":=",
"pipe",
".",
"Exec",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Get all results from pipeline",
"data",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n",
"for",
"key",
",",
"cmd",
":=",
"range",
"cmds",
"{",
"res",
",",
"err",
":=",
"cmd",
".",
"Result",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"sort",
".",
"Strings",
"(",
"res",
")",
"\n",
"data",
"[",
"strings",
".",
"TrimPrefix",
"(",
"key",
",",
"s",
".",
"prefix",
")",
"]",
"=",
"res",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"data",
",",
"nil",
"\n",
"}"
] | // GetAll returns all results for the given keys, prepending the prefix to the keys if necessary | [
"GetAll",
"returns",
"all",
"results",
"for",
"the",
"given",
"keys",
"prepending",
"the",
"prefix",
"to",
"the",
"keys",
"if",
"necessary"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_set_store.go#L31-L75 | train |
TheThingsNetwork/ttn | core/storage/redis_set_store.go | Count | func (s *RedisSetStore) Count(key string) (int, error) {
if !strings.HasPrefix(key, s.prefix) {
key = s.prefix + key
}
res, err := s.client.SCard(key).Result()
return int(res), err
} | go | func (s *RedisSetStore) Count(key string) (int, error) {
if !strings.HasPrefix(key, s.prefix) {
key = s.prefix + key
}
res, err := s.client.SCard(key).Result()
return int(res), err
} | [
"func",
"(",
"s",
"*",
"RedisSetStore",
")",
"Count",
"(",
"key",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"key",
",",
"s",
".",
"prefix",
")",
"{",
"key",
"=",
"s",
".",
"prefix",
"+",
"key",
"\n",
"}",
"\n",
"res",
",",
"err",
":=",
"s",
".",
"client",
".",
"SCard",
"(",
"key",
")",
".",
"Result",
"(",
")",
"\n",
"return",
"int",
"(",
"res",
")",
",",
"err",
"\n",
"}"
] | // Count the number of items for the given key | [
"Count",
"the",
"number",
"of",
"items",
"for",
"the",
"given",
"key"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_set_store.go#L78-L84 | train |
TheThingsNetwork/ttn | core/storage/redis_set_store.go | Contains | func (s *RedisSetStore) Contains(key string, value string) (res bool, err error) {
if !strings.HasPrefix(key, s.prefix) {
key = s.prefix + key
}
res, err = s.client.SIsMember(key, value).Result()
if err == redis.Nil {
return res, errors.NewErrNotFound(key)
}
return res, err
} | go | func (s *RedisSetStore) Contains(key string, value string) (res bool, err error) {
if !strings.HasPrefix(key, s.prefix) {
key = s.prefix + key
}
res, err = s.client.SIsMember(key, value).Result()
if err == redis.Nil {
return res, errors.NewErrNotFound(key)
}
return res, err
} | [
"func",
"(",
"s",
"*",
"RedisSetStore",
")",
"Contains",
"(",
"key",
"string",
",",
"value",
"string",
")",
"(",
"res",
"bool",
",",
"err",
"error",
")",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"key",
",",
"s",
".",
"prefix",
")",
"{",
"key",
"=",
"s",
".",
"prefix",
"+",
"key",
"\n",
"}",
"\n",
"res",
",",
"err",
"=",
"s",
".",
"client",
".",
"SIsMember",
"(",
"key",
",",
"value",
")",
".",
"Result",
"(",
")",
"\n",
"if",
"err",
"==",
"redis",
".",
"Nil",
"{",
"return",
"res",
",",
"errors",
".",
"NewErrNotFound",
"(",
"key",
")",
"\n",
"}",
"\n",
"return",
"res",
",",
"err",
"\n",
"}"
] | // Contains returns wheter the set contains a given value, prepending the prefix to the key if necessary | [
"Contains",
"returns",
"wheter",
"the",
"set",
"contains",
"a",
"given",
"value",
"prepending",
"the",
"prefix",
"to",
"the",
"key",
"if",
"necessary"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_set_store.go#L109-L118 | train |
TheThingsNetwork/ttn | core/storage/redis_set_store.go | Add | func (s *RedisSetStore) Add(key string, values ...string) error {
if !strings.HasPrefix(key, s.prefix) {
key = s.prefix + key
}
valuesI := make([]interface{}, len(values))
for i, v := range values {
valuesI[i] = v
}
return s.client.SAdd(key, valuesI...).Err()
} | go | func (s *RedisSetStore) Add(key string, values ...string) error {
if !strings.HasPrefix(key, s.prefix) {
key = s.prefix + key
}
valuesI := make([]interface{}, len(values))
for i, v := range values {
valuesI[i] = v
}
return s.client.SAdd(key, valuesI...).Err()
} | [
"func",
"(",
"s",
"*",
"RedisSetStore",
")",
"Add",
"(",
"key",
"string",
",",
"values",
"...",
"string",
")",
"error",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"key",
",",
"s",
".",
"prefix",
")",
"{",
"key",
"=",
"s",
".",
"prefix",
"+",
"key",
"\n",
"}",
"\n",
"valuesI",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"len",
"(",
"values",
")",
")",
"\n",
"for",
"i",
",",
"v",
":=",
"range",
"values",
"{",
"valuesI",
"[",
"i",
"]",
"=",
"v",
"\n",
"}",
"\n",
"return",
"s",
".",
"client",
".",
"SAdd",
"(",
"key",
",",
"valuesI",
"...",
")",
".",
"Err",
"(",
")",
"\n",
"}"
] | // Add one or more values to the set, prepending the prefix to the key if necessary | [
"Add",
"one",
"or",
"more",
"values",
"to",
"the",
"set",
"prepending",
"the",
"prefix",
"to",
"the",
"key",
"if",
"necessary"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_set_store.go#L121-L130 | train |
TheThingsNetwork/ttn | core/storage/redis_map_migrate.go | AddMigration | func (s *RedisMapStore) AddMigration(version string, migrate MigrateFunction) {
s.migrations[version] = migrate
} | go | func (s *RedisMapStore) AddMigration(version string, migrate MigrateFunction) {
s.migrations[version] = migrate
} | [
"func",
"(",
"s",
"*",
"RedisMapStore",
")",
"AddMigration",
"(",
"version",
"string",
",",
"migrate",
"MigrateFunction",
")",
"{",
"s",
".",
"migrations",
"[",
"version",
"]",
"=",
"migrate",
"\n",
"}"
] | // AddMigration adds a data migration for a version | [
"AddMigration",
"adds",
"a",
"data",
"migration",
"for",
"a",
"version"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_migrate.go#L25-L27 | train |
TheThingsNetwork/ttn | core/storage/redis_map_migrate.go | Migrate | func (s *RedisMapStore) Migrate(selector string) error {
if selector == "" {
selector = "*"
}
if !strings.HasPrefix(selector, s.prefix) {
selector = s.prefix + selector
}
var cursor uint64
for {
keys, next, err := s.client.Scan(cursor, selector, 0).Result()
if err != nil {
return err
}
for _, key := range keys {
// Get migrates the item
_, err := s.Get(key)
// NotFound if item was deleted since Scan started
if errors.GetErrType(err) == errors.NotFound {
continue
}
// TxFailedError is returned if the item was changed by a concurrent process.
// If it was a parallel migration, we don't have to do anything
// Otherwise, this item will be migrated with the next Get
if err == redis.TxFailedErr {
continue
}
// Any other error should be returned
if err != nil {
return err
}
}
cursor = next
if cursor == 0 {
break
}
}
return nil
} | go | func (s *RedisMapStore) Migrate(selector string) error {
if selector == "" {
selector = "*"
}
if !strings.HasPrefix(selector, s.prefix) {
selector = s.prefix + selector
}
var cursor uint64
for {
keys, next, err := s.client.Scan(cursor, selector, 0).Result()
if err != nil {
return err
}
for _, key := range keys {
// Get migrates the item
_, err := s.Get(key)
// NotFound if item was deleted since Scan started
if errors.GetErrType(err) == errors.NotFound {
continue
}
// TxFailedError is returned if the item was changed by a concurrent process.
// If it was a parallel migration, we don't have to do anything
// Otherwise, this item will be migrated with the next Get
if err == redis.TxFailedErr {
continue
}
// Any other error should be returned
if err != nil {
return err
}
}
cursor = next
if cursor == 0 {
break
}
}
return nil
} | [
"func",
"(",
"s",
"*",
"RedisMapStore",
")",
"Migrate",
"(",
"selector",
"string",
")",
"error",
"{",
"if",
"selector",
"==",
"\"",
"\"",
"{",
"selector",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"selector",
",",
"s",
".",
"prefix",
")",
"{",
"selector",
"=",
"s",
".",
"prefix",
"+",
"selector",
"\n",
"}",
"\n\n",
"var",
"cursor",
"uint64",
"\n",
"for",
"{",
"keys",
",",
"next",
",",
"err",
":=",
"s",
".",
"client",
".",
"Scan",
"(",
"cursor",
",",
"selector",
",",
"0",
")",
".",
"Result",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"key",
":=",
"range",
"keys",
"{",
"// Get migrates the item",
"_",
",",
"err",
":=",
"s",
".",
"Get",
"(",
"key",
")",
"\n\n",
"// NotFound if item was deleted since Scan started",
"if",
"errors",
".",
"GetErrType",
"(",
"err",
")",
"==",
"errors",
".",
"NotFound",
"{",
"continue",
"\n",
"}",
"\n\n",
"// TxFailedError is returned if the item was changed by a concurrent process.",
"// If it was a parallel migration, we don't have to do anything",
"// Otherwise, this item will be migrated with the next Get",
"if",
"err",
"==",
"redis",
".",
"TxFailedErr",
"{",
"continue",
"\n",
"}",
"\n\n",
"// Any other error should be returned",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"cursor",
"=",
"next",
"\n",
"if",
"cursor",
"==",
"0",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Migrate all documents matching the selector | [
"Migrate",
"all",
"documents",
"matching",
"the",
"selector"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_migrate.go#L30-L74 | train |
TheThingsNetwork/ttn | core/storage/util.go | GetTotalAndSelected | func (o ListOptions) GetTotalAndSelected() (total, selected uint64) {
return o.total, o.selected
} | go | func (o ListOptions) GetTotalAndSelected() (total, selected uint64) {
return o.total, o.selected
} | [
"func",
"(",
"o",
"ListOptions",
")",
"GetTotalAndSelected",
"(",
")",
"(",
"total",
",",
"selected",
"uint64",
")",
"{",
"return",
"o",
".",
"total",
",",
"o",
".",
"selected",
"\n",
"}"
] | // GetTotalAndSelected returns the total number of items, along with the number of selected items | [
"GetTotalAndSelected",
"returns",
"the",
"total",
"number",
"of",
"items",
"along",
"with",
"the",
"number",
"of",
"selected",
"items"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/util.go#L21-L23 | train |
TheThingsNetwork/ttn | core/storage/util.go | UseCache | func (o *ListOptions) UseCache(key string, ttl time.Duration) {
o.cacheKey, o.cacheTTL = key, ttl
} | go | func (o *ListOptions) UseCache(key string, ttl time.Duration) {
o.cacheKey, o.cacheTTL = key, ttl
} | [
"func",
"(",
"o",
"*",
"ListOptions",
")",
"UseCache",
"(",
"key",
"string",
",",
"ttl",
"time",
".",
"Duration",
")",
"{",
"o",
".",
"cacheKey",
",",
"o",
".",
"cacheTTL",
"=",
"key",
",",
"ttl",
"\n",
"}"
] | // UseCache instructs the list operation to use a result cache. | [
"UseCache",
"instructs",
"the",
"list",
"operation",
"to",
"use",
"a",
"result",
"cache",
"."
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/util.go#L26-L28 | train |
TheThingsNetwork/ttn | core/proxy/proxy.go | WithLogger | func WithLogger(handler http.Handler, ctx ttnlog.Interface) http.Handler {
return &logProxier{ctx, handler}
} | go | func WithLogger(handler http.Handler, ctx ttnlog.Interface) http.Handler {
return &logProxier{ctx, handler}
} | [
"func",
"WithLogger",
"(",
"handler",
"http",
".",
"Handler",
",",
"ctx",
"ttnlog",
".",
"Interface",
")",
"http",
".",
"Handler",
"{",
"return",
"&",
"logProxier",
"{",
"ctx",
",",
"handler",
"}",
"\n",
"}"
] | // WithLogger wraps the handler so that each request gets logged | [
"WithLogger",
"wraps",
"the",
"handler",
"so",
"that",
"each",
"request",
"gets",
"logged"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/proxy/proxy.go#L50-L52 | train |
TheThingsNetwork/ttn | core/networkserver/device/frames.go | Push | func (s *RedisFrameHistory) Push(frame *Frame) error {
frameBytes, err := json.Marshal(frame)
if err != nil {
return err
}
if err := s.store.AddFront(s.key(), string(frameBytes)); err != nil {
return err
}
return s.Trim()
} | go | func (s *RedisFrameHistory) Push(frame *Frame) error {
frameBytes, err := json.Marshal(frame)
if err != nil {
return err
}
if err := s.store.AddFront(s.key(), string(frameBytes)); err != nil {
return err
}
return s.Trim()
} | [
"func",
"(",
"s",
"*",
"RedisFrameHistory",
")",
"Push",
"(",
"frame",
"*",
"Frame",
")",
"error",
"{",
"frameBytes",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"frame",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"store",
".",
"AddFront",
"(",
"s",
".",
"key",
"(",
")",
",",
"string",
"(",
"frameBytes",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"s",
".",
"Trim",
"(",
")",
"\n",
"}"
] | // Push a Frame to the device's history | [
"Push",
"a",
"Frame",
"to",
"the",
"device",
"s",
"history"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/networkserver/device/frames.go#L43-L52 | train |
TheThingsNetwork/ttn | core/networkserver/device/frames.go | Get | func (s *RedisFrameHistory) Get() (out []*Frame, err error) {
frames, err := s.store.GetFront(s.key(), FramesHistorySize)
for _, frameStr := range frames {
frame := new(Frame)
if err := json.Unmarshal([]byte(frameStr), frame); err != nil {
return nil, err
}
out = append(out, frame)
}
return
} | go | func (s *RedisFrameHistory) Get() (out []*Frame, err error) {
frames, err := s.store.GetFront(s.key(), FramesHistorySize)
for _, frameStr := range frames {
frame := new(Frame)
if err := json.Unmarshal([]byte(frameStr), frame); err != nil {
return nil, err
}
out = append(out, frame)
}
return
} | [
"func",
"(",
"s",
"*",
"RedisFrameHistory",
")",
"Get",
"(",
")",
"(",
"out",
"[",
"]",
"*",
"Frame",
",",
"err",
"error",
")",
"{",
"frames",
",",
"err",
":=",
"s",
".",
"store",
".",
"GetFront",
"(",
"s",
".",
"key",
"(",
")",
",",
"FramesHistorySize",
")",
"\n",
"for",
"_",
",",
"frameStr",
":=",
"range",
"frames",
"{",
"frame",
":=",
"new",
"(",
"Frame",
")",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"frameStr",
")",
",",
"frame",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"out",
"=",
"append",
"(",
"out",
",",
"frame",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Get the last frames from the device's history | [
"Get",
"the",
"last",
"frames",
"from",
"the",
"device",
"s",
"history"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/networkserver/device/frames.go#L55-L65 | train |
TheThingsNetwork/ttn | core/networkserver/device/frames.go | Trim | func (s *RedisFrameHistory) Trim() error {
return s.store.Trim(s.key(), FramesHistorySize)
} | go | func (s *RedisFrameHistory) Trim() error {
return s.store.Trim(s.key(), FramesHistorySize)
} | [
"func",
"(",
"s",
"*",
"RedisFrameHistory",
")",
"Trim",
"(",
")",
"error",
"{",
"return",
"s",
".",
"store",
".",
"Trim",
"(",
"s",
".",
"key",
"(",
")",
",",
"FramesHistorySize",
")",
"\n",
"}"
] | // Trim frames in the device's history | [
"Trim",
"frames",
"in",
"the",
"device",
"s",
"history"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/networkserver/device/frames.go#L68-L70 | train |
TheThingsNetwork/ttn | core/handler/manager_server.go | eventUpdatedFields | func eventUpdatedFields(dev *device.Device) types.DeviceEventData {
changeList := dev.ChangedFields()
e := types.DeviceEventData{}
for _, key := range changeList {
switch key {
case "Latitude":
e.Latitude = dev.Latitude
case "Longitude":
e.Longitude = dev.Longitude
case "Altitude":
e.Altitude = dev.Altitude
case "UpdatedAt":
e.UpdatedAt = dev.UpdatedAt
}
}
return e
} | go | func eventUpdatedFields(dev *device.Device) types.DeviceEventData {
changeList := dev.ChangedFields()
e := types.DeviceEventData{}
for _, key := range changeList {
switch key {
case "Latitude":
e.Latitude = dev.Latitude
case "Longitude":
e.Longitude = dev.Longitude
case "Altitude":
e.Altitude = dev.Altitude
case "UpdatedAt":
e.UpdatedAt = dev.UpdatedAt
}
}
return e
} | [
"func",
"eventUpdatedFields",
"(",
"dev",
"*",
"device",
".",
"Device",
")",
"types",
".",
"DeviceEventData",
"{",
"changeList",
":=",
"dev",
".",
"ChangedFields",
"(",
")",
"\n",
"e",
":=",
"types",
".",
"DeviceEventData",
"{",
"}",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"changeList",
"{",
"switch",
"key",
"{",
"case",
"\"",
"\"",
":",
"e",
".",
"Latitude",
"=",
"dev",
".",
"Latitude",
"\n",
"case",
"\"",
"\"",
":",
"e",
".",
"Longitude",
"=",
"dev",
".",
"Longitude",
"\n",
"case",
"\"",
"\"",
":",
"e",
".",
"Altitude",
"=",
"dev",
".",
"Altitude",
"\n",
"case",
"\"",
"\"",
":",
"e",
".",
"UpdatedAt",
"=",
"dev",
".",
"UpdatedAt",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"e",
"\n",
"}"
] | // eventUpdatedFields create DeviceEvent based of on the changelist of a device | [
"eventUpdatedFields",
"create",
"DeviceEvent",
"based",
"of",
"on",
"the",
"changelist",
"of",
"a",
"device"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/manager_server.go#L240-L256 | train |
TheThingsNetwork/ttn | core/handler/application/migrate/application.go | ApplicationMigrations | func ApplicationMigrations(prefix string) map[string]storage.MigrateFunction {
funcs := make(map[string]storage.MigrateFunction)
for v, f := range applicationMigrations {
funcs[v] = f(prefix)
}
return funcs
} | go | func ApplicationMigrations(prefix string) map[string]storage.MigrateFunction {
funcs := make(map[string]storage.MigrateFunction)
for v, f := range applicationMigrations {
funcs[v] = f(prefix)
}
return funcs
} | [
"func",
"ApplicationMigrations",
"(",
"prefix",
"string",
")",
"map",
"[",
"string",
"]",
"storage",
".",
"MigrateFunction",
"{",
"funcs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"storage",
".",
"MigrateFunction",
")",
"\n",
"for",
"v",
",",
"f",
":=",
"range",
"applicationMigrations",
"{",
"funcs",
"[",
"v",
"]",
"=",
"f",
"(",
"prefix",
")",
"\n",
"}",
"\n",
"return",
"funcs",
"\n",
"}"
] | // ApplicationMigrations filled with the prefix | [
"ApplicationMigrations",
"filled",
"with",
"the",
"prefix"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/application/migrate/application.go#L13-L19 | train |
TheThingsNetwork/ttn | core/types/random.go | NewPopulatedDevAddr | func NewPopulatedDevAddr(r Rand) (devAddr *DevAddr) {
devAddr = &DevAddr{}
if _, err := randRead(r, devAddr[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedDevAddr: %s", err))
}
return
} | go | func NewPopulatedDevAddr(r Rand) (devAddr *DevAddr) {
devAddr = &DevAddr{}
if _, err := randRead(r, devAddr[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedDevAddr: %s", err))
}
return
} | [
"func",
"NewPopulatedDevAddr",
"(",
"r",
"Rand",
")",
"(",
"devAddr",
"*",
"DevAddr",
")",
"{",
"devAddr",
"=",
"&",
"DevAddr",
"{",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"randRead",
"(",
"r",
",",
"devAddr",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // NewPopulatedDevAddr returns random DevAddr | [
"NewPopulatedDevAddr",
"returns",
"random",
"DevAddr"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/random.go#L32-L38 | train |
TheThingsNetwork/ttn | core/types/random.go | NewPopulatedAppEUI | func NewPopulatedAppEUI(r Rand) (appEUI *AppEUI) {
appEUI = &AppEUI{}
if _, err := randRead(r, appEUI[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedAppEUI: %s", err))
}
return
} | go | func NewPopulatedAppEUI(r Rand) (appEUI *AppEUI) {
appEUI = &AppEUI{}
if _, err := randRead(r, appEUI[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedAppEUI: %s", err))
}
return
} | [
"func",
"NewPopulatedAppEUI",
"(",
"r",
"Rand",
")",
"(",
"appEUI",
"*",
"AppEUI",
")",
"{",
"appEUI",
"=",
"&",
"AppEUI",
"{",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"randRead",
"(",
"r",
",",
"appEUI",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // NewPopulatedAppEUI returns random AppEUI | [
"NewPopulatedAppEUI",
"returns",
"random",
"AppEUI"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/random.go#L41-L47 | train |
TheThingsNetwork/ttn | core/types/random.go | NewPopulatedDevEUI | func NewPopulatedDevEUI(r Rand) (devEUI *DevEUI) {
devEUI = &DevEUI{}
if _, err := randRead(r, devEUI[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedDevEUI: %s", err))
}
return
} | go | func NewPopulatedDevEUI(r Rand) (devEUI *DevEUI) {
devEUI = &DevEUI{}
if _, err := randRead(r, devEUI[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedDevEUI: %s", err))
}
return
} | [
"func",
"NewPopulatedDevEUI",
"(",
"r",
"Rand",
")",
"(",
"devEUI",
"*",
"DevEUI",
")",
"{",
"devEUI",
"=",
"&",
"DevEUI",
"{",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"randRead",
"(",
"r",
",",
"devEUI",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // NewPopulatedDevEUI returns random DevEUI | [
"NewPopulatedDevEUI",
"returns",
"random",
"DevEUI"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/random.go#L50-L56 | train |
TheThingsNetwork/ttn | core/types/random.go | NewPopulatedAppKey | func NewPopulatedAppKey(r Rand) (key *AppKey) {
key = &AppKey{}
if _, err := randRead(r, key[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedAppKey: %s", err))
}
return
} | go | func NewPopulatedAppKey(r Rand) (key *AppKey) {
key = &AppKey{}
if _, err := randRead(r, key[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedAppKey: %s", err))
}
return
} | [
"func",
"NewPopulatedAppKey",
"(",
"r",
"Rand",
")",
"(",
"key",
"*",
"AppKey",
")",
"{",
"key",
"=",
"&",
"AppKey",
"{",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"randRead",
"(",
"r",
",",
"key",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // NewPopulatedAppKey returns random AppKey | [
"NewPopulatedAppKey",
"returns",
"random",
"AppKey"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/random.go#L59-L65 | train |
TheThingsNetwork/ttn | core/types/random.go | NewPopulatedAppSKey | func NewPopulatedAppSKey(r Rand) (key *AppSKey) {
key = &AppSKey{}
if _, err := randRead(r, key[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedAppSKey: %s", err))
}
return
} | go | func NewPopulatedAppSKey(r Rand) (key *AppSKey) {
key = &AppSKey{}
if _, err := randRead(r, key[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedAppSKey: %s", err))
}
return
} | [
"func",
"NewPopulatedAppSKey",
"(",
"r",
"Rand",
")",
"(",
"key",
"*",
"AppSKey",
")",
"{",
"key",
"=",
"&",
"AppSKey",
"{",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"randRead",
"(",
"r",
",",
"key",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // NewPopulatedAppSKey returns random AppSKey | [
"NewPopulatedAppSKey",
"returns",
"random",
"AppSKey"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/random.go#L68-L74 | train |
TheThingsNetwork/ttn | core/types/random.go | NewPopulatedNwkSKey | func NewPopulatedNwkSKey(r Rand) (key *NwkSKey) {
key = &NwkSKey{}
if _, err := randRead(r, key[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedNwkSKey: %s", err))
}
return
} | go | func NewPopulatedNwkSKey(r Rand) (key *NwkSKey) {
key = &NwkSKey{}
if _, err := randRead(r, key[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedNwkSKey: %s", err))
}
return
} | [
"func",
"NewPopulatedNwkSKey",
"(",
"r",
"Rand",
")",
"(",
"key",
"*",
"NwkSKey",
")",
"{",
"key",
"=",
"&",
"NwkSKey",
"{",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"randRead",
"(",
"r",
",",
"key",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // NewPopulatedNwkSKey returns random NwkSKey | [
"NewPopulatedNwkSKey",
"returns",
"random",
"NwkSKey"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/random.go#L77-L83 | train |
TheThingsNetwork/ttn | core/types/random.go | NewPopulatedDevNonce | func NewPopulatedDevNonce(r Rand) (nonce *DevNonce) {
nonce = &DevNonce{}
if _, err := randRead(r, nonce[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedDevNonce: %s", err))
}
return
} | go | func NewPopulatedDevNonce(r Rand) (nonce *DevNonce) {
nonce = &DevNonce{}
if _, err := randRead(r, nonce[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedDevNonce: %s", err))
}
return
} | [
"func",
"NewPopulatedDevNonce",
"(",
"r",
"Rand",
")",
"(",
"nonce",
"*",
"DevNonce",
")",
"{",
"nonce",
"=",
"&",
"DevNonce",
"{",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"randRead",
"(",
"r",
",",
"nonce",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // NewPopulatedDevNonce returns random DevNonce | [
"NewPopulatedDevNonce",
"returns",
"random",
"DevNonce"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/random.go#L86-L92 | train |
TheThingsNetwork/ttn | core/types/random.go | NewPopulatedAppNonce | func NewPopulatedAppNonce(r Rand) (nonce *AppNonce) {
nonce = &AppNonce{}
if _, err := randRead(r, nonce[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedAppNonce: %s", err))
}
return
} | go | func NewPopulatedAppNonce(r Rand) (nonce *AppNonce) {
nonce = &AppNonce{}
if _, err := randRead(r, nonce[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedAppNonce: %s", err))
}
return
} | [
"func",
"NewPopulatedAppNonce",
"(",
"r",
"Rand",
")",
"(",
"nonce",
"*",
"AppNonce",
")",
"{",
"nonce",
"=",
"&",
"AppNonce",
"{",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"randRead",
"(",
"r",
",",
"nonce",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // NewPopulatedAppNonce returns random AppNonce | [
"NewPopulatedAppNonce",
"returns",
"random",
"AppNonce"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/random.go#L95-L101 | train |
TheThingsNetwork/ttn | core/types/random.go | NewPopulatedNetID | func NewPopulatedNetID(r Rand) (id *NetID) {
id = &NetID{}
if _, err := randRead(r, id[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedNetID: %s", err))
}
return
} | go | func NewPopulatedNetID(r Rand) (id *NetID) {
id = &NetID{}
if _, err := randRead(r, id[:]); err != nil {
panic(fmt.Errorf("types.NewPopulatedNetID: %s", err))
}
return
} | [
"func",
"NewPopulatedNetID",
"(",
"r",
"Rand",
")",
"(",
"id",
"*",
"NetID",
")",
"{",
"id",
"=",
"&",
"NetID",
"{",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"randRead",
"(",
"r",
",",
"id",
"[",
":",
"]",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // NewPopulatedNetID returns random NetID | [
"NewPopulatedNetID",
"returns",
"random",
"NetID"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/random.go#L104-L110 | train |
TheThingsNetwork/ttn | core/router/gateway/utilization.go | NewUtilization | func NewUtilization() Utilization {
return &utilization{
overallRx: metrics.NewEWMA1(),
channelRx: map[uint64]metrics.EWMA{},
overallTx: metrics.NewEWMA1(),
channelTx: map[uint64]metrics.EWMA{},
}
} | go | func NewUtilization() Utilization {
return &utilization{
overallRx: metrics.NewEWMA1(),
channelRx: map[uint64]metrics.EWMA{},
overallTx: metrics.NewEWMA1(),
channelTx: map[uint64]metrics.EWMA{},
}
} | [
"func",
"NewUtilization",
"(",
")",
"Utilization",
"{",
"return",
"&",
"utilization",
"{",
"overallRx",
":",
"metrics",
".",
"NewEWMA1",
"(",
")",
",",
"channelRx",
":",
"map",
"[",
"uint64",
"]",
"metrics",
".",
"EWMA",
"{",
"}",
",",
"overallTx",
":",
"metrics",
".",
"NewEWMA1",
"(",
")",
",",
"channelTx",
":",
"map",
"[",
"uint64",
"]",
"metrics",
".",
"EWMA",
"{",
"}",
",",
"}",
"\n",
"}"
] | // NewUtilization creates a new Utilization | [
"NewUtilization",
"creates",
"a",
"new",
"Utilization"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/router/gateway/utilization.go#L34-L41 | train |
TheThingsNetwork/ttn | core/handler/device/migrate/2_4_1_downlink_queue.go | DownlinkQueue | func DownlinkQueue(prefix string) storage.MigrateFunction {
return func(client *redis.Client, key string, obj map[string]string) (string, map[string]string, error) {
var err error
nextDownlink, ok := obj["next_downlink"]
if ok {
delete(obj, "next_downlink")
scheduleKey := prefix + ":downlink" + strings.TrimPrefix(key, prefix+":device")
err = client.LPush(scheduleKey, nextDownlink).Err()
}
return "2.4.2", obj, err
}
} | go | func DownlinkQueue(prefix string) storage.MigrateFunction {
return func(client *redis.Client, key string, obj map[string]string) (string, map[string]string, error) {
var err error
nextDownlink, ok := obj["next_downlink"]
if ok {
delete(obj, "next_downlink")
scheduleKey := prefix + ":downlink" + strings.TrimPrefix(key, prefix+":device")
err = client.LPush(scheduleKey, nextDownlink).Err()
}
return "2.4.2", obj, err
}
} | [
"func",
"DownlinkQueue",
"(",
"prefix",
"string",
")",
"storage",
".",
"MigrateFunction",
"{",
"return",
"func",
"(",
"client",
"*",
"redis",
".",
"Client",
",",
"key",
"string",
",",
"obj",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"string",
",",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"nextDownlink",
",",
"ok",
":=",
"obj",
"[",
"\"",
"\"",
"]",
"\n",
"if",
"ok",
"{",
"delete",
"(",
"obj",
",",
"\"",
"\"",
")",
"\n",
"scheduleKey",
":=",
"prefix",
"+",
"\"",
"\"",
"+",
"strings",
".",
"TrimPrefix",
"(",
"key",
",",
"prefix",
"+",
"\"",
"\"",
")",
"\n",
"err",
"=",
"client",
".",
"LPush",
"(",
"scheduleKey",
",",
"nextDownlink",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"obj",
",",
"err",
"\n",
"}",
"\n",
"}"
] | // DownlinkQueue migration from 2.4.1 to 2.5.0 | [
"DownlinkQueue",
"migration",
"from",
"2",
".",
"4",
".",
"1",
"to",
"2",
".",
"5",
".",
"0"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/migrate/2_4_1_downlink_queue.go#L14-L25 | train |
TheThingsNetwork/ttn | ttnctl/cmd/root.go | init | func init() {
cobra.OnInitialize(initConfig)
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.ttnctl.yml)")
RootCmd.PersistentFlags().StringVar(&dataDir, "data", "", "directory where ttnctl stores data (default is $HOME/.ttnctl)")
RootCmd.PersistentFlags().String("discovery-address", "discover.thethingsnetwork.org:1900", "The address of the Discovery server")
RootCmd.PersistentFlags().String("router-id", "ttn-router-eu", "The ID of the TTN Router as announced in the Discovery server")
RootCmd.PersistentFlags().String("handler-id", "ttn-handler-eu", "The ID of the TTN Handler as announced in the Discovery server")
RootCmd.PersistentFlags().String("mqtt-address", "eu.thethings.network:1883", "The address of the MQTT broker")
RootCmd.PersistentFlags().String("mqtt-username", "", "The username for the MQTT broker")
RootCmd.PersistentFlags().String("mqtt-password", "", "The password for the MQTT broker")
RootCmd.PersistentFlags().String("auth-server", "https://account.thethingsnetwork.org", "The address of the OAuth 2.0 server")
RootCmd.PersistentFlags().Bool("allow-insecure", false, "Allow insecure fallback if TLS unavailable")
viper.SetDefault("gateway-id", "dev")
viper.SetDefault("gateway-token", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0dG4tYWNjb3VudC12MiIsInN1YiI6ImRldiIsInR5cGUiOiJnYXRld2F5IiwiaWF0IjoxNDgyNDIxMTEyfQ.obhobeREK9bOpi-YO5lZ8rpW4CkXZUSrRBRIjbFThhvAsj_IjkFmCovIVLsGlaDVEKciZmXmWnY-6ZEgUEu6H6_GG4AD6HNHXnT0o0XSPgf5_Bc6dpzuI5FCEpcELihpBMaW3vPUt29NecLo4LvZGAuOllUYKHsZi34GYnR6PFlOgi40drN_iU_8aMCxFxm6ki83QlcyHEmDAh5GAGIym0qnUDh5_L1VE_upmoR72j8_l5lSuUA2_w8CH5_Z9CrXlTKQ2XQXsQXprkhbmOKKC8rfbTjRsB_nxObu0qcTWLH9tMd4KGFkJ20mdMw38fg2Vt7eLrkU1R1kl6a65eo6LZi0JvRSsboVZFWLwI02Azkwsm903K5n1r25Wq2oiwPJpNq5vsYLdYlb-WdAPsEDnfQGLPaqxd5we8tDcHsF4C1JHTwLsKy2Sqj8WNVmLgXiFER0DNfISDgS5SYdOxd9dUf5lTlIYdJU6aG1yYLSEhq80QOcdhCqNMVu1uRIucn_BhHbKo_LCMmD7TGppaXcQ2tCL3qHQaW8GCoun_UPo4C67LIMYUMfwd_h6CaykzlZvDlLa64ZiQ3XPmMcT_gVT7MJS2jGPbtJmcLHAVa5NZLv2d6WZfutPAocl3bYrY-sQmaSwJrzakIb2D-DNsg0qBJAZcm2o021By8U4bKAAFQ")
viper.BindPFlags(RootCmd.PersistentFlags())
} | go | func init() {
cobra.OnInitialize(initConfig)
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.ttnctl.yml)")
RootCmd.PersistentFlags().StringVar(&dataDir, "data", "", "directory where ttnctl stores data (default is $HOME/.ttnctl)")
RootCmd.PersistentFlags().String("discovery-address", "discover.thethingsnetwork.org:1900", "The address of the Discovery server")
RootCmd.PersistentFlags().String("router-id", "ttn-router-eu", "The ID of the TTN Router as announced in the Discovery server")
RootCmd.PersistentFlags().String("handler-id", "ttn-handler-eu", "The ID of the TTN Handler as announced in the Discovery server")
RootCmd.PersistentFlags().String("mqtt-address", "eu.thethings.network:1883", "The address of the MQTT broker")
RootCmd.PersistentFlags().String("mqtt-username", "", "The username for the MQTT broker")
RootCmd.PersistentFlags().String("mqtt-password", "", "The password for the MQTT broker")
RootCmd.PersistentFlags().String("auth-server", "https://account.thethingsnetwork.org", "The address of the OAuth 2.0 server")
RootCmd.PersistentFlags().Bool("allow-insecure", false, "Allow insecure fallback if TLS unavailable")
viper.SetDefault("gateway-id", "dev")
viper.SetDefault("gateway-token", "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ0dG4tYWNjb3VudC12MiIsInN1YiI6ImRldiIsInR5cGUiOiJnYXRld2F5IiwiaWF0IjoxNDgyNDIxMTEyfQ.obhobeREK9bOpi-YO5lZ8rpW4CkXZUSrRBRIjbFThhvAsj_IjkFmCovIVLsGlaDVEKciZmXmWnY-6ZEgUEu6H6_GG4AD6HNHXnT0o0XSPgf5_Bc6dpzuI5FCEpcELihpBMaW3vPUt29NecLo4LvZGAuOllUYKHsZi34GYnR6PFlOgi40drN_iU_8aMCxFxm6ki83QlcyHEmDAh5GAGIym0qnUDh5_L1VE_upmoR72j8_l5lSuUA2_w8CH5_Z9CrXlTKQ2XQXsQXprkhbmOKKC8rfbTjRsB_nxObu0qcTWLH9tMd4KGFkJ20mdMw38fg2Vt7eLrkU1R1kl6a65eo6LZi0JvRSsboVZFWLwI02Azkwsm903K5n1r25Wq2oiwPJpNq5vsYLdYlb-WdAPsEDnfQGLPaqxd5we8tDcHsF4C1JHTwLsKy2Sqj8WNVmLgXiFER0DNfISDgS5SYdOxd9dUf5lTlIYdJU6aG1yYLSEhq80QOcdhCqNMVu1uRIucn_BhHbKo_LCMmD7TGppaXcQ2tCL3qHQaW8GCoun_UPo4C67LIMYUMfwd_h6CaykzlZvDlLa64ZiQ3XPmMcT_gVT7MJS2jGPbtJmcLHAVa5NZLv2d6WZfutPAocl3bYrY-sQmaSwJrzakIb2D-DNsg0qBJAZcm2o021By8U4bKAAFQ")
viper.BindPFlags(RootCmd.PersistentFlags())
} | [
"func",
"init",
"(",
")",
"{",
"cobra",
".",
"OnInitialize",
"(",
"initConfig",
")",
"\n\n",
"RootCmd",
".",
"PersistentFlags",
"(",
")",
".",
"StringVar",
"(",
"&",
"cfgFile",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"RootCmd",
".",
"PersistentFlags",
"(",
")",
".",
"StringVar",
"(",
"&",
"dataDir",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"RootCmd",
".",
"PersistentFlags",
"(",
")",
".",
"String",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"RootCmd",
".",
"PersistentFlags",
"(",
")",
".",
"String",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"RootCmd",
".",
"PersistentFlags",
"(",
")",
".",
"String",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"RootCmd",
".",
"PersistentFlags",
"(",
")",
".",
"String",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"RootCmd",
".",
"PersistentFlags",
"(",
")",
".",
"String",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"RootCmd",
".",
"PersistentFlags",
"(",
")",
".",
"String",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"RootCmd",
".",
"PersistentFlags",
"(",
")",
".",
"String",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"RootCmd",
".",
"PersistentFlags",
"(",
")",
".",
"Bool",
"(",
"\"",
"\"",
",",
"false",
",",
"\"",
"\"",
")",
"\n\n",
"viper",
".",
"SetDefault",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"viper",
".",
"SetDefault",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"viper",
".",
"BindPFlags",
"(",
"RootCmd",
".",
"PersistentFlags",
"(",
")",
")",
"\n",
"}"
] | // init initializes the configuration and command line flags | [
"init",
"initializes",
"the",
"configuration",
"and",
"command",
"line",
"flags"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/cmd/root.go#L68-L86 | train |
TheThingsNetwork/ttn | utils/elasticsearch/handler/elasticsearch.go | indexName | func (h *Handler) indexName() string {
return fmt.Sprintf("%s-%s", h.Config.Prefix, time.Now().Format("2006.01.02"))
} | go | func (h *Handler) indexName() string {
return fmt.Sprintf("%s-%s", h.Config.Prefix, time.Now().Format("2006.01.02"))
} | [
"func",
"(",
"h",
"*",
"Handler",
")",
"indexName",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"h",
".",
"Config",
".",
"Prefix",
",",
"time",
".",
"Now",
"(",
")",
".",
"Format",
"(",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // indexName returns the index for the configured | [
"indexName",
"returns",
"the",
"index",
"for",
"the",
"configured"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/elasticsearch/handler/elasticsearch.go#L54-L56 | train |
TheThingsNetwork/ttn | core/types/keys.go | ParseAES128Key | func ParseAES128Key(input string) (key AES128Key, err error) {
bytes, err := ParseHEX(input, 16)
if err != nil {
return
}
copy(key[:], bytes)
return
} | go | func ParseAES128Key(input string) (key AES128Key, err error) {
bytes, err := ParseHEX(input, 16)
if err != nil {
return
}
copy(key[:], bytes)
return
} | [
"func",
"ParseAES128Key",
"(",
"input",
"string",
")",
"(",
"key",
"AES128Key",
",",
"err",
"error",
")",
"{",
"bytes",
",",
"err",
":=",
"ParseHEX",
"(",
"input",
",",
"16",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"copy",
"(",
"key",
"[",
":",
"]",
",",
"bytes",
")",
"\n",
"return",
"\n",
"}"
] | // ParseAES128Key parses a 128-bit hex-encoded string to an AES128Key | [
"ParseAES128Key",
"parses",
"a",
"128",
"-",
"bit",
"hex",
"-",
"encoded",
"string",
"to",
"an",
"AES128Key"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/keys.go#L26-L33 | train |
TheThingsNetwork/ttn | core/types/keys.go | ParseAppKey | func ParseAppKey(input string) (key AppKey, err error) {
aes128key, err := ParseAES128Key(input)
if err != nil {
return
}
key = AppKey(aes128key)
return
} | go | func ParseAppKey(input string) (key AppKey, err error) {
aes128key, err := ParseAES128Key(input)
if err != nil {
return
}
key = AppKey(aes128key)
return
} | [
"func",
"ParseAppKey",
"(",
"input",
"string",
")",
"(",
"key",
"AppKey",
",",
"err",
"error",
")",
"{",
"aes128key",
",",
"err",
":=",
"ParseAES128Key",
"(",
"input",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"key",
"=",
"AppKey",
"(",
"aes128key",
")",
"\n",
"return",
"\n",
"}"
] | // ParseAppKey parses a 64-bit hex-encoded string to an AppKey | [
"ParseAppKey",
"parses",
"a",
"64",
"-",
"bit",
"hex",
"-",
"encoded",
"string",
"to",
"an",
"AppKey"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/keys.go#L110-L117 | train |
TheThingsNetwork/ttn | core/types/keys.go | ParseAppSKey | func ParseAppSKey(input string) (key AppSKey, err error) {
aes128key, err := ParseAES128Key(input)
if err != nil {
return
}
key = AppSKey(aes128key)
return
} | go | func ParseAppSKey(input string) (key AppSKey, err error) {
aes128key, err := ParseAES128Key(input)
if err != nil {
return
}
key = AppSKey(aes128key)
return
} | [
"func",
"ParseAppSKey",
"(",
"input",
"string",
")",
"(",
"key",
"AppSKey",
",",
"err",
"error",
")",
"{",
"aes128key",
",",
"err",
":=",
"ParseAES128Key",
"(",
"input",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"key",
"=",
"AppSKey",
"(",
"aes128key",
")",
"\n",
"return",
"\n",
"}"
] | // ParseAppSKey parses a 64-bit hex-encoded string to an AppSKey | [
"ParseAppSKey",
"parses",
"a",
"64",
"-",
"bit",
"hex",
"-",
"encoded",
"string",
"to",
"an",
"AppSKey"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/keys.go#L193-L200 | train |
TheThingsNetwork/ttn | core/types/keys.go | ParseNwkSKey | func ParseNwkSKey(input string) (key NwkSKey, err error) {
aes128key, err := ParseAES128Key(input)
if err != nil {
return
}
key = NwkSKey(aes128key)
return
} | go | func ParseNwkSKey(input string) (key NwkSKey, err error) {
aes128key, err := ParseAES128Key(input)
if err != nil {
return
}
key = NwkSKey(aes128key)
return
} | [
"func",
"ParseNwkSKey",
"(",
"input",
"string",
")",
"(",
"key",
"NwkSKey",
",",
"err",
"error",
")",
"{",
"aes128key",
",",
"err",
":=",
"ParseAES128Key",
"(",
"input",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"key",
"=",
"NwkSKey",
"(",
"aes128key",
")",
"\n",
"return",
"\n",
"}"
] | // ParseNwkSKey parses a 64-bit hex-encoded string to an NwkSKey | [
"ParseNwkSKey",
"parses",
"a",
"64",
"-",
"bit",
"hex",
"-",
"encoded",
"string",
"to",
"an",
"NwkSKey"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/keys.go#L276-L283 | train |
TheThingsNetwork/ttn | core/storage/redis_map_store.go | NewRedisMapStore | func NewRedisMapStore(client *redis.Client, prefix string) *RedisMapStore {
if !strings.HasSuffix(prefix, ":") {
prefix += ":"
}
return &RedisMapStore{
RedisStore: NewRedisStore(client, prefix),
migrations: make(map[string]MigrateFunction),
}
} | go | func NewRedisMapStore(client *redis.Client, prefix string) *RedisMapStore {
if !strings.HasSuffix(prefix, ":") {
prefix += ":"
}
return &RedisMapStore{
RedisStore: NewRedisStore(client, prefix),
migrations: make(map[string]MigrateFunction),
}
} | [
"func",
"NewRedisMapStore",
"(",
"client",
"*",
"redis",
".",
"Client",
",",
"prefix",
"string",
")",
"*",
"RedisMapStore",
"{",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"prefix",
",",
"\"",
"\"",
")",
"{",
"prefix",
"+=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"&",
"RedisMapStore",
"{",
"RedisStore",
":",
"NewRedisStore",
"(",
"client",
",",
"prefix",
")",
",",
"migrations",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"MigrateFunction",
")",
",",
"}",
"\n",
"}"
] | // NewRedisMapStore returns a new RedisMapStore that talks to the given Redis client and respects the given prefix | [
"NewRedisMapStore",
"returns",
"a",
"new",
"RedisMapStore",
"that",
"talks",
"to",
"the",
"given",
"Redis",
"client",
"and",
"respects",
"the",
"given",
"prefix"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L24-L32 | train |
TheThingsNetwork/ttn | core/storage/redis_map_store.go | SetBase | func (s *RedisMapStore) SetBase(base interface{}, tagName string) {
if tagName == "" {
tagName = "redis"
}
s.SetEncoder(func(input interface{}, properties ...string) (map[string]string, error) {
return encoding.ToStringStringMap(tagName, input, properties...)
})
s.SetDecoder(func(input map[string]string) (output interface{}, err error) {
return encoding.FromStringStringMap(tagName, base, input)
})
} | go | func (s *RedisMapStore) SetBase(base interface{}, tagName string) {
if tagName == "" {
tagName = "redis"
}
s.SetEncoder(func(input interface{}, properties ...string) (map[string]string, error) {
return encoding.ToStringStringMap(tagName, input, properties...)
})
s.SetDecoder(func(input map[string]string) (output interface{}, err error) {
return encoding.FromStringStringMap(tagName, base, input)
})
} | [
"func",
"(",
"s",
"*",
"RedisMapStore",
")",
"SetBase",
"(",
"base",
"interface",
"{",
"}",
",",
"tagName",
"string",
")",
"{",
"if",
"tagName",
"==",
"\"",
"\"",
"{",
"tagName",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"s",
".",
"SetEncoder",
"(",
"func",
"(",
"input",
"interface",
"{",
"}",
",",
"properties",
"...",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"return",
"encoding",
".",
"ToStringStringMap",
"(",
"tagName",
",",
"input",
",",
"properties",
"...",
")",
"\n",
"}",
")",
"\n",
"s",
".",
"SetDecoder",
"(",
"func",
"(",
"input",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"output",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"return",
"encoding",
".",
"FromStringStringMap",
"(",
"tagName",
",",
"base",
",",
"input",
")",
"\n",
"}",
")",
"\n",
"}"
] | // SetBase sets the base struct for automatically encoding and decoding to and from Redis format | [
"SetBase",
"sets",
"the",
"base",
"struct",
"for",
"automatically",
"encoding",
"and",
"decoding",
"to",
"and",
"from",
"Redis",
"format"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L35-L45 | train |
TheThingsNetwork/ttn | core/storage/redis_map_store.go | SetEncoder | func (s *RedisMapStore) SetEncoder(encoder func(input interface{}, properties ...string) (map[string]string, error)) {
s.encoder = encoder
} | go | func (s *RedisMapStore) SetEncoder(encoder func(input interface{}, properties ...string) (map[string]string, error)) {
s.encoder = encoder
} | [
"func",
"(",
"s",
"*",
"RedisMapStore",
")",
"SetEncoder",
"(",
"encoder",
"func",
"(",
"input",
"interface",
"{",
"}",
",",
"properties",
"...",
"string",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
")",
"{",
"s",
".",
"encoder",
"=",
"encoder",
"\n",
"}"
] | // SetEncoder sets the encoder to convert structs to Redis format | [
"SetEncoder",
"sets",
"the",
"encoder",
"to",
"convert",
"structs",
"to",
"Redis",
"format"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L48-L50 | train |
TheThingsNetwork/ttn | core/storage/redis_map_store.go | SetDecoder | func (s *RedisMapStore) SetDecoder(decoder func(input map[string]string) (output interface{}, err error)) {
s.decoder = decoder
} | go | func (s *RedisMapStore) SetDecoder(decoder func(input map[string]string) (output interface{}, err error)) {
s.decoder = decoder
} | [
"func",
"(",
"s",
"*",
"RedisMapStore",
")",
"SetDecoder",
"(",
"decoder",
"func",
"(",
"input",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"output",
"interface",
"{",
"}",
",",
"err",
"error",
")",
")",
"{",
"s",
".",
"decoder",
"=",
"decoder",
"\n",
"}"
] | // SetDecoder sets the decoder to convert structs from Redis format | [
"SetDecoder",
"sets",
"the",
"decoder",
"to",
"convert",
"structs",
"from",
"Redis",
"format"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L53-L55 | train |
TheThingsNetwork/ttn | core/storage/redis_map_store.go | GetAll | func (s *RedisMapStore) GetAll(keys []string, options *ListOptions) ([]interface{}, error) {
if len(keys) == 0 {
return []interface{}{}, nil
}
for i, key := range keys {
if !strings.HasPrefix(key, s.prefix) {
keys[i] = s.prefix + key
}
}
sort.Strings(keys)
selectedKeys := selectKeys(keys, options)
if len(selectedKeys) == 0 {
return []interface{}{}, nil
}
pipe := s.client.Pipeline()
defer pipe.Close()
// Add all commands to pipeline
cmds := make(map[string]*redis.StringStringMapCmd)
for _, key := range selectedKeys {
cmds[key] = pipe.HGetAll(key)
}
// Execute pipeline
_, err := pipe.Exec()
if err != nil {
return nil, err
}
// Get all results from pipeline
results := make([]interface{}, len(selectedKeys))
for i, key := range selectedKeys {
if result, err := cmds[key].Result(); err == nil {
result, _ = s.migrate(key, result)
if result, err := s.decoder(result); err == nil {
results[i] = result
}
}
}
return results, nil
} | go | func (s *RedisMapStore) GetAll(keys []string, options *ListOptions) ([]interface{}, error) {
if len(keys) == 0 {
return []interface{}{}, nil
}
for i, key := range keys {
if !strings.HasPrefix(key, s.prefix) {
keys[i] = s.prefix + key
}
}
sort.Strings(keys)
selectedKeys := selectKeys(keys, options)
if len(selectedKeys) == 0 {
return []interface{}{}, nil
}
pipe := s.client.Pipeline()
defer pipe.Close()
// Add all commands to pipeline
cmds := make(map[string]*redis.StringStringMapCmd)
for _, key := range selectedKeys {
cmds[key] = pipe.HGetAll(key)
}
// Execute pipeline
_, err := pipe.Exec()
if err != nil {
return nil, err
}
// Get all results from pipeline
results := make([]interface{}, len(selectedKeys))
for i, key := range selectedKeys {
if result, err := cmds[key].Result(); err == nil {
result, _ = s.migrate(key, result)
if result, err := s.decoder(result); err == nil {
results[i] = result
}
}
}
return results, nil
} | [
"func",
"(",
"s",
"*",
"RedisMapStore",
")",
"GetAll",
"(",
"keys",
"[",
"]",
"string",
",",
"options",
"*",
"ListOptions",
")",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"len",
"(",
"keys",
")",
"==",
"0",
"{",
"return",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"key",
":=",
"range",
"keys",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"key",
",",
"s",
".",
"prefix",
")",
"{",
"keys",
"[",
"i",
"]",
"=",
"s",
".",
"prefix",
"+",
"key",
"\n",
"}",
"\n",
"}",
"\n\n",
"sort",
".",
"Strings",
"(",
"keys",
")",
"\n\n",
"selectedKeys",
":=",
"selectKeys",
"(",
"keys",
",",
"options",
")",
"\n",
"if",
"len",
"(",
"selectedKeys",
")",
"==",
"0",
"{",
"return",
"[",
"]",
"interface",
"{",
"}",
"{",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"pipe",
":=",
"s",
".",
"client",
".",
"Pipeline",
"(",
")",
"\n",
"defer",
"pipe",
".",
"Close",
"(",
")",
"\n\n",
"// Add all commands to pipeline",
"cmds",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"redis",
".",
"StringStringMapCmd",
")",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"selectedKeys",
"{",
"cmds",
"[",
"key",
"]",
"=",
"pipe",
".",
"HGetAll",
"(",
"key",
")",
"\n",
"}",
"\n\n",
"// Execute pipeline",
"_",
",",
"err",
":=",
"pipe",
".",
"Exec",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Get all results from pipeline",
"results",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"len",
"(",
"selectedKeys",
")",
")",
"\n",
"for",
"i",
",",
"key",
":=",
"range",
"selectedKeys",
"{",
"if",
"result",
",",
"err",
":=",
"cmds",
"[",
"key",
"]",
".",
"Result",
"(",
")",
";",
"err",
"==",
"nil",
"{",
"result",
",",
"_",
"=",
"s",
".",
"migrate",
"(",
"key",
",",
"result",
")",
"\n",
"if",
"result",
",",
"err",
":=",
"s",
".",
"decoder",
"(",
"result",
")",
";",
"err",
"==",
"nil",
"{",
"results",
"[",
"i",
"]",
"=",
"result",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"results",
",",
"nil",
"\n",
"}"
] | // GetAll returns all results for the given keys, prepending the prefix to the keys if necessary
// This function will migrate outdated results to newer versions if migrations are set | [
"GetAll",
"returns",
"all",
"results",
"for",
"the",
"given",
"keys",
"prepending",
"the",
"prefix",
"to",
"the",
"keys",
"if",
"necessary",
"This",
"function",
"will",
"migrate",
"outdated",
"results",
"to",
"newer",
"versions",
"if",
"migrations",
"are",
"set"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L59-L104 | train |
TheThingsNetwork/ttn | core/storage/redis_map_store.go | Get | func (s *RedisMapStore) Get(key string) (interface{}, error) {
if !strings.HasPrefix(key, s.prefix) {
key = s.prefix + key
}
result, err := s.client.HGetAll(key).Result()
if err == redis.Nil || len(result) == 0 {
return nil, errors.NewErrNotFound(key)
}
if err != nil {
return nil, err
}
result, _ = s.migrate(key, result)
i, err := s.decoder(result)
if err != nil {
return nil, err
}
return i, nil
} | go | func (s *RedisMapStore) Get(key string) (interface{}, error) {
if !strings.HasPrefix(key, s.prefix) {
key = s.prefix + key
}
result, err := s.client.HGetAll(key).Result()
if err == redis.Nil || len(result) == 0 {
return nil, errors.NewErrNotFound(key)
}
if err != nil {
return nil, err
}
result, _ = s.migrate(key, result)
i, err := s.decoder(result)
if err != nil {
return nil, err
}
return i, nil
} | [
"func",
"(",
"s",
"*",
"RedisMapStore",
")",
"Get",
"(",
"key",
"string",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"key",
",",
"s",
".",
"prefix",
")",
"{",
"key",
"=",
"s",
".",
"prefix",
"+",
"key",
"\n",
"}",
"\n",
"result",
",",
"err",
":=",
"s",
".",
"client",
".",
"HGetAll",
"(",
"key",
")",
".",
"Result",
"(",
")",
"\n",
"if",
"err",
"==",
"redis",
".",
"Nil",
"||",
"len",
"(",
"result",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"errors",
".",
"NewErrNotFound",
"(",
"key",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"result",
",",
"_",
"=",
"s",
".",
"migrate",
"(",
"key",
",",
"result",
")",
"\n",
"i",
",",
"err",
":=",
"s",
".",
"decoder",
"(",
"result",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"i",
",",
"nil",
"\n",
"}"
] | // Get one result, prepending the prefix to the key if necessary
// This function will migrate outdated results to newer versions if migrations are set | [
"Get",
"one",
"result",
"prepending",
"the",
"prefix",
"to",
"the",
"key",
"if",
"necessary",
"This",
"function",
"will",
"migrate",
"outdated",
"results",
"to",
"newer",
"versions",
"if",
"migrations",
"are",
"set"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L117-L134 | train |
TheThingsNetwork/ttn | core/storage/redis_map_store.go | Set | func (s *RedisMapStore) Set(key string, value interface{}, properties ...string) error {
key, vmap, err := s.prepare(key, value, properties...)
if err != nil {
return err
}
if len(vmap) == 0 {
return nil
}
return s.client.HMSet(key, vmap).Err()
} | go | func (s *RedisMapStore) Set(key string, value interface{}, properties ...string) error {
key, vmap, err := s.prepare(key, value, properties...)
if err != nil {
return err
}
if len(vmap) == 0 {
return nil
}
return s.client.HMSet(key, vmap).Err()
} | [
"func",
"(",
"s",
"*",
"RedisMapStore",
")",
"Set",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
",",
"properties",
"...",
"string",
")",
"error",
"{",
"key",
",",
"vmap",
",",
"err",
":=",
"s",
".",
"prepare",
"(",
"key",
",",
"value",
",",
"properties",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"vmap",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"s",
".",
"client",
".",
"HMSet",
"(",
"key",
",",
"vmap",
")",
".",
"Err",
"(",
")",
"\n",
"}"
] | // Set a record, prepending the prefix to the key if necessary, optionally setting only the given properties | [
"Set",
"a",
"record",
"prepending",
"the",
"prefix",
"to",
"the",
"key",
"if",
"necessary",
"optionally",
"setting",
"only",
"the",
"given",
"properties"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L193-L202 | train |
TheThingsNetwork/ttn | core/storage/redis_map_store.go | Create | func (s *RedisMapStore) Create(key string, value interface{}, properties ...string) error {
key, vmap, err := s.prepare(key, value, properties...)
if err != nil {
return err
}
if len(vmap) == 0 {
return nil
}
err = s.client.Watch(func(tx *redis.Tx) error {
exists, err := tx.Exists(key).Result()
if err != nil {
return err
}
if exists {
return errors.NewErrAlreadyExists(key)
}
_, err = tx.Pipelined(func(pipe *redis.Pipeline) error {
pipe.HMSet(key, vmap)
return nil
})
if err != nil {
return err
}
return nil
}, key)
if err != nil {
return err
}
return nil
} | go | func (s *RedisMapStore) Create(key string, value interface{}, properties ...string) error {
key, vmap, err := s.prepare(key, value, properties...)
if err != nil {
return err
}
if len(vmap) == 0 {
return nil
}
err = s.client.Watch(func(tx *redis.Tx) error {
exists, err := tx.Exists(key).Result()
if err != nil {
return err
}
if exists {
return errors.NewErrAlreadyExists(key)
}
_, err = tx.Pipelined(func(pipe *redis.Pipeline) error {
pipe.HMSet(key, vmap)
return nil
})
if err != nil {
return err
}
return nil
}, key)
if err != nil {
return err
}
return nil
} | [
"func",
"(",
"s",
"*",
"RedisMapStore",
")",
"Create",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
",",
"properties",
"...",
"string",
")",
"error",
"{",
"key",
",",
"vmap",
",",
"err",
":=",
"s",
".",
"prepare",
"(",
"key",
",",
"value",
",",
"properties",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"vmap",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"err",
"=",
"s",
".",
"client",
".",
"Watch",
"(",
"func",
"(",
"tx",
"*",
"redis",
".",
"Tx",
")",
"error",
"{",
"exists",
",",
"err",
":=",
"tx",
".",
"Exists",
"(",
"key",
")",
".",
"Result",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"exists",
"{",
"return",
"errors",
".",
"NewErrAlreadyExists",
"(",
"key",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"tx",
".",
"Pipelined",
"(",
"func",
"(",
"pipe",
"*",
"redis",
".",
"Pipeline",
")",
"error",
"{",
"pipe",
".",
"HMSet",
"(",
"key",
",",
"vmap",
")",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
",",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Create a new record, prepending the prefix to the key if necessary, optionally setting only the given properties
// This function returns an error if the record already exists | [
"Create",
"a",
"new",
"record",
"prepending",
"the",
"prefix",
"to",
"the",
"key",
"if",
"necessary",
"optionally",
"setting",
"only",
"the",
"given",
"properties",
"This",
"function",
"returns",
"an",
"error",
"if",
"the",
"record",
"already",
"exists"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_map_store.go#L206-L235 | train |
TheThingsNetwork/ttn | utils/random/random.go | RSSI | func (r *TTNRandom) RSSI() int32 {
// Generate RSSI. Tend towards generating great signal strength.
x := float64(r.Interface.Intn(math.MaxInt32)) * float64(2e-9)
return int32(-1.6 * math.Exp(x))
} | go | func (r *TTNRandom) RSSI() int32 {
// Generate RSSI. Tend towards generating great signal strength.
x := float64(r.Interface.Intn(math.MaxInt32)) * float64(2e-9)
return int32(-1.6 * math.Exp(x))
} | [
"func",
"(",
"r",
"*",
"TTNRandom",
")",
"RSSI",
"(",
")",
"int32",
"{",
"// Generate RSSI. Tend towards generating great signal strength.",
"x",
":=",
"float64",
"(",
"r",
".",
"Interface",
".",
"Intn",
"(",
"math",
".",
"MaxInt32",
")",
")",
"*",
"float64",
"(",
"2e-9",
")",
"\n",
"return",
"int32",
"(",
"-",
"1.6",
"*",
"math",
".",
"Exp",
"(",
"x",
")",
")",
"\n",
"}"
] | // RSSI generates RSSI signal between -120 < rssi < 0 | [
"RSSI",
"generates",
"RSSI",
"signal",
"between",
"-",
"120",
"<",
"rssi",
"<",
"0"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/random/random.go#L74-L78 | train |
TheThingsNetwork/ttn | utils/random/random.go | Freq | func (r *TTNRandom) Freq() float32 {
return freqs[r.Interface.Intn(len(freqs))]
} | go | func (r *TTNRandom) Freq() float32 {
return freqs[r.Interface.Intn(len(freqs))]
} | [
"func",
"(",
"r",
"*",
"TTNRandom",
")",
"Freq",
"(",
")",
"float32",
"{",
"return",
"freqs",
"[",
"r",
".",
"Interface",
".",
"Intn",
"(",
"len",
"(",
"freqs",
")",
")",
"]",
"\n",
"}"
] | // Freq generates a frequency between 867.1 and 905.3 Mhz | [
"Freq",
"generates",
"a",
"frequency",
"between",
"867",
".",
"1",
"and",
"905",
".",
"3",
"Mhz"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/random/random.go#L105-L107 | train |
TheThingsNetwork/ttn | utils/random/random.go | LSNR | func (r *TTNRandom) LSNR() float32 {
x := float64(r.Interface.Intn(math.MaxInt32)) * float64(2e-9)
return float32(math.Floor((-0.1*math.Exp(x)+5.5)*10) / 10)
} | go | func (r *TTNRandom) LSNR() float32 {
x := float64(r.Interface.Intn(math.MaxInt32)) * float64(2e-9)
return float32(math.Floor((-0.1*math.Exp(x)+5.5)*10) / 10)
} | [
"func",
"(",
"r",
"*",
"TTNRandom",
")",
"LSNR",
"(",
")",
"float32",
"{",
"x",
":=",
"float64",
"(",
"r",
".",
"Interface",
".",
"Intn",
"(",
"math",
".",
"MaxInt32",
")",
")",
"*",
"float64",
"(",
"2e-9",
")",
"\n",
"return",
"float32",
"(",
"math",
".",
"Floor",
"(",
"(",
"-",
"0.1",
"*",
"math",
".",
"Exp",
"(",
"x",
")",
"+",
"5.5",
")",
"*",
"10",
")",
"/",
"10",
")",
"\n",
"}"
] | // LSNR generates LoRa SNR ratio in db. Tend towards generating good ratio with low noise | [
"LSNR",
"generates",
"LoRa",
"SNR",
"ratio",
"in",
"db",
".",
"Tend",
"towards",
"generating",
"good",
"ratio",
"with",
"low",
"noise"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/random/random.go#L131-L134 | train |
TheThingsNetwork/ttn | core/discovery/discovery.go | NewRedisDiscovery | func NewRedisDiscovery(client *redis.Client) Discovery {
return &discovery{
services: announcement.NewRedisAnnouncementStore(client, "discovery"),
masterAuthServers: make(map[string]struct{}),
}
} | go | func NewRedisDiscovery(client *redis.Client) Discovery {
return &discovery{
services: announcement.NewRedisAnnouncementStore(client, "discovery"),
masterAuthServers: make(map[string]struct{}),
}
} | [
"func",
"NewRedisDiscovery",
"(",
"client",
"*",
"redis",
".",
"Client",
")",
"Discovery",
"{",
"return",
"&",
"discovery",
"{",
"services",
":",
"announcement",
".",
"NewRedisAnnouncementStore",
"(",
"client",
",",
"\"",
"\"",
")",
",",
"masterAuthServers",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
",",
"}",
"\n",
"}"
] | // NewRedisDiscovery creates a new Redis-based discovery service | [
"NewRedisDiscovery",
"creates",
"a",
"new",
"Redis",
"-",
"based",
"discovery",
"service"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/discovery.go#L162-L167 | train |
TheThingsNetwork/ttn | core/handler/application/store.go | NewRedisApplicationStore | func NewRedisApplicationStore(client *redis.Client, prefix string) Store {
if prefix == "" {
prefix = defaultRedisPrefix
}
store := storage.NewRedisMapStore(client, prefix+":"+redisApplicationPrefix)
store.SetBase(Application{}, "")
for v, f := range migrate.ApplicationMigrations(prefix) {
store.AddMigration(v, f)
}
s := &RedisApplicationStore{
store: store,
}
countStore(s)
return s
} | go | func NewRedisApplicationStore(client *redis.Client, prefix string) Store {
if prefix == "" {
prefix = defaultRedisPrefix
}
store := storage.NewRedisMapStore(client, prefix+":"+redisApplicationPrefix)
store.SetBase(Application{}, "")
for v, f := range migrate.ApplicationMigrations(prefix) {
store.AddMigration(v, f)
}
s := &RedisApplicationStore{
store: store,
}
countStore(s)
return s
} | [
"func",
"NewRedisApplicationStore",
"(",
"client",
"*",
"redis",
".",
"Client",
",",
"prefix",
"string",
")",
"Store",
"{",
"if",
"prefix",
"==",
"\"",
"\"",
"{",
"prefix",
"=",
"defaultRedisPrefix",
"\n",
"}",
"\n",
"store",
":=",
"storage",
".",
"NewRedisMapStore",
"(",
"client",
",",
"prefix",
"+",
"\"",
"\"",
"+",
"redisApplicationPrefix",
")",
"\n",
"store",
".",
"SetBase",
"(",
"Application",
"{",
"}",
",",
"\"",
"\"",
")",
"\n",
"for",
"v",
",",
"f",
":=",
"range",
"migrate",
".",
"ApplicationMigrations",
"(",
"prefix",
")",
"{",
"store",
".",
"AddMigration",
"(",
"v",
",",
"f",
")",
"\n",
"}",
"\n",
"s",
":=",
"&",
"RedisApplicationStore",
"{",
"store",
":",
"store",
",",
"}",
"\n",
"countStore",
"(",
"s",
")",
"\n",
"return",
"s",
"\n",
"}"
] | // NewRedisApplicationStore creates a new Redis-based Application store
// if an empty prefix is passed, a default prefix will be used. | [
"NewRedisApplicationStore",
"creates",
"a",
"new",
"Redis",
"-",
"based",
"Application",
"store",
"if",
"an",
"empty",
"prefix",
"is",
"passed",
"a",
"default",
"prefix",
"will",
"be",
"used",
"."
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/application/store.go#L29-L43 | train |
TheThingsNetwork/ttn | core/handler/application/store.go | Get | func (s *RedisApplicationStore) Get(appID string) (*Application, error) {
applicationI, err := s.store.Get(appID)
if err != nil {
return nil, err
}
if application, ok := applicationI.(Application); ok {
return &application, nil
}
return nil, errors.New("Database did not return a Application")
} | go | func (s *RedisApplicationStore) Get(appID string) (*Application, error) {
applicationI, err := s.store.Get(appID)
if err != nil {
return nil, err
}
if application, ok := applicationI.(Application); ok {
return &application, nil
}
return nil, errors.New("Database did not return a Application")
} | [
"func",
"(",
"s",
"*",
"RedisApplicationStore",
")",
"Get",
"(",
"appID",
"string",
")",
"(",
"*",
"Application",
",",
"error",
")",
"{",
"applicationI",
",",
"err",
":=",
"s",
".",
"store",
".",
"Get",
"(",
"appID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"application",
",",
"ok",
":=",
"applicationI",
".",
"(",
"Application",
")",
";",
"ok",
"{",
"return",
"&",
"application",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Get a specific Application | [
"Get",
"a",
"specific",
"Application"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/application/store.go#L72-L81 | train |
TheThingsNetwork/ttn | core/handler/application/store.go | Set | func (s *RedisApplicationStore) Set(new *Application, properties ...string) (err error) {
now := time.Now()
new.UpdatedAt = now
if new.old == nil {
new.CreatedAt = now
}
err = s.store.Set(new.AppID, *new, properties...)
if err != nil {
return
}
return nil
} | go | func (s *RedisApplicationStore) Set(new *Application, properties ...string) (err error) {
now := time.Now()
new.UpdatedAt = now
if new.old == nil {
new.CreatedAt = now
}
err = s.store.Set(new.AppID, *new, properties...)
if err != nil {
return
}
return nil
} | [
"func",
"(",
"s",
"*",
"RedisApplicationStore",
")",
"Set",
"(",
"new",
"*",
"Application",
",",
"properties",
"...",
"string",
")",
"(",
"err",
"error",
")",
"{",
"now",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"new",
".",
"UpdatedAt",
"=",
"now",
"\n",
"if",
"new",
".",
"old",
"==",
"nil",
"{",
"new",
".",
"CreatedAt",
"=",
"now",
"\n",
"}",
"\n",
"err",
"=",
"s",
".",
"store",
".",
"Set",
"(",
"new",
".",
"AppID",
",",
"*",
"new",
",",
"properties",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Set a new Application or update an existing one | [
"Set",
"a",
"new",
"Application",
"or",
"update",
"an",
"existing",
"one"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/application/store.go#L84-L95 | train |
TheThingsNetwork/ttn | core/handler/application/store.go | Delete | func (s *RedisApplicationStore) Delete(appID string) error {
return s.store.Delete(appID)
} | go | func (s *RedisApplicationStore) Delete(appID string) error {
return s.store.Delete(appID)
} | [
"func",
"(",
"s",
"*",
"RedisApplicationStore",
")",
"Delete",
"(",
"appID",
"string",
")",
"error",
"{",
"return",
"s",
".",
"store",
".",
"Delete",
"(",
"appID",
")",
"\n",
"}"
] | // Delete an Application | [
"Delete",
"an",
"Application"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/application/store.go#L98-L100 | train |
TheThingsNetwork/ttn | core/component/status.go | RegisterHealthServer | func (c *Component) RegisterHealthServer(srv *grpc.Server) {
c.healthServer = health.NewServer()
healthpb.RegisterHealthServer(srv, c.healthServer)
grpc_prometheus.Register(srv)
} | go | func (c *Component) RegisterHealthServer(srv *grpc.Server) {
c.healthServer = health.NewServer()
healthpb.RegisterHealthServer(srv, c.healthServer)
grpc_prometheus.Register(srv)
} | [
"func",
"(",
"c",
"*",
"Component",
")",
"RegisterHealthServer",
"(",
"srv",
"*",
"grpc",
".",
"Server",
")",
"{",
"c",
".",
"healthServer",
"=",
"health",
".",
"NewServer",
"(",
")",
"\n",
"healthpb",
".",
"RegisterHealthServer",
"(",
"srv",
",",
"c",
".",
"healthServer",
")",
"\n",
"grpc_prometheus",
".",
"Register",
"(",
"srv",
")",
"\n",
"}"
] | // RegisterHealthServer registers the component's health status to the gRPC server | [
"RegisterHealthServer",
"registers",
"the",
"component",
"s",
"health",
"status",
"to",
"the",
"gRPC",
"server"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/status.go#L85-L89 | train |
TheThingsNetwork/ttn | core/handler/functions/logger.go | JSON | func JSON(val otto.Value) string {
vm := otto.New()
vm.Set("value", val)
res, _ := vm.Run(`JSON.stringify(value)`)
return res.String()
} | go | func JSON(val otto.Value) string {
vm := otto.New()
vm.Set("value", val)
res, _ := vm.Run(`JSON.stringify(value)`)
return res.String()
} | [
"func",
"JSON",
"(",
"val",
"otto",
".",
"Value",
")",
"string",
"{",
"vm",
":=",
"otto",
".",
"New",
"(",
")",
"\n",
"vm",
".",
"Set",
"(",
"\"",
"\"",
",",
"val",
")",
"\n",
"res",
",",
"_",
":=",
"vm",
".",
"Run",
"(",
"`JSON.stringify(value)`",
")",
"\n",
"return",
"res",
".",
"String",
"(",
")",
"\n",
"}"
] | // JSON stringifies a value inside of the otto vm, yielding better
// results than Export for Object-like class such as Date, but being much
// slower. | [
"JSON",
"stringifies",
"a",
"value",
"inside",
"of",
"the",
"otto",
"vm",
"yielding",
"better",
"results",
"than",
"Export",
"for",
"Object",
"-",
"like",
"class",
"such",
"as",
"Date",
"but",
"being",
"much",
"slower",
"."
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/functions/logger.go#L39-L44 | train |
TheThingsNetwork/ttn | ttnctl/util/uplink_metadata.go | GetProtocolMetadata | func GetProtocolMetadata(dataRate string) *protocol.RxMetadata {
return &protocol.RxMetadata{Protocol: &protocol.RxMetadata_LoRaWAN{LoRaWAN: &lorawan.Metadata{
CodingRate: "4/5",
DataRate: dataRate,
Modulation: lorawan.Modulation_LORA,
}}}
} | go | func GetProtocolMetadata(dataRate string) *protocol.RxMetadata {
return &protocol.RxMetadata{Protocol: &protocol.RxMetadata_LoRaWAN{LoRaWAN: &lorawan.Metadata{
CodingRate: "4/5",
DataRate: dataRate,
Modulation: lorawan.Modulation_LORA,
}}}
} | [
"func",
"GetProtocolMetadata",
"(",
"dataRate",
"string",
")",
"*",
"protocol",
".",
"RxMetadata",
"{",
"return",
"&",
"protocol",
".",
"RxMetadata",
"{",
"Protocol",
":",
"&",
"protocol",
".",
"RxMetadata_LoRaWAN",
"{",
"LoRaWAN",
":",
"&",
"lorawan",
".",
"Metadata",
"{",
"CodingRate",
":",
"\"",
"\"",
",",
"DataRate",
":",
"dataRate",
",",
"Modulation",
":",
"lorawan",
".",
"Modulation_LORA",
",",
"}",
"}",
"}",
"\n",
"}"
] | // GetProtocolMetadata returns protocol metadata for the given datarate | [
"GetProtocolMetadata",
"returns",
"protocol",
"metadata",
"for",
"the",
"given",
"datarate"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/uplink_metadata.go#L13-L19 | train |
TheThingsNetwork/ttn | ttnctl/util/uplink_metadata.go | GetGatewayMetadata | func GetGatewayMetadata(id string, freq uint64) *gateway.RxMetadata {
return &gateway.RxMetadata{
GatewayID: id,
Timestamp: 0,
Frequency: freq,
RSSI: -25.0,
SNR: 5.0,
}
} | go | func GetGatewayMetadata(id string, freq uint64) *gateway.RxMetadata {
return &gateway.RxMetadata{
GatewayID: id,
Timestamp: 0,
Frequency: freq,
RSSI: -25.0,
SNR: 5.0,
}
} | [
"func",
"GetGatewayMetadata",
"(",
"id",
"string",
",",
"freq",
"uint64",
")",
"*",
"gateway",
".",
"RxMetadata",
"{",
"return",
"&",
"gateway",
".",
"RxMetadata",
"{",
"GatewayID",
":",
"id",
",",
"Timestamp",
":",
"0",
",",
"Frequency",
":",
"freq",
",",
"RSSI",
":",
"-",
"25.0",
",",
"SNR",
":",
"5.0",
",",
"}",
"\n",
"}"
] | // GetGatewayMetadata returns gateway metadata for the given gateway ID and frequency | [
"GetGatewayMetadata",
"returns",
"gateway",
"metadata",
"for",
"the",
"given",
"gateway",
"ID",
"and",
"frequency"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/uplink_metadata.go#L22-L30 | train |
TheThingsNetwork/ttn | core/band/adr.go | ADRSettings | func (f *FrequencyPlan) ADRSettings(dataRate string, txPower int, snr float32, deviceMargin float32) (desiredDataRate string, desiredTxPower int, err error) {
if f.ADR == nil {
return dataRate, txPower, ErrADRUnavailable
}
margin := linkMargin(dataRate, snr) - deviceMargin
drIdx, err := f.GetDataRateIndexFor(dataRate)
if err != nil {
return dataRate, txPower, err
}
nStep := int(margin / 3)
// Increase the data rate with each step
for nStep > 0 && drIdx < f.ADR.MaxDataRate {
drIdx++
nStep--
}
nStep = int(float32(nStep*3) / float32(f.ADR.StepTXPower))
// Decrease the Tx power by f.ADR.StepTXPower for each step, until min reached
for nStep > 0 && txPower > f.ADR.MinTXPower {
txPower -= f.ADR.StepTXPower
nStep--
}
if txPower < f.ADR.MinTXPower {
txPower = f.ADR.MinTXPower
}
// Increase the Tx power by 3 for each step, until max reached
for nStep < 0 && txPower < f.ADR.MaxTXPower {
txPower += f.ADR.StepTXPower
nStep++
}
if txPower > f.ADR.MaxTXPower {
txPower = f.ADR.MaxTXPower
}
desiredDataRate, err = f.GetDataRateStringForIndex(drIdx)
if err != nil {
return dataRate, txPower, err // This should maybe panic; it means that f.ADR is incosistent with f.DataRates
}
return desiredDataRate, txPower, nil
} | go | func (f *FrequencyPlan) ADRSettings(dataRate string, txPower int, snr float32, deviceMargin float32) (desiredDataRate string, desiredTxPower int, err error) {
if f.ADR == nil {
return dataRate, txPower, ErrADRUnavailable
}
margin := linkMargin(dataRate, snr) - deviceMargin
drIdx, err := f.GetDataRateIndexFor(dataRate)
if err != nil {
return dataRate, txPower, err
}
nStep := int(margin / 3)
// Increase the data rate with each step
for nStep > 0 && drIdx < f.ADR.MaxDataRate {
drIdx++
nStep--
}
nStep = int(float32(nStep*3) / float32(f.ADR.StepTXPower))
// Decrease the Tx power by f.ADR.StepTXPower for each step, until min reached
for nStep > 0 && txPower > f.ADR.MinTXPower {
txPower -= f.ADR.StepTXPower
nStep--
}
if txPower < f.ADR.MinTXPower {
txPower = f.ADR.MinTXPower
}
// Increase the Tx power by 3 for each step, until max reached
for nStep < 0 && txPower < f.ADR.MaxTXPower {
txPower += f.ADR.StepTXPower
nStep++
}
if txPower > f.ADR.MaxTXPower {
txPower = f.ADR.MaxTXPower
}
desiredDataRate, err = f.GetDataRateStringForIndex(drIdx)
if err != nil {
return dataRate, txPower, err // This should maybe panic; it means that f.ADR is incosistent with f.DataRates
}
return desiredDataRate, txPower, nil
} | [
"func",
"(",
"f",
"*",
"FrequencyPlan",
")",
"ADRSettings",
"(",
"dataRate",
"string",
",",
"txPower",
"int",
",",
"snr",
"float32",
",",
"deviceMargin",
"float32",
")",
"(",
"desiredDataRate",
"string",
",",
"desiredTxPower",
"int",
",",
"err",
"error",
")",
"{",
"if",
"f",
".",
"ADR",
"==",
"nil",
"{",
"return",
"dataRate",
",",
"txPower",
",",
"ErrADRUnavailable",
"\n",
"}",
"\n",
"margin",
":=",
"linkMargin",
"(",
"dataRate",
",",
"snr",
")",
"-",
"deviceMargin",
"\n",
"drIdx",
",",
"err",
":=",
"f",
".",
"GetDataRateIndexFor",
"(",
"dataRate",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"dataRate",
",",
"txPower",
",",
"err",
"\n",
"}",
"\n",
"nStep",
":=",
"int",
"(",
"margin",
"/",
"3",
")",
"\n\n",
"// Increase the data rate with each step",
"for",
"nStep",
">",
"0",
"&&",
"drIdx",
"<",
"f",
".",
"ADR",
".",
"MaxDataRate",
"{",
"drIdx",
"++",
"\n",
"nStep",
"--",
"\n",
"}",
"\n\n",
"nStep",
"=",
"int",
"(",
"float32",
"(",
"nStep",
"*",
"3",
")",
"/",
"float32",
"(",
"f",
".",
"ADR",
".",
"StepTXPower",
")",
")",
"\n",
"// Decrease the Tx power by f.ADR.StepTXPower for each step, until min reached",
"for",
"nStep",
">",
"0",
"&&",
"txPower",
">",
"f",
".",
"ADR",
".",
"MinTXPower",
"{",
"txPower",
"-=",
"f",
".",
"ADR",
".",
"StepTXPower",
"\n",
"nStep",
"--",
"\n",
"}",
"\n",
"if",
"txPower",
"<",
"f",
".",
"ADR",
".",
"MinTXPower",
"{",
"txPower",
"=",
"f",
".",
"ADR",
".",
"MinTXPower",
"\n",
"}",
"\n\n",
"// Increase the Tx power by 3 for each step, until max reached",
"for",
"nStep",
"<",
"0",
"&&",
"txPower",
"<",
"f",
".",
"ADR",
".",
"MaxTXPower",
"{",
"txPower",
"+=",
"f",
".",
"ADR",
".",
"StepTXPower",
"\n",
"nStep",
"++",
"\n",
"}",
"\n",
"if",
"txPower",
">",
"f",
".",
"ADR",
".",
"MaxTXPower",
"{",
"txPower",
"=",
"f",
".",
"ADR",
".",
"MaxTXPower",
"\n",
"}",
"\n\n",
"desiredDataRate",
",",
"err",
"=",
"f",
".",
"GetDataRateStringForIndex",
"(",
"drIdx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"dataRate",
",",
"txPower",
",",
"err",
"// This should maybe panic; it means that f.ADR is incosistent with f.DataRates",
"\n",
"}",
"\n",
"return",
"desiredDataRate",
",",
"txPower",
",",
"nil",
"\n",
"}"
] | // ADRSettings gets the ADR settings given a dataRate, txPower, SNR and device margin | [
"ADRSettings",
"gets",
"the",
"ADR",
"settings",
"given",
"a",
"dataRate",
"txPower",
"SNR",
"and",
"device",
"margin"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/band/adr.go#L39-L80 | train |
TheThingsNetwork/ttn | core/band/band.go | Guess | func Guess(frequency uint64) string {
// Join frequencies
switch {
case frequency == 923200000 || frequency == 923400000:
// not considering AS_920_923 and AS_923_925 because we're not sure
return pb_lorawan.FrequencyPlan_AS_923.String()
case frequency == 922100000 || frequency == 922300000 || frequency == 922500000:
return pb_lorawan.FrequencyPlan_KR_920_923.String()
}
// Existing Channels
if region, ok := channels[int(frequency)]; ok {
return region
}
// Everything Else: not allowed
return ""
} | go | func Guess(frequency uint64) string {
// Join frequencies
switch {
case frequency == 923200000 || frequency == 923400000:
// not considering AS_920_923 and AS_923_925 because we're not sure
return pb_lorawan.FrequencyPlan_AS_923.String()
case frequency == 922100000 || frequency == 922300000 || frequency == 922500000:
return pb_lorawan.FrequencyPlan_KR_920_923.String()
}
// Existing Channels
if region, ok := channels[int(frequency)]; ok {
return region
}
// Everything Else: not allowed
return ""
} | [
"func",
"Guess",
"(",
"frequency",
"uint64",
")",
"string",
"{",
"// Join frequencies",
"switch",
"{",
"case",
"frequency",
"==",
"923200000",
"||",
"frequency",
"==",
"923400000",
":",
"// not considering AS_920_923 and AS_923_925 because we're not sure",
"return",
"pb_lorawan",
".",
"FrequencyPlan_AS_923",
".",
"String",
"(",
")",
"\n",
"case",
"frequency",
"==",
"922100000",
"||",
"frequency",
"==",
"922300000",
"||",
"frequency",
"==",
"922500000",
":",
"return",
"pb_lorawan",
".",
"FrequencyPlan_KR_920_923",
".",
"String",
"(",
")",
"\n",
"}",
"\n\n",
"// Existing Channels",
"if",
"region",
",",
"ok",
":=",
"channels",
"[",
"int",
"(",
"frequency",
")",
"]",
";",
"ok",
"{",
"return",
"region",
"\n",
"}",
"\n\n",
"// Everything Else: not allowed",
"return",
"\"",
"\"",
"\n",
"}"
] | // Guess the region based on frequency | [
"Guess",
"the",
"region",
"based",
"on",
"frequency"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/band/band.go#L50-L67 | train |
TheThingsNetwork/ttn | core/band/band.go | InitializeTables | func InitializeTables() {
initializeOnce.Do(func() {
frequencyPlans = make(map[string]FrequencyPlan)
channels = make(map[int]string)
for _, r := range []pb_lorawan.FrequencyPlan{ // ordering is important here
pb_lorawan.FrequencyPlan_EU_863_870,
pb_lorawan.FrequencyPlan_IN_865_867,
pb_lorawan.FrequencyPlan_US_902_928,
pb_lorawan.FrequencyPlan_CN_779_787,
pb_lorawan.FrequencyPlan_EU_433,
pb_lorawan.FrequencyPlan_AS_923,
pb_lorawan.FrequencyPlan_AS_920_923,
pb_lorawan.FrequencyPlan_AS_923_925,
pb_lorawan.FrequencyPlan_KR_920_923,
pb_lorawan.FrequencyPlan_AU_915_928,
pb_lorawan.FrequencyPlan_CN_470_510,
pb_lorawan.FrequencyPlan_RU_864_870,
} {
region := r.String()
frequencyPlans[region], _ = Get(region)
for _, ch := range frequencyPlans[region].UplinkChannels {
if len(ch.DataRates) > 1 { // ignore FSK channels
if _, ok := channels[ch.Frequency]; !ok { // ordering indicates priority
channels[ch.Frequency] = region
}
}
}
}
})
} | go | func InitializeTables() {
initializeOnce.Do(func() {
frequencyPlans = make(map[string]FrequencyPlan)
channels = make(map[int]string)
for _, r := range []pb_lorawan.FrequencyPlan{ // ordering is important here
pb_lorawan.FrequencyPlan_EU_863_870,
pb_lorawan.FrequencyPlan_IN_865_867,
pb_lorawan.FrequencyPlan_US_902_928,
pb_lorawan.FrequencyPlan_CN_779_787,
pb_lorawan.FrequencyPlan_EU_433,
pb_lorawan.FrequencyPlan_AS_923,
pb_lorawan.FrequencyPlan_AS_920_923,
pb_lorawan.FrequencyPlan_AS_923_925,
pb_lorawan.FrequencyPlan_KR_920_923,
pb_lorawan.FrequencyPlan_AU_915_928,
pb_lorawan.FrequencyPlan_CN_470_510,
pb_lorawan.FrequencyPlan_RU_864_870,
} {
region := r.String()
frequencyPlans[region], _ = Get(region)
for _, ch := range frequencyPlans[region].UplinkChannels {
if len(ch.DataRates) > 1 { // ignore FSK channels
if _, ok := channels[ch.Frequency]; !ok { // ordering indicates priority
channels[ch.Frequency] = region
}
}
}
}
})
} | [
"func",
"InitializeTables",
"(",
")",
"{",
"initializeOnce",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"frequencyPlans",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"FrequencyPlan",
")",
"\n",
"channels",
"=",
"make",
"(",
"map",
"[",
"int",
"]",
"string",
")",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"[",
"]",
"pb_lorawan",
".",
"FrequencyPlan",
"{",
"// ordering is important here",
"pb_lorawan",
".",
"FrequencyPlan_EU_863_870",
",",
"pb_lorawan",
".",
"FrequencyPlan_IN_865_867",
",",
"pb_lorawan",
".",
"FrequencyPlan_US_902_928",
",",
"pb_lorawan",
".",
"FrequencyPlan_CN_779_787",
",",
"pb_lorawan",
".",
"FrequencyPlan_EU_433",
",",
"pb_lorawan",
".",
"FrequencyPlan_AS_923",
",",
"pb_lorawan",
".",
"FrequencyPlan_AS_920_923",
",",
"pb_lorawan",
".",
"FrequencyPlan_AS_923_925",
",",
"pb_lorawan",
".",
"FrequencyPlan_KR_920_923",
",",
"pb_lorawan",
".",
"FrequencyPlan_AU_915_928",
",",
"pb_lorawan",
".",
"FrequencyPlan_CN_470_510",
",",
"pb_lorawan",
".",
"FrequencyPlan_RU_864_870",
",",
"}",
"{",
"region",
":=",
"r",
".",
"String",
"(",
")",
"\n",
"frequencyPlans",
"[",
"region",
"]",
",",
"_",
"=",
"Get",
"(",
"region",
")",
"\n",
"for",
"_",
",",
"ch",
":=",
"range",
"frequencyPlans",
"[",
"region",
"]",
".",
"UplinkChannels",
"{",
"if",
"len",
"(",
"ch",
".",
"DataRates",
")",
">",
"1",
"{",
"// ignore FSK channels",
"if",
"_",
",",
"ok",
":=",
"channels",
"[",
"ch",
".",
"Frequency",
"]",
";",
"!",
"ok",
"{",
"// ordering indicates priority",
"channels",
"[",
"ch",
".",
"Frequency",
"]",
"=",
"region",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n",
"}"
] | // InitializeTables initializes the frequency plan and channel tables. | [
"InitializeTables",
"initializes",
"the",
"frequency",
"plan",
"and",
"channel",
"tables",
"."
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/band/band.go#L205-L234 | train |
TheThingsNetwork/ttn | ttnctl/util/discovery.go | GetDiscovery | func GetDiscovery(ctx ttnlog.Interface) (*grpc.ClientConn, discovery.DiscoveryClient) {
path := path.Join(GetDataDir(), "/ca.cert")
cert, err := ioutil.ReadFile(path)
if err == nil && !pool.RootCAs.AppendCertsFromPEM(cert) {
ctx.Warnf("Could not add root certificates from %s", path)
}
conn, err := api.Dial(viper.GetString("discovery-address"))
if err != nil {
ctx.WithError(err).Fatal("Could not connect to Discovery server")
}
return conn, discovery.NewDiscoveryClient(conn)
} | go | func GetDiscovery(ctx ttnlog.Interface) (*grpc.ClientConn, discovery.DiscoveryClient) {
path := path.Join(GetDataDir(), "/ca.cert")
cert, err := ioutil.ReadFile(path)
if err == nil && !pool.RootCAs.AppendCertsFromPEM(cert) {
ctx.Warnf("Could not add root certificates from %s", path)
}
conn, err := api.Dial(viper.GetString("discovery-address"))
if err != nil {
ctx.WithError(err).Fatal("Could not connect to Discovery server")
}
return conn, discovery.NewDiscoveryClient(conn)
} | [
"func",
"GetDiscovery",
"(",
"ctx",
"ttnlog",
".",
"Interface",
")",
"(",
"*",
"grpc",
".",
"ClientConn",
",",
"discovery",
".",
"DiscoveryClient",
")",
"{",
"path",
":=",
"path",
".",
"Join",
"(",
"GetDataDir",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"cert",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"path",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"!",
"pool",
".",
"RootCAs",
".",
"AppendCertsFromPEM",
"(",
"cert",
")",
"{",
"ctx",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n\n",
"conn",
",",
"err",
":=",
"api",
".",
"Dial",
"(",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ctx",
".",
"WithError",
"(",
"err",
")",
".",
"Fatal",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"conn",
",",
"discovery",
".",
"NewDiscoveryClient",
"(",
"conn",
")",
"\n",
"}"
] | // GetDiscovery gets the Discovery client for ttnctl | [
"GetDiscovery",
"gets",
"the",
"Discovery",
"client",
"for",
"ttnctl"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/discovery.go#L19-L31 | train |
TheThingsNetwork/ttn | utils/security/generate_keys.go | GenerateKeypair | func GenerateKeypair(location string) error {
// Generate private key
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return err
}
privPEM, err := PrivatePEM(key)
if err != nil {
return err
}
pubPEM, err := PublicPEM(key)
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Clean(location+"/server.pub"), pubPEM, 0644)
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Clean(location+"/server.key"), privPEM, 0600)
if err != nil {
return err
}
return nil
} | go | func GenerateKeypair(location string) error {
// Generate private key
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return err
}
privPEM, err := PrivatePEM(key)
if err != nil {
return err
}
pubPEM, err := PublicPEM(key)
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Clean(location+"/server.pub"), pubPEM, 0644)
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Clean(location+"/server.key"), privPEM, 0600)
if err != nil {
return err
}
return nil
} | [
"func",
"GenerateKeypair",
"(",
"location",
"string",
")",
"error",
"{",
"// Generate private key",
"key",
",",
"err",
":=",
"ecdsa",
".",
"GenerateKey",
"(",
"elliptic",
".",
"P256",
"(",
")",
",",
"rand",
".",
"Reader",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"privPEM",
",",
"err",
":=",
"PrivatePEM",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"pubPEM",
",",
"err",
":=",
"PublicPEM",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"filepath",
".",
"Clean",
"(",
"location",
"+",
"\"",
"\"",
")",
",",
"pubPEM",
",",
"0644",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"filepath",
".",
"Clean",
"(",
"location",
"+",
"\"",
"\"",
")",
",",
"privPEM",
",",
"0600",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // GenerateKeypair generates a new keypair in the given location | [
"GenerateKeypair",
"generates",
"a",
"new",
"keypair",
"in",
"the",
"given",
"location"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/security/generate_keys.go#L25-L51 | train |
TheThingsNetwork/ttn | utils/security/generate_keys.go | GenerateCert | func GenerateCert(location string, commonName string, hostnames ...string) error {
privKey, err := LoadKeypair(location)
if err != nil {
return err
}
// Build Certificate
notBefore := time.Now()
notAfter := notBefore.Add(validFor)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return err
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
CommonName: commonName,
Organization: []string{"The Things Network"},
},
IsCA: true,
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
BasicConstraintsValid: true,
}
for _, h := range hostnames {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, h)
}
}
// Generate certificate
certBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, privKey.Public(), privKey)
if err != nil {
return err
}
certPEM := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: certBytes,
})
err = ioutil.WriteFile(filepath.Clean(location+"/server.cert"), certPEM, 0644)
if err != nil {
return err
}
return nil
} | go | func GenerateCert(location string, commonName string, hostnames ...string) error {
privKey, err := LoadKeypair(location)
if err != nil {
return err
}
// Build Certificate
notBefore := time.Now()
notAfter := notBefore.Add(validFor)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return err
}
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
CommonName: commonName,
Organization: []string{"The Things Network"},
},
IsCA: true,
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
BasicConstraintsValid: true,
}
for _, h := range hostnames {
if ip := net.ParseIP(h); ip != nil {
template.IPAddresses = append(template.IPAddresses, ip)
} else {
template.DNSNames = append(template.DNSNames, h)
}
}
// Generate certificate
certBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, privKey.Public(), privKey)
if err != nil {
return err
}
certPEM := pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE",
Bytes: certBytes,
})
err = ioutil.WriteFile(filepath.Clean(location+"/server.cert"), certPEM, 0644)
if err != nil {
return err
}
return nil
} | [
"func",
"GenerateCert",
"(",
"location",
"string",
",",
"commonName",
"string",
",",
"hostnames",
"...",
"string",
")",
"error",
"{",
"privKey",
",",
"err",
":=",
"LoadKeypair",
"(",
"location",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Build Certificate",
"notBefore",
":=",
"time",
".",
"Now",
"(",
")",
"\n",
"notAfter",
":=",
"notBefore",
".",
"Add",
"(",
"validFor",
")",
"\n",
"serialNumberLimit",
":=",
"new",
"(",
"big",
".",
"Int",
")",
".",
"Lsh",
"(",
"big",
".",
"NewInt",
"(",
"1",
")",
",",
"128",
")",
"\n",
"serialNumber",
",",
"err",
":=",
"rand",
".",
"Int",
"(",
"rand",
".",
"Reader",
",",
"serialNumberLimit",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"template",
":=",
"x509",
".",
"Certificate",
"{",
"SerialNumber",
":",
"serialNumber",
",",
"Subject",
":",
"pkix",
".",
"Name",
"{",
"CommonName",
":",
"commonName",
",",
"Organization",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
"}",
",",
"}",
",",
"IsCA",
":",
"true",
",",
"NotBefore",
":",
"notBefore",
",",
"NotAfter",
":",
"notAfter",
",",
"KeyUsage",
":",
"x509",
".",
"KeyUsageKeyEncipherment",
"|",
"x509",
".",
"KeyUsageDigitalSignature",
"|",
"x509",
".",
"KeyUsageCertSign",
",",
"ExtKeyUsage",
":",
"[",
"]",
"x509",
".",
"ExtKeyUsage",
"{",
"x509",
".",
"ExtKeyUsageServerAuth",
",",
"x509",
".",
"ExtKeyUsageClientAuth",
"}",
",",
"BasicConstraintsValid",
":",
"true",
",",
"}",
"\n",
"for",
"_",
",",
"h",
":=",
"range",
"hostnames",
"{",
"if",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"h",
")",
";",
"ip",
"!=",
"nil",
"{",
"template",
".",
"IPAddresses",
"=",
"append",
"(",
"template",
".",
"IPAddresses",
",",
"ip",
")",
"\n",
"}",
"else",
"{",
"template",
".",
"DNSNames",
"=",
"append",
"(",
"template",
".",
"DNSNames",
",",
"h",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Generate certificate",
"certBytes",
",",
"err",
":=",
"x509",
".",
"CreateCertificate",
"(",
"rand",
".",
"Reader",
",",
"&",
"template",
",",
"&",
"template",
",",
"privKey",
".",
"Public",
"(",
")",
",",
"privKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"certPEM",
":=",
"pem",
".",
"EncodeToMemory",
"(",
"&",
"pem",
".",
"Block",
"{",
"Type",
":",
"\"",
"\"",
",",
"Bytes",
":",
"certBytes",
",",
"}",
")",
"\n\n",
"err",
"=",
"ioutil",
".",
"WriteFile",
"(",
"filepath",
".",
"Clean",
"(",
"location",
"+",
"\"",
"\"",
")",
",",
"certPEM",
",",
"0644",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // GenerateCert generates a certificate for the given hostnames in the given location | [
"GenerateCert",
"generates",
"a",
"certificate",
"for",
"the",
"given",
"hostnames",
"in",
"the",
"given",
"location"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/security/generate_keys.go#L54-L105 | train |
TheThingsNetwork/ttn | core/discovery/announcement/migrate/announcement.go | AnnouncementMigrations | func AnnouncementMigrations(prefix string) map[string]storage.MigrateFunction {
funcs := make(map[string]storage.MigrateFunction)
for v, f := range announcementMigrations {
funcs[v] = f(prefix)
}
return funcs
} | go | func AnnouncementMigrations(prefix string) map[string]storage.MigrateFunction {
funcs := make(map[string]storage.MigrateFunction)
for v, f := range announcementMigrations {
funcs[v] = f(prefix)
}
return funcs
} | [
"func",
"AnnouncementMigrations",
"(",
"prefix",
"string",
")",
"map",
"[",
"string",
"]",
"storage",
".",
"MigrateFunction",
"{",
"funcs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"storage",
".",
"MigrateFunction",
")",
"\n",
"for",
"v",
",",
"f",
":=",
"range",
"announcementMigrations",
"{",
"funcs",
"[",
"v",
"]",
"=",
"f",
"(",
"prefix",
")",
"\n",
"}",
"\n",
"return",
"funcs",
"\n",
"}"
] | // AnnouncementMigrations filled with the prefix | [
"AnnouncementMigrations",
"filled",
"with",
"the",
"prefix"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/discovery/announcement/migrate/announcement.go#L13-L19 | train |
TheThingsNetwork/ttn | utils/errors/errors.go | GetErrType | func GetErrType(err error) ErrType {
switch errs.Cause(err).(type) {
case *ErrAlreadyExists:
return AlreadyExists
case *ErrInternal:
return Internal
case *ErrInvalidArgument:
return InvalidArgument
case *ErrNotFound:
return NotFound
case *ErrPermissionDenied:
return PermissionDenied
}
return Unknown
} | go | func GetErrType(err error) ErrType {
switch errs.Cause(err).(type) {
case *ErrAlreadyExists:
return AlreadyExists
case *ErrInternal:
return Internal
case *ErrInvalidArgument:
return InvalidArgument
case *ErrNotFound:
return NotFound
case *ErrPermissionDenied:
return PermissionDenied
}
return Unknown
} | [
"func",
"GetErrType",
"(",
"err",
"error",
")",
"ErrType",
"{",
"switch",
"errs",
".",
"Cause",
"(",
"err",
")",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ErrAlreadyExists",
":",
"return",
"AlreadyExists",
"\n",
"case",
"*",
"ErrInternal",
":",
"return",
"Internal",
"\n",
"case",
"*",
"ErrInvalidArgument",
":",
"return",
"InvalidArgument",
"\n",
"case",
"*",
"ErrNotFound",
":",
"return",
"NotFound",
"\n",
"case",
"*",
"ErrPermissionDenied",
":",
"return",
"PermissionDenied",
"\n",
"}",
"\n",
"return",
"Unknown",
"\n",
"}"
] | // GetErrType returns the type of err | [
"GetErrType",
"returns",
"the",
"type",
"of",
"err"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/errors/errors.go#L31-L45 | train |
TheThingsNetwork/ttn | utils/errors/errors.go | BuildGRPCError | func BuildGRPCError(err error) error {
if err == nil {
return nil
}
code := grpc.Code(err)
if code != codes.Unknown {
return err // it already is a gRPC error
}
switch errs.Cause(err).(type) {
case *ErrAlreadyExists:
code = codes.AlreadyExists
case *ErrInternal:
code = codes.Internal
case *ErrInvalidArgument:
code = codes.InvalidArgument
case *ErrNotFound:
code = codes.NotFound
case *ErrPermissionDenied:
code = codes.PermissionDenied
}
switch err {
case context.Canceled:
code = codes.Canceled
case io.EOF:
code = codes.OutOfRange
}
return grpc.Errorf(code, err.Error())
} | go | func BuildGRPCError(err error) error {
if err == nil {
return nil
}
code := grpc.Code(err)
if code != codes.Unknown {
return err // it already is a gRPC error
}
switch errs.Cause(err).(type) {
case *ErrAlreadyExists:
code = codes.AlreadyExists
case *ErrInternal:
code = codes.Internal
case *ErrInvalidArgument:
code = codes.InvalidArgument
case *ErrNotFound:
code = codes.NotFound
case *ErrPermissionDenied:
code = codes.PermissionDenied
}
switch err {
case context.Canceled:
code = codes.Canceled
case io.EOF:
code = codes.OutOfRange
}
return grpc.Errorf(code, err.Error())
} | [
"func",
"BuildGRPCError",
"(",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"code",
":=",
"grpc",
".",
"Code",
"(",
"err",
")",
"\n",
"if",
"code",
"!=",
"codes",
".",
"Unknown",
"{",
"return",
"err",
"// it already is a gRPC error",
"\n",
"}",
"\n",
"switch",
"errs",
".",
"Cause",
"(",
"err",
")",
".",
"(",
"type",
")",
"{",
"case",
"*",
"ErrAlreadyExists",
":",
"code",
"=",
"codes",
".",
"AlreadyExists",
"\n",
"case",
"*",
"ErrInternal",
":",
"code",
"=",
"codes",
".",
"Internal",
"\n",
"case",
"*",
"ErrInvalidArgument",
":",
"code",
"=",
"codes",
".",
"InvalidArgument",
"\n",
"case",
"*",
"ErrNotFound",
":",
"code",
"=",
"codes",
".",
"NotFound",
"\n",
"case",
"*",
"ErrPermissionDenied",
":",
"code",
"=",
"codes",
".",
"PermissionDenied",
"\n",
"}",
"\n",
"switch",
"err",
"{",
"case",
"context",
".",
"Canceled",
":",
"code",
"=",
"codes",
".",
"Canceled",
"\n",
"case",
"io",
".",
"EOF",
":",
"code",
"=",
"codes",
".",
"OutOfRange",
"\n",
"}",
"\n",
"return",
"grpc",
".",
"Errorf",
"(",
"code",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}"
] | // BuildGRPCError returns the error with a GRPC code | [
"BuildGRPCError",
"returns",
"the",
"error",
"with",
"a",
"GRPC",
"code"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/errors/errors.go#L73-L100 | train |
TheThingsNetwork/ttn | utils/errors/errors.go | FromGRPCError | func FromGRPCError(err error) error {
if err == nil {
return nil
}
if GetErrType(err) != Unknown {
return err
}
code := grpc.Code(err)
desc := grpc.ErrorDesc(err)
switch code {
case codes.AlreadyExists:
return NewErrAlreadyExists(strings.TrimSuffix(desc, " already exists"))
case codes.Internal:
return NewErrInternal(strings.TrimPrefix(desc, "Internal error: "))
case codes.InvalidArgument:
if split := strings.Split(desc, " not valid: "); len(split) == 2 {
return NewErrInvalidArgument(split[0], split[1])
}
return NewErrInvalidArgument("Argument", desc)
case codes.NotFound:
return NewErrNotFound(strings.TrimSuffix(desc, " not found"))
case codes.PermissionDenied:
return NewErrPermissionDenied(strings.TrimPrefix(desc, "permission denied: "))
case codes.Unknown: // This also includes all non-gRPC errors
if desc == "EOF" {
return io.EOF
}
return errs.New(desc)
}
return NewErrInternal(fmt.Sprintf("[%s] %s", code, desc))
} | go | func FromGRPCError(err error) error {
if err == nil {
return nil
}
if GetErrType(err) != Unknown {
return err
}
code := grpc.Code(err)
desc := grpc.ErrorDesc(err)
switch code {
case codes.AlreadyExists:
return NewErrAlreadyExists(strings.TrimSuffix(desc, " already exists"))
case codes.Internal:
return NewErrInternal(strings.TrimPrefix(desc, "Internal error: "))
case codes.InvalidArgument:
if split := strings.Split(desc, " not valid: "); len(split) == 2 {
return NewErrInvalidArgument(split[0], split[1])
}
return NewErrInvalidArgument("Argument", desc)
case codes.NotFound:
return NewErrNotFound(strings.TrimSuffix(desc, " not found"))
case codes.PermissionDenied:
return NewErrPermissionDenied(strings.TrimPrefix(desc, "permission denied: "))
case codes.Unknown: // This also includes all non-gRPC errors
if desc == "EOF" {
return io.EOF
}
return errs.New(desc)
}
return NewErrInternal(fmt.Sprintf("[%s] %s", code, desc))
} | [
"func",
"FromGRPCError",
"(",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"GetErrType",
"(",
"err",
")",
"!=",
"Unknown",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"code",
":=",
"grpc",
".",
"Code",
"(",
"err",
")",
"\n",
"desc",
":=",
"grpc",
".",
"ErrorDesc",
"(",
"err",
")",
"\n",
"switch",
"code",
"{",
"case",
"codes",
".",
"AlreadyExists",
":",
"return",
"NewErrAlreadyExists",
"(",
"strings",
".",
"TrimSuffix",
"(",
"desc",
",",
"\"",
"\"",
")",
")",
"\n",
"case",
"codes",
".",
"Internal",
":",
"return",
"NewErrInternal",
"(",
"strings",
".",
"TrimPrefix",
"(",
"desc",
",",
"\"",
"\"",
")",
")",
"\n",
"case",
"codes",
".",
"InvalidArgument",
":",
"if",
"split",
":=",
"strings",
".",
"Split",
"(",
"desc",
",",
"\"",
"\"",
")",
";",
"len",
"(",
"split",
")",
"==",
"2",
"{",
"return",
"NewErrInvalidArgument",
"(",
"split",
"[",
"0",
"]",
",",
"split",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"return",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"desc",
")",
"\n",
"case",
"codes",
".",
"NotFound",
":",
"return",
"NewErrNotFound",
"(",
"strings",
".",
"TrimSuffix",
"(",
"desc",
",",
"\"",
"\"",
")",
")",
"\n",
"case",
"codes",
".",
"PermissionDenied",
":",
"return",
"NewErrPermissionDenied",
"(",
"strings",
".",
"TrimPrefix",
"(",
"desc",
",",
"\"",
"\"",
")",
")",
"\n",
"case",
"codes",
".",
"Unknown",
":",
"// This also includes all non-gRPC errors",
"if",
"desc",
"==",
"\"",
"\"",
"{",
"return",
"io",
".",
"EOF",
"\n",
"}",
"\n",
"return",
"errs",
".",
"New",
"(",
"desc",
")",
"\n",
"}",
"\n",
"return",
"NewErrInternal",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"code",
",",
"desc",
")",
")",
"\n",
"}"
] | // FromGRPCError creates a regular error with the same type as the gRPC error | [
"FromGRPCError",
"creates",
"a",
"regular",
"error",
"with",
"the",
"same",
"type",
"as",
"the",
"gRPC",
"error"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/errors/errors.go#L103-L135 | train |
TheThingsNetwork/ttn | utils/errors/errors.go | NewErrInvalidArgument | func NewErrInvalidArgument(argument string, reason string) error {
return &ErrInvalidArgument{argument: argument, reason: reason}
} | go | func NewErrInvalidArgument(argument string, reason string) error {
return &ErrInvalidArgument{argument: argument, reason: reason}
} | [
"func",
"NewErrInvalidArgument",
"(",
"argument",
"string",
",",
"reason",
"string",
")",
"error",
"{",
"return",
"&",
"ErrInvalidArgument",
"{",
"argument",
":",
"argument",
",",
"reason",
":",
"reason",
"}",
"\n",
"}"
] | // NewErrInvalidArgument returns a new ErrInvalidArgument for the given entitiy | [
"NewErrInvalidArgument",
"returns",
"a",
"new",
"ErrInvalidArgument",
"for",
"the",
"given",
"entitiy"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/errors/errors.go#L168-L170 | train |
TheThingsNetwork/ttn | utils/errors/errors.go | Wrapf | func Wrapf(err error, format string, args ...interface{}) error {
return errs.Wrapf(err, format, args...)
} | go | func Wrapf(err error, format string, args ...interface{}) error {
return errs.Wrapf(err, format, args...)
} | [
"func",
"Wrapf",
"(",
"err",
"error",
",",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"errs",
".",
"Wrapf",
"(",
"err",
",",
"format",
",",
"args",
"...",
")",
"\n",
"}"
] | // Wrapf returns an error annotating err with the format specifier.
// If err is nil, Wrapf returns nil. | [
"Wrapf",
"returns",
"an",
"error",
"annotating",
"err",
"with",
"the",
"format",
"specifier",
".",
"If",
"err",
"is",
"nil",
"Wrapf",
"returns",
"nil",
"."
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/errors/errors.go#L215-L217 | train |
TheThingsNetwork/ttn | utils/errors/errors.go | Wrap | func Wrap(err error, message string) error {
return errs.Wrap(err, message)
} | go | func Wrap(err error, message string) error {
return errs.Wrap(err, message)
} | [
"func",
"Wrap",
"(",
"err",
"error",
",",
"message",
"string",
")",
"error",
"{",
"return",
"errs",
".",
"Wrap",
"(",
"err",
",",
"message",
")",
"\n",
"}"
] | // Wrap returns an error annotating err with message.
// If err is nil, Wrap returns nil. | [
"Wrap",
"returns",
"an",
"error",
"annotating",
"err",
"with",
"message",
".",
"If",
"err",
"is",
"nil",
"Wrap",
"returns",
"nil",
"."
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/errors/errors.go#L221-L223 | train |
TheThingsNetwork/ttn | core/storage/redis_store.go | NewRedisStore | func NewRedisStore(client *redis.Client, prefix string) *RedisStore {
if !strings.HasSuffix(prefix, ":") {
prefix += ":"
}
return &RedisStore{
client: client,
prefix: prefix,
}
} | go | func NewRedisStore(client *redis.Client, prefix string) *RedisStore {
if !strings.HasSuffix(prefix, ":") {
prefix += ":"
}
return &RedisStore{
client: client,
prefix: prefix,
}
} | [
"func",
"NewRedisStore",
"(",
"client",
"*",
"redis",
".",
"Client",
",",
"prefix",
"string",
")",
"*",
"RedisStore",
"{",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"prefix",
",",
"\"",
"\"",
")",
"{",
"prefix",
"+=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"&",
"RedisStore",
"{",
"client",
":",
"client",
",",
"prefix",
":",
"prefix",
",",
"}",
"\n",
"}"
] | // NewRedisStore creates a new RedisStore | [
"NewRedisStore",
"creates",
"a",
"new",
"RedisStore"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_store.go#L19-L27 | train |
TheThingsNetwork/ttn | core/storage/redis_store.go | Keys | func (s *RedisStore) Keys(selector string, opts *ListOptions) ([]string, error) {
if opts != nil && opts.cacheKey != "" {
cacheExists, err := s.client.Exists(opts.cacheKey).Result()
if err != nil {
return nil, err
}
if cacheExists {
res, err := s.client.SMembers(opts.cacheKey).Result()
if err == nil {
return res, nil
}
}
}
if selector == "" {
selector = "*"
}
if !strings.HasPrefix(selector, s.prefix) {
selector = s.prefix + selector
}
var allKeys []string
var cursor uint64
for {
keys, next, err := s.client.Scan(cursor, selector, 10000).Result()
if err != nil {
return nil, err
}
allKeys = append(allKeys, keys...)
cursor = next
if cursor == 0 {
break
}
}
if opts != nil && opts.cacheKey != "" {
pipe := s.client.Pipeline()
defer pipe.Close()
pipe.Del(opts.cacheKey)
if len(allKeys) > 0 {
var allKeysAsInterface = make([]interface{}, len(allKeys))
for i, key := range allKeys {
allKeysAsInterface[i] = key
}
pipe.SAdd(opts.cacheKey, allKeysAsInterface...)
if opts.cacheTTL > 0 {
pipe.Expire(opts.cacheKey, opts.cacheTTL)
}
}
pipe.Exec()
}
return allKeys, nil
} | go | func (s *RedisStore) Keys(selector string, opts *ListOptions) ([]string, error) {
if opts != nil && opts.cacheKey != "" {
cacheExists, err := s.client.Exists(opts.cacheKey).Result()
if err != nil {
return nil, err
}
if cacheExists {
res, err := s.client.SMembers(opts.cacheKey).Result()
if err == nil {
return res, nil
}
}
}
if selector == "" {
selector = "*"
}
if !strings.HasPrefix(selector, s.prefix) {
selector = s.prefix + selector
}
var allKeys []string
var cursor uint64
for {
keys, next, err := s.client.Scan(cursor, selector, 10000).Result()
if err != nil {
return nil, err
}
allKeys = append(allKeys, keys...)
cursor = next
if cursor == 0 {
break
}
}
if opts != nil && opts.cacheKey != "" {
pipe := s.client.Pipeline()
defer pipe.Close()
pipe.Del(opts.cacheKey)
if len(allKeys) > 0 {
var allKeysAsInterface = make([]interface{}, len(allKeys))
for i, key := range allKeys {
allKeysAsInterface[i] = key
}
pipe.SAdd(opts.cacheKey, allKeysAsInterface...)
if opts.cacheTTL > 0 {
pipe.Expire(opts.cacheKey, opts.cacheTTL)
}
}
pipe.Exec()
}
return allKeys, nil
} | [
"func",
"(",
"s",
"*",
"RedisStore",
")",
"Keys",
"(",
"selector",
"string",
",",
"opts",
"*",
"ListOptions",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"opts",
"!=",
"nil",
"&&",
"opts",
".",
"cacheKey",
"!=",
"\"",
"\"",
"{",
"cacheExists",
",",
"err",
":=",
"s",
".",
"client",
".",
"Exists",
"(",
"opts",
".",
"cacheKey",
")",
".",
"Result",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"cacheExists",
"{",
"res",
",",
"err",
":=",
"s",
".",
"client",
".",
"SMembers",
"(",
"opts",
".",
"cacheKey",
")",
".",
"Result",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"res",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"selector",
"==",
"\"",
"\"",
"{",
"selector",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"selector",
",",
"s",
".",
"prefix",
")",
"{",
"selector",
"=",
"s",
".",
"prefix",
"+",
"selector",
"\n",
"}",
"\n",
"var",
"allKeys",
"[",
"]",
"string",
"\n",
"var",
"cursor",
"uint64",
"\n",
"for",
"{",
"keys",
",",
"next",
",",
"err",
":=",
"s",
".",
"client",
".",
"Scan",
"(",
"cursor",
",",
"selector",
",",
"10000",
")",
".",
"Result",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"allKeys",
"=",
"append",
"(",
"allKeys",
",",
"keys",
"...",
")",
"\n",
"cursor",
"=",
"next",
"\n",
"if",
"cursor",
"==",
"0",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"opts",
"!=",
"nil",
"&&",
"opts",
".",
"cacheKey",
"!=",
"\"",
"\"",
"{",
"pipe",
":=",
"s",
".",
"client",
".",
"Pipeline",
"(",
")",
"\n",
"defer",
"pipe",
".",
"Close",
"(",
")",
"\n",
"pipe",
".",
"Del",
"(",
"opts",
".",
"cacheKey",
")",
"\n",
"if",
"len",
"(",
"allKeys",
")",
">",
"0",
"{",
"var",
"allKeysAsInterface",
"=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"len",
"(",
"allKeys",
")",
")",
"\n",
"for",
"i",
",",
"key",
":=",
"range",
"allKeys",
"{",
"allKeysAsInterface",
"[",
"i",
"]",
"=",
"key",
"\n",
"}",
"\n",
"pipe",
".",
"SAdd",
"(",
"opts",
".",
"cacheKey",
",",
"allKeysAsInterface",
"...",
")",
"\n",
"if",
"opts",
".",
"cacheTTL",
">",
"0",
"{",
"pipe",
".",
"Expire",
"(",
"opts",
".",
"cacheKey",
",",
"opts",
".",
"cacheTTL",
")",
"\n",
"}",
"\n",
"}",
"\n",
"pipe",
".",
"Exec",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"allKeys",
",",
"nil",
"\n",
"}"
] | // Keys matching the selector, prepending the prefix to the selector if necessary | [
"Keys",
"matching",
"the",
"selector",
"prepending",
"the",
"prefix",
"to",
"the",
"selector",
"if",
"necessary"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_store.go#L30-L82 | train |
TheThingsNetwork/ttn | core/storage/redis_store.go | Count | func (s *RedisStore) Count(selector string, options *ListOptions) (int, error) {
allKeys, err := s.Keys(selector, options)
if err != nil {
return 0, err
}
return len(allKeys), nil
} | go | func (s *RedisStore) Count(selector string, options *ListOptions) (int, error) {
allKeys, err := s.Keys(selector, options)
if err != nil {
return 0, err
}
return len(allKeys), nil
} | [
"func",
"(",
"s",
"*",
"RedisStore",
")",
"Count",
"(",
"selector",
"string",
",",
"options",
"*",
"ListOptions",
")",
"(",
"int",
",",
"error",
")",
"{",
"allKeys",
",",
"err",
":=",
"s",
".",
"Keys",
"(",
"selector",
",",
"options",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"len",
"(",
"allKeys",
")",
",",
"nil",
"\n",
"}"
] | // Count the results matching the selector | [
"Count",
"the",
"results",
"matching",
"the",
"selector"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_store.go#L85-L91 | train |
TheThingsNetwork/ttn | core/storage/redis_store.go | Delete | func (s *RedisStore) Delete(key string) error {
if !strings.HasPrefix(key, s.prefix) {
key = s.prefix + key
}
return s.client.Del(key).Err()
} | go | func (s *RedisStore) Delete(key string) error {
if !strings.HasPrefix(key, s.prefix) {
key = s.prefix + key
}
return s.client.Del(key).Err()
} | [
"func",
"(",
"s",
"*",
"RedisStore",
")",
"Delete",
"(",
"key",
"string",
")",
"error",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"key",
",",
"s",
".",
"prefix",
")",
"{",
"key",
"=",
"s",
".",
"prefix",
"+",
"key",
"\n",
"}",
"\n",
"return",
"s",
".",
"client",
".",
"Del",
"(",
"key",
")",
".",
"Err",
"(",
")",
"\n",
"}"
] | // Delete an existing record, prepending the prefix to the key if necessary | [
"Delete",
"an",
"existing",
"record",
"prepending",
"the",
"prefix",
"to",
"the",
"key",
"if",
"necessary"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/storage/redis_store.go#L94-L99 | train |
TheThingsNetwork/ttn | mqtt/client.go | Connect | func (c *DefaultClient) Connect() error {
if c.mqtt.IsConnected() {
return nil
}
var err error
for retries := 0; retries < ConnectRetries; retries++ {
token := c.mqtt.Connect()
finished := token.WaitTimeout(1 * time.Second)
if !finished {
c.ctx.Warn("mqtt: connection took longer than expected...")
token.Wait()
}
err = token.Error()
if err == nil {
break
}
c.ctx.Warnf("mqtt: could not connect (%s), retrying...", err)
<-time.After(ConnectRetryDelay)
}
if err != nil {
return fmt.Errorf("Could not connect to MQTT Broker (%s)", err)
}
return nil
} | go | func (c *DefaultClient) Connect() error {
if c.mqtt.IsConnected() {
return nil
}
var err error
for retries := 0; retries < ConnectRetries; retries++ {
token := c.mqtt.Connect()
finished := token.WaitTimeout(1 * time.Second)
if !finished {
c.ctx.Warn("mqtt: connection took longer than expected...")
token.Wait()
}
err = token.Error()
if err == nil {
break
}
c.ctx.Warnf("mqtt: could not connect (%s), retrying...", err)
<-time.After(ConnectRetryDelay)
}
if err != nil {
return fmt.Errorf("Could not connect to MQTT Broker (%s)", err)
}
return nil
} | [
"func",
"(",
"c",
"*",
"DefaultClient",
")",
"Connect",
"(",
")",
"error",
"{",
"if",
"c",
".",
"mqtt",
".",
"IsConnected",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"for",
"retries",
":=",
"0",
";",
"retries",
"<",
"ConnectRetries",
";",
"retries",
"++",
"{",
"token",
":=",
"c",
".",
"mqtt",
".",
"Connect",
"(",
")",
"\n",
"finished",
":=",
"token",
".",
"WaitTimeout",
"(",
"1",
"*",
"time",
".",
"Second",
")",
"\n",
"if",
"!",
"finished",
"{",
"c",
".",
"ctx",
".",
"Warn",
"(",
"\"",
"\"",
")",
"\n",
"token",
".",
"Wait",
"(",
")",
"\n",
"}",
"\n",
"err",
"=",
"token",
".",
"Error",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"c",
".",
"ctx",
".",
"Warnf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"<-",
"time",
".",
"After",
"(",
"ConnectRetryDelay",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Connect to the MQTT broker. It will retry for ConnectRetries times with a delay of ConnectRetryDelay between retries | [
"Connect",
"to",
"the",
"MQTT",
"broker",
".",
"It",
"will",
"retry",
"for",
"ConnectRetries",
"times",
"with",
"a",
"delay",
"of",
"ConnectRetryDelay",
"between",
"retries"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/client.go#L214-L237 | train |
TheThingsNetwork/ttn | mqtt/client.go | Disconnect | func (c *DefaultClient) Disconnect() {
if !c.mqtt.IsConnected() {
return
}
c.ctx.Debug("mqtt: disconnecting")
c.mqtt.Disconnect(25)
} | go | func (c *DefaultClient) Disconnect() {
if !c.mqtt.IsConnected() {
return
}
c.ctx.Debug("mqtt: disconnecting")
c.mqtt.Disconnect(25)
} | [
"func",
"(",
"c",
"*",
"DefaultClient",
")",
"Disconnect",
"(",
")",
"{",
"if",
"!",
"c",
".",
"mqtt",
".",
"IsConnected",
"(",
")",
"{",
"return",
"\n",
"}",
"\n",
"c",
".",
"ctx",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n",
"c",
".",
"mqtt",
".",
"Disconnect",
"(",
"25",
")",
"\n",
"}"
] | // Disconnect from the MQTT broker | [
"Disconnect",
"from",
"the",
"MQTT",
"broker"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/client.go#L254-L260 | train |
TheThingsNetwork/ttn | ttnctl/util/lorawan.go | SetDevice | func (m *Message) SetDevice(devAddr types.DevAddr, nwkSKey types.NwkSKey, appSKey types.AppSKey) {
m.devAddr = devAddr
m.nwkSKey = nwkSKey
m.appSKey = appSKey
} | go | func (m *Message) SetDevice(devAddr types.DevAddr, nwkSKey types.NwkSKey, appSKey types.AppSKey) {
m.devAddr = devAddr
m.nwkSKey = nwkSKey
m.appSKey = appSKey
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"SetDevice",
"(",
"devAddr",
"types",
".",
"DevAddr",
",",
"nwkSKey",
"types",
".",
"NwkSKey",
",",
"appSKey",
"types",
".",
"AppSKey",
")",
"{",
"m",
".",
"devAddr",
"=",
"devAddr",
"\n",
"m",
".",
"nwkSKey",
"=",
"nwkSKey",
"\n",
"m",
".",
"appSKey",
"=",
"appSKey",
"\n",
"}"
] | // SetDevice with the LoRaWAN options | [
"SetDevice",
"with",
"the",
"LoRaWAN",
"options"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/lorawan.go#L27-L31 | train |
TheThingsNetwork/ttn | ttnctl/util/lorawan.go | SetMessage | func (m *Message) SetMessage(confirmed bool, ack bool, fCnt int, payload []byte) {
m.confirmed = confirmed
m.ack = ack
m.FCnt = fCnt
m.Payload = payload
} | go | func (m *Message) SetMessage(confirmed bool, ack bool, fCnt int, payload []byte) {
m.confirmed = confirmed
m.ack = ack
m.FCnt = fCnt
m.Payload = payload
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"SetMessage",
"(",
"confirmed",
"bool",
",",
"ack",
"bool",
",",
"fCnt",
"int",
",",
"payload",
"[",
"]",
"byte",
")",
"{",
"m",
".",
"confirmed",
"=",
"confirmed",
"\n",
"m",
".",
"ack",
"=",
"ack",
"\n",
"m",
".",
"FCnt",
"=",
"fCnt",
"\n",
"m",
".",
"Payload",
"=",
"payload",
"\n",
"}"
] | // SetMessage with some options | [
"SetMessage",
"with",
"some",
"options"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/lorawan.go#L34-L39 | train |
TheThingsNetwork/ttn | ttnctl/util/lorawan.go | Bytes | func (m *Message) Bytes() []byte {
if m.FPort == 0 && len(m.Payload) > 0 {
m.FPort = 1
}
macPayload := &lorawan.MACPayload{}
macPayload.FHDR = lorawan.FHDR{
DevAddr: lorawan.DevAddr(m.devAddr),
FCnt: uint32(m.FCnt),
FCtrl: lorawan.FCtrl{
ACK: m.ack,
},
}
macPayload.FPort = pointer.Uint8(uint8(m.FPort))
if len(m.Payload) > 0 {
macPayload.FRMPayload = []lorawan.Payload{&lorawan.DataPayload{Bytes: m.Payload}}
}
phyPayload := &lorawan.PHYPayload{}
phyPayload.MHDR = lorawan.MHDR{
MType: lorawan.UnconfirmedDataUp,
Major: lorawan.LoRaWANR1,
}
if m.confirmed {
phyPayload.MHDR.MType = lorawan.ConfirmedDataUp
}
phyPayload.MACPayload = macPayload
phyPayload.EncryptFRMPayload(lorawan.AES128Key(m.appSKey))
phyPayload.SetMIC(lorawan.AES128Key(m.nwkSKey))
uplinkBytes, _ := phyPayload.MarshalBinary()
return uplinkBytes
} | go | func (m *Message) Bytes() []byte {
if m.FPort == 0 && len(m.Payload) > 0 {
m.FPort = 1
}
macPayload := &lorawan.MACPayload{}
macPayload.FHDR = lorawan.FHDR{
DevAddr: lorawan.DevAddr(m.devAddr),
FCnt: uint32(m.FCnt),
FCtrl: lorawan.FCtrl{
ACK: m.ack,
},
}
macPayload.FPort = pointer.Uint8(uint8(m.FPort))
if len(m.Payload) > 0 {
macPayload.FRMPayload = []lorawan.Payload{&lorawan.DataPayload{Bytes: m.Payload}}
}
phyPayload := &lorawan.PHYPayload{}
phyPayload.MHDR = lorawan.MHDR{
MType: lorawan.UnconfirmedDataUp,
Major: lorawan.LoRaWANR1,
}
if m.confirmed {
phyPayload.MHDR.MType = lorawan.ConfirmedDataUp
}
phyPayload.MACPayload = macPayload
phyPayload.EncryptFRMPayload(lorawan.AES128Key(m.appSKey))
phyPayload.SetMIC(lorawan.AES128Key(m.nwkSKey))
uplinkBytes, _ := phyPayload.MarshalBinary()
return uplinkBytes
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"Bytes",
"(",
")",
"[",
"]",
"byte",
"{",
"if",
"m",
".",
"FPort",
"==",
"0",
"&&",
"len",
"(",
"m",
".",
"Payload",
")",
">",
"0",
"{",
"m",
".",
"FPort",
"=",
"1",
"\n",
"}",
"\n",
"macPayload",
":=",
"&",
"lorawan",
".",
"MACPayload",
"{",
"}",
"\n",
"macPayload",
".",
"FHDR",
"=",
"lorawan",
".",
"FHDR",
"{",
"DevAddr",
":",
"lorawan",
".",
"DevAddr",
"(",
"m",
".",
"devAddr",
")",
",",
"FCnt",
":",
"uint32",
"(",
"m",
".",
"FCnt",
")",
",",
"FCtrl",
":",
"lorawan",
".",
"FCtrl",
"{",
"ACK",
":",
"m",
".",
"ack",
",",
"}",
",",
"}",
"\n",
"macPayload",
".",
"FPort",
"=",
"pointer",
".",
"Uint8",
"(",
"uint8",
"(",
"m",
".",
"FPort",
")",
")",
"\n",
"if",
"len",
"(",
"m",
".",
"Payload",
")",
">",
"0",
"{",
"macPayload",
".",
"FRMPayload",
"=",
"[",
"]",
"lorawan",
".",
"Payload",
"{",
"&",
"lorawan",
".",
"DataPayload",
"{",
"Bytes",
":",
"m",
".",
"Payload",
"}",
"}",
"\n",
"}",
"\n",
"phyPayload",
":=",
"&",
"lorawan",
".",
"PHYPayload",
"{",
"}",
"\n",
"phyPayload",
".",
"MHDR",
"=",
"lorawan",
".",
"MHDR",
"{",
"MType",
":",
"lorawan",
".",
"UnconfirmedDataUp",
",",
"Major",
":",
"lorawan",
".",
"LoRaWANR1",
",",
"}",
"\n",
"if",
"m",
".",
"confirmed",
"{",
"phyPayload",
".",
"MHDR",
".",
"MType",
"=",
"lorawan",
".",
"ConfirmedDataUp",
"\n",
"}",
"\n",
"phyPayload",
".",
"MACPayload",
"=",
"macPayload",
"\n",
"phyPayload",
".",
"EncryptFRMPayload",
"(",
"lorawan",
".",
"AES128Key",
"(",
"m",
".",
"appSKey",
")",
")",
"\n",
"phyPayload",
".",
"SetMIC",
"(",
"lorawan",
".",
"AES128Key",
"(",
"m",
".",
"nwkSKey",
")",
")",
"\n",
"uplinkBytes",
",",
"_",
":=",
"phyPayload",
".",
"MarshalBinary",
"(",
")",
"\n",
"return",
"uplinkBytes",
"\n",
"}"
] | // Bytes returns the bytes | [
"Bytes",
"returns",
"the",
"bytes"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/lorawan.go#L42-L71 | train |
TheThingsNetwork/ttn | ttnctl/util/lorawan.go | Unmarshal | func (m *Message) Unmarshal(bytes []byte) error {
payload := &lorawan.PHYPayload{}
payload.UnmarshalBinary(bytes)
if micOK, _ := payload.ValidateMIC(lorawan.AES128Key(m.nwkSKey)); !micOK {
return errors.New("Invalid MIC")
}
macPayload, ok := payload.MACPayload.(*lorawan.MACPayload)
if !ok {
return errors.New("No MACPayload")
}
m.FCnt = int(macPayload.FHDR.FCnt)
m.FPort = -1
if macPayload.FPort != nil {
m.FPort = int(*macPayload.FPort)
}
m.Payload = []byte{}
if len(macPayload.FRMPayload) > 0 {
payload.DecryptFRMPayload(lorawan.AES128Key(m.appSKey))
m.Payload = macPayload.FRMPayload[0].(*lorawan.DataPayload).Bytes
}
return nil
} | go | func (m *Message) Unmarshal(bytes []byte) error {
payload := &lorawan.PHYPayload{}
payload.UnmarshalBinary(bytes)
if micOK, _ := payload.ValidateMIC(lorawan.AES128Key(m.nwkSKey)); !micOK {
return errors.New("Invalid MIC")
}
macPayload, ok := payload.MACPayload.(*lorawan.MACPayload)
if !ok {
return errors.New("No MACPayload")
}
m.FCnt = int(macPayload.FHDR.FCnt)
m.FPort = -1
if macPayload.FPort != nil {
m.FPort = int(*macPayload.FPort)
}
m.Payload = []byte{}
if len(macPayload.FRMPayload) > 0 {
payload.DecryptFRMPayload(lorawan.AES128Key(m.appSKey))
m.Payload = macPayload.FRMPayload[0].(*lorawan.DataPayload).Bytes
}
return nil
} | [
"func",
"(",
"m",
"*",
"Message",
")",
"Unmarshal",
"(",
"bytes",
"[",
"]",
"byte",
")",
"error",
"{",
"payload",
":=",
"&",
"lorawan",
".",
"PHYPayload",
"{",
"}",
"\n",
"payload",
".",
"UnmarshalBinary",
"(",
"bytes",
")",
"\n",
"if",
"micOK",
",",
"_",
":=",
"payload",
".",
"ValidateMIC",
"(",
"lorawan",
".",
"AES128Key",
"(",
"m",
".",
"nwkSKey",
")",
")",
";",
"!",
"micOK",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"macPayload",
",",
"ok",
":=",
"payload",
".",
"MACPayload",
".",
"(",
"*",
"lorawan",
".",
"MACPayload",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"m",
".",
"FCnt",
"=",
"int",
"(",
"macPayload",
".",
"FHDR",
".",
"FCnt",
")",
"\n",
"m",
".",
"FPort",
"=",
"-",
"1",
"\n",
"if",
"macPayload",
".",
"FPort",
"!=",
"nil",
"{",
"m",
".",
"FPort",
"=",
"int",
"(",
"*",
"macPayload",
".",
"FPort",
")",
"\n",
"}",
"\n",
"m",
".",
"Payload",
"=",
"[",
"]",
"byte",
"{",
"}",
"\n",
"if",
"len",
"(",
"macPayload",
".",
"FRMPayload",
")",
">",
"0",
"{",
"payload",
".",
"DecryptFRMPayload",
"(",
"lorawan",
".",
"AES128Key",
"(",
"m",
".",
"appSKey",
")",
")",
"\n",
"m",
".",
"Payload",
"=",
"macPayload",
".",
"FRMPayload",
"[",
"0",
"]",
".",
"(",
"*",
"lorawan",
".",
"DataPayload",
")",
".",
"Bytes",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Unmarshal a byte slice into a Message | [
"Unmarshal",
"a",
"byte",
"slice",
"into",
"a",
"Message"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/ttnctl/util/lorawan.go#L74-L95 | train |
TheThingsNetwork/ttn | utils/parse/parse.go | Port | func Port(address string) (uint, error) {
parts := strings.Split(address, ":")
length := len(parts)
if length < 2 {
return 0, errors.New("Could not parse the port: malformated address")
}
port, err := strconv.Atoi(parts[length-1])
if err != nil {
return 0, err
}
if port < 0 {
return 0, errors.New("Invalid port number")
}
return uint(port), nil
} | go | func Port(address string) (uint, error) {
parts := strings.Split(address, ":")
length := len(parts)
if length < 2 {
return 0, errors.New("Could not parse the port: malformated address")
}
port, err := strconv.Atoi(parts[length-1])
if err != nil {
return 0, err
}
if port < 0 {
return 0, errors.New("Invalid port number")
}
return uint(port), nil
} | [
"func",
"Port",
"(",
"address",
"string",
")",
"(",
"uint",
",",
"error",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"address",
",",
"\"",
"\"",
")",
"\n\n",
"length",
":=",
"len",
"(",
"parts",
")",
"\n",
"if",
"length",
"<",
"2",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"port",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"parts",
"[",
"length",
"-",
"1",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"if",
"port",
"<",
"0",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"uint",
"(",
"port",
")",
",",
"nil",
"\n",
"}"
] | // Port returns the port from an address | [
"Port",
"returns",
"the",
"port",
"from",
"an",
"address"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/utils/parse/parse.go#L10-L27 | train |
TheThingsNetwork/ttn | core/handler/device/store.go | NewRedisDeviceStore | func NewRedisDeviceStore(client *redis.Client, prefix string) *RedisDeviceStore {
if prefix == "" {
prefix = defaultRedisPrefix
}
store := storage.NewRedisMapStore(client, prefix+":"+redisDevicePrefix)
store.SetBase(Device{}, "")
for v, f := range migrate.DeviceMigrations(prefix) {
store.AddMigration(v, f)
}
queues := storage.NewRedisQueueStore(client, prefix+":"+redisDownlinkQueuePrefix)
s := &RedisDeviceStore{
client: client,
prefix: prefix,
store: store,
queues: queues,
}
s.AddBuiltinAttribute(defaultDeviceAttributes...)
countStore(s)
return s
} | go | func NewRedisDeviceStore(client *redis.Client, prefix string) *RedisDeviceStore {
if prefix == "" {
prefix = defaultRedisPrefix
}
store := storage.NewRedisMapStore(client, prefix+":"+redisDevicePrefix)
store.SetBase(Device{}, "")
for v, f := range migrate.DeviceMigrations(prefix) {
store.AddMigration(v, f)
}
queues := storage.NewRedisQueueStore(client, prefix+":"+redisDownlinkQueuePrefix)
s := &RedisDeviceStore{
client: client,
prefix: prefix,
store: store,
queues: queues,
}
s.AddBuiltinAttribute(defaultDeviceAttributes...)
countStore(s)
return s
} | [
"func",
"NewRedisDeviceStore",
"(",
"client",
"*",
"redis",
".",
"Client",
",",
"prefix",
"string",
")",
"*",
"RedisDeviceStore",
"{",
"if",
"prefix",
"==",
"\"",
"\"",
"{",
"prefix",
"=",
"defaultRedisPrefix",
"\n",
"}",
"\n",
"store",
":=",
"storage",
".",
"NewRedisMapStore",
"(",
"client",
",",
"prefix",
"+",
"\"",
"\"",
"+",
"redisDevicePrefix",
")",
"\n",
"store",
".",
"SetBase",
"(",
"Device",
"{",
"}",
",",
"\"",
"\"",
")",
"\n",
"for",
"v",
",",
"f",
":=",
"range",
"migrate",
".",
"DeviceMigrations",
"(",
"prefix",
")",
"{",
"store",
".",
"AddMigration",
"(",
"v",
",",
"f",
")",
"\n",
"}",
"\n",
"queues",
":=",
"storage",
".",
"NewRedisQueueStore",
"(",
"client",
",",
"prefix",
"+",
"\"",
"\"",
"+",
"redisDownlinkQueuePrefix",
")",
"\n",
"s",
":=",
"&",
"RedisDeviceStore",
"{",
"client",
":",
"client",
",",
"prefix",
":",
"prefix",
",",
"store",
":",
"store",
",",
"queues",
":",
"queues",
",",
"}",
"\n",
"s",
".",
"AddBuiltinAttribute",
"(",
"defaultDeviceAttributes",
"...",
")",
"\n",
"countStore",
"(",
"s",
")",
"\n",
"return",
"s",
"\n",
"}"
] | // NewRedisDeviceStore creates a new Redis-based Device store | [
"NewRedisDeviceStore",
"creates",
"a",
"new",
"Redis",
"-",
"based",
"Device",
"store"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/store.go#L49-L68 | train |
TheThingsNetwork/ttn | core/handler/device/store.go | Count | func (s *RedisDeviceStore) Count() (int, error) {
opts := new(storage.ListOptions)
opts.UseCache(s.listResultCacheKey("_all_"), listCacheTTL)
return s.store.Count("", opts)
} | go | func (s *RedisDeviceStore) Count() (int, error) {
opts := new(storage.ListOptions)
opts.UseCache(s.listResultCacheKey("_all_"), listCacheTTL)
return s.store.Count("", opts)
} | [
"func",
"(",
"s",
"*",
"RedisDeviceStore",
")",
"Count",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"opts",
":=",
"new",
"(",
"storage",
".",
"ListOptions",
")",
"\n",
"opts",
".",
"UseCache",
"(",
"s",
".",
"listResultCacheKey",
"(",
"\"",
"\"",
")",
",",
"listCacheTTL",
")",
"\n",
"return",
"s",
".",
"store",
".",
"Count",
"(",
"\"",
"\"",
",",
"opts",
")",
"\n",
"}"
] | // Count all devices in the store | [
"Count",
"all",
"devices",
"in",
"the",
"store"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/store.go#L87-L91 | train |
TheThingsNetwork/ttn | core/handler/device/store.go | CountForApp | func (s *RedisDeviceStore) CountForApp(appID string) (int, error) {
opts := new(storage.ListOptions)
opts.UseCache(s.listResultCacheKey(appID), listCacheTTL)
return s.store.Count(fmt.Sprintf("%s:*", appID), opts)
} | go | func (s *RedisDeviceStore) CountForApp(appID string) (int, error) {
opts := new(storage.ListOptions)
opts.UseCache(s.listResultCacheKey(appID), listCacheTTL)
return s.store.Count(fmt.Sprintf("%s:*", appID), opts)
} | [
"func",
"(",
"s",
"*",
"RedisDeviceStore",
")",
"CountForApp",
"(",
"appID",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"opts",
":=",
"new",
"(",
"storage",
".",
"ListOptions",
")",
"\n",
"opts",
".",
"UseCache",
"(",
"s",
".",
"listResultCacheKey",
"(",
"appID",
")",
",",
"listCacheTTL",
")",
"\n",
"return",
"s",
".",
"store",
".",
"Count",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"appID",
")",
",",
"opts",
")",
"\n",
"}"
] | // CountForApp counts all devices for an Application | [
"CountForApp",
"counts",
"all",
"devices",
"for",
"an",
"Application"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/store.go#L94-L98 | train |
TheThingsNetwork/ttn | core/handler/device/store.go | List | func (s *RedisDeviceStore) List(opts *storage.ListOptions) ([]*Device, error) {
if opts == nil {
opts = new(storage.ListOptions)
}
opts.UseCache(s.listResultCacheKey("_all_"), listCacheTTL)
devicesI, err := s.store.List("", opts)
if err != nil {
return nil, err
}
devices := make([]*Device, len(devicesI))
for i, deviceI := range devicesI {
if device, ok := deviceI.(Device); ok {
devices[i] = &device
}
}
return devices, nil
} | go | func (s *RedisDeviceStore) List(opts *storage.ListOptions) ([]*Device, error) {
if opts == nil {
opts = new(storage.ListOptions)
}
opts.UseCache(s.listResultCacheKey("_all_"), listCacheTTL)
devicesI, err := s.store.List("", opts)
if err != nil {
return nil, err
}
devices := make([]*Device, len(devicesI))
for i, deviceI := range devicesI {
if device, ok := deviceI.(Device); ok {
devices[i] = &device
}
}
return devices, nil
} | [
"func",
"(",
"s",
"*",
"RedisDeviceStore",
")",
"List",
"(",
"opts",
"*",
"storage",
".",
"ListOptions",
")",
"(",
"[",
"]",
"*",
"Device",
",",
"error",
")",
"{",
"if",
"opts",
"==",
"nil",
"{",
"opts",
"=",
"new",
"(",
"storage",
".",
"ListOptions",
")",
"\n",
"}",
"\n",
"opts",
".",
"UseCache",
"(",
"s",
".",
"listResultCacheKey",
"(",
"\"",
"\"",
")",
",",
"listCacheTTL",
")",
"\n",
"devicesI",
",",
"err",
":=",
"s",
".",
"store",
".",
"List",
"(",
"\"",
"\"",
",",
"opts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"devices",
":=",
"make",
"(",
"[",
"]",
"*",
"Device",
",",
"len",
"(",
"devicesI",
")",
")",
"\n",
"for",
"i",
",",
"deviceI",
":=",
"range",
"devicesI",
"{",
"if",
"device",
",",
"ok",
":=",
"deviceI",
".",
"(",
"Device",
")",
";",
"ok",
"{",
"devices",
"[",
"i",
"]",
"=",
"&",
"device",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"devices",
",",
"nil",
"\n",
"}"
] | // List all Devices | [
"List",
"all",
"Devices"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/store.go#L101-L117 | train |
TheThingsNetwork/ttn | core/handler/device/store.go | DownlinkQueue | func (s *RedisDeviceStore) DownlinkQueue(appID, devID string) (DownlinkQueue, error) {
return &RedisDownlinkQueue{
appID: appID,
devID: devID,
queues: s.queues,
}, nil
} | go | func (s *RedisDeviceStore) DownlinkQueue(appID, devID string) (DownlinkQueue, error) {
return &RedisDownlinkQueue{
appID: appID,
devID: devID,
queues: s.queues,
}, nil
} | [
"func",
"(",
"s",
"*",
"RedisDeviceStore",
")",
"DownlinkQueue",
"(",
"appID",
",",
"devID",
"string",
")",
"(",
"DownlinkQueue",
",",
"error",
")",
"{",
"return",
"&",
"RedisDownlinkQueue",
"{",
"appID",
":",
"appID",
",",
"devID",
":",
"devID",
",",
"queues",
":",
"s",
".",
"queues",
",",
"}",
",",
"nil",
"\n",
"}"
] | // DownlinkQueue for a specific Device | [
"DownlinkQueue",
"for",
"a",
"specific",
"Device"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/store.go#L151-L157 | train |
TheThingsNetwork/ttn | core/handler/device/store.go | AddBuiltinAttribute | func (s *RedisDeviceStore) AddBuiltinAttribute(attr ...string) {
s.builtinAttibutes = append(s.builtinAttibutes, attr...)
sort.Strings(s.builtinAttibutes)
} | go | func (s *RedisDeviceStore) AddBuiltinAttribute(attr ...string) {
s.builtinAttibutes = append(s.builtinAttibutes, attr...)
sort.Strings(s.builtinAttibutes)
} | [
"func",
"(",
"s",
"*",
"RedisDeviceStore",
")",
"AddBuiltinAttribute",
"(",
"attr",
"...",
"string",
")",
"{",
"s",
".",
"builtinAttibutes",
"=",
"append",
"(",
"s",
".",
"builtinAttibutes",
",",
"attr",
"...",
")",
"\n",
"sort",
".",
"Strings",
"(",
"s",
".",
"builtinAttibutes",
")",
"\n",
"}"
] | // AddBuiltinAttribute adds builtin device attributes to the list. | [
"AddBuiltinAttribute",
"adds",
"builtin",
"device",
"attributes",
"to",
"the",
"list",
"."
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/device/store.go#L208-L211 | train |
TheThingsNetwork/ttn | core/component/config.go | ConfigFromViper | func ConfigFromViper() Config {
return Config{
AuthServers: viper.GetStringMapString("auth-servers"),
KeyDir: viper.GetString("key-dir"),
UseTLS: viper.GetBool("tls"),
MinTLSVersion: viper.GetString("min-tls-version"),
}
} | go | func ConfigFromViper() Config {
return Config{
AuthServers: viper.GetStringMapString("auth-servers"),
KeyDir: viper.GetString("key-dir"),
UseTLS: viper.GetBool("tls"),
MinTLSVersion: viper.GetString("min-tls-version"),
}
} | [
"func",
"ConfigFromViper",
"(",
")",
"Config",
"{",
"return",
"Config",
"{",
"AuthServers",
":",
"viper",
".",
"GetStringMapString",
"(",
"\"",
"\"",
")",
",",
"KeyDir",
":",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"UseTLS",
":",
"viper",
".",
"GetBool",
"(",
"\"",
"\"",
")",
",",
"MinTLSVersion",
":",
"viper",
".",
"GetString",
"(",
"\"",
"\"",
")",
",",
"}",
"\n",
"}"
] | // ConfigFromViper imports configuration from Viper | [
"ConfigFromViper",
"imports",
"configuration",
"from",
"Viper"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/component/config.go#L19-L26 | train |
TheThingsNetwork/ttn | amqp/publisher.go | NewPublisher | func (c *DefaultClient) NewPublisher(exchange string) Publisher {
return &DefaultPublisher{
DefaultChannelClient: DefaultChannelClient{
ctx: c.ctx,
client: c,
exchange: exchange,
name: "Publisher",
},
}
} | go | func (c *DefaultClient) NewPublisher(exchange string) Publisher {
return &DefaultPublisher{
DefaultChannelClient: DefaultChannelClient{
ctx: c.ctx,
client: c,
exchange: exchange,
name: "Publisher",
},
}
} | [
"func",
"(",
"c",
"*",
"DefaultClient",
")",
"NewPublisher",
"(",
"exchange",
"string",
")",
"Publisher",
"{",
"return",
"&",
"DefaultPublisher",
"{",
"DefaultChannelClient",
":",
"DefaultChannelClient",
"{",
"ctx",
":",
"c",
".",
"ctx",
",",
"client",
":",
"c",
",",
"exchange",
":",
"exchange",
",",
"name",
":",
"\"",
"\"",
",",
"}",
",",
"}",
"\n",
"}"
] | // NewPublisher returns a new topic publisher on the specified exchange | [
"NewPublisher",
"returns",
"a",
"new",
"topic",
"publisher",
"on",
"the",
"specified",
"exchange"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/publisher.go#L29-L38 | train |
TheThingsNetwork/ttn | mqtt/topics.go | ParseDeviceTopic | func ParseDeviceTopic(topic string) (*DeviceTopic, error) {
pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\+)/(devices)/([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\+)/(events|up|down)([0-9a-z/]+)?$")
matches := pattern.FindStringSubmatch(topic)
if len(matches) < 5 {
return nil, fmt.Errorf("Invalid topic format")
}
var appID string
if matches[1] != simpleWildcard {
appID = matches[1]
}
var devID string
if matches[3] != simpleWildcard {
devID = matches[3]
}
topicType := DeviceTopicType(matches[4])
deviceTopic := &DeviceTopic{appID, devID, topicType, ""}
if (topicType == DeviceUplink || topicType == DeviceEvents) && len(matches) > 5 {
deviceTopic.Field = strings.Trim(matches[5], "/")
}
return deviceTopic, nil
} | go | func ParseDeviceTopic(topic string) (*DeviceTopic, error) {
pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\+)/(devices)/([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\+)/(events|up|down)([0-9a-z/]+)?$")
matches := pattern.FindStringSubmatch(topic)
if len(matches) < 5 {
return nil, fmt.Errorf("Invalid topic format")
}
var appID string
if matches[1] != simpleWildcard {
appID = matches[1]
}
var devID string
if matches[3] != simpleWildcard {
devID = matches[3]
}
topicType := DeviceTopicType(matches[4])
deviceTopic := &DeviceTopic{appID, devID, topicType, ""}
if (topicType == DeviceUplink || topicType == DeviceEvents) && len(matches) > 5 {
deviceTopic.Field = strings.Trim(matches[5], "/")
}
return deviceTopic, nil
} | [
"func",
"ParseDeviceTopic",
"(",
"topic",
"string",
")",
"(",
"*",
"DeviceTopic",
",",
"error",
")",
"{",
"pattern",
":=",
"regexp",
".",
"MustCompile",
"(",
"\"",
"\\\\",
"\\\\",
"\"",
")",
"\n",
"matches",
":=",
"pattern",
".",
"FindStringSubmatch",
"(",
"topic",
")",
"\n",
"if",
"len",
"(",
"matches",
")",
"<",
"5",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"var",
"appID",
"string",
"\n",
"if",
"matches",
"[",
"1",
"]",
"!=",
"simpleWildcard",
"{",
"appID",
"=",
"matches",
"[",
"1",
"]",
"\n",
"}",
"\n",
"var",
"devID",
"string",
"\n",
"if",
"matches",
"[",
"3",
"]",
"!=",
"simpleWildcard",
"{",
"devID",
"=",
"matches",
"[",
"3",
"]",
"\n",
"}",
"\n",
"topicType",
":=",
"DeviceTopicType",
"(",
"matches",
"[",
"4",
"]",
")",
"\n",
"deviceTopic",
":=",
"&",
"DeviceTopic",
"{",
"appID",
",",
"devID",
",",
"topicType",
",",
"\"",
"\"",
"}",
"\n",
"if",
"(",
"topicType",
"==",
"DeviceUplink",
"||",
"topicType",
"==",
"DeviceEvents",
")",
"&&",
"len",
"(",
"matches",
")",
">",
"5",
"{",
"deviceTopic",
".",
"Field",
"=",
"strings",
".",
"Trim",
"(",
"matches",
"[",
"5",
"]",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"deviceTopic",
",",
"nil",
"\n",
"}"
] | // ParseDeviceTopic parses an MQTT device topic string to a DeviceTopic struct | [
"ParseDeviceTopic",
"parses",
"an",
"MQTT",
"device",
"topic",
"string",
"to",
"a",
"DeviceTopic",
"struct"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/topics.go#L34-L54 | train |
TheThingsNetwork/ttn | mqtt/topics.go | ParseApplicationTopic | func ParseApplicationTopic(topic string) (*ApplicationTopic, error) {
pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\+)/(events)([0-9a-z/-]+|/#)?$")
matches := pattern.FindStringSubmatch(topic)
if len(matches) < 3 {
return nil, fmt.Errorf("Invalid topic format")
}
var appID string
if matches[1] != simpleWildcard {
appID = matches[1]
}
topicType := ApplicationTopicType(matches[2])
appTopic := &ApplicationTopic{appID, topicType, ""}
if topicType == AppEvents && len(matches) > 3 {
appTopic.Field = strings.Trim(matches[3], "/")
}
return appTopic, nil
} | go | func ParseApplicationTopic(topic string) (*ApplicationTopic, error) {
pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\+)/(events)([0-9a-z/-]+|/#)?$")
matches := pattern.FindStringSubmatch(topic)
if len(matches) < 3 {
return nil, fmt.Errorf("Invalid topic format")
}
var appID string
if matches[1] != simpleWildcard {
appID = matches[1]
}
topicType := ApplicationTopicType(matches[2])
appTopic := &ApplicationTopic{appID, topicType, ""}
if topicType == AppEvents && len(matches) > 3 {
appTopic.Field = strings.Trim(matches[3], "/")
}
return appTopic, nil
} | [
"func",
"ParseApplicationTopic",
"(",
"topic",
"string",
")",
"(",
"*",
"ApplicationTopic",
",",
"error",
")",
"{",
"pattern",
":=",
"regexp",
".",
"MustCompile",
"(",
"\"",
"\\\\",
"\"",
")",
"\n",
"matches",
":=",
"pattern",
".",
"FindStringSubmatch",
"(",
"topic",
")",
"\n",
"if",
"len",
"(",
"matches",
")",
"<",
"3",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"var",
"appID",
"string",
"\n",
"if",
"matches",
"[",
"1",
"]",
"!=",
"simpleWildcard",
"{",
"appID",
"=",
"matches",
"[",
"1",
"]",
"\n",
"}",
"\n",
"topicType",
":=",
"ApplicationTopicType",
"(",
"matches",
"[",
"2",
"]",
")",
"\n",
"appTopic",
":=",
"&",
"ApplicationTopic",
"{",
"appID",
",",
"topicType",
",",
"\"",
"\"",
"}",
"\n",
"if",
"topicType",
"==",
"AppEvents",
"&&",
"len",
"(",
"matches",
")",
">",
"3",
"{",
"appTopic",
".",
"Field",
"=",
"strings",
".",
"Trim",
"(",
"matches",
"[",
"3",
"]",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"appTopic",
",",
"nil",
"\n",
"}"
] | // ParseApplicationTopic parses an MQTT device topic string to an ApplicationTopic struct | [
"ParseApplicationTopic",
"parses",
"an",
"MQTT",
"device",
"topic",
"string",
"to",
"an",
"ApplicationTopic",
"struct"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/mqtt/topics.go#L92-L108 | train |
TheThingsNetwork/ttn | core/handler/dry_run.go | DryUplink | func (h *handlerManager) DryUplink(ctx context.Context, in *pb.DryUplinkMessage) (*pb.DryUplinkResult, error) {
app := in.App
flds := ""
valid := true
var logs []*pb.LogEntry
var decoder PayloadDecoder
switch application.PayloadFormat(app.PayloadFormat) {
case "", application.PayloadFormatCustom:
decoder = &CustomUplinkFunctions{
Decoder: app.Decoder,
Converter: app.Converter,
Validator: app.Validator,
Logger: functions.NewEntryLogger(),
}
case application.PayloadFormatCayenneLPP:
decoder = &cayennelpp.Decoder{}
default:
return nil, errors.NewErrInvalidArgument("App", "unknown payload format")
}
fields, val, err := decoder.Decode(in.Payload, uint8(in.Port))
if err != nil {
return nil, err
}
valid = val
logs = decoder.Log()
marshalled, err := json.Marshal(fields)
if err != nil {
return nil, err
}
flds = string(marshalled)
return &pb.DryUplinkResult{
Payload: in.Payload,
Fields: flds,
Valid: valid,
Logs: logs,
}, nil
} | go | func (h *handlerManager) DryUplink(ctx context.Context, in *pb.DryUplinkMessage) (*pb.DryUplinkResult, error) {
app := in.App
flds := ""
valid := true
var logs []*pb.LogEntry
var decoder PayloadDecoder
switch application.PayloadFormat(app.PayloadFormat) {
case "", application.PayloadFormatCustom:
decoder = &CustomUplinkFunctions{
Decoder: app.Decoder,
Converter: app.Converter,
Validator: app.Validator,
Logger: functions.NewEntryLogger(),
}
case application.PayloadFormatCayenneLPP:
decoder = &cayennelpp.Decoder{}
default:
return nil, errors.NewErrInvalidArgument("App", "unknown payload format")
}
fields, val, err := decoder.Decode(in.Payload, uint8(in.Port))
if err != nil {
return nil, err
}
valid = val
logs = decoder.Log()
marshalled, err := json.Marshal(fields)
if err != nil {
return nil, err
}
flds = string(marshalled)
return &pb.DryUplinkResult{
Payload: in.Payload,
Fields: flds,
Valid: valid,
Logs: logs,
}, nil
} | [
"func",
"(",
"h",
"*",
"handlerManager",
")",
"DryUplink",
"(",
"ctx",
"context",
".",
"Context",
",",
"in",
"*",
"pb",
".",
"DryUplinkMessage",
")",
"(",
"*",
"pb",
".",
"DryUplinkResult",
",",
"error",
")",
"{",
"app",
":=",
"in",
".",
"App",
"\n\n",
"flds",
":=",
"\"",
"\"",
"\n",
"valid",
":=",
"true",
"\n",
"var",
"logs",
"[",
"]",
"*",
"pb",
".",
"LogEntry",
"\n",
"var",
"decoder",
"PayloadDecoder",
"\n",
"switch",
"application",
".",
"PayloadFormat",
"(",
"app",
".",
"PayloadFormat",
")",
"{",
"case",
"\"",
"\"",
",",
"application",
".",
"PayloadFormatCustom",
":",
"decoder",
"=",
"&",
"CustomUplinkFunctions",
"{",
"Decoder",
":",
"app",
".",
"Decoder",
",",
"Converter",
":",
"app",
".",
"Converter",
",",
"Validator",
":",
"app",
".",
"Validator",
",",
"Logger",
":",
"functions",
".",
"NewEntryLogger",
"(",
")",
",",
"}",
"\n",
"case",
"application",
".",
"PayloadFormatCayenneLPP",
":",
"decoder",
"=",
"&",
"cayennelpp",
".",
"Decoder",
"{",
"}",
"\n",
"default",
":",
"return",
"nil",
",",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"fields",
",",
"val",
",",
"err",
":=",
"decoder",
".",
"Decode",
"(",
"in",
".",
"Payload",
",",
"uint8",
"(",
"in",
".",
"Port",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"valid",
"=",
"val",
"\n",
"logs",
"=",
"decoder",
".",
"Log",
"(",
")",
"\n\n",
"marshalled",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"fields",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"flds",
"=",
"string",
"(",
"marshalled",
")",
"\n\n",
"return",
"&",
"pb",
".",
"DryUplinkResult",
"{",
"Payload",
":",
"in",
".",
"Payload",
",",
"Fields",
":",
"flds",
",",
"Valid",
":",
"valid",
",",
"Logs",
":",
"logs",
",",
"}",
",",
"nil",
"\n",
"}"
] | // DryUplink converts the uplink message payload by running the payload
// functions that are provided in the DryUplinkMessage, without actually going to the network.
// This is helpful for testing the payload functions without having to save them. | [
"DryUplink",
"converts",
"the",
"uplink",
"message",
"payload",
"by",
"running",
"the",
"payload",
"functions",
"that",
"are",
"provided",
"in",
"the",
"DryUplinkMessage",
"without",
"actually",
"going",
"to",
"the",
"network",
".",
"This",
"is",
"helpful",
"for",
"testing",
"the",
"payload",
"functions",
"without",
"having",
"to",
"save",
"them",
"."
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/dry_run.go#L20-L62 | train |
TheThingsNetwork/ttn | core/handler/dry_run.go | DryDownlink | func (h *handlerManager) DryDownlink(ctx context.Context, in *pb.DryDownlinkMessage) (*pb.DryDownlinkResult, error) {
app := in.App
if in.Payload != nil {
if in.Fields != "" {
return nil, errors.NewErrInvalidArgument("Downlink", "Both Fields and Payload provided")
}
return &pb.DryDownlinkResult{
Payload: in.Payload,
}, nil
}
if in.Fields == "" {
return nil, errors.NewErrInvalidArgument("Downlink", "Neither Fields nor Payload provided")
}
var encoder PayloadEncoder
switch application.PayloadFormat(in.App.PayloadFormat) {
case "", application.PayloadFormatCustom:
encoder = &CustomDownlinkFunctions{
Encoder: app.Encoder,
Logger: functions.NewEntryLogger(),
}
case application.PayloadFormatCayenneLPP:
encoder = &cayennelpp.Encoder{}
default:
return nil, errors.NewErrInvalidArgument("App", "unknown payload format")
}
var parsed map[string]interface{}
err := json.Unmarshal([]byte(in.Fields), &parsed)
if err != nil {
return nil, errors.NewErrInvalidArgument("Fields", err.Error())
}
payload, _, err := encoder.Encode(parsed, uint8(in.Port))
if err != nil {
return nil, err
}
return &pb.DryDownlinkResult{
Payload: payload,
Logs: encoder.Log(),
}, nil
} | go | func (h *handlerManager) DryDownlink(ctx context.Context, in *pb.DryDownlinkMessage) (*pb.DryDownlinkResult, error) {
app := in.App
if in.Payload != nil {
if in.Fields != "" {
return nil, errors.NewErrInvalidArgument("Downlink", "Both Fields and Payload provided")
}
return &pb.DryDownlinkResult{
Payload: in.Payload,
}, nil
}
if in.Fields == "" {
return nil, errors.NewErrInvalidArgument("Downlink", "Neither Fields nor Payload provided")
}
var encoder PayloadEncoder
switch application.PayloadFormat(in.App.PayloadFormat) {
case "", application.PayloadFormatCustom:
encoder = &CustomDownlinkFunctions{
Encoder: app.Encoder,
Logger: functions.NewEntryLogger(),
}
case application.PayloadFormatCayenneLPP:
encoder = &cayennelpp.Encoder{}
default:
return nil, errors.NewErrInvalidArgument("App", "unknown payload format")
}
var parsed map[string]interface{}
err := json.Unmarshal([]byte(in.Fields), &parsed)
if err != nil {
return nil, errors.NewErrInvalidArgument("Fields", err.Error())
}
payload, _, err := encoder.Encode(parsed, uint8(in.Port))
if err != nil {
return nil, err
}
return &pb.DryDownlinkResult{
Payload: payload,
Logs: encoder.Log(),
}, nil
} | [
"func",
"(",
"h",
"*",
"handlerManager",
")",
"DryDownlink",
"(",
"ctx",
"context",
".",
"Context",
",",
"in",
"*",
"pb",
".",
"DryDownlinkMessage",
")",
"(",
"*",
"pb",
".",
"DryDownlinkResult",
",",
"error",
")",
"{",
"app",
":=",
"in",
".",
"App",
"\n\n",
"if",
"in",
".",
"Payload",
"!=",
"nil",
"{",
"if",
"in",
".",
"Fields",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"pb",
".",
"DryDownlinkResult",
"{",
"Payload",
":",
"in",
".",
"Payload",
",",
"}",
",",
"nil",
"\n",
"}",
"\n\n",
"if",
"in",
".",
"Fields",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"encoder",
"PayloadEncoder",
"\n",
"switch",
"application",
".",
"PayloadFormat",
"(",
"in",
".",
"App",
".",
"PayloadFormat",
")",
"{",
"case",
"\"",
"\"",
",",
"application",
".",
"PayloadFormatCustom",
":",
"encoder",
"=",
"&",
"CustomDownlinkFunctions",
"{",
"Encoder",
":",
"app",
".",
"Encoder",
",",
"Logger",
":",
"functions",
".",
"NewEntryLogger",
"(",
")",
",",
"}",
"\n",
"case",
"application",
".",
"PayloadFormatCayenneLPP",
":",
"encoder",
"=",
"&",
"cayennelpp",
".",
"Encoder",
"{",
"}",
"\n",
"default",
":",
"return",
"nil",
",",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"var",
"parsed",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"in",
".",
"Fields",
")",
",",
"&",
"parsed",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"NewErrInvalidArgument",
"(",
"\"",
"\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n\n",
"payload",
",",
"_",
",",
"err",
":=",
"encoder",
".",
"Encode",
"(",
"parsed",
",",
"uint8",
"(",
"in",
".",
"Port",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"pb",
".",
"DryDownlinkResult",
"{",
"Payload",
":",
"payload",
",",
"Logs",
":",
"encoder",
".",
"Log",
"(",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // DryDownlink converts the downlink message payload by running the payload
// functions that are provided in the DryDownlinkMessage, without actually going to the network.
// This is helpful for testing the payload functions without having to save them. | [
"DryDownlink",
"converts",
"the",
"downlink",
"message",
"payload",
"by",
"running",
"the",
"payload",
"functions",
"that",
"are",
"provided",
"in",
"the",
"DryDownlinkMessage",
"without",
"actually",
"going",
"to",
"the",
"network",
".",
"This",
"is",
"helpful",
"for",
"testing",
"the",
"payload",
"functions",
"without",
"having",
"to",
"save",
"them",
"."
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/handler/dry_run.go#L67-L111 | train |
TheThingsNetwork/ttn | amqp/routing_keys.go | ParseDeviceKey | func ParseDeviceKey(key string) (*DeviceKey, error) {
pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\*)\\.(devices)\\.([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\*)\\.(events|up|down)([0-9a-z\\.]+)?$")
matches := pattern.FindStringSubmatch(key)
if len(matches) < 5 {
return nil, fmt.Errorf("Invalid key format")
}
var appID string
if matches[1] != simpleWildcard {
appID = matches[1]
}
var devID string
if matches[3] != simpleWildcard {
devID = matches[3]
}
keyType := DeviceKeyType(matches[4])
deviceKey := &DeviceKey{appID, devID, keyType, ""}
if keyType == DeviceEvents && len(matches) > 5 {
deviceKey.Field = strings.Trim(matches[5], ".")
}
return deviceKey, nil
} | go | func ParseDeviceKey(key string) (*DeviceKey, error) {
pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\*)\\.(devices)\\.([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\*)\\.(events|up|down)([0-9a-z\\.]+)?$")
matches := pattern.FindStringSubmatch(key)
if len(matches) < 5 {
return nil, fmt.Errorf("Invalid key format")
}
var appID string
if matches[1] != simpleWildcard {
appID = matches[1]
}
var devID string
if matches[3] != simpleWildcard {
devID = matches[3]
}
keyType := DeviceKeyType(matches[4])
deviceKey := &DeviceKey{appID, devID, keyType, ""}
if keyType == DeviceEvents && len(matches) > 5 {
deviceKey.Field = strings.Trim(matches[5], ".")
}
return deviceKey, nil
} | [
"func",
"ParseDeviceKey",
"(",
"key",
"string",
")",
"(",
"*",
"DeviceKey",
",",
"error",
")",
"{",
"pattern",
":=",
"regexp",
".",
"MustCompile",
"(",
"\"",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\"",
")",
"\n",
"matches",
":=",
"pattern",
".",
"FindStringSubmatch",
"(",
"key",
")",
"\n",
"if",
"len",
"(",
"matches",
")",
"<",
"5",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"var",
"appID",
"string",
"\n",
"if",
"matches",
"[",
"1",
"]",
"!=",
"simpleWildcard",
"{",
"appID",
"=",
"matches",
"[",
"1",
"]",
"\n",
"}",
"\n",
"var",
"devID",
"string",
"\n",
"if",
"matches",
"[",
"3",
"]",
"!=",
"simpleWildcard",
"{",
"devID",
"=",
"matches",
"[",
"3",
"]",
"\n",
"}",
"\n",
"keyType",
":=",
"DeviceKeyType",
"(",
"matches",
"[",
"4",
"]",
")",
"\n",
"deviceKey",
":=",
"&",
"DeviceKey",
"{",
"appID",
",",
"devID",
",",
"keyType",
",",
"\"",
"\"",
"}",
"\n",
"if",
"keyType",
"==",
"DeviceEvents",
"&&",
"len",
"(",
"matches",
")",
">",
"5",
"{",
"deviceKey",
".",
"Field",
"=",
"strings",
".",
"Trim",
"(",
"matches",
"[",
"5",
"]",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"deviceKey",
",",
"nil",
"\n",
"}"
] | // ParseDeviceKey parses an AMQP device routing key string to a DeviceKey struct | [
"ParseDeviceKey",
"parses",
"an",
"AMQP",
"device",
"routing",
"key",
"string",
"to",
"a",
"DeviceKey",
"struct"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/routing_keys.go#L34-L54 | train |
TheThingsNetwork/ttn | amqp/routing_keys.go | ParseApplicationKey | func ParseApplicationKey(key string) (*ApplicationKey, error) {
pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\*)\\.(events)([0-9a-z\\.-]+|\\.#)?$")
matches := pattern.FindStringSubmatch(key)
if len(matches) < 3 {
return nil, fmt.Errorf("Invalid key format")
}
var appID string
if matches[1] != simpleWildcard {
appID = matches[1]
}
keyType := ApplicationKeyType(matches[2])
appKey := &ApplicationKey{appID, keyType, ""}
if keyType == AppEvents && len(matches) > 3 {
appKey.Field = strings.Trim(matches[3], ".")
}
return appKey, nil
} | go | func ParseApplicationKey(key string) (*ApplicationKey, error) {
pattern := regexp.MustCompile("^([0-9a-z](?:[_-]?[0-9a-z]){1,35}|\\*)\\.(events)([0-9a-z\\.-]+|\\.#)?$")
matches := pattern.FindStringSubmatch(key)
if len(matches) < 3 {
return nil, fmt.Errorf("Invalid key format")
}
var appID string
if matches[1] != simpleWildcard {
appID = matches[1]
}
keyType := ApplicationKeyType(matches[2])
appKey := &ApplicationKey{appID, keyType, ""}
if keyType == AppEvents && len(matches) > 3 {
appKey.Field = strings.Trim(matches[3], ".")
}
return appKey, nil
} | [
"func",
"ParseApplicationKey",
"(",
"key",
"string",
")",
"(",
"*",
"ApplicationKey",
",",
"error",
")",
"{",
"pattern",
":=",
"regexp",
".",
"MustCompile",
"(",
"\"",
"\\\\",
"\\\\",
"\\\\",
"\\\\",
"\"",
")",
"\n",
"matches",
":=",
"pattern",
".",
"FindStringSubmatch",
"(",
"key",
")",
"\n",
"if",
"len",
"(",
"matches",
")",
"<",
"3",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"var",
"appID",
"string",
"\n",
"if",
"matches",
"[",
"1",
"]",
"!=",
"simpleWildcard",
"{",
"appID",
"=",
"matches",
"[",
"1",
"]",
"\n",
"}",
"\n",
"keyType",
":=",
"ApplicationKeyType",
"(",
"matches",
"[",
"2",
"]",
")",
"\n",
"appKey",
":=",
"&",
"ApplicationKey",
"{",
"appID",
",",
"keyType",
",",
"\"",
"\"",
"}",
"\n",
"if",
"keyType",
"==",
"AppEvents",
"&&",
"len",
"(",
"matches",
")",
">",
"3",
"{",
"appKey",
".",
"Field",
"=",
"strings",
".",
"Trim",
"(",
"matches",
"[",
"3",
"]",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"appKey",
",",
"nil",
"\n",
"}"
] | // ParseApplicationKey parses an AMQP application routing key string to an ApplicationKey struct | [
"ParseApplicationKey",
"parses",
"an",
"AMQP",
"application",
"routing",
"key",
"string",
"to",
"an",
"ApplicationKey",
"struct"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/routing_keys.go#L92-L108 | train |
TheThingsNetwork/ttn | amqp/client.go | Connect | func (c *DefaultClient) Connect() error {
_, err := c.connect(false)
return err
} | go | func (c *DefaultClient) Connect() error {
_, err := c.connect(false)
return err
} | [
"func",
"(",
"c",
"*",
"DefaultClient",
")",
"Connect",
"(",
")",
"error",
"{",
"_",
",",
"err",
":=",
"c",
".",
"connect",
"(",
"false",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // Connect to the AMQP server. It will retry for ConnectRetries times with a delay of ConnectRetryDelay between retries | [
"Connect",
"to",
"the",
"AMQP",
"server",
".",
"It",
"will",
"retry",
"for",
"ConnectRetries",
"times",
"with",
"a",
"delay",
"of",
"ConnectRetryDelay",
"between",
"retries"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/client.go#L148-L151 | train |
TheThingsNetwork/ttn | amqp/client.go | Disconnect | func (c *DefaultClient) Disconnect() {
if !c.IsConnected() {
return
}
c.ctx.Debug("Disconnecting from AMQP")
c.mutex.Lock()
defer c.mutex.Unlock()
for user, channel := range c.channels {
channel.Close()
delete(c.channels, user)
}
c.conn.Close()
c.conn = nil
} | go | func (c *DefaultClient) Disconnect() {
if !c.IsConnected() {
return
}
c.ctx.Debug("Disconnecting from AMQP")
c.mutex.Lock()
defer c.mutex.Unlock()
for user, channel := range c.channels {
channel.Close()
delete(c.channels, user)
}
c.conn.Close()
c.conn = nil
} | [
"func",
"(",
"c",
"*",
"DefaultClient",
")",
"Disconnect",
"(",
")",
"{",
"if",
"!",
"c",
".",
"IsConnected",
"(",
")",
"{",
"return",
"\n",
"}",
"\n\n",
"c",
".",
"ctx",
".",
"Debug",
"(",
"\"",
"\"",
")",
"\n\n",
"c",
".",
"mutex",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"mutex",
".",
"Unlock",
"(",
")",
"\n",
"for",
"user",
",",
"channel",
":=",
"range",
"c",
".",
"channels",
"{",
"channel",
".",
"Close",
"(",
")",
"\n",
"delete",
"(",
"c",
".",
"channels",
",",
"user",
")",
"\n",
"}",
"\n\n",
"c",
".",
"conn",
".",
"Close",
"(",
")",
"\n",
"c",
".",
"conn",
"=",
"nil",
"\n",
"}"
] | // Disconnect from the AMQP server | [
"Disconnect",
"from",
"the",
"AMQP",
"server"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/client.go#L154-L170 | train |
TheThingsNetwork/ttn | amqp/client.go | Open | func (p *DefaultChannelClient) Open() error {
channel, err := p.client.openChannel(p)
if err != nil {
return fmt.Errorf("Could not open AMQP channel (%s)", err)
}
p.channel = channel
return nil
} | go | func (p *DefaultChannelClient) Open() error {
channel, err := p.client.openChannel(p)
if err != nil {
return fmt.Errorf("Could not open AMQP channel (%s)", err)
}
p.channel = channel
return nil
} | [
"func",
"(",
"p",
"*",
"DefaultChannelClient",
")",
"Open",
"(",
")",
"error",
"{",
"channel",
",",
"err",
":=",
"p",
".",
"client",
".",
"openChannel",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"p",
".",
"channel",
"=",
"channel",
"\n",
"return",
"nil",
"\n",
"}"
] | // Open opens a new channel and declares the exchange | [
"Open",
"opens",
"a",
"new",
"channel",
"and",
"declares",
"the",
"exchange"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/client.go#L205-L213 | train |
TheThingsNetwork/ttn | amqp/client.go | Close | func (p *DefaultChannelClient) Close() error {
p.usersMutex.RLock()
defer p.usersMutex.RUnlock()
for _, user := range p.users {
user.close()
}
return p.client.closeChannel(p)
} | go | func (p *DefaultChannelClient) Close() error {
p.usersMutex.RLock()
defer p.usersMutex.RUnlock()
for _, user := range p.users {
user.close()
}
return p.client.closeChannel(p)
} | [
"func",
"(",
"p",
"*",
"DefaultChannelClient",
")",
"Close",
"(",
")",
"error",
"{",
"p",
".",
"usersMutex",
".",
"RLock",
"(",
")",
"\n",
"defer",
"p",
".",
"usersMutex",
".",
"RUnlock",
"(",
")",
"\n",
"for",
"_",
",",
"user",
":=",
"range",
"p",
".",
"users",
"{",
"user",
".",
"close",
"(",
")",
"\n",
"}",
"\n",
"return",
"p",
".",
"client",
".",
"closeChannel",
"(",
"p",
")",
"\n",
"}"
] | // Close closes the channel | [
"Close",
"closes",
"the",
"channel"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/amqp/client.go#L216-L223 | train |
TheThingsNetwork/ttn | core/types/eui.go | ParseEUI64 | func ParseEUI64(input string) (eui EUI64, err error) {
bytes, err := ParseHEX(input, 8)
if err != nil {
return
}
copy(eui[:], bytes)
return
} | go | func ParseEUI64(input string) (eui EUI64, err error) {
bytes, err := ParseHEX(input, 8)
if err != nil {
return
}
copy(eui[:], bytes)
return
} | [
"func",
"ParseEUI64",
"(",
"input",
"string",
")",
"(",
"eui",
"EUI64",
",",
"err",
"error",
")",
"{",
"bytes",
",",
"err",
":=",
"ParseHEX",
"(",
"input",
",",
"8",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"copy",
"(",
"eui",
"[",
":",
"]",
",",
"bytes",
")",
"\n",
"return",
"\n",
"}"
] | // ParseEUI64 parses a 64-bit hex-encoded string to an EUI64. | [
"ParseEUI64",
"parses",
"a",
"64",
"-",
"bit",
"hex",
"-",
"encoded",
"string",
"to",
"an",
"EUI64",
"."
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/eui.go#L23-L30 | train |
TheThingsNetwork/ttn | core/types/eui.go | ParseAppEUI | func ParseAppEUI(input string) (eui AppEUI, err error) {
eui64, err := ParseEUI64(input)
if err != nil {
return
}
eui = AppEUI(eui64)
return
} | go | func ParseAppEUI(input string) (eui AppEUI, err error) {
eui64, err := ParseEUI64(input)
if err != nil {
return
}
eui = AppEUI(eui64)
return
} | [
"func",
"ParseAppEUI",
"(",
"input",
"string",
")",
"(",
"eui",
"AppEUI",
",",
"err",
"error",
")",
"{",
"eui64",
",",
"err",
":=",
"ParseEUI64",
"(",
"input",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"eui",
"=",
"AppEUI",
"(",
"eui64",
")",
"\n",
"return",
"\n",
"}"
] | // ParseAppEUI parses a 64-bit hex-encoded string to an AppEUI | [
"ParseAppEUI",
"parses",
"a",
"64",
"-",
"bit",
"hex",
"-",
"encoded",
"string",
"to",
"an",
"AppEUI"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/eui.go#L106-L113 | train |
TheThingsNetwork/ttn | core/types/eui.go | ParseDevEUI | func ParseDevEUI(input string) (eui DevEUI, err error) {
eui64, err := ParseEUI64(input)
if err != nil {
return
}
eui = DevEUI(eui64)
return
} | go | func ParseDevEUI(input string) (eui DevEUI, err error) {
eui64, err := ParseEUI64(input)
if err != nil {
return
}
eui = DevEUI(eui64)
return
} | [
"func",
"ParseDevEUI",
"(",
"input",
"string",
")",
"(",
"eui",
"DevEUI",
",",
"err",
"error",
")",
"{",
"eui64",
",",
"err",
":=",
"ParseEUI64",
"(",
"input",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"eui",
"=",
"DevEUI",
"(",
"eui64",
")",
"\n",
"return",
"\n",
"}"
] | // ParseDevEUI parses a 64-bit hex-encoded string to an DevEUI | [
"ParseDevEUI",
"parses",
"a",
"64",
"-",
"bit",
"hex",
"-",
"encoded",
"string",
"to",
"an",
"DevEUI"
] | fc5709a55c20e1712047e5cb5a8d571aa62eefbb | https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/eui.go#L190-L197 | train |
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.