Skip to content

Commit

Permalink
036
Browse files Browse the repository at this point in the history
  • Loading branch information
bbelderbos committed May 2, 2017
1 parent c1046dc commit 165afd3
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
1 change: 1 addition & 0 deletions 036/.gitignore
@@ -0,0 +1 @@
data
45 changes: 45 additions & 0 deletions 036/cache.py
@@ -0,0 +1,45 @@
from collections import defaultdict
from datetime import datetime
import pickle
from random import choice

CACHE = 'data'
NAMES = ('bob', 'julian', 'martin', 'dante', 'snake')
TIMES = range(15, 61, 15)


def gen_random_entry():
while True:
yield datetime.now(), choice(NAMES), choice(TIMES)


class Cache:

def __enter__(self):
try:
self.cache = pickle.load(open(CACHE, "rb"))
except FileNotFoundError:
self.cache = defaultdict(list)
return self.cache

def __exit__(self, exc_type, exc_val, exc_tb):
pickle.dump(self.cache, open(CACHE, "wb"))


if __name__ == '__main__':
it = gen_random_entry()

with Cache() as wl:
for i in range(5):
d, n, t = next(it)
wl[n].append((d, t))

print('Cached work so far')
print('(this will grow each time program is run)')
print()
col1, col2 = ('NAME', 'MINUTES')
print('{:<10}: {}'.format(col1, col2))
with Cache() as wl:
for name, work in sorted(wl.items()):
total = sum(w[1] for w in work) # TODO: use namedtuple
print('{:<10}: {}'.format(name, total))
2 changes: 1 addition & 1 deletion LOG.md
Expand Up @@ -37,7 +37,7 @@
| 033 | May 01, 2017 | [I need to drink more water at work so I wrote a #Python #script to remind (spam) me every hour](033) | A simple script using MIME and a cron job (read the readme.txt) to remind me to drink more water at work! Doesn't email on the weekends or before/after hours. Over the top? Maybe. Satisfying? Hell yes. |
| 034 | May 02, 2017 | [Import a #podcast feed into a DB table with #SQLAlchemy](034) | Part of the this week's code challenge solution. Found it useful enough to extract this bit as separate nudget |
| 035 | May 03, 2017 | [TITLE](035) | LEARNING |
| 036 | May 04, 2017 | [TITLE](036) | LEARNING |
| 036 | May 04, 2017 | [Use #Python #pickle to store and retrieve a defaultdict](036) | Nice and easy persistence tool. Using it with context manager to write random log entries. Each time the script is run the data pickle file gets updates. To get random entries I used a generator. |
| 037 | May 05, 2017 | [TITLE](037) | LEARNING |
| 038 | May 06, 2017 | [TITLE](038) | LEARNING |
| 039 | May 07, 2017 | [TITLE](039) | LEARNING |
Expand Down

0 comments on commit 165afd3

Please sign in to comment.