-
Notifications
You must be signed in to change notification settings - Fork 3
/
worklog.py
1323 lines (994 loc) · 36.1 KB
/
worklog.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- mode: python ; coding: utf-8 -*-
# Copyright 2014-2017 Peter Williams <peter@newton.cx>
# Licensed under the GNU General Public License, version 3 or higher.
"""
Shared routines for my worklog tools.
"""
from __future__ import absolute_import, division, print_function
from six import string_types, text_type
from six.moves import map, range, zip
__all__ = str(
"""
nbsp
months
Holder
die
warn
open_template
slurp_template
process_template
list_data_files
load
unicode_to_latex
html_escape
Markup
MupText
MupItalics
MupBold
MupUnderline
MupLink
MupJoin
MupList
render_latex
render_html
Formatter
ADSCountError
parse_ads_cites
canonicalize_name
surname
best_url
cite_info
compute_cite_stats
partition_pubs
setup_processing
get_ads_cite_count
bootstrap_bibtex"""
).split()
nbsp = "\u00a0"
months = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()
# Infrastructure
from inifile import Holder
def die(fmt, *args):
if len(args):
text = fmt % args
else:
text = str(fmt)
raise SystemExit("error: " + text)
def warn(fmt, *args):
if len(args):
text = fmt % args
else:
text = str(fmt)
import sys
print("warning:", text, file=sys.stderr)
def open_template(stem):
from os.path import join, dirname
from errno import ENOENT
try:
return open(join("templates", stem))
except IOError as e:
if e.errno != ENOENT:
raise
try:
return open(join(dirname(__file__), "templates", stem))
except Exception as e:
die('cannot open template "%s": %s (%s)', stem, e, e.__class__.__name__)
def slurp_template(stem):
with open_template(stem) as f:
return f.read().decode("utf8")
class MultilineHandler(object):
def handle_line(self, context, line):
raise NotImplementedError()
def handle_end_span(self, context):
raise NotImplementedError()
def process_template(stream, commands, context):
"""Read through a template line-by-line and replace special lines. Each
regular line is yielded to the caller. `commands` is a dictionary of
strings to callables; if the first word in a line is in `commands`, the
callable is invoked, with `context` and the remaining words in the line as
arguments. Its return value is either a string or an iterable, with each
iterate being yielded to the caller in the latter case."""
current_multiline_handler = None
for line in stream:
line = line.decode("utf8").rstrip()
if current_multiline_handler is not None:
if line != "END":
current_multiline_handler.handle_line(context, line)
else:
result = current_multiline_handler.handle_end_span(context)
if isinstance(result, string_types):
yield result
else:
for subline in result:
yield subline
current_multiline_handler = None
else:
a = line.split()
if not len(a) or a[0] not in commands:
yield line
else:
result = commands[a[0]](context, *a[1:])
if isinstance(result, string_types):
yield result
elif isinstance(result, MultilineHandler):
current_multiline_handler = result
else:
for subline in result:
yield subline
def list_data_files(datadir="."):
from os import listdir
from os.path import join
any = False
for item in sorted(listdir(datadir)):
if item.startswith("."):
continue
if not item.endswith(".txt"):
continue
# Note that if there are text files that contain no records (e.g. all
# commented), we won't complain.
any = True
yield join(datadir, item)
if not any:
die('no data files found in directory "%s"', datadir)
def load(datadir="."):
from inifile import read as iniread
for path in list_data_files(datadir):
for item in iniread(path):
yield item
# Text formatting. We have a tiny DOM-type system for markup so we can
# abstract across LaTeX and HTML. Initially I tried to do everything in HTML,
# and then convert that to LaTeX, but the layers of escaping got a little
# worrisome, and some constructs just don't work well in that model (e.g.
# tables). So we do this silliness instead.
from unicode_to_latex import unicode_to_latex, unicode_to_latex_string
def html_escape(text):
"""Escape special characters for our dumb subset of HTML."""
return (
text_type(text)
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace('"', """)
.replace("'", "'")
)
class Markup(object):
def _latex(self):
raise NotImplementedError()
def _html(self):
raise NotImplementedError()
def latex(self):
return "".join(self._latex())
def html(self):
return "".join(self._html())
def _maybe_wrap_text(thing):
if isinstance(thing, Markup):
return thing
return MupText(thing)
class MupText(Markup):
def __init__(self, text):
self.text = text_type(text)
def _latex(self):
return [unicode_to_latex_string(self.text)]
def _html(self):
return [html_escape(self.text)]
class MupItalics(Markup):
def __init__(self, inner):
self.inner = _maybe_wrap_text(inner)
def _latex(self):
return ["\\textit{"] + self.inner._latex() + ["}"]
def _html(self):
return ["<i>"] + self.inner._html() + ["</i>"]
class MupBold(Markup):
def __init__(self, inner):
self.inner = _maybe_wrap_text(inner)
def _latex(self):
return ["\\textbf{"] + self.inner._latex() + ["}"]
def _html(self):
return ["<b>"] + self.inner._html() + ["</b>"]
class MupUnderline(Markup):
def __init__(self, inner):
self.inner = _maybe_wrap_text(inner)
def _latex(self):
return ["\\underline{"] + self.inner._latex() + ["}"]
def _html(self):
return ["<u>"] + self.inner._html() + ["</u>"]
class MupLink(Markup):
def __init__(self, url, inner):
self.url = str(url)
self.inner = _maybe_wrap_text(inner)
def _latex(self):
return (
["\\href{", self.url.replace("%", "\\%"), "}{"]
+ self.inner._latex()
+ ["}"]
)
def _html(self):
return (
['<a href="', html_escape(self.url), '">'] + self.inner._html() + ["</a>"]
)
class MupJoin(Markup):
def __init__(self, sep, items):
self.sep = _maybe_wrap_text(sep)
self.items = [_maybe_wrap_text(i) for i in items]
def _latex(self):
esep = self.sep._latex()
result = []
first = True
for i in self.items:
if first:
first = False
else:
result += esep
result += i._latex()
return result
def _html(self):
esep = self.sep._html()
result = []
first = True
for i in self.items:
if first:
first = False
else:
result += esep
result += i._html()
return result
class MupList(Markup):
def __init__(self, ordered, items):
self.ordered = bool(ordered)
self.items = [_maybe_wrap_text(i) for i in items]
def _latex(self):
if self.ordered:
res = ["\\begin{enumerate}"]
else:
res = ["\\begin{itemize}"]
for i in self.items:
res.append("\n\\item ")
res += i._latex()
if self.ordered:
res.append("\n\\end{enumerate}\n")
else:
res.append("\n\\end{itemize}\n")
return res
def _html(self):
if self.ordered:
res = ["<ol>"]
else:
res = ["<ul>"]
for i in self.items:
res.append("\n<li>")
res += i._html()
res.append("</li>")
if self.ordered:
res.append("\n</ol>\n")
else:
res.append("\n</ul>\n")
return res
def render_latex(value):
if isinstance(value, int):
return str(value)
if isinstance(value, text_type):
return unicode_to_latex_string(value)
if isinstance(value, string_types):
return unicode_to_latex_string(text_type(value))
if isinstance(value, Markup):
return value.latex()
raise ValueError("don't know how to render %r into latex" % value)
def render_html(value):
if isinstance(value, int):
return str(value)
if isinstance(value, text_type):
return html_escape(value)
if isinstance(value, string_types):
return html_escape(text_type(value))
if isinstance(value, Markup):
return value.html()
raise ValueError("don't know how to render %r into HTML" % value)
class Formatter(object):
"""Substituted items are delimited by pipes |likethis|. This works well in
both HTML and Latex. If `israw`, the non-substituted template text is
returned verbatim; otherwise, it is escaped.
We have a special hack. If the substituted item is specified as
|texturl:foo|, the key "foo" will be looked in `item` and output as a link
whose text value is the same as its URL: i.e.
<a href="http://...">http://...</a>
This particular tactic is needed to work with textual URLs in LaTeX, since
the \\url{} and \\href{} commands redefine character codes such that the
standard LaTeX escaping mechanism is inappropriate. In particular, URLs
with tildes were breaking.
"""
def __init__(self, renderer, israw, text):
from re import split
pieces = split(r"(\|[^|]+\|)", text)
def process(piece):
if len(piece) and piece[0] == "|":
return True, piece[1:-1]
return False, piece
self.tmplinfo = [process(p) for p in pieces]
self.renderer = renderer
self.israw = israw
def _handle_one(self, tmpldata, item):
issubst, text = tmpldata
if not issubst:
if self.israw:
return text
return self.renderer(text)
try:
if text.startswith("texturl:"):
thing = item.get(text[8:])
thing = MupLink(thing, thing)
else:
thing = item.get(text)
return self.renderer(thing)
except ValueError as e:
raise ValueError(
('while rendering field "%s" of item %s: %s' % (text, item, e)).encode(
"utf-8"
)
)
def __call__(self, item):
return "".join(self._handle_one(d, item) for d in self.tmplinfo)
# Utilities for dealing with publications.
def parse_ads_cites(pub):
from time import mktime
if not pub.has("adscites"):
return None
try:
a = pub.adscites.split()[:2]
y, m, d = [int(x) for x in a[0].split("/")]
lastupdate = int(mktime((y, m, d, 0, 0, 0, 0, 0, 0)))
cites = int(a[1])
except Exception:
warn('cannot parse adscites entry "%s"', pub.adscites)
return None
return Holder(lastupdate=lastupdate, cites=cites)
def canonicalize_name(name):
"""Convert a name into "canonical" form, by which I mean something like "PKG
Williams". The returned string uses a nonbreaking space between the two
pieces.
I handle spaces in surnames by replacing them with underscores. Hopefully
none of my coauthors will ever have an underscore in their names.
TODO: handle "Surname, First Middle" etc.
TODO: also Russian initials: Yu. G. Levin
"""
bits = name.strip().split()
surname = bits[-1].replace("_", " ")
rest = bits[:-1]
abbrev = []
for item in rest:
for char in item:
if char.isupper() or char == "-":
abbrev.append(char)
return "".join(abbrev) + nbsp + surname
def surname(name):
return name.strip().split()[-1].replace("_", " ")
def best_url(item):
try:
from urllib.parse import quote
except ImportError:
from urllib2 import quote
if item.has("bibcode"):
return "http://adsabs.harvard.edu/abs/" + quote(item.bibcode)
if item.has("doi"):
return "http://dx.doi.org/" + quote(item.doi)
if item.has("url"):
return item.url
if item.has("arxiv"):
return "http://arxiv.org/abs/" + quote(item.arxiv)
return None
def cite_info(oitem, context):
"""Create a Holder with citation text from a publication item. This can then
be fed into a template however one wants. The various computed fields are
are Unicode or Markups.
`oitem` = original item; not to be modified
`aitem` = augmented item; = oitem + new fields
"""
aitem = oitem.copy()
# Canonicalized authors with bolding of self and underlining of advisees.
cauths = [canonicalize_name(a) for a in oitem.authors.split(";")]
mypos = int(oitem.mypos)
if mypos < 0:
myidx = len(cauths) + mypos
elif mypos == 0:
die("illegal mypos value %r" % (oitem.mypos,))
else:
myidx = mypos - 1
cauths[myidx] = MupBold(cauths[myidx])
advposlist = oitem.get("advpos", "")
if len(advposlist):
for i in [int(x) - 1 for x in advposlist.split(",")]:
cauths[i] = MupUnderline(cauths[i])
aitem.full_authors = MupJoin(", ", cauths)
# Short list of authors, possibly abbreviating my name.
sauths = [surname(a) for a in oitem.authors.split(";")]
if context.my_abbrev_name is not None:
sauths[myidx] = context.my_abbrev_name
if len(advposlist):
for i in [int(x) - 1 for x in advposlist.split(",")]:
sauths[i] = MupUnderline(sauths[i])
if len(sauths) == 1:
aitem.short_authors = sauths[0]
elif len(sauths) == 2:
aitem.short_authors = MupJoin(" & ", sauths)
elif len(sauths) == 3:
aitem.short_authors = MupJoin(", ", sauths)
else:
aitem.short_authors = MupJoin(" ", [sauths[0], "et" + nbsp + "al."])
if oitem.refereed == "y":
aitem.refereed_mark = "»"
else:
aitem.refereed_mark = ""
# Title with replaced quotes, for nesting in double-quotes, and
# optionally-bolded for first authorship.
aitem.quotable_title = oitem.title.replace("“", "‘").replace("”", "’")
if myidx == 0:
aitem.bold_if_first_title = MupBold(oitem.title)
else:
aitem.bold_if_first_title = oitem.title
# Pub year and nicely-formatted date
aitem.year, aitem.month = list(map(int, oitem.pubdate.split("/")))
aitem.pubdate = "%d%s%s" % (aitem.year, nbsp, months[aitem.month - 1])
# Template-friendly citation count
citeinfo = parse_ads_cites(oitem)
if citeinfo is not None and citeinfo.cites > 0:
aitem.citecountnote = " [%d]" % citeinfo.cites
else:
aitem.citecountnote = ""
# Citation text with link
url = best_url(oitem)
if url is None:
aitem.lcite = aitem.cite
else:
aitem.lcite = MupLink(url, aitem.cite)
# Other links for the web pub list, individually and as an <ul>
try:
from urllib.parse import quote as urlquote
except ImportError:
from urllib2 import quote as urlquote
aitem.abstract_link = ""
aitem.preprint_link = ""
aitem.official_link = ""
aitem.other_link = ""
link_items = []
if oitem.has("bibcode"):
aitem.abstract_link = MupLink(
"http://adsabs.harvard.edu/abs/" + urlquote(oitem.bibcode), "abstract"
)
link_items.append(aitem.abstract_link)
if oitem.has("arxiv"):
aitem.preprint_link = MupLink(
"http://arxiv.org/abs/" + urlquote(oitem.arxiv), "preprint"
)
link_items.append(aitem.preprint_link)
if oitem.has("doi"):
aitem.official_link = MupLink(
"http://dx.doi.org/" + urlquote(oitem.doi), "official"
)
link_items.append(aitem.official_link)
if oitem.has("url") and not oitem.has("doi"):
aitem.other_link = MupLink(oitem.url, oitem.kind)
link_items.append(aitem.other_link)
aitem.links_list = MupList(False, link_items)
return aitem
def compute_cite_stats(pubs):
"""Compute an h-index and other stats from the known publications."""
from time import gmtime
stats = Holder()
stats.refpubs = 0
stats.refcites = 0
stats.reffirstauth = 0
cites = []
dates = []
for pub in pubs:
if pub.refereed == "y":
stats.refpubs += 1
if int(pub.mypos) == 1:
stats.reffirstauth += 1
citeinfo = parse_ads_cites(pub)
if citeinfo is None:
continue
if citeinfo.cites < 1:
continue
cites.append(citeinfo.cites)
dates.append(citeinfo.lastupdate)
if pub.refereed == "y":
stats.refcites += citeinfo.cites
if not len(cites):
stats.meddate = 0
stats.hindex = 0
else:
ranked = sorted(cites, reverse=True)
index = 0
while index < len(ranked) and ranked[index] >= index + 1:
index += 1
dates = sorted(dates)
stats.meddate = dates[len(dates) // 2]
stats.hindex = index
stats.year, stats.month, stats.day = gmtime(stats.meddate)[:3]
stats.monthstr = months[stats.month - 1]
stats.italich = MupItalics("h")
stats.adslink = MupLink("http://labs.adsabs.harvard.edu/adsabs", "ADS")
return stats
def partition_pubs(pubs):
groups = Holder()
groups.all = []
groups.refereed = []
groups.refpreprint = []
groups.non_refereed = []
groups.all_formal = []
groups.all_non_refereed = []
groups.informal = []
groups.chapters = []
for pub in pubs:
refereed = pub.refereed == "y"
refpreprint = pub.get("refpreprint", "n") == "y"
chapter = pub.get("kind", "default") == "book chapter"
formal = pub.get("informal", "n") == "n"
# we assume refereed implies formal.
groups.all.append(pub)
if formal:
groups.all_formal.append(pub)
if refereed:
groups.refereed.append(pub)
elif refpreprint:
groups.refpreprint.append(pub)
elif chapter:
groups.chapters.append(pub)
else:
groups.all_non_refereed.append(pub)
if formal:
groups.non_refereed.append(pub)
else:
groups.informal.append(pub)
groups.all_rev = groups.all[::-1]
groups.chapters_rev = groups.chapters[::-1]
groups.refereed_rev = groups.refereed[::-1]
groups.refpreprint_rev = groups.refpreprint[::-1]
groups.non_refereed_rev = groups.non_refereed[::-1]
groups.informal_rev = groups.informal[::-1]
return groups
# Utilities for dealing with allocated observing time. Namely, we total up the
# time allocated for each telescope as PI.
def compute_time_allocations(props):
allocs = {}
def get_contributions(prop):
amount = prop.get("award")
if amount is None:
amount = prop.get("request")
if amount is None:
die('no "award" or "request" for proposal %s', prop)
try:
facil1 = prop.facil
quantity1, units1 = amount.split()
quantity1 = float(quantity1)
except Exception as e:
die("error processing primary outcome of proposal <%s>: %s", prop, e)
yield facil1, quantity1, units1
i = 2
while True:
amount = prop.get("award%d" % i)
if amount is None:
amount = prop.get("request%d" % i)
if amount is None:
break
try:
quantity, units, facil = amount.split(None, 2)
quantity = float(quantity)
except Exception as e:
die("error processing outcome #%d of proposal <%s>: %s", i, prop, e)
yield facil, quantity, units
i += 1
for prop in props:
if prop.get("mepi", "n") != "y":
continue # self as PI only
if prop.get("accepted", "n") != "y":
continue # only accepted ones!
for facil, quantity, units in get_contributions(prop):
if facil not in allocs:
allocs[facil] = (quantity, units)
else:
q0, u0 = allocs[facil]
if u0 != units:
die(
'disagreeing time units for %s: both "%s" and "%s"',
facil,
u0,
units,
)
allocs[facil] = (q0 + quantity, u0)
# Implement the hack for putting support funding last and in italics. For
# some allocations we have fractional precision (e.g., right now I've been
# awarded 244.64 ks on Chandra), but the float formatting is annoying to
# get to work universally, so just round everything off.
def process(facil_text, info):
quantity, unit = info
is_summary = facil_text.startswith("SUMMARY:")
if is_summary:
facil = MupItalics(facil_text[8:])
else:
facil = facil_text
return Holder(
is_summary=is_summary,
facil=facil,
total="%.0f" % quantity,
unit=unit,
)
return sorted(
(process(k, v) for (k, v) in allocs.items()),
key=lambda h: (h.is_summary, h.facil),
)
# Utilities for dealing with public code repositories
def process_repositories(items):
try:
from urllib.parse import quote as urlquote
except ImportError:
from urllib2 import quote as urlquote
repos = []
for i in items:
if i.section != "repo":
continue
if i.get("skip", "n") == "y":
continue
if i.usercommits == "0":
continue
repo = i.copy()
repos.append(repo)
if i.service == "github":
repo.linkname = MupLink("https://github.com/" + urlquote(i.name), i.name)
else:
repo.linkname = i.name
repo.commit_frac = "%.0f%%" % (100.0 * int(i.usercommits) / int(i.allcommits))
if repo.commit_frac == "0%":
repo.commit_frac = "<1%"
repo.luc_year, repo.luc_month, repo.luc_day = [
int(x) for x in i.lastusercommit.split("/")
]
repo.date = "%04d %s" % (repo.luc_year, months[repo.luc_month - 1])
repo._datekey = repo.luc_year * 10000 + repo.luc_month * 100 + repo.luc_day
return sorted(repos, key=lambda r: r._datekey)
def compute_repo_stats(repos):
info = {}
info["total_repos"] = len(repos)
tc = 0
pa_stars = 0
pa_forks = 0
for repo in repos:
tc += int(repo.usercommits)
if 2 * int(repo.usercommits) > int(
repo.allcommits
): # >=50% of commits ("primary author")?
pa_stars += int(repo.get("stars", "0"))
pa_forks += int(repo.get("forks", "0"))
info["total_commits"] = tc
info["primary_author_stars"] = pa_stars
info["primary_author_forks"] = pa_forks
return info
# (Professional) Talks
def summarize_talks(talks):
info = {}
info["n_total"] = len(talks)
info["n_invited"] = len([t for t in talks if t.get("invited", "n") == "y"])
info["n_conference"] = len([t for t in talks if t.get("conference", "n") == "y"])
return info
# Public engagement
def summarize_engagement(items):
info = {}
count = lambda c: len([i for i in items if i.get("class", "?") == c])
info["n_interviews"] = count("interview")
info["n_outreach_events"] = count("outreach_event")
info["n_press_releases"] = count("press_release")
info["n_public_talks"] = count("public_talk")
return info
# Commands for templates
class MultilineSubstHandler(MultilineHandler):
def __init__(self, info):
self.info = info
self.lines = []
def handle_line(self, context, line):
self.lines.append(line)
def handle_end_span(self, context):
tmpl = "\n".join(self.lines)
return Formatter(context.render, True, tmpl)(self.info)
def cmd_begin_subst(context, group):
try:
info = getattr(context, group)
except AttributeError:
die('no such substitution group "%s" for BEGIN_SUBST command', group)
return MultilineSubstHandler(info)
def cmd_format(context, *inline_template):
inline_template = " ".join(inline_template)
context.cur_formatter = Formatter(context.render, True, inline_template)
return ""
def cmd_my_abbrev_name(context, *text):
context.my_abbrev_name = " ".join(text)
return ""
def cmd_pub_list(context, group):
if context.cur_formatter is None:
die("cannot use PUBLIST command before using FORMAT")
pubs = context.pubgroups.get(group)
npubs = len(pubs)
for num, pub in enumerate(pubs):
info = cite_info(pub, context)
info.number = num + 1
info.rev_number = npubs - num
yield context.cur_formatter(info)
def cmd_talloc_list(context):
if context.cur_formatter is None:
die("cannot use TALLOCLIST command before using FORMAT")
for info in context.time_allocs:
yield context.cur_formatter(info)
def cmd_split_talloc_list(context, *split_template):
if context.cur_formatter is None:
die("cannot use SPLIT_TALLOCLIST command before using FORMAT")
split_template = " ".join(split_template)
alloc_info = list(context.time_allocs)
n = len(alloc_info)
for info in alloc_info[: (n + 1) // 2]:
yield context.cur_formatter(info)
yield split_template
for info in alloc_info[(n + 1) // 2 :]:
yield context.cur_formatter(info)
def _rev_misc_list(context, sections, gate):
if context.cur_formatter is None:
die("cannot use RMISCLIST* command before using FORMAT")
sections = frozenset(sections.split(","))
for item in context.items[::-1]:
if item.section not in sections:
continue
if not gate(item):
continue
yield context.cur_formatter(item)
def cmd_rev_misc_list(context, sections):
return _rev_misc_list(context, sections, lambda i: True)
def cmd_rev_misc_list_if(context, sections, gatefield):
"""Same a RMISCLIST, but only shows items where a certain item
is True. XXX: this kind of approach could get out of hand
quickly."""
return _rev_misc_list(context, sections, lambda i: i.get(gatefield, "n") == "y")
def cmd_rev_misc_list_if_not(context, sections, gatefield):
return _rev_misc_list(context, sections, lambda i: i.get(gatefield, "n") != "y")