Skip to content

Commit

Permalink
like graph
Browse files Browse the repository at this point in the history
  • Loading branch information
Ozoniuss committed Apr 7, 2024
1 parent 2cf59c2 commit c1b4eb2
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 29 deletions.
67 changes: 43 additions & 24 deletions outbox/main.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,27 @@
import datetime
import json
import socket
import sys
from collections import Counter
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from dataclasses import dataclass, asdict


# #define data
# df = pd.DataFrame({'date': np.array([datetime.datetime(2020, 1, i+1)
# for i in range(12)]),
# 'sales': [3, 4, 4, 7, 8, 9, 14, 17, 12, 8, 8, 13]})

# #plot time series
# plt.plot(df.date, df.sales, linewidth=3)
# plt.savefig("data.png")

HOST = "127.0.0.1"
PORT = sys.argv[1]

PORT = 13312
if PORT == None or PORT == "":
PORT = 13311
else:
PORT = int(PORT)

@dataclass
class ArticleLikedEvent:
event_id: str
article_id: str
timestamp: datetime.datetime
timestamp: str

@dataclass
class Message:
Expand All @@ -36,17 +32,42 @@ class Message:
class Ack:
id: int

def parse_time(timestamp: str) -> datetime.datetime:
"""Helper to generate a valid timestamp from a string"""

# Parse the string into a datetime object
dt = datetime.datetime.fromisoformat(timestamp[:-6])

# Extract timezone offset
tz_offset = timestamp[-6:]

# Parse the timezone offset
hours_offset = int(tz_offset[:3])
minutes_offset = int(tz_offset[4:])

# Create a timedelta object for timezone offset
td = datetime.timedelta(hours=hours_offset, minutes=minutes_offset)

# Adjust datetime object with timezone offset
if tz_offset[3] == '+':
dt = dt - td
else:
dt = dt + td

return dt

def generate_like_graph(events: list[ArticleLikedEvent]):

totals = []
for e in events:
totals.append(str(datetime.datetime(
e.timestamp.year,
e.timestamp.month,
e.timestamp.day,
e.timestamp.hour,
e.timestamp.minute,
e.timestamp.second)))
ts = parse_time(e.timestamp)
totals.append(datetime.datetime(
ts.year,
ts.month,
ts.day,
ts.hour,
ts.minute,
ts.second))

totalsDict = dict(Counter(totals))
xaxis, yaxis = [], []
Expand All @@ -56,14 +77,14 @@ def generate_like_graph(events: list[ArticleLikedEvent]):

#define data
df = pd.DataFrame({
'time':xaxis,
'time':[str(t.second) for t in xaxis],
'seconds': yaxis})

#plot time series
plt.plot(df.time, df.seconds, linewidth=3)
#add title and axis labels
plt.title('Likes by second')
plt.xlabel('Second')
plt.xlabel('Second (trimmed)')
plt.ylabel('Likes')

plt.savefig('data.png')
Expand All @@ -88,17 +109,15 @@ def generate_like_graph(events: list[ArticleLikedEvent]):

receivedEvents.extend(message.events)


ack = json.dumps(asdict(Ack(id=message.id)))
conn.sendall(bytes(ack,encoding="utf-8"))
all = [e.event_id for e in receivedEvents]
print("allevents", all, len(all))

if c == 10:

break
# generate the graph upon ctrl + C
except KeyboardInterrupt:
generate_like_graph(receivedEvents)
break

except Exception as e:
print("exception", e)
Expand Down
15 changes: 10 additions & 5 deletions outbox/producer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ func NewHandler(storage articles.ArticleStorage) handler {

func main() {

portstr := os.Args[1]
if portstr == "" {
portstr = "13311"
}

zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
zerolog.SetGlobalLevel(zerolog.DebugLevel)

Expand All @@ -66,13 +71,13 @@ func main() {
ModifiedAt: time.Now(),
}
storage.Insert(a)
err := LikeArticle(a.Id)
if err != nil {
log.Error().Err(err).Msg("could not like article")
}
// err := LikeArticle(a.Id)
// if err != nil {
// log.Error().Err(err).Msg("could not like article")
// }

// Initialize poller
poller, err := articles.NewLikedArticlesPoller(storage, 5*time.Second, "localhost:13312")
poller, err := articles.NewLikedArticlesPoller(storage, 5*time.Second, "localhost:"+portstr)
if err != nil {
fmt.Printf("could not start poller: %s\n", err.Error())
os.Exit(1)
Expand Down

0 comments on commit c1b4eb2

Please sign in to comment.