id
int64
0
843k
repository_name
stringlengths
7
55
file_path
stringlengths
9
332
class_name
stringlengths
3
290
human_written_code
stringlengths
12
4.36M
class_skeleton
stringlengths
19
2.2M
total_program_units
int64
1
9.57k
total_doc_str
int64
0
4.2k
AvgCountLine
float64
0
7.89k
AvgCountLineBlank
float64
0
300
AvgCountLineCode
float64
0
7.89k
AvgCountLineComment
float64
0
7.89k
AvgCyclomatic
float64
0
130
CommentToCodeRatio
float64
0
176
CountClassBase
float64
0
48
CountClassCoupled
float64
0
589
CountClassCoupledModified
float64
0
581
CountClassDerived
float64
0
5.37k
CountDeclInstanceMethod
float64
0
4.2k
CountDeclInstanceVariable
float64
0
299
CountDeclMethod
float64
0
4.2k
CountDeclMethodAll
float64
0
4.2k
CountLine
float64
1
115k
CountLineBlank
float64
0
9.01k
CountLineCode
float64
0
94.4k
CountLineCodeDecl
float64
0
46.1k
CountLineCodeExe
float64
0
91.3k
CountLineComment
float64
0
27k
CountStmt
float64
1
93.2k
CountStmtDecl
float64
0
46.1k
CountStmtExe
float64
0
90.2k
MaxCyclomatic
float64
0
759
MaxInheritanceTree
float64
0
16
MaxNesting
float64
0
34
SumCyclomatic
float64
0
6k
143,748
Kozea/pygal
Kozea_pygal/pygal/graph/horizontal.py
pygal.graph.horizontal.HorizontalGraph
class HorizontalGraph(Graph): """Horizontal graph mixin""" def __init__(self, *args, **kwargs): """Set the horizontal flag to True""" self.horizontal = True super(HorizontalGraph, self).__init__(*args, **kwargs) def _post_compute(self): """After computations transpose labels""" self._x_labels, self._y_labels = self._y_labels, self._x_labels self._x_labels_major, self._y_labels_major = ( self._y_labels_major, self._x_labels_major ) self._x_2nd_labels, self._y_2nd_labels = ( self._y_2nd_labels, self._x_2nd_labels ) self.show_y_guides, self.show_x_guides = ( self.show_x_guides, self.show_y_guides ) def _axes(self): """Set the _force_vertical flag when rendering axes""" self.view._force_vertical = True super(HorizontalGraph, self)._axes() self.view._force_vertical = False def _set_view(self): """Assign a horizontal view to current graph""" if self.logarithmic: view_class = HorizontalLogView else: view_class = HorizontalView self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._box ) def _get_x_label(self, i): """Convenience function to get the x_label of a value index""" if not self.x_labels or not self._y_labels or len(self._y_labels) <= i: return return self._y_labels[i][0]
class HorizontalGraph(Graph): '''Horizontal graph mixin''' def __init__(self, *args, **kwargs): '''Set the horizontal flag to True''' pass def _post_compute(self): '''After computations transpose labels''' pass def _axes(self): '''Set the _force_vertical flag when rendering axes''' pass def _set_view(self): '''Assign a horizontal view to current graph''' pass def _get_x_label(self, i): '''Convenience function to get the x_label of a value index''' pass
6
6
7
0
6
1
1
0.19
1
3
2
6
5
10
5
74
44
6
32
13
26
6
22
13
16
2
4
1
7
143,749
Kozea/pygal
Kozea_pygal/pygal/graph/horizontalbar.py
pygal.graph.horizontalbar.HorizontalBar
class HorizontalBar(HorizontalGraph, Bar): """Horizontal Bar graph""" def _plot(self): """Draw the bars in reverse order""" for serie in self.series[::-1]: self.bar(serie) for serie in self.secondary_series[::-1]: self.bar(serie, True)
class HorizontalBar(HorizontalGraph, Bar): '''Horizontal Bar graph''' def _plot(self): '''Draw the bars in reverse order''' pass
2
2
6
0
5
1
3
0.33
2
0
0
0
1
0
1
80
9
1
6
3
4
2
6
3
4
3
5
1
3
143,750
Kozea/pygal
Kozea_pygal/pygal/graph/histogram.py
pygal.graph.histogram.Histogram
class Histogram(Dual, Bar): """Histogram chart class""" _series_margin = 0 @cached_property def _values(self): """Getter for secondary series values (flattened)""" return self.yvals @cached_property def _secondary_values(self): """Getter for secondary series values (flattened)""" return [ val[0] for serie in self.secondary_series for val in serie.values if val[0] is not None ] @cached_property def xvals(self): """All x values""" return [ val for serie in self.all_series for dval in serie.values for val in dval[1:3] if val is not None ] @cached_property def yvals(self): """All y values""" return [ val[0] for serie in self.series for val in serie.values if val[0] is not None ] def _bar(self, serie, parent, x0, x1, y, i, zero, secondary=False): """Internal bar drawing function""" x, y = self.view((x0, y)) x1, _ = self.view((x1, y)) width = x1 - x height = self.view.y(zero) - y series_margin = width * self._series_margin x += series_margin width -= 2 * series_margin r = serie.rounded_bars * 1 if serie.rounded_bars else 0 alter( self.svg.transposable_node( parent, 'rect', x=x, y=y, rx=r, ry=r, width=width, height=height, class_='rect reactive tooltip-trigger' ), serie.metadata.get(i) ) return x, y, width, height def bar(self, serie, rescale=False): """Draw a bar graph for a serie""" serie_node = self.svg.serie(serie) bars = self.svg.node(serie_node['plot'], class_="histbars") points = serie.points for i, (y, x0, x1) in enumerate(points): if None in (x0, x1, y) or (self.logarithmic and y <= 0): continue metadata = serie.metadata.get(i) bar = decorate( self.svg, self.svg.node(bars, class_='histbar'), metadata ) val = self._format(serie, i) bounds = self._bar( serie, bar, x0, x1, y, i, self.zero, secondary=rescale ) self._tooltip_and_print_values( serie_node, serie, bar, i, val, metadata, *bounds ) def _compute(self): """Compute x/y min and max and x/y scale and set labels""" if self.xvals: xmin = min(self.xvals) xmax = max(self.xvals) xrng = (xmax - xmin) else: xrng = None if self.yvals: ymin = min(min(self.yvals), self.zero) ymax = max(max(self.yvals), self.zero) yrng = (ymax - ymin) else: yrng = None for serie in self.all_series: serie.points = serie.values if xrng: self._box.xmin, self._box.xmax = xmin, xmax if yrng: self._box.ymin, self._box.ymax = ymin, ymax if self.range and self.range[0] is not None: self._box.ymin = self.range[0] if self.range and self.range[1] is not None: self._box.ymax = self.range[1]
class Histogram(Dual, Bar): '''Histogram chart class''' @cached_property def _values(self): '''Getter for secondary series values (flattened)''' pass @cached_property def _secondary_values(self): '''Getter for secondary series values (flattened)''' pass @cached_property def xvals(self): '''All x values''' pass @cached_property def yvals(self): '''All y values''' pass def _bar(self, serie, parent, x0, x1, y, i, zero, secondary=False): '''Internal bar drawing function''' pass def bar(self, serie, rescale=False): '''Draw a bar graph for a serie''' pass def _compute(self): '''Compute x/y min and max and x/y scale and set labels''' pass
12
8
14
1
12
1
2
0.09
2
1
0
0
7
2
7
85
111
16
87
39
75
8
54
30
46
8
5
2
17
143,751
Kozea/pygal
Kozea_pygal/pygal/graph/graph.py
pygal.graph.graph.Graph
class Graph(PublicApi): """Graph super class containing generic common functions""" _dual = False def _decorate(self): """Draw all decorations""" self._set_view() self._make_graph() self._axes() self._legend() self._make_title() self._make_x_title() self._make_y_title() def _axes(self): """Draw axes""" self._y_axis() self._x_axis() def _set_view(self): """Assign a view to current graph""" if self.logarithmic: if self._dual: view_class = XYLogView else: view_class = LogView else: view_class = ReverseView if self.inverse_y_axis else View self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._box ) def _make_graph(self): """Init common graph svg structure""" self.nodes['graph'] = self.svg.node( class_='graph %s-graph %s' % ( self.__class__.__name__.lower(), 'horizontal' if self.horizontal else 'vertical' ) ) self.svg.node( self.nodes['graph'], 'rect', class_='background', x=0, y=0, width=self.width, height=self.height ) self.nodes['plot'] = self.svg.node( self.nodes['graph'], class_="plot", transform="translate(%d, %d)" % (self.margin_box.left, self.margin_box.top) ) self.svg.node( self.nodes['plot'], 'rect', class_='background', x=0, y=0, width=self.view.width, height=self.view.height ) self.nodes['title'] = self.svg.node( self.nodes['graph'], class_="titles" ) self.nodes['overlay'] = self.svg.node( self.nodes['graph'], class_="plot overlay", transform="translate(%d, %d)" % (self.margin_box.left, self.margin_box.top) ) self.nodes['text_overlay'] = self.svg.node( self.nodes['graph'], class_="plot text-overlay", transform="translate(%d, %d)" % (self.margin_box.left, self.margin_box.top) ) self.nodes['tooltip_overlay'] = self.svg.node( self.nodes['graph'], class_="plot tooltip-overlay", transform="translate(%d, %d)" % (self.margin_box.left, self.margin_box.top) ) self.nodes['tooltip'] = self.svg.node( self.nodes['tooltip_overlay'], transform='translate(0 0)', style="opacity: 0", **{'class': 'tooltip'} ) self.svg.node( self.nodes['tooltip'], 'rect', rx=self.tooltip_border_radius, ry=self.tooltip_border_radius, width=0, height=0, **{'class': 'tooltip-box'} ) self.svg.node(self.nodes['tooltip'], 'g', class_='text') def _x_axis(self): """Make the x axis: labels and guides""" if not self._x_labels or not self.show_x_labels: return axis = self.svg.node( self.nodes['plot'], class_="axis x%s" % (' always_show' if self.show_x_guides else '') ) truncation = self.truncate_label if not truncation: if self.x_label_rotation or len(self._x_labels) <= 1: truncation = 25 else: first_label_position = self.view.x(self._x_labels[0][1]) or 0 last_label_position = self.view.x(self._x_labels[-1][1]) or 0 available_space = (last_label_position - first_label_position ) / len(self._x_labels) - 1 truncation = reverse_text_len( available_space, self.style.label_font_size ) truncation = max(truncation, 1) lastlabel = self._x_labels[-1][0] if 0 not in [label[1] for label in self._x_labels]: self.svg.node( axis, 'path', d='M%f %f v%f' % (0, 0, self.view.height), class_='line' ) lastlabel = None for label, position in self._x_labels: if self.horizontal: major = position in self._x_labels_major else: major = label in self._x_labels_major if not (self.show_minor_x_labels or major): continue guides = self.svg.node(axis, class_='guides') x = self.view.x(position) if x is None: continue y = self.view.height + 5 last_guide = (self._y_2nd_labels and label == lastlabel) self.svg.node( guides, 'path', d='M%f %f v%f' % (x or 0, 0, self.view.height), class_='%s%s%sline' % ( 'axis ' if label == "0" else '', 'major ' if major else '', 'guide ' if position != 0 and not last_guide else '' ) ) y += .5 * self.style.label_font_size + 5 text = self.svg.node( guides, 'text', x=x, y=y, class_='major' if major else '' ) text.text = truncate(label, truncation) if text.text != label: self.svg.node(guides, 'title').text = label elif self._dual: self.svg.node( guides, 'title', ).text = self._x_format(position) if self.x_label_rotation: text.attrib['transform'] = "rotate(%d %f %f)" % ( self.x_label_rotation, x, y ) if self.x_label_rotation >= 180: text.attrib['class'] = ' '.join(( text.attrib['class'] and text.attrib['class'].split(' ') or [] ) + ['backwards']) if self._y_2nd_labels and 0 not in [label[1] for label in self._x_labels]: self.svg.node( axis, 'path', d='M%f %f v%f' % (self.view.width, 0, self.view.height), class_='line' ) if self._x_2nd_labels: secondary_ax = self.svg.node( self.nodes['plot'], class_="axis x x2%s" % (' always_show' if self.show_x_guides else '') ) for label, position in self._x_2nd_labels: major = label in self._x_labels_major if not (self.show_minor_x_labels or major): continue # it is needed, to have the same structure as primary axis guides = self.svg.node(secondary_ax, class_='guides') x = self.view.x(position) y = -5 text = self.svg.node( guides, 'text', x=x, y=y, class_='major' if major else '' ) text.text = label if self.x_label_rotation: text.attrib['transform'] = "rotate(%d %f %f)" % ( -self.x_label_rotation, x, y ) if self.x_label_rotation >= 180: text.attrib['class'] = ' '.join(( text.attrib['class'] and text.attrib['class'].split(' ') or [] ) + ['backwards']) def _y_axis(self): """Make the y axis: labels and guides""" if not self._y_labels or not self.show_y_labels: return axis = self.svg.node( self.nodes['plot'], class_="axis y%s" % (' always_show' if self.show_y_guides else '') ) if (0 not in [label[1] for label in self._y_labels] and self.show_y_guides): self.svg.node( axis, 'path', d='M%f %f h%f' % ( 0, 0 if self.inverse_y_axis else self.view.height, self.view.width ), class_='line' ) for label, position in self._y_labels: if self.horizontal: major = label in self._y_labels_major else: major = position in self._y_labels_major if not (self.show_minor_y_labels or major): continue guides = self.svg.node( axis, class_='%sguides' % ('logarithmic ' if self.logarithmic else '') ) x = -5 y = self.view.y(position) if not y: continue if self.show_y_guides: self.svg.node( guides, 'path', d='M%f %f h%f' % (0, y, self.view.width), class_='%s%s%sline' % ( 'axis ' if label == "0" else '', 'major ' if major else '', 'guide ' if position != 0 else '' ) ) text = self.svg.node( guides, 'text', x=x, y=y + .35 * self.style.label_font_size, class_='major' if major else '' ) text.text = label if self.y_label_rotation: text.attrib['transform'] = "rotate(%d %f %f)" % ( self.y_label_rotation, x, y ) if 90 < self.y_label_rotation < 270: text.attrib['class'] = ' '.join(( text.attrib['class'] and text.attrib['class'].split(' ') or [] ) + ['backwards']) self.svg.node( guides, 'title', ).text = self._y_format(position) if self._y_2nd_labels: secondary_ax = self.svg.node(self.nodes['plot'], class_="axis y2") for label, position in self._y_2nd_labels: major = position in self._y_labels_major if not (self.show_minor_y_labels or major): continue # it is needed, to have the same structure as primary axis guides = self.svg.node(secondary_ax, class_='guides') x = self.view.width + 5 y = self.view.y(position) text = self.svg.node( guides, 'text', x=x, y=y + .35 * self.style.label_font_size, class_='major' if major else '' ) text.text = label if self.y_label_rotation: text.attrib['transform'] = "rotate(%d %f %f)" % ( self.y_label_rotation, x, y ) if 90 < self.y_label_rotation < 270: text.attrib['class'] = ' '.join(( text.attrib['class'] and text.attrib['class'].split(' ') or [] ) + ['backwards']) def _legend(self): """Make the legend box""" if not self.show_legend: return truncation = self.truncate_legend if self.legend_at_bottom: x = self.margin_box.left + self.spacing y = ( self.margin_box.top + self.view.height + self._x_title_height + self._x_labels_height + self.spacing ) cols = self.legend_at_bottom_columns or ceil(sqrt(self._order) ) or 1 if not truncation: available_space = self.view.width / cols - ( self.legend_box_size + 5 ) truncation = reverse_text_len( available_space, self.style.legend_font_size ) else: x = self.spacing y = self.margin_box.top + self.spacing cols = 1 if not truncation: truncation = 15 legends = self.svg.node( self.nodes['graph'], class_='legends', transform='translate(%d, %d)' % (x, y) ) h = max(self.legend_box_size, self.style.legend_font_size) x_step = self.view.width / cols if self.legend_at_bottom: secondary_legends = legends # svg node is the same else: # draw secondary axis on right x = self.margin_box.left + self.view.width + self.spacing if self._y_2nd_labels: h, w = get_texts_box( cut(self._y_2nd_labels), self.style.label_font_size ) x += self.spacing + max( w * abs(cos(rad(self.y_label_rotation))), h ) y = self.margin_box.top + self.spacing secondary_legends = self.svg.node( self.nodes['graph'], class_='legends', transform='translate(%d, %d)' % (x, y) ) serie_number = -1 i = 0 for titles, is_secondary in ((self._legends, False), (self._secondary_legends, True)): if not self.legend_at_bottom and is_secondary: i = 0 for title in titles: serie_number += 1 if title is None: continue col = i % cols row = i // cols legend = self.svg.node( secondary_legends if is_secondary else legends, class_='legend reactive activate-serie', id="activate-serie-%d" % serie_number ) self.svg.node( legend, 'rect', x=col * x_step, y=1.5 * row * h + ( self.style.legend_font_size - self.legend_box_size if self.style.legend_font_size > self.legend_box_size else 0 ) / 2, width=self.legend_box_size, height=self.legend_box_size, class_="color-%d reactive" % serie_number ) if isinstance(title, dict): node = decorate(self.svg, legend, title) title = title['title'] else: node = legend truncated = truncate(title, truncation) self.svg.node( node, 'text', x=col * x_step + self.legend_box_size + 5, y=1.5 * row * h + .5 * h + .3 * self.style.legend_font_size ).text = truncated if truncated != title: self.svg.node(legend, 'title').text = title i += 1 def _make_title(self): """Make the title""" if self._title: for i, title_line in enumerate(self._title, 1): self.svg.node( self.nodes['title'], 'text', class_='title plot_title', x=self.width / 2, y=i * (self.style.title_font_size + self.spacing) ).text = title_line def _make_x_title(self): """Make the X-Axis title""" y = (self.height - self.margin_box.bottom + self._x_labels_height) if self._x_title: for i, title_line in enumerate(self._x_title, 1): text = self.svg.node( self.nodes['title'], 'text', class_='title', x=self.margin_box.left + self.view.width / 2, y=y + i * (self.style.title_font_size + self.spacing) ) text.text = title_line def _make_y_title(self): """Make the Y-Axis title""" if self._y_title: yc = self.margin_box.top + self.view.height / 2 for i, title_line in enumerate(self._y_title, 1): text = self.svg.node( self.nodes['title'], 'text', class_='title', x=self._legend_at_left_width, y=i * (self.style.title_font_size + self.spacing) + yc ) text.attrib['transform'] = "rotate(%d %f %f)" % ( -90, self._legend_at_left_width, yc ) text.text = title_line def _interpolate(self, xs, ys): """Make the interpolation""" x = [] y = [] for i in range(len(ys)): if ys[i] is not None: x.append(xs[i]) y.append(ys[i]) interpolate = INTERPOLATIONS[self.interpolate] return list( interpolate( x, y, self.interpolation_precision, **self.interpolation_parameters ) ) def _rescale(self, points): """Scale for secondary""" return [( x, self._scale_diff + (y - self._scale_min_2nd) * self._scale if y is not None else None ) for x, y in points] def _tooltip_data(self, node, value, x, y, classes=None, xlabel=None): """Insert in desc tags informations for the javascript tooltip""" self.svg.node(node, 'desc', class_="value").text = value if classes is None: classes = [] if x > self.view.width / 2: classes.append('left') if y > self.view.height / 2: classes.append('top') classes = ' '.join(classes) self.svg.node(node, 'desc', class_="x " + classes).text = str(x) self.svg.node(node, 'desc', class_="y " + classes).text = str(y) if xlabel: self.svg.node(node, 'desc', class_="x_label").text = str(xlabel) def _static_value( self, serie_node, value, x, y, metadata, align_text='left', classes=None ): """Write the print value""" label = metadata and metadata.get('label') classes = classes and [classes] or [] if self.print_labels and label: label_cls = classes + ['label'] if self.print_values: y -= self.style.value_font_size / 2 self.svg.node( serie_node['text_overlay'], 'text', class_=' '.join(label_cls), x=x, y=y + self.style.value_font_size / 3 ).text = label y += self.style.value_font_size if self.print_values or self.dynamic_print_values: val_cls = classes + ['value'] if self.dynamic_print_values: val_cls.append('showable') self.svg.node( serie_node['text_overlay'], 'text', class_=' '.join(val_cls), x=x, y=y + self.style.value_font_size / 3, attrib={ 'text-anchor': align_text } ).text = value if self.print_zeroes or value != '0' else '' def _points(self, x_pos): """ Convert given data values into drawable points (x, y) and interpolated points if interpolate option is specified """ for serie in self.all_series: serie.points = [(x_pos[i], v) for i, v in enumerate(serie.values)] if serie.points and self.interpolate: serie.interpolated = self._interpolate(x_pos, serie.values) else: serie.interpolated = [] def _compute_secondary(self): """Compute secondary axis min max and label positions""" # secondary y axis support if self.secondary_series and self._y_labels: y_pos = list(zip(*self._y_labels))[1] if self.include_x_axis: ymin = min(self._secondary_min, 0) ymax = max(self._secondary_max, 0) else: ymin = self._secondary_min ymax = self._secondary_max steps = len(y_pos) left_range = abs(y_pos[-1] - y_pos[0]) right_range = abs(ymax - ymin) or 1 scale = right_range / ((steps - 1) or 1) self._y_2nd_labels = [(self._y_format(ymin + i * scale), pos) for i, pos in enumerate(y_pos)] self._scale = left_range / right_range self._scale_diff = y_pos[0] self._scale_min_2nd = ymin def _post_compute(self): """Hook called after compute and before margin computations and plot""" pass def _get_x_label(self, i): """Convenience function to get the x_label of a value index""" if not self.x_labels or not self._x_labels or len(self._x_labels) <= i: return return self._x_labels[i][0] @property def all_series(self): """Getter for all series (nomal and secondary)""" return self.series + self.secondary_series @property def _x_format(self): """Return the abscissa value formatter (always unary)""" return self.x_value_formatter @property def _default_formatter(self): return str @property def _y_format(self): """Return the ordinate value formatter (always unary)""" return self.value_formatter def _value_format(self, value): """ Format value for value display. (Varies in type between chart types) """ return self._y_format(value) def _format(self, serie, i): """Format the nth value for the serie""" value = serie.values[i] metadata = serie.metadata.get(i) kwargs = {'chart': self, 'serie': serie, 'index': i} formatter = ((metadata and metadata.get('formatter')) or serie.formatter or self.formatter or self._value_format) kwargs = filter_kwargs(formatter, kwargs) return formatter(value, **kwargs) def _serie_format(self, serie, value): """Format an independent value for the serie""" kwargs = {'chart': self, 'serie': serie, 'index': None} formatter = (serie.formatter or self.formatter or self._value_format) kwargs = filter_kwargs(formatter, kwargs) return formatter(value, **kwargs) def _compute(self): """Initial computations to draw the graph""" def _compute_margin(self): """Compute graph margins from set texts""" self._legend_at_left_width = 0 for series_group in (self.series, self.secondary_series): if self.show_legend and series_group: h, w = get_texts_box( map( lambda x: truncate(x, self.truncate_legend or 15), [ serie.title['title'] if isinstance(serie.title, dict) else serie.title or '' for serie in series_group ] ), self.style.legend_font_size ) if self.legend_at_bottom: h_max = max(h, self.legend_box_size) cols = ( self._order // self.legend_at_bottom_columns if self.legend_at_bottom_columns else ceil(sqrt(self._order)) or 1 ) self.margin_box.bottom += self.spacing + h_max * round( cols - 1 ) * 1.5 + h_max else: if series_group is self.series: legend_width = self.spacing + w + self.legend_box_size self.margin_box.left += legend_width self._legend_at_left_width += legend_width else: self.margin_box.right += ( self.spacing + w + self.legend_box_size ) self._x_labels_height = 0 if (self._x_labels or self._x_2nd_labels) and self.show_x_labels: for xlabels in (self._x_labels, self._x_2nd_labels): if xlabels: h, w = get_texts_box( map( lambda x: truncate(x, self.truncate_label or 25), cut(xlabels) ), self.style.label_font_size ) self._x_labels_height = self.spacing + max( w * abs(sin(rad(self.x_label_rotation))), h ) if xlabels is self._x_labels: self.margin_box.bottom += self._x_labels_height else: self.margin_box.top += self._x_labels_height if self.x_label_rotation: if self.x_label_rotation % 180 < 90: self.margin_box.right = max( w * abs(cos(rad(self.x_label_rotation))), self.margin_box.right ) else: self.margin_box.left = max( w * abs(cos(rad(self.x_label_rotation))), self.margin_box.left ) if self.show_y_labels: for ylabels in (self._y_labels, self._y_2nd_labels): if ylabels: h, w = get_texts_box( cut(ylabels), self.style.label_font_size ) if ylabels is self._y_labels: self.margin_box.left += self.spacing + max( w * abs(cos(rad(self.y_label_rotation))), h ) else: self.margin_box.right += self.spacing + max( w * abs(cos(rad(self.y_label_rotation))), h ) self._title = split_title( self.title, self.width, self.style.title_font_size ) if self.title: h, _ = get_text_box(self._title[0], self.style.title_font_size) self.margin_box.top += len(self._title) * (self.spacing + h) self._x_title = split_title( self.x_title, self.width - self.margin_box.x, self.style.title_font_size ) self._x_title_height = 0 if self._x_title: h, _ = get_text_box(self._x_title[0], self.style.title_font_size) height = len(self._x_title) * (self.spacing + h) self.margin_box.bottom += height self._x_title_height = height + self.spacing self._y_title = split_title( self.y_title, self.height - self.margin_box.y, self.style.title_font_size ) self._y_title_height = 0 if self._y_title: h, _ = get_text_box(self._y_title[0], self.style.title_font_size) height = len(self._y_title) * (self.spacing + h) self.margin_box.left += height self._y_title_height = height + self.spacing # Inner margin if self.print_values_position == 'top': gh = self.height - self.margin_box.y alpha = 1.1 * (self.style.value_font_size / gh) * self._box.height if self._max and self._max > 0: self._box.ymax += alpha if self._min and self._min < 0: self._box.ymin -= alpha def _confidence_interval(self, node, x, y, value, metadata): if not metadata or 'ci' not in metadata: return ci = metadata['ci'] ci['point_estimate'] = value low, high = getattr( stats, 'confidence_interval_%s' % ci.get('type', 'manual') )(**ci) self.svg.confidence_interval( node, x, # Respect some charts y modifications (pyramid, stackbar) y + (self.view.y(low) - self.view.y(value)), y + (self.view.y(high) - self.view.y(value)) ) @cached_property def _legends(self): """Getter for series title""" return [serie.title for serie in self.series] @cached_property def _secondary_legends(self): """Getter for series title on secondary y axis""" return [serie.title for serie in self.secondary_series] @cached_property def _values(self): """Getter for series values (flattened)""" return [ val for serie in self.series for val in serie.values if val is not None ] @cached_property def _secondary_values(self): """Getter for secondary series values (flattened)""" return [ val for serie in self.secondary_series for val in serie.values if val is not None ] @cached_property def _len(self): """Getter for the maximum series size""" return max([len(serie.values) for serie in self.all_series] or [0]) @cached_property def _secondary_min(self): """Getter for the minimum series value""" return ( self.secondary_range[0] if (self.secondary_range and self.secondary_range[0] is not None) else (min(self._secondary_values) if self._secondary_values else None) ) @cached_property def _min(self): """Getter for the minimum series value""" return ( self.range[0] if (self.range and self.range[0] is not None) else (min(self._values) if self._values else None) ) @cached_property def _max(self): """Getter for the maximum series value""" return ( self.range[1] if (self.range and self.range[1] is not None) else (max(self._values) if self._values else None) ) @cached_property def _secondary_max(self): """Getter for the maximum series value""" return ( self.secondary_range[1] if (self.secondary_range and self.secondary_range[1] is not None) else (max(self._secondary_values) if self._secondary_values else None) ) @cached_property def _order(self): """Getter for the number of series""" return len(self.all_series) def _x_label_format_if_value(self, label): if not isinstance(label, str): return self._x_format(label) return label def _compute_x_labels(self): self._x_labels = self.x_labels and list( zip( map(self._x_label_format_if_value, self.x_labels), self._x_pos ) ) def _compute_x_labels_major(self): if self.x_labels_major_every: self._x_labels_major = [ self._x_labels[i][0] for i in range(0, len(self._x_labels), self.x_labels_major_every) ] elif self.x_labels_major_count: label_count = len(self._x_labels) major_count = self.x_labels_major_count if (major_count >= label_count): self._x_labels_major = [label[0] for label in self._x_labels] else: self._x_labels_major = [ self._x_labels[int( i * (label_count - 1) / (major_count - 1) )][0] for i in range(major_count) ] else: self._x_labels_major = self.x_labels_major and list( map(self._x_label_format_if_value, self.x_labels_major) ) or [] def _compute_y_labels(self): y_pos = compute_scale( self._box.ymin, self._box.ymax, self.logarithmic, self.order_min, self.min_scale, self.max_scale ) if self.y_labels: self._y_labels = [] for i, y_label in enumerate(self.y_labels): if isinstance(y_label, dict): pos = self._adapt(y_label.get('value')) title = y_label.get('label', self._y_format(pos)) elif isinstance(y_label, str): pos = self._adapt(y_pos[i % len(y_pos)]) title = y_label else: pos = self._adapt(y_label) title = self._y_format(pos) self._y_labels.append((title, pos)) self._box.ymin = min(self._box.ymin, min(cut(self._y_labels, 1))) self._box.ymax = max(self._box.ymax, max(cut(self._y_labels, 1))) else: self._y_labels = list(zip(map(self._y_format, y_pos), y_pos)) def _compute_y_labels_major(self): if self.y_labels_major_every: self._y_labels_major = [ self._y_labels[i][1] for i in range(0, len(self._y_labels), self.y_labels_major_every) ] elif self.y_labels_major_count: label_count = len(self._y_labels) major_count = self.y_labels_major_count if (major_count >= label_count): self._y_labels_major = [label[1] for label in self._y_labels] else: self._y_labels_major = [ self._y_labels[int( i * (label_count - 1) / (major_count - 1) )][1] for i in range(major_count) ] elif self.y_labels_major: self._y_labels_major = list(map(self._adapt, self.y_labels_major)) elif self._y_labels: self._y_labels_major = majorize(cut(self._y_labels, 1)) else: self._y_labels_major = [] def add_squares(self, squares): x_lines = squares[0] - 1 y_lines = squares[1] - 1 _current_x = 0 _current_y = 0 for line in range(x_lines): _current_x += (self.width - self.margin_box.x) / squares[0] self.svg.node( self.nodes['plot'], 'path', class_='bg-lines', d='M%s %s L%s %s' % (_current_x, 0, _current_x, self.height - self.margin_box.y) ) for line in range(y_lines): _current_y += (self.height - self.margin_box.y) / squares[1] self.svg.node( self.nodes['plot'], 'path', class_='bg-lines', d='M%s %s L%s %s' % (0, _current_y, self.width - self.margin_box.x, _current_y) ) return ((self.width - self.margin_box.x) / squares[0], (self.height - self.margin_box.y) / squares[1]) def _draw(self): """Draw all the things""" self._compute() self._compute_x_labels() self._compute_x_labels_major() self._compute_y_labels() self._compute_y_labels_major() self._compute_secondary() self._post_compute() self._compute_margin() self._decorate() if self.series and self._has_data() and self._values: self._plot() else: self.svg.draw_no_data() def _has_data(self): """Check if there is any data""" return any([ len([ v for a in (s[0] if is_list_like(s) else [s]) for v in (a if is_list_like(a) else [a]) if v is not None ]) for s in self.raw_series ])
class Graph(PublicApi): '''Graph super class containing generic common functions''' def _decorate(self): '''Draw all decorations''' pass def _axes(self): '''Draw axes''' pass def _set_view(self): '''Assign a view to current graph''' pass def _make_graph(self): '''Init common graph svg structure''' pass def _x_axis(self): '''Make the x axis: labels and guides''' pass def _y_axis(self): '''Make the y axis: labels and guides''' pass def _legend(self): '''Make the legend box''' pass def _make_title(self): '''Make the title''' pass def _make_x_title(self): '''Make the X-Axis title''' pass def _make_y_title(self): '''Make the Y-Axis title''' pass def _interpolate(self, xs, ys): '''Make the interpolation''' pass def _rescale(self, points): '''Scale for secondary''' pass def _tooltip_data(self, node, value, x, y, classes=None, xlabel=None): '''Insert in desc tags informations for the javascript tooltip''' pass def _static_value( self, serie_node, value, x, y, metadata, align_text='left', classes=None ): '''Write the print value''' pass def _points(self, x_pos): ''' Convert given data values into drawable points (x, y) and interpolated points if interpolate option is specified ''' pass def _compute_secondary(self): '''Compute secondary axis min max and label positions''' pass def _post_compute(self): '''Hook called after compute and before margin computations and plot''' pass def _get_x_label(self, i): '''Convenience function to get the x_label of a value index''' pass @property def all_series(self): '''Getter for all series (nomal and secondary)''' pass @property def _x_format(self): '''Return the abscissa value formatter (always unary)''' pass @property def _default_formatter(self): pass @property def _y_format(self): '''Return the ordinate value formatter (always unary)''' pass def _value_format(self, value): ''' Format value for value display. (Varies in type between chart types) ''' pass def _format(self, serie, i): '''Format the nth value for the serie''' pass def _serie_format(self, serie, value): '''Format an independent value for the serie''' pass def _compute_secondary(self): '''Initial computations to draw the graph''' pass def _compute_margin(self): '''Compute graph margins from set texts''' pass def _confidence_interval(self, node, x, y, value, metadata): pass @cached_property def _legends(self): '''Getter for series title''' pass @cached_property def _secondary_legends(self): '''Getter for series title on secondary y axis''' pass @cached_property def _values(self): '''Getter for series values (flattened)''' pass @cached_property def _secondary_values(self): '''Getter for secondary series values (flattened)''' pass @cached_property def _len(self): '''Getter for the maximum series size''' pass @cached_property def _secondary_min(self): '''Getter for the minimum series value''' pass @cached_property def _min(self): '''Getter for the minimum series value''' pass @cached_property def _max(self): '''Getter for the maximum series value''' pass @cached_property def _secondary_max(self): '''Getter for the maximum series value''' pass @cached_property def _order(self): '''Getter for the number of series''' pass def _x_label_format_if_value(self, label): pass def _compute_x_labels(self): pass def _compute_x_labels_major(self): pass def _compute_y_labels(self): pass def _compute_y_labels_major(self): pass def add_squares(self, squares): pass def _draw(self): '''Draw all the things''' pass def _has_data(self): '''Check if there is any data''' pass
61
39
20
1
18
1
4
0.06
1
12
4
12
46
20
46
69
1,003
105
847
190
777
52
440
159
393
26
3
5
183
143,752
Kozea/pygal
Kozea_pygal/pygal/graph/gauge.py
pygal.graph.gauge.Gauge
class Gauge(Graph): """Gauge graph class""" needle_width = 1 / 20 def _set_view(self): """Assign a view to current graph""" if self.logarithmic: view_class = PolarThetaLogView else: view_class = PolarThetaView self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._box ) def needle(self, serie): """Draw a needle for each value""" serie_node = self.svg.serie(serie) for i, theta in enumerate(serie.values): if theta is None: continue def point(x, y): return '%f %f' % self.view((x, y)) val = self._format(serie, i) metadata = serie.metadata.get(i) gauges = decorate( self.svg, self.svg.node(serie_node['plot'], class_="dots"), metadata ) tolerance = 1.15 if theta < self._min: theta = self._min * tolerance if theta > self._max: theta = self._max * tolerance w = (self._box._tmax - self._box._tmin + self.view.aperture) / 4 if self.logarithmic: w = min(w, self._min - self._min * 10**-10) alter( self.svg.node( gauges, 'path', d='M %s L %s A %s 1 0 1 %s Z' % ( point(.85, theta), point(self.needle_width, theta - w), '%f %f' % (self.needle_width, self.needle_width), point(self.needle_width, theta + w), ), class_='line reactive tooltip-trigger' ), metadata ) x, y = self.view((.75, theta)) self._tooltip_data(gauges, val, x, y, xlabel=self._get_x_label(i)) self._static_value(serie_node, val, x, y, metadata) def _y_axis(self, draw_axes=True): """Override y axis to plot a polar axis""" axis = self.svg.node(self.nodes['plot'], class_="axis x gauge") for i, (label, theta) in enumerate(self._y_labels): guides = self.svg.node(axis, class_='guides') self.svg.line( guides, [self.view((.95, theta)), self.view((1, theta))], close=True, class_='line' ) self.svg.line( guides, [self.view((0, theta)), self.view((.95, theta))], close=True, class_='guide line %s' % ('major' if i in (0, len(self._y_labels) - 1) else '') ) x, y = self.view((.9, theta)) self.svg.node(guides, 'text', x=x, y=y).text = label self.svg.node( guides, 'title', ).text = self._y_format(theta) def _x_axis(self, draw_axes=True): """Override x axis to put a center circle in center""" axis = self.svg.node(self.nodes['plot'], class_="axis y gauge") x, y = self.view((0, 0)) self.svg.node(axis, 'circle', cx=x, cy=y, r=4) def _compute(self): """Compute y min and max and y scale and set labels""" self.min_ = self._min or 0 self.max_ = self._max or 0 if self.max_ - self.min_ == 0: self.min_ -= 1 self.max_ += 1 self._box.set_polar_box(0, 1, self.min_, self.max_) def _compute_x_labels(self): pass def _compute_y_labels(self): y_pos = compute_scale( self.min_, self.max_, self.logarithmic, self.order_min, self.min_scale, self.max_scale ) if self.y_labels: self._y_labels = [] for i, y_label in enumerate(self.y_labels): if isinstance(y_label, dict): pos = self._adapt(y_label.get('value')) title = y_label.get('label', self._y_format(pos)) elif isinstance(y_label, str): pos = self._adapt(y_pos[i]) title = y_label else: pos = self._adapt(y_label) title = self._y_format(pos) self._y_labels.append((title, pos)) self.min_ = min(self.min_, min(cut(self._y_labels, 1))) self.max_ = max(self.max_, max(cut(self._y_labels, 1))) self._box.set_polar_box(0, 1, self.min_, self.max_) else: self._y_labels = list(zip(map(self._y_format, y_pos), y_pos)) def _plot(self): """Plot all needles""" for serie in self.series: self.needle(serie)
class Gauge(Graph): '''Gauge graph class''' def _set_view(self): '''Assign a view to current graph''' pass def needle(self, serie): '''Draw a needle for each value''' pass def point(x, y): pass def _y_axis(self, draw_axes=True): '''Override y axis to plot a polar axis''' pass def _x_axis(self, draw_axes=True): '''Override x axis to put a center circle in center''' pass def _compute(self): '''Compute y min and max and y scale and set labels''' pass def _compute_x_labels(self): pass def _compute_y_labels(self): pass def _plot(self): '''Plot all needles''' pass
10
7
15
2
12
1
3
0.06
1
8
2
0
8
5
8
77
142
25
110
36
100
7
71
35
61
6
4
3
23
143,753
Kozea/pygal
Kozea_pygal/pygal/graph/funnel.py
pygal.graph.funnel.Funnel
class Funnel(Graph): """Funnel graph class""" _adapters = [positive, none_to_zero] def _value_format(self, value): """Format value for dual value display.""" return super(Funnel, self)._value_format(value and abs(value)) def funnel(self, serie): """Draw a funnel slice""" serie_node = self.svg.serie(serie) fmt = lambda x: '%f %f' % x for i, poly in enumerate(serie.points): metadata = serie.metadata.get(i) val = self._format(serie, i) funnels = decorate( self.svg, self.svg.node(serie_node['plot'], class_="funnels"), metadata ) alter( self.svg.node( funnels, 'polygon', points=' '.join(map(fmt, map(self.view, poly))), class_='funnel reactive tooltip-trigger' ), metadata ) # Poly center from label x, y = self.view(( self._center(self._x_pos[serie.index]), sum([point[1] for point in poly]) / len(poly) )) self._tooltip_data( funnels, val, x, y, 'centered', self._get_x_label(serie.index) ) self._static_value(serie_node, val, x, y, metadata) def _center(self, x): return x - 1 / (2 * self._order) def _compute(self): """Compute y min and max and y scale and set labels""" self._x_pos = [ (x + 1) / self._order for x in range(self._order) ] if self._order != 1 else [.5] # Center if only one value previous = [[self.zero, self.zero] for i in range(self._len)] for i, serie in enumerate(self.series): y_height = -sum(serie.safe_values) / 2 all_x_pos = [0] + self._x_pos serie.points = [] for j, value in enumerate(serie.values): poly = [] poly.append((all_x_pos[i], previous[j][0])) poly.append((all_x_pos[i], previous[j][1])) previous[j][0] = y_height y_height = previous[j][1] = y_height + value poly.append((all_x_pos[i + 1], previous[j][1])) poly.append((all_x_pos[i + 1], previous[j][0])) serie.points.append(poly) val_max = max(list(map(sum, cut(self.series, 'values'))) + [self.zero]) self._box.ymin = -val_max self._box.ymax = val_max if self.range and self.range[0] is not None: self._box.ymin = self.range[0] if self.range and self.range[1] is not None: self._box.ymax = self.range[1] def _compute_x_labels(self): self._x_labels = list( zip( self.x_labels and map(self._x_format, self.x_labels) or [ serie.title['title'] if isinstance(serie.title, dict) else serie.title or '' for serie in self.series ], map(self._center, self._x_pos) ) ) def _plot(self): """Plot the funnel""" for serie in self.series: self.funnel(serie)
class Funnel(Graph): '''Funnel graph class''' def _value_format(self, value): '''Format value for dual value display.''' pass def funnel(self, serie): '''Draw a funnel slice''' pass def _center(self, x): pass def _compute(self): '''Compute y min and max and y scale and set labels''' pass def _compute_x_labels(self): pass def _plot(self): '''Plot the funnel''' pass
7
5
13
1
11
1
2
0.1
1
7
0
0
6
4
6
75
90
14
70
27
63
7
45
25
38
6
4
2
14
143,754
Kozea/pygal
Kozea_pygal/pygal/graph/horizontalline.py
pygal.graph.horizontalline.HorizontalLine
class HorizontalLine(HorizontalGraph, Line): """Horizontal Line graph""" def _plot(self): """Draw the lines in reverse order""" for serie in self.series[::-1]: self.line(serie) for serie in self.secondary_series[::-1]: self.line(serie, True)
class HorizontalLine(HorizontalGraph, Line): '''Horizontal Line graph''' def _plot(self): '''Draw the lines in reverse order''' pass
2
2
6
0
5
1
3
0.33
2
0
0
0
1
0
1
82
9
1
6
3
4
2
6
3
4
3
5
1
3
143,755
Kozea/pygal
Kozea_pygal/pygal/graph/dual.py
pygal.graph.dual.Dual
class Dual(Graph): _dual = True def _value_format(self, value): """ Format value for dual value display. """ return '%s: %s' % (self._x_format(value[0]), self._y_format(value[1])) def _compute_x_labels(self): x_pos = compute_scale( self._box.xmin, self._box.xmax, self.logarithmic, self.order_min, self.min_scale, self.max_scale ) if self.x_labels: self._x_labels = [] for i, x_label in enumerate(self.x_labels): if isinstance(x_label, dict): pos = self._x_adapt(x_label.get('value')) title = x_label.get('label', self._x_format(pos)) elif isinstance(x_label, str): pos = self._x_adapt(x_pos[i % len(x_pos)]) title = x_label else: pos = self._x_adapt(x_label) title = self._x_format(pos) self._x_labels.append((title, pos)) self._box.xmin = min(self._box.xmin, min(cut(self._x_labels, 1))) self._box.xmax = max(self._box.xmax, max(cut(self._x_labels, 1))) else: self._x_labels = list(zip(map(self._x_format, x_pos), x_pos)) def _compute_x_labels_major(self): # In case of dual, x labels must adapters and so majors too self.x_labels_major = self.x_labels_major and list( map(self._x_adapt, self.x_labels_major) ) super(Dual, self)._compute_x_labels_major() def _get_x_label(self, i): """Convenience function to get the x_label of a value index""" return
class Dual(Graph): def _value_format(self, value): ''' Format value for dual value display. ''' pass def _compute_x_labels(self): pass def _compute_x_labels_major(self): pass def _get_x_label(self, i): '''Convenience function to get the x_label of a value index''' pass
5
2
10
1
8
1
2
0.15
1
7
0
2
4
2
4
73
44
6
33
12
28
5
25
12
20
5
4
3
8
143,756
Kozea/pygal
Kozea_pygal/pygal/graph/stackedbar.py
pygal.graph.stackedbar.StackedBar
class StackedBar(Bar): """Stacked Bar graph class""" _adapters = [none_to_zero] def _get_separated_values(self, secondary=False): """Separate values between positives and negatives stacked""" series = self.secondary_series if secondary else self.series transposed = list(zip(*[serie.values for serie in series])) positive_vals = [ sum([val for val in vals if val is not None and val >= self.zero]) for vals in transposed ] negative_vals = [ sum([val for val in vals if val is not None and val < self.zero]) for vals in transposed ] return positive_vals, negative_vals def _compute_box(self, positive_vals, negative_vals): """Compute Y min and max""" if self.range and self.range[0] is not None: self._box.ymin = self.range[0] else: self._box.ymin = negative_vals and min( min(negative_vals), self.zero ) or self.zero if self.range and self.range[1] is not None: self._box.ymax = self.range[1] else: self._box.ymax = positive_vals and max( max(positive_vals), self.zero ) or self.zero def _compute(self): """Compute y min and max and y scale and set labels""" positive_vals, negative_vals = self._get_separated_values() if self.logarithmic: positive_vals = list( filter(lambda x: x > self.zero, positive_vals) ) negative_vals = list( filter(lambda x: x > self.zero, negative_vals) ) self._compute_box(positive_vals, negative_vals) positive_vals = positive_vals or [self.zero] negative_vals = negative_vals or [self.zero] self._x_pos = [ x / self._len for x in range(self._len + 1) ] if self._len > 1 else [0, 1] # Center if only one value self._points(self._x_pos) self.negative_cumulation = [0] * self._len self.positive_cumulation = [0] * self._len if self.secondary_series: positive_vals, negative_vals = self._get_separated_values(True) positive_vals = positive_vals or [self.zero] negative_vals = negative_vals or [self.zero] self.secondary_negative_cumulation = [0] * self._len self.secondary_positive_cumulation = [0] * self._len self._pre_compute_secondary(positive_vals, negative_vals) self._x_pos = [(i + .5) / self._len for i in range(self._len)] def _pre_compute_secondary(self, positive_vals, negative_vals): """Compute secondary y min and max""" self._secondary_min = ( negative_vals and min(min(negative_vals), self.zero) ) or self.zero self._secondary_max = ( positive_vals and max(max(positive_vals), self.zero) ) or self.zero def _bar(self, serie, parent, x, y, i, zero, secondary=False): """Internal stacking bar drawing function""" if secondary: cumulation = ( self.secondary_negative_cumulation if y < self.zero else self.secondary_positive_cumulation ) else: cumulation = ( self.negative_cumulation if y < self.zero else self.positive_cumulation ) zero = cumulation[i] cumulation[i] = zero + y if zero == 0: zero = self.zero y -= self.zero y += zero width = (self.view.x(1) - self.view.x(0)) / self._len x, y = self.view((x, y)) y = y or 0 series_margin = width * self._series_margin x += series_margin width -= 2 * series_margin if self.secondary_series: width /= 2 x += int(secondary) * width serie_margin = width * self._serie_margin x += serie_margin width -= 2 * serie_margin height = self.view.y(zero) - y r = serie.rounded_bars * 1 if serie.rounded_bars else 0 self.svg.transposable_node( parent, 'rect', x=x, y=y, rx=r, ry=r, width=width, height=height, class_='rect reactive tooltip-trigger' ) return x, y, width, height def _plot(self): """Draw bars for series and secondary series""" for serie in self.series[::-1 if self.stack_from_top else 1]: self.bar(serie) for serie in self.secondary_series[::-1 if self.stack_from_top else 1]: self.bar(serie, True)
class StackedBar(Bar): '''Stacked Bar graph class''' def _get_separated_values(self, secondary=False): '''Separate values between positives and negatives stacked''' pass def _compute_box(self, positive_vals, negative_vals): '''Compute Y min and max''' pass def _compute_box(self, positive_vals, negative_vals): '''Compute y min and max and y scale and set labels''' pass def _pre_compute_secondary(self, positive_vals, negative_vals): '''Compute secondary y min and max''' pass def _bar(self, serie, parent, x, y, i, zero, secondary=False): '''Internal stacking bar drawing function''' pass def _plot(self): '''Draw bars for series and secondary series''' pass
7
7
20
1
18
1
4
0.07
1
5
0
2
6
7
6
80
130
15
108
27
101
8
69
27
62
7
5
1
22
143,757
Kozea/pygal
Kozea_pygal/pygal/graph/pie.py
pygal.graph.pie.Pie
class Pie(Graph): """Pie graph class""" _adapters = [positive, none_to_zero] def slice(self, serie, start_angle, total): """Make a serie slice""" serie_node = self.svg.serie(serie) dual = self._len > 1 and not self._order == 1 slices = self.svg.node(serie_node['plot'], class_="slices") serie_angle = 0 original_start_angle = start_angle if self.half_pie: center = ((self.width - self.margin_box.x) / 2., (self.height - self.margin_box.y) / 1.25) else: center = ((self.width - self.margin_box.x) / 2., (self.height - self.margin_box.y) / 2.) radius = min(center) for i, val in enumerate(serie.values): perc = val / total if self.half_pie: angle = 2 * pi * perc / 2 else: angle = 2 * pi * perc serie_angle += angle val = self._format(serie, i) metadata = serie.metadata.get(i) slice_ = decorate( self.svg, self.svg.node(slices, class_="slice"), metadata ) if dual: small_radius = radius * .9 big_radius = radius else: big_radius = radius * .9 small_radius = radius * serie.inner_radius alter( self.svg.slice( serie_node, slice_, big_radius, small_radius, angle, start_angle, center, val, i, metadata ), metadata ) start_angle += angle if dual: val = self._serie_format(serie, sum(serie.values)) self.svg.slice( serie_node, self.svg.node(slices, class_="big_slice"), radius * .9, 0, serie_angle, original_start_angle, center, val, i, metadata ) return serie_angle def _compute_x_labels(self): pass def _compute_y_labels(self): pass def _plot(self): """Draw all the serie slices""" total = sum(map(sum, map(lambda x: x.values, self.series))) if total == 0: return if self.half_pie: current_angle = 3 * pi / 2 else: current_angle = 0 for index, serie in enumerate(self.series): angle = self.slice(serie, current_angle, total) current_angle += angle
class Pie(Graph): '''Pie graph class''' def slice(self, serie, start_angle, total): '''Make a serie slice''' pass def _compute_x_labels(self): pass def _compute_y_labels(self): pass def _plot(self): '''Draw all the serie slices''' pass
5
3
17
1
15
1
3
0.05
1
2
0
0
4
1
4
73
76
10
63
25
58
3
46
24
41
6
4
2
12
143,758
Kozea/pygal
Kozea_pygal/pygal/graph/public.py
pygal.graph.public.PublicApi
class PublicApi(BaseGraph): """Chart public functions""" def add(self, title, values, **kwargs): """Add a serie to this graph, compat api""" if not is_list_like(values) and not isinstance(values, dict): values = [values] kwargs['title'] = title self.raw_series.append((values, kwargs)) return self def __call__(self, *args, **kwargs): """Call api: chart(1, 2, 3, title='T')""" self.raw_series.append((args, kwargs)) return self def add_xml_filter(self, callback): """Add an xml filter for in tree post processing""" self.xml_filters.append(callback) return self def render(self, is_unicode=False, **kwargs): """Render the graph, and return the svg string""" self.setup(**kwargs) svg = self.svg.render( is_unicode=is_unicode, pretty_print=self.pretty_print ) self.teardown() return svg def render_tree(self, **kwargs): """Render the graph, and return (l)xml etree""" self.setup(**kwargs) svg = self.svg.root for f in self.xml_filters: svg = f(svg) self.teardown() return svg def render_table(self, **kwargs): """Render the data as a html table""" # Import here to avoid lxml import try: from pygal.table import Table except ImportError: raise ImportError('You must install lxml to use render table') return Table(self).render(**kwargs) def render_pyquery(self, **kwargs): """Render the graph, and return a pyquery wrapped tree""" from pyquery import PyQuery as pq return pq(self.render(**kwargs), parser='html') def render_in_browser(self, **kwargs): """Render the graph, open it in your browser with black magic""" try: from lxml.html import open_in_browser except ImportError: raise ImportError('You must install lxml to use render in browser') kwargs.setdefault('force_uri_protocol', 'https') open_in_browser(self.render_tree(**kwargs), encoding='utf-8') def render_response(self, **kwargs): """Render the graph, and return a Flask response""" from flask import Response return Response(self.render(**kwargs), mimetype='image/svg+xml') def render_django_response(self, **kwargs): """Render the graph, and return a Django response""" from django.http import HttpResponse return HttpResponse( self.render(**kwargs), content_type='image/svg+xml' ) def render_data_uri(self, **kwargs): """Output a base 64 encoded data uri""" # Force protocol as data uri have none kwargs.setdefault('force_uri_protocol', 'https') return "data:image/svg+xml;charset=utf-8;base64,%s" % ( base64.b64encode(self.render(**kwargs) ).decode('utf-8').replace('\n', '') ) def render_to_file(self, filename, **kwargs): """Render the graph, and write it to filename""" with io.open(filename, 'w', encoding='utf-8') as f: f.write(self.render(is_unicode=True, **kwargs)) def render_to_png(self, filename=None, dpi=72, **kwargs): """Render the graph, convert it to png and write it to filename""" import cairosvg return cairosvg.svg2png( bytestring=self.render(**kwargs), write_to=filename, dpi=dpi ) def render_sparktext(self, relative_to=None): """Make a mini text sparkline from chart""" bars = '▁▂▃▄▅▆▇█' if len(self.raw_series) == 0: return '' values = list(self.raw_series[0][0]) if len(values) == 0: return '' chart = '' values = list(map(lambda x: max(x, 0), values)) vmax = max(values) if relative_to is None: relative_to = min(values) if (vmax - relative_to) == 0: chart = bars[0] * len(values) return chart divisions = len(bars) - 1 for value in values: chart += bars[int( divisions * (value - relative_to) / (vmax - relative_to) )] return chart def render_sparkline(self, **kwargs): """Render a sparkline""" spark_options = dict( width=200, height=50, show_dots=False, show_legend=False, show_x_labels=False, show_y_labels=False, spacing=0, margin=5, min_scale=1, max_scale=2, explicit_size=True, no_data_text='', js=(), classes=(Ellipsis, 'pygal-sparkline'), ) spark_options.update(kwargs) return self.render(**spark_options)
class PublicApi(BaseGraph): '''Chart public functions''' def add(self, title, values, **kwargs): '''Add a serie to this graph, compat api''' pass def __call__(self, *args, **kwargs): '''Call api: chart(1, 2, 3, title='T')''' pass def add_xml_filter(self, callback): '''Add an xml filter for in tree post processing''' pass def render(self, is_unicode=False, **kwargs): '''Render the graph, and return the svg string''' pass def render_tree(self, **kwargs): '''Render the graph, and return (l)xml etree''' pass def render_table(self, **kwargs): '''Render the data as a html table''' pass def render_pyquery(self, **kwargs): '''Render the graph, and return a pyquery wrapped tree''' pass def render_in_browser(self, **kwargs): '''Render the graph, open it in your browser with black magic''' pass def render_response(self, **kwargs): '''Render the graph, and return a Flask response''' pass def render_django_response(self, **kwargs): '''Render the graph, and return a Django response''' pass def render_data_uri(self, **kwargs): '''Output a base 64 encoded data uri''' pass def render_to_file(self, filename, **kwargs): '''Render the graph, and write it to filename''' pass def render_to_png(self, filename=None, dpi=72, **kwargs): '''Render the graph, convert it to png and write it to filename''' pass def render_sparktext(self, relative_to=None): '''Make a mini text sparkline from chart''' pass def render_sparkline(self, **kwargs): '''Render a sparkline''' pass
16
16
8
0
7
1
2
0.17
1
6
1
1
15
0
15
23
142
19
105
33
83
18
79
32
57
6
2
1
24
143,759
Kozea/pygal
Kozea_pygal/pygal/graph/pyramid.py
pygal.graph.pyramid.VerticalPyramid
class VerticalPyramid(StackedBar): """Vertical Pyramid graph class""" _adapters = [positive] def _value_format(self, value): """Format value for dual value display.""" return super(VerticalPyramid, self)._value_format(value and abs(value)) def _get_separated_values(self, secondary=False): """Separate values between odd and even series stacked""" series = self.secondary_series if secondary else self.series positive_vals = map( sum, zip( *[ serie.safe_values for index, serie in enumerate(series) if index % 2 ] ) ) negative_vals = map( sum, zip( *[ serie.safe_values for index, serie in enumerate(series) if not index % 2 ] ) ) return list(positive_vals), list(negative_vals) def _compute_box(self, positive_vals, negative_vals): """Compute Y min and max""" max_ = max( max(positive_vals or [self.zero]), max(negative_vals or [self.zero]) ) if self.range and self.range[0] is not None: self._box.ymin = self.range[0] else: self._box.ymin = -max_ if self.range and self.range[1] is not None: self._box.ymax = self.range[1] else: self._box.ymax = max_ def _pre_compute_secondary(self, positive_vals, negative_vals): """Compute secondary y min and max""" self._secondary_max = max(max(positive_vals), max(negative_vals)) self._secondary_min = -self._secondary_max def _bar(self, serie, parent, x, y, i, zero, secondary=False): """Internal stacking bar drawing function""" if serie.index % 2: y = -y return super(VerticalPyramid, self)._bar(serie, parent, x, y, i, zero, secondary)
class VerticalPyramid(StackedBar): '''Vertical Pyramid graph class''' def _value_format(self, value): '''Format value for dual value display.''' pass def _get_separated_values(self, secondary=False): '''Separate values between odd and even series stacked''' pass def _compute_box(self, positive_vals, negative_vals): '''Compute Y min and max''' pass def _pre_compute_secondary(self, positive_vals, negative_vals): '''Compute secondary y min and max''' pass def _bar(self, serie, parent, x, y, i, zero, secondary=False): '''Internal stacking bar drawing function''' pass
6
6
10
0
9
1
2
0.13
1
5
0
1
5
2
5
85
60
8
46
14
40
6
24
13
18
3
6
1
9
143,760
Kozea/pygal
Kozea_pygal/pygal/graph/radar.py
pygal.graph.radar.Radar
class Radar(Line): """Rada graph class""" _adapters = [positive, none_to_zero] def __init__(self, *args, **kwargs): """Init custom vars""" self._rmax = None super(Radar, self).__init__(*args, **kwargs) def _fill(self, values): """Add extra values to fill the line""" return values @cached_property def _values(self): """Getter for series values (flattened)""" if self.interpolate: return [ val[0] for serie in self.series for val in serie.interpolated ] else: return super(Line, self)._values def _set_view(self): """Assign a view to current graph""" if self.logarithmic: view_class = PolarLogView else: view_class = PolarView self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._box ) def _x_axis(self, draw_axes=True): """Override x axis to make it polar""" if not self._x_labels or not self.show_x_labels: return axis = self.svg.node( self.nodes['plot'], class_="axis x web%s" % (' always_show' if self.show_x_guides else '') ) format_ = lambda x: '%f %f' % x center = self.view((0, 0)) r = self._rmax # Can't simply determine truncation truncation = self.truncate_label or 25 for label, theta in self._x_labels: major = label in self._x_labels_major if not (self.show_minor_x_labels or major): continue guides = self.svg.node(axis, class_='guides') end = self.view((r, theta)) self.svg.node( guides, 'path', d='M%s L%s' % (format_(center), format_(end)), class_='%s%sline' % ('axis ' if label == "0" else '', 'major ' if major else '') ) r_txt = (1 - self._box.__class__.margin) * self._box.ymax pos_text = self.view((r_txt, theta)) text = self.svg.node( guides, 'text', x=pos_text[0], y=pos_text[1], class_='major' if major else '' ) text.text = truncate(label, truncation) if text.text != label: self.svg.node(guides, 'title').text = label else: self.svg.node( guides, 'title', ).text = self._x_format(theta) angle = -theta + pi / 2 if cos(angle) < 0: angle -= pi text.attrib['transform'] = 'rotate(%f %s)' % ( self.x_label_rotation or deg(angle), format_(pos_text) ) def _y_axis(self, draw_axes=True): """Override y axis to make it polar""" if not self._y_labels or not self.show_y_labels: return axis = self.svg.node(self.nodes['plot'], class_="axis y web") for label, r in reversed(self._y_labels): major = r in self._y_labels_major if not (self.show_minor_y_labels or major): continue guides = self.svg.node( axis, class_='%sguides' % ('logarithmic ' if self.logarithmic else '') ) if self.show_y_guides: self.svg.line( guides, [self.view((r, theta)) for theta in self._x_pos], close=True, class_='%sguide line' % ('major ' if major else '') ) x, y = self.view((r, self._x_pos[0])) x -= 5 text = self.svg.node( guides, 'text', x=x, y=y, class_='major' if major else '' ) text.text = label if self.y_label_rotation: text.attrib[ 'transform' ] = "rotate(%d %f %f)" % (self.y_label_rotation, x, y) self.svg.node( guides, 'title', ).text = self._y_format(r) def _compute(self): """Compute r min max and labels position""" delta = 2 * pi / self._len if self._len else 0 self._x_pos = [.5 * pi + i * delta for i in range(self._len + 1)] for serie in self.all_series: serie.points = [(v, self._x_pos[i]) for i, v in enumerate(serie.values)] if self.interpolate: extended_x_pos = ([.5 * pi - delta] + self._x_pos) extended_vals = (serie.values[-1:] + serie.values) serie.interpolated = list( map( tuple, map( reversed, self._interpolate(extended_x_pos, extended_vals) ) ) ) # x labels space self._box.margin *= 2 self._rmin = self.zero self._rmax = self._max or 1 self._box.set_polar_box(self._rmin, self._rmax) self._self_close = True def _compute_y_labels(self): y_pos = compute_scale( self._rmin, self._rmax, self.logarithmic, self.order_min, self.min_scale, self.max_scale / 2 ) if self.y_labels: self._y_labels = [] for i, y_label in enumerate(self.y_labels): if isinstance(y_label, dict): pos = self._adapt(y_label.get('value')) title = y_label.get('label', self._y_format(pos)) elif isinstance(y_label, str): pos = self._adapt(y_pos[i]) title = y_label else: pos = self._adapt(y_label) title = self._y_format(pos) self._y_labels.append((title, pos)) self._rmin = min(self._rmin, min(cut(self._y_labels, 1))) self._rmax = max(self._rmax, max(cut(self._y_labels, 1))) self._box.set_polar_box(self._rmin, self._rmax) else: self._y_labels = list(zip(map(self._y_format, y_pos), y_pos))
class Radar(Line): '''Rada graph class''' def __init__(self, *args, **kwargs): '''Init custom vars''' pass def _fill(self, values): '''Add extra values to fill the line''' pass @cached_property def _values(self): '''Getter for series values (flattened)''' pass def _set_view(self): '''Assign a view to current graph''' pass def _x_axis(self, draw_axes=True): '''Override x axis to make it polar''' pass def _y_axis(self, draw_axes=True): '''Override y axis to make it polar''' pass def _compute(self): '''Compute r min max and labels position''' pass def _compute_y_labels(self): pass
10
8
21
2
19
1
4
0.07
1
12
2
0
8
6
8
84
183
22
151
46
141
10
91
44
82
10
5
3
34
143,761
Kozea/pygal
Kozea_pygal/pygal/graph/solidgauge.py
pygal.graph.solidgauge.SolidGauge
class SolidGauge(Graph): def gaugify(self, serie, squares, sq_dimensions, current_square): serie_node = self.svg.serie(serie) if self.half_pie: start_angle = 3 * pi / 2 center = ((current_square[1] * sq_dimensions[0]) - (sq_dimensions[0] / 2.), (current_square[0] * sq_dimensions[1]) - (sq_dimensions[1] / 4)) end_angle = pi / 2 else: start_angle = 0 center = ((current_square[1] * sq_dimensions[0]) - (sq_dimensions[0] / 2.), (current_square[0] * sq_dimensions[1]) - (sq_dimensions[1] / 2.)) end_angle = 2 * pi max_value = serie.metadata.get(0, {}).get('max_value', 100) radius = min([sq_dimensions[0] / 2, sq_dimensions[1] / 2]) * .9 small_radius = radius * serie.inner_radius self.svg.gauge_background( serie_node, start_angle, center, radius, small_radius, end_angle, self.half_pie, self._serie_format(serie, max_value) ) sum_ = 0 for i, value in enumerate(serie.values): if value is None: continue ratio = min(value, max_value) / max_value if self.half_pie: angle = 2 * pi * ratio / 2 else: angle = 2 * pi * ratio val = self._format(serie, i) metadata = serie.metadata.get(i) gauge_ = decorate( self.svg, self.svg.node(serie_node['plot'], class_="gauge"), metadata ) alter( self.svg.solid_gauge( serie_node, gauge_, radius, small_radius, angle, start_angle, center, val, i, metadata, self.half_pie, end_angle, self._serie_format(serie, max_value) ), metadata ) start_angle += angle sum_ += value x, y = center self.svg.node( serie_node['text_overlay'], 'text', class_='value gauge-sum', x=x, y=y + self.style.value_font_size / 3, attrib={ 'text-anchor': 'middle' } ).text = self._serie_format(serie, sum_) def _compute_x_labels(self): pass def _compute_y_labels(self): pass def _plot(self): """Draw all the serie slices""" squares = self._squares() sq_dimensions = self.add_squares(squares) for index, serie in enumerate(self.series): current_square = self._current_square(squares, index) self.gaugify(serie, squares, sq_dimensions, current_square) def _squares(self): n_series_ = len(self.series) i = 2 if sqrt(n_series_).is_integer(): _x = int(sqrt(n_series_)) _y = int(sqrt(n_series_)) else: while i * i < n_series_: while n_series_ % i == 0: n_series_ = n_series_ / i i = i + 1 _y = int(n_series_) _x = int(len(self.series) / _y) if len(self.series) == 5: _x, _y = 2, 3 if abs(_x - _y) > 2: _sq = 3 while (_x * _y) - 1 < len(self.series): _x, _y = _sq, _sq _sq += 1 return (_x, _y) def _current_square(self, squares, index): current_square = [1, 1] steps = index + 1 steps_taken = 0 for i in range(squares[0] * squares[1]): steps_taken += 1 if steps_taken != steps and steps_taken % squares[0] != 0: current_square[1] += 1 elif steps_taken != steps and steps_taken % squares[0] == 0: current_square[1] = 1 current_square[0] += 1 else: return tuple(current_square) raise Exception( 'Something went wrong with the current square assignment.' )
class SolidGauge(Graph): def gaugify(self, serie, squares, sq_dimensions, current_square): pass def _compute_x_labels(self): pass def _compute_y_labels(self): pass def _plot(self): '''Draw all the serie slices''' pass def _squares(self): pass def _current_square(self, squares, index): pass
7
1
19
2
18
0
3
0.01
1
5
0
0
6
1
6
75
122
15
106
36
99
1
72
35
65
7
4
3
20
143,762
Kozea/pygal
Kozea_pygal/pygal/graph/stackedline.py
pygal.graph.stackedline.StackedLine
class StackedLine(Line): """Stacked Line graph class""" _adapters = [none_to_zero] def __init__(self, *args, **kwargs): """Custom variable initialization""" self._previous_line = None super(StackedLine, self).__init__(*args, **kwargs) def _value_format(self, value, serie, index): """ Display value and cumulation """ sum_ = serie.points[index][1] if serie in self.series and ( self.stack_from_top and self.series.index(serie) == self._order - 1 or not self.stack_from_top and self.series.index(serie) == 0): return super(StackedLine, self)._value_format(value) return '%s (+%s)' % (self._y_format(sum_), self._y_format(value)) def _fill(self, values): """Add extra values to fill the line""" if not self._previous_line: self._previous_line = values return super(StackedLine, self)._fill(values) new_values = values + list(reversed(self._previous_line)) self._previous_line = values return new_values def _points(self, x_pos): """ Convert given data values into drawable points (x, y) and interpolated points if interpolate option is specified """ for series_group in (self.series, self.secondary_series): accumulation = [0] * self._len for serie in series_group[::-1 if self.stack_from_top else 1]: accumulation = list(map(sum, zip(accumulation, serie.values))) serie.points = [(x_pos[i], v) for i, v in enumerate(accumulation)] if serie.points and self.interpolate: serie.interpolated = self._interpolate(x_pos, accumulation) else: serie.interpolated = [] def _plot(self): """Plot stacked serie lines and stacked secondary lines""" for serie in self.series[::-1 if self.stack_from_top else 1]: self.line(serie) for serie in self.secondary_series[::-1 if self.stack_from_top else 1]: self.line(serie, True)
class StackedLine(Line): '''Stacked Line graph class''' def __init__(self, *args, **kwargs): '''Custom variable initialization''' pass def _value_format(self, value, serie, index): ''' Display value and cumulation ''' pass def _fill(self, values): '''Add extra values to fill the line''' pass def _points(self, x_pos): ''' Convert given data values into drawable points (x, y) and interpolated points if interpolate option is specified ''' pass def _plot(self): '''Plot stacked serie lines and stacked secondary lines''' pass
6
6
9
0
7
2
3
0.31
1
6
0
1
5
1
5
81
53
6
36
14
30
11
31
14
25
5
5
3
15
143,763
Kozea/pygal
Kozea_pygal/pygal/graph/time.py
pygal.graph.time.DateLine
class DateLine(DateTimeLine): """Date abscissa xy graph class""" @property def _x_format(self): """Return the value formatter for this graph""" def date_to_str(x): d = datetime.utcfromtimestamp(x).date() return self.x_value_formatter(d) return date_to_str
class DateLine(DateTimeLine): '''Date abscissa xy graph class''' @property def _x_format(self): '''Return the value formatter for this graph''' pass def date_to_str(x): pass
4
2
6
1
4
1
1
0.29
1
1
0
0
1
0
1
87
12
3
7
5
3
2
6
4
3
1
7
0
2
143,764
Kozea/pygal
Kozea_pygal/pygal/graph/time.py
pygal.graph.time.DateTimeLine
class DateTimeLine(XY): """DateTime abscissa xy graph class""" _x_adapters = [datetime_to_timestamp, date_to_datetime] @property def _x_format(self): """Return the value formatter for this graph""" def datetime_to_str(x): dt = datetime.utcfromtimestamp(x) return self.x_value_formatter(dt) return datetime_to_str
class DateTimeLine(XY): '''DateTime abscissa xy graph class''' @property def _x_format(self): '''Return the value formatter for this graph''' pass def datetime_to_str(x): pass
4
2
6
1
4
1
1
0.25
1
1
0
2
1
0
1
86
14
4
8
6
4
2
7
5
4
1
6
0
2
143,765
Kozea/pygal
Kozea_pygal/pygal/graph/time.py
pygal.graph.time.TimeDeltaLine
class TimeDeltaLine(XY): """TimeDelta abscissa xy graph class""" _x_adapters = [timedelta_to_seconds] @property def _x_format(self): """Return the value formatter for this graph""" def timedelta_to_str(x): td = timedelta(seconds=x) return self.x_value_formatter(td) return timedelta_to_str
class TimeDeltaLine(XY): '''TimeDelta abscissa xy graph class''' @property def _x_format(self): '''Return the value formatter for this graph''' pass def timedelta_to_str(x): pass
4
2
6
1
4
1
1
0.25
1
1
0
0
1
0
1
86
14
4
8
6
4
2
7
5
4
1
6
0
2
143,766
Kozea/pygal
Kozea_pygal/pygal/graph/time.py
pygal.graph.time.TimeLine
class TimeLine(DateTimeLine): """Time abscissa xy graph class""" _x_adapters = [positive, time_to_seconds, datetime_to_time] @property def _x_format(self): """Return the value formatter for this graph""" def date_to_str(x): t = seconds_to_time(x) return self.x_value_formatter(t) return date_to_str
class TimeLine(DateTimeLine): '''Time abscissa xy graph class''' @property def _x_format(self): '''Return the value formatter for this graph''' pass def date_to_str(x): pass
4
2
6
1
4
1
1
0.25
1
0
0
0
1
0
1
87
14
4
8
6
4
2
7
5
4
1
7
0
2
143,767
Kozea/pygal
Kozea_pygal/pygal/graph/treemap.py
pygal.graph.treemap.Treemap
class Treemap(Graph): """Treemap graph class""" _adapters = [positive, none_to_zero] def _rect(self, serie, serie_node, rects, val, x, y, w, h, i): rx, ry = self.view((x, y)) rw, rh = self.view((x + w, y + h)) rw -= rx rh -= ry metadata = serie.metadata.get(i) val = self._format(serie, i) rect = decorate( self.svg, self.svg.node(rects, class_="rect"), metadata ) alter( self.svg.node( rect, 'rect', x=rx, y=ry, width=rw, height=rh, class_='rect reactive tooltip-trigger' ), metadata ) self._tooltip_data( rect, val, rx + rw / 2, ry + rh / 2, 'centered', self._get_x_label(i) ) self._static_value(serie_node, val, rx + rw / 2, ry + rh / 2, metadata) def _binary_tree(self, data, total, x, y, w, h, parent=None): if total == 0: return if len(data) == 1: if parent: i, datum = data[0] serie, serie_node, rects = parent self._rect(serie, serie_node, rects, datum, x, y, w, h, i) else: datum = data[0] serie_node = self.svg.serie(datum) self._binary_tree( list(enumerate(datum.values)), total, x, y, w, h, ( datum, serie_node, self.svg.node(serie_node['plot'], class_="rects") ) ) return midpoint = total / 2 pivot_index = 1 running_sum = 0 for i, elt in enumerate(data): if running_sum >= midpoint: pivot_index = i break running_sum += elt[1] if parent else sum(elt.values) half1 = data[:pivot_index] half2 = data[pivot_index:] if parent: half1_sum = sum(cut(half1, 1)) half2_sum = sum(cut(half2, 1)) else: half1_sum = sum(map(sum, map(lambda x: x.values, half1))) half2_sum = sum(map(sum, map(lambda x: x.values, half2))) pivot_pct = half1_sum / total if h > w: y_pivot = pivot_pct * h self._binary_tree(half1, half1_sum, x, y, w, y_pivot, parent) self._binary_tree( half2, half2_sum, x, y + y_pivot, w, h - y_pivot, parent ) else: x_pivot = pivot_pct * w self._binary_tree(half1, half1_sum, x, y, x_pivot, h, parent) self._binary_tree( half2, half2_sum, x + x_pivot, y, w - x_pivot, h, parent ) def _compute_x_labels(self): pass def _compute_y_labels(self): pass def _plot(self): total = sum(map(sum, map(lambda x: x.values, self.series))) if total == 0: return gw = self.width - self.margin_box.x gh = self.height - self.margin_box.y self.view.box.xmin = self.view.box.ymin = x = y = 0 self.view.box.xmax = w = (total * gw / gh)**.5 self.view.box.ymax = h = total / w self.view.box.fix() self._binary_tree(self.series, total, x, y, w, h)
class Treemap(Graph): '''Treemap graph class''' def _rect(self, serie, serie_node, rects, val, x, y, w, h, i): pass def _binary_tree(self, data, total, x, y, w, h, parent=None): pass def _compute_x_labels(self): pass def _compute_y_labels(self): pass def _plot(self): pass
6
1
20
3
18
0
3
0.01
1
3
0
0
5
1
5
74
110
19
90
31
84
1
63
27
57
9
4
2
14
143,768
Kozea/pygal
Kozea_pygal/pygal/graph/dot.py
pygal.graph.dot.Dot
class Dot(Graph): """Dot graph class""" def dot(self, serie, r_max): """Draw a dot line""" serie_node = self.svg.serie(serie) view_values = list(map(self.view, serie.points)) for i, value in safe_enumerate(serie.values): x, y = view_values[i] if self.logarithmic: log10min = log10(self._min) - 1 log10max = log10(self._max or 1) if value != 0: size = r_max * ((log10(abs(value)) - log10min) / (log10max - log10min)) else: size = 0 else: size = r_max * (abs(value) / (self._max or 1)) metadata = serie.metadata.get(i) dots = decorate( self.svg, self.svg.node(serie_node['plot'], class_="dots"), metadata ) alter( self.svg.node( dots, 'circle', cx=x, cy=y, r=size, class_='dot reactive tooltip-trigger' + (' negative' if value < 0 else '') ), metadata ) val = self._format(serie, i) self._tooltip_data( dots, val, x, y, 'centered', self._get_x_label(i) ) self._static_value(serie_node, val, x, y, metadata) def _compute(self): """Compute y min and max and y scale and set labels""" x_len = self._len y_len = self._order self._box.xmax = x_len self._box.ymax = y_len self._x_pos = [n / 2 for n in range(1, 2 * x_len, 2)] self._y_pos = [n / 2 for n in reversed(range(1, 2 * y_len, 2))] for j, serie in enumerate(self.series): serie.points = [(self._x_pos[i], self._y_pos[j]) for i in range(x_len)] def _compute_y_labels(self): if self.y_labels: y_labels = [str(label) for label in self.y_labels] else: y_labels = [ ( serie.title['title'] if isinstance(serie.title, dict) else serie.title ) or '' for serie in self.series ] self._y_labels = list(zip(y_labels, self._y_pos)) def _set_view(self): """Assign a view to current graph""" view_class = ReverseView if self.inverse_y_axis else View self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._box ) @cached_property def _values(self): """Getter for series values (flattened)""" return [abs(val) for val in super(Dot, self)._values if val != 0] @cached_property def _max(self): """Getter for the maximum series value""" return ( self.range[1] if (self.range and self.range[1] is not None) else (max(map(abs, self._values)) if self._values else None) ) def _plot(self): """Plot all dots for series""" r_max = min( self.view.x(1) - self.view.x(0), (self.view.y(0) or 0) - self.view.y(1) ) / (2 * 1.05) for serie in self.series: self.dot(serie, r_max)
class Dot(Graph): '''Dot graph class''' def dot(self, serie, r_max): '''Draw a dot line''' pass def _compute(self): '''Compute y min and max and y scale and set labels''' pass def _compute_y_labels(self): pass def _set_view(self): '''Assign a view to current graph''' pass @cached_property def _values(self): '''Getter for series values (flattened)''' pass @cached_property def _max(self): '''Getter for the maximum series value''' pass def _plot(self): '''Plot all dots for series''' pass
10
7
13
1
11
1
3
0.09
1
11
2
0
7
5
7
76
103
14
82
32
72
7
44
29
36
5
4
3
18
143,769
Kozea/pygal
Kozea_pygal/pygal/graph/map.py
pygal.graph.map.BaseMap
class BaseMap(Graph): """Base class for maps""" _dual = True @cached_property def _values(self): """Getter for series values (flattened)""" return [ val[1] for serie in self.series for val in serie.values if val[1] is not None ] def enumerate_values(self, serie): """Hook to replace default enumeration on values""" return enumerate(serie.values) def adapt_code(self, area_code): """Hook to change the area code""" return area_code def _value_format(self, value): """ Format value for map value display. """ return '%s: %s' % ( self.area_names.get(self.adapt_code(value[0]), '?'), self._y_format(value[1]) ) def _plot(self): """Insert a map in the chart and apply data on it""" map = etree.fromstring(self.svg_map) map.set('width', str(self.view.width)) map.set('height', str(self.view.height)) for i, serie in enumerate(self.series): safe_vals = list( filter(lambda x: x is not None, cut(serie.values, 1)) ) if not safe_vals: continue min_ = min(safe_vals) max_ = max(safe_vals) for j, (area_code, value) in self.enumerate_values(serie): area_code = self.adapt_code(area_code) if value is None: continue if max_ == min_: ratio = 1 else: ratio = .3 + .7 * (value - min_) / (max_ - min_) areae = map.findall( ".//*[@class='%s%s %s map-element']" % (self.area_prefix, area_code, self.kind) ) if not areae: continue for area in areae: cls = area.get('class', '').split(' ') cls.append('color-%d' % i) cls.append('serie-%d' % i) cls.append('series') area.set('class', ' '.join(cls)) area.set('style', 'fill-opacity: %f' % ratio) metadata = serie.metadata.get(j) if metadata: node = decorate(self.svg, area, metadata) if node != area: area.remove(node) for g in map: if area not in g: continue index = list(g).index(area) g.remove(area) node.append(area) g.insert(index, node) for node in area: cls = node.get('class', '').split(' ') cls.append('reactive') cls.append('tooltip-trigger') cls.append('map-area') node.set('class', ' '.join(cls)) alter(node, metadata) val = self._format(serie, j) self._tooltip_data(area, val, 0, 0, 'auto') self.nodes['plot'].append(map) def _compute_x_labels(self): pass def _compute_y_labels(self): pass
class BaseMap(Graph): '''Base class for maps''' @cached_property def _values(self): '''Getter for series values (flattened)''' pass def enumerate_values(self, serie): '''Hook to replace default enumeration on values''' pass def adapt_code(self, area_code): '''Hook to change the area code''' pass def _value_format(self, value): ''' Format value for map value display. ''' pass def _plot(self): '''Insert a map in the chart and apply data on it''' pass def _compute_x_labels(self): pass def _compute_y_labels(self): pass
9
6
13
1
10
1
3
0.11
1
4
0
0
7
0
7
76
101
17
76
26
67
8
63
24
55
13
4
7
19
143,770
Kozea/pygal
Kozea_pygal/pygal/graph/box.py
pygal.graph.box.Box
class Box(Graph): """ Box plot For each series, shows the median value, the 25th and 75th percentiles, and the values within 1.5 times the interquartile range of the 25th and 75th percentiles. See http://en.wikipedia.org/wiki/Box_plot """ _series_margin = .06 def _value_format(self, value, serie): """ Format value for dual value display. """ if self.box_mode == "extremes": return ( 'Min: %s\nQ1 : %s\nQ2 : %s\nQ3 : %s\nMax: %s' % tuple(map(self._y_format, serie.points[1:6])) ) elif self.box_mode in ["tukey", "stdev", "pstdev"]: return ( 'Min: %s\nLower Whisker: %s\nQ1: %s\nQ2: %s\nQ3: %s\n' 'Upper Whisker: %s\nMax: %s' % tuple(map(self._y_format, serie.points)) ) elif self.box_mode == '1.5IQR': # 1.5IQR mode return 'Q1: %s\nQ2: %s\nQ3: %s' % tuple( map(self._y_format, serie.points[2:5]) ) else: return self._y_format(serie.points) def _compute(self): """ Compute parameters necessary for later steps within the rendering process """ for serie in self.series: serie.points, serie.outliers = \ self._box_points(serie.values, self.box_mode) self._x_pos = [(i + .5) / self._order for i in range(self._order)] if self._min: self._box.ymin = min(self._min, self.zero) if self._max: self._box.ymax = max(self._max, self.zero) def _plot(self): """Plot the series data""" for serie in self.series: self._boxf(serie) @property def _len(self): """Len is always 7 here""" return 7 def _boxf(self, serie): """For a specific series, draw the box plot.""" serie_node = self.svg.serie(serie) # Note: q0 and q4 do not literally mean the zero-th quartile # and the fourth quartile, but rather the distance from 1.5 times # the inter-quartile range to Q1 and Q3, respectively. boxes = self.svg.node(serie_node['plot'], class_="boxes") metadata = serie.metadata.get(0) box = decorate(self.svg, self.svg.node(boxes, class_='box'), metadata) val = self._format(serie, 0) x_center, y_center = self._draw_box( box, serie.points[1:6], serie.outliers, serie.index, metadata ) self._tooltip_data( box, val, x_center, y_center, "centered", self._get_x_label(serie.index) ) self._static_value(serie_node, val, x_center, y_center, metadata) def _draw_box(self, parent_node, quartiles, outliers, box_index, metadata): """ Return the center of a bounding box defined by a box plot. Draws a box plot on self.svg. """ width = (self.view.x(1) - self.view.x(0)) / self._order series_margin = width * self._series_margin left_edge = self.view.x(0) + width * box_index + series_margin width -= 2 * series_margin # draw lines for whiskers - bottom, median, and top for i, whisker in enumerate((quartiles[0], quartiles[2], quartiles[4])): whisker_width = width if i == 1 else width / 2 shift = (width - whisker_width) / 2 xs = left_edge + shift xe = left_edge + width - shift alter( self.svg.line( parent_node, coords=[(xs, self.view.y(whisker)), (xe, self.view.y(whisker))], class_='reactive tooltip-trigger', attrib={'stroke-width': 3} ), metadata ) # draw lines connecting whiskers to box (Q1 and Q3) alter( self.svg.line( parent_node, coords=[(left_edge + width / 2, self.view.y(quartiles[0])), (left_edge + width / 2, self.view.y(quartiles[1]))], class_='reactive tooltip-trigger', attrib={'stroke-width': 2} ), metadata ) alter( self.svg.line( parent_node, coords=[(left_edge + width / 2, self.view.y(quartiles[4])), (left_edge + width / 2, self.view.y(quartiles[3]))], class_='reactive tooltip-trigger', attrib={'stroke-width': 2} ), metadata ) # box, bounded by Q1 and Q3 alter( self.svg.node( parent_node, tag='rect', x=left_edge, y=self.view.y(quartiles[1]), height=self.view.y(quartiles[3]) - self.view.y(quartiles[1]), width=width, class_='subtle-fill reactive tooltip-trigger' ), metadata ) # draw outliers for o in outliers: alter( self.svg.node( parent_node, tag='circle', cx=left_edge + width / 2, cy=self.view.y(o), r=3, class_='subtle-fill reactive tooltip-trigger' ), metadata ) return ( left_edge + width / 2, self.view.y(sum(quartiles) / len(quartiles)) ) @staticmethod def _box_points(values, mode='extremes'): """ Default mode: (mode='extremes' or unset) Return a 7-tuple of 2x minimum, Q1, Median, Q3, and 2x maximum for a list of numeric values. 1.5IQR mode: (mode='1.5IQR') Return a 7-tuple of min, Q1 - 1.5 * IQR, Q1, Median, Q3, Q3 + 1.5 * IQR and max for a list of numeric values. Tukey mode: (mode='tukey') Return a 7-tuple of min, q[0..4], max and a list of outliers Outliers are considered values x: x < q1 - IQR or x > q3 + IQR SD mode: (mode='stdev') Return a 7-tuple of min, q[0..4], max and a list of outliers Outliers are considered values x: x < q2 - SD or x > q2 + SD SDp mode: (mode='pstdev') Return a 7-tuple of min, q[0..4], max and a list of outliers Outliers are considered values x: x < q2 - SDp or x > q2 + SDp The iterator values may include None values. Uses quartile definition from Mendenhall, W. and Sincich, T. L. Statistics for Engineering and the Sciences, 4th ed. Prentice-Hall, 1995. """ def median(seq): n = len(seq) if n % 2 == 0: # seq has an even length return (seq[n // 2] + seq[n // 2 - 1]) / 2 else: # seq has an odd length return seq[n // 2] def mean(seq): return sum(seq) / len(seq) def stdev(seq): m = mean(seq) l = len(seq) v = sum((n - m)**2 for n in seq) / (l - 1) # variance return v**0.5 # sqrt def pstdev(seq): m = mean(seq) l = len(seq) v = sum((n - m)**2 for n in seq) / l # variance return v**0.5 # sqrt outliers = [] # sort the copy in case the originals must stay in original order s = sorted([x for x in values if x is not None]) n = len(s) if not n: return (0, 0, 0, 0, 0, 0, 0), [] elif n == 1: return (s[0], s[0], s[0], s[0], s[0], s[0], s[0]), [] else: q2 = median(s) # See 'Method 3' in http://en.wikipedia.org/wiki/Quartile if n % 2 == 0: # even q1 = median(s[:n // 2]) q3 = median(s[n // 2:]) else: # odd if n == 1: # special case q1 = s[0] q3 = s[0] elif n % 4 == 1: # n is of form 4n + 1 where n >= 1 m = (n - 1) // 4 q1 = 0.25 * s[m - 1] + 0.75 * s[m] q3 = 0.75 * s[3 * m] + 0.25 * s[3 * m + 1] else: # n is of form 4n + 3 where n >= 1 m = (n - 3) // 4 q1 = 0.75 * s[m] + 0.25 * s[m + 1] q3 = 0.25 * s[3 * m + 1] + 0.75 * s[3 * m + 2] iqr = q3 - q1 min_s = s[0] max_s = s[-1] if mode == 'extremes': q0 = min_s q4 = max_s elif mode == 'tukey': # the lowest datum still within 1.5 IQR of the lower quartile, # and the highest datum still within 1.5 IQR of the upper # quartile [Tukey box plot, Wikipedia ] b0 = bisect_left(s, q1 - 1.5 * iqr) b4 = bisect_right(s, q3 + 1.5 * iqr) q0 = s[b0] q4 = s[b4 - 1] outliers = s[:b0] + s[b4:] elif mode == 'stdev': # one standard deviation above and below the mean of the data sd = stdev(s) b0 = bisect_left(s, q2 - sd) b4 = bisect_right(s, q2 + sd) q0 = s[b0] q4 = s[b4 - 1] outliers = s[:b0] + s[b4:] elif mode == 'pstdev': # one population standard deviation above and below # the mean of the data sdp = pstdev(s) b0 = bisect_left(s, q2 - sdp) b4 = bisect_right(s, q2 + sdp) q0 = s[b0] q4 = s[b4 - 1] outliers = s[:b0] + s[b4:] elif mode == '1.5IQR': # 1.5IQR mode q0 = q1 - 1.5 * iqr q4 = q3 + 1.5 * iqr return (min_s, q0, q1, q2, q3, q4, max_s), outliers
class Box(Graph): ''' Box plot For each series, shows the median value, the 25th and 75th percentiles, and the values within 1.5 times the interquartile range of the 25th and 75th percentiles. See http://en.wikipedia.org/wiki/Box_plot ''' def _value_format(self, value, serie): ''' Format value for dual value display. ''' pass def _compute(self): ''' Compute parameters necessary for later steps within the rendering process ''' pass def _plot(self): '''Plot the series data''' pass @property def _len(self): '''Len is always 7 here''' pass def _boxf(self, serie): '''For a specific series, draw the box plot.''' pass def _draw_box(self, parent_node, quartiles, outliers, box_index, metadata): ''' Return the center of a bounding box defined by a box plot. Draws a box plot on self.svg. ''' pass @staticmethod def _box_points(values, mode='extremes'): ''' Default mode: (mode='extremes' or unset) Return a 7-tuple of 2x minimum, Q1, Median, Q3, and 2x maximum for a list of numeric values. 1.5IQR mode: (mode='1.5IQR') Return a 7-tuple of min, Q1 - 1.5 * IQR, Q1, Median, Q3, Q3 + 1.5 * IQR and max for a list of numeric values. Tukey mode: (mode='tukey') Return a 7-tuple of min, q[0..4], max and a list of outliers Outliers are considered values x: x < q1 - IQR or x > q3 + IQR SD mode: (mode='stdev') Return a 7-tuple of min, q[0..4], max and a list of outliers Outliers are considered values x: x < q2 - SD or x > q2 + SD SDp mode: (mode='pstdev') Return a 7-tuple of min, q[0..4], max and a list of outliers Outliers are considered values x: x < q2 - SDp or x > q2 + SDp The iterator values may include None values. Uses quartile definition from Mendenhall, W. and Sincich, T. L. Statistics for Engineering and the Sciences, 4th ed. Prentice-Hall, 1995. ''' pass def median(seq): pass def mean(seq): pass def stdev(seq): pass def pstdev(seq): pass
14
8
25
2
18
6
3
0.37
1
4
0
0
6
3
7
76
274
28
187
57
173
70
110
54
98
11
4
3
32
143,771
Kozea/pygal
Kozea_pygal/pygal/view.py
pygal.view.PolarView
class PolarView(View): """Polar projection for pie like graphs""" def __call__(self, rhotheta): """Project rho and theta""" if None in rhotheta: return None, None rho, theta = rhotheta return super(PolarView, self).__call__((rho * cos(theta), rho * sin(theta)))
class PolarView(View): '''Polar projection for pie like graphs''' def __call__(self, rhotheta): '''Project rho and theta''' pass
2
2
7
0
6
1
2
0.29
1
1
0
0
1
0
1
5
10
1
7
3
5
2
6
3
4
2
2
1
2
143,772
Kozea/pygal
Kozea_pygal/pygal/graph/bar.py
pygal.graph.bar.Bar
class Bar(Graph): """Bar graph class""" _series_margin = .06 _serie_margin = .06 def _bar(self, serie, parent, x, y, i, zero, secondary=False): """Internal bar drawing function""" width = (self.view.x(1) - self.view.x(0)) / self._len x, y = self.view((x, y)) series_margin = width * self._series_margin x += series_margin width -= 2 * series_margin width /= self._order if self.horizontal: serie_index = self._order - serie.index - 1 else: serie_index = serie.index x += serie_index * width serie_margin = width * self._serie_margin x += serie_margin width -= 2 * serie_margin height = self.view.y(zero) - y r = serie.rounded_bars * 1 if serie.rounded_bars else 0 alter( self.svg.transposable_node( parent, 'rect', x=x, y=y, rx=r, ry=r, width=width, height=height, class_='rect reactive tooltip-trigger' ), serie.metadata.get(i) ) return x, y, width, height def _tooltip_and_print_values( self, serie_node, serie, parent, i, val, metadata, x, y, width, height ): transpose = swap if self.horizontal else ident x_center, y_center = transpose((x + width / 2, y + height / 2)) x_top, y_top = transpose((x + width, y + height)) x_bottom, y_bottom = transpose((x, y)) if self._dual: v = serie.values[i][0] else: v = serie.values[i] sign = -1 if v < self.zero else 1 self._tooltip_data( parent, val, x_center, y_center, "centered", self._get_x_label(i) ) if self.print_values_position == 'top': if self.horizontal: x = x_bottom + sign * self.style.value_font_size / 2 y = y_center else: x = x_center y = y_bottom - sign * self.style.value_font_size / 2 elif self.print_values_position == 'bottom': if self.horizontal: x = x_top + sign * self.style.value_font_size / 2 y = y_center else: x = x_center y = y_top - sign * self.style.value_font_size / 2 else: x = x_center y = y_center self._static_value(serie_node, val, x, y, metadata, "middle") def bar(self, serie, rescale=False): """Draw a bar graph for a serie""" serie_node = self.svg.serie(serie) bars = self.svg.node(serie_node['plot'], class_="bars") if rescale and self.secondary_series: points = self._rescale(serie.points) else: points = serie.points for i, (x, y) in enumerate(points): if None in (x, y) or (self.logarithmic and y <= 0): continue metadata = serie.metadata.get(i) val = self._format(serie, i) bar = decorate( self.svg, self.svg.node(bars, class_='bar'), metadata ) x_, y_, width, height = self._bar( serie, bar, x, y, i, self.zero, secondary=rescale ) self._confidence_interval( serie_node['overlay'], x_ + width / 2, y_, serie.values[i], metadata ) self._tooltip_and_print_values( serie_node, serie, bar, i, val, metadata, x_, y_, width, height ) def _compute(self): """Compute y min and max and y scale and set labels""" if self._min: self._box.ymin = min(self._min, self.zero) if self._max: self._box.ymax = max(self._max, self.zero) self._x_pos = [ x / self._len for x in range(self._len + 1) ] if self._len > 1 else [0, 1] # Center if only one value self._points(self._x_pos) self._x_pos = [(i + .5) / self._len for i in range(self._len)] def _plot(self): """Draw bars for series and secondary series""" for serie in self.series: self.bar(serie) for serie in self.secondary_series: self.bar(serie, True)
class Bar(Graph): '''Bar graph class''' def _bar(self, serie, parent, x, y, i, zero, secondary=False): '''Internal bar drawing function''' pass def _tooltip_and_print_values( self, serie_node, serie, parent, i, val, metadata, x, y, width, height ): pass def bar(self, serie, rescale=False): '''Draw a bar graph for a serie''' pass def _compute(self): '''Compute y min and max and y scale and set labels''' pass def _plot(self): '''Draw bars for series and secondary series''' pass
6
5
24
2
21
1
4
0.06
1
2
0
3
5
3
5
74
128
15
108
35
99
6
73
30
67
8
4
2
22
143,773
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.TurquoiseStyle
class TurquoiseStyle(Style): """A turquoise style""" background = darken('#1b8088', 15) plot_background = darken('#1b8088', 17) foreground = 'rgba(255, 255, 255, 0.9)' foreground_strong = 'rgba(255, 255, 255, 0.9)' foreground_subtle = 'rgba(255, 255 , 255, 0.5)' opacity = '.5' opacity_hover = '.9' transition = '250ms ease-in' colors = ( '#93d2d9', '#ef940f', '#8C6243', '#fff', darken('#93d2d9', 20), lighten('#ef940f', 15), lighten('#8c6243', 15), '#1b8088' )
class TurquoiseStyle(Style): '''A turquoise style''' pass
1
1
0
0
0
0
0
0.38
1
0
0
0
0
0
0
3
15
1
13
10
12
5
10
10
9
0
2
0
0
143,774
Kozea/pygal
Kozea_pygal/pygal/svg.py
pygal.svg.Svg
class Svg(object): """Svg related methods""" ns = 'http://www.w3.org/2000/svg' xlink_ns = 'http://www.w3.org/1999/xlink' def __init__(self, graph): """Create the svg helper with the chart instance""" self.graph = graph if not graph.no_prefix: self.id = '#chart-%s ' % graph.uuid else: self.id = '' self.processing_instructions = [] if etree.lxml: attrs = {'nsmap': {None: self.ns, 'xlink': self.xlink_ns}} else: attrs = {'xmlns': self.ns} if hasattr(etree, 'register_namespace'): etree.register_namespace('xlink', self.xlink_ns) else: etree._namespace_map[self.xlink_ns] = 'xlink' self.root = etree.Element('svg', **attrs) self.root.attrib['id'] = self.id.lstrip('#').rstrip() if graph.classes: self.root.attrib['class'] = ' '.join(graph.classes) self.root.append( etree.Comment( 'Generated with pygal %s (%s) ©Kozea 2012-2016 on %s' % ( __version__, 'lxml' if etree.lxml else 'etree', date.today().isoformat() ) ) ) self.root.append(etree.Comment('http://pygal.org')) self.root.append(etree.Comment('http://github.com/Kozea/pygal')) self.defs = self.node(tag='defs') self.title = self.node(tag='title') self.title.text = graph.title or 'Pygal' for def_ in self.graph.defs: self.defs.append(etree.fromstring(def_)) def add_styles(self): """Add the css to the svg""" colors = self.graph.style.get_colors(self.id, self.graph._order) strokes = self.get_strokes() all_css = [] auto_css = ['file://base.css'] if self.graph.style._google_fonts: auto_css.append( '//fonts.googleapis.com/css?family=%s' % quote_plus('|'.join(self.graph.style._google_fonts)) ) for css in auto_css + list(self.graph.css): css_text = None if css.startswith('inline:'): css_text = css[len('inline:'):] elif css.startswith('file://'): css = css[len('file://'):] if not os.path.exists(css): css = os.path.join(os.path.dirname(__file__), 'css', css) with io.open(css, encoding='utf-8') as f: css_text = template( f.read(), style=self.graph.style, colors=colors, strokes=strokes, id=self.id ) if css_text is not None: if not self.graph.pretty_print: css_text = minify_css(css_text) all_css.append(css_text) else: if css.startswith('//') and self.graph.force_uri_protocol: css = '%s:%s' % (self.graph.force_uri_protocol, css) self.processing_instructions.append( etree.PI('xml-stylesheet', 'href="%s"' % css) ) self.node( self.defs, 'style', type='text/css' ).text = '\n'.join(all_css) def add_scripts(self): """Add the js to the svg""" common_script = self.node(self.defs, 'script', type='text/javascript') def get_js_dict(): return dict( (k, getattr(self.graph.state, k)) for k in dir(self.graph.config) if not k.startswith('_') and hasattr(self.graph.state, k) and not hasattr(getattr(self.graph.state, k), '__call__') ) def json_default(o): if isinstance(o, (datetime, date)): return o.isoformat() if hasattr(o, 'to_dict'): return o.to_dict() return json.JSONEncoder().default(o) dct = get_js_dict() # Config adds dct['legends'] = [ l.get('title') if isinstance(l, dict) else l for l in self.graph._legends + self.graph._secondary_legends ] common_js = 'window.pygal = window.pygal || {};' common_js += 'window.pygal.config = window.pygal.config || {};' if self.graph.no_prefix: common_js += 'window.pygal.config = ' else: common_js += 'window.pygal.config[%r] = ' % self.graph.uuid common_script.text = common_js + json.dumps(dct, default=json_default) for js in self.graph.js: if js.startswith('file://'): script = self.node(self.defs, 'script', type='text/javascript') with io.open(js[len('file://'):], encoding='utf-8') as f: script.text = f.read() else: if js.startswith('//') and self.graph.force_uri_protocol: js = '%s:%s' % (self.graph.force_uri_protocol, js) self.node(self.defs, 'script', type='text/javascript', href=js) def node(self, parent=None, tag='g', attrib=None, **extras): """Make a new svg node""" if parent is None: parent = self.root attrib = attrib or {} attrib.update(extras) def in_attrib_and_number(key): return key in attrib and isinstance(attrib[key], Number) for pos, dim in (('x', 'width'), ('y', 'height')): if in_attrib_and_number(dim) and attrib[dim] < 0: attrib[dim] = -attrib[dim] if in_attrib_and_number(pos): attrib[pos] = attrib[pos] - attrib[dim] for key, value in dict(attrib).items(): if value is None: del attrib[key] attrib[key] = str(value) if key.endswith('_'): attrib[key.rstrip('_')] = attrib[key] del attrib[key] elif key == 'href': attrib[etree.QName('http://www.w3.org/1999/xlink', key)] = attrib[key] del attrib[key] return etree.SubElement(parent, tag, attrib) def transposable_node(self, parent=None, tag='g', attrib=None, **extras): """Make a new svg node which can be transposed if horizontal""" if self.graph.horizontal: for key1, key2 in (('x', 'y'), ('width', 'height'), ('cx', 'cy')): attr1 = extras.get(key1, None) attr2 = extras.get(key2, None) if attr2: extras[key1] = attr2 elif attr1: del extras[key1] if attr1: extras[key2] = attr1 elif attr2: del extras[key2] return self.node(parent, tag, attrib, **extras) def serie(self, serie): """Make serie node""" return dict( plot=self.node( self.graph.nodes['plot'], class_='series serie-%d color-%d' % (serie.index, serie.index) ), overlay=self.node( self.graph.nodes['overlay'], class_='series serie-%d color-%d' % (serie.index, serie.index) ), text_overlay=self.node( self.graph.nodes['text_overlay'], class_='series serie-%d color-%d' % (serie.index, serie.index) ) ) def line(self, node, coords, close=False, **kwargs): """Draw a svg line""" line_len = len(coords) if len([c for c in coords if c[1] is not None]) < 2: return root = 'M%s L%s Z' if close else 'M%s L%s' origin_index = 0 while origin_index < line_len and None in coords[origin_index]: origin_index += 1 if origin_index == line_len: return if self.graph.horizontal: coord_format = lambda xy: '%f %f' % (xy[1], xy[0]) else: coord_format = lambda xy: '%f %f' % xy origin = coord_format(coords[origin_index]) line = ' '.join([ coord_format(c) for c in coords[origin_index + 1:] if None not in c ]) return self.node(node, 'path', d=root % (origin, line), **kwargs) def slice( self, serie_node, node, radius, small_radius, angle, start_angle, center, val, i, metadata ): """Draw a pie slice""" if angle == 2 * pi: angle = nearly_2pi if angle > 0: to = [ coord_abs_project(center, radius, start_angle), coord_abs_project(center, radius, start_angle + angle), coord_abs_project(center, small_radius, start_angle + angle), coord_abs_project(center, small_radius, start_angle) ] rv = self.node( node, 'path', d='M%s A%s 0 %d 1 %s L%s A%s 0 %d 0 %s z' % ( to[0], coord_dual(radius), int(angle > pi), to[1], to[2], coord_dual(small_radius), int(angle > pi), to[3] ), class_='slice reactive tooltip-trigger' ) else: rv = None x, y = coord_diff( center, coord_project((radius + small_radius) / 2, start_angle + angle / 2) ) self.graph._tooltip_data( node, val, x, y, "centered", self.graph._x_labels and self.graph._x_labels[i][0] ) if angle >= 0.3: # 0.3 radians is about 17 degrees self.graph._static_value(serie_node, val, x, y, metadata) return rv def gauge_background( self, serie_node, start_angle, center, radius, small_radius, end_angle, half_pie, max_value ): if end_angle == 2 * pi: end_angle = nearly_2pi to_shade = [ coord_abs_project(center, radius, start_angle), coord_abs_project(center, radius, end_angle), coord_abs_project(center, small_radius, end_angle), coord_abs_project(center, small_radius, start_angle) ] self.node( serie_node['plot'], 'path', d='M%s A%s 0 1 1 %s L%s A%s 0 1 0 %s z' % ( to_shade[0], coord_dual(radius), to_shade[1], to_shade[2], coord_dual(small_radius), to_shade[3] ), class_='gauge-background reactive' ) if half_pie: begin_end = [ coord_diff( center, coord_project( radius - (radius - small_radius) / 2, start_angle ) ), coord_diff( center, coord_project( radius - (radius - small_radius) / 2, end_angle ) ) ] pos = 0 for i in begin_end: self.node( serie_node['plot'], 'text', class_='y-{} bound reactive'.format(pos), x=i[0], y=i[1] + 10, attrib={ 'text-anchor': 'middle' } ).text = '{}'.format(0 if pos == 0 else max_value) pos += 1 else: middle_radius = .5 * (radius + small_radius) # Correct text vertical alignment middle_radius -= .1 * (radius - small_radius) to_labels = [ coord_abs_project(center, middle_radius, 0), coord_abs_project(center, middle_radius, nearly_2pi) ] self.node( self.defs, 'path', id='valuePath-%s%s' % center, d='M%s A%s 0 1 1 %s' % (to_labels[0], coord_dual(middle_radius), to_labels[1]) ) text_ = self.node(serie_node['text_overlay'], 'text') self.node( text_, 'textPath', class_='max-value reactive', attrib={ 'href': '#valuePath-%s%s' % center, 'startOffset': '99%', 'text-anchor': 'end' } ).text = max_value def solid_gauge( self, serie_node, node, radius, small_radius, angle, start_angle, center, val, i, metadata, half_pie, end_angle, max_value ): """Draw a solid gauge slice and background slice""" if angle == 2 * pi: angle = nearly_2pi if angle > 0: to = [ coord_abs_project(center, radius, start_angle), coord_abs_project(center, radius, start_angle + angle), coord_abs_project(center, small_radius, start_angle + angle), coord_abs_project(center, small_radius, start_angle) ] self.node( node, 'path', d='M%s A%s 0 %d 1 %s L%s A%s 0 %d 0 %s z' % ( to[0], coord_dual(radius), int(angle > pi), to[1], to[2], coord_dual(small_radius), int(angle > pi), to[3] ), class_='slice reactive tooltip-trigger' ) else: return x, y = coord_diff( center, coord_project((radius + small_radius) / 2, start_angle + angle / 2) ) self.graph._static_value(serie_node, val, x, y, metadata, 'middle') self.graph._tooltip_data( node, val, x, y, "centered", self.graph._x_labels and self.graph._x_labels[i][0] ) def confidence_interval(self, node, x, low, high, width=7): if self.graph.horizontal: fmt = lambda xy: '%f %f' % (xy[1], xy[0]) else: fmt = coord_format shr = lambda xy: (xy[0] + width, xy[1]) shl = lambda xy: (xy[0] - width, xy[1]) top = (x, high) bottom = (x, low) ci = self.node(node, class_="ci") self.node( ci, 'path', d="M%s L%s M%s L%s M%s L%s L%s M%s L%s" % tuple( map( fmt, ( top, shr(top), top, shl(top), top, bottom, shr(bottom), bottom, shl(bottom) ) ) ), class_='nofill reactive' ) def pre_render(self): """Last things to do before rendering""" self.add_styles() self.add_scripts() self.root.set( 'viewBox', '0 0 %d %d' % (self.graph.width, self.graph.height) ) if self.graph.explicit_size: self.root.set('width', str(self.graph.width)) self.root.set('height', str(self.graph.height)) def draw_no_data(self): """Write the no data text to the svg""" no_data = self.node( self.graph.nodes['text_overlay'], 'text', x=self.graph.view.width / 2, y=self.graph.view.height / 2, class_='no_data' ) no_data.text = self.graph.no_data_text def render(self, is_unicode=False, pretty_print=False): """Last thing to do before rendering""" for f in self.graph.xml_filters: self.root = f(self.root) args = {'encoding': 'utf-8'} svg = b'' if etree.lxml: args['pretty_print'] = pretty_print if not self.graph.disable_xml_declaration: svg = b"<?xml version='1.0' encoding='utf-8'?>\n" if not self.graph.disable_xml_declaration: svg += b'\n'.join([ etree.tostring(pi, **args) for pi in self.processing_instructions ]) svg += etree.tostring(self.root, **args) if self.graph.disable_xml_declaration or is_unicode: svg = svg.decode('utf-8') return svg def get_strokes(self): """Return a css snippet containing all stroke style options""" def stroke_dict_to_css(stroke, i=None): """Return a css style for the given option""" css = [ '%s.series%s {\n' % (self.id, '.serie-%d' % i if i is not None else '') ] for key in ('width', 'linejoin', 'linecap', 'dasharray', 'dashoffset'): if stroke.get(key): css.append(' stroke-%s: %s;\n' % (key, stroke[key])) css.append('}') return '\n'.join(css) css = [] if self.graph.stroke_style is not None: css.append(stroke_dict_to_css(self.graph.stroke_style)) for serie in self.graph.series: if serie.stroke_style is not None: css.append(stroke_dict_to_css(serie.stroke_style, serie.index)) for secondary_serie in self.graph.secondary_series: if secondary_serie.stroke_style is not None: css.append( stroke_dict_to_css( secondary_serie.stroke_style, secondary_serie.index ) ) return '\n'.join(css)
class Svg(object): '''Svg related methods''' def __init__(self, graph): '''Create the svg helper with the chart instance''' pass def add_styles(self): '''Add the css to the svg''' pass def add_scripts(self): '''Add the js to the svg''' pass def get_js_dict(): pass def json_default(o): pass def node(self, parent=None, tag='g', attrib=None, **extras): '''Make a new svg node''' pass def in_attrib_and_number(key): pass def transposable_node(self, parent=None, tag='g', attrib=None, **extras): '''Make a new svg node which can be transposed if horizontal''' pass def serie(self, serie): '''Make serie node''' pass def line(self, node, coords, close=False, **kwargs): '''Draw a svg line''' pass def slice( self, serie_node, node, radius, small_radius, angle, start_angle, center, val, i, metadata ): '''Draw a pie slice''' pass def gauge_background( self, serie_node, start_angle, center, radius, small_radius, end_angle, half_pie, max_value ): pass def solid_gauge( self, serie_node, node, radius, small_radius, angle, start_angle, center, val, i, metadata, half_pie, end_angle, max_value ): '''Draw a solid gauge slice and background slice''' pass def confidence_interval(self, node, x, low, high, width=7): pass def pre_render(self): '''Last things to do before rendering''' pass def draw_no_data(self): '''Write the no data text to the svg''' pass def render(self, is_unicode=False, pretty_print=False): '''Last thing to do before rendering''' pass def get_strokes(self): '''Return a css snippet containing all stroke style options''' pass def stroke_dict_to_css(stroke, i=None): '''Return a css style for the given option''' pass
20
15
26
2
23
1
4
0.05
1
10
0
0
15
6
15
15
483
55
411
90
382
21
221
79
201
9
1
3
83
143,775
Kozea/pygal
Kozea_pygal/pygal/table.py
pygal.table.HTML
class HTML(object): """Lower case adapter of lxml builder""" def __getattribute__(self, attr): """Get the uppercase builder attribute""" return getattr(builder, attr.upper())
class HTML(object): '''Lower case adapter of lxml builder''' def __getattribute__(self, attr): '''Get the uppercase builder attribute''' pass
2
2
3
0
2
1
1
0.67
1
0
0
0
1
0
1
1
6
1
3
2
1
2
3
2
1
1
1
0
1
143,776
Kozea/pygal
Kozea_pygal/pygal/table.py
pygal.table.Table
class Table(object): """Table generator class""" _dual = None def __init__(self, chart): """Init the table""" self.chart = chart def render(self, total=False, transpose=False, style=False): """Render the HTMTL table of the chart. `total` can be specified to include data sums `transpose` make labels becomes columns `style` include scoped style for the table """ self.chart.setup() ln = self.chart._len html = HTML() attrs = {} if style: attrs['id'] = 'table-%s' % uuid.uuid4() table = [] _ = lambda x: x if x is not None else '' if self.chart.x_labels: labels = [None] + list(self.chart.x_labels) if len(labels) < ln: labels += [None] * (ln + 1 - len(labels)) if len(labels) > ln + 1: labels = labels[:ln + 1] table.append(labels) if total: if len(table): table[0].append('Total') else: table.append([None] * (ln + 1) + ['Total']) acc = [0] * (ln + 1) for i, serie in enumerate(self.chart.all_series): row = [serie.title] if total: sum_ = 0 for j, value in enumerate(serie.values): if total: v = value or 0 acc[j] += v sum_ += v row.append(self.chart._format(serie, j)) if total: acc[-1] += sum_ row.append(self.chart._serie_format(serie, sum_)) table.append(row) width = ln + 1 if total: width += 1 table.append(['Total']) for val in acc: table[-1].append(self.chart._serie_format(serie, val)) # Align values len_ = max([len(r) for r in table] or [0]) for i, row in enumerate(table[:]): len_ = len(row) if len_ < width: table[i] = row + [None] * (width - len_) if not transpose: table = list(zip(*table)) thead = [] tbody = [] tfoot = [] if not transpose or self.chart.x_labels: # There's always series title but not always x_labels thead = [table[0]] tbody = table[1:] else: tbody = table if total: tfoot = [tbody[-1]] tbody = tbody[:-1] parts = [] if thead: parts.append( html.thead( *[html.tr(*[html.th(_(col)) for col in r]) for r in thead] ) ) if tbody: parts.append( html.tbody( *[html.tr(*[html.td(_(col)) for col in r]) for r in tbody] ) ) if tfoot: parts.append( html.tfoot( *[html.tr(*[html.th(_(col)) for col in r]) for r in tfoot] ) ) table = tostring(html.table(*parts, **attrs)) if style: if style is True: css = ''' #{{ id }} { border-collapse: collapse; border-spacing: 0; empty-cells: show; border: 1px solid #cbcbcb; } #{{ id }} td, #{{ id }} th { border-left: 1px solid #cbcbcb; border-width: 0 0 0 1px; margin: 0; padding: 0.5em 1em; } #{{ id }} td:first-child, #{{ id }} th:first-child { border-left-width: 0; } #{{ id }} thead, #{{ id }} tfoot { color: #000; text-align: left; vertical-align: bottom; } #{{ id }} thead { background: #e0e0e0; } #{{ id }} tfoot { background: #ededed; } #{{ id }} tr:nth-child(2n-1) td { background-color: #f2f2f2; } ''' else: css = style table = tostring( html.style(template(css, **attrs), scoped='scoped') ) + table table = table.decode('utf-8') self.chart.teardown() return table
class Table(object): '''Table generator class''' def __init__(self, chart): '''Init the table''' pass def render(self, total=False, transpose=False, style=False): '''Render the HTMTL table of the chart. `total` can be specified to include data sums `transpose` make labels becomes columns `style` include scoped style for the table ''' pass
3
3
74
9
58
11
13
0.19
1
4
1
0
2
1
2
2
154
20
118
25
115
22
78
25
75
24
1
3
25
143,777
Kozea/pygal
Kozea_pygal/docs/ext/pygal_sphinx_directives.py
pygal_sphinx_directives.PygalTable
class PygalTable(Directive): """Execute the given python file and puts its result in the document.""" required_arguments = 0 optional_arguments = 0 final_argument_whitespace = True has_content = True def run(self): self.content = list(self.content) content = list(self.content) content[-1] = 'rv = ' + content[-1] code = '\n'.join(content) scope = {'pygal': pygal} try: exec(code, scope) except Exception: print_exc() return [ docutils.nodes.system_message( 'An exception as occured during code parsing:' ' \n %s' % format_exc(), type='ERROR', source='/', level=3 ) ] rv = scope['rv'] return [docutils.nodes.raw('', rv, format='html')]
class PygalTable(Directive): '''Execute the given python file and puts its result in the document.''' def run(self): pass
2
1
23
2
21
0
2
0.04
1
2
0
1
1
1
1
1
30
3
26
11
24
1
18
11
16
2
1
1
2
143,778
Kozea/pygal
Kozea_pygal/docs/ext/pygal_sphinx_directives.py
pygal_sphinx_directives.PygalTableWithCode
class PygalTableWithCode(PygalTable): def run(self): node_list = super(PygalTableWithCode, self).run() node_list.extend( CodeBlock( self.name, ['python'], self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine ).run() ) return [docutils.nodes.compound('', *node_list)]
class PygalTableWithCode(PygalTable): def run(self): pass
2
0
11
1
10
0
1
0
1
1
0
0
1
0
1
2
12
1
11
3
9
0
5
3
3
1
2
0
1
143,779
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.DarkSolarizedStyle
class DarkSolarizedStyle(Style): """Dark solarized popular theme""" background = '#073642' plot_background = '#002b36' foreground = '#839496' foreground_strong = '#fdf6e3' foreground_subtle = '#657b83' opacity = '.66' opacity_hover = '.9' transition = '500ms ease-in' colors = ( '#b58900', '#cb4b16', '#dc322f', '#d33682', '#6c71c4', '#268bd2', '#2aa198', '#859900' )
class DarkSolarizedStyle(Style): '''Dark solarized popular theme''' pass
1
1
0
0
0
0
0
0.62
1
0
0
1
0
0
0
3
15
1
13
10
12
8
10
10
9
0
2
0
0
143,780
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.DarkStyle
class DarkStyle(Style): """A dark style (old default)""" background = 'black' plot_background = '#111' foreground = '#999' foreground_strong = '#eee' foreground_subtle = '#555' opacity = '.8' opacity_hover = '.4' transition = '250ms' colors = ( '#ff5995', '#b6e354', '#feed6c', '#8cedff', '#9e6ffe', '#899ca1', '#f8f8f2', '#bf4646', '#516083', '#f92672', '#82b414', '#fd971f', '#56c2d6', '#808384', '#8c54fe', '#465457' )
class DarkStyle(Style): '''A dark style (old default)'''
1
1
0
0
0
0
0
0.57
1
0
0
1
0
0
0
3
16
1
14
10
13
8
10
10
9
0
2
0
0
143,781
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.DarkGreenBlueStyle
class DarkGreenBlueStyle(Style): """A dark green and blue style""" background = '#000' plot_background = lighten('#000', 8) foreground = 'rgba(255, 255, 255, 0.9)' foreground_strong = 'rgba(255, 255, 255, 0.9)' foreground_subtle = 'rgba(255, 255, 255, 0.6)' opacity = '.55' opacity_hover = '.9' transition = '250ms ease-in' colors = ( lighten('#34B8F7', 15), '#7dcf30', '#247fab', darken('#7dcf30', 10), lighten('#247fab', 10), lighten('#7dcf30', 10), darken('#247fab', 10), '#fff' )
class DarkGreenBlueStyle(Style): '''A dark green and blue style''' pass
1
1
0
0
0
0
0
0.43
1
0
0
0
0
0
0
3
16
1
14
10
13
6
10
10
9
0
2
0
0
143,782
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.DarkGreenStyle
class DarkGreenStyle(Style): """A dark green style""" background = darken('#251e01', 3) plot_background = darken('#251e01', 1) foreground = 'rgba(255, 255, 255, 0.9)' foreground_strong = 'rgba(255, 255, 255, 0.9)' foreground_subtle = 'rgba(255, 255, 255, 0.6)' opacity = '.6' opacity_hover = '.9' transition = '250ms ease-in' colors = ( '#adde09', '#6e8c06', '#4a5e04', '#fcd202', '#C1E34D', lighten('#fcd202', 25) )
class DarkGreenStyle(Style): '''A dark green style''' pass
1
1
0
0
0
0
0
0.38
1
0
0
0
0
0
0
3
15
1
13
10
12
5
10
10
9
0
2
0
0
143,783
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.LightStyle
class LightStyle(Style): """A light style""" background = 'white' plot_background = 'rgba(0, 0, 255, 0.1)' foreground = 'rgba(0, 0, 0, 0.7)' foreground_strong = 'rgba(0, 0, 0, 0.9)' foreground_subtle = 'rgba(0, 0, 0, 0.5)' colors = ( '#242424', '#9f6767', '#92ac68', '#d0d293', '#9aacc3', '#bb77a4', '#77bbb5', '#777777' )
class LightStyle(Style): '''A light style''' pass
1
1
0
0
0
0
0
0.3
1
0
0
0
0
0
0
3
12
1
10
7
9
3
7
7
6
0
2
0
0
143,784
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.LightSolarizedStyle
class LightSolarizedStyle(DarkSolarizedStyle): """Light solarized popular theme""" background = '#fdf6e3' plot_background = '#eee8d5' foreground = '#657b83' foreground_strong = '#073642' foreground_subtle = '#073642'
class LightSolarizedStyle(DarkSolarizedStyle): '''Light solarized popular theme''' pass
1
1
0
0
0
0
0
1
1
0
0
0
0
0
0
3
8
1
6
6
5
6
6
6
5
0
3
0
0
143,785
Kozea/pygal
Kozea_pygal/docs/ext/pygal_sphinx_directives.py
pygal_sphinx_directives.PygalWithCode
class PygalWithCode(PygalDirective): def run(self): node_list = super(PygalWithCode, self).run() node_list.extend( CodeBlock( self.name, ['python'], self.options, self.content, self.lineno, self.content_offset, self.block_text, self.state, self.state_machine ).run() ) return [docutils.nodes.compound('', *node_list)]
class PygalWithCode(PygalDirective): def run(self): pass
2
0
11
1
10
0
1
0
1
1
0
0
1
0
1
2
12
1
11
3
9
0
5
3
3
1
2
0
1
143,786
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.DarkenStyle
class DarkenStyle(ParametricStyleBase): """Create a style by darkening the given color""" _op = 'darken'
class DarkenStyle(ParametricStyleBase): '''Create a style by darkening the given color''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
4
4
1
2
2
1
1
2
2
1
0
3
0
0
143,787
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.DesaturateStyle
class DesaturateStyle(ParametricStyleBase): """Create a style by desaturating the given color""" _op = 'desaturate'
class DesaturateStyle(ParametricStyleBase): '''Create a style by desaturating the given color''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
4
4
1
2
2
1
1
2
2
1
0
3
0
0
143,788
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.LightColorizedStyle
class LightColorizedStyle(Style): """A light colorized style""" background = '#f8f8f8' plot_background = lighten('#f8f8f8', 3) foreground = '#333' foreground_strong = '#666' foreground_subtle = 'rgba(0, 0 , 0, 0.5)' opacity = '.5' opacity_hover = '.9' transition = '250ms ease-in' colors = ( '#fe9592', '#534f4c', '#3ac2c0', '#a2a7a1', darken('#fe9592', 15), lighten('#534f4c', 15), lighten('#3ac2c0', 15), lighten('#a2a7a1', 15), lighten('#fe9592', 15), darken('#3ac2c0', 10) )
class LightColorizedStyle(Style): '''A light colorized style''' pass
1
1
0
0
0
0
0
0.57
1
0
0
0
0
0
0
3
16
1
14
10
13
8
10
10
9
0
2
0
0
143,789
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.LightGreenStyle
class LightGreenStyle(Style): """A light green style""" background = lighten('#f3f3f3', 3) plot_background = '#fff' foreground = '#333333' foreground_strong = '#666' foreground_subtle = '#222222' opacity = '.5' opacity_hover = '.9' transition = '250ms ease-in' colors = ( '#7dcf30', '#247fab', lighten('#7dcf30', 10), '#ccc', darken('#7dcf30', 15), '#ddd', lighten('#247fab', 10), darken('#247fab', 15) )
class LightGreenStyle(Style): '''A light green style''' pass
1
1
0
0
0
0
0
0.64
1
0
0
0
0
0
0
3
16
1
14
10
13
9
10
10
9
0
2
0
0
143,790
Kozea/pygal
Kozea_pygal/pygal/view.py
pygal.view.PolarThetaLogView
class PolarThetaLogView(View): """Logarithmic polar projection""" def __init__(self, width, height, box, aperture=pi / 3): """Create the view with a width an height and a box bounds""" super(PolarThetaLogView, self).__init__(width, height, box) self.aperture = aperture if not hasattr(box, '_tmin') or not hasattr(box, '_tmax'): raise Exception( 'Box must be set with set_polar_box for polar charts' ) self.log10_tmax = log10(self.box._tmax) if self.box._tmax > 0 else 0 self.log10_tmin = log10(self.box._tmin) if self.box._tmin > 0 else 0 if self.log10_tmin == self.log10_tmax: self.log10_tmax = self.log10_tmin + 1 def __call__(self, rhotheta): """Project rho and theta""" if None in rhotheta: return None, None rho, theta = rhotheta # Center case if theta == 0: return super(PolarThetaLogView, self).__call__((0, 0)) theta = self.box._tmin + (self.box._tmax - self.box._tmin) * ( log10(theta) - self.log10_tmin ) / (self.log10_tmax - self.log10_tmin) start = 3 * pi / 2 + self.aperture / 2 theta = start + (2 * pi - self.aperture) * (theta - self.box._tmin) / ( self.box._tmax - self.box._tmin ) return super(PolarThetaLogView, self).__call__((rho * cos(theta), rho * sin(theta)))
class PolarThetaLogView(View): '''Logarithmic polar projection''' def __init__(self, width, height, box, aperture=pi / 3): '''Create the view with a width an height and a box bounds''' pass def __call__(self, rhotheta): '''Project rho and theta''' pass
3
3
16
1
13
2
4
0.15
1
2
0
0
2
3
2
6
35
4
27
8
24
4
20
8
17
5
2
1
8
143,791
Kozea/pygal
Kozea_pygal/pygal/view.py
pygal.view.PolarLogView
class PolarLogView(View): """Logarithmic polar projection""" def __init__(self, width, height, box): """Create the view with a width an height and a box bounds""" super(PolarLogView, self).__init__(width, height, box) if not hasattr(box, '_rmin') or not hasattr(box, '_rmax'): raise Exception( 'Box must be set with set_polar_box for polar charts' ) self.log10_rmax = log10(self.box._rmax) self.log10_rmin = log10(self.box._rmin) if self.log10_rmin == self.log10_rmax: self.log10_rmax = self.log10_rmin + 1 def __call__(self, rhotheta): """Project rho and theta""" if None in rhotheta: return None, None rho, theta = rhotheta # Center case if rho == 0: return super(PolarLogView, self).__call__((0, 0)) rho = (self.box._rmax - self.box._rmin) * ( log10(rho) - self.log10_rmin ) / (self.log10_rmax - self.log10_rmin) return super(PolarLogView, self).__call__((rho * cos(theta), rho * sin(theta)))
class PolarLogView(View): '''Logarithmic polar projection''' def __init__(self, width, height, box): '''Create the view with a width an height and a box bounds''' pass def __call__(self, rhotheta): '''Project rho and theta''' pass
3
3
13
1
11
2
3
0.18
1
2
0
0
2
2
2
6
29
3
22
6
19
4
17
6
14
3
2
1
6
143,792
Kozea/pygal
Kozea_pygal/pygal/view.py
pygal.view.Margin
class Margin(object): """Class reprensenting a margin (top, right, left, bottom)""" def __init__(self, top, right, bottom, left): """Create the margin object from the top, right, left, bottom margin""" self.top = top self.right = right self.bottom = bottom self.left = left @property def x(self): """Helper for total x margin""" return self.left + self.right @property def y(self): """Helper for total y margin""" return self.top + self.bottom
class Margin(object): '''Class reprensenting a margin (top, right, left, bottom)''' def __init__(self, top, right, bottom, left): '''Create the margin object from the top, right, left, bottom margin''' pass @property def x(self): '''Helper for total x margin''' pass @property def y(self): '''Helper for total y margin''' pass
6
4
4
0
3
1
1
0.33
1
0
0
0
3
4
3
3
19
3
12
10
6
4
10
8
6
1
1
0
3
143,793
Kozea/pygal
Kozea_pygal/pygal/view.py
pygal.view.LogView
class LogView(View): """Y Logarithmic projection""" # Do not want to call the parent here def __init__(self, width, height, box): """Create the view with a width an height and a box bounds""" self.width = width self.height = height self.box = box self.log10_ymax = log10(self.box.ymax) if self.box.ymax > 0 else 0 self.log10_ymin = log10(self.box.ymin) if self.box.ymin > 0 else 0 if self.log10_ymin == self.log10_ymax: self.log10_ymax = self.log10_ymin + 1 self.box.fix(False) def y(self, y): """Project y""" if y is None or y <= 0 or self.log10_ymax - self.log10_ymin == 0: return 0 return ( self.height - self.height * (log10(y) - self.log10_ymin) / (self.log10_ymax - self.log10_ymin) )
class LogView(View): '''Y Logarithmic projection''' def __init__(self, width, height, box): '''Create the view with a width an height and a box bounds''' pass def y(self, y): '''Project y''' pass
3
3
9
0
8
1
3
0.24
1
0
0
1
2
5
2
6
23
2
17
8
14
4
14
8
11
4
2
1
6
143,794
Kozea/pygal
Kozea_pygal/pygal/view.py
pygal.view.HorizontalView
class HorizontalView(View): """Same as view but transposed""" def __init__(self, width, height, box): """Create the view with a width an height and a box bounds""" self._force_vertical = None self.width = width self.height = height self.box = box self.box.fix() self.box.swap() def x(self, x): """Project x as y""" if x is None: return None if self._force_vertical: return super(HorizontalView, self).x(x) return super(HorizontalView, self).y(x) def y(self, y): """Project y as x""" if y is None: return None if self._force_vertical: return super(HorizontalView, self).y(y) return super(HorizontalView, self).x(y)
class HorizontalView(View): '''Same as view but transposed''' def __init__(self, width, height, box): '''Create the view with a width an height and a box bounds''' pass def x(self, x): '''Project x as y''' pass def y(self, y): '''Project y as x''' pass
4
4
8
0
6
1
2
0.2
1
1
0
0
3
4
3
7
28
4
20
8
16
4
20
8
16
3
2
1
7
143,795
Kozea/pygal
Kozea_pygal/pygal/view.py
pygal.view.HorizontalLogView
class HorizontalLogView(XLogView): """Transposed Logarithmic projection""" # Do not want to call the parent here def __init__(self, width, height, box): """Create the view with a width an height and a box bounds""" self._force_vertical = None self.width = width self.height = height self.box = box self.log10_xmax = log10(self.box.ymax) if self.box.ymax > 0 else 0 self.log10_xmin = log10(self.box.ymin) if self.box.ymin > 0 else 0 if self.log10_xmin == self.log10_xmax: self.log10_xmax = self.log10_xmin + 1 self.box.fix(False) self.box.swap() def x(self, x): """Project x as y""" if x is None: return None if self._force_vertical: return super(HorizontalLogView, self).x(x) return super(XLogView, self).y(x) def y(self, y): """Project y as x""" if y is None: return None if self._force_vertical: return super(XLogView, self).y(y) return super(HorizontalLogView, self).x(y)
class HorizontalLogView(XLogView): '''Transposed Logarithmic projection''' def __init__(self, width, height, box): '''Create the view with a width an height and a box bounds''' pass def x(self, x): '''Project x as y''' pass def y(self, y): '''Project y as x''' pass
4
4
9
0
8
1
3
0.21
1
1
0
0
3
6
3
9
32
3
24
10
20
5
24
10
20
4
3
1
10
143,796
Kozea/pygal
Kozea_pygal/pygal/graph/base.py
pygal.graph.base.BaseGraph
class BaseGraph(object): """Chart internal behaviour related functions""" _adapters = [] def __init__(self, config=None, **kwargs): """Config preparation and various initialization""" if config: if isinstance(config, type): config = config() else: config = config.copy() else: config = Config() config(**kwargs) self.config = config self.state = None self.uuid = str(uuid4()) self.raw_series = [] self.xml_filters = [] def __setattr__(self, name, value): """Set an attribute on the class or in the state if there is one""" if name.startswith('__') or getattr(self, 'state', None) is None: super(BaseGraph, self).__setattr__(name, value) else: setattr(self.state, name, value) def __getattribute__(self, name): """Get an attribute from the class or from the state if there is one""" if name.startswith('__') or name == 'state' or getattr( self, 'state', None) is None or name not in self.state.__dict__: return super(BaseGraph, self).__getattribute__(name) return getattr(self.state, name) def prepare_values(self, raw, offset=0): """Prepare the values to start with sane values""" from pygal import Histogram from pygal.graph.map import BaseMap if self.zero == 0 and isinstance(self, BaseMap): self.zero = 1 if self.x_label_rotation: self.x_label_rotation %= 360 if self.y_label_rotation: self.y_label_rotation %= 360 for key in ('x_labels', 'y_labels'): if getattr(self, key): setattr(self, key, list(getattr(self, key))) if not raw: return adapters = list(self._adapters) or [lambda x: x] if self.logarithmic: for fun in not_zero, positive: if fun in adapters: adapters.remove(fun) adapters = adapters + [positive, not_zero] adapters = adapters + [decimal_to_float] self._adapt = reduce(compose, adapters) if not self.strict else ident self._x_adapt = reduce( compose, self._x_adapters ) if not self.strict and getattr(self, '_x_adapters', None) else ident series = [] raw = [( list(raw_values) if not isinstance(raw_values, dict) else raw_values, serie_config_kwargs ) for raw_values, serie_config_kwargs in raw] width = max([len(values) for values, _ in raw] + [len(self.x_labels or [])]) for raw_values, serie_config_kwargs in raw: metadata = {} values = [] if isinstance(raw_values, dict): if isinstance(self, BaseMap): raw_values = list(raw_values.items()) else: value_list = [None] * width for k, v in raw_values.items(): if k in (self.x_labels or []): value_list[self.x_labels.index(k)] = v raw_values = value_list for index, raw_value in enumerate(raw_values + ( (width - len(raw_values)) * [None] # aligning values if len(raw_values) < width else [])): if isinstance(raw_value, dict): raw_value = dict(raw_value) value = raw_value.pop('value', None) metadata[index] = raw_value else: value = raw_value # Fix this by doing this in charts class methods if isinstance(self, Histogram): if value is None: value = (None, None, None) elif not is_list_like(value): value = (value, self.zero, self.zero) elif len(value) == 2: value = (1, value[0], value[1]) value = list(map(self._adapt, value)) elif self._dual: if value is None: value = (None, None) elif not is_list_like(value): value = (value, self.zero) if self._x_adapt: value = ( self._x_adapt(value[0]), self._adapt(value[1]) ) if isinstance(self, BaseMap): value = (self._adapt(value[0]), value[1]) else: value = list(map(self._adapt, value)) else: value = self._adapt(value) values.append(value) serie_config = SerieConfig() serie_config( **dict((k, v) for k, v in self.state.__dict__.items() if k in dir(serie_config)) ) serie_config(**serie_config_kwargs) series.append( Serie(offset + len(series), values, serie_config, metadata) ) return series def setup(self, **kwargs): """Set up the transient state prior rendering""" # Keep labels in case of map if getattr(self, 'x_labels', None) is not None: self.x_labels = list(self.x_labels) if getattr(self, 'y_labels', None) is not None: self.y_labels = list(self.y_labels) self.state = State(self, **kwargs) if isinstance(self.style, type): self.style = self.style() self.series = self.prepare_values([ rs for rs in self.raw_series if not rs[1].get('secondary') ]) or [] self.secondary_series = self.prepare_values([ rs for rs in self.raw_series if rs[1].get('secondary') ], len(self.series)) or [] self.horizontal = getattr(self, 'horizontal', False) self.svg = Svg(self) self._x_labels = None self._y_labels = None self._x_2nd_labels = None self._y_2nd_labels = None self.nodes = {} self.margin_box = Margin( self.margin_top or self.margin, self.margin_right or self.margin, self.margin_bottom or self.margin, self.margin_left or self.margin ) self._box = Box() self.view = None if self.logarithmic and self.zero == 0: # Explicit min to avoid interpolation dependency positive_values = list( filter( lambda x: x > 0, [ val[1] or 1 if self._dual else val for serie in self.series for val in serie.safe_values ] ) ) self.zero = min(positive_values or (1, )) or 1 if self._len < 3: self.interpolate = None self._draw() self.svg.pre_render() def teardown(self): """Remove the transient state after rendering""" if os.getenv('PYGAL_KEEP_STATE'): return del self.state self.state = None def _repr_svg_(self): """Display svg in IPython notebook""" return self.render(disable_xml_declaration=True) def _repr_png_(self): """Display png in IPython notebook""" return self.render_to_png()
class BaseGraph(object): '''Chart internal behaviour related functions''' def __init__(self, config=None, **kwargs): '''Config preparation and various initialization''' pass def __setattr__(self, name, value): '''Set an attribute on the class or in the state if there is one''' pass def __getattribute__(self, name): '''Get an attribute from the class or from the state if there is one''' pass def prepare_values(self, raw, offset=0): '''Prepare the values to start with sane values''' pass def setup(self, **kwargs): '''Set up the transient state prior rendering''' pass def teardown(self): '''Remove the transient state after rendering''' pass def _repr_svg_(self): '''Display svg in IPython notebook''' pass def _repr_png_(self): '''Display png in IPython notebook''' pass
9
9
24
2
20
2
6
0.08
1
17
9
1
8
24
8
8
201
25
164
50
153
13
122
48
111
30
1
5
48
143,797
Kozea/pygal
Kozea_pygal/pygal/view.py
pygal.view.Box
class Box(object): """Chart boundings""" margin = .02 def __init__(self, xmin=0, ymin=0, xmax=1, ymax=1): """ Create the chart bounds with min max horizontal and vertical values """ self._xmin = xmin self._ymin = ymin self._xmax = xmax self._ymax = ymax def set_polar_box(self, rmin=0, rmax=1, tmin=0, tmax=2 * pi): """Helper for polar charts""" self._rmin = rmin self._rmax = rmax self._tmin = tmin self._tmax = tmax self.xmin = self.ymin = rmin - rmax self.xmax = self.ymax = rmax - rmin @property def xmin(self): """X minimum getter""" return self._xmin @xmin.setter def xmin(self, value): """X minimum setter""" if value is not None: self._xmin = value @property def ymin(self): """Y minimum getter""" return self._ymin @ymin.setter def ymin(self, value): """Y minimum setter""" if value is not None: self._ymin = value @property def xmax(self): """X maximum getter""" return self._xmax @xmax.setter def xmax(self, value): """X maximum setter""" if value is not None: self._xmax = value @property def ymax(self): """Y maximum getter""" return self._ymax @ymax.setter def ymax(self, value): """Y maximum setter""" if value or self.ymin: self._ymax = value @property def width(self): """Helper for box width""" return self.xmax - self.xmin @property def height(self): """Helper for box height""" return self.ymax - self.ymin def swap(self): """Return the box (for horizontal graphs)""" self.xmin, self.ymin = self.ymin, self.xmin self.xmax, self.ymax = self.ymax, self.xmax def fix(self, with_margin=True): """Correct box when no values and take margin in account""" if not self.width: self.xmax = self.xmin + 1 if not self.height: self.ymin /= 2 self.ymax += self.ymin xmargin = self.margin * self.width self.xmin -= xmargin self.xmax += xmargin if with_margin: ymargin = self.margin * self.height self.ymin -= ymargin self.ymax += ymargin
class Box(object): '''Chart boundings''' def __init__(self, xmin=0, ymin=0, xmax=1, ymax=1): ''' Create the chart bounds with min max horizontal and vertical values ''' pass def set_polar_box(self, rmin=0, rmax=1, tmin=0, tmax=2 * pi): '''Helper for polar charts''' pass @property def xmin(self): '''X minimum getter''' pass @xmin.setter def xmin(self): '''X minimum setter''' pass @property def ymin(self): '''Y minimum getter''' pass @ymin.setter def ymin(self): '''Y minimum setter''' pass @property def xmax(self): '''X maximum getter''' pass @xmax.setter def xmax(self): '''X maximum setter''' pass @property def ymax(self): '''Y maximum getter''' pass @ymax.setter def ymax(self): '''Y maximum setter''' pass @property def width(self): '''Helper for box width''' pass @property def height(self): '''Helper for box height''' pass def swap(self): '''Return the box (for horizontal graphs)''' pass def fix(self, with_margin=True): '''Correct box when no values and take margin in account''' pass
25
15
5
0
4
1
2
0.28
1
0
0
0
14
8
14
14
97
15
64
36
39
18
54
26
39
4
1
1
21
143,798
Kozea/pygal
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kozea_pygal/pygal/test/test_config.py
pygal.test.test_config.test_config_behaviours.LineConfig
class LineConfig(Config): show_legend = False fill = True pretty_print = True no_prefix = True x_labels = ['a', 'b', 'c']
class LineConfig(Config): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
19
6
0
6
6
5
0
6
6
5
0
6
0
0
143,799
Kozea/pygal
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kozea_pygal/pygal/test/test_config.py
pygal.test.test_config.test_config_alterations_kwargs.LineConfig
class LineConfig(Config): no_prefix = True show_legend = False fill = True pretty_print = True x_labels = ['a', 'b', 'c']
class LineConfig(Config): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
19
6
0
6
6
5
0
6
6
5
0
6
0
0
143,800
Kozea/pygal
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kozea_pygal/demo/moulinrouge/tests.py
moulinrouge.tests.get_test_routes.test_horizontal_force_for.H
class H(CHARTS_BY_NAME[chart], HorizontalGraph): pass
class H(CHARTS_BY_NAME[chart], HorizontalGraph): pass
1
0
0
0
0
0
0
0
2
0
0
0
0
0
0
74
2
0
2
1
1
0
2
1
1
0
5
0
0
143,801
Kozea/pygal
Kozea_pygal/pygal/util.py
pygal.util.cached_property
class cached_property(object): """Memoize a property""" def __init__(self, getter, doc=None): """Initialize the decorator""" self.getter = getter self.__module__ = getter.__module__ self.__name__ = getter.__name__ self.__doc__ = doc or getter.__doc__ def __get__(self, obj, type_=None): """ Get descriptor calling the property function and replacing it with its value or on state if we are in the transient state. """ if obj is None: return self value = self.getter(obj) if hasattr(obj, 'state'): setattr(obj.state, self.__name__, value) else: obj.__dict__[self.__name__] = self.getter(obj) return value
class cached_property(object): '''Memoize a property''' def __init__(self, getter, doc=None): '''Initialize the decorator''' pass def __get__(self, obj, type_=None): ''' Get descriptor calling the property function and replacing it with its value or on state if we are in the transient state. ''' pass
3
3
10
0
7
3
2
0.4
1
0
0
0
2
4
2
2
23
2
15
8
12
6
14
8
11
3
1
1
4
143,802
Kozea/pygal
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kozea_pygal/demo/moulinrouge/tests.py
moulinrouge.tests.get_test_routes.test_config.LolConfig
class LolConfig(Config): js = ['http://l:2343/2.0.x/pygal-tooltips.js']
class LolConfig(Config): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
19
2
0
2
2
1
0
2
2
1
0
6
0
0
143,803
Kozea/pygal
Kozea_pygal/pygal/test/test_xml_filters.py
pygal.test.test_xml_filters.ChangeBarsXMLFilter
class ChangeBarsXMLFilter(object): """xml filter that insert a subplot""" def __init__(self, a, b): """Generate data""" self.data = [b[i] - a[i] for i in range(len(a))] def __call__(self, T): """Apply the filter on the tree""" subplot = Bar( legend_at_bottom=True, explicit_size=True, width=800, height=150 ) subplot.add("Difference", self.data) subplot = subplot.render_tree() subplot = subplot.findall("g")[0] T.insert(2, subplot) T.findall("g")[1].set('transform', 'translate(0,150), scale(1,0.75)') return T
class ChangeBarsXMLFilter(object): '''xml filter that insert a subplot''' def __init__(self, a, b): '''Generate data''' pass def __call__(self, T): '''Apply the filter on the tree''' pass
3
3
7
0
6
1
1
0.23
1
2
1
0
2
1
2
2
18
2
13
5
10
3
11
5
8
1
1
0
2
143,804
Kozea/pygal
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/Kozea_pygal/pygal/test/test_util.py
pygal.test.test_util.test_format.Object
class Object(object): pass
class Object(object): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
143,805
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.SolidColorStyle
class SolidColorStyle(Style): """A light style with strong colors""" background = '#FFFFFF' plot_background = '#FFFFFF' foreground = '#000000' foreground_strong = '#000000' foreground_subtle = '#828282' opacity = '.8' opacity_hover = '.9' transition = '400ms ease-in' colors = ( '#FF9900', '#DC3912', '#4674D1', '#109618', '#990099', '#0099C6', '#DD4477', '#74B217', '#B82E2E', '#316395', '#994499' )
class SolidColorStyle(Style): '''A light style with strong colors''' pass
1
1
0
0
0
0
0
0.62
1
0
0
0
0
0
0
3
15
1
13
10
12
8
10
10
9
0
2
0
0
143,806
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.Style
class Style(object): """Styling class containing colors for the css generation""" plot_background = 'rgba(255, 255, 255, 1)' background = 'rgba(249, 249, 249, 1)' value_background = 'rgba(229, 229, 229, 1)' foreground = 'rgba(0, 0, 0, .87)' foreground_strong = 'rgba(0, 0, 0, 1)' foreground_subtle = 'rgba(0, 0, 0, .54)' # Monospaced font is highly encouraged font_family = ('Consolas, "Liberation Mono", Menlo, Courier, monospace') label_font_family = None major_label_font_family = None value_font_family = None value_label_font_family = None tooltip_font_family = None title_font_family = None legend_font_family = None no_data_font_family = None label_font_size = 10 major_label_font_size = 10 value_font_size = 16 value_label_font_size = 10 tooltip_font_size = 14 title_font_size = 16 legend_font_size = 14 no_data_font_size = 64 # Guide line dash array style guide_stroke_dasharray = '4,4' major_guide_stroke_dasharray = '6,6' guide_stroke_color = 'black' major_guide_stroke_color = 'black' opacity = '.7' opacity_hover = '.8' stroke_opacity = '.8' stroke_width = '1' stroke_opacity_hover = '.9' stroke_width_hover = '4' dot_opacity = '1' transition = '150ms' colors = ( '#F44336', # 0 '#3F51B5', # 4 '#009688', # 8 '#FFC107', # 13 '#FF5722', # 15 '#9C27B0', # 2 '#03A9F4', # 6 '#8BC34A', # 10 '#FF9800', # 14 '#E91E63', # 1 '#2196F3', # 5 '#4CAF50', # 9 '#FFEB3B', # 12 '#673AB7', # 3 '#00BCD4', # 7 '#CDDC39', # 11b '#9E9E9E', # 17 '#607D8B', # 18 ) value_colors = () ci_colors = () def __init__(self, **kwargs): """Create the style""" self.__dict__.update(kwargs) self._google_fonts = set() if self.font_family.startswith('googlefont:'): self.font_family = self.font_family.replace('googlefont:', '') self._google_fonts.add(self.font_family.split(',')[0].strip()) for name in dir(self): if name.endswith('_font_family'): fn = getattr(self, name) if fn is None: setattr(self, name, self.font_family) elif fn.startswith('googlefont:'): setattr(self, name, fn.replace('googlefont:', '')) self._google_fonts.add( getattr(self, name).split(',')[0].strip() ) def get_colors(self, prefix, len_): """Get the css color list""" def color(tupl): """Make a color css""" return (( '%s.color-{0}, %s.color-{0} a:visited {{\n' ' stroke: {1};\n' ' fill: {1};\n' '}}\n' ) % (prefix, prefix)).format(*tupl) def value_color(tupl): """Make a value color css""" return (( '%s .text-overlay .color-{0} text {{\n' ' fill: {1};\n' '}}\n' ) % (prefix, )).format(*tupl) def ci_color(tupl): """Make a value color css""" if not tupl[1]: return '' return (('%s .color-{0} .ci {{\n' ' stroke: {1};\n' '}}\n') % (prefix, )).format(*tupl) if len(self.colors) < len_: missing = len_ - len(self.colors) cycles = 1 + missing // len(self.colors) colors = [] for i in range(0, cycles + 1): for color_ in self.colors: colors.append(darken(color_, 33 * i / cycles)) if len(colors) >= len_: break else: continue break else: colors = self.colors[:len_] # Auto compute foreground value color when color is missing value_colors = [] for i in range(len_): if i < len(self.value_colors) and self.value_colors[i] is not None: value_colors.append(self.value_colors[i]) else: value_colors.append( 'white' if is_foreground_light(colors[i]) else 'black' ) return '\n'.join( chain( map(color, enumerate(colors)), map(value_color, enumerate(value_colors)), map(ci_color, enumerate(self.ci_colors)) ) ) def to_dict(self): """Convert instance to a serializable mapping.""" config = {} for attr in dir(self): if not attr.startswith('_'): value = getattr(self, attr) if not hasattr(value, '__call__'): config[attr] = value return config
class Style(object): '''Styling class containing colors for the css generation''' def __init__(self, **kwargs): '''Create the style''' pass def get_colors(self, prefix, len_): '''Get the css color list''' pass def color(tupl): '''Make a color css''' pass def value_color(tupl): '''Make a value color css''' pass def ci_color(tupl): '''Make a value color css''' pass def to_dict(self): '''Convert instance to a serializable mapping.''' pass
7
7
18
1
15
2
4
0.21
1
5
0
14
3
1
3
3
161
20
131
57
124
28
88
57
81
7
1
4
21
143,807
Kozea/pygal
Kozea_pygal/pygal/config.py
pygal.config.BaseConfig
class BaseConfig(MetaConfig('ConfigBase', (object, ), {})): """ This class holds the common method for configs. A config object can be instanciated with keyword arguments and updated on call with keyword arguments. """ def __init__(self, **kwargs): """Can be instanciated with config kwargs""" for k in dir(self): v = getattr(self, k) if (k not in self.__dict__ and not k.startswith('_') and not hasattr(v, '__call__')): if isinstance(v, Key): if v.is_list and v.value is not None: v = list(v.value) else: v = v.value setattr(self, k, v) self._update(kwargs) def __call__(self, **kwargs): """Can be updated with kwargs""" self._update(kwargs) def _update(self, kwargs): """Update the config with the given dictionary""" from pygal.util import merge dir_self_set = set(dir(self)) merge( self.__dict__, dict([(k, v) for (k, v) in kwargs.items() if not k.startswith('_') and k in dir_self_set]) ) def to_dict(self): """Export a JSON serializable dictionary of the config""" config = {} for attr in dir(self): if not attr.startswith('__'): value = getattr(self, attr) if hasattr(value, 'to_dict'): config[attr] = value.to_dict() elif not hasattr(value, '__call__'): config[attr] = value return config def copy(self): """Copy this config object into another""" return deepcopy(self)
class BaseConfig(MetaConfig('ConfigBase', (object, ), {})): ''' This class holds the common method for configs. A config object can be instanciated with keyword arguments and updated on call with keyword arguments. ''' def __init__(self, **kwargs): '''Can be instanciated with config kwargs''' pass def __call__(self, **kwargs): '''Can be updated with kwargs''' pass def _update(self, kwargs): '''Update the config with the given dictionary''' pass def to_dict(self): '''Export a JSON serializable dictionary of the config''' pass def copy(self): '''Copy this config object into another''' pass
6
6
8
0
7
1
3
0.29
1
4
1
1
5
0
5
19
51
6
35
13
28
10
28
13
21
5
3
4
13
143,808
Kozea/pygal
Kozea_pygal/pygal/formatters.py
pygal.formatters.IsoDateTime
class IsoDateTime(Formatter): """Iso format datetimes""" def __call__(self, val): if val is None: return '' return val.isoformat()
class IsoDateTime(Formatter): '''Iso format datetimes''' def __call__(self, val): pass
2
1
4
0
4
0
2
0.2
1
0
0
1
1
0
1
1
7
1
5
2
3
1
5
2
3
2
2
1
2
143,809
Kozea/pygal
Kozea_pygal/pygal/formatters.py
pygal.formatters.Integer
class Integer(Formatter): """Cast number to integer""" def __call__(self, val): if val is None: return '' return '%d' % val
class Integer(Formatter): '''Cast number to integer''' def __call__(self, val): pass
2
1
4
0
4
0
2
0.2
1
0
0
0
1
0
1
1
7
1
5
2
3
1
5
2
3
2
2
1
2
143,810
Kozea/pygal
Kozea_pygal/pygal/formatters.py
pygal.formatters.HumanReadable
class HumanReadable(Formatter): """Format a number to engineer scale""" ORDERS = "yzafpnµm kMGTPEZY" def __init__(self, none_char='∅'): self.none_char = none_char def __call__(self, val): if val is None: return self.none_char order = val and int(floor(log(abs(val)) / log(1000))) orders = self.ORDERS.split(" ")[int(order > 0)] if order == 0 or order > len(orders): return float_format(val / (1000**int(order))) return ( float_format(val / (1000**int(order))) + orders[int(order) - int(order > 0)] )
class HumanReadable(Formatter): '''Format a number to engineer scale''' def __init__(self, none_char='∅'): pass def __call__(self, val): pass
3
1
7
0
7
0
2
0.07
1
1
0
0
2
1
2
2
18
2
15
7
12
1
12
7
9
3
2
1
4
143,811
Kozea/pygal
Kozea_pygal/pygal/formatters.py
pygal.formatters.Formatter
class Formatter(object): pass
class Formatter(object): pass
1
0
0
0
0
0
0
0
1
0
0
5
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
143,812
Kozea/pygal
Kozea_pygal/pygal/formatters.py
pygal.formatters.Default
class Default(Significant, IsoDateTime, Raw): """Try to guess best format from type""" def __call__(self, val): if val is None: return '' if isinstance(val, (int, float)): return Significant.__call__(self, val) if isinstance(val, (date, time, datetime)): return IsoDateTime.__call__(self, val) return Raw.__call__(self, val)
class Default(Significant, IsoDateTime, Raw): '''Try to guess best format from type''' def __call__(self, val): pass
2
1
8
0
8
0
4
0.11
3
5
0
0
1
0
1
5
11
1
9
2
7
1
9
2
7
4
3
1
4
143,813
Kozea/pygal
Kozea_pygal/pygal/etree.py
pygal.etree.Etree
class Etree(object): """Etree wrapper using lxml.etree or standard xml.etree""" def __init__(self): """Create the wrapper""" from xml.etree import ElementTree as _py_etree self._py_etree = _py_etree try: from lxml import etree as _lxml_etree self._lxml_etree = _lxml_etree except ImportError: self._lxml_etree = None if os.getenv('NO_LXML', None): self._etree = self._py_etree else: self._etree = self._lxml_etree or self._py_etree self.lxml = self._etree is self._lxml_etree def __getattribute__(self, attr): """Retrieve attr from current active etree implementation""" if (attr not in object.__getattribute__(self, '__dict__') and attr not in Etree.__dict__): return object.__getattribute__(self._etree, attr) return object.__getattribute__(self, attr) def to_lxml(self): """Force lxml.etree to be used""" self._etree = self._lxml_etree self.lxml = True def to_etree(self): """Force xml.etree to be used""" self._etree = self._py_etree self.lxml = False
class Etree(object): '''Etree wrapper using lxml.etree or standard xml.etree''' def __init__(self): '''Create the wrapper''' pass def __getattribute__(self, attr): '''Retrieve attr from current active etree implementation''' pass def to_lxml(self): '''Force lxml.etree to be used''' pass def to_etree(self): '''Force xml.etree to be used''' pass
5
5
7
0
6
1
2
0.2
1
1
0
0
4
4
4
4
35
5
25
11
18
5
23
11
16
3
1
1
7
143,814
Kozea/pygal
Kozea_pygal/pygal/config.py
pygal.config.SerieConfig
class SerieConfig(CommonConfig): """Class holding serie config values""" title = Key( None, str, "Look", "Serie title.", "Leave it to None to disable title." ) secondary = Key( False, bool, "Misc", "Set it to put the serie in a second axis" )
class SerieConfig(CommonConfig): '''Class holding serie config values''' pass
1
1
0
0
0
0
0
0.14
1
0
0
0
0
0
0
19
10
2
7
3
6
1
3
3
2
0
5
0
0
143,815
Kozea/pygal
Kozea_pygal/pygal/config.py
pygal.config.MetaConfig
class MetaConfig(type): """Config metaclass. Used to get the key name and set it on the value.""" def __new__(mcs, classname, bases, classdict): """Get the name of the key and set it on the key""" for k, v in classdict.items(): if isinstance(v, Key): v.name = k return type.__new__(mcs, classname, bases, classdict)
class MetaConfig(type): '''Config metaclass. Used to get the key name and set it on the value.''' def __new__(mcs, classname, bases, classdict): '''Get the name of the key and set it on the key''' pass
2
2
7
1
5
1
3
0.33
1
1
1
1
1
0
1
14
10
2
6
3
4
2
6
3
4
3
2
2
3
143,816
Kozea/pygal
Kozea_pygal/pygal/config.py
pygal.config.Key
class Key(object): """ Represents a config parameter. A config parameter has a name, a default value, a type, a category, a documentation, an optional longer documentatation and an optional subtype for list style option. Most of these informations are used in cabaret to auto generate forms representing these options. """ _categories = [] def __init__( self, default_value, type_, category, doc, subdoc="", subtype=None ): """Create a configuration key""" self.value = default_value self.type = type_ self.doc = doc self.category = category self.subdoc = subdoc self.subtype = subtype self.name = "Unbound" if category not in self._categories: self._categories.append(category) CONFIG_ITEMS.append(self) def __repr__(self): """ Make a documentation repr. This is a hack to generate doc from inner doc """ return """ Type: %s%s Default: %r %s%s """ % ( self.type.__name__, (' of %s' % self.subtype.__name__) if self.subtype else '', self.value, self.doc, (' %s' % self.subdoc) if self.subdoc else '' ) @property def is_boolean(self): """Return `True` if this parameter is a boolean""" return self.type == bool @property def is_numeric(self): """Return `True` if this parameter is numeric (int or float)""" return self.type in (int, float) @property def is_string(self): """Return `True` if this parameter is a string""" return self.type == str @property def is_dict(self): """Return `True` if this parameter is a mapping""" return self.type == dict @property def is_list(self): """Return `True` if this parameter is a list""" return self.type == list def coerce(self, value): """Cast a string into this key type""" if self.type == Style: return value elif self.type == list: return self.type( map(self.subtype, map(lambda x: x.strip(), value.split(','))) ) elif self.type == dict: rv = {} for pair in value.split(','): key, val = pair.split(':') key = key.strip() val = val.strip() try: rv[key] = self.subtype(val) except Exception: rv[key] = val return rv return self.type(value)
class Key(object): ''' Represents a config parameter. A config parameter has a name, a default value, a type, a category, a documentation, an optional longer documentatation and an optional subtype for list style option. Most of these informations are used in cabaret to auto generate forms representing these options. ''' def __init__( self, default_value, type_, category, doc, subdoc="", subtype=None ): '''Create a configuration key''' pass def __repr__(self): ''' Make a documentation repr. This is a hack to generate doc from inner doc ''' pass @property def is_boolean(self): '''Return `True` if this parameter is a boolean''' pass @property def is_numeric(self): '''Return `True` if this parameter is numeric (int or float)''' pass @property def is_string(self): '''Return `True` if this parameter is a string''' pass @property def is_dict(self): '''Return `True` if this parameter is a mapping''' pass @property def is_list(self): '''Return `True` if this parameter is a list''' pass def coerce(self, value): '''Cast a string into this key type''' pass
14
9
8
0
7
1
2
0.32
1
9
1
0
8
7
8
8
90
12
59
27
43
19
40
20
31
6
1
3
16
143,817
Kozea/pygal
Kozea_pygal/pygal/config.py
pygal.config.Config
class Config(CommonConfig): """Class holding config values""" style = Key( DefaultStyle, Style, "Style", "Style holding values injected in css" ) css = Key( ('file://style.css', 'file://graph.css'), list, "Style", "List of css file", "It can be any uri from file:///tmp/style.css to //domain/style.css", str ) classes = Key(('pygal-chart', ), list, "Style", "Classes of the root svg node", str) defs = Key([], list, "Misc", "Extraneous defs to be inserted in svg", "Useful for adding gradients / patterns…", str) # Look # title = Key( None, str, "Look", "Graph title.", "Leave it to None to disable title." ) x_title = Key( None, str, "Look", "Graph X-Axis title.", "Leave it to None to disable X-Axis title." ) y_title = Key( None, str, "Look", "Graph Y-Axis title.", "Leave it to None to disable Y-Axis title." ) width = Key(800, int, "Look", "Graph width") height = Key(600, int, "Look", "Graph height") show_x_guides = Key( False, bool, "Look", "Set to true to always show x guide lines" ) show_y_guides = Key( True, bool, "Look", "Set to false to hide y guide lines" ) show_legend = Key(True, bool, "Look", "Set to false to remove legend") legend_at_bottom = Key( False, bool, "Look", "Set to true to position legend at bottom" ) legend_at_bottom_columns = Key( None, int, "Look", "Set to true to position legend at bottom" ) legend_box_size = Key(12, int, "Look", "Size of legend boxes") rounded_bars = Key( None, int, "Look", "Set this to the desired radius in px" ) stack_from_top = Key( False, bool, "Look", "Stack from top to zero, this makes the stacked " "data match the legend order" ) spacing = Key(10, int, "Look", "Space between titles/legend/axes") margin = Key(20, int, "Look", "Margin around chart") margin_top = Key(None, int, "Look", "Margin around top of chart") margin_right = Key(None, int, "Look", "Margin around right of chart") margin_bottom = Key(None, int, "Look", "Margin around bottom of chart") margin_left = Key(None, int, "Look", "Margin around left of chart") tooltip_border_radius = Key(0, int, "Look", "Tooltip border radius") tooltip_fancy_mode = Key( True, bool, "Look", "Fancy tooltips", "Print legend, x label in tooltip and use serie color for value." ) inner_radius = Key( 0, float, "Look", "Piechart inner radius (donut), must be <.9" ) half_pie = Key(False, bool, "Look", "Create a half-pie chart") x_labels = Key( None, list, "Label", "X labels, must have same len than data.", "Leave it to None to disable x labels display.", str ) x_labels_major = Key( None, list, "Label", "X labels that will be marked major.", subtype=str ) x_labels_major_every = Key( None, int, "Label", "Mark every n-th x label as major." ) x_labels_major_count = Key( None, int, "Label", "Mark n evenly distributed labels as major." ) show_x_labels = Key(True, bool, "Label", "Set to false to hide x-labels") show_minor_x_labels = Key( True, bool, "Label", "Set to false to hide x-labels not marked major" ) y_labels = Key( None, list, "Label", "You can specify explicit y labels", "Must be a list of numbers", float ) y_labels_major = Key( None, list, "Label", "Y labels that will be marked major. Default: auto", subtype=str ) y_labels_major_every = Key( None, int, "Label", "Mark every n-th y label as major." ) y_labels_major_count = Key( None, int, "Label", "Mark n evenly distributed y labels as major." ) show_minor_y_labels = Key( True, bool, "Label", "Set to false to hide y-labels not marked major" ) show_y_labels = Key(True, bool, "Label", "Set to false to hide y-labels") x_label_rotation = Key( 0, int, "Label", "Specify x labels rotation angles", "in degrees" ) y_label_rotation = Key( 0, int, "Label", "Specify y labels rotation angles", "in degrees" ) missing_value_fill_truncation = Key( "x", str, "Look", "Filled series with missing x and/or y values at the end of a series " "are closed at the first value with a missing " "'x' (default), 'y' or 'either'" ) # Value # x_value_formatter = Key( formatters.default, callable, "Value", "A function to convert abscissa numeric value to strings " "(used in XY and Date charts)" ) value_formatter = Key( formatters.default, callable, "Value", "A function to convert ordinate numeric value to strings" ) logarithmic = Key( False, bool, "Value", "Display values in logarithmic scale" ) interpolate = Key( None, str, "Value", "Interpolation", "May be %s" % ' or '.join(INTERPOLATIONS) ) interpolation_precision = Key( 250, int, "Value", "Number of interpolated points between two values" ) interpolation_parameters = Key( {}, dict, "Value", "Various parameters for parametric interpolations", "ie: For hermite interpolation, you can set the cardinal tension with" "{'type': 'cardinal', 'c': .5}", int ) box_mode = Key( 'extremes', str, "Value", "Sets the mode to be used. " "(Currently only supported on box plot)", "May be %s" % ' or '.join(["1.5IQR", "extremes", "tukey", "stdev", "pstdev"]) ) order_min = Key( None, int, "Value", "Minimum order of scale, defaults to None" ) min_scale = Key( 4, int, "Value", "Minimum number of scale graduation for auto scaling" ) max_scale = Key( 16, int, "Value", "Maximum number of scale graduation for auto scaling" ) range = Key( None, list, "Value", "Explicitly specify min and max of values", "(ie: (0, 100))", int ) secondary_range = Key( None, list, "Value", "Explicitly specify min and max of secondary values", "(ie: (0, 100))", int ) xrange = Key( None, list, "Value", "Explicitly specify min and max of x values " "(used in XY and Date charts)", "(ie: (0, 100))", int ) include_x_axis = Key(False, bool, "Value", "Always include x axis") zero = Key( 0, int, "Value", "Set the ordinate zero value", "Useful for filling to another base than abscissa" ) # Text # no_data_text = Key( "No data", str, "Text", "Text to display when no data is given" ) print_values = Key(False, bool, "Text", "Display values as text over plot") dynamic_print_values = Key( False, bool, "Text", "Show values only on hover" ) print_values_position = Key( 'center', str, "Text", "Customize position of `print_values`. " "(For bars: `top`, `center` or `bottom`)" ) print_zeroes = Key(True, bool, "Text", "Display zero values as well") print_labels = Key(False, bool, "Text", "Display value labels") truncate_legend = Key( None, int, "Text", "Legend string length truncation threshold", "None = auto, Negative for none" ) truncate_label = Key( None, int, "Text", "Label string length truncation threshold", "None = auto, Negative for none" ) # Misc # js = Key(('//kozea.github.io/pygal.js/2.0.x/pygal-tooltips.min.js', ), list, "Misc", "List of js file", "It can be any uri from file:///tmp/ext.js to //domain/ext.js", str) disable_xml_declaration = Key( False, bool, "Misc", "Don't write xml declaration and return str instead of string", "useful for writing output directly in html" ) force_uri_protocol = Key( 'https', str, "Misc", "Default uri protocol", "Default protocol for external files. " "Can be set to None to use a // uri" ) explicit_size = Key( False, bool, "Misc", "Write width and height attributes" ) pretty_print = Key(False, bool, "Misc", "Pretty print the svg") strict = Key( False, bool, "Misc", "If True don't try to adapt / filter wrong values" ) no_prefix = Key(False, bool, "Misc", "Don't prefix css") inverse_y_axis = Key(False, bool, "Misc", "Inverse Y axis direction")
class Config(CommonConfig): '''Class holding config values''' pass
1
1
0
0
0
0
0
0.02
1
0
0
5
0
0
0
19
295
73
217
74
216
5
74
74
73
0
5
0
0
143,818
Kozea/pygal
Kozea_pygal/pygal/config.py
pygal.config.CommonConfig
class CommonConfig(BaseConfig): """Class holding options used in both chart and serie configuration""" stroke = Key( True, bool, "Look", "Line dots (set it to false to get a scatter plot)" ) show_dots = Key(True, bool, "Look", "Set to false to remove dots") show_only_major_dots = Key( False, bool, "Look", "Set to true to show only major dots according to their majored label" ) dots_size = Key(2.5, float, "Look", "Radius of the dots") fill = Key(False, bool, "Look", "Fill areas under lines") stroke_style = Key( None, dict, "Look", "Stroke style of serie element.", "This is a dict which can contain a " "'width', 'linejoin', 'linecap', 'dasharray' " "and 'dashoffset'" ) rounded_bars = Key( None, int, "Look", "Set this to the desired radius in px (for Bar-like charts)" ) inner_radius = Key( 0, float, "Look", "Piechart inner radius (donut), must be <.9" ) allow_interruptions = Key( False, bool, "Look", "Break lines on None values" ) formatter = Key( None, callable, "Value", "A function to convert raw value to strings for this chart or serie", "Default to value_formatter in most charts, it depends on dual charts." "(Can be overriden by value with the formatter metadata.)" )
class CommonConfig(BaseConfig): '''Class holding options used in both chart and serie configuration''' pass
1
1
0
0
0
0
0
0.03
1
0
0
2
0
0
0
19
44
10
33
11
32
1
11
11
10
0
4
0
0
143,819
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.SaturateStyle
class SaturateStyle(ParametricStyleBase): """Create a style by saturating the given color""" _op = 'saturate'
class SaturateStyle(ParametricStyleBase): '''Create a style by saturating the given color''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
4
4
1
2
2
1
1
2
2
1
0
3
0
0
143,820
Kozea/pygal
Kozea_pygal/pygal/__init__.py
pygal.PluginImportFixer
class PluginImportFixer(object): """ Allow external map plugins to be imported from pygal.maps package. It is a ``sys.meta_path`` loader. """ def find_module(self, fullname, path=None): """ Tell if the module to load can be loaded by the load_module function, ie: if it is a ``pygal.maps.*`` module. """ if fullname.startswith('pygal.maps.') and hasattr( maps, fullname.split('.')[2]): return self return None def load_module(self, name): """ Load the ``pygal.maps.name`` module from the previously loaded plugin """ if name not in sys.modules: sys.modules[name] = getattr(maps, name.split('.')[2]) return sys.modules[name]
class PluginImportFixer(object): ''' Allow external map plugins to be imported from pygal.maps package. It is a ``sys.meta_path`` loader. ''' def find_module(self, fullname, path=None): ''' Tell if the module to load can be loaded by the load_module function, ie: if it is a ``pygal.maps.*`` module. ''' pass def load_module(self, name): ''' Load the ``pygal.maps.name`` module from the previously loaded plugin ''' pass
3
3
9
0
5
5
2
1.3
1
0
0
0
2
0
2
2
26
3
10
3
7
13
9
3
6
2
1
1
4
143,821
Kozea/pygal
Kozea_pygal/pygal/formatters.py
pygal.formatters.Raw
class Raw(Formatter): """Cast everything to string""" def __call__(self, val): if val is None: return '' return str(val)
class Raw(Formatter): '''Cast everything to string''' def __call__(self, val): pass
2
1
4
0
4
0
2
0.2
1
1
0
1
1
0
1
1
7
1
5
2
3
1
5
2
3
2
2
1
2
143,822
Kozea/pygal
Kozea_pygal/pygal/view.py
pygal.view.ReverseView
class ReverseView(View): """Same as view but reversed vertically""" def y(self, y): """Project reversed y""" if y is None: return None return (self.height * (y - self.box.ymin) / self.box.height)
class ReverseView(View): '''Same as view but reversed vertically''' def y(self, y): '''Project reversed y''' pass
2
2
5
0
4
1
2
0.4
1
0
0
0
1
0
1
5
8
1
5
2
3
2
5
2
3
2
2
1
2
143,823
Kozea/pygal
Kozea_pygal/pygal/view.py
pygal.view.PolarThetaView
class PolarThetaView(View): """Logarithmic polar projection""" def __init__(self, width, height, box, aperture=pi / 3): """Create the view with a width an height and a box bounds""" super(PolarThetaView, self).__init__(width, height, box) self.aperture = aperture if not hasattr(box, '_tmin') or not hasattr(box, '_tmax'): raise Exception( 'Box must be set with set_polar_box for polar charts' ) def __call__(self, rhotheta): """Project rho and theta""" if None in rhotheta: return None, None rho, theta = rhotheta start = 3 * pi / 2 + self.aperture / 2 theta = start + (2 * pi - self.aperture) * (theta - self.box._tmin) / ( self.box._tmax - self.box._tmin ) return super(PolarThetaView, self).__call__((rho * cos(theta), rho * sin(theta)))
class PolarThetaView(View): '''Logarithmic polar projection''' def __init__(self, width, height, box, aperture=pi / 3): '''Create the view with a width an height and a box bounds''' pass def __call__(self, rhotheta): '''Project rho and theta''' pass
3
3
10
0
9
1
2
0.17
1
2
0
0
2
1
2
6
23
2
18
6
15
3
13
6
10
2
2
1
4
143,824
Kozea/pygal
Kozea_pygal/pygal/view.py
pygal.view.XLogView
class XLogView(View): """X logarithmic projection""" # Do not want to call the parent here def __init__(self, width, height, box): """Create the view with a width an height and a box bounds""" self.width = width self.height = height self.box = box self.log10_xmax = log10(self.box.xmax) if self.box.xmax > 0 else 0 self.log10_xmin = log10(self.box.xmin) if self.box.xmin > 0 else 0 self.box.fix(False) def x(self, x): """Project x""" if x is None or x <= 0 or self.log10_xmax - self.log10_xmin == 0: return None return ( self.width * (log10(x) - self.log10_xmin) / (self.log10_xmax - self.log10_xmin) )
class XLogView(View): '''X logarithmic projection''' def __init__(self, width, height, box): '''Create the view with a width an height and a box bounds''' pass def x(self, x): '''Project x''' pass
3
3
8
0
7
1
3
0.27
1
0
0
2
2
5
2
6
21
2
15
8
12
4
12
8
9
3
2
1
5
143,825
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.DarkColorizedStyle
class DarkColorizedStyle(Style): """A dark colorized style""" background = darken('#3a2d3f', 5) plot_background = lighten('#3a2d3f', 2) foreground = 'rgba(255, 255, 255, 0.9)' foreground_strong = 'rgba(255, 255, 255, 0.9)' foreground_subtle = 'rgba(255, 255 , 255, 0.5)' opacity = '.2' opacity_hover = '.7' transition = '250ms ease-in' colors = ( '#c900fe', '#01b8fe', '#59f500', '#ff00e4', '#f9fa00', darken('#c900fe', 20), darken('#01b8fe', 15), darken('#59f500', 20), darken('#ff00e4', 15), lighten('#f9fa00', 20) )
class DarkColorizedStyle(Style): '''A dark colorized style''' pass
1
1
0
0
0
0
0
0.43
1
0
0
0
0
0
0
3
16
1
14
10
13
6
10
10
9
0
2
0
0
143,826
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.CleanStyle
class CleanStyle(Style): """A rather clean style""" background = 'transparent' plot_background = 'rgba(240, 240, 240, 0.7)' foreground = 'rgba(0, 0, 0, 0.9)' foreground_strong = 'rgba(0, 0, 0, 0.9)' foreground_subtle = 'rgba(0, 0, 0, 0.5)' colors = ( 'rgb(12,55,149)', 'rgb(117,38,65)', 'rgb(228,127,0)', 'rgb(159,170,0)', 'rgb(149,12,12)' )
class CleanStyle(Style): '''A rather clean style''' pass
1
1
0
0
0
0
0
0.1
1
0
0
0
0
0
0
3
12
1
10
7
9
1
7
7
6
0
2
0
0
143,827
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.BlueStyle
class BlueStyle(Style): """A blue style""" background = darken('#f8f8f8', 3) plot_background = '#f8f8f8' foreground = 'rgba(0, 0, 0, 0.9)' foreground_strong = 'rgba(0, 0, 0, 0.9)' foreground_subtle = 'rgba(0, 0, 0, 0.6)' opacity = '.5' opacity_hover = '.9' transition = '250ms ease-in' colors = ( '#00b2f0', '#43d9be', '#0662ab', darken('#00b2f0', 20), lighten('#43d9be', 20), lighten('#7dcf30', 10), darken('#0662ab', 15), '#ffd541', '#7dcf30', lighten('#00b2f0', 15), darken('#ffd541', 20) )
class BlueStyle(Style): '''A blue style''' pass
1
1
0
0
0
0
0
0.43
1
0
0
0
0
0
0
3
16
1
14
10
13
6
10
10
9
0
2
0
0
143,828
Kozea/pygal
Kozea_pygal/pygal/state.py
pygal.state.State
class State(object): """ Class containing config values overriden by chart values overriden by keyword args """ def __init__(self, graph, **kwargs): """Create the transient state""" merge(self.__dict__, graph.config.__class__.__dict__) merge(self.__dict__, graph.config.__dict__) merge(self.__dict__, graph.__dict__) merge(self.__dict__, kwargs)
class State(object): ''' Class containing config values overriden by chart values overriden by keyword args ''' def __init__(self, graph, **kwargs): '''Create the transient state''' pass
2
2
6
0
5
1
1
1
1
0
0
0
1
0
1
1
13
1
6
2
4
6
6
2
4
1
1
0
1
143,829
Kozea/pygal
Kozea_pygal/pygal/serie.py
pygal.serie.Serie
class Serie(object): """Serie class containing title, values and the graph serie index""" def __init__(self, index, values, config, metadata=None): """Create the serie with its options""" self.index = index self.values = values self.config = config self.__dict__.update(config.__dict__) self.metadata = metadata or {} @cached_property def safe_values(self): """Property containing all values that are not None""" return list(filter(lambda x: x is not None, self.values))
class Serie(object): '''Serie class containing title, values and the graph serie index''' def __init__(self, index, values, config, metadata=None): '''Create the serie with its options''' pass @cached_property def safe_values(self): '''Property containing all values that are not None''' pass
4
3
5
0
4
1
1
0.3
1
2
0
0
2
4
2
2
15
2
10
8
6
3
9
7
6
1
1
0
2
143,830
Kozea/pygal
Kozea_pygal/pygal/view.py
pygal.view.View
class View(object): """Projection base class""" def __init__(self, width, height, box): """Create the view with a width an height and a box bounds""" self.width = width self.height = height self.box = box self.box.fix() def x(self, x): """Project x""" if x is None: return None return self.width * (x - self.box.xmin) / self.box.width def y(self, y): """Project y""" if y is None: return None return ( self.height - self.height * (y - self.box.ymin) / self.box.height ) def __call__(self, xy): """Project x and y""" x, y = xy return (self.x(x), self.y(y))
class View(object): '''Projection base class''' def __init__(self, width, height, box): '''Create the view with a width an height and a box bounds''' pass def x(self, x): '''Project x''' pass def y(self, y): '''Project y''' pass def __call__(self, xy): '''Project x and y''' pass
5
5
6
0
5
1
2
0.26
1
0
0
8
4
3
4
4
28
4
19
9
14
5
17
9
12
2
1
1
6
143,831
Kozea/pygal
Kozea_pygal/pygal/graph/xy.py
pygal.graph.xy.XY
class XY(Line, Dual): """XY Line graph class""" _x_adapters = [] @cached_property def xvals(self): """All x values""" return [ val[0] for serie in self.all_series for val in serie.values if val[0] is not None ] @cached_property def yvals(self): """All y values""" return [ val[1] for serie in self.series for val in serie.values if val[1] is not None ] @cached_property def _min(self): """Getter for the minimum series value""" return ( self.range[0] if (self.range and self.range[0] is not None) else (min(self.yvals) if self.yvals else None) ) @cached_property def _max(self): """Getter for the maximum series value""" return ( self.range[1] if (self.range and self.range[1] is not None) else (max(self.yvals) if self.yvals else None) ) def _compute(self): """Compute x/y min and max and x/y scale and set labels""" if self.xvals: if self.xrange: x_adapter = reduce(compose, self._x_adapters) if getattr( self, '_x_adapters', None ) else ident xmin = x_adapter(self.xrange[0]) xmax = x_adapter(self.xrange[1]) else: xmin = min(self.xvals) xmax = max(self.xvals) xrng = (xmax - xmin) else: xrng = None if self.yvals: ymin = self._min ymax = self._max if self.include_x_axis: ymin = min(ymin or 0, 0) ymax = max(ymax or 0, 0) yrng = (ymax - ymin) else: yrng = None for serie in self.all_series: serie.points = serie.values if self.interpolate: vals = list( zip( *sorted( filter(lambda t: None not in t, serie.points), key=lambda x: x[0] ) ) ) serie.interpolated = self._interpolate(vals[0], vals[1]) if self.interpolate: self.xvals = [ val[0] for serie in self.all_series for val in serie.interpolated ] self.yvals = [ val[1] for serie in self.series for val in serie.interpolated ] if self.xvals: xmin = min(self.xvals) xmax = max(self.xvals) xrng = (xmax - xmin) else: xrng = None # these values can also be 0 (zero), so testing explicitly for None if xrng is not None: self._box.xmin, self._box.xmax = xmin, xmax if yrng is not None: self._box.ymin, self._box.ymax = ymin, ymax
class XY(Line, Dual): '''XY Line graph class''' @cached_property def xvals(self): '''All x values''' pass @cached_property def yvals(self): '''All y values''' pass @cached_property def _min(self): '''Getter for the minimum series value''' pass @cached_property def _max(self): '''Getter for the maximum series value''' pass def _compute(self): '''Compute x/y min and max and x/y scale and set labels''' pass
10
6
18
2
15
1
4
0.09
2
3
0
2
5
0
5
85
101
15
79
22
69
7
45
16
39
12
5
2
20
143,832
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.LightenStyle
class LightenStyle(ParametricStyleBase): """Create a style by lightening the given color""" _op = 'lighten'
class LightenStyle(ParametricStyleBase): '''Create a style by lightening the given color''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
4
4
1
2
2
1
1
2
2
1
0
3
0
0
143,833
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.NeonStyle
class NeonStyle(DarkStyle): """Similar to DarkStyle but with more opacity and effects""" opacity = '.1' opacity_hover = '.75' transition = '1s ease-out'
class NeonStyle(DarkStyle): '''Similar to DarkStyle but with more opacity and effects''' pass
1
1
0
0
0
0
0
0.25
1
0
0
0
0
0
0
3
6
1
4
4
3
1
4
4
3
0
3
0
0
143,834
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.ParametricStyleBase
class ParametricStyleBase(Style): """Parametric Style base class for all the parametric operations""" _op = None def __init__(self, color, step=10, max_=None, base_style=None, **kwargs): """ Initialization of the parametric style. This takes several parameters: * a `step` which correspond on how many colors will be needed * a `max_` which defines the maximum amplitude of the color effect * a `base_style` which will be taken as default for everything except colors * any keyword arguments setting other style parameters """ if self._op is None: raise RuntimeError('ParametricStyle is not instanciable') defaults = {} if base_style is not None: if isinstance(base_style, type): base_style = base_style() defaults.update(base_style.to_dict()) defaults.update(kwargs) super(ParametricStyleBase, self).__init__(**defaults) if max_ is None: violency = { 'darken': 50, 'lighten': 50, 'saturate': 100, 'desaturate': 100, 'rotate': 360 } max_ = violency[self._op] def modifier(index): percent = max_ * index / (step - 1) return getattr(colors, self._op)(color, percent) self.colors = list(map(modifier, range(0, max(2, step))))
class ParametricStyleBase(Style): '''Parametric Style base class for all the parametric operations''' def __init__(self, color, step=10, max_=None, base_style=None, **kwargs): ''' Initialization of the parametric style. This takes several parameters: * a `step` which correspond on how many colors will be needed * a `max_` which defines the maximum amplitude of the color effect * a `base_style` which will be taken as default for everything except colors * any keyword arguments setting other style parameters ''' pass def modifier(index): pass
3
2
21
4
13
5
3
0.4
1
6
0
5
1
1
1
4
44
9
25
8
22
10
19
8
16
5
2
2
6
143,835
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.RotateStyle
class RotateStyle(ParametricStyleBase): """Create a style by rotating the given color""" _op = 'rotate'
class RotateStyle(ParametricStyleBase): '''Create a style by rotating the given color''' pass
1
1
0
0
0
0
0
0.5
1
0
0
0
0
0
0
4
4
1
2
2
1
1
2
2
1
0
3
0
0
143,836
Kozea/pygal
Kozea_pygal/docs/ext/pygal_sphinx_directives.py
pygal_sphinx_directives.PygalDirective
class PygalDirective(Directive): """Execute the given python file and puts its result in the document.""" required_arguments = 0 optional_arguments = 2 final_argument_whitespace = True has_content = True def run(self): width, height = map(int, self.arguments[:2] ) if len(self.arguments) >= 2 else (600, 400) if len(self.arguments) == 1: self.render_fix = bool(self.arguments[0]) elif len(self.arguments) == 3: self.render_fix = bool(self.arguments[2]) else: self.render_fix = False self.content = list(self.content) content = list(self.content) if self.render_fix: content[-1] = 'rv = ' + content[-1] code = '\n'.join(content) scope = {'pygal': pygal} try: exec(code, scope) except Exception: print(code) print_exc() return [ docutils.nodes.system_message( 'An exception as occured during code parsing:' ' \n %s' % format_exc(), type='ERROR', source='/', level=3 ) ] if self.render_fix: _rv = scope['rv'] else: chart = None for key, value in scope.items(): if isinstance(value, pygal.graph.graph.Graph): chart = value self.content.append(key + '.render()') break if chart is None: return [ docutils.nodes.system_message( 'No instance of graph found', level=3, type='ERROR', source='/' ) ] chart.config.width = width chart.config.height = height chart.explicit_size = True try: svg = '<embed src="%s" />' % chart.render_data_uri() except Exception: return [ docutils.nodes.system_message( 'An exception as occured during graph generation:' ' \n %s' % format_exc(), type='ERROR', source='/', level=3 ) ] return [docutils.nodes.raw('', svg, format='html')]
class PygalDirective(Directive): '''Execute the given python file and puts its result in the document.''' def run(self): pass
2
1
64
1
63
0
11
0.01
1
5
0
1
1
2
1
1
71
2
68
16
66
1
41
16
39
11
1
3
11
143,837
Kozea/pygal
Kozea_pygal/pygal/view.py
pygal.view.XYLogView
class XYLogView(XLogView, LogView): """X and Y logarithmic projection""" def __init__(self, width, height, box): """Create the view with a width an height and a box bounds""" self.width = width self.height = height self.box = box self.log10_ymax = log10(self.box.ymax) if self.box.ymax > 0 else 0 self.log10_ymin = log10(self.box.ymin) if self.box.ymin > 0 else 0 self.log10_xmax = log10(self.box.xmax) if self.box.xmax > 0 else 0 self.log10_xmin = log10(self.box.xmin) if self.box.xmin > 0 else 0 self.box.fix(False)
class XYLogView(XLogView, LogView): '''X and Y logarithmic projection''' def __init__(self, width, height, box): '''Create the view with a width an height and a box bounds''' pass
2
2
10
0
9
1
5
0.2
2
0
0
0
1
7
1
9
13
1
10
9
8
2
10
9
8
5
3
0
5
143,838
Kozea/pygal
Kozea_pygal/pygal/style.py
pygal.style.RedBlueStyle
class RedBlueStyle(Style): """A red and blue theme""" background = lighten('#e6e7e9', 7) plot_background = lighten('#e6e7e9', 10) foreground = 'rgba(0, 0, 0, 0.9)' foreground_strong = 'rgba(0, 0, 0, 0.9)' foreground_subtle = 'rgba(0, 0, 0, 0.5)' opacity = '.6' opacity_hover = '.9' colors = ( '#d94e4c', '#e5884f', '#39929a', lighten('#d94e4c', 10), darken('#39929a', 15), lighten('#e5884f', 17), darken('#d94e4c', 10), '#234547' )
class RedBlueStyle(Style): '''A red and blue theme''' pass
1
1
0
0
0
0
0
0.46
1
0
0
0
0
0
0
3
15
1
13
9
12
6
9
9
8
0
2
0
0
143,839
Kozea/pygal
Kozea_pygal/pygal/formatters.py
pygal.formatters.Significant
class Significant(Formatter): """Show precision significant digit of float""" def __init__(self, precision=10): self.format = '%%.%dg' % precision def __call__(self, val): if val is None: return '' return self.format % val
class Significant(Formatter): '''Show precision significant digit of float''' def __init__(self, precision=10): pass def __call__(self, val): pass
3
1
3
0
3
0
2
0.14
1
0
0
1
2
1
2
2
10
2
7
4
4
1
7
4
4
2
2
1
3
143,840
Kozea/wdb
Kozea_wdb/wdb_over_pdb/pdb.py
pdb.Pdb
class Pdb(Wdb): pass
class Pdb(Wdb): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
2
0
2
1
1
0
2
1
1
0
1
0
0
143,841
Kozea/wdb
Kozea_wdb/pytest_wdb/pytest_wdb.py
pytest_wdb.Trace
class Trace(object): def pytest_collection_modifyitems(config, items): for item in items: item.obj = wdb.with_trace(item.obj)
class Trace(object): def pytest_collection_modifyitems(config, items): pass
2
0
3
0
3
0
2
0
1
0
0
0
1
0
1
1
4
0
4
3
2
0
4
3
2
2
1
1
2
143,842
Kozea/wdb
Kozea_wdb/test/conftest.py
test.conftest.Socket
class Socket(object): def __init__(self, testfile, host='localhost', port=19999): self.slave = Slave(testfile, host, port) self.slave.start() self.started = False self.host = host self.port = port self.connections = {} self.listener = None def connection(self, uuid): if uuid is None and len(self.connections) == 1: return list(self.connections.values())[0] else: return self.connections[uuid] def start(self): log.info('Accepting') if not self.listener: self.listener = Listener((self.host, self.port)) try: connection = self.listener.accept() except Exception: self.listener.close() raise self.started = True log.info('Connection get') uuid = connection.recv_bytes().decode('utf-8') self.connections[uuid] = connection msg = self.receive(uuid) assert msg.command == 'ServerBreaks' self.send('[]', uuid=uuid) self.send('Start', uuid=uuid) return uuid def assert_init(self): assert self.receive().command == 'Init' assert self.receive().command == 'Title' assert self.receive().command == 'Trace' assert self.receive().command == 'SelectCheck' echo_watched = self.receive().command if echo_watched == 'Echo': echo_watched = self.receive().command assert echo_watched == 'Watched' def assert_position( self, title=None, subtitle=None, file=None, code=None, function=None, line=None, breaks=None, call=None, return_=None, exception=None, bottom_code=None, bottom_line=None, ): titlemsg = self.receive() assert titlemsg.command == 'Title' if title is not None: assert titlemsg.data.title == title if subtitle is not None: assert titlemsg.data.subtitle == subtitle tracemsg = self.receive() assert tracemsg.command == 'Trace' current = tracemsg.data.trace[-1] if file is not None: assert current.file == file if code is not None: assert current.code == code if function is not None: assert current.function == function if line is not None: assert current.lno == line for frame in tracemsg.data.trace: if frame.file == self.slave.file: break if bottom_code is not None: assert frame.code == bottom_code if bottom_line is not None: assert frame.lno == bottom_line selectmsg = self.receive() assert selectmsg.command == 'SelectCheck' if any((exception, call, return_)): echomsg = self.receive() assert echomsg.command == 'Echo' if exception: assert echomsg.data['for'] == '__exception__' assert exception in echomsg.data.val if call: assert echomsg.data['for'] == '__call__' assert call in echomsg.data.val if return_: assert echomsg.data['for'] == '__return__' assert return_ in echomsg.data.val watchedmsg = self.receive() assert watchedmsg.command == 'Watched' def receive(self, uuid=None): got = self.connection(uuid).recv_bytes().decode('utf-8') if got == 'PING' or got.startswith('UPDATE_FILENAME'): return self.receive(uuid) return Message(got) def send(self, command, data=None, uuid=None): message = '%s|%s' % (command, data) if data else command log.info('Sending %s' % message) self.connection(uuid).send_bytes(message.encode('utf-8')) def join(self): self.slave.join() def close(self, failed=False): slave_was_alive = False if self.slave.is_alive(): self.slave.terminate() slave_was_alive = True if self.started: for connection in self.connections.values(): connection.close() self.listener.close() if slave_was_alive and not failed: raise Exception('Tests must join the subprocess')
class Socket(object): def __init__(self, testfile, host='localhost', port=19999): pass def connection(self, uuid): pass def start(self): pass def assert_init(self): pass def assert_position( self, title=None, subtitle=None, file=None, code=None, function=None, line=None, breaks=None, call=None, return_=None, exception=None, bottom_code=None, bottom_line=None, ): pass def receive(self, uuid=None): pass def send(self, command, data=None, uuid=None): pass def join(self): pass def close(self, failed=False): pass
10
0
15
2
13
0
4
0
1
5
2
0
9
6
9
9
140
22
118
45
94
0
103
31
93
15
1
2
33
143,843
Kozea/wdb
Kozea_wdb/test/conftest.py
test.conftest.Slave
class Slave(Process): def __init__(self, use, host='localhost', port=19999): self.argv = None self.file = os.path.join( os.path.dirname(__file__), 'scripts', use.file ) if use.with_main: self.argv = ['', '--trace', self.file] self.file = os.path.join( os.path.dirname(__file__), '..', 'client', 'wdb', '__main__.py' ) self.host = host self.port = port super(Slave, self).__init__() def run(self): import wdb wdb.SOCKET_SERVER = self.host wdb.SOCKET_PORT = self.port wdb.WDB_NO_BROWSER_AUTO_OPEN = True sys.argv = self.argv with open(self.file, 'rb') as file: LOCALS['__name__'] = '__main__' exec(compile(file.read(), self.file, 'exec'), GLOBALS, LOCALS)
class Slave(Process): def __init__(self, use, host='localhost', port=19999): pass def run(self): pass
3
0
13
2
11
0
2
0
1
1
0
0
2
4
2
2
28
5
23
9
19
0
19
8
15
2
1
1
3
143,844
Kozea/wdb
Kozea_wdb/test/conftest.py
test.conftest.Message
class Message(object): def __init__(self, message): log.info('Received %s' % message) pickled = False if message.startswith('Server|'): message = message.replace('Server|', '') pickled = True if '|' in message: pipe = message.index('|') self.command, self.data = message[:pipe], message[pipe + 1 :] if pickled and self.data: self.data = pickle.loads(self.data.encode('utf-8'), protocol=2) else: self.data = json.loads(self.data, object_hook=AttrDict) else: self.command, self.data = message, ''
class Message(object): def __init__(self, message): pass
2
0
15
0
15
0
4
0
1
1
1
0
1
2
1
1
16
0
16
5
14
0
14
5
12
4
1
2
4
143,845
Kozea/wdb
Kozea_wdb/test/conftest.py
test.conftest.use
class use(object): def __init__(self, file, with_main=False): self.file = file self.with_main = with_main def __call__(self, fun): fun._wdb_use = self return fun
class use(object): def __init__(self, file, with_main=False): pass def __call__(self, fun): pass
3
0
3
0
3
0
1
0
1
0
0
0
2
2
2
2
8
1
7
5
4
0
7
5
4
1
1
0
2
143,846
Kozea/wdb
Kozea_wdb/client/wdb/state.py
wdb.state.Running
class Running(State): """Running state: never stopping""" def stops(self, frame, event): return False
class Running(State): '''Running state: never stopping''' def stops(self, frame, event): pass
2
1
2
0
2
0
1
0.33
1
0
0
0
1
0
1
4
5
1
3
2
1
1
3
2
1
1
2
0
1
143,847
Kozea/wdb
Kozea_wdb/test/scripts/forks.py
test.scripts.forks.Process2
class Process2(Process): def run(self): print('Process 2 start') wtf() print('Process 2 end')
class Process2(Process): def run(self): pass
2
0
4
0
4
0
1
0
1
0
0
0
1
0
1
1
5
0
5
2
3
0
5
2
3
1
1
0
1