Skip to content

Instantly share code, notes, and snippets.

@kdungs
Created May 23, 2015 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kdungs/7efb49a0497d9bbfe404 to your computer and use it in GitHub Desktop.
Save kdungs/7efb49a0497d9bbfe404 to your computer and use it in GitHub Desktop.
package main
import (
zmq "github.com/pebbe/zmq4"
//"golang.org/x/net/websocket"
"errors"
"fmt"
"strconv"
"strings"
)
type Hist struct {
Bins []int64
N int64
Min, Max float64
BinWidth float64
}
func NewHist(n int64, min, max float64) (*Hist, error) {
if min >= max {
return nil, errors.New("Min has to be smaller than max.")
}
if n < 1 {
return nil, errors.New("N has to be larger than 0.")
}
hist := new(Hist)
hist.Min = min
hist.Max = max
hist.N = n
hist.Bins = make([]int64, n)
hist.BinWidth = (max - min) / float64(n)
return hist, nil
}
func (hist *Hist) UnsafeAdd(val float64) {
bin := int64((val - hist.Min) / hist.BinWidth)
hist.Bins[bin]++
}
func (hist *Hist) Add(val float64) error {
if val < hist.Min || val > hist.Max {
return errors.New("Value has to be within limits.")
}
hist.UnsafeAdd(val)
return nil
}
func (hist *Hist) Print() {
binValue := hist.Min
for _, bin := range hist.Bins {
fmt.Printf("%f: %d\n", binValue, bin)
binValue += hist.BinWidth
}
}
func main() {
sub, _ := zmq.NewSocket(zmq.SUB)
defer sub.Close()
sub.Connect("tcp://localhost:31337")
filter := "10001 "
sub.SetSubscribe(filter)
update_nbr := 0
h, err := NewHist(10, -3, 3)
if err != nil {
panic("LULWUT!")
}
for update_nbr <= 10 {
msg, _ := sub.Recv(0)
fmt.Printf("%s\n", msg)
if msgs := strings.Fields(msg); len(msgs) > 1 {
if temp, err := strconv.ParseFloat(msgs[1], 64); err == nil {
herr := h.Add(temp)
if herr != nil {
fmt.Printf("Couldn't add value: %s", herr)
}
update_nbr++
}
}
}
h.Print()
}
#!/usr/bin/env python
import random
import time
import zmq
PORT = 31337
if __name__ == '__main__':
ctx = zmq.Context()
sck = ctx.socket(zmq.PUB)
sck.bind("tcp://*:{}".format(PORT))
while True:
top = random.randrange(9999, 10005)
msg = random.normalvariate(0, 1)
msgstr = "{} {}".format(top, msg)
print(msgstr)
sck.send_string(msgstr)
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment