z_friday-notes.html


001| ####################################################################################################
002| from sys import argv
003| from os import path
004| from datetime import date,datetime
005| import matplotlib.pyplot as plt
006| from matplotlib.ticker import NullLocator, MultipleLocator, NullFormatter, FormatStrFormatter
007| from goodies import NumberStats
008| from files import tabfile
009| from wordpress import dbPostsTable
010| ####################################################################################################
011| BasePath = r'C:\CJS\prj\Python\blog\lcc'
012| HtmlPath = r'C:\CJS\www\root\cjs\blog\lcc'
013| 
014| Adds = []
015| 
016| 
017| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
018| class myPostsTable (dbPostsTable):
019|     dbName = 'logosconcarne.sqlite'
020|     dbPath = HtmlPath
021|     xmlName = 'logosconcarne.xml'
022|     xmlPath = HtmlPath
023| 
024| ##------------------------------------------------------------------------------------------------##
025| SQL = '''\
025| SELECT post_date,post_title
025| FROM "%s"
025| WHERE (post_type='post')
025|     AND (post_status='publish')
025|     AND (
025|         (post_title LIKE 'Friday Notes%%') OR
025|         (post_title LIKE 'Science Notes%%') OR
025|         (post_title = 'Pi Day Friday')
025|     )
025| ORDER BY post_date DESC
025| '''

