id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
144,800
rjeczalik/notify
watcher_trigger.go
send
func (t *trg) send(evn []event) { for i := range evn { t.c <- &evn[i] } }
go
func (t *trg) send(evn []event) { for i := range evn { t.c <- &evn[i] } }
[ "func", "(", "t", "*", "trg", ")", "send", "(", "evn", "[", "]", "event", ")", "{", "for", "i", ":=", "range", "evn", "{", "t", ".", "c", "<-", "&", "evn", "[", "i", "]", "\n", "}", "\n", "}" ]
// send reported events one by one through chan.
[ "send", "reported", "events", "one", "by", "one", "through", "chan", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_trigger.go#L143-L147
144,801
rjeczalik/notify
watcher_trigger.go
Watch
func (t *trg) Watch(p string, e Event) error { fi, err := os.Stat(p) if err != nil { return err } t.Lock() err = t.watch(p, e, fi) t.Unlock() return err }
go
func (t *trg) Watch(p string, e Event) error { fi, err := os.Stat(p) if err != nil { return err } t.Lock() err = t.watch(p, e, fi) t.Unlock() return err }
[ "func", "(", "t", "*", "trg", ")", "Watch", "(", "p", "string", ",", "e", "Event", ")", "error", "{", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "t", ".", "Lock", "(", ")", "\n", "err", "=", "t", ".", "watch", "(", "p", ",", "e", ",", "fi", ")", "\n", "t", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// Watch implements Watcher interface.
[ "Watch", "implements", "Watcher", "interface", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_trigger.go#L252-L261
144,802
rjeczalik/notify
watcher_trigger.go
Unwatch
func (t *trg) Unwatch(p string) error { fi, err := os.Stat(p) if err != nil { return err } t.Lock() err = t.unwatch(p, fi) t.Unlock() return err }
go
func (t *trg) Unwatch(p string) error { fi, err := os.Stat(p) if err != nil { return err } t.Lock() err = t.unwatch(p, fi) t.Unlock() return err }
[ "func", "(", "t", "*", "trg", ")", "Unwatch", "(", "p", "string", ")", "error", "{", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "t", ".", "Lock", "(", ")", "\n", "err", "=", "t", ".", "unwatch", "(", "p", ",", "fi", ")", "\n", "t", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// Unwatch implements Watcher interface.
[ "Unwatch", "implements", "Watcher", "interface", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_trigger.go#L264-L273
144,803
rjeczalik/notify
watcher_trigger.go
process
func (t *trg) process(n interface{}) (evn []event) { t.Lock() w, ge, err := t.t.Watched(n) if err != nil { t.Unlock() dbgprintf("trg: %v event lookup failed: %q", Event(ge), err) return } e := decode(ge, w.eDir|w.eNonDir) if ge&int64(not2nat[Remove]|not2nat[Rename]) == 0 { switch fi, err := os.Stat(w.p); { case err != nil: default: if err = t.t.Watch(fi, w, encode(w.eDir|w.eNonDir, fi.IsDir())); err != nil { dbgprintf("trg: %q is no longer watched: %q", w.p, err) t.t.Del(w) } } } if e == Event(0) && (!w.fi.IsDir() || (ge&int64(not2nat[Write])) == 0) { t.Unlock() return } if w.fi.IsDir() { evn = append(evn, t.dir(w, n, e, Event(ge))...) } else { evn = append(evn, t.file(w, n, e)...) } if Event(ge)&(not2nat[Remove]|not2nat[Rename]) != 0 { t.t.Del(w) } t.Unlock() return }
go
func (t *trg) process(n interface{}) (evn []event) { t.Lock() w, ge, err := t.t.Watched(n) if err != nil { t.Unlock() dbgprintf("trg: %v event lookup failed: %q", Event(ge), err) return } e := decode(ge, w.eDir|w.eNonDir) if ge&int64(not2nat[Remove]|not2nat[Rename]) == 0 { switch fi, err := os.Stat(w.p); { case err != nil: default: if err = t.t.Watch(fi, w, encode(w.eDir|w.eNonDir, fi.IsDir())); err != nil { dbgprintf("trg: %q is no longer watched: %q", w.p, err) t.t.Del(w) } } } if e == Event(0) && (!w.fi.IsDir() || (ge&int64(not2nat[Write])) == 0) { t.Unlock() return } if w.fi.IsDir() { evn = append(evn, t.dir(w, n, e, Event(ge))...) } else { evn = append(evn, t.file(w, n, e)...) } if Event(ge)&(not2nat[Remove]|not2nat[Rename]) != 0 { t.t.Del(w) } t.Unlock() return }
[ "func", "(", "t", "*", "trg", ")", "process", "(", "n", "interface", "{", "}", ")", "(", "evn", "[", "]", "event", ")", "{", "t", ".", "Lock", "(", ")", "\n", "w", ",", "ge", ",", "err", ":=", "t", ".", "t", ".", "Watched", "(", "n", ")", "\n", "if", "err", "!=", "nil", "{", "t", ".", "Unlock", "(", ")", "\n", "dbgprintf", "(", "\"", "\"", ",", "Event", "(", "ge", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "e", ":=", "decode", "(", "ge", ",", "w", ".", "eDir", "|", "w", ".", "eNonDir", ")", "\n", "if", "ge", "&", "int64", "(", "not2nat", "[", "Remove", "]", "|", "not2nat", "[", "Rename", "]", ")", "==", "0", "{", "switch", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "w", ".", "p", ")", ";", "{", "case", "err", "!=", "nil", ":", "default", ":", "if", "err", "=", "t", ".", "t", ".", "Watch", "(", "fi", ",", "w", ",", "encode", "(", "w", ".", "eDir", "|", "w", ".", "eNonDir", ",", "fi", ".", "IsDir", "(", ")", ")", ")", ";", "err", "!=", "nil", "{", "dbgprintf", "(", "\"", "\"", ",", "w", ".", "p", ",", "err", ")", "\n", "t", ".", "t", ".", "Del", "(", "w", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "e", "==", "Event", "(", "0", ")", "&&", "(", "!", "w", ".", "fi", ".", "IsDir", "(", ")", "||", "(", "ge", "&", "int64", "(", "not2nat", "[", "Write", "]", ")", ")", "==", "0", ")", "{", "t", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n\n", "if", "w", ".", "fi", ".", "IsDir", "(", ")", "{", "evn", "=", "append", "(", "evn", ",", "t", ".", "dir", "(", "w", ",", "n", ",", "e", ",", "Event", "(", "ge", ")", ")", "...", ")", "\n", "}", "else", "{", "evn", "=", "append", "(", "evn", ",", "t", ".", "file", "(", "w", ",", "n", ",", "e", ")", "...", ")", "\n", "}", "\n", "if", "Event", "(", "ge", ")", "&", "(", "not2nat", "[", "Remove", "]", "|", "not2nat", "[", "Rename", "]", ")", "!=", "0", "{", "t", ".", "t", ".", "Del", "(", "w", ")", "\n", "}", "\n", "t", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// process event returned by native call.
[ "process", "event", "returned", "by", "native", "call", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_trigger.go#L415-L450
144,804
rjeczalik/notify
watcher_inotify.go
newWatcher
func newWatcher(c chan<- EventInfo) watcher { i := &inotify{ m: make(map[int32]*watched), fd: invalidDescriptor, pipefd: []int{invalidDescriptor, invalidDescriptor}, epfd: invalidDescriptor, epes: make([]unix.EpollEvent, 0), c: c, } runtime.SetFinalizer(i, func(i *inotify) { i.epollclose() if i.fd != invalidDescriptor { unix.Close(int(i.fd)) } }) return i }
go
func newWatcher(c chan<- EventInfo) watcher { i := &inotify{ m: make(map[int32]*watched), fd: invalidDescriptor, pipefd: []int{invalidDescriptor, invalidDescriptor}, epfd: invalidDescriptor, epes: make([]unix.EpollEvent, 0), c: c, } runtime.SetFinalizer(i, func(i *inotify) { i.epollclose() if i.fd != invalidDescriptor { unix.Close(int(i.fd)) } }) return i }
[ "func", "newWatcher", "(", "c", "chan", "<-", "EventInfo", ")", "watcher", "{", "i", ":=", "&", "inotify", "{", "m", ":", "make", "(", "map", "[", "int32", "]", "*", "watched", ")", ",", "fd", ":", "invalidDescriptor", ",", "pipefd", ":", "[", "]", "int", "{", "invalidDescriptor", ",", "invalidDescriptor", "}", ",", "epfd", ":", "invalidDescriptor", ",", "epes", ":", "make", "(", "[", "]", "unix", ".", "EpollEvent", ",", "0", ")", ",", "c", ":", "c", ",", "}", "\n", "runtime", ".", "SetFinalizer", "(", "i", ",", "func", "(", "i", "*", "inotify", ")", "{", "i", ".", "epollclose", "(", ")", "\n", "if", "i", ".", "fd", "!=", "invalidDescriptor", "{", "unix", ".", "Close", "(", "int", "(", "i", ".", "fd", ")", ")", "\n", "}", "\n", "}", ")", "\n", "return", "i", "\n", "}" ]
// NewWatcher creates new non-recursive inotify backed by inotify.
[ "NewWatcher", "creates", "new", "non", "-", "recursive", "inotify", "backed", "by", "inotify", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L54-L70
144,805
rjeczalik/notify
watcher_inotify.go
Watch
func (i *inotify) Watch(path string, e Event) error { return i.watch(path, e) }
go
func (i *inotify) Watch(path string, e Event) error { return i.watch(path, e) }
[ "func", "(", "i", "*", "inotify", ")", "Watch", "(", "path", "string", ",", "e", "Event", ")", "error", "{", "return", "i", ".", "watch", "(", "path", ",", "e", ")", "\n", "}" ]
// Watch implements notify.watcher interface.
[ "Watch", "implements", "notify", ".", "watcher", "interface", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L73-L75
144,806
rjeczalik/notify
watcher_inotify.go
Rewatch
func (i *inotify) Rewatch(path string, _, newevent Event) error { return i.watch(path, newevent) }
go
func (i *inotify) Rewatch(path string, _, newevent Event) error { return i.watch(path, newevent) }
[ "func", "(", "i", "*", "inotify", ")", "Rewatch", "(", "path", "string", ",", "_", ",", "newevent", "Event", ")", "error", "{", "return", "i", ".", "watch", "(", "path", ",", "newevent", ")", "\n", "}" ]
// Rewatch implements notify.watcher interface.
[ "Rewatch", "implements", "notify", ".", "watcher", "interface", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L78-L80
144,807
rjeczalik/notify
watcher_inotify.go
watch
func (i *inotify) watch(path string, e Event) (err error) { if e&^(All|Event(unix.IN_ALL_EVENTS)) != 0 { return errors.New("notify: unknown event") } if err = i.lazyinit(); err != nil { return } iwd, err := unix.InotifyAddWatch(int(i.fd), path, encode(e)) if err != nil { return } i.RLock() wd := i.m[int32(iwd)] i.RUnlock() if wd == nil { i.Lock() if i.m[int32(iwd)] == nil { i.m[int32(iwd)] = &watched{path: path, mask: uint32(e)} } i.Unlock() } else { i.Lock() wd.mask = uint32(e) i.Unlock() } return nil }
go
func (i *inotify) watch(path string, e Event) (err error) { if e&^(All|Event(unix.IN_ALL_EVENTS)) != 0 { return errors.New("notify: unknown event") } if err = i.lazyinit(); err != nil { return } iwd, err := unix.InotifyAddWatch(int(i.fd), path, encode(e)) if err != nil { return } i.RLock() wd := i.m[int32(iwd)] i.RUnlock() if wd == nil { i.Lock() if i.m[int32(iwd)] == nil { i.m[int32(iwd)] = &watched{path: path, mask: uint32(e)} } i.Unlock() } else { i.Lock() wd.mask = uint32(e) i.Unlock() } return nil }
[ "func", "(", "i", "*", "inotify", ")", "watch", "(", "path", "string", ",", "e", "Event", ")", "(", "err", "error", ")", "{", "if", "e", "&^", "(", "All", "|", "Event", "(", "unix", ".", "IN_ALL_EVENTS", ")", ")", "!=", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", "=", "i", ".", "lazyinit", "(", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "iwd", ",", "err", ":=", "unix", ".", "InotifyAddWatch", "(", "int", "(", "i", ".", "fd", ")", ",", "path", ",", "encode", "(", "e", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "i", ".", "RLock", "(", ")", "\n", "wd", ":=", "i", ".", "m", "[", "int32", "(", "iwd", ")", "]", "\n", "i", ".", "RUnlock", "(", ")", "\n", "if", "wd", "==", "nil", "{", "i", ".", "Lock", "(", ")", "\n", "if", "i", ".", "m", "[", "int32", "(", "iwd", ")", "]", "==", "nil", "{", "i", ".", "m", "[", "int32", "(", "iwd", ")", "]", "=", "&", "watched", "{", "path", ":", "path", ",", "mask", ":", "uint32", "(", "e", ")", "}", "\n", "}", "\n", "i", ".", "Unlock", "(", ")", "\n", "}", "else", "{", "i", ".", "Lock", "(", ")", "\n", "wd", ".", "mask", "=", "uint32", "(", "e", ")", "\n", "i", ".", "Unlock", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// watch adds a new watcher to the set of watched objects or modifies the existing // one. If called for the first time, this function initializes inotify filesystem // monitor and starts producer-consumers goroutines.
[ "watch", "adds", "a", "new", "watcher", "to", "the", "set", "of", "watched", "objects", "or", "modifies", "the", "existing", "one", ".", "If", "called", "for", "the", "first", "time", "this", "function", "initializes", "inotify", "filesystem", "monitor", "and", "starts", "producer", "-", "consumers", "goroutines", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L85-L111
144,808
rjeczalik/notify
watcher_inotify.go
lazyinit
func (i *inotify) lazyinit() error { if atomic.LoadInt32(&i.fd) == invalidDescriptor { i.Lock() defer i.Unlock() if atomic.LoadInt32(&i.fd) == invalidDescriptor { fd, err := unix.InotifyInit1(unix.IN_CLOEXEC) if err != nil { return err } i.fd = int32(fd) if err = i.epollinit(); err != nil { _, _ = i.epollclose(), unix.Close(int(fd)) // Ignore errors. i.fd = invalidDescriptor return err } esch := make(chan []*event) go i.loop(esch) i.wg.Add(consumersCount) for n := 0; n < consumersCount; n++ { go i.send(esch) } } } return nil }
go
func (i *inotify) lazyinit() error { if atomic.LoadInt32(&i.fd) == invalidDescriptor { i.Lock() defer i.Unlock() if atomic.LoadInt32(&i.fd) == invalidDescriptor { fd, err := unix.InotifyInit1(unix.IN_CLOEXEC) if err != nil { return err } i.fd = int32(fd) if err = i.epollinit(); err != nil { _, _ = i.epollclose(), unix.Close(int(fd)) // Ignore errors. i.fd = invalidDescriptor return err } esch := make(chan []*event) go i.loop(esch) i.wg.Add(consumersCount) for n := 0; n < consumersCount; n++ { go i.send(esch) } } } return nil }
[ "func", "(", "i", "*", "inotify", ")", "lazyinit", "(", ")", "error", "{", "if", "atomic", ".", "LoadInt32", "(", "&", "i", ".", "fd", ")", "==", "invalidDescriptor", "{", "i", ".", "Lock", "(", ")", "\n", "defer", "i", ".", "Unlock", "(", ")", "\n", "if", "atomic", ".", "LoadInt32", "(", "&", "i", ".", "fd", ")", "==", "invalidDescriptor", "{", "fd", ",", "err", ":=", "unix", ".", "InotifyInit1", "(", "unix", ".", "IN_CLOEXEC", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "i", ".", "fd", "=", "int32", "(", "fd", ")", "\n", "if", "err", "=", "i", ".", "epollinit", "(", ")", ";", "err", "!=", "nil", "{", "_", ",", "_", "=", "i", ".", "epollclose", "(", ")", ",", "unix", ".", "Close", "(", "int", "(", "fd", ")", ")", "// Ignore errors.", "\n", "i", ".", "fd", "=", "invalidDescriptor", "\n", "return", "err", "\n", "}", "\n", "esch", ":=", "make", "(", "chan", "[", "]", "*", "event", ")", "\n", "go", "i", ".", "loop", "(", "esch", ")", "\n", "i", ".", "wg", ".", "Add", "(", "consumersCount", ")", "\n", "for", "n", ":=", "0", ";", "n", "<", "consumersCount", ";", "n", "++", "{", "go", "i", ".", "send", "(", "esch", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// lazyinit sets up all required file descriptors and starts 1+consumersCount // goroutines. The producer goroutine blocks until file-system notifications // occur. Then, all events are read from system buffer and sent to consumer // goroutines which construct valid notify events. This method uses // Double-Checked Locking optimization.
[ "lazyinit", "sets", "up", "all", "required", "file", "descriptors", "and", "starts", "1", "+", "consumersCount", "goroutines", ".", "The", "producer", "goroutine", "blocks", "until", "file", "-", "system", "notifications", "occur", ".", "Then", "all", "events", "are", "read", "from", "system", "buffer", "and", "sent", "to", "consumer", "goroutines", "which", "construct", "valid", "notify", "events", ".", "This", "method", "uses", "Double", "-", "Checked", "Locking", "optimization", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L118-L142
144,809
rjeczalik/notify
watcher_inotify.go
send
func (i *inotify) send(esch <-chan []*event) { for es := range esch { for _, e := range i.transform(es) { if e != nil { i.c <- e } } } i.wg.Done() }
go
func (i *inotify) send(esch <-chan []*event) { for es := range esch { for _, e := range i.transform(es) { if e != nil { i.c <- e } } } i.wg.Done() }
[ "func", "(", "i", "*", "inotify", ")", "send", "(", "esch", "<-", "chan", "[", "]", "*", "event", ")", "{", "for", "es", ":=", "range", "esch", "{", "for", "_", ",", "e", ":=", "range", "i", ".", "transform", "(", "es", ")", "{", "if", "e", "!=", "nil", "{", "i", ".", "c", "<-", "e", "\n", "}", "\n", "}", "\n", "}", "\n", "i", ".", "wg", ".", "Done", "(", ")", "\n", "}" ]
// send is a consumer function which sends events to event dispatcher channel. // It is run in a separate goroutine in order to not block loop method when // possibly expensive write operations are performed on inotify map.
[ "send", "is", "a", "consumer", "function", "which", "sends", "events", "to", "event", "dispatcher", "channel", ".", "It", "is", "run", "in", "a", "separate", "goroutine", "in", "order", "to", "not", "block", "loop", "method", "when", "possibly", "expensive", "write", "operations", "are", "performed", "on", "inotify", "map", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L253-L262
144,810
rjeczalik/notify
watcher_inotify.go
transform
func (i *inotify) transform(es []*event) []*event { var multi []*event i.RLock() for idx, e := range es { if e.sys.Mask&(unix.IN_IGNORED|unix.IN_Q_OVERFLOW) != 0 { es[idx] = nil continue } wd, ok := i.m[e.sys.Wd] if !ok || e.sys.Mask&encode(Event(wd.mask)) == 0 { es[idx] = nil continue } if e.path == "" { e.path = wd.path } else { e.path = filepath.Join(wd.path, e.path) } multi = append(multi, decode(Event(wd.mask), e)) if e.event == 0 { es[idx] = nil } } i.RUnlock() es = append(es, multi...) return es }
go
func (i *inotify) transform(es []*event) []*event { var multi []*event i.RLock() for idx, e := range es { if e.sys.Mask&(unix.IN_IGNORED|unix.IN_Q_OVERFLOW) != 0 { es[idx] = nil continue } wd, ok := i.m[e.sys.Wd] if !ok || e.sys.Mask&encode(Event(wd.mask)) == 0 { es[idx] = nil continue } if e.path == "" { e.path = wd.path } else { e.path = filepath.Join(wd.path, e.path) } multi = append(multi, decode(Event(wd.mask), e)) if e.event == 0 { es[idx] = nil } } i.RUnlock() es = append(es, multi...) return es }
[ "func", "(", "i", "*", "inotify", ")", "transform", "(", "es", "[", "]", "*", "event", ")", "[", "]", "*", "event", "{", "var", "multi", "[", "]", "*", "event", "\n", "i", ".", "RLock", "(", ")", "\n", "for", "idx", ",", "e", ":=", "range", "es", "{", "if", "e", ".", "sys", ".", "Mask", "&", "(", "unix", ".", "IN_IGNORED", "|", "unix", ".", "IN_Q_OVERFLOW", ")", "!=", "0", "{", "es", "[", "idx", "]", "=", "nil", "\n", "continue", "\n", "}", "\n", "wd", ",", "ok", ":=", "i", ".", "m", "[", "e", ".", "sys", ".", "Wd", "]", "\n", "if", "!", "ok", "||", "e", ".", "sys", ".", "Mask", "&", "encode", "(", "Event", "(", "wd", ".", "mask", ")", ")", "==", "0", "{", "es", "[", "idx", "]", "=", "nil", "\n", "continue", "\n", "}", "\n", "if", "e", ".", "path", "==", "\"", "\"", "{", "e", ".", "path", "=", "wd", ".", "path", "\n", "}", "else", "{", "e", ".", "path", "=", "filepath", ".", "Join", "(", "wd", ".", "path", ",", "e", ".", "path", ")", "\n", "}", "\n", "multi", "=", "append", "(", "multi", ",", "decode", "(", "Event", "(", "wd", ".", "mask", ")", ",", "e", ")", ")", "\n", "if", "e", ".", "event", "==", "0", "{", "es", "[", "idx", "]", "=", "nil", "\n", "}", "\n", "}", "\n", "i", ".", "RUnlock", "(", ")", "\n", "es", "=", "append", "(", "es", ",", "multi", "...", ")", "\n", "return", "es", "\n", "}" ]
// transform prepares events read from inotify file descriptor for sending to // user. It removes invalid events and these which are no longer present in // inotify map. This method may also split one raw event into two different ones // when system-dependent result is required.
[ "transform", "prepares", "events", "read", "from", "inotify", "file", "descriptor", "for", "sending", "to", "user", ".", "It", "removes", "invalid", "events", "and", "these", "which", "are", "no", "longer", "present", "in", "inotify", "map", ".", "This", "method", "may", "also", "split", "one", "raw", "event", "into", "two", "different", "ones", "when", "system", "-", "dependent", "result", "is", "required", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L268-L294
144,811
rjeczalik/notify
watcher_inotify.go
decode
func decode(mask Event, e *event) (syse *event) { if sysmask := uint32(mask) & e.sys.Mask; sysmask != 0 { syse = &event{sys: unix.InotifyEvent{ Wd: e.sys.Wd, Mask: e.sys.Mask, Cookie: e.sys.Cookie, }, event: Event(sysmask), path: e.path} } imask := encode(mask) switch { case mask&Create != 0 && imask&uint32(InCreate|InMovedTo)&e.sys.Mask != 0: e.event = Create case mask&Remove != 0 && imask&uint32(InDelete|InDeleteSelf)&e.sys.Mask != 0: e.event = Remove case mask&Write != 0 && imask&uint32(InModify)&e.sys.Mask != 0: e.event = Write case mask&Rename != 0 && imask&uint32(InMovedFrom|InMoveSelf)&e.sys.Mask != 0: e.event = Rename default: e.event = 0 } return }
go
func decode(mask Event, e *event) (syse *event) { if sysmask := uint32(mask) & e.sys.Mask; sysmask != 0 { syse = &event{sys: unix.InotifyEvent{ Wd: e.sys.Wd, Mask: e.sys.Mask, Cookie: e.sys.Cookie, }, event: Event(sysmask), path: e.path} } imask := encode(mask) switch { case mask&Create != 0 && imask&uint32(InCreate|InMovedTo)&e.sys.Mask != 0: e.event = Create case mask&Remove != 0 && imask&uint32(InDelete|InDeleteSelf)&e.sys.Mask != 0: e.event = Remove case mask&Write != 0 && imask&uint32(InModify)&e.sys.Mask != 0: e.event = Write case mask&Rename != 0 && imask&uint32(InMovedFrom|InMoveSelf)&e.sys.Mask != 0: e.event = Rename default: e.event = 0 } return }
[ "func", "decode", "(", "mask", "Event", ",", "e", "*", "event", ")", "(", "syse", "*", "event", ")", "{", "if", "sysmask", ":=", "uint32", "(", "mask", ")", "&", "e", ".", "sys", ".", "Mask", ";", "sysmask", "!=", "0", "{", "syse", "=", "&", "event", "{", "sys", ":", "unix", ".", "InotifyEvent", "{", "Wd", ":", "e", ".", "sys", ".", "Wd", ",", "Mask", ":", "e", ".", "sys", ".", "Mask", ",", "Cookie", ":", "e", ".", "sys", ".", "Cookie", ",", "}", ",", "event", ":", "Event", "(", "sysmask", ")", ",", "path", ":", "e", ".", "path", "}", "\n", "}", "\n", "imask", ":=", "encode", "(", "mask", ")", "\n", "switch", "{", "case", "mask", "&", "Create", "!=", "0", "&&", "imask", "&", "uint32", "(", "InCreate", "|", "InMovedTo", ")", "&", "e", ".", "sys", ".", "Mask", "!=", "0", ":", "e", ".", "event", "=", "Create", "\n", "case", "mask", "&", "Remove", "!=", "0", "&&", "imask", "&", "uint32", "(", "InDelete", "|", "InDeleteSelf", ")", "&", "e", ".", "sys", ".", "Mask", "!=", "0", ":", "e", ".", "event", "=", "Remove", "\n", "case", "mask", "&", "Write", "!=", "0", "&&", "imask", "&", "uint32", "(", "InModify", ")", "&", "e", ".", "sys", ".", "Mask", "!=", "0", ":", "e", ".", "event", "=", "Write", "\n", "case", "mask", "&", "Rename", "!=", "0", "&&", "imask", "&", "uint32", "(", "InMovedFrom", "|", "InMoveSelf", ")", "&", "e", ".", "sys", ".", "Mask", "!=", "0", ":", "e", ".", "event", "=", "Rename", "\n", "default", ":", "e", ".", "event", "=", "0", "\n", "}", "\n", "return", "\n", "}" ]
// decode uses internally stored mask to distinguish whether system-independent // or system-dependent event is requested. The first one is created by modifying // `e` argument. decode method sets e.event value to 0 when an event should be // skipped. System-dependent event is set as the function's return value which // can be nil when the event should not be passed on.
[ "decode", "uses", "internally", "stored", "mask", "to", "distinguish", "whether", "system", "-", "independent", "or", "system", "-", "dependent", "event", "is", "requested", ".", "The", "first", "one", "is", "created", "by", "modifying", "e", "argument", ".", "decode", "method", "sets", "e", ".", "event", "value", "to", "0", "when", "an", "event", "should", "be", "skipped", ".", "System", "-", "dependent", "event", "is", "set", "as", "the", "function", "s", "return", "value", "which", "can", "be", "nil", "when", "the", "event", "should", "not", "be", "passed", "on", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L319-L341
144,812
rjeczalik/notify
watcher_inotify.go
Close
func (i *inotify) Close() (err error) { i.Lock() if fd := atomic.LoadInt32(&i.fd); fd == invalidDescriptor { i.Unlock() return nil } for iwd := range i.m { if e := removeInotifyWatch(i.fd, iwd); e != nil && err == nil { err = e } delete(i.m, iwd) } switch _, errwrite := unix.Write(i.pipefd[1], []byte{0x00}); { case errwrite != nil && err == nil: err = errwrite fallthrough case errwrite != nil: i.Unlock() default: i.Unlock() i.wg.Wait() } return }
go
func (i *inotify) Close() (err error) { i.Lock() if fd := atomic.LoadInt32(&i.fd); fd == invalidDescriptor { i.Unlock() return nil } for iwd := range i.m { if e := removeInotifyWatch(i.fd, iwd); e != nil && err == nil { err = e } delete(i.m, iwd) } switch _, errwrite := unix.Write(i.pipefd[1], []byte{0x00}); { case errwrite != nil && err == nil: err = errwrite fallthrough case errwrite != nil: i.Unlock() default: i.Unlock() i.wg.Wait() } return }
[ "func", "(", "i", "*", "inotify", ")", "Close", "(", ")", "(", "err", "error", ")", "{", "i", ".", "Lock", "(", ")", "\n", "if", "fd", ":=", "atomic", ".", "LoadInt32", "(", "&", "i", ".", "fd", ")", ";", "fd", "==", "invalidDescriptor", "{", "i", ".", "Unlock", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "for", "iwd", ":=", "range", "i", ".", "m", "{", "if", "e", ":=", "removeInotifyWatch", "(", "i", ".", "fd", ",", "iwd", ")", ";", "e", "!=", "nil", "&&", "err", "==", "nil", "{", "err", "=", "e", "\n", "}", "\n", "delete", "(", "i", ".", "m", ",", "iwd", ")", "\n", "}", "\n", "switch", "_", ",", "errwrite", ":=", "unix", ".", "Write", "(", "i", ".", "pipefd", "[", "1", "]", ",", "[", "]", "byte", "{", "0x00", "}", ")", ";", "{", "case", "errwrite", "!=", "nil", "&&", "err", "==", "nil", ":", "err", "=", "errwrite", "\n", "fallthrough", "\n", "case", "errwrite", "!=", "nil", ":", "i", ".", "Unlock", "(", ")", "\n", "default", ":", "i", ".", "Unlock", "(", ")", "\n", "i", ".", "wg", ".", "Wait", "(", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Close implements notify.watcher interface. It removes all existing watch // descriptors and wakes up producer goroutine by sending data to the write end // of the pipe. The function waits for a signal from producer which means that // all operations on current monitoring instance are done.
[ "Close", "implements", "notify", ".", "watcher", "interface", ".", "It", "removes", "all", "existing", "watch", "descriptors", "and", "wakes", "up", "producer", "goroutine", "by", "sending", "data", "to", "the", "write", "end", "of", "the", "pipe", ".", "The", "function", "waits", "for", "a", "signal", "from", "producer", "which", "means", "that", "all", "operations", "on", "current", "monitoring", "instance", "are", "done", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L374-L397
144,813
rjeczalik/notify
watcher_inotify.go
removeInotifyWatch
func removeInotifyWatch(fd int32, iwd int32) (err error) { if _, err = unix.InotifyRmWatch(int(fd), uint32(iwd)); err != nil && err != unix.EINVAL { return } return nil }
go
func removeInotifyWatch(fd int32, iwd int32) (err error) { if _, err = unix.InotifyRmWatch(int(fd), uint32(iwd)); err != nil && err != unix.EINVAL { return } return nil }
[ "func", "removeInotifyWatch", "(", "fd", "int32", ",", "iwd", "int32", ")", "(", "err", "error", ")", "{", "if", "_", ",", "err", "=", "unix", ".", "InotifyRmWatch", "(", "int", "(", "fd", ")", ",", "uint32", "(", "iwd", ")", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "unix", ".", "EINVAL", "{", "return", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// if path was removed, notify already removed the watch and returns EINVAL error
[ "if", "path", "was", "removed", "notify", "already", "removed", "the", "watch", "and", "returns", "EINVAL", "error" ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_inotify.go#L400-L405
144,814
rjeczalik/notify
watcher_kqueue.go
Stop
func (k *kq) Stop() (err error) { // trigger event used to interrupt Kevent call. _, err = syscall.Write(k.pipefds[1], []byte{0x00}) return }
go
func (k *kq) Stop() (err error) { // trigger event used to interrupt Kevent call. _, err = syscall.Write(k.pipefds[1], []byte{0x00}) return }
[ "func", "(", "k", "*", "kq", ")", "Stop", "(", ")", "(", "err", "error", ")", "{", "// trigger event used to interrupt Kevent call.", "_", ",", "err", "=", "syscall", ".", "Write", "(", "k", ".", "pipefds", "[", "1", "]", ",", "[", "]", "byte", "{", "0x00", "}", ")", "\n", "return", "\n", "}" ]
// Stop implements trigger.
[ "Stop", "implements", "trigger", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_kqueue.go#L45-L49
144,815
rjeczalik/notify
watcher_kqueue.go
Init
func (k *kq) Init() (err error) { if k.fd, err = syscall.Kqueue(); err != nil { return } // Creates pipe used to stop `Kevent` call by registering it, // watching read end and writing to other end of it. if err = syscall.Pipe(k.pipefds[:]); err != nil { return nonil(err, k.Close()) } var kevn [1]syscall.Kevent_t syscall.SetKevent(&kevn[0], k.pipefds[0], syscall.EVFILT_READ, syscall.EV_ADD) if _, err = syscall.Kevent(k.fd, kevn[:], nil, nil); err != nil { return nonil(err, k.Close()) } return }
go
func (k *kq) Init() (err error) { if k.fd, err = syscall.Kqueue(); err != nil { return } // Creates pipe used to stop `Kevent` call by registering it, // watching read end and writing to other end of it. if err = syscall.Pipe(k.pipefds[:]); err != nil { return nonil(err, k.Close()) } var kevn [1]syscall.Kevent_t syscall.SetKevent(&kevn[0], k.pipefds[0], syscall.EVFILT_READ, syscall.EV_ADD) if _, err = syscall.Kevent(k.fd, kevn[:], nil, nil); err != nil { return nonil(err, k.Close()) } return }
[ "func", "(", "k", "*", "kq", ")", "Init", "(", ")", "(", "err", "error", ")", "{", "if", "k", ".", "fd", ",", "err", "=", "syscall", ".", "Kqueue", "(", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "// Creates pipe used to stop `Kevent` call by registering it,", "// watching read end and writing to other end of it.", "if", "err", "=", "syscall", ".", "Pipe", "(", "k", ".", "pipefds", "[", ":", "]", ")", ";", "err", "!=", "nil", "{", "return", "nonil", "(", "err", ",", "k", ".", "Close", "(", ")", ")", "\n", "}", "\n", "var", "kevn", "[", "1", "]", "syscall", ".", "Kevent_t", "\n", "syscall", ".", "SetKevent", "(", "&", "kevn", "[", "0", "]", ",", "k", ".", "pipefds", "[", "0", "]", ",", "syscall", ".", "EVFILT_READ", ",", "syscall", ".", "EV_ADD", ")", "\n", "if", "_", ",", "err", "=", "syscall", ".", "Kevent", "(", "k", ".", "fd", ",", "kevn", "[", ":", "]", ",", "nil", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "nonil", "(", "err", ",", "k", ".", "Close", "(", ")", ")", "\n", "}", "\n", "return", "\n", "}" ]
// Init implements trigger.
[ "Init", "implements", "trigger", "." ]
629144ba06a1c6af28c1e42c228e3d42594ce081
https://github.com/rjeczalik/notify/blob/629144ba06a1c6af28c1e42c228e3d42594ce081/watcher_kqueue.go#L89-L104
144,816
adjust/rmq
redis_wrapper.go
checkErr
func checkErr(err error) (ok bool) { switch err { case nil: return true case redis.Nil: return false default: log.Panicf("rmq redis error is not nil %s", err) return false } }
go
func checkErr(err error) (ok bool) { switch err { case nil: return true case redis.Nil: return false default: log.Panicf("rmq redis error is not nil %s", err) return false } }
[ "func", "checkErr", "(", "err", "error", ")", "(", "ok", "bool", ")", "{", "switch", "err", "{", "case", "nil", ":", "return", "true", "\n", "case", "redis", ".", "Nil", ":", "return", "false", "\n", "default", ":", "log", ".", "Panicf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "}" ]
// checkErr returns true if there is no error, false if the result error is nil and panics if there's another error
[ "checkErr", "returns", "true", "if", "there", "is", "no", "error", "false", "if", "the", "result", "error", "is", "nil", "and", "panics", "if", "there", "s", "another", "error" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/redis_wrapper.go#L89-L99
144,817
adjust/rmq
queue.go
Publish
func (queue *redisQueue) Publish(payload string) bool { // debug(fmt.Sprintf("publish %s %s", payload, queue)) // COMMENTOUT return queue.redisClient.LPush(queue.readyKey, payload) }
go
func (queue *redisQueue) Publish(payload string) bool { // debug(fmt.Sprintf("publish %s %s", payload, queue)) // COMMENTOUT return queue.redisClient.LPush(queue.readyKey, payload) }
[ "func", "(", "queue", "*", "redisQueue", ")", "Publish", "(", "payload", "string", ")", "bool", "{", "// debug(fmt.Sprintf(\"publish %s %s\", payload, queue)) // COMMENTOUT", "return", "queue", ".", "redisClient", ".", "LPush", "(", "queue", ".", "readyKey", ",", "payload", ")", "\n", "}" ]
// Publish adds a delivery with the given payload to the queue
[ "Publish", "adds", "a", "delivery", "with", "the", "given", "payload", "to", "the", "queue" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L96-L99
144,818
adjust/rmq
queue.go
PublishBytes
func (queue *redisQueue) PublishBytes(payload []byte) bool { return queue.Publish(string(payload)) }
go
func (queue *redisQueue) PublishBytes(payload []byte) bool { return queue.Publish(string(payload)) }
[ "func", "(", "queue", "*", "redisQueue", ")", "PublishBytes", "(", "payload", "[", "]", "byte", ")", "bool", "{", "return", "queue", ".", "Publish", "(", "string", "(", "payload", ")", ")", "\n", "}" ]
// PublishBytes just casts the bytes and calls Publish
[ "PublishBytes", "just", "casts", "the", "bytes", "and", "calls", "Publish" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L102-L104
144,819
adjust/rmq
queue.go
Close
func (queue *redisQueue) Close() bool { queue.PurgeRejected() queue.PurgeReady() count, _ := queue.redisClient.SRem(queuesKey, queue.name) return count > 0 }
go
func (queue *redisQueue) Close() bool { queue.PurgeRejected() queue.PurgeReady() count, _ := queue.redisClient.SRem(queuesKey, queue.name) return count > 0 }
[ "func", "(", "queue", "*", "redisQueue", ")", "Close", "(", ")", "bool", "{", "queue", ".", "PurgeRejected", "(", ")", "\n", "queue", ".", "PurgeReady", "(", ")", "\n", "count", ",", "_", ":=", "queue", ".", "redisClient", ".", "SRem", "(", "queuesKey", ",", "queue", ".", "name", ")", "\n", "return", "count", ">", "0", "\n", "}" ]
// Close purges and removes the queue from the list of queues
[ "Close", "purges", "and", "removes", "the", "queue", "from", "the", "list", "of", "queues" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L117-L122
144,820
adjust/rmq
queue.go
ReturnAllUnacked
func (queue *redisQueue) ReturnAllUnacked() int { count, ok := queue.redisClient.LLen(queue.unackedKey) if !ok { return 0 } unackedCount := count for i := 0; i < unackedCount; i++ { if _, ok := queue.redisClient.RPopLPush(queue.unackedKey, queue.readyKey); !ok { return i } // debug(fmt.Sprintf("rmq queue returned unacked delivery %s %s", count, queue.readyKey)) // COMMENTOUT } return unackedCount }
go
func (queue *redisQueue) ReturnAllUnacked() int { count, ok := queue.redisClient.LLen(queue.unackedKey) if !ok { return 0 } unackedCount := count for i := 0; i < unackedCount; i++ { if _, ok := queue.redisClient.RPopLPush(queue.unackedKey, queue.readyKey); !ok { return i } // debug(fmt.Sprintf("rmq queue returned unacked delivery %s %s", count, queue.readyKey)) // COMMENTOUT } return unackedCount }
[ "func", "(", "queue", "*", "redisQueue", ")", "ReturnAllUnacked", "(", ")", "int", "{", "count", ",", "ok", ":=", "queue", ".", "redisClient", ".", "LLen", "(", "queue", ".", "unackedKey", ")", "\n", "if", "!", "ok", "{", "return", "0", "\n", "}", "\n\n", "unackedCount", ":=", "count", "\n", "for", "i", ":=", "0", ";", "i", "<", "unackedCount", ";", "i", "++", "{", "if", "_", ",", "ok", ":=", "queue", ".", "redisClient", ".", "RPopLPush", "(", "queue", ".", "unackedKey", ",", "queue", ".", "readyKey", ")", ";", "!", "ok", "{", "return", "i", "\n", "}", "\n", "// debug(fmt.Sprintf(\"rmq queue returned unacked delivery %s %s\", count, queue.readyKey)) // COMMENTOUT", "}", "\n\n", "return", "unackedCount", "\n", "}" ]
// ReturnAllUnacked moves all unacked deliveries back to the ready // queue and deletes the unacked key afterwards, returns number of returned // deliveries
[ "ReturnAllUnacked", "moves", "all", "unacked", "deliveries", "back", "to", "the", "ready", "queue", "and", "deletes", "the", "unacked", "key", "afterwards", "returns", "number", "of", "returned", "deliveries" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L142-L157
144,821
adjust/rmq
queue.go
ReturnAllRejected
func (queue *redisQueue) ReturnAllRejected() int { rejectedCount, _ := queue.redisClient.LLen(queue.rejectedKey) return queue.ReturnRejected(rejectedCount) }
go
func (queue *redisQueue) ReturnAllRejected() int { rejectedCount, _ := queue.redisClient.LLen(queue.rejectedKey) return queue.ReturnRejected(rejectedCount) }
[ "func", "(", "queue", "*", "redisQueue", ")", "ReturnAllRejected", "(", ")", "int", "{", "rejectedCount", ",", "_", ":=", "queue", ".", "redisClient", ".", "LLen", "(", "queue", ".", "rejectedKey", ")", "\n", "return", "queue", ".", "ReturnRejected", "(", "rejectedCount", ")", "\n", "}" ]
// ReturnAllRejected moves all rejected deliveries back to the ready // list and returns the number of returned deliveries
[ "ReturnAllRejected", "moves", "all", "rejected", "deliveries", "back", "to", "the", "ready", "list", "and", "returns", "the", "number", "of", "returned", "deliveries" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L161-L164
144,822
adjust/rmq
queue.go
ReturnRejected
func (queue *redisQueue) ReturnRejected(count int) int { if count == 0 { return 0 } for i := 0; i < count; i++ { _, ok := queue.redisClient.RPopLPush(queue.rejectedKey, queue.readyKey) if !ok { return i } // debug(fmt.Sprintf("rmq queue returned rejected delivery %s %s", value, queue.readyKey)) // COMMENTOUT } return count }
go
func (queue *redisQueue) ReturnRejected(count int) int { if count == 0 { return 0 } for i := 0; i < count; i++ { _, ok := queue.redisClient.RPopLPush(queue.rejectedKey, queue.readyKey) if !ok { return i } // debug(fmt.Sprintf("rmq queue returned rejected delivery %s %s", value, queue.readyKey)) // COMMENTOUT } return count }
[ "func", "(", "queue", "*", "redisQueue", ")", "ReturnRejected", "(", "count", "int", ")", "int", "{", "if", "count", "==", "0", "{", "return", "0", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "count", ";", "i", "++", "{", "_", ",", "ok", ":=", "queue", ".", "redisClient", ".", "RPopLPush", "(", "queue", ".", "rejectedKey", ",", "queue", ".", "readyKey", ")", "\n", "if", "!", "ok", "{", "return", "i", "\n", "}", "\n", "// debug(fmt.Sprintf(\"rmq queue returned rejected delivery %s %s\", value, queue.readyKey)) // COMMENTOUT", "}", "\n\n", "return", "count", "\n", "}" ]
// ReturnRejected tries to return count rejected deliveries back to // the ready list and returns the number of returned deliveries
[ "ReturnRejected", "tries", "to", "return", "count", "rejected", "deliveries", "back", "to", "the", "ready", "list", "and", "returns", "the", "number", "of", "returned", "deliveries" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L168-L182
144,823
adjust/rmq
queue.go
CloseInConnection
func (queue *redisQueue) CloseInConnection() { queue.redisClient.Del(queue.unackedKey) queue.redisClient.Del(queue.consumersKey) queue.redisClient.SRem(queue.queuesKey, queue.name) }
go
func (queue *redisQueue) CloseInConnection() { queue.redisClient.Del(queue.unackedKey) queue.redisClient.Del(queue.consumersKey) queue.redisClient.SRem(queue.queuesKey, queue.name) }
[ "func", "(", "queue", "*", "redisQueue", ")", "CloseInConnection", "(", ")", "{", "queue", ".", "redisClient", ".", "Del", "(", "queue", ".", "unackedKey", ")", "\n", "queue", ".", "redisClient", ".", "Del", "(", "queue", ".", "consumersKey", ")", "\n", "queue", ".", "redisClient", ".", "SRem", "(", "queue", ".", "queuesKey", ",", "queue", ".", "name", ")", "\n", "}" ]
// CloseInConnection closes the queue in the associated connection by removing all related keys
[ "CloseInConnection", "closes", "the", "queue", "in", "the", "associated", "connection", "by", "removing", "all", "related", "keys" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L185-L189
144,824
adjust/rmq
queue.go
StartConsuming
func (queue *redisQueue) StartConsuming(prefetchLimit int, pollDuration time.Duration) bool { if queue.deliveryChan != nil { return false // already consuming } // add queue to list of queues consumed on this connection if ok := queue.redisClient.SAdd(queue.queuesKey, queue.name); !ok { log.Panicf("rmq queue failed to start consuming %s", queue) } queue.prefetchLimit = prefetchLimit queue.pollDuration = pollDuration queue.deliveryChan = make(chan Delivery, prefetchLimit) atomic.StoreInt32(&queue.consumingStopped, 0) // log.Printf("rmq queue started consuming %s %d %s", queue, prefetchLimit, pollDuration) go queue.consume() return true }
go
func (queue *redisQueue) StartConsuming(prefetchLimit int, pollDuration time.Duration) bool { if queue.deliveryChan != nil { return false // already consuming } // add queue to list of queues consumed on this connection if ok := queue.redisClient.SAdd(queue.queuesKey, queue.name); !ok { log.Panicf("rmq queue failed to start consuming %s", queue) } queue.prefetchLimit = prefetchLimit queue.pollDuration = pollDuration queue.deliveryChan = make(chan Delivery, prefetchLimit) atomic.StoreInt32(&queue.consumingStopped, 0) // log.Printf("rmq queue started consuming %s %d %s", queue, prefetchLimit, pollDuration) go queue.consume() return true }
[ "func", "(", "queue", "*", "redisQueue", ")", "StartConsuming", "(", "prefetchLimit", "int", ",", "pollDuration", "time", ".", "Duration", ")", "bool", "{", "if", "queue", ".", "deliveryChan", "!=", "nil", "{", "return", "false", "// already consuming", "\n", "}", "\n\n", "// add queue to list of queues consumed on this connection", "if", "ok", ":=", "queue", ".", "redisClient", ".", "SAdd", "(", "queue", ".", "queuesKey", ",", "queue", ".", "name", ")", ";", "!", "ok", "{", "log", ".", "Panicf", "(", "\"", "\"", ",", "queue", ")", "\n", "}", "\n\n", "queue", ".", "prefetchLimit", "=", "prefetchLimit", "\n", "queue", ".", "pollDuration", "=", "pollDuration", "\n", "queue", ".", "deliveryChan", "=", "make", "(", "chan", "Delivery", ",", "prefetchLimit", ")", "\n", "atomic", ".", "StoreInt32", "(", "&", "queue", ".", "consumingStopped", ",", "0", ")", "\n", "// log.Printf(\"rmq queue started consuming %s %d %s\", queue, prefetchLimit, pollDuration)", "go", "queue", ".", "consume", "(", ")", "\n", "return", "true", "\n", "}" ]
// StartConsuming starts consuming into a channel of size prefetchLimit // must be called before consumers can be added! // pollDuration is the duration the queue sleeps before checking for new deliveries
[ "StartConsuming", "starts", "consuming", "into", "a", "channel", "of", "size", "prefetchLimit", "must", "be", "called", "before", "consumers", "can", "be", "added!", "pollDuration", "is", "the", "duration", "the", "queue", "sleeps", "before", "checking", "for", "new", "deliveries" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L203-L220
144,825
adjust/rmq
queue.go
AddConsumer
func (queue *redisQueue) AddConsumer(tag string, consumer Consumer) string { queue.stopWg.Add(1) name := queue.addConsumer(tag) go queue.consumerConsume(consumer) return name }
go
func (queue *redisQueue) AddConsumer(tag string, consumer Consumer) string { queue.stopWg.Add(1) name := queue.addConsumer(tag) go queue.consumerConsume(consumer) return name }
[ "func", "(", "queue", "*", "redisQueue", ")", "AddConsumer", "(", "tag", "string", ",", "consumer", "Consumer", ")", "string", "{", "queue", ".", "stopWg", ".", "Add", "(", "1", ")", "\n", "name", ":=", "queue", ".", "addConsumer", "(", "tag", ")", "\n", "go", "queue", ".", "consumerConsume", "(", "consumer", ")", "\n", "return", "name", "\n", "}" ]
// AddConsumer adds a consumer to the queue and returns its internal name // panics if StartConsuming wasn't called before!
[ "AddConsumer", "adds", "a", "consumer", "to", "the", "queue", "and", "returns", "its", "internal", "name", "panics", "if", "StartConsuming", "wasn", "t", "called", "before!" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L242-L247
144,826
adjust/rmq
queue.go
AddBatchConsumer
func (queue *redisQueue) AddBatchConsumer(tag string, batchSize int, consumer BatchConsumer) string { return queue.AddBatchConsumerWithTimeout(tag, batchSize, defaultBatchTimeout, consumer) }
go
func (queue *redisQueue) AddBatchConsumer(tag string, batchSize int, consumer BatchConsumer) string { return queue.AddBatchConsumerWithTimeout(tag, batchSize, defaultBatchTimeout, consumer) }
[ "func", "(", "queue", "*", "redisQueue", ")", "AddBatchConsumer", "(", "tag", "string", ",", "batchSize", "int", ",", "consumer", "BatchConsumer", ")", "string", "{", "return", "queue", ".", "AddBatchConsumerWithTimeout", "(", "tag", ",", "batchSize", ",", "defaultBatchTimeout", ",", "consumer", ")", "\n", "}" ]
// AddBatchConsumer is similar to AddConsumer, but for batches of deliveries
[ "AddBatchConsumer", "is", "similar", "to", "AddConsumer", "but", "for", "batches", "of", "deliveries" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L254-L256
144,827
adjust/rmq
queue.go
AddBatchConsumerWithTimeout
func (queue *redisQueue) AddBatchConsumerWithTimeout(tag string, batchSize int, timeout time.Duration, consumer BatchConsumer) string { queue.stopWg.Add(1) name := queue.addConsumer(tag) go queue.consumerBatchConsume(batchSize, timeout, consumer) return name }
go
func (queue *redisQueue) AddBatchConsumerWithTimeout(tag string, batchSize int, timeout time.Duration, consumer BatchConsumer) string { queue.stopWg.Add(1) name := queue.addConsumer(tag) go queue.consumerBatchConsume(batchSize, timeout, consumer) return name }
[ "func", "(", "queue", "*", "redisQueue", ")", "AddBatchConsumerWithTimeout", "(", "tag", "string", ",", "batchSize", "int", ",", "timeout", "time", ".", "Duration", ",", "consumer", "BatchConsumer", ")", "string", "{", "queue", ".", "stopWg", ".", "Add", "(", "1", ")", "\n", "name", ":=", "queue", ".", "addConsumer", "(", "tag", ")", "\n", "go", "queue", ".", "consumerBatchConsume", "(", "batchSize", ",", "timeout", ",", "consumer", ")", "\n", "return", "name", "\n", "}" ]
// Timeout limits the amount of time waiting to fill an entire batch // The timer is only started when the first message in a batch is received
[ "Timeout", "limits", "the", "amount", "of", "time", "waiting", "to", "fill", "an", "entire", "batch", "The", "timer", "is", "only", "started", "when", "the", "first", "message", "in", "a", "batch", "is", "received" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L260-L265
144,828
adjust/rmq
queue.go
consumeBatch
func (queue *redisQueue) consumeBatch(batchSize int) bool { if batchSize == 0 { return false } for i := 0; i < batchSize; i++ { value, ok := queue.redisClient.RPopLPush(queue.readyKey, queue.unackedKey) if !ok { // debug(fmt.Sprintf("rmq queue consumed last batch %s %d", queue, i)) // COMMENTOUT return false } // debug(fmt.Sprintf("consume %d/%d %s %s", i, batchSize, value, queue)) // COMMENTOUT queue.deliveryChan <- newDelivery(value, queue.unackedKey, queue.rejectedKey, queue.pushKey, queue.redisClient) } // debug(fmt.Sprintf("rmq queue consumed batch %s %d", queue, batchSize)) // COMMENTOUT return true }
go
func (queue *redisQueue) consumeBatch(batchSize int) bool { if batchSize == 0 { return false } for i := 0; i < batchSize; i++ { value, ok := queue.redisClient.RPopLPush(queue.readyKey, queue.unackedKey) if !ok { // debug(fmt.Sprintf("rmq queue consumed last batch %s %d", queue, i)) // COMMENTOUT return false } // debug(fmt.Sprintf("consume %d/%d %s %s", i, batchSize, value, queue)) // COMMENTOUT queue.deliveryChan <- newDelivery(value, queue.unackedKey, queue.rejectedKey, queue.pushKey, queue.redisClient) } // debug(fmt.Sprintf("rmq queue consumed batch %s %d", queue, batchSize)) // COMMENTOUT return true }
[ "func", "(", "queue", "*", "redisQueue", ")", "consumeBatch", "(", "batchSize", "int", ")", "bool", "{", "if", "batchSize", "==", "0", "{", "return", "false", "\n", "}", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "batchSize", ";", "i", "++", "{", "value", ",", "ok", ":=", "queue", ".", "redisClient", ".", "RPopLPush", "(", "queue", ".", "readyKey", ",", "queue", ".", "unackedKey", ")", "\n", "if", "!", "ok", "{", "// debug(fmt.Sprintf(\"rmq queue consumed last batch %s %d\", queue, i)) // COMMENTOUT", "return", "false", "\n", "}", "\n\n", "// debug(fmt.Sprintf(\"consume %d/%d %s %s\", i, batchSize, value, queue)) // COMMENTOUT", "queue", ".", "deliveryChan", "<-", "newDelivery", "(", "value", ",", "queue", ".", "unackedKey", ",", "queue", ".", "rejectedKey", ",", "queue", ".", "pushKey", ",", "queue", ".", "redisClient", ")", "\n", "}", "\n\n", "// debug(fmt.Sprintf(\"rmq queue consumed batch %s %d\", queue, batchSize)) // COMMENTOUT", "return", "true", "\n", "}" ]
// consumeBatch tries to read batchSize deliveries, returns true if any and all were consumed
[ "consumeBatch", "tries", "to", "read", "batchSize", "deliveries", "returns", "true", "if", "any", "and", "all", "were", "consumed" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/queue.go#L326-L344
144,829
adjust/rmq
connection.go
OpenConnectionWithRedisClient
func OpenConnectionWithRedisClient(tag string, redisClient *redis.Client) *redisConnection { return openConnectionWithRedisClient(tag, RedisWrapper{redisClient}) }
go
func OpenConnectionWithRedisClient(tag string, redisClient *redis.Client) *redisConnection { return openConnectionWithRedisClient(tag, RedisWrapper{redisClient}) }
[ "func", "OpenConnectionWithRedisClient", "(", "tag", "string", ",", "redisClient", "*", "redis", ".", "Client", ")", "*", "redisConnection", "{", "return", "openConnectionWithRedisClient", "(", "tag", ",", "RedisWrapper", "{", "redisClient", "}", ")", "\n", "}" ]
// OpenConnectionWithRedisClient opens and returns a new connection
[ "OpenConnectionWithRedisClient", "opens", "and", "returns", "a", "new", "connection" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L33-L35
144,830
adjust/rmq
connection.go
OpenConnection
func OpenConnection(tag, network, address string, db int) *redisConnection { redisClient := redis.NewClient(&redis.Options{ Network: network, Addr: address, DB: db, }) return OpenConnectionWithRedisClient(tag, redisClient) }
go
func OpenConnection(tag, network, address string, db int) *redisConnection { redisClient := redis.NewClient(&redis.Options{ Network: network, Addr: address, DB: db, }) return OpenConnectionWithRedisClient(tag, redisClient) }
[ "func", "OpenConnection", "(", "tag", ",", "network", ",", "address", "string", ",", "db", "int", ")", "*", "redisConnection", "{", "redisClient", ":=", "redis", ".", "NewClient", "(", "&", "redis", ".", "Options", "{", "Network", ":", "network", ",", "Addr", ":", "address", ",", "DB", ":", "db", ",", "}", ")", "\n", "return", "OpenConnectionWithRedisClient", "(", "tag", ",", "redisClient", ")", "\n", "}" ]
// OpenConnection opens and returns a new connection
[ "OpenConnection", "opens", "and", "returns", "a", "new", "connection" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L66-L73
144,831
adjust/rmq
connection.go
OpenQueue
func (connection *redisConnection) OpenQueue(name string) Queue { connection.redisClient.SAdd(queuesKey, name) queue := newQueue(name, connection.Name, connection.queuesKey, connection.redisClient) return queue }
go
func (connection *redisConnection) OpenQueue(name string) Queue { connection.redisClient.SAdd(queuesKey, name) queue := newQueue(name, connection.Name, connection.queuesKey, connection.redisClient) return queue }
[ "func", "(", "connection", "*", "redisConnection", ")", "OpenQueue", "(", "name", "string", ")", "Queue", "{", "connection", ".", "redisClient", ".", "SAdd", "(", "queuesKey", ",", "name", ")", "\n", "queue", ":=", "newQueue", "(", "name", ",", "connection", ".", "Name", ",", "connection", ".", "queuesKey", ",", "connection", ".", "redisClient", ")", "\n", "return", "queue", "\n", "}" ]
// OpenQueue opens and returns the queue with a given name
[ "OpenQueue", "opens", "and", "returns", "the", "queue", "with", "a", "given", "name" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L76-L80
144,832
adjust/rmq
connection.go
Check
func (connection *redisConnection) Check() bool { heartbeatKey := strings.Replace(connectionHeartbeatTemplate, phConnection, connection.Name, 1) ttl, _ := connection.redisClient.TTL(heartbeatKey) return ttl > 0 }
go
func (connection *redisConnection) Check() bool { heartbeatKey := strings.Replace(connectionHeartbeatTemplate, phConnection, connection.Name, 1) ttl, _ := connection.redisClient.TTL(heartbeatKey) return ttl > 0 }
[ "func", "(", "connection", "*", "redisConnection", ")", "Check", "(", ")", "bool", "{", "heartbeatKey", ":=", "strings", ".", "Replace", "(", "connectionHeartbeatTemplate", ",", "phConnection", ",", "connection", ".", "Name", ",", "1", ")", "\n", "ttl", ",", "_", ":=", "connection", ".", "redisClient", ".", "TTL", "(", "heartbeatKey", ")", "\n", "return", "ttl", ">", "0", "\n", "}" ]
// Check retuns true if the connection is currently active in terms of heartbeat
[ "Check", "retuns", "true", "if", "the", "connection", "is", "currently", "active", "in", "terms", "of", "heartbeat" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L96-L100
144,833
adjust/rmq
connection.go
StopHeartbeat
func (connection *redisConnection) StopHeartbeat() bool { connection.heartbeatStopped = true _, ok := connection.redisClient.Del(connection.heartbeatKey) return ok }
go
func (connection *redisConnection) StopHeartbeat() bool { connection.heartbeatStopped = true _, ok := connection.redisClient.Del(connection.heartbeatKey) return ok }
[ "func", "(", "connection", "*", "redisConnection", ")", "StopHeartbeat", "(", ")", "bool", "{", "connection", ".", "heartbeatStopped", "=", "true", "\n", "_", ",", "ok", ":=", "connection", ".", "redisClient", ".", "Del", "(", "connection", ".", "heartbeatKey", ")", "\n", "return", "ok", "\n", "}" ]
// StopHeartbeat stops the heartbeat of the connection // it does not remove it from the list of connections so it can later be found by the cleaner
[ "StopHeartbeat", "stops", "the", "heartbeat", "of", "the", "connection", "it", "does", "not", "remove", "it", "from", "the", "list", "of", "connections", "so", "it", "can", "later", "be", "found", "by", "the", "cleaner" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L104-L108
144,834
adjust/rmq
connection.go
CloseAllQueues
func (connection *redisConnection) CloseAllQueues() int { count, _ := connection.redisClient.Del(queuesKey) return count }
go
func (connection *redisConnection) CloseAllQueues() int { count, _ := connection.redisClient.Del(queuesKey) return count }
[ "func", "(", "connection", "*", "redisConnection", ")", "CloseAllQueues", "(", ")", "int", "{", "count", ",", "_", ":=", "connection", ".", "redisClient", ".", "Del", "(", "queuesKey", ")", "\n", "return", "count", "\n", "}" ]
// CloseAllQueues closes all queues by removing them from the global list
[ "CloseAllQueues", "closes", "all", "queues", "by", "removing", "them", "from", "the", "global", "list" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L121-L124
144,835
adjust/rmq
connection.go
CloseAllQueuesInConnection
func (connection *redisConnection) CloseAllQueuesInConnection() error { connection.redisClient.Del(connection.queuesKey) // debug(fmt.Sprintf("connection closed all queues %s %d", connection, connection.queuesKey)) // COMMENTOUT return nil }
go
func (connection *redisConnection) CloseAllQueuesInConnection() error { connection.redisClient.Del(connection.queuesKey) // debug(fmt.Sprintf("connection closed all queues %s %d", connection, connection.queuesKey)) // COMMENTOUT return nil }
[ "func", "(", "connection", "*", "redisConnection", ")", "CloseAllQueuesInConnection", "(", ")", "error", "{", "connection", ".", "redisClient", ".", "Del", "(", "connection", ".", "queuesKey", ")", "\n", "// debug(fmt.Sprintf(\"connection closed all queues %s %d\", connection, connection.queuesKey)) // COMMENTOUT", "return", "nil", "\n", "}" ]
// CloseAllQueuesInConnection closes all queues in the associated connection by removing all related keys
[ "CloseAllQueuesInConnection", "closes", "all", "queues", "in", "the", "associated", "connection", "by", "removing", "all", "related", "keys" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L127-L131
144,836
adjust/rmq
connection.go
heartbeat
func (connection *redisConnection) heartbeat() { for { if !connection.updateHeartbeat() { // log.Printf("rmq connection failed to update heartbeat %s", connection) } time.Sleep(time.Second) if connection.heartbeatStopped { // log.Printf("rmq connection stopped heartbeat %s", connection) return } } }
go
func (connection *redisConnection) heartbeat() { for { if !connection.updateHeartbeat() { // log.Printf("rmq connection failed to update heartbeat %s", connection) } time.Sleep(time.Second) if connection.heartbeatStopped { // log.Printf("rmq connection stopped heartbeat %s", connection) return } } }
[ "func", "(", "connection", "*", "redisConnection", ")", "heartbeat", "(", ")", "{", "for", "{", "if", "!", "connection", ".", "updateHeartbeat", "(", ")", "{", "// log.Printf(\"rmq connection failed to update heartbeat %s\", connection)", "}", "\n\n", "time", ".", "Sleep", "(", "time", ".", "Second", ")", "\n\n", "if", "connection", ".", "heartbeatStopped", "{", "// log.Printf(\"rmq connection stopped heartbeat %s\", connection)", "return", "\n", "}", "\n", "}", "\n", "}" ]
// heartbeat keeps the heartbeat key alive
[ "heartbeat", "keeps", "the", "heartbeat", "key", "alive" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L139-L152
144,837
adjust/rmq
connection.go
hijackConnection
func (connection *redisConnection) hijackConnection(name string) *redisConnection { return &redisConnection{ Name: name, heartbeatKey: strings.Replace(connectionHeartbeatTemplate, phConnection, name, 1), queuesKey: strings.Replace(connectionQueuesTemplate, phConnection, name, 1), redisClient: connection.redisClient, } }
go
func (connection *redisConnection) hijackConnection(name string) *redisConnection { return &redisConnection{ Name: name, heartbeatKey: strings.Replace(connectionHeartbeatTemplate, phConnection, name, 1), queuesKey: strings.Replace(connectionQueuesTemplate, phConnection, name, 1), redisClient: connection.redisClient, } }
[ "func", "(", "connection", "*", "redisConnection", ")", "hijackConnection", "(", "name", "string", ")", "*", "redisConnection", "{", "return", "&", "redisConnection", "{", "Name", ":", "name", ",", "heartbeatKey", ":", "strings", ".", "Replace", "(", "connectionHeartbeatTemplate", ",", "phConnection", ",", "name", ",", "1", ")", ",", "queuesKey", ":", "strings", ".", "Replace", "(", "connectionQueuesTemplate", ",", "phConnection", ",", "name", ",", "1", ")", ",", "redisClient", ":", "connection", ".", "redisClient", ",", "}", "\n", "}" ]
// hijackConnection reopens an existing connection for inspection purposes without starting a heartbeat
[ "hijackConnection", "reopens", "an", "existing", "connection", "for", "inspection", "purposes", "without", "starting", "a", "heartbeat" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L160-L167
144,838
adjust/rmq
connection.go
openQueue
func (connection *redisConnection) openQueue(name string) *redisQueue { return newQueue(name, connection.Name, connection.queuesKey, connection.redisClient) }
go
func (connection *redisConnection) openQueue(name string) *redisQueue { return newQueue(name, connection.Name, connection.queuesKey, connection.redisClient) }
[ "func", "(", "connection", "*", "redisConnection", ")", "openQueue", "(", "name", "string", ")", "*", "redisQueue", "{", "return", "newQueue", "(", "name", ",", "connection", ".", "Name", ",", "connection", ".", "queuesKey", ",", "connection", ".", "redisClient", ")", "\n", "}" ]
// openQueue opens a queue without adding it to the set of queues
[ "openQueue", "opens", "a", "queue", "without", "adding", "it", "to", "the", "set", "of", "queues" ]
d0da8bbb71c869171bf054c3ae60ecee3012b249
https://github.com/adjust/rmq/blob/d0da8bbb71c869171bf054c3ae60ecee3012b249/connection.go#L170-L172
144,839
vdobler/chart
chart.go
Reset
func (r *Range) Reset() { r.Min, r.Max = 0, 0 r.TMin, r.TMax = time.Time{}, time.Time{} r.Tics = nil r.Norm, r.InvNorm = nil, nil r.Data2Screen, r.Screen2Data = nil, nil if !r.TicSetting.UserDelta { r.TicSetting.Delta = 0 r.TicSetting.TDelta = nil } }
go
func (r *Range) Reset() { r.Min, r.Max = 0, 0 r.TMin, r.TMax = time.Time{}, time.Time{} r.Tics = nil r.Norm, r.InvNorm = nil, nil r.Data2Screen, r.Screen2Data = nil, nil if !r.TicSetting.UserDelta { r.TicSetting.Delta = 0 r.TicSetting.TDelta = nil } }
[ "func", "(", "r", "*", "Range", ")", "Reset", "(", ")", "{", "r", ".", "Min", ",", "r", ".", "Max", "=", "0", ",", "0", "\n", "r", ".", "TMin", ",", "r", ".", "TMax", "=", "time", ".", "Time", "{", "}", ",", "time", ".", "Time", "{", "}", "\n", "r", ".", "Tics", "=", "nil", "\n", "r", ".", "Norm", ",", "r", ".", "InvNorm", "=", "nil", ",", "nil", "\n", "r", ".", "Data2Screen", ",", "r", ".", "Screen2Data", "=", "nil", ",", "nil", "\n\n", "if", "!", "r", ".", "TicSetting", ".", "UserDelta", "{", "r", ".", "TicSetting", ".", "Delta", "=", "0", "\n", "r", ".", "TicSetting", ".", "TDelta", "=", "nil", "\n", "}", "\n", "}" ]
// Reset the fields in r which have been set up during a plot.
[ "Reset", "the", "fields", "in", "r", "which", "have", "been", "set", "up", "during", "a", "plot", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/chart.go#L143-L154
144,840
vdobler/chart
chart.go
autoscale
func (r *Range) autoscale(x float64) { if x < r.DataMin && !r.MinMode.Fixed { if !r.MinMode.Constrained { // full autoscaling r.DataMin = x } else { r.DataMin = fmin(fmax(x, r.MinMode.Lower), r.DataMin) } } if x > r.DataMax && !r.MaxMode.Fixed { if !r.MaxMode.Constrained { // full autoscaling r.DataMax = x } else { r.DataMax = fmax(fmin(x, r.MaxMode.Upper), r.DataMax) } } }
go
func (r *Range) autoscale(x float64) { if x < r.DataMin && !r.MinMode.Fixed { if !r.MinMode.Constrained { // full autoscaling r.DataMin = x } else { r.DataMin = fmin(fmax(x, r.MinMode.Lower), r.DataMin) } } if x > r.DataMax && !r.MaxMode.Fixed { if !r.MaxMode.Constrained { // full autoscaling r.DataMax = x } else { r.DataMax = fmax(fmin(x, r.MaxMode.Upper), r.DataMax) } } }
[ "func", "(", "r", "*", "Range", ")", "autoscale", "(", "x", "float64", ")", "{", "if", "x", "<", "r", ".", "DataMin", "&&", "!", "r", ".", "MinMode", ".", "Fixed", "{", "if", "!", "r", ".", "MinMode", ".", "Constrained", "{", "// full autoscaling", "r", ".", "DataMin", "=", "x", "\n", "}", "else", "{", "r", ".", "DataMin", "=", "fmin", "(", "fmax", "(", "x", ",", "r", ".", "MinMode", ".", "Lower", ")", ",", "r", ".", "DataMin", ")", "\n", "}", "\n", "}", "\n\n", "if", "x", ">", "r", ".", "DataMax", "&&", "!", "r", ".", "MaxMode", ".", "Fixed", "{", "if", "!", "r", ".", "MaxMode", ".", "Constrained", "{", "// full autoscaling", "r", ".", "DataMax", "=", "x", "\n", "}", "else", "{", "r", ".", "DataMax", "=", "fmax", "(", "fmin", "(", "x", ",", "r", ".", "MaxMode", ".", "Upper", ")", ",", "r", ".", "DataMax", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Update DataMin and DataMax according to the RangeModes.
[ "Update", "DataMin", "and", "DataMax", "according", "to", "the", "RangeModes", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/chart.go#L213-L232
144,841
vdobler/chart
box.go
AddData
func (c *BoxChart) AddData(name string, data []Box, style Style) { c.Data = append(c.Data, BoxChartData{name, style, data}) ps := PlotStyle(PlotStylePoints | PlotStyleBox) c.Key.Entries = append(c.Key.Entries, KeyEntry{Text: name, Style: style, PlotStyle: ps}) // TODO(vodo) min, max }
go
func (c *BoxChart) AddData(name string, data []Box, style Style) { c.Data = append(c.Data, BoxChartData{name, style, data}) ps := PlotStyle(PlotStylePoints | PlotStyleBox) c.Key.Entries = append(c.Key.Entries, KeyEntry{Text: name, Style: style, PlotStyle: ps}) // TODO(vodo) min, max }
[ "func", "(", "c", "*", "BoxChart", ")", "AddData", "(", "name", "string", ",", "data", "[", "]", "Box", ",", "style", "Style", ")", "{", "c", ".", "Data", "=", "append", "(", "c", ".", "Data", ",", "BoxChartData", "{", "name", ",", "style", ",", "data", "}", ")", "\n", "ps", ":=", "PlotStyle", "(", "PlotStylePoints", "|", "PlotStyleBox", ")", "\n", "c", ".", "Key", ".", "Entries", "=", "append", "(", "c", ".", "Key", ".", "Entries", ",", "KeyEntry", "{", "Text", ":", "name", ",", "Style", ":", "style", ",", "PlotStyle", ":", "ps", "}", ")", "\n", "// TODO(vodo) min, max", "}" ]
// AddData adds all boxes in data to the chart.
[ "AddData", "adds", "all", "boxes", "in", "data", "to", "the", "chart", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/box.go#L32-L37
144,842
vdobler/chart
scatter.go
AddDataGeneric
func (c *ScatterChart) AddDataGeneric(name string, data []XYErrValue, plotstyle PlotStyle, style Style) { edata := make([]EPoint, len(data)) for i, d := range data { x, y := d.XVal(), d.YVal() xl, xh := d.XErr() yl, yh := d.YErr() dx, dy := xh-xl, yh-yl xo, yo := xh-dx/2-x, yh-dy/2-y edata[i] = EPoint{X: x, Y: y, DeltaX: dx, DeltaY: dy, OffX: xo, OffY: yo} } c.AddData(name, edata, plotstyle, style) }
go
func (c *ScatterChart) AddDataGeneric(name string, data []XYErrValue, plotstyle PlotStyle, style Style) { edata := make([]EPoint, len(data)) for i, d := range data { x, y := d.XVal(), d.YVal() xl, xh := d.XErr() yl, yh := d.YErr() dx, dy := xh-xl, yh-yl xo, yo := xh-dx/2-x, yh-dy/2-y edata[i] = EPoint{X: x, Y: y, DeltaX: dx, DeltaY: dy, OffX: xo, OffY: yo} } c.AddData(name, edata, plotstyle, style) }
[ "func", "(", "c", "*", "ScatterChart", ")", "AddDataGeneric", "(", "name", "string", ",", "data", "[", "]", "XYErrValue", ",", "plotstyle", "PlotStyle", ",", "style", "Style", ")", "{", "edata", ":=", "make", "(", "[", "]", "EPoint", ",", "len", "(", "data", ")", ")", "\n", "for", "i", ",", "d", ":=", "range", "data", "{", "x", ",", "y", ":=", "d", ".", "XVal", "(", ")", ",", "d", ".", "YVal", "(", ")", "\n", "xl", ",", "xh", ":=", "d", ".", "XErr", "(", ")", "\n", "yl", ",", "yh", ":=", "d", ".", "YErr", "(", ")", "\n", "dx", ",", "dy", ":=", "xh", "-", "xl", ",", "yh", "-", "yl", "\n", "xo", ",", "yo", ":=", "xh", "-", "dx", "/", "2", "-", "x", ",", "yh", "-", "dy", "/", "2", "-", "y", "\n", "edata", "[", "i", "]", "=", "EPoint", "{", "X", ":", "x", ",", "Y", ":", "y", ",", "DeltaX", ":", "dx", ",", "DeltaY", ":", "dy", ",", "OffX", ":", "xo", ",", "OffY", ":", "yo", "}", "\n", "}", "\n", "c", ".", "AddData", "(", "name", ",", "edata", ",", "plotstyle", ",", "style", ")", "\n", "}" ]
// AddDataGeneric is the generiv version of AddData which allows any type // to be plotted that implements the XYErrValue interface.
[ "AddDataGeneric", "is", "the", "generiv", "version", "of", "AddData", "which", "allows", "any", "type", "to", "be", "plotted", "that", "implements", "the", "XYErrValue", "interface", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/scatter.go#L97-L108
144,843
vdobler/chart
scatter.go
Plot
func (c *ScatterChart) Plot(g Graphics) { layout := layout(g, c.Title, c.XRange.Label, c.YRange.Label, c.XRange.TicSetting.Hide || c.XRange.TicSetting.HideLabels, c.YRange.TicSetting.Hide || c.YRange.TicSetting.HideLabels, &c.Key) width, height := layout.Width, layout.Height topm, leftm := layout.Top, layout.Left numxtics, numytics := layout.NumXtics, layout.NumYtics // fmt.Printf("\nSet up of X-Range (%d)\n", numxtics) c.XRange.Setup(numxtics, numxtics+2, width, leftm, false) // fmt.Printf("\nSet up of Y-Range (%d)\n", numytics) c.YRange.Setup(numytics, numytics+2, height, topm, true) g.Begin() if c.Title != "" { drawTitle(g, c.Title, elementStyle(c.Options, TitleElement)) } g.XAxis(c.XRange, topm+height, topm, c.Options) g.YAxis(c.YRange, leftm, leftm+width, c.Options) // Plot Data xf, yf := c.XRange.Data2Screen, c.YRange.Data2Screen xmin, xmax := c.XRange.Min, c.XRange.Max ymin, ymax := c.YRange.Min, c.YRange.Max spf := screenPointFunc(xf, yf, xmin, xmax, ymin, ymax) for i, data := range c.Data { style := data.Style if data.Samples != nil { // Samples points := make([]EPoint, 0, len(data.Samples)) for _, d := range data.Samples { if d.X < xmin || d.X > xmax || d.Y < ymin || d.Y > ymax { continue } p := spf(d) points = append(points, p) } g.Scatter(points, data.PlotStyle, style) } else if data.Func != nil { c.drawFunction(g, i) } } if !c.Key.Hide { g.Key(layout.KeyX, layout.KeyY, c.Key, c.Options) } g.End() }
go
func (c *ScatterChart) Plot(g Graphics) { layout := layout(g, c.Title, c.XRange.Label, c.YRange.Label, c.XRange.TicSetting.Hide || c.XRange.TicSetting.HideLabels, c.YRange.TicSetting.Hide || c.YRange.TicSetting.HideLabels, &c.Key) width, height := layout.Width, layout.Height topm, leftm := layout.Top, layout.Left numxtics, numytics := layout.NumXtics, layout.NumYtics // fmt.Printf("\nSet up of X-Range (%d)\n", numxtics) c.XRange.Setup(numxtics, numxtics+2, width, leftm, false) // fmt.Printf("\nSet up of Y-Range (%d)\n", numytics) c.YRange.Setup(numytics, numytics+2, height, topm, true) g.Begin() if c.Title != "" { drawTitle(g, c.Title, elementStyle(c.Options, TitleElement)) } g.XAxis(c.XRange, topm+height, topm, c.Options) g.YAxis(c.YRange, leftm, leftm+width, c.Options) // Plot Data xf, yf := c.XRange.Data2Screen, c.YRange.Data2Screen xmin, xmax := c.XRange.Min, c.XRange.Max ymin, ymax := c.YRange.Min, c.YRange.Max spf := screenPointFunc(xf, yf, xmin, xmax, ymin, ymax) for i, data := range c.Data { style := data.Style if data.Samples != nil { // Samples points := make([]EPoint, 0, len(data.Samples)) for _, d := range data.Samples { if d.X < xmin || d.X > xmax || d.Y < ymin || d.Y > ymax { continue } p := spf(d) points = append(points, p) } g.Scatter(points, data.PlotStyle, style) } else if data.Func != nil { c.drawFunction(g, i) } } if !c.Key.Hide { g.Key(layout.KeyX, layout.KeyY, c.Key, c.Options) } g.End() }
[ "func", "(", "c", "*", "ScatterChart", ")", "Plot", "(", "g", "Graphics", ")", "{", "layout", ":=", "layout", "(", "g", ",", "c", ".", "Title", ",", "c", ".", "XRange", ".", "Label", ",", "c", ".", "YRange", ".", "Label", ",", "c", ".", "XRange", ".", "TicSetting", ".", "Hide", "||", "c", ".", "XRange", ".", "TicSetting", ".", "HideLabels", ",", "c", ".", "YRange", ".", "TicSetting", ".", "Hide", "||", "c", ".", "YRange", ".", "TicSetting", ".", "HideLabels", ",", "&", "c", ".", "Key", ")", "\n\n", "width", ",", "height", ":=", "layout", ".", "Width", ",", "layout", ".", "Height", "\n", "topm", ",", "leftm", ":=", "layout", ".", "Top", ",", "layout", ".", "Left", "\n", "numxtics", ",", "numytics", ":=", "layout", ".", "NumXtics", ",", "layout", ".", "NumYtics", "\n\n", "// fmt.Printf(\"\\nSet up of X-Range (%d)\\n\", numxtics)", "c", ".", "XRange", ".", "Setup", "(", "numxtics", ",", "numxtics", "+", "2", ",", "width", ",", "leftm", ",", "false", ")", "\n", "// fmt.Printf(\"\\nSet up of Y-Range (%d)\\n\", numytics)", "c", ".", "YRange", ".", "Setup", "(", "numytics", ",", "numytics", "+", "2", ",", "height", ",", "topm", ",", "true", ")", "\n\n", "g", ".", "Begin", "(", ")", "\n\n", "if", "c", ".", "Title", "!=", "\"", "\"", "{", "drawTitle", "(", "g", ",", "c", ".", "Title", ",", "elementStyle", "(", "c", ".", "Options", ",", "TitleElement", ")", ")", "\n", "}", "\n\n", "g", ".", "XAxis", "(", "c", ".", "XRange", ",", "topm", "+", "height", ",", "topm", ",", "c", ".", "Options", ")", "\n", "g", ".", "YAxis", "(", "c", ".", "YRange", ",", "leftm", ",", "leftm", "+", "width", ",", "c", ".", "Options", ")", "\n\n", "// Plot Data", "xf", ",", "yf", ":=", "c", ".", "XRange", ".", "Data2Screen", ",", "c", ".", "YRange", ".", "Data2Screen", "\n", "xmin", ",", "xmax", ":=", "c", ".", "XRange", ".", "Min", ",", "c", ".", "XRange", ".", "Max", "\n", "ymin", ",", "ymax", ":=", "c", ".", "YRange", ".", "Min", ",", "c", ".", "YRange", ".", "Max", "\n", "spf", ":=", "screenPointFunc", "(", "xf", ",", "yf", ",", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", ")", "\n\n", "for", "i", ",", "data", ":=", "range", "c", ".", "Data", "{", "style", ":=", "data", ".", "Style", "\n", "if", "data", ".", "Samples", "!=", "nil", "{", "// Samples", "points", ":=", "make", "(", "[", "]", "EPoint", ",", "0", ",", "len", "(", "data", ".", "Samples", ")", ")", "\n", "for", "_", ",", "d", ":=", "range", "data", ".", "Samples", "{", "if", "d", ".", "X", "<", "xmin", "||", "d", ".", "X", ">", "xmax", "||", "d", ".", "Y", "<", "ymin", "||", "d", ".", "Y", ">", "ymax", "{", "continue", "\n", "}", "\n", "p", ":=", "spf", "(", "d", ")", "\n", "points", "=", "append", "(", "points", ",", "p", ")", "\n", "}", "\n", "g", ".", "Scatter", "(", "points", ",", "data", ".", "PlotStyle", ",", "style", ")", "\n", "}", "else", "if", "data", ".", "Func", "!=", "nil", "{", "c", ".", "drawFunction", "(", "g", ",", "i", ")", "\n", "}", "\n", "}", "\n\n", "if", "!", "c", ".", "Key", ".", "Hide", "{", "g", ".", "Key", "(", "layout", ".", "KeyX", ",", "layout", ".", "KeyY", ",", "c", ".", "Key", ",", "c", ".", "Options", ")", "\n", "}", "\n\n", "g", ".", "End", "(", ")", "\n", "}" ]
// Plot outputs the scatter chart to the graphic output g.
[ "Plot", "outputs", "the", "scatter", "chart", "to", "the", "graphic", "output", "g", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/scatter.go#L129-L182
144,844
vdobler/chart
scatter.go
clipPoint
func (c *ScatterChart) clipPoint(in, out EPoint, min, max float64) (p EPoint) { // fmt.Printf("clipPoint: in (%g,%g), out(%g,%g) min/max=%g/%g\n", in.X, in.Y, out.X, out.Y, min, max) dx, dy := in.X-out.X, in.Y-out.Y var y float64 if out.Y <= min { y = min } else { y = max } x := in.X + dx*(y-in.Y)/dy p.X, p.Y = x, y p.DeltaX, p.DeltaY = math.NaN(), math.NaN() return }
go
func (c *ScatterChart) clipPoint(in, out EPoint, min, max float64) (p EPoint) { // fmt.Printf("clipPoint: in (%g,%g), out(%g,%g) min/max=%g/%g\n", in.X, in.Y, out.X, out.Y, min, max) dx, dy := in.X-out.X, in.Y-out.Y var y float64 if out.Y <= min { y = min } else { y = max } x := in.X + dx*(y-in.Y)/dy p.X, p.Y = x, y p.DeltaX, p.DeltaY = math.NaN(), math.NaN() return }
[ "func", "(", "c", "*", "ScatterChart", ")", "clipPoint", "(", "in", ",", "out", "EPoint", ",", "min", ",", "max", "float64", ")", "(", "p", "EPoint", ")", "{", "// fmt.Printf(\"clipPoint: in (%g,%g), out(%g,%g) min/max=%g/%g\\n\", in.X, in.Y, out.X, out.Y, min, max)", "dx", ",", "dy", ":=", "in", ".", "X", "-", "out", ".", "X", ",", "in", ".", "Y", "-", "out", ".", "Y", "\n\n", "var", "y", "float64", "\n", "if", "out", ".", "Y", "<=", "min", "{", "y", "=", "min", "\n", "}", "else", "{", "y", "=", "max", "\n", "}", "\n", "x", ":=", "in", ".", "X", "+", "dx", "*", "(", "y", "-", "in", ".", "Y", ")", "/", "dy", "\n", "p", ".", "X", ",", "p", ".", "Y", "=", "x", ",", "y", "\n", "p", ".", "DeltaX", ",", "p", ".", "DeltaY", "=", "math", ".", "NaN", "(", ")", ",", "math", ".", "NaN", "(", ")", "\n", "return", "\n", "}" ]
// Point in is in valid y range, out is out. Return p which clips the line from in to out to valid y range
[ "Point", "in", "is", "in", "valid", "y", "range", "out", "is", "out", ".", "Return", "p", "which", "clips", "the", "line", "from", "in", "to", "out", "to", "valid", "y", "range" ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/scatter.go#L267-L281
144,845
vdobler/chart
scatter.go
screenPointFunc
func screenPointFunc(xf, yf func(float64) int, xmin, xmax, ymin, ymax float64) (spf func(EPoint) EPoint) { spf = func(d EPoint) (p EPoint) { xl, yl, xh, yh := d.BoundingBox() // fmt.Printf("OrigBB: %.1f %.1f %.1f %.1f (%.1f,%.1f)\n", xl,yl,xh,yh,d.X,d.Y) if xl < xmin { xl = xmin } if xh > xmax { xh = xmax } if yl < ymin { yl = ymin } if yh > ymax { yh = ymax } // fmt.Printf("ClippedBB: %.1f %.1f %.1f %.1f\n", xl,yl,xh,yh) x := float64(xf(d.X)) y := float64(yf(d.Y)) xsl, xsh := float64(xf(xl)), float64(xf(xh)) ysl, ysh := float64(yf(yl)), float64(yf(yh)) // fmt.Printf("ScreenBB: %.0f %.0f %.0f %.0f (%.0f,%.0f)\n", xsl,ysl,xsh,ysh,x,y) dx, dy := math.NaN(), math.NaN() var xo, yo float64 if xsl != xsh { dx = math.Abs(xsh - xsl) xo = xsl - x + dx/2 } if ysl != ysh { dy = math.Abs(ysh - ysl) yo = ysh - y + dy/2 } // fmt.Printf(" >> dx=%.0f dy=%.0f xo=%.0f yo=%.0f\n", dx,dy,xo,yo) p = EPoint{X: x, Y: y, DeltaX: dx, DeltaY: dy, OffX: xo, OffY: yo} return /************************** if xl < xmin { // happens only if d.Delta!=0,NaN a := xmin - xl d.DeltaX -= a d.OffX += a / 2 } if xh > xmax { a := xh - xmax d.DeltaX -= a d.OffX -= a / 2 } if yl < ymin { // happens only if d.Delta!=0,NaN a := ymin - yl d.DeltaY -= a d.OffY += a / 2 } if yh > ymax { a := yh - ymax d.DeltaY -= a d.OffY -= a / 2 } x := xf(d.X) y := yf(d.Y) dx, dy := math.NaN(), math.NaN() var xo, yo float64 if !math.IsNaN(d.DeltaX) { dx = float64(xf(d.DeltaX) - xf(0)) // TODO: abs? xo = float64(xf(d.OffX) - xf(0)) } if !math.IsNaN(d.DeltaY) { dy = float64(yf(d.DeltaY) - yf(0)) // TODO: abs? yo = float64(yf(d.OffY) - yf(0)) } // fmt.Printf("Point %d: %f\n", i, dx) p = EPoint{X: float64(x), Y: float64(y), DeltaX: dx, DeltaY: dy, OffX: xo, OffY: yo} return *********************/ } return }
go
func screenPointFunc(xf, yf func(float64) int, xmin, xmax, ymin, ymax float64) (spf func(EPoint) EPoint) { spf = func(d EPoint) (p EPoint) { xl, yl, xh, yh := d.BoundingBox() // fmt.Printf("OrigBB: %.1f %.1f %.1f %.1f (%.1f,%.1f)\n", xl,yl,xh,yh,d.X,d.Y) if xl < xmin { xl = xmin } if xh > xmax { xh = xmax } if yl < ymin { yl = ymin } if yh > ymax { yh = ymax } // fmt.Printf("ClippedBB: %.1f %.1f %.1f %.1f\n", xl,yl,xh,yh) x := float64(xf(d.X)) y := float64(yf(d.Y)) xsl, xsh := float64(xf(xl)), float64(xf(xh)) ysl, ysh := float64(yf(yl)), float64(yf(yh)) // fmt.Printf("ScreenBB: %.0f %.0f %.0f %.0f (%.0f,%.0f)\n", xsl,ysl,xsh,ysh,x,y) dx, dy := math.NaN(), math.NaN() var xo, yo float64 if xsl != xsh { dx = math.Abs(xsh - xsl) xo = xsl - x + dx/2 } if ysl != ysh { dy = math.Abs(ysh - ysl) yo = ysh - y + dy/2 } // fmt.Printf(" >> dx=%.0f dy=%.0f xo=%.0f yo=%.0f\n", dx,dy,xo,yo) p = EPoint{X: x, Y: y, DeltaX: dx, DeltaY: dy, OffX: xo, OffY: yo} return /************************** if xl < xmin { // happens only if d.Delta!=0,NaN a := xmin - xl d.DeltaX -= a d.OffX += a / 2 } if xh > xmax { a := xh - xmax d.DeltaX -= a d.OffX -= a / 2 } if yl < ymin { // happens only if d.Delta!=0,NaN a := ymin - yl d.DeltaY -= a d.OffY += a / 2 } if yh > ymax { a := yh - ymax d.DeltaY -= a d.OffY -= a / 2 } x := xf(d.X) y := yf(d.Y) dx, dy := math.NaN(), math.NaN() var xo, yo float64 if !math.IsNaN(d.DeltaX) { dx = float64(xf(d.DeltaX) - xf(0)) // TODO: abs? xo = float64(xf(d.OffX) - xf(0)) } if !math.IsNaN(d.DeltaY) { dy = float64(yf(d.DeltaY) - yf(0)) // TODO: abs? yo = float64(yf(d.OffY) - yf(0)) } // fmt.Printf("Point %d: %f\n", i, dx) p = EPoint{X: float64(x), Y: float64(y), DeltaX: dx, DeltaY: dy, OffX: xo, OffY: yo} return *********************/ } return }
[ "func", "screenPointFunc", "(", "xf", ",", "yf", "func", "(", "float64", ")", "int", ",", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", "float64", ")", "(", "spf", "func", "(", "EPoint", ")", "EPoint", ")", "{", "spf", "=", "func", "(", "d", "EPoint", ")", "(", "p", "EPoint", ")", "{", "xl", ",", "yl", ",", "xh", ",", "yh", ":=", "d", ".", "BoundingBox", "(", ")", "\n", "// fmt.Printf(\"OrigBB: %.1f %.1f %.1f %.1f (%.1f,%.1f)\\n\", xl,yl,xh,yh,d.X,d.Y)", "if", "xl", "<", "xmin", "{", "xl", "=", "xmin", "\n", "}", "\n", "if", "xh", ">", "xmax", "{", "xh", "=", "xmax", "\n", "}", "\n", "if", "yl", "<", "ymin", "{", "yl", "=", "ymin", "\n", "}", "\n", "if", "yh", ">", "ymax", "{", "yh", "=", "ymax", "\n", "}", "\n", "// fmt.Printf(\"ClippedBB: %.1f %.1f %.1f %.1f\\n\", xl,yl,xh,yh)", "x", ":=", "float64", "(", "xf", "(", "d", ".", "X", ")", ")", "\n", "y", ":=", "float64", "(", "yf", "(", "d", ".", "Y", ")", ")", "\n", "xsl", ",", "xsh", ":=", "float64", "(", "xf", "(", "xl", ")", ")", ",", "float64", "(", "xf", "(", "xh", ")", ")", "\n", "ysl", ",", "ysh", ":=", "float64", "(", "yf", "(", "yl", ")", ")", ",", "float64", "(", "yf", "(", "yh", ")", ")", "\n", "// fmt.Printf(\"ScreenBB: %.0f %.0f %.0f %.0f (%.0f,%.0f)\\n\", xsl,ysl,xsh,ysh,x,y)", "dx", ",", "dy", ":=", "math", ".", "NaN", "(", ")", ",", "math", ".", "NaN", "(", ")", "\n", "var", "xo", ",", "yo", "float64", "\n\n", "if", "xsl", "!=", "xsh", "{", "dx", "=", "math", ".", "Abs", "(", "xsh", "-", "xsl", ")", "\n", "xo", "=", "xsl", "-", "x", "+", "dx", "/", "2", "\n", "}", "\n", "if", "ysl", "!=", "ysh", "{", "dy", "=", "math", ".", "Abs", "(", "ysh", "-", "ysl", ")", "\n", "yo", "=", "ysh", "-", "y", "+", "dy", "/", "2", "\n", "}", "\n", "// fmt.Printf(\" >> dx=%.0f dy=%.0f xo=%.0f yo=%.0f\\n\", dx,dy,xo,yo)", "p", "=", "EPoint", "{", "X", ":", "x", ",", "Y", ":", "y", ",", "DeltaX", ":", "dx", ",", "DeltaY", ":", "dy", ",", "OffX", ":", "xo", ",", "OffY", ":", "yo", "}", "\n", "return", "\n\n", "/**************************\n\t\tif xl < xmin { // happens only if d.Delta!=0,NaN\n\t\t\ta := xmin - xl\n\t\t\td.DeltaX -= a\n\t\t\td.OffX += a / 2\n\t\t}\n\t\tif xh > xmax {\n\t\t\ta := xh - xmax\n\t\t\td.DeltaX -= a\n\t\t\td.OffX -= a / 2\n\t\t}\n\t\tif yl < ymin { // happens only if d.Delta!=0,NaN\n\t\t\ta := ymin - yl\n\t\t\td.DeltaY -= a\n\t\t\td.OffY += a / 2\n\t\t}\n\t\tif yh > ymax {\n\t\t\ta := yh - ymax\n\t\t\td.DeltaY -= a\n\t\t\td.OffY -= a / 2\n\t\t}\n\n\t\tx := xf(d.X)\n\t\ty := yf(d.Y)\n\t\tdx, dy := math.NaN(), math.NaN()\n\t\tvar xo, yo float64\n\t\tif !math.IsNaN(d.DeltaX) {\n\t\t\tdx = float64(xf(d.DeltaX) - xf(0)) // TODO: abs?\n\t\t\txo = float64(xf(d.OffX) - xf(0))\n\t\t}\n\t\tif !math.IsNaN(d.DeltaY) {\n\t\t\tdy = float64(yf(d.DeltaY) - yf(0)) // TODO: abs?\n\t\t\tyo = float64(yf(d.OffY) - yf(0))\n\t\t}\n\t\t// fmt.Printf(\"Point %d: %f\\n\", i, dx)\n\t\tp = EPoint{X: float64(x), Y: float64(y), DeltaX: dx, DeltaY: dy, OffX: xo, OffY: yo}\n\t\treturn\n\t\t *********************/", "}", "\n", "return", "\n", "}" ]
// Set up function which handles mappig data->screen coordinates and does // proper clipping on the error bars.
[ "Set", "up", "function", "which", "handles", "mappig", "data", "-", ">", "screen", "coordinates", "and", "does", "proper", "clipping", "on", "the", "error", "bars", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/scatter.go#L304-L384
144,846
vdobler/chart
imgg/image.go
New
func New(width, height int, bgcol color.RGBA, font *truetype.Font, fontsize map[chart.FontSize]float64) *ImageGraphics { img := image.NewRGBA(image.Rect(0, 0, width, height)) gc := draw2dimg.NewGraphicContext(img) gc.SetLineJoin(draw2d.BevelJoin) gc.SetLineCap(draw2d.SquareCap) gc.SetStrokeColor(image.Black) gc.SetFillColor(bgcol) gc.Translate(0.5, 0.5) gc.Clear() if font == nil { font = defaultFont } if len(fontsize) == 0 { fontsize = ConstructFontSizes(13) } return &ImageGraphics{Image: img, x0: 0, y0: 0, w: width, h: height, bg: bgcol, gc: gc, font: font, fs: fontsize} }
go
func New(width, height int, bgcol color.RGBA, font *truetype.Font, fontsize map[chart.FontSize]float64) *ImageGraphics { img := image.NewRGBA(image.Rect(0, 0, width, height)) gc := draw2dimg.NewGraphicContext(img) gc.SetLineJoin(draw2d.BevelJoin) gc.SetLineCap(draw2d.SquareCap) gc.SetStrokeColor(image.Black) gc.SetFillColor(bgcol) gc.Translate(0.5, 0.5) gc.Clear() if font == nil { font = defaultFont } if len(fontsize) == 0 { fontsize = ConstructFontSizes(13) } return &ImageGraphics{Image: img, x0: 0, y0: 0, w: width, h: height, bg: bgcol, gc: gc, font: font, fs: fontsize} }
[ "func", "New", "(", "width", ",", "height", "int", ",", "bgcol", "color", ".", "RGBA", ",", "font", "*", "truetype", ".", "Font", ",", "fontsize", "map", "[", "chart", ".", "FontSize", "]", "float64", ")", "*", "ImageGraphics", "{", "img", ":=", "image", ".", "NewRGBA", "(", "image", ".", "Rect", "(", "0", ",", "0", ",", "width", ",", "height", ")", ")", "\n", "gc", ":=", "draw2dimg", ".", "NewGraphicContext", "(", "img", ")", "\n", "gc", ".", "SetLineJoin", "(", "draw2d", ".", "BevelJoin", ")", "\n", "gc", ".", "SetLineCap", "(", "draw2d", ".", "SquareCap", ")", "\n", "gc", ".", "SetStrokeColor", "(", "image", ".", "Black", ")", "\n", "gc", ".", "SetFillColor", "(", "bgcol", ")", "\n", "gc", ".", "Translate", "(", "0.5", ",", "0.5", ")", "\n", "gc", ".", "Clear", "(", ")", "\n", "if", "font", "==", "nil", "{", "font", "=", "defaultFont", "\n", "}", "\n", "if", "len", "(", "fontsize", ")", "==", "0", "{", "fontsize", "=", "ConstructFontSizes", "(", "13", ")", "\n", "}", "\n", "return", "&", "ImageGraphics", "{", "Image", ":", "img", ",", "x0", ":", "0", ",", "y0", ":", "0", ",", "w", ":", "width", ",", "h", ":", "height", ",", "bg", ":", "bgcol", ",", "gc", ":", "gc", ",", "font", ":", "font", ",", "fs", ":", "fontsize", "}", "\n", "}" ]
// New creates a new ImageGraphics including an image.RGBA of dimension w x h // with background bgcol. If font is nil it will use a builtin font. // If fontsize is empty useful default are used.
[ "New", "creates", "a", "new", "ImageGraphics", "including", "an", "image", ".", "RGBA", "of", "dimension", "w", "x", "h", "with", "background", "bgcol", ".", "If", "font", "is", "nil", "it", "will", "use", "a", "builtin", "font", ".", "If", "fontsize", "is", "empty", "useful", "default", "are", "used", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/imgg/image.go#L46-L63
144,847
vdobler/chart
imgg/image.go
textBox
func (ig *ImageGraphics) textBox(t string, font chart.Font, textCol color.Color) image.Image { // Initialize the context. bg := image.NewUniform(color.Alpha{0}) fg := image.NewUniform(textCol) width := ig.TextLen(t, font) size := ig.relFontsizeToPixel(font.Size) c := freetype.NewContext() c.SetDPI(dpi) c.SetFont(ig.font) c.SetFontSize(size) bb := ig.font.Bounds(c.PointToFixed(float64(size))) bbDelta := bb.Max.Sub(bb.Min) height := int(bbDelta.Y+32) >> 6 canvas := image.NewRGBA(image.Rect(0, 0, width, height)) draw.Draw(canvas, canvas.Bounds(), bg, image.ZP, draw.Src) c.SetDst(canvas) c.SetSrc(fg) c.SetClip(canvas.Bounds()) // Draw the text. extent, err := c.DrawString(t, fixed.Point26_6{X: 0, Y: bb.Max.Y}) if err != nil { log.Println(err) return nil } // Ugly heuristic hack: font bounds are pretty high resulting in white top border: Trim. topskip := 1 if size > 15 { topskip = 2 } else if size > 20 { topskip = 3 } return canvas.SubImage(image.Rect(0, topskip, int(extent.X)>>6, height)) }
go
func (ig *ImageGraphics) textBox(t string, font chart.Font, textCol color.Color) image.Image { // Initialize the context. bg := image.NewUniform(color.Alpha{0}) fg := image.NewUniform(textCol) width := ig.TextLen(t, font) size := ig.relFontsizeToPixel(font.Size) c := freetype.NewContext() c.SetDPI(dpi) c.SetFont(ig.font) c.SetFontSize(size) bb := ig.font.Bounds(c.PointToFixed(float64(size))) bbDelta := bb.Max.Sub(bb.Min) height := int(bbDelta.Y+32) >> 6 canvas := image.NewRGBA(image.Rect(0, 0, width, height)) draw.Draw(canvas, canvas.Bounds(), bg, image.ZP, draw.Src) c.SetDst(canvas) c.SetSrc(fg) c.SetClip(canvas.Bounds()) // Draw the text. extent, err := c.DrawString(t, fixed.Point26_6{X: 0, Y: bb.Max.Y}) if err != nil { log.Println(err) return nil } // Ugly heuristic hack: font bounds are pretty high resulting in white top border: Trim. topskip := 1 if size > 15 { topskip = 2 } else if size > 20 { topskip = 3 } return canvas.SubImage(image.Rect(0, topskip, int(extent.X)>>6, height)) }
[ "func", "(", "ig", "*", "ImageGraphics", ")", "textBox", "(", "t", "string", ",", "font", "chart", ".", "Font", ",", "textCol", "color", ".", "Color", ")", "image", ".", "Image", "{", "// Initialize the context.", "bg", ":=", "image", ".", "NewUniform", "(", "color", ".", "Alpha", "{", "0", "}", ")", "\n", "fg", ":=", "image", ".", "NewUniform", "(", "textCol", ")", "\n", "width", ":=", "ig", ".", "TextLen", "(", "t", ",", "font", ")", "\n", "size", ":=", "ig", ".", "relFontsizeToPixel", "(", "font", ".", "Size", ")", "\n\n", "c", ":=", "freetype", ".", "NewContext", "(", ")", "\n", "c", ".", "SetDPI", "(", "dpi", ")", "\n", "c", ".", "SetFont", "(", "ig", ".", "font", ")", "\n", "c", ".", "SetFontSize", "(", "size", ")", "\n", "bb", ":=", "ig", ".", "font", ".", "Bounds", "(", "c", ".", "PointToFixed", "(", "float64", "(", "size", ")", ")", ")", "\n", "bbDelta", ":=", "bb", ".", "Max", ".", "Sub", "(", "bb", ".", "Min", ")", "\n\n", "height", ":=", "int", "(", "bbDelta", ".", "Y", "+", "32", ")", ">>", "6", "\n", "canvas", ":=", "image", ".", "NewRGBA", "(", "image", ".", "Rect", "(", "0", ",", "0", ",", "width", ",", "height", ")", ")", "\n", "draw", ".", "Draw", "(", "canvas", ",", "canvas", ".", "Bounds", "(", ")", ",", "bg", ",", "image", ".", "ZP", ",", "draw", ".", "Src", ")", "\n", "c", ".", "SetDst", "(", "canvas", ")", "\n", "c", ".", "SetSrc", "(", "fg", ")", "\n", "c", ".", "SetClip", "(", "canvas", ".", "Bounds", "(", ")", ")", "\n", "// Draw the text.", "extent", ",", "err", ":=", "c", ".", "DrawString", "(", "t", ",", "fixed", ".", "Point26_6", "{", "X", ":", "0", ",", "Y", ":", "bb", ".", "Max", ".", "Y", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Println", "(", "err", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// Ugly heuristic hack: font bounds are pretty high resulting in white top border: Trim.", "topskip", ":=", "1", "\n", "if", "size", ">", "15", "{", "topskip", "=", "2", "\n", "}", "else", "if", "size", ">", "20", "{", "topskip", "=", "3", "\n", "}", "\n", "return", "canvas", ".", "SubImage", "(", "image", ".", "Rect", "(", "0", ",", "topskip", ",", "int", "(", "extent", ".", "X", ")", ">>", "6", ",", "height", ")", ")", "\n", "}" ]
// textBox renders t into a tight fitting image
[ "textBox", "renders", "t", "into", "a", "tight", "fitting", "image" ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/imgg/image.go#L246-L281
144,848
vdobler/chart
txtg/text.go
New
func New(w, h int) *TextGraphics { tg := TextGraphics{} tg.tb = NewTextBuf(w, h) tg.w, tg.h = w, h tg.xoff = -1 return &tg }
go
func New(w, h int) *TextGraphics { tg := TextGraphics{} tg.tb = NewTextBuf(w, h) tg.w, tg.h = w, h tg.xoff = -1 return &tg }
[ "func", "New", "(", "w", ",", "h", "int", ")", "*", "TextGraphics", "{", "tg", ":=", "TextGraphics", "{", "}", "\n", "tg", ".", "tb", "=", "NewTextBuf", "(", "w", ",", "h", ")", "\n", "tg", ".", "w", ",", "tg", ".", "h", "=", "w", ",", "h", "\n", "tg", ".", "xoff", "=", "-", "1", "\n", "return", "&", "tg", "\n", "}" ]
// New creates a TextGraphic of dimensions w x h.
[ "New", "creates", "a", "TextGraphic", "of", "dimensions", "w", "x", "h", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/txtg/text.go#L17-L23
144,849
vdobler/chart
hist.go
AddData
func (c *HistChart) AddData(name string, data []float64, style Style) { // Style if style.empty() { style = AutoStyle(len(c.Data), true) } // Init axis, add data, autoscale if len(c.Data) == 0 { c.XRange.init() } c.Data = append(c.Data, HistChartData{name, style, data}) for _, d := range data { c.XRange.autoscale(d) } // Key/Legend if name != "" { c.Key.Entries = append(c.Key.Entries, KeyEntry{Text: name, Style: style, PlotStyle: PlotStyleBox}) } }
go
func (c *HistChart) AddData(name string, data []float64, style Style) { // Style if style.empty() { style = AutoStyle(len(c.Data), true) } // Init axis, add data, autoscale if len(c.Data) == 0 { c.XRange.init() } c.Data = append(c.Data, HistChartData{name, style, data}) for _, d := range data { c.XRange.autoscale(d) } // Key/Legend if name != "" { c.Key.Entries = append(c.Key.Entries, KeyEntry{Text: name, Style: style, PlotStyle: PlotStyleBox}) } }
[ "func", "(", "c", "*", "HistChart", ")", "AddData", "(", "name", "string", ",", "data", "[", "]", "float64", ",", "style", "Style", ")", "{", "// Style", "if", "style", ".", "empty", "(", ")", "{", "style", "=", "AutoStyle", "(", "len", "(", "c", ".", "Data", ")", ",", "true", ")", "\n", "}", "\n\n", "// Init axis, add data, autoscale", "if", "len", "(", "c", ".", "Data", ")", "==", "0", "{", "c", ".", "XRange", ".", "init", "(", ")", "\n", "}", "\n", "c", ".", "Data", "=", "append", "(", "c", ".", "Data", ",", "HistChartData", "{", "name", ",", "style", ",", "data", "}", ")", "\n", "for", "_", ",", "d", ":=", "range", "data", "{", "c", ".", "XRange", ".", "autoscale", "(", "d", ")", "\n", "}", "\n\n", "// Key/Legend", "if", "name", "!=", "\"", "\"", "{", "c", ".", "Key", ".", "Entries", "=", "append", "(", "c", ".", "Key", ".", "Entries", ",", "KeyEntry", "{", "Text", ":", "name", ",", "Style", ":", "style", ",", "PlotStyle", ":", "PlotStyleBox", "}", ")", "\n", "}", "\n", "}" ]
// AddData will add data to the plot. Legend will be updated by name.
[ "AddData", "will", "add", "data", "to", "the", "plot", ".", "Legend", "will", "be", "updated", "by", "name", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/hist.go#L93-L112
144,850
vdobler/chart
hist.go
AddDataGeneric
func (c *HistChart) AddDataGeneric(name string, data []Value, style Style) { fdata := make([]float64, len(data)) for i, d := range data { fdata[i] = d.XVal() } c.AddData(name, fdata, style) }
go
func (c *HistChart) AddDataGeneric(name string, data []Value, style Style) { fdata := make([]float64, len(data)) for i, d := range data { fdata[i] = d.XVal() } c.AddData(name, fdata, style) }
[ "func", "(", "c", "*", "HistChart", ")", "AddDataGeneric", "(", "name", "string", ",", "data", "[", "]", "Value", ",", "style", "Style", ")", "{", "fdata", ":=", "make", "(", "[", "]", "float64", ",", "len", "(", "data", ")", ")", "\n", "for", "i", ",", "d", ":=", "range", "data", "{", "fdata", "[", "i", "]", "=", "d", ".", "XVal", "(", ")", "\n", "}", "\n", "c", ".", "AddData", "(", "name", ",", "fdata", ",", "style", ")", "\n", "}" ]
// AddDataGeneric is the generic version which allows the addition of any type // implementing the Value interface.
[ "AddDataGeneric", "is", "the", "generic", "version", "which", "allows", "the", "addition", "of", "any", "type", "implementing", "the", "Value", "interface", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/hist.go#L126-L132
144,851
vdobler/chart
hist.go
binify
func (c *HistChart) binify(binStart, binWidth float64, binCnt int) (freqs [][]float64, max float64) { x2bin := func(x float64) int { return int((x - binStart) / binWidth) } freqs = make([][]float64, len(c.Data)) // freqs[d][b] is frequency/count of bin b in dataset d max = 0 for i, data := range c.Data { freq := make([]float64, binCnt) drops := 0 for _, x := range data.Samples { bin := x2bin(x) if bin < 0 || bin >= binCnt { // fmt.Printf("!!!!! Lost %.3f (bin=%d)\n", x, bin) drops++ continue } freq[bin] = freq[bin] + 1 //fmt.Printf("Value %.2f sorted into bin %d, count now %d\n", x, bin, int(freq[bin])) } // scale if requested and determine max n := float64(len(data.Samples) - drops) // DebugLogger.Printf("Dataset %d has %d samples (by %d drops).\n", i, int(n), drops) ff := 0.0 for bin := 0; bin < binCnt; bin++ { if !c.Counts { freq[bin] = 100 * freq[bin] / n } ff += freq[bin] if freq[bin] > max { max = freq[bin] } } freqs[i] = freq } // DebugLogger.Printf("Maximum : %.2f\n", max) if c.Stacked { // recalculate max max = 0 for bin := 0; bin < binCnt; bin++ { sum := 0.0 for i := range freqs { sum += freqs[i][bin] } // fmt.Printf("sum of bin %d = %d\n", bin, sum) if sum > max { max = sum } } // DebugLogger.Printf("Re-Maxed (stacked) to: %.2f\n", max) } return }
go
func (c *HistChart) binify(binStart, binWidth float64, binCnt int) (freqs [][]float64, max float64) { x2bin := func(x float64) int { return int((x - binStart) / binWidth) } freqs = make([][]float64, len(c.Data)) // freqs[d][b] is frequency/count of bin b in dataset d max = 0 for i, data := range c.Data { freq := make([]float64, binCnt) drops := 0 for _, x := range data.Samples { bin := x2bin(x) if bin < 0 || bin >= binCnt { // fmt.Printf("!!!!! Lost %.3f (bin=%d)\n", x, bin) drops++ continue } freq[bin] = freq[bin] + 1 //fmt.Printf("Value %.2f sorted into bin %d, count now %d\n", x, bin, int(freq[bin])) } // scale if requested and determine max n := float64(len(data.Samples) - drops) // DebugLogger.Printf("Dataset %d has %d samples (by %d drops).\n", i, int(n), drops) ff := 0.0 for bin := 0; bin < binCnt; bin++ { if !c.Counts { freq[bin] = 100 * freq[bin] / n } ff += freq[bin] if freq[bin] > max { max = freq[bin] } } freqs[i] = freq } // DebugLogger.Printf("Maximum : %.2f\n", max) if c.Stacked { // recalculate max max = 0 for bin := 0; bin < binCnt; bin++ { sum := 0.0 for i := range freqs { sum += freqs[i][bin] } // fmt.Printf("sum of bin %d = %d\n", bin, sum) if sum > max { max = sum } } // DebugLogger.Printf("Re-Maxed (stacked) to: %.2f\n", max) } return }
[ "func", "(", "c", "*", "HistChart", ")", "binify", "(", "binStart", ",", "binWidth", "float64", ",", "binCnt", "int", ")", "(", "freqs", "[", "]", "[", "]", "float64", ",", "max", "float64", ")", "{", "x2bin", ":=", "func", "(", "x", "float64", ")", "int", "{", "return", "int", "(", "(", "x", "-", "binStart", ")", "/", "binWidth", ")", "}", "\n\n", "freqs", "=", "make", "(", "[", "]", "[", "]", "float64", ",", "len", "(", "c", ".", "Data", ")", ")", "// freqs[d][b] is frequency/count of bin b in dataset d", "\n", "max", "=", "0", "\n", "for", "i", ",", "data", ":=", "range", "c", ".", "Data", "{", "freq", ":=", "make", "(", "[", "]", "float64", ",", "binCnt", ")", "\n", "drops", ":=", "0", "\n", "for", "_", ",", "x", ":=", "range", "data", ".", "Samples", "{", "bin", ":=", "x2bin", "(", "x", ")", "\n", "if", "bin", "<", "0", "||", "bin", ">=", "binCnt", "{", "// fmt.Printf(\"!!!!! Lost %.3f (bin=%d)\\n\", x, bin)", "drops", "++", "\n", "continue", "\n", "}", "\n", "freq", "[", "bin", "]", "=", "freq", "[", "bin", "]", "+", "1", "\n", "//fmt.Printf(\"Value %.2f sorted into bin %d, count now %d\\n\", x, bin, int(freq[bin]))", "}", "\n", "// scale if requested and determine max", "n", ":=", "float64", "(", "len", "(", "data", ".", "Samples", ")", "-", "drops", ")", "\n", "// DebugLogger.Printf(\"Dataset %d has %d samples (by %d drops).\\n\", i, int(n), drops)", "ff", ":=", "0.0", "\n", "for", "bin", ":=", "0", ";", "bin", "<", "binCnt", ";", "bin", "++", "{", "if", "!", "c", ".", "Counts", "{", "freq", "[", "bin", "]", "=", "100", "*", "freq", "[", "bin", "]", "/", "n", "\n", "}", "\n", "ff", "+=", "freq", "[", "bin", "]", "\n", "if", "freq", "[", "bin", "]", ">", "max", "{", "max", "=", "freq", "[", "bin", "]", "\n", "}", "\n", "}", "\n", "freqs", "[", "i", "]", "=", "freq", "\n", "}", "\n", "// DebugLogger.Printf(\"Maximum : %.2f\\n\", max)", "if", "c", ".", "Stacked", "{", "// recalculate max", "max", "=", "0", "\n", "for", "bin", ":=", "0", ";", "bin", "<", "binCnt", ";", "bin", "++", "{", "sum", ":=", "0.0", "\n", "for", "i", ":=", "range", "freqs", "{", "sum", "+=", "freqs", "[", "i", "]", "[", "bin", "]", "\n", "}", "\n", "// fmt.Printf(\"sum of bin %d = %d\\n\", bin, sum)", "if", "sum", ">", "max", "{", "max", "=", "sum", "\n", "}", "\n", "}", "\n", "// DebugLogger.Printf(\"Re-Maxed (stacked) to: %.2f\\n\", max)", "}", "\n", "return", "\n", "}" ]
// Prepare binCnt bins of width binWidth starting from binStart and count // data samples per bin for each data set. If c.Counts is true than the // absolute counts are returned instead if the frequencies. max is the // largest y-value which will occur in our plot.
[ "Prepare", "binCnt", "bins", "of", "width", "binWidth", "starting", "from", "binStart", "and", "count", "data", "samples", "per", "bin", "for", "each", "data", "set", ".", "If", "c", ".", "Counts", "is", "true", "than", "the", "absolute", "counts", "are", "returned", "instead", "if", "the", "frequencies", ".", "max", "is", "the", "largest", "y", "-", "value", "which", "will", "occur", "in", "our", "plot", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/hist.go#L181-L230
144,852
vdobler/chart
time.go
RoundUp
func RoundUp(t time.Time, d TimeDelta) time.Time { // works only because all TimeDeltas are more than 1.5 times as large as the next lower shift := d.Seconds() shift += shift / 2 t = d.RoundDown(t) t = t.Add(time.Duration(shift) * time.Second) t = d.RoundDown(t) DebugLogger.Printf("RoundUp( %s, %s ) --> %s ", t.Format("2006-01-02 15:04:05 (Mon)"), d.String(), t.Format("2006-01-02 15:04:05 (Mon)")) return t }
go
func RoundUp(t time.Time, d TimeDelta) time.Time { // works only because all TimeDeltas are more than 1.5 times as large as the next lower shift := d.Seconds() shift += shift / 2 t = d.RoundDown(t) t = t.Add(time.Duration(shift) * time.Second) t = d.RoundDown(t) DebugLogger.Printf("RoundUp( %s, %s ) --> %s ", t.Format("2006-01-02 15:04:05 (Mon)"), d.String(), t.Format("2006-01-02 15:04:05 (Mon)")) return t }
[ "func", "RoundUp", "(", "t", "time", ".", "Time", ",", "d", "TimeDelta", ")", "time", ".", "Time", "{", "// works only because all TimeDeltas are more than 1.5 times as large as the next lower", "shift", ":=", "d", ".", "Seconds", "(", ")", "\n", "shift", "+=", "shift", "/", "2", "\n", "t", "=", "d", ".", "RoundDown", "(", "t", ")", "\n", "t", "=", "t", ".", "Add", "(", "time", ".", "Duration", "(", "shift", ")", "*", "time", ".", "Second", ")", "\n", "t", "=", "d", ".", "RoundDown", "(", "t", ")", "\n", "DebugLogger", ".", "Printf", "(", "\"", "\"", ",", "t", ".", "Format", "(", "\"", "\"", ")", ",", "d", ".", "String", "(", ")", ",", "t", ".", "Format", "(", "\"", "\"", ")", ")", "\n", "return", "t", "\n", "}" ]
// RoundUp will round tp up to next "full" d.
[ "RoundUp", "will", "round", "tp", "up", "to", "next", "full", "d", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/time.go#L170-L180
144,853
vdobler/chart
time.go
RoundNext
func RoundNext(t time.Time, d TimeDelta) time.Time { DebugLogger.Printf("RoundNext( %s, %s )", t.Format("2006-01-02 15:04:05 (Mon)"), d.String()) os := t.Unix() lt := d.RoundDown(t) shift := d.Seconds() shift += shift / 2 ut := lt.Add(time.Duration(shift) * time.Second) // see RoundUp() ut = d.RoundDown(ut) ld := os - lt.Unix() ud := ut.Unix() - os if ld < ud { return lt } return ut }
go
func RoundNext(t time.Time, d TimeDelta) time.Time { DebugLogger.Printf("RoundNext( %s, %s )", t.Format("2006-01-02 15:04:05 (Mon)"), d.String()) os := t.Unix() lt := d.RoundDown(t) shift := d.Seconds() shift += shift / 2 ut := lt.Add(time.Duration(shift) * time.Second) // see RoundUp() ut = d.RoundDown(ut) ld := os - lt.Unix() ud := ut.Unix() - os if ld < ud { return lt } return ut }
[ "func", "RoundNext", "(", "t", "time", ".", "Time", ",", "d", "TimeDelta", ")", "time", ".", "Time", "{", "DebugLogger", ".", "Printf", "(", "\"", "\"", ",", "t", ".", "Format", "(", "\"", "\"", ")", ",", "d", ".", "String", "(", ")", ")", "\n", "os", ":=", "t", ".", "Unix", "(", ")", "\n", "lt", ":=", "d", ".", "RoundDown", "(", "t", ")", "\n", "shift", ":=", "d", ".", "Seconds", "(", ")", "\n", "shift", "+=", "shift", "/", "2", "\n", "ut", ":=", "lt", ".", "Add", "(", "time", ".", "Duration", "(", "shift", ")", "*", "time", ".", "Second", ")", "// see RoundUp()", "\n", "ut", "=", "d", ".", "RoundDown", "(", "ut", ")", "\n", "ld", ":=", "os", "-", "lt", ".", "Unix", "(", ")", "\n", "ud", ":=", "ut", ".", "Unix", "(", ")", "-", "os", "\n", "if", "ld", "<", "ud", "{", "return", "lt", "\n", "}", "\n", "return", "ut", "\n", "}" ]
// RoundNext will round t to nearest full d.
[ "RoundNext", "will", "round", "t", "to", "nearest", "full", "d", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/time.go#L183-L197
144,854
vdobler/chart
time.go
RoundDown
func RoundDown(t time.Time, d TimeDelta) time.Time { td := d.RoundDown(t) DebugLogger.Printf("RoundDown( %s, %s ) --> %s", t.Format("2006-01-02 15:04:05 (Mon)"), d.String(), td.Format("2006-01-02 15:04:05 (Mon)")) return td }
go
func RoundDown(t time.Time, d TimeDelta) time.Time { td := d.RoundDown(t) DebugLogger.Printf("RoundDown( %s, %s ) --> %s", t.Format("2006-01-02 15:04:05 (Mon)"), d.String(), td.Format("2006-01-02 15:04:05 (Mon)")) return td }
[ "func", "RoundDown", "(", "t", "time", ".", "Time", ",", "d", "TimeDelta", ")", "time", ".", "Time", "{", "td", ":=", "d", ".", "RoundDown", "(", "t", ")", "\n", "DebugLogger", ".", "Printf", "(", "\"", "\"", ",", "t", ".", "Format", "(", "\"", "\"", ")", ",", "d", ".", "String", "(", ")", ",", "td", ".", "Format", "(", "\"", "\"", ")", ")", "\n", "return", "td", "\n", "}" ]
// RoundDown will round tp down to next "full" d.
[ "RoundDown", "will", "round", "tp", "down", "to", "next", "full", "d", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/time.go#L200-L205
144,855
vdobler/chart
pie.go
PercentValue
func PercentValue(value, sum float64) (s string) { value *= 100 / sum s = AbsoluteValue(value, sum) + "% " return }
go
func PercentValue(value, sum float64) (s string) { value *= 100 / sum s = AbsoluteValue(value, sum) + "% " return }
[ "func", "PercentValue", "(", "value", ",", "sum", "float64", ")", "(", "s", "string", ")", "{", "value", "*=", "100", "/", "sum", "\n", "s", "=", "AbsoluteValue", "(", "value", ",", "sum", ")", "+", "\"", "\"", "\n", "return", "\n", "}" ]
// PercentValue formats value as percentage of sum. // It is a convenience function which can be assigned to the // PieChart.FmtVal or PieChart.FmtKey field.
[ "PercentValue", "formats", "value", "as", "percentage", "of", "sum", ".", "It", "is", "a", "convenience", "function", "which", "can", "be", "assigned", "to", "the", "PieChart", ".", "FmtVal", "or", "PieChart", ".", "FmtKey", "field", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/pie.go#L57-L61
144,856
vdobler/chart
pie.go
Plot
func (c *PieChart) Plot(g Graphics) { layout := layout(g, c.Title, "", "", true, true, &c.Key) width, height := layout.Width, layout.Height topm, leftm := layout.Top, layout.Left width += 0 r := imin(height, width) / 2 x0, y0 := leftm+r, topm+r // Make sure pie fits into plotting area rshift := int(float64(r) * PieChartHighlight) if rshift < 6 { rshift = 6 } for _, d := range c.Data[0].Samples { if d.Flag { // DebugLogger.Printf("Reduced %d by %d", r, rshift) r -= rshift / 3 break } } g.Begin() if c.Title != "" { drawTitle(g, c.Title, elementStyle(c.Options, TitleElement)) } for _, data := range c.Data { var sum float64 for _, d := range data.Samples { sum += d.Val } wedges := make([]Wedgeinfo, len(data.Samples)) var ri int = 0 if c.Inner > 0 { ri = int(float64(r) * c.Inner) } var phi float64 = -math.Pi for j, d := range data.Samples { style := data.Style[j] alpha := 2 * math.Pi * d.Val / sum shift := 0 var t string if c.FmtVal != nil { t = c.FmtVal(d.Val, sum) } if d.Flag { shift = rshift } wedges[j] = Wedgeinfo{Phi: phi, Psi: phi + alpha, Text: t, Tp: "c", Style: style, Font: Font{}, Shift: shift} phi += alpha } g.Rings(wedges, x0, y0, r, ri) r = int(float64(r) * PieChartShrinkage) } if !c.Key.Hide { g.Key(layout.KeyX, layout.KeyY, c.Key, c.Options) } g.End() }
go
func (c *PieChart) Plot(g Graphics) { layout := layout(g, c.Title, "", "", true, true, &c.Key) width, height := layout.Width, layout.Height topm, leftm := layout.Top, layout.Left width += 0 r := imin(height, width) / 2 x0, y0 := leftm+r, topm+r // Make sure pie fits into plotting area rshift := int(float64(r) * PieChartHighlight) if rshift < 6 { rshift = 6 } for _, d := range c.Data[0].Samples { if d.Flag { // DebugLogger.Printf("Reduced %d by %d", r, rshift) r -= rshift / 3 break } } g.Begin() if c.Title != "" { drawTitle(g, c.Title, elementStyle(c.Options, TitleElement)) } for _, data := range c.Data { var sum float64 for _, d := range data.Samples { sum += d.Val } wedges := make([]Wedgeinfo, len(data.Samples)) var ri int = 0 if c.Inner > 0 { ri = int(float64(r) * c.Inner) } var phi float64 = -math.Pi for j, d := range data.Samples { style := data.Style[j] alpha := 2 * math.Pi * d.Val / sum shift := 0 var t string if c.FmtVal != nil { t = c.FmtVal(d.Val, sum) } if d.Flag { shift = rshift } wedges[j] = Wedgeinfo{Phi: phi, Psi: phi + alpha, Text: t, Tp: "c", Style: style, Font: Font{}, Shift: shift} phi += alpha } g.Rings(wedges, x0, y0, r, ri) r = int(float64(r) * PieChartShrinkage) } if !c.Key.Hide { g.Key(layout.KeyX, layout.KeyY, c.Key, c.Options) } g.End() }
[ "func", "(", "c", "*", "PieChart", ")", "Plot", "(", "g", "Graphics", ")", "{", "layout", ":=", "layout", "(", "g", ",", "c", ".", "Title", ",", "\"", "\"", ",", "\"", "\"", ",", "true", ",", "true", ",", "&", "c", ".", "Key", ")", "\n\n", "width", ",", "height", ":=", "layout", ".", "Width", ",", "layout", ".", "Height", "\n", "topm", ",", "leftm", ":=", "layout", ".", "Top", ",", "layout", ".", "Left", "\n", "width", "+=", "0", "\n\n", "r", ":=", "imin", "(", "height", ",", "width", ")", "/", "2", "\n", "x0", ",", "y0", ":=", "leftm", "+", "r", ",", "topm", "+", "r", "\n\n", "// Make sure pie fits into plotting area", "rshift", ":=", "int", "(", "float64", "(", "r", ")", "*", "PieChartHighlight", ")", "\n", "if", "rshift", "<", "6", "{", "rshift", "=", "6", "\n", "}", "\n", "for", "_", ",", "d", ":=", "range", "c", ".", "Data", "[", "0", "]", ".", "Samples", "{", "if", "d", ".", "Flag", "{", "// DebugLogger.Printf(\"Reduced %d by %d\", r, rshift)", "r", "-=", "rshift", "/", "3", "\n", "break", "\n", "}", "\n", "}", "\n\n", "g", ".", "Begin", "(", ")", "\n\n", "if", "c", ".", "Title", "!=", "\"", "\"", "{", "drawTitle", "(", "g", ",", "c", ".", "Title", ",", "elementStyle", "(", "c", ".", "Options", ",", "TitleElement", ")", ")", "\n", "}", "\n\n", "for", "_", ",", "data", ":=", "range", "c", ".", "Data", "{", "var", "sum", "float64", "\n", "for", "_", ",", "d", ":=", "range", "data", ".", "Samples", "{", "sum", "+=", "d", ".", "Val", "\n", "}", "\n\n", "wedges", ":=", "make", "(", "[", "]", "Wedgeinfo", ",", "len", "(", "data", ".", "Samples", ")", ")", "\n", "var", "ri", "int", "=", "0", "\n", "if", "c", ".", "Inner", ">", "0", "{", "ri", "=", "int", "(", "float64", "(", "r", ")", "*", "c", ".", "Inner", ")", "\n", "}", "\n\n", "var", "phi", "float64", "=", "-", "math", ".", "Pi", "\n", "for", "j", ",", "d", ":=", "range", "data", ".", "Samples", "{", "style", ":=", "data", ".", "Style", "[", "j", "]", "\n", "alpha", ":=", "2", "*", "math", ".", "Pi", "*", "d", ".", "Val", "/", "sum", "\n", "shift", ":=", "0", "\n\n", "var", "t", "string", "\n", "if", "c", ".", "FmtVal", "!=", "nil", "{", "t", "=", "c", ".", "FmtVal", "(", "d", ".", "Val", ",", "sum", ")", "\n", "}", "\n", "if", "d", ".", "Flag", "{", "shift", "=", "rshift", "\n", "}", "\n\n", "wedges", "[", "j", "]", "=", "Wedgeinfo", "{", "Phi", ":", "phi", ",", "Psi", ":", "phi", "+", "alpha", ",", "Text", ":", "t", ",", "Tp", ":", "\"", "\"", ",", "Style", ":", "style", ",", "Font", ":", "Font", "{", "}", ",", "Shift", ":", "shift", "}", "\n\n", "phi", "+=", "alpha", "\n", "}", "\n", "g", ".", "Rings", "(", "wedges", ",", "x0", ",", "y0", ",", "r", ",", "ri", ")", "\n\n", "r", "=", "int", "(", "float64", "(", "r", ")", "*", "PieChartShrinkage", ")", "\n", "}", "\n\n", "if", "!", "c", ".", "Key", ".", "Hide", "{", "g", ".", "Key", "(", "layout", ".", "KeyX", ",", "layout", ".", "KeyY", ",", "c", ".", "Key", ",", "c", ".", "Options", ")", "\n", "}", "\n\n", "g", ".", "End", "(", ")", "\n", "}" ]
// Plot outputs the scatter chart sc to g.
[ "Plot", "outputs", "the", "scatter", "chart", "sc", "to", "g", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/pie.go#L121-L191
144,857
vdobler/chart
graphics.go
GenericTextLen
func GenericTextLen(mg MinimalGraphics, t string, font Font) (width int) { // TODO: how handle newlines? same way like Text does fw, _, mono := mg.FontMetrics(font) if mono { for _ = range t { width++ } width = int(float32(width)*fw + 0.5) } else { var length float32 for _, r := range t { if w, ok := CharacterWidth[int(r)]; ok { length += w } else { length += 20 // save above average } } length /= averageCharacterWidth length *= fw width = int(length + 0.5) } return }
go
func GenericTextLen(mg MinimalGraphics, t string, font Font) (width int) { // TODO: how handle newlines? same way like Text does fw, _, mono := mg.FontMetrics(font) if mono { for _ = range t { width++ } width = int(float32(width)*fw + 0.5) } else { var length float32 for _, r := range t { if w, ok := CharacterWidth[int(r)]; ok { length += w } else { length += 20 // save above average } } length /= averageCharacterWidth length *= fw width = int(length + 0.5) } return }
[ "func", "GenericTextLen", "(", "mg", "MinimalGraphics", ",", "t", "string", ",", "font", "Font", ")", "(", "width", "int", ")", "{", "// TODO: how handle newlines? same way like Text does", "fw", ",", "_", ",", "mono", ":=", "mg", ".", "FontMetrics", "(", "font", ")", "\n", "if", "mono", "{", "for", "_", "=", "range", "t", "{", "width", "++", "\n", "}", "\n", "width", "=", "int", "(", "float32", "(", "width", ")", "*", "fw", "+", "0.5", ")", "\n", "}", "else", "{", "var", "length", "float32", "\n", "for", "_", ",", "r", ":=", "range", "t", "{", "if", "w", ",", "ok", ":=", "CharacterWidth", "[", "int", "(", "r", ")", "]", ";", "ok", "{", "length", "+=", "w", "\n", "}", "else", "{", "length", "+=", "20", "// save above average", "\n", "}", "\n", "}", "\n", "length", "/=", "averageCharacterWidth", "\n", "length", "*=", "fw", "\n", "width", "=", "int", "(", "length", "+", "0.5", ")", "\n", "}", "\n", "return", "\n", "}" ]
// GenericTextLen tries to determine the width in pixel of t if rendered into mg in using font.
[ "GenericTextLen", "tries", "to", "determine", "the", "width", "in", "pixel", "of", "t", "if", "rendered", "into", "mg", "in", "using", "font", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/graphics.go#L72-L94
144,858
vdobler/chart
graphics.go
GenericXAxis
func GenericXAxis(bg BasicGraphics, rng Range, y, ym int, options PlotOptions) { _, fontheight, _ := bg.FontMetrics(elementStyle(options, MajorTicElement).Font) var ticLen int = 0 if !rng.TicSetting.Hide { ticLen = imin(12, imax(4, fontheight/2)) } xa, xe := rng.Data2Screen(rng.Min), rng.Data2Screen(rng.Max) // Axis label and range limits aly := y + 2*ticLen if !rng.TicSetting.Hide { aly += (3 * fontheight) / 2 } if rng.ShowLimits { font := elementStyle(options, RangeLimitElement).Font if rng.Time { bg.Text(xa, aly, rng.TMin.Format("2006-01-02 15:04:05"), "tl", 0, font) bg.Text(xe, aly, rng.TMax.Format("2006-01-02 15:04:05"), "tr", 0, font) } else { bg.Text(xa, aly, fmt.Sprintf("%g", rng.Min), "tl", 0, font) bg.Text(xe, aly, fmt.Sprintf("%g", rng.Max), "tr", 0, font) } } if rng.Label != "" { // draw label _after_ (=over) range limits font := elementStyle(options, MajorAxisElement).Font bg.Text((xa+xe)/2, aly, " "+rng.Label+" ", "tc", 0, font) } // Tics and Grid if !rng.TicSetting.Hide { drawXTics(bg, rng, y, ym, ticLen, options) } // Axis itself, mirrord axis and zero bg.Line(xa, y, xe, y, elementStyle(options, MajorAxisElement)) if rng.TicSetting.Mirror >= 1 { bg.Line(xa, ym, xe, ym, elementStyle(options, MinorAxisElement)) } if rng.ShowZero && rng.Min < 0 && rng.Max > 0 { z := rng.Data2Screen(0) bg.Line(z, y, z, ym, elementStyle(options, ZeroAxisElement)) } }
go
func GenericXAxis(bg BasicGraphics, rng Range, y, ym int, options PlotOptions) { _, fontheight, _ := bg.FontMetrics(elementStyle(options, MajorTicElement).Font) var ticLen int = 0 if !rng.TicSetting.Hide { ticLen = imin(12, imax(4, fontheight/2)) } xa, xe := rng.Data2Screen(rng.Min), rng.Data2Screen(rng.Max) // Axis label and range limits aly := y + 2*ticLen if !rng.TicSetting.Hide { aly += (3 * fontheight) / 2 } if rng.ShowLimits { font := elementStyle(options, RangeLimitElement).Font if rng.Time { bg.Text(xa, aly, rng.TMin.Format("2006-01-02 15:04:05"), "tl", 0, font) bg.Text(xe, aly, rng.TMax.Format("2006-01-02 15:04:05"), "tr", 0, font) } else { bg.Text(xa, aly, fmt.Sprintf("%g", rng.Min), "tl", 0, font) bg.Text(xe, aly, fmt.Sprintf("%g", rng.Max), "tr", 0, font) } } if rng.Label != "" { // draw label _after_ (=over) range limits font := elementStyle(options, MajorAxisElement).Font bg.Text((xa+xe)/2, aly, " "+rng.Label+" ", "tc", 0, font) } // Tics and Grid if !rng.TicSetting.Hide { drawXTics(bg, rng, y, ym, ticLen, options) } // Axis itself, mirrord axis and zero bg.Line(xa, y, xe, y, elementStyle(options, MajorAxisElement)) if rng.TicSetting.Mirror >= 1 { bg.Line(xa, ym, xe, ym, elementStyle(options, MinorAxisElement)) } if rng.ShowZero && rng.Min < 0 && rng.Max > 0 { z := rng.Data2Screen(0) bg.Line(z, y, z, ym, elementStyle(options, ZeroAxisElement)) } }
[ "func", "GenericXAxis", "(", "bg", "BasicGraphics", ",", "rng", "Range", ",", "y", ",", "ym", "int", ",", "options", "PlotOptions", ")", "{", "_", ",", "fontheight", ",", "_", ":=", "bg", ".", "FontMetrics", "(", "elementStyle", "(", "options", ",", "MajorTicElement", ")", ".", "Font", ")", "\n", "var", "ticLen", "int", "=", "0", "\n", "if", "!", "rng", ".", "TicSetting", ".", "Hide", "{", "ticLen", "=", "imin", "(", "12", ",", "imax", "(", "4", ",", "fontheight", "/", "2", ")", ")", "\n", "}", "\n", "xa", ",", "xe", ":=", "rng", ".", "Data2Screen", "(", "rng", ".", "Min", ")", ",", "rng", ".", "Data2Screen", "(", "rng", ".", "Max", ")", "\n\n", "// Axis label and range limits", "aly", ":=", "y", "+", "2", "*", "ticLen", "\n", "if", "!", "rng", ".", "TicSetting", ".", "Hide", "{", "aly", "+=", "(", "3", "*", "fontheight", ")", "/", "2", "\n", "}", "\n", "if", "rng", ".", "ShowLimits", "{", "font", ":=", "elementStyle", "(", "options", ",", "RangeLimitElement", ")", ".", "Font", "\n", "if", "rng", ".", "Time", "{", "bg", ".", "Text", "(", "xa", ",", "aly", ",", "rng", ".", "TMin", ".", "Format", "(", "\"", "\"", ")", ",", "\"", "\"", ",", "0", ",", "font", ")", "\n", "bg", ".", "Text", "(", "xe", ",", "aly", ",", "rng", ".", "TMax", ".", "Format", "(", "\"", "\"", ")", ",", "\"", "\"", ",", "0", ",", "font", ")", "\n", "}", "else", "{", "bg", ".", "Text", "(", "xa", ",", "aly", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rng", ".", "Min", ")", ",", "\"", "\"", ",", "0", ",", "font", ")", "\n", "bg", ".", "Text", "(", "xe", ",", "aly", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "rng", ".", "Max", ")", ",", "\"", "\"", ",", "0", ",", "font", ")", "\n", "}", "\n", "}", "\n", "if", "rng", ".", "Label", "!=", "\"", "\"", "{", "// draw label _after_ (=over) range limits", "font", ":=", "elementStyle", "(", "options", ",", "MajorAxisElement", ")", ".", "Font", "\n", "bg", ".", "Text", "(", "(", "xa", "+", "xe", ")", "/", "2", ",", "aly", ",", "\"", "\"", "+", "rng", ".", "Label", "+", "\"", "\"", ",", "\"", "\"", ",", "0", ",", "font", ")", "\n", "}", "\n\n", "// Tics and Grid", "if", "!", "rng", ".", "TicSetting", ".", "Hide", "{", "drawXTics", "(", "bg", ",", "rng", ",", "y", ",", "ym", ",", "ticLen", ",", "options", ")", "\n", "}", "\n\n", "// Axis itself, mirrord axis and zero", "bg", ".", "Line", "(", "xa", ",", "y", ",", "xe", ",", "y", ",", "elementStyle", "(", "options", ",", "MajorAxisElement", ")", ")", "\n", "if", "rng", ".", "TicSetting", ".", "Mirror", ">=", "1", "{", "bg", ".", "Line", "(", "xa", ",", "ym", ",", "xe", ",", "ym", ",", "elementStyle", "(", "options", ",", "MinorAxisElement", ")", ")", "\n", "}", "\n", "if", "rng", ".", "ShowZero", "&&", "rng", ".", "Min", "<", "0", "&&", "rng", ".", "Max", ">", "0", "{", "z", ":=", "rng", ".", "Data2Screen", "(", "0", ")", "\n", "bg", ".", "Line", "(", "z", ",", "y", ",", "z", ",", "ym", ",", "elementStyle", "(", "options", ",", "ZeroAxisElement", ")", ")", "\n", "}", "\n\n", "}" ]
// GenericXAxis draws the x-axis with range rng solely by graphic primitives of bg. // The x-axis is drawn at y on the screen and the mirrored x-axis is drawn at ym.
[ "GenericXAxis", "draws", "the", "x", "-", "axis", "with", "range", "rng", "solely", "by", "graphic", "primitives", "of", "bg", ".", "The", "x", "-", "axis", "is", "drawn", "at", "y", "on", "the", "screen", "and", "the", "mirrored", "x", "-", "axis", "is", "drawn", "at", "ym", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/graphics.go#L206-L249
144,859
vdobler/chart
graphics.go
GenericYAxis
func GenericYAxis(bg BasicGraphics, rng Range, x, xm int, options PlotOptions) { font := elementStyle(options, MajorAxisElement).Font _, fontheight, _ := bg.FontMetrics(font) var ticLen int = 0 if !rng.TicSetting.Hide { ticLen = imin(10, imax(4, fontheight/2)) } ya, ye := rng.Data2Screen(rng.Min), rng.Data2Screen(rng.Max) // Label and axis ranges alx := 2 * fontheight if rng.ShowLimits { /* TODO st := bg.Style("rangelimit") if rng.Time { bg.Text(xa, aly, rng.TMin.Format("2006-01-02 15:04:05"), "tl", 0, st) bg.Text(xe, aly, rng.TMax.Format("2006-01-02 15:04:05"), "tr", 0, st) } else { bg.Text(xa, aly, fmt.Sprintf("%g", rng.Min), "tl", 0, st) bg.Text(xe, aly, fmt.Sprintf("%g", rng.Max), "tr", 0, st) } */ } if rng.Label != "" { y := (ya + ye) / 2 bg.Text(alx, y, rng.Label, "bc", 90, font) } if !rng.TicSetting.Hide { drawYTics(bg, rng, x, xm, ticLen, options) } // Axis itself, mirrord axis and zero bg.Line(x, ya, x, ye, elementStyle(options, MajorAxisElement)) if rng.TicSetting.Mirror >= 1 { bg.Line(xm, ya, xm, ye, elementStyle(options, MinorAxisElement)) } if rng.ShowZero && rng.Min < 0 && rng.Max > 0 { z := rng.Data2Screen(0) bg.Line(x, z, xm, z, elementStyle(options, ZeroAxisElement)) } }
go
func GenericYAxis(bg BasicGraphics, rng Range, x, xm int, options PlotOptions) { font := elementStyle(options, MajorAxisElement).Font _, fontheight, _ := bg.FontMetrics(font) var ticLen int = 0 if !rng.TicSetting.Hide { ticLen = imin(10, imax(4, fontheight/2)) } ya, ye := rng.Data2Screen(rng.Min), rng.Data2Screen(rng.Max) // Label and axis ranges alx := 2 * fontheight if rng.ShowLimits { /* TODO st := bg.Style("rangelimit") if rng.Time { bg.Text(xa, aly, rng.TMin.Format("2006-01-02 15:04:05"), "tl", 0, st) bg.Text(xe, aly, rng.TMax.Format("2006-01-02 15:04:05"), "tr", 0, st) } else { bg.Text(xa, aly, fmt.Sprintf("%g", rng.Min), "tl", 0, st) bg.Text(xe, aly, fmt.Sprintf("%g", rng.Max), "tr", 0, st) } */ } if rng.Label != "" { y := (ya + ye) / 2 bg.Text(alx, y, rng.Label, "bc", 90, font) } if !rng.TicSetting.Hide { drawYTics(bg, rng, x, xm, ticLen, options) } // Axis itself, mirrord axis and zero bg.Line(x, ya, x, ye, elementStyle(options, MajorAxisElement)) if rng.TicSetting.Mirror >= 1 { bg.Line(xm, ya, xm, ye, elementStyle(options, MinorAxisElement)) } if rng.ShowZero && rng.Min < 0 && rng.Max > 0 { z := rng.Data2Screen(0) bg.Line(x, z, xm, z, elementStyle(options, ZeroAxisElement)) } }
[ "func", "GenericYAxis", "(", "bg", "BasicGraphics", ",", "rng", "Range", ",", "x", ",", "xm", "int", ",", "options", "PlotOptions", ")", "{", "font", ":=", "elementStyle", "(", "options", ",", "MajorAxisElement", ")", ".", "Font", "\n", "_", ",", "fontheight", ",", "_", ":=", "bg", ".", "FontMetrics", "(", "font", ")", "\n", "var", "ticLen", "int", "=", "0", "\n", "if", "!", "rng", ".", "TicSetting", ".", "Hide", "{", "ticLen", "=", "imin", "(", "10", ",", "imax", "(", "4", ",", "fontheight", "/", "2", ")", ")", "\n", "}", "\n", "ya", ",", "ye", ":=", "rng", ".", "Data2Screen", "(", "rng", ".", "Min", ")", ",", "rng", ".", "Data2Screen", "(", "rng", ".", "Max", ")", "\n\n", "// Label and axis ranges", "alx", ":=", "2", "*", "fontheight", "\n", "if", "rng", ".", "ShowLimits", "{", "/* TODO\n\t\tst := bg.Style(\"rangelimit\")\n\t\tif rng.Time {\n\t\t\tbg.Text(xa, aly, rng.TMin.Format(\"2006-01-02 15:04:05\"), \"tl\", 0, st)\n\t\t\tbg.Text(xe, aly, rng.TMax.Format(\"2006-01-02 15:04:05\"), \"tr\", 0, st)\n\t\t} else {\n\t\t\tbg.Text(xa, aly, fmt.Sprintf(\"%g\", rng.Min), \"tl\", 0, st)\n\t\t\tbg.Text(xe, aly, fmt.Sprintf(\"%g\", rng.Max), \"tr\", 0, st)\n\t\t}\n\t\t*/", "}", "\n", "if", "rng", ".", "Label", "!=", "\"", "\"", "{", "y", ":=", "(", "ya", "+", "ye", ")", "/", "2", "\n", "bg", ".", "Text", "(", "alx", ",", "y", ",", "rng", ".", "Label", ",", "\"", "\"", ",", "90", ",", "font", ")", "\n", "}", "\n\n", "if", "!", "rng", ".", "TicSetting", ".", "Hide", "{", "drawYTics", "(", "bg", ",", "rng", ",", "x", ",", "xm", ",", "ticLen", ",", "options", ")", "\n", "}", "\n\n", "// Axis itself, mirrord axis and zero", "bg", ".", "Line", "(", "x", ",", "ya", ",", "x", ",", "ye", ",", "elementStyle", "(", "options", ",", "MajorAxisElement", ")", ")", "\n", "if", "rng", ".", "TicSetting", ".", "Mirror", ">=", "1", "{", "bg", ".", "Line", "(", "xm", ",", "ya", ",", "xm", ",", "ye", ",", "elementStyle", "(", "options", ",", "MinorAxisElement", ")", ")", "\n", "}", "\n", "if", "rng", ".", "ShowZero", "&&", "rng", ".", "Min", "<", "0", "&&", "rng", ".", "Max", ">", "0", "{", "z", ":=", "rng", ".", "Data2Screen", "(", "0", ")", "\n", "bg", ".", "Line", "(", "x", ",", "z", ",", "xm", ",", "z", ",", "elementStyle", "(", "options", ",", "ZeroAxisElement", ")", ")", "\n", "}", "\n\n", "}" ]
// GenericYAxis draws the y-axis with the range rng solely by graphic primitives of bg. // The y.axis and the mirrord y-axis are drawn at x and ym respectively.
[ "GenericYAxis", "draws", "the", "y", "-", "axis", "with", "the", "range", "rng", "solely", "by", "graphic", "primitives", "of", "bg", ".", "The", "y", ".", "axis", "and", "the", "mirrord", "y", "-", "axis", "are", "drawn", "at", "x", "and", "ym", "respectively", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/graphics.go#L320-L362
144,860
vdobler/chart
graphics.go
GenericScatter
func GenericScatter(bg BasicGraphics, points []EPoint, plotstyle PlotStyle, style Style) { // First pass: Error bars ebs := style ebs.LineColor, ebs.LineWidth, ebs.LineStyle = ebs.FillColor, 1, SolidLine if ebs.LineColor == nil { ebs.LineColor = color.NRGBA{0x40, 0x40, 0x40, 0xff} } if ebs.LineWidth == 0 { ebs.LineWidth = 1 } for _, p := range points { xl, yl, xh, yh := p.BoundingBox() // fmt.Printf("Draw %d: %f %f-%f; %f %f-%f\n", i, p.DeltaX, xl,xh, p.DeltaY, yl,yh) if !math.IsNaN(p.DeltaX) { bg.Line(int(xl), int(p.Y), int(xh), int(p.Y), ebs) } if !math.IsNaN(p.DeltaY) { // fmt.Printf(" Draw %d,%d to %d,%d\n",int(p.X), int(yl), int(p.X), int(yh)) bg.Line(int(p.X), int(yl), int(p.X), int(yh), ebs) } } // Second pass: Line if (plotstyle&PlotStyleLines) != 0 && len(points) > 0 { lastx, lasty := int(points[0].X), int(points[0].Y) for i := 1; i < len(points); i++ { x, y := int(points[i].X), int(points[i].Y) bg.Line(lastx, lasty, x, y, style) lastx, lasty = x, y } } // Third pass: symbols if (plotstyle&PlotStylePoints) != 0 && len(points) != 0 { for _, p := range points { // fmt.Printf("Point %d at %d,%d\n", i, int(p.X), int(p.Y)) bg.Symbol(int(p.X), int(p.Y), style) } } }
go
func GenericScatter(bg BasicGraphics, points []EPoint, plotstyle PlotStyle, style Style) { // First pass: Error bars ebs := style ebs.LineColor, ebs.LineWidth, ebs.LineStyle = ebs.FillColor, 1, SolidLine if ebs.LineColor == nil { ebs.LineColor = color.NRGBA{0x40, 0x40, 0x40, 0xff} } if ebs.LineWidth == 0 { ebs.LineWidth = 1 } for _, p := range points { xl, yl, xh, yh := p.BoundingBox() // fmt.Printf("Draw %d: %f %f-%f; %f %f-%f\n", i, p.DeltaX, xl,xh, p.DeltaY, yl,yh) if !math.IsNaN(p.DeltaX) { bg.Line(int(xl), int(p.Y), int(xh), int(p.Y), ebs) } if !math.IsNaN(p.DeltaY) { // fmt.Printf(" Draw %d,%d to %d,%d\n",int(p.X), int(yl), int(p.X), int(yh)) bg.Line(int(p.X), int(yl), int(p.X), int(yh), ebs) } } // Second pass: Line if (plotstyle&PlotStyleLines) != 0 && len(points) > 0 { lastx, lasty := int(points[0].X), int(points[0].Y) for i := 1; i < len(points); i++ { x, y := int(points[i].X), int(points[i].Y) bg.Line(lastx, lasty, x, y, style) lastx, lasty = x, y } } // Third pass: symbols if (plotstyle&PlotStylePoints) != 0 && len(points) != 0 { for _, p := range points { // fmt.Printf("Point %d at %d,%d\n", i, int(p.X), int(p.Y)) bg.Symbol(int(p.X), int(p.Y), style) } } }
[ "func", "GenericScatter", "(", "bg", "BasicGraphics", ",", "points", "[", "]", "EPoint", ",", "plotstyle", "PlotStyle", ",", "style", "Style", ")", "{", "// First pass: Error bars", "ebs", ":=", "style", "\n", "ebs", ".", "LineColor", ",", "ebs", ".", "LineWidth", ",", "ebs", ".", "LineStyle", "=", "ebs", ".", "FillColor", ",", "1", ",", "SolidLine", "\n", "if", "ebs", ".", "LineColor", "==", "nil", "{", "ebs", ".", "LineColor", "=", "color", ".", "NRGBA", "{", "0x40", ",", "0x40", ",", "0x40", ",", "0xff", "}", "\n", "}", "\n", "if", "ebs", ".", "LineWidth", "==", "0", "{", "ebs", ".", "LineWidth", "=", "1", "\n", "}", "\n", "for", "_", ",", "p", ":=", "range", "points", "{", "xl", ",", "yl", ",", "xh", ",", "yh", ":=", "p", ".", "BoundingBox", "(", ")", "\n", "// fmt.Printf(\"Draw %d: %f %f-%f; %f %f-%f\\n\", i, p.DeltaX, xl,xh, p.DeltaY, yl,yh)", "if", "!", "math", ".", "IsNaN", "(", "p", ".", "DeltaX", ")", "{", "bg", ".", "Line", "(", "int", "(", "xl", ")", ",", "int", "(", "p", ".", "Y", ")", ",", "int", "(", "xh", ")", ",", "int", "(", "p", ".", "Y", ")", ",", "ebs", ")", "\n", "}", "\n", "if", "!", "math", ".", "IsNaN", "(", "p", ".", "DeltaY", ")", "{", "// fmt.Printf(\" Draw %d,%d to %d,%d\\n\",int(p.X), int(yl), int(p.X), int(yh))", "bg", ".", "Line", "(", "int", "(", "p", ".", "X", ")", ",", "int", "(", "yl", ")", ",", "int", "(", "p", ".", "X", ")", ",", "int", "(", "yh", ")", ",", "ebs", ")", "\n", "}", "\n", "}", "\n\n", "// Second pass: Line", "if", "(", "plotstyle", "&", "PlotStyleLines", ")", "!=", "0", "&&", "len", "(", "points", ")", ">", "0", "{", "lastx", ",", "lasty", ":=", "int", "(", "points", "[", "0", "]", ".", "X", ")", ",", "int", "(", "points", "[", "0", "]", ".", "Y", ")", "\n", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "points", ")", ";", "i", "++", "{", "x", ",", "y", ":=", "int", "(", "points", "[", "i", "]", ".", "X", ")", ",", "int", "(", "points", "[", "i", "]", ".", "Y", ")", "\n", "bg", ".", "Line", "(", "lastx", ",", "lasty", ",", "x", ",", "y", ",", "style", ")", "\n", "lastx", ",", "lasty", "=", "x", ",", "y", "\n", "}", "\n", "}", "\n\n", "// Third pass: symbols", "if", "(", "plotstyle", "&", "PlotStylePoints", ")", "!=", "0", "&&", "len", "(", "points", ")", "!=", "0", "{", "for", "_", ",", "p", ":=", "range", "points", "{", "// fmt.Printf(\"Point %d at %d,%d\\n\", i, int(p.X), int(p.Y))", "bg", ".", "Symbol", "(", "int", "(", "p", ".", "X", ")", ",", "int", "(", "p", ".", "Y", ")", ",", "style", ")", "\n", "}", "\n", "}", "\n", "}" ]
// GenericScatter draws the given points according to style. // style.FillColor is used as color of error bars and style.FontSize is used // as the length of the endmarks of the error bars. Both have suitable defaults // if the FontXyz are not set. Point coordinates and errors must be provided // in screen coordinates.
[ "GenericScatter", "draws", "the", "given", "points", "according", "to", "style", ".", "style", ".", "FillColor", "is", "used", "as", "color", "of", "error", "bars", "and", "style", ".", "FontSize", "is", "used", "as", "the", "length", "of", "the", "endmarks", "of", "the", "error", "bars", ".", "Both", "have", "suitable", "defaults", "if", "the", "FontXyz", "are", "not", "set", ".", "Point", "coordinates", "and", "errors", "must", "be", "provided", "in", "screen", "coordinates", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/graphics.go#L369-L410
144,861
vdobler/chart
key.go
Layout
func (key Key) Layout(bg BasicGraphics, m [][]*KeyEntry, font Font) (w, h int, colwidth, rowheight []int) { fontwidth, fontheight, _ := bg.FontMetrics(font) cols, rows := len(m), len(m[0]) // Find total width and height totalh := 0 rowheight = make([]int, rows) for r := 0; r < rows; r++ { rh := 0 for c := 0; c < cols; c++ { e := m[c][r] if e == nil { continue } // fmt.Printf("Layout1 (%d,%d): %s\n", c,r,e.Text) _, h := textDim(e.Text) if h > rh { rh = h } } rowheight[r] = rh totalh += rh } totalw := 0 colwidth = make([]int, cols) // fmt.Printf("Making totalw for %d cols\n", cols) for c := 0; c < cols; c++ { var rw float32 for r := 0; r < rows; r++ { e := m[c][r] if e == nil { continue } // fmt.Printf("Layout2 (%d,%d): %s\n", c,r,e.Text) w, _ := textDim(e.Text) if w > rw { rw = w } } irw := int(rw + 0.75) colwidth[c] = irw totalw += irw // fmt.Printf("Width of col %d: %d. Total now: %d\n", c, irw, totalw) } if fontwidth == 1 && fontheight == 1 { // totalw/h are characters only and still in character-units totalw += int(KeyColSep) * (cols - 1) // add space between columns totalw += int(2*KeyHorSep + 0.5) // add space for left/right border totalw += int(KeySymbolWidth+KeySymbolSep+0.5) * cols // place for symbol and symbol-text sep totalh += int(KeyRowSep) * (rows - 1) // add space between rows vsep := KeyVertSep if vsep < 1 { vsep = 1 } // make sure there _is_ room (as KeyVertSep < 1) totalh += int(2 * vsep) // add border at top/bottom } else { // totalw/h are characters only and still in character-units totalw = int(float32(totalw) * fontwidth) // scale to pixels totalw += int(KeyColSep * (float32(cols-1) * fontwidth)) // add space between columns totalw += int(2 * KeyHorSep * fontwidth) // add space for left/right border totalw += int((KeySymbolWidth+KeySymbolSep)*fontwidth) * cols // place for symbol and symbol-text sep totalh *= fontheight totalh += int(KeyRowSep * float32((rows-1)*fontheight)) // add space between rows vsep := KeyVertSep * float32(fontheight) if vsep < 1 { vsep = 1 } // make sure there _is_ room (as KeyVertSep < 1) totalh += int(2 * vsep) // add border at top/bottom } return totalw, totalh, colwidth, rowheight }
go
func (key Key) Layout(bg BasicGraphics, m [][]*KeyEntry, font Font) (w, h int, colwidth, rowheight []int) { fontwidth, fontheight, _ := bg.FontMetrics(font) cols, rows := len(m), len(m[0]) // Find total width and height totalh := 0 rowheight = make([]int, rows) for r := 0; r < rows; r++ { rh := 0 for c := 0; c < cols; c++ { e := m[c][r] if e == nil { continue } // fmt.Printf("Layout1 (%d,%d): %s\n", c,r,e.Text) _, h := textDim(e.Text) if h > rh { rh = h } } rowheight[r] = rh totalh += rh } totalw := 0 colwidth = make([]int, cols) // fmt.Printf("Making totalw for %d cols\n", cols) for c := 0; c < cols; c++ { var rw float32 for r := 0; r < rows; r++ { e := m[c][r] if e == nil { continue } // fmt.Printf("Layout2 (%d,%d): %s\n", c,r,e.Text) w, _ := textDim(e.Text) if w > rw { rw = w } } irw := int(rw + 0.75) colwidth[c] = irw totalw += irw // fmt.Printf("Width of col %d: %d. Total now: %d\n", c, irw, totalw) } if fontwidth == 1 && fontheight == 1 { // totalw/h are characters only and still in character-units totalw += int(KeyColSep) * (cols - 1) // add space between columns totalw += int(2*KeyHorSep + 0.5) // add space for left/right border totalw += int(KeySymbolWidth+KeySymbolSep+0.5) * cols // place for symbol and symbol-text sep totalh += int(KeyRowSep) * (rows - 1) // add space between rows vsep := KeyVertSep if vsep < 1 { vsep = 1 } // make sure there _is_ room (as KeyVertSep < 1) totalh += int(2 * vsep) // add border at top/bottom } else { // totalw/h are characters only and still in character-units totalw = int(float32(totalw) * fontwidth) // scale to pixels totalw += int(KeyColSep * (float32(cols-1) * fontwidth)) // add space between columns totalw += int(2 * KeyHorSep * fontwidth) // add space for left/right border totalw += int((KeySymbolWidth+KeySymbolSep)*fontwidth) * cols // place for symbol and symbol-text sep totalh *= fontheight totalh += int(KeyRowSep * float32((rows-1)*fontheight)) // add space between rows vsep := KeyVertSep * float32(fontheight) if vsep < 1 { vsep = 1 } // make sure there _is_ room (as KeyVertSep < 1) totalh += int(2 * vsep) // add border at top/bottom } return totalw, totalh, colwidth, rowheight }
[ "func", "(", "key", "Key", ")", "Layout", "(", "bg", "BasicGraphics", ",", "m", "[", "]", "[", "]", "*", "KeyEntry", ",", "font", "Font", ")", "(", "w", ",", "h", "int", ",", "colwidth", ",", "rowheight", "[", "]", "int", ")", "{", "fontwidth", ",", "fontheight", ",", "_", ":=", "bg", ".", "FontMetrics", "(", "font", ")", "\n", "cols", ",", "rows", ":=", "len", "(", "m", ")", ",", "len", "(", "m", "[", "0", "]", ")", "\n\n", "// Find total width and height", "totalh", ":=", "0", "\n", "rowheight", "=", "make", "(", "[", "]", "int", ",", "rows", ")", "\n", "for", "r", ":=", "0", ";", "r", "<", "rows", ";", "r", "++", "{", "rh", ":=", "0", "\n", "for", "c", ":=", "0", ";", "c", "<", "cols", ";", "c", "++", "{", "e", ":=", "m", "[", "c", "]", "[", "r", "]", "\n", "if", "e", "==", "nil", "{", "continue", "\n", "}", "\n", "// fmt.Printf(\"Layout1 (%d,%d): %s\\n\", c,r,e.Text)", "_", ",", "h", ":=", "textDim", "(", "e", ".", "Text", ")", "\n", "if", "h", ">", "rh", "{", "rh", "=", "h", "\n", "}", "\n", "}", "\n", "rowheight", "[", "r", "]", "=", "rh", "\n", "totalh", "+=", "rh", "\n", "}", "\n\n", "totalw", ":=", "0", "\n", "colwidth", "=", "make", "(", "[", "]", "int", ",", "cols", ")", "\n", "// fmt.Printf(\"Making totalw for %d cols\\n\", cols)", "for", "c", ":=", "0", ";", "c", "<", "cols", ";", "c", "++", "{", "var", "rw", "float32", "\n", "for", "r", ":=", "0", ";", "r", "<", "rows", ";", "r", "++", "{", "e", ":=", "m", "[", "c", "]", "[", "r", "]", "\n", "if", "e", "==", "nil", "{", "continue", "\n", "}", "\n", "// fmt.Printf(\"Layout2 (%d,%d): %s\\n\", c,r,e.Text)", "w", ",", "_", ":=", "textDim", "(", "e", ".", "Text", ")", "\n", "if", "w", ">", "rw", "{", "rw", "=", "w", "\n", "}", "\n", "}", "\n", "irw", ":=", "int", "(", "rw", "+", "0.75", ")", "\n", "colwidth", "[", "c", "]", "=", "irw", "\n", "totalw", "+=", "irw", "\n", "// fmt.Printf(\"Width of col %d: %d. Total now: %d\\n\", c, irw, totalw)", "}", "\n\n", "if", "fontwidth", "==", "1", "&&", "fontheight", "==", "1", "{", "// totalw/h are characters only and still in character-units", "totalw", "+=", "int", "(", "KeyColSep", ")", "*", "(", "cols", "-", "1", ")", "// add space between columns", "\n", "totalw", "+=", "int", "(", "2", "*", "KeyHorSep", "+", "0.5", ")", "// add space for left/right border", "\n", "totalw", "+=", "int", "(", "KeySymbolWidth", "+", "KeySymbolSep", "+", "0.5", ")", "*", "cols", "// place for symbol and symbol-text sep", "\n\n", "totalh", "+=", "int", "(", "KeyRowSep", ")", "*", "(", "rows", "-", "1", ")", "// add space between rows", "\n", "vsep", ":=", "KeyVertSep", "\n", "if", "vsep", "<", "1", "{", "vsep", "=", "1", "\n", "}", "// make sure there _is_ room (as KeyVertSep < 1)", "\n", "totalh", "+=", "int", "(", "2", "*", "vsep", ")", "// add border at top/bottom", "\n", "}", "else", "{", "// totalw/h are characters only and still in character-units", "totalw", "=", "int", "(", "float32", "(", "totalw", ")", "*", "fontwidth", ")", "// scale to pixels", "\n", "totalw", "+=", "int", "(", "KeyColSep", "*", "(", "float32", "(", "cols", "-", "1", ")", "*", "fontwidth", ")", ")", "// add space between columns", "\n", "totalw", "+=", "int", "(", "2", "*", "KeyHorSep", "*", "fontwidth", ")", "// add space for left/right border", "\n", "totalw", "+=", "int", "(", "(", "KeySymbolWidth", "+", "KeySymbolSep", ")", "*", "fontwidth", ")", "*", "cols", "// place for symbol and symbol-text sep", "\n\n", "totalh", "*=", "fontheight", "\n", "totalh", "+=", "int", "(", "KeyRowSep", "*", "float32", "(", "(", "rows", "-", "1", ")", "*", "fontheight", ")", ")", "// add space between rows", "\n", "vsep", ":=", "KeyVertSep", "*", "float32", "(", "fontheight", ")", "\n", "if", "vsep", "<", "1", "{", "vsep", "=", "1", "\n", "}", "// make sure there _is_ room (as KeyVertSep < 1)", "\n", "totalh", "+=", "int", "(", "2", "*", "vsep", ")", "// add border at top/bottom", "\n", "}", "\n", "return", "totalw", ",", "totalh", ",", "colwidth", ",", "rowheight", "\n", "}" ]
// Layout determines how wide and broad the places keys in m will be rendered.
[ "Layout", "determines", "how", "wide", "and", "broad", "the", "places", "keys", "in", "m", "will", "be", "rendered", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/key.go#L137-L212
144,862
vdobler/chart
bar.go
AddData
func (c *BarChart) AddData(name string, data []Point, style Style) { if len(c.Data) == 0 { c.XRange.init() c.YRange.init() } c.Data = append(c.Data, BarChartData{name, style, data}) for _, d := range data { c.XRange.autoscale(d.X) c.YRange.autoscale(d.Y) } if name != "" { c.Key.Entries = append(c.Key.Entries, KeyEntry{Style: style, Text: name, PlotStyle: PlotStyleBox}) } }
go
func (c *BarChart) AddData(name string, data []Point, style Style) { if len(c.Data) == 0 { c.XRange.init() c.YRange.init() } c.Data = append(c.Data, BarChartData{name, style, data}) for _, d := range data { c.XRange.autoscale(d.X) c.YRange.autoscale(d.Y) } if name != "" { c.Key.Entries = append(c.Key.Entries, KeyEntry{Style: style, Text: name, PlotStyle: PlotStyleBox}) } }
[ "func", "(", "c", "*", "BarChart", ")", "AddData", "(", "name", "string", ",", "data", "[", "]", "Point", ",", "style", "Style", ")", "{", "if", "len", "(", "c", ".", "Data", ")", "==", "0", "{", "c", ".", "XRange", ".", "init", "(", ")", "\n", "c", ".", "YRange", ".", "init", "(", ")", "\n", "}", "\n", "c", ".", "Data", "=", "append", "(", "c", ".", "Data", ",", "BarChartData", "{", "name", ",", "style", ",", "data", "}", ")", "\n", "for", "_", ",", "d", ":=", "range", "data", "{", "c", ".", "XRange", ".", "autoscale", "(", "d", ".", "X", ")", "\n", "c", ".", "YRange", ".", "autoscale", "(", "d", ".", "Y", ")", "\n", "}", "\n\n", "if", "name", "!=", "\"", "\"", "{", "c", ".", "Key", ".", "Entries", "=", "append", "(", "c", ".", "Key", ".", "Entries", ",", "KeyEntry", "{", "Style", ":", "style", ",", "Text", ":", "name", ",", "PlotStyle", ":", "PlotStyleBox", "}", ")", "\n", "}", "\n", "}" ]
// AddData adds the data to the chart.
[ "AddData", "adds", "the", "data", "to", "the", "chart", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/bar.go#L35-L49
144,863
vdobler/chart
style.go
SymbolIndex
func SymbolIndex(s int) (idx int) { for idx = 0; idx < len(Symbol); idx++ { if Symbol[idx] == s { return idx } } return -1 }
go
func SymbolIndex(s int) (idx int) { for idx = 0; idx < len(Symbol); idx++ { if Symbol[idx] == s { return idx } } return -1 }
[ "func", "SymbolIndex", "(", "s", "int", ")", "(", "idx", "int", ")", "{", "for", "idx", "=", "0", ";", "idx", "<", "len", "(", "Symbol", ")", ";", "idx", "++", "{", "if", "Symbol", "[", "idx", "]", "==", "s", "{", "return", "idx", "\n", "}", "\n", "}", "\n", "return", "-", "1", "\n", "}" ]
// SymbolIndex returns the index of the symbol s in Symbol or -1 if not found.
[ "SymbolIndex", "returns", "the", "index", "of", "the", "symbol", "s", "in", "Symbol", "or", "-", "1", "if", "not", "found", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/style.go#L29-L36
144,864
vdobler/chart
stat.go
PercentilInt
func PercentilInt(data []int, p int) int { n := len(data) if n == 0 { return 0 } if n == 1 { return data[0] } pos := float64(p) * float64(n+1) / 100 fpos := math.Floor(pos) intPos := int(fpos) dif := pos - fpos if intPos < 1 { return data[0] } if intPos >= n { return data[n-1] } lower := data[intPos-1] upper := data[intPos] val := float64(lower) + dif*float64(upper-lower) return int(math.Floor(val + 0.5)) }
go
func PercentilInt(data []int, p int) int { n := len(data) if n == 0 { return 0 } if n == 1 { return data[0] } pos := float64(p) * float64(n+1) / 100 fpos := math.Floor(pos) intPos := int(fpos) dif := pos - fpos if intPos < 1 { return data[0] } if intPos >= n { return data[n-1] } lower := data[intPos-1] upper := data[intPos] val := float64(lower) + dif*float64(upper-lower) return int(math.Floor(val + 0.5)) }
[ "func", "PercentilInt", "(", "data", "[", "]", "int", ",", "p", "int", ")", "int", "{", "n", ":=", "len", "(", "data", ")", "\n", "if", "n", "==", "0", "{", "return", "0", "\n", "}", "\n", "if", "n", "==", "1", "{", "return", "data", "[", "0", "]", "\n", "}", "\n\n", "pos", ":=", "float64", "(", "p", ")", "*", "float64", "(", "n", "+", "1", ")", "/", "100", "\n", "fpos", ":=", "math", ".", "Floor", "(", "pos", ")", "\n", "intPos", ":=", "int", "(", "fpos", ")", "\n", "dif", ":=", "pos", "-", "fpos", "\n", "if", "intPos", "<", "1", "{", "return", "data", "[", "0", "]", "\n", "}", "\n", "if", "intPos", ">=", "n", "{", "return", "data", "[", "n", "-", "1", "]", "\n", "}", "\n", "lower", ":=", "data", "[", "intPos", "-", "1", "]", "\n", "upper", ":=", "data", "[", "intPos", "]", "\n", "val", ":=", "float64", "(", "lower", ")", "+", "dif", "*", "float64", "(", "upper", "-", "lower", ")", "\n", "return", "int", "(", "math", ".", "Floor", "(", "val", "+", "0.5", ")", ")", "\n", "}" ]
// Return p percentil of pre-sorted integer data. 0 <= p <= 100.
[ "Return", "p", "percentil", "of", "pre", "-", "sorted", "integer", "data", ".", "0", "<", "=", "p", "<", "=", "100", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/stat.go#L9-L32
144,865
vdobler/chart
svgg/svg.go
New
func New(sp *svg.SVG, width, height int, font string, fontsize int, background color.RGBA) *SvgGraphics { if font == "" { font = "Helvetica" } if fontsize == 0 { fontsize = 12 } s := SvgGraphics{svg: sp, w: width, h: height, font: font, fs: fontsize, bg: background} return &s }
go
func New(sp *svg.SVG, width, height int, font string, fontsize int, background color.RGBA) *SvgGraphics { if font == "" { font = "Helvetica" } if fontsize == 0 { fontsize = 12 } s := SvgGraphics{svg: sp, w: width, h: height, font: font, fs: fontsize, bg: background} return &s }
[ "func", "New", "(", "sp", "*", "svg", ".", "SVG", ",", "width", ",", "height", "int", ",", "font", "string", ",", "fontsize", "int", ",", "background", "color", ".", "RGBA", ")", "*", "SvgGraphics", "{", "if", "font", "==", "\"", "\"", "{", "font", "=", "\"", "\"", "\n", "}", "\n", "if", "fontsize", "==", "0", "{", "fontsize", "=", "12", "\n", "}", "\n", "s", ":=", "SvgGraphics", "{", "svg", ":", "sp", ",", "w", ":", "width", ",", "h", ":", "height", ",", "font", ":", "font", ",", "fs", ":", "fontsize", ",", "bg", ":", "background", "}", "\n", "return", "&", "s", "\n", "}" ]
// New creates a new SvgGraphics of dimension w x h, with a default font font of size fontsize.
[ "New", "creates", "a", "new", "SvgGraphics", "of", "dimension", "w", "x", "h", "with", "a", "default", "font", "font", "of", "size", "fontsize", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/svgg/svg.go#L23-L32
144,866
vdobler/chart
txtg/buf.go
NewTextBuf
func NewTextBuf(w, h int) (tb *TextBuf) { tb = new(TextBuf) tb.W, tb.H = w, h tb.Buf = make([]rune, (w+1)*h) for i, _ := range tb.Buf { tb.Buf[i] = ' ' } for i := 0; i < h; i++ { tb.Buf[i*(w+1)+w] = '\n' } // tb.Buf[0], tb.Buf[(w+1)*h-1] = 'X', 'X' return }
go
func NewTextBuf(w, h int) (tb *TextBuf) { tb = new(TextBuf) tb.W, tb.H = w, h tb.Buf = make([]rune, (w+1)*h) for i, _ := range tb.Buf { tb.Buf[i] = ' ' } for i := 0; i < h; i++ { tb.Buf[i*(w+1)+w] = '\n' } // tb.Buf[0], tb.Buf[(w+1)*h-1] = 'X', 'X' return }
[ "func", "NewTextBuf", "(", "w", ",", "h", "int", ")", "(", "tb", "*", "TextBuf", ")", "{", "tb", "=", "new", "(", "TextBuf", ")", "\n", "tb", ".", "W", ",", "tb", ".", "H", "=", "w", ",", "h", "\n", "tb", ".", "Buf", "=", "make", "(", "[", "]", "rune", ",", "(", "w", "+", "1", ")", "*", "h", ")", "\n", "for", "i", ",", "_", ":=", "range", "tb", ".", "Buf", "{", "tb", ".", "Buf", "[", "i", "]", "=", "' '", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "h", ";", "i", "++", "{", "tb", ".", "Buf", "[", "i", "*", "(", "w", "+", "1", ")", "+", "w", "]", "=", "'\\n'", "\n", "}", "\n", "// tb.Buf[0], tb.Buf[(w+1)*h-1] = 'X', 'X'", "return", "\n", "}" ]
// Set up a new TextBuf with width w and height h.
[ "Set", "up", "a", "new", "TextBuf", "with", "width", "w", "and", "height", "h", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/txtg/buf.go#L17-L29
144,867
vdobler/chart
strip.go
AddData
func (sc *StripChart) AddData(name string, data []float64, style Style) { n := len(sc.ScatterChart.Data) + 1 pd := make([]EPoint, len(data)) nan := math.NaN() for i, d := range data { pd[i].X = d pd[i].Y = float64(n) pd[i].DeltaX, pd[i].DeltaY = nan, nan } if style.empty() { style = AutoStyle(len(sc.Data), false) } style.LineStyle = 0 sc.ScatterChart.AddData(name, pd, PlotStylePoints, style) }
go
func (sc *StripChart) AddData(name string, data []float64, style Style) { n := len(sc.ScatterChart.Data) + 1 pd := make([]EPoint, len(data)) nan := math.NaN() for i, d := range data { pd[i].X = d pd[i].Y = float64(n) pd[i].DeltaX, pd[i].DeltaY = nan, nan } if style.empty() { style = AutoStyle(len(sc.Data), false) } style.LineStyle = 0 sc.ScatterChart.AddData(name, pd, PlotStylePoints, style) }
[ "func", "(", "sc", "*", "StripChart", ")", "AddData", "(", "name", "string", ",", "data", "[", "]", "float64", ",", "style", "Style", ")", "{", "n", ":=", "len", "(", "sc", ".", "ScatterChart", ".", "Data", ")", "+", "1", "\n", "pd", ":=", "make", "(", "[", "]", "EPoint", ",", "len", "(", "data", ")", ")", "\n", "nan", ":=", "math", ".", "NaN", "(", ")", "\n", "for", "i", ",", "d", ":=", "range", "data", "{", "pd", "[", "i", "]", ".", "X", "=", "d", "\n", "pd", "[", "i", "]", ".", "Y", "=", "float64", "(", "n", ")", "\n", "pd", "[", "i", "]", ".", "DeltaX", ",", "pd", "[", "i", "]", ".", "DeltaY", "=", "nan", ",", "nan", "\n", "}", "\n", "if", "style", ".", "empty", "(", ")", "{", "style", "=", "AutoStyle", "(", "len", "(", "sc", ".", "Data", ")", ",", "false", ")", "\n", "}", "\n", "style", ".", "LineStyle", "=", "0", "\n", "sc", ".", "ScatterChart", ".", "AddData", "(", "name", ",", "pd", ",", "PlotStylePoints", ",", "style", ")", "\n", "}" ]
// AddData adds data to the strip chart.
[ "AddData", "adds", "data", "to", "the", "strip", "chart", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/strip.go#L18-L32
144,868
vdobler/chart
strip.go
Plot
func (sc *StripChart) Plot(g Graphics) { sc.ScatterChart.YRange.Label = "" sc.ScatterChart.YRange.TicSetting.Hide = true sc.ScatterChart.YRange.TicSetting.Delta = 1 sc.ScatterChart.YRange.MinMode.Fixed = true sc.ScatterChart.YRange.MinMode.Value = 0.5 sc.ScatterChart.YRange.MaxMode.Fixed = true sc.ScatterChart.YRange.MaxMode.Value = float64(len(sc.ScatterChart.Data)) + 0.5 if sc.Jitter { // Set up ranging layout := layout(g, sc.Title, sc.XRange.Label, sc.YRange.Label, sc.XRange.TicSetting.Hide || sc.XRange.TicSetting.HideLabels, sc.YRange.TicSetting.Hide || sc.YRange.TicSetting.HideLabels, &sc.Key) _, height := layout.Width, layout.Height topm, _ := layout.Top, layout.Left _, numytics := layout.NumXtics, layout.NumYtics sc.YRange.Setup(numytics, numytics+1, height, topm, true) // amplitude of jitter: not too smal to be visible and useful, not to // big to be ugly or even overlapp other null := sc.YRange.Screen2Data(0) absmin := 1.4 * math.Abs(sc.YRange.Screen2Data(1)-null) // would be one pixel tenpc := math.Abs(sc.YRange.Screen2Data(height)-null) / 10 // 10 percent of graph area smplcnt := len(sc.ScatterChart.Data) + 1 // as samples are borders noverlp := math.Abs(sc.YRange.Screen2Data(height/smplcnt) - null) // do not overlapp other sample yj := noverlp if tenpc < yj { yj = tenpc } if yj < absmin { yj = absmin } // yjs := sc.YRange.Data2Screen(yj) - sc.YRange.Data2Screen(0) // fmt.Printf("yj = %.2f : in screen = %d\n", yj, yjs) for _, data := range sc.ScatterChart.Data { if data.Samples == nil { continue // should not happen } for i := range data.Samples { shift := yj * rand.NormFloat64() * yj data.Samples[i].Y += shift } } } sc.ScatterChart.Plot(g) if sc.Jitter { // Revert Jitter for s, data := range sc.ScatterChart.Data { if data.Samples == nil { continue // should not happen } for i, _ := range data.Samples { data.Samples[i].Y = float64(s + 1) } } } }
go
func (sc *StripChart) Plot(g Graphics) { sc.ScatterChart.YRange.Label = "" sc.ScatterChart.YRange.TicSetting.Hide = true sc.ScatterChart.YRange.TicSetting.Delta = 1 sc.ScatterChart.YRange.MinMode.Fixed = true sc.ScatterChart.YRange.MinMode.Value = 0.5 sc.ScatterChart.YRange.MaxMode.Fixed = true sc.ScatterChart.YRange.MaxMode.Value = float64(len(sc.ScatterChart.Data)) + 0.5 if sc.Jitter { // Set up ranging layout := layout(g, sc.Title, sc.XRange.Label, sc.YRange.Label, sc.XRange.TicSetting.Hide || sc.XRange.TicSetting.HideLabels, sc.YRange.TicSetting.Hide || sc.YRange.TicSetting.HideLabels, &sc.Key) _, height := layout.Width, layout.Height topm, _ := layout.Top, layout.Left _, numytics := layout.NumXtics, layout.NumYtics sc.YRange.Setup(numytics, numytics+1, height, topm, true) // amplitude of jitter: not too smal to be visible and useful, not to // big to be ugly or even overlapp other null := sc.YRange.Screen2Data(0) absmin := 1.4 * math.Abs(sc.YRange.Screen2Data(1)-null) // would be one pixel tenpc := math.Abs(sc.YRange.Screen2Data(height)-null) / 10 // 10 percent of graph area smplcnt := len(sc.ScatterChart.Data) + 1 // as samples are borders noverlp := math.Abs(sc.YRange.Screen2Data(height/smplcnt) - null) // do not overlapp other sample yj := noverlp if tenpc < yj { yj = tenpc } if yj < absmin { yj = absmin } // yjs := sc.YRange.Data2Screen(yj) - sc.YRange.Data2Screen(0) // fmt.Printf("yj = %.2f : in screen = %d\n", yj, yjs) for _, data := range sc.ScatterChart.Data { if data.Samples == nil { continue // should not happen } for i := range data.Samples { shift := yj * rand.NormFloat64() * yj data.Samples[i].Y += shift } } } sc.ScatterChart.Plot(g) if sc.Jitter { // Revert Jitter for s, data := range sc.ScatterChart.Data { if data.Samples == nil { continue // should not happen } for i, _ := range data.Samples { data.Samples[i].Y = float64(s + 1) } } } }
[ "func", "(", "sc", "*", "StripChart", ")", "Plot", "(", "g", "Graphics", ")", "{", "sc", ".", "ScatterChart", ".", "YRange", ".", "Label", "=", "\"", "\"", "\n", "sc", ".", "ScatterChart", ".", "YRange", ".", "TicSetting", ".", "Hide", "=", "true", "\n", "sc", ".", "ScatterChart", ".", "YRange", ".", "TicSetting", ".", "Delta", "=", "1", "\n", "sc", ".", "ScatterChart", ".", "YRange", ".", "MinMode", ".", "Fixed", "=", "true", "\n", "sc", ".", "ScatterChart", ".", "YRange", ".", "MinMode", ".", "Value", "=", "0.5", "\n", "sc", ".", "ScatterChart", ".", "YRange", ".", "MaxMode", ".", "Fixed", "=", "true", "\n", "sc", ".", "ScatterChart", ".", "YRange", ".", "MaxMode", ".", "Value", "=", "float64", "(", "len", "(", "sc", ".", "ScatterChart", ".", "Data", ")", ")", "+", "0.5", "\n\n", "if", "sc", ".", "Jitter", "{", "// Set up ranging", "layout", ":=", "layout", "(", "g", ",", "sc", ".", "Title", ",", "sc", ".", "XRange", ".", "Label", ",", "sc", ".", "YRange", ".", "Label", ",", "sc", ".", "XRange", ".", "TicSetting", ".", "Hide", "||", "sc", ".", "XRange", ".", "TicSetting", ".", "HideLabels", ",", "sc", ".", "YRange", ".", "TicSetting", ".", "Hide", "||", "sc", ".", "YRange", ".", "TicSetting", ".", "HideLabels", ",", "&", "sc", ".", "Key", ")", "\n\n", "_", ",", "height", ":=", "layout", ".", "Width", ",", "layout", ".", "Height", "\n", "topm", ",", "_", ":=", "layout", ".", "Top", ",", "layout", ".", "Left", "\n", "_", ",", "numytics", ":=", "layout", ".", "NumXtics", ",", "layout", ".", "NumYtics", "\n\n", "sc", ".", "YRange", ".", "Setup", "(", "numytics", ",", "numytics", "+", "1", ",", "height", ",", "topm", ",", "true", ")", "\n\n", "// amplitude of jitter: not too smal to be visible and useful, not to", "// big to be ugly or even overlapp other", "null", ":=", "sc", ".", "YRange", ".", "Screen2Data", "(", "0", ")", "\n", "absmin", ":=", "1.4", "*", "math", ".", "Abs", "(", "sc", ".", "YRange", ".", "Screen2Data", "(", "1", ")", "-", "null", ")", "// would be one pixel", "\n", "tenpc", ":=", "math", ".", "Abs", "(", "sc", ".", "YRange", ".", "Screen2Data", "(", "height", ")", "-", "null", ")", "/", "10", "// 10 percent of graph area", "\n", "smplcnt", ":=", "len", "(", "sc", ".", "ScatterChart", ".", "Data", ")", "+", "1", "// as samples are borders", "\n", "noverlp", ":=", "math", ".", "Abs", "(", "sc", ".", "YRange", ".", "Screen2Data", "(", "height", "/", "smplcnt", ")", "-", "null", ")", "// do not overlapp other sample", "\n\n", "yj", ":=", "noverlp", "\n", "if", "tenpc", "<", "yj", "{", "yj", "=", "tenpc", "\n", "}", "\n", "if", "yj", "<", "absmin", "{", "yj", "=", "absmin", "\n", "}", "\n\n", "// yjs := sc.YRange.Data2Screen(yj) - sc.YRange.Data2Screen(0)", "// fmt.Printf(\"yj = %.2f : in screen = %d\\n\", yj, yjs)", "for", "_", ",", "data", ":=", "range", "sc", ".", "ScatterChart", ".", "Data", "{", "if", "data", ".", "Samples", "==", "nil", "{", "continue", "// should not happen", "\n", "}", "\n", "for", "i", ":=", "range", "data", ".", "Samples", "{", "shift", ":=", "yj", "*", "rand", ".", "NormFloat64", "(", ")", "*", "yj", "\n", "data", ".", "Samples", "[", "i", "]", ".", "Y", "+=", "shift", "\n", "}", "\n", "}", "\n", "}", "\n", "sc", ".", "ScatterChart", ".", "Plot", "(", "g", ")", "\n\n", "if", "sc", ".", "Jitter", "{", "// Revert Jitter", "for", "s", ",", "data", ":=", "range", "sc", ".", "ScatterChart", ".", "Data", "{", "if", "data", ".", "Samples", "==", "nil", "{", "continue", "// should not happen", "\n", "}", "\n", "for", "i", ",", "_", ":=", "range", "data", ".", "Samples", "{", "data", ".", "Samples", "[", "i", "]", ".", "Y", "=", "float64", "(", "s", "+", "1", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Plot outputs the strip chart sc to g.
[ "Plot", "outputs", "the", "strip", "chart", "sc", "to", "g", "." ]
6627804132c7c237061d1c8fd2554e3206daecb6
https://github.com/vdobler/chart/blob/6627804132c7c237061d1c8fd2554e3206daecb6/strip.go#L52-L116
144,869
TheThingsNetwork/ttn
api/health/client.go
Check
func Check(conn *grpc.ClientConn) (bool, error) { res, err := healthpb.NewHealthClient(conn).Check(context.Background(), &healthpb.HealthCheckRequest{}) if err != nil { return false, err } return res.Status == healthpb.HealthCheckResponse_SERVING, nil }
go
func Check(conn *grpc.ClientConn) (bool, error) { res, err := healthpb.NewHealthClient(conn).Check(context.Background(), &healthpb.HealthCheckRequest{}) if err != nil { return false, err } return res.Status == healthpb.HealthCheckResponse_SERVING, nil }
[ "func", "Check", "(", "conn", "*", "grpc", ".", "ClientConn", ")", "(", "bool", ",", "error", ")", "{", "res", ",", "err", ":=", "healthpb", ".", "NewHealthClient", "(", "conn", ")", ".", "Check", "(", "context", ".", "Background", "(", ")", ",", "&", "healthpb", ".", "HealthCheckRequest", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "res", ".", "Status", "==", "healthpb", ".", "HealthCheckResponse_SERVING", ",", "nil", "\n", "}" ]
// Check the health of a connection
[ "Check", "the", "health", "of", "a", "connection" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/api/health/client.go#L13-L19
144,870
TheThingsNetwork/ttn
core/types/parse_hex.go
ParseHEX
func ParseHEX(input string, length int) ([]byte, error) { if input == "" { return make([]byte, length), nil } pattern := regexp.MustCompile(fmt.Sprintf("^[[:xdigit:]]{%d}$", length*2)) valid := pattern.MatchString(input) if !valid { return nil, fmt.Errorf("Invalid input: %s is not hex", input) } slice, _ := hex.DecodeString(input) return slice, nil }
go
func ParseHEX(input string, length int) ([]byte, error) { if input == "" { return make([]byte, length), nil } pattern := regexp.MustCompile(fmt.Sprintf("^[[:xdigit:]]{%d}$", length*2)) valid := pattern.MatchString(input) if !valid { return nil, fmt.Errorf("Invalid input: %s is not hex", input) } slice, _ := hex.DecodeString(input) return slice, nil }
[ "func", "ParseHEX", "(", "input", "string", ",", "length", "int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "input", "==", "\"", "\"", "{", "return", "make", "(", "[", "]", "byte", ",", "length", ")", ",", "nil", "\n", "}", "\n\n", "pattern", ":=", "regexp", ".", "MustCompile", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "length", "*", "2", ")", ")", "\n\n", "valid", ":=", "pattern", ".", "MatchString", "(", "input", ")", "\n", "if", "!", "valid", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "input", ")", "\n", "}", "\n\n", "slice", ",", "_", ":=", "hex", ".", "DecodeString", "(", "input", ")", "\n\n", "return", "slice", ",", "nil", "\n", "}" ]
// ParseHEX parses a string "input" to a byteslice with length "length".
[ "ParseHEX", "parses", "a", "string", "input", "to", "a", "byteslice", "with", "length", "length", "." ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/types/parse_hex.go#L13-L28
144,871
TheThingsNetwork/ttn
core/router/router.go
NewRouter
func NewRouter() Router { return &router{ gateways: make(map[string]*gateway.Gateway), brokers: make(map[string]*broker), } }
go
func NewRouter() Router { return &router{ gateways: make(map[string]*gateway.Gateway), brokers: make(map[string]*broker), } }
[ "func", "NewRouter", "(", ")", "Router", "{", "return", "&", "router", "{", "gateways", ":", "make", "(", "map", "[", "string", "]", "*", "gateway", ".", "Gateway", ")", ",", "brokers", ":", "make", "(", "map", "[", "string", "]", "*", "broker", ")", ",", "}", "\n", "}" ]
// NewRouter creates a new Router
[ "NewRouter", "creates", "a", "new", "Router" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/router/router.go#L54-L59
144,872
TheThingsNetwork/ttn
core/router/router.go
getGateway
func (r *router) getGateway(id string) *gateway.Gateway { // We're going to be optimistic and guess that the gateway is already active r.gatewaysLock.RLock() gtw, ok := r.gateways[id] r.gatewaysLock.RUnlock() if ok { return gtw } // If it doesn't we still have to lock r.gatewaysLock.Lock() defer r.gatewaysLock.Unlock() gtw, ok = r.gateways[id] if !ok { gtw = gateway.NewGateway(r.Ctx, id) ctx := context.Background() ctx = ttnctx.OutgoingContextWithID(ctx, id) if r.Identity != nil { ctx = ttnctx.OutgoingContextWithServiceInfo(ctx, r.Identity.ServiceName, r.Identity.ServiceVersion, r.Identity.NetAddress) } gtw.MonitorStream = r.Component.Monitor.GatewayClient( ctx, grpc.PerRPCCredentials(auth.WithTokenFunc("id", func(ctxID string) string { if ctxID != id { return "" } return gtw.Token() })), ) r.gateways[id] = gtw } return gtw }
go
func (r *router) getGateway(id string) *gateway.Gateway { // We're going to be optimistic and guess that the gateway is already active r.gatewaysLock.RLock() gtw, ok := r.gateways[id] r.gatewaysLock.RUnlock() if ok { return gtw } // If it doesn't we still have to lock r.gatewaysLock.Lock() defer r.gatewaysLock.Unlock() gtw, ok = r.gateways[id] if !ok { gtw = gateway.NewGateway(r.Ctx, id) ctx := context.Background() ctx = ttnctx.OutgoingContextWithID(ctx, id) if r.Identity != nil { ctx = ttnctx.OutgoingContextWithServiceInfo(ctx, r.Identity.ServiceName, r.Identity.ServiceVersion, r.Identity.NetAddress) } gtw.MonitorStream = r.Component.Monitor.GatewayClient( ctx, grpc.PerRPCCredentials(auth.WithTokenFunc("id", func(ctxID string) string { if ctxID != id { return "" } return gtw.Token() })), ) r.gateways[id] = gtw } return gtw }
[ "func", "(", "r", "*", "router", ")", "getGateway", "(", "id", "string", ")", "*", "gateway", ".", "Gateway", "{", "// We're going to be optimistic and guess that the gateway is already active", "r", ".", "gatewaysLock", ".", "RLock", "(", ")", "\n", "gtw", ",", "ok", ":=", "r", ".", "gateways", "[", "id", "]", "\n", "r", ".", "gatewaysLock", ".", "RUnlock", "(", ")", "\n", "if", "ok", "{", "return", "gtw", "\n", "}", "\n", "// If it doesn't we still have to lock", "r", ".", "gatewaysLock", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "gatewaysLock", ".", "Unlock", "(", ")", "\n\n", "gtw", ",", "ok", "=", "r", ".", "gateways", "[", "id", "]", "\n", "if", "!", "ok", "{", "gtw", "=", "gateway", ".", "NewGateway", "(", "r", ".", "Ctx", ",", "id", ")", "\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "ctx", "=", "ttnctx", ".", "OutgoingContextWithID", "(", "ctx", ",", "id", ")", "\n", "if", "r", ".", "Identity", "!=", "nil", "{", "ctx", "=", "ttnctx", ".", "OutgoingContextWithServiceInfo", "(", "ctx", ",", "r", ".", "Identity", ".", "ServiceName", ",", "r", ".", "Identity", ".", "ServiceVersion", ",", "r", ".", "Identity", ".", "NetAddress", ")", "\n", "}", "\n", "gtw", ".", "MonitorStream", "=", "r", ".", "Component", ".", "Monitor", ".", "GatewayClient", "(", "ctx", ",", "grpc", ".", "PerRPCCredentials", "(", "auth", ".", "WithTokenFunc", "(", "\"", "\"", ",", "func", "(", "ctxID", "string", ")", "string", "{", "if", "ctxID", "!=", "id", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "gtw", ".", "Token", "(", ")", "\n", "}", ")", ")", ",", ")", "\n", "r", ".", "gateways", "[", "id", "]", "=", "gtw", "\n", "}", "\n\n", "return", "gtw", "\n", "}" ]
// getGateway gets or creates a Gateway
[ "getGateway", "gets", "or", "creates", "a", "Gateway" ]
fc5709a55c20e1712047e5cb5a8d571aa62eefbb
https://github.com/TheThingsNetwork/ttn/blob/fc5709a55c20e1712047e5cb5a8d571aa62eefbb/core/router/router.go#L114-L147
144,873
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
144,874
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
144,875
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
144,876
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
144,877
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
144,878
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
144,879
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
144,880
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
144,881
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
144,882
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
144,883
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
144,884
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
144,885
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
144,886
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
144,887
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
144,888
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
144,889
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
144,890
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
144,891
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
144,892
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
144,893
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
144,894
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
144,895
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
144,896
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
144,897
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
144,898
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
144,899
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