026| 
027| ##================================================================================================##
028| def get_data_from_database ():
029|     '''Get a list of sorted Friday Notes dates from sqlite DB.'''
030| 
031|     # Get post data...
032|     tbl = myPostsTable()
033|     rs = tbl.db_query(SQL % tbl.name)
034|     if not rs:
035|         print('No data!')
036|         return 'No records'
037| 
038|     print('Records Found: %d' % len(rs))
039|     print()
040| 
041|     # List the records found...
042|     for rcd in rs:
043|         print(rcd)
044|     print()
045| 
046|     # Get a list of days...
047|     dts = [datetime.fromisoformat(rcd[0]).day for rcd in rs]
048|     dts.extend(Adds)
049| 
050|     # Return sorted list...
051|     return list(sorted(dts))
052| 
053| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
054| LCC = 1
055| HCC = 2
056| Sub = 3
057| xref = {'LCC':LCC, 'HCC':HCC, 'Sub':Sub}
058| 
059| class Posts:
060|     '''All the Blogs, All the Posts!'''
061|     filename = r"C:\CJS\prj\Python\blog\posts.tab"
062| 
063|     def __init__ (self):
064|         '''New Posts instance.'''
065|         self.posts = []
066|         self.years = {}
067|         self.months = {}
068|         self.total = 0
069|         # Load the list-of-posts data file...
070|         self.fobj = tabfile(self.filename, headers=True)
071|         self.fobj.load()
072| 
073|         # Process the file data...
074|         for post in self.fobj:
075|             # If the first field is empty, skip the line...
076|             if len(post[0]) == 0:
077|                 continue
078|             # Ignore comment lines (start with ";" or "#")...
079|             if post[0].startswith(';') or post[0].startswith('#'):
080|                 continue
081| 
082|             # Translate the tag field...
083|             tag = xref[post[0]]
084|             # Translate the data field...
085|             dt = datetime(int(post[1]), int(post[2]), int(post[3]))
086|             # Get the name field...
087|             name = post[4]
088|             pid = int(post[5])
089|             url = post[6]
090|             self.posts.append((tag,dt,name,pid,url))
091|             self.total += 1
092| 
093|             # Update years and months counters...
094|             if dt.year not in self.years: self.years[dt.year] = 0
095|             self.years[dt.year] += 1
096| 
097|             key = (dt.year,dt.month)
098|             if key not in self.months: self.months[key] = 0
099|             self.months[key] += 1
100| 
101|     def __iter__(self): return iter(self.posts)
102|     def __len__(self): return len(self.posts)
103|     def __getitem__(self, ix): return self.posts[ix]
104| 
105|     def __repr__ (self):
106|         return f'<{typename(self)} @{id(self):012x}>'
107| 
108|     def __str__ (self):
109|         return f'{path.basename(self.filename)} ({len(self)} posts)'
110| 
111|     @property
112|     def total_posts (self):
113|         return self.total
114| 
115| ##================================================================================================##
116| def get_data_from_posts_csv ():
117|     '''Get a list of sorted Friday Notes dates from Posts.CSV file.'''
118| 
119|     def only_friday_notes (post):
120|         '''Filter function.'''
121| 
122|         # Has to be WP LCC blog...
123|         if post[0] != LCC: return False
124|         # Looking for Friday Notes posts...
125|         if post[2].startswith('Friday Notes'): return True
126|         # Or for Science Notes posts...
127|         if post[2].startswith('Science Notes'): return True
128|         # Or for Science Notes posts...
129|         if post[2].startswith('Weather Notes'): return True
130|         # Or for that Pi Day Friday post...
131|         if post[2] == 'Pi Day Friday': return True
132|         # Nope...
133|         return False
134| 
135|     # Get the posts...
136|     ps = Posts()
137| 
138|     # Extract Friday Notes posts...
139|     ps = list(filter(only_friday_notes, ps))
140| 
141|     print('Records Found: %d' % len(ps))
142|     print()
143| 
144|     # List the records found...
145|     for p in reversed(ps):
146|         print(f'{p[1]} {p[2]}')
147|     print()
148| 
149|     # Get a list of days...
150|     dts = [p[1].day for p in ps]
151|     dts.extend(Adds)
152| 
153|     # Return sorted list...
154|     return list(sorted(dts))
155| 
156| 
157| ##================================================================================================##
158| def create_graph (xs:list, ys:list, cs:list) -> None:
159|     '''Create histogram graph. (PNG)'''
160| 
161|     fig, ax = plt.subplots()
162|     fig.suptitle('Friday Notes Month Day Histogram', fontsize=13, fontweight='bold')
163|     fig.set_figwidth(4.4)
164|     fig.set_figheight(2.0)
165|     fig.subplots_adjust(left=0.10, right=0.99, bottom=0.23, top=0.88)
166| 
167|     ax.set_xlabel('Day of the Month', fontsize=11)
168|     ax.set_xlim(0.5, 31.5)
169|     ax.xaxis.set_major_locator(MultipleLocator(5))
170|     ax.xaxis.set_minor_locator(MultipleLocator(1))
171|     ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))
172|     ax.xaxis.set_minor_formatter(NullFormatter())
173| 
174|     ax.set_ylabel('Number of Posts', fontsize=11)
175|     ax.set_ylim(0,6)
176|     ax.yaxis.set_major_locator(MultipleLocator(1))
177|     ax.yaxis.set_minor_locator(NullLocator())
178|     ax.yaxis.set_major_formatter(FormatStrFormatter('%d'))
179|     ax.yaxis.set_minor_formatter(NullFormatter())
180| 
181|     ax.grid(which='major', axis='both', color='#7f7f7f', lw=1.2,ls='-',zorder=1, alpha=1.0)
182|     ax.grid(which='minor', axis='both', color='#bfbfbf', lw=0.6,ls='-',zorder=0, alpha=1.0)
183|     ax.tick_params(which='major', axis='both', direction='out', color='#000000')
184|     ax.tick_params(which='minor', axis='both', direction='out', color='#000000')
185| 
186|     ax.bar(xs,ys, width=0.75, color=cs, alpha=0.75, zorder=11)
187|     #ax.legend()
188| 
189|     fn = path.join(BasePath, 'Friday Notes DotM histogram.png')
190|     fig.savefig(fn)
191|     print('wrote: %s' % fn)
192|     print()
193| 
194| 
195| ##================================================================================================##
196| def friday_notes ():
197| 
198|     #dts = get_data_from_database()
199|     dts = get_data_from_posts_csv()
200| 
201|     ns = NumberStats(dts)
202| 
203|     def calc_median (ns):
204|         length = len(ns)
205|         center = int(length/2)
206|         # Odd...
207|         if length % 1:
208|             return float(ns[center])
209|         # Even...
210|         a = ns[center-1]
211|         b = ns[center]
212|         return (a+b)/2
213| 
214|     print(dts)
215|     print()
216|     print(f'Friday Notes Days ({ns.count}):')
217|     print(f'first-dotm: {ns.minimum}')
218|     print(f'last-dotm: {ns.maximum}')
219|     print(f'mean-dotm: {ns.average}')
220|     print(f'median-dotm: {calc_median(dts)}')
221|     print()
222| 
223|     hist = {}
224|     for d in dts:
225|         if d not in hist: hist[d] = 0
226|         hist[d] += 1
227| 
228|     for d in sorted(hist):
229|         print(f'{d:2d}: {hist[d]}')
230|     print()
231| 
232|     def determine_bar_color (dt):
233|         '''Get bar color for given DOTM.'''
234|         if dt == 13: return '#ff0000'
235|         if dt in Adds: return '#00af3f'
236|         return '#3366cc'
237| 
238|     xs = list(sorted(hist))
239|     ys = [hist[x] for x in xs]
240|     cs = [determine_bar_color(x) for x in xs]
241|     create_graph (xs, ys, cs)
242| 
243|     return (ns, dts, xs,ys,cs)
244| 
245| 
246| ####################################################################################################
247| if __name__ == '__main__':
248|     print(argv[0])
249|     print()
250|     ns,dts,xs,ys,cs = friday_notes()
251|     print()
252| ####################################################################################################
253| '''eof'''
254|