_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q24700 | PluginOptions._argparse_minmax_type | train | def _argparse_minmax_type(self, string):
"""Custom type for argparse to enforce value limits"""
value = float(string)
if value < 0 or value > 8:
raise argparse.ArgumentTypeError(
'%s must be between 0.0 and 8.0' % string,
)
return value | python | {
"resource": ""
} |
q24701 | HighEntropyStringsPlugin.calculate_shannon_entropy | train | def calculate_shannon_entropy(self, data):
"""Returns the entropy of a given string.
Borrowed from: http://blog.dkbza.org/2007/05/scanning-data-for-entropy-anomalies.html.
:param data: string. The word to analyze.
:returns: float, between 0.0 and 8.0
"""
if not d... | python | {
"resource": ""
} |
q24702 | HighEntropyStringsPlugin.analyze_string_content | train | def analyze_string_content(self, string, line_num, filename):
"""Searches string for custom pattern, and captures all high entropy strings that
match self.regex, with a limit defined as self.entropy_limit.
"""
output = {}
for result in self.secret_generator(string):
... | python | {
"resource": ""
} |
q24703 | HighEntropyStringsPlugin.non_quoted_string_regex | train | def non_quoted_string_regex(self, strict=True):
"""For certain file formats, strings need not necessarily follow the
normal convention of being denoted by single or double quotes. In these
cases, we modify the regex accordingly.
Public, because detect_secrets.core.audit needs to referen... | python | {
"resource": ""
} |
q24704 | HexHighEntropyString.calculate_shannon_entropy | train | def calculate_shannon_entropy(self, data):
"""
In our investigations, we have found that when the input is all digits,
the number of false positives we get greatly exceeds realistic true
positive scenarios.
Therefore, this tries to capture this heuristic mathemetically.
... | python | {
"resource": ""
} |
q24705 | initialize | train | def initialize(
plugins,
exclude_files_regex=None,
exclude_lines_regex=None,
path='.',
scan_all_files=False,
):
"""Scans the entire codebase for secrets, and returns a
SecretsCollection object.
:type plugins: tuple of detect_secrets.plugins.base.BasePlugin
:param plugins: rules to i... | python | {
"resource": ""
} |
q24706 | merge_results | train | def merge_results(old_results, new_results):
"""Update results in baseline with latest information.
:type old_results: dict
:param old_results: results of status quo
:type new_results: dict
:param new_results: results to replace status quo
:rtype: dict
"""
for filename, old_secrets in... | python | {
"resource": ""
} |
q24707 | _get_git_tracked_files | train | def _get_git_tracked_files(rootdir='.'):
"""Parsing .gitignore rules is hard.
However, a way we can get around this problem by just listing all
currently tracked git files, and start our search from there.
After all, if it isn't in the git repo, we're not concerned about
it, because secrets aren't ... | python | {
"resource": ""
} |
q24708 | _get_files_recursively | train | def _get_files_recursively(rootdir):
"""Sometimes, we want to use this tool with non-git repositories.
This function allows us to do so.
"""
output = []
for root, dirs, files in os.walk(rootdir):
for filename in files:
output.append(os.path.join(root, filename))
return outpu... | python | {
"resource": ""
} |
q24709 | _add_baseline_to_exclude_files | train | def _add_baseline_to_exclude_files(args):
"""
Modifies args.exclude_files in-place.
"""
baseline_name_regex = r'^{}$'.format(args.import_filename[0])
if not args.exclude_files:
args.exclude_files = baseline_name_regex
elif baseline_name_regex not in args.exclude_files:
args.excl... | python | {
"resource": ""
} |
q24710 | from_plugin_classname | train | def from_plugin_classname(plugin_classname, exclude_lines_regex=None, **kwargs):
"""Initializes a plugin class, given a classname and kwargs.
:type plugin_classname: str
:param plugin_classname: subclass of BasePlugin.
:type exclude_lines_regex: str|None
:param exclude_lines_regex: optional regex ... | python | {
"resource": ""
} |
q24711 | _get_mapping_from_secret_type_to_class_name | train | def _get_mapping_from_secret_type_to_class_name():
"""Returns secret_type => plugin classname"""
mapping = {}
for key, value in globals().items():
try:
if issubclass(value, BasePlugin) and value != BasePlugin:
mapping[value.secret_type] = key
except TypeError:
... | python | {
"resource": ""
} |
q24712 | confidence_interval_continuous | train | def confidence_interval_continuous(
point_estimate, stddev, sample_size, confidence=.95, **kwargs
):
"""Continuous confidence interval from sample size and standard error"""
alpha = ppf((confidence + 1) / 2, sample_size - 1)
margin = stddev / sqrt(sample_size)
return (point_estimate - alpha * m... | python | {
"resource": ""
} |
q24713 | confidence_interval_dichotomous | train | def confidence_interval_dichotomous(
point_estimate,
sample_size,
confidence=.95,
bias=False,
percentage=True,
**kwargs
):
"""Dichotomous confidence interval from sample size and maybe a bias"""
alpha = ppf((confidence + 1) / 2, sample_size - 1)
p = point_esti... | python | {
"resource": ""
} |
q24714 | Dot.dot | train | 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._... | python | {
"resource": ""
} |
q24715 | Dot._plot | train | 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) | python | {
"resource": ""
} |
q24716 | timestamp | train | def timestamp(x):
"""Get a timestamp from a date in python 3 and python 2"""
if x.tzinfo is None:
# Naive dates to utc
x = x.replace(tzinfo=utc)
if hasattr(x, 'timestamp'):
return x.timestamp()
else:
return (x - datetime(1970, 1, 1, tzinfo=utc)).total_seconds() | python | {
"resource": ""
} |
q24717 | Key.coerce | train | 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:
... | python | {
"resource": ""
} |
q24718 | BaseConfig._update | train | 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... | python | {
"resource": ""
} |
q24719 | StackedBar._get_separated_values | train | 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 ... | python | {
"resource": ""
} |
q24720 | StackedBar._plot | train | 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) | python | {
"resource": ""
} |
q24721 | PublicApi.add | train | 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 | python | {
"resource": ""
} |
q24722 | PublicApi.render | train | 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 | python | {
"resource": ""
} |
q24723 | PublicApi.render_table | train | 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(**kwa... | python | {
"resource": ""
} |
q24724 | PublicApi.render_pyquery | train | 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') | python | {
"resource": ""
} |
q24725 | PublicApi.render_in_browser | train | 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_... | python | {
"resource": ""
} |
q24726 | PublicApi.render_response | train | 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') | python | {
"resource": ""
} |
q24727 | PublicApi.render_django_response | train | 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'
) | python | {
"resource": ""
} |
q24728 | PublicApi.render_data_uri | train | 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)
... | python | {
"resource": ""
} |
q24729 | PublicApi.render_to_file | train | 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)) | python | {
"resource": ""
} |
q24730 | PublicApi.render_to_png | train | 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
) | python | {
"resource": ""
} |
q24731 | PublicApi.render_sparkline | train | 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,
... | python | {
"resource": ""
} |
q24732 | Radar._x_axis | train | 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 '')
... | python | {
"resource": ""
} |
q24733 | Radar._y_axis | train | 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_... | python | {
"resource": ""
} |
q24734 | Radar._compute | train | 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... | python | {
"resource": ""
} |
q24735 | BaseMap._value_format | train | 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])
) | python | {
"resource": ""
} |
q24736 | BaseMap._plot | train | 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... | python | {
"resource": ""
} |
q24737 | StackedLine._value_format | train | 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_fro... | python | {
"resource": ""
} |
q24738 | StackedLine._plot | train | 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) | python | {
"resource": ""
} |
q24739 | Svg.add_styles | train | 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(
'/... | python | {
"resource": ""
} |
q24740 | Svg.add_scripts | train | 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.starts... | python | {
"resource": ""
} |
q24741 | Svg.node | train | 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... | python | {
"resource": ""
} |
q24742 | Svg.transposable_node | train | 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)
... | python | {
"resource": ""
} |
q24743 | Svg.serie | train | 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'],
... | python | {
"resource": ""
} |
q24744 | Svg.line | train | 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 ... | python | {
"resource": ""
} |
q24745 | Svg.slice | train | 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... | python | {
"resource": ""
} |
q24746 | Svg.pre_render | train | 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.w... | python | {
"resource": ""
} |
q24747 | Svg.draw_no_data | train | 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.gra... | python | {
"resource": ""
} |
q24748 | Svg.render | train | 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... | python | {
"resource": ""
} |
q24749 | Svg.get_strokes | train | 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... | python | {
"resource": ""
} |
q24750 | XY.xvals | train | 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
] | python | {
"resource": ""
} |
q24751 | XY.yvals | train | 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
] | python | {
"resource": ""
} |
q24752 | PluginImportFixer.load_module | train | 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] | python | {
"resource": ""
} |
q24753 | majorize | train | def majorize(values):
"""Filter sequence to return only major considered numbers"""
sorted_values = sorted(values)
if len(values) <= 3 or (
abs(2 * sorted_values[1] - sorted_values[0] - sorted_values[2]) >
abs(1.5 * (sorted_values[1] - sorted_values[0]))):
return []
value... | python | {
"resource": ""
} |
q24754 | round_to_int | train | def round_to_int(number, precision):
"""Round a number to a precision"""
precision = int(precision)
rounded = (int(number) + precision / 2) // precision * precision
return rounded | python | {
"resource": ""
} |
q24755 | round_to_float | train | def round_to_float(number, precision):
"""Round a float to a precision"""
rounded = Decimal(str(floor((number + precision / 2) // precision))
) * Decimal(str(precision))
return float(rounded) | python | {
"resource": ""
} |
q24756 | round_to_scale | train | def round_to_scale(number, precision):
"""Round a number or a float to a precision"""
if precision < 1:
return round_to_float(number, precision)
return round_to_int(number, precision) | python | {
"resource": ""
} |
q24757 | cut | train | def cut(list_, index=0):
"""Cut a list by index or arg"""
if isinstance(index, int):
cut_ = lambda x: x[index]
else:
cut_ = lambda x: getattr(x, index)
return list(map(cut_, list_)) | python | {
"resource": ""
} |
q24758 | _swap_curly | train | def _swap_curly(string):
"""Swap single and double curly brackets"""
return (
string.replace('{{ ', '{{').replace('{{', '\x00').replace('{', '{{')
.replace('\x00', '{').replace(' }}', '}}').replace('}}', '\x00')
.replace('}', '}}').replace('\x00', '}')
) | python | {
"resource": ""
} |
q24759 | compute_logarithmic_scale | train | def compute_logarithmic_scale(min_, max_, min_scale, max_scale):
"""Compute an optimal scale for logarithmic"""
if max_ <= 0 or min_ <= 0:
return []
min_order = int(floor(log10(min_)))
max_order = int(ceil(log10(max_)))
positions = []
amplitude = max_order - min_order
if amplitude <=... | python | {
"resource": ""
} |
q24760 | compute_scale | train | def compute_scale(min_, max_, logarithmic, order_min, min_scale, max_scale):
"""Compute an optimal scale between min and max"""
if min_ == 0 and max_ == 0:
return [0]
if max_ - min_ == 0:
return [min_]
if logarithmic:
log_scale = compute_logarithmic_scale(min_, max_, min_scale, m... | python | {
"resource": ""
} |
q24761 | get_texts_box | train | def get_texts_box(texts, fs):
"""Approximation of multiple texts bounds"""
max_len = max(map(len, texts))
return (fs, text_len(max_len, fs)) | python | {
"resource": ""
} |
q24762 | decorate | train | def decorate(svg, node, metadata):
"""Add metedata next to a node"""
if not metadata:
return node
xlink = metadata.get('xlink')
if xlink:
if not isinstance(xlink, dict):
xlink = {'href': xlink, 'target': '_blank'}
node = svg.node(node, 'a', **xlink)
svg.node(
... | python | {
"resource": ""
} |
q24763 | alter | train | def alter(node, metadata):
"""Override nodes attributes from metadata node mapping"""
if node is not None and metadata and 'node' in metadata:
node.attrib.update(
dict((k, str(v)) for k, v in metadata['node'].items())
) | python | {
"resource": ""
} |
q24764 | minify_css | train | def minify_css(css):
"""Little css minifier"""
# Inspired by slimmer by Peter Bengtsson
remove_next_comment = 1
for css_comment in css_comments.findall(css):
if css_comment[-3:] == '\*/':
remove_next_comment = 0
continue
if remove_next_comment:
css = c... | python | {
"resource": ""
} |
q24765 | split_title | train | def split_title(title, width, title_fs):
"""Split a string for a specified width and font size"""
titles = []
if not title:
return titles
size = reverse_text_len(width, title_fs * 1.1)
title_lines = title.split("\n")
for title_line in title_lines:
while len(title_line) > size:
... | python | {
"resource": ""
} |
q24766 | Box._compute | train | 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._orde... | python | {
"resource": ""
} |
q24767 | Box._boxf | train | 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, respe... | python | {
"resource": ""
} |
q24768 | Box._draw_box | train | 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... | python | {
"resource": ""
} |
q24769 | HorizontalGraph._post_compute | train | 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 = (
... | python | {
"resource": ""
} |
q24770 | HorizontalGraph._axes | train | 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 | python | {
"resource": ""
} |
q24771 | HorizontalGraph._set_view | train | 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,
... | python | {
"resource": ""
} |
q24772 | Pie.slice | train | 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... | python | {
"resource": ""
} |
q24773 | Graph._decorate | train | 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() | python | {
"resource": ""
} |
q24774 | Graph._make_graph | train | 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(
... | python | {
"resource": ""
} |
q24775 | Graph._make_title | train | 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,... | python | {
"resource": ""
} |
q24776 | Graph._make_x_title | train | 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'],
... | python | {
"resource": ""
} |
q24777 | Graph._make_y_title | train | 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',
... | python | {
"resource": ""
} |
q24778 | Graph._interpolate | train | 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(
... | python | {
"resource": ""
} |
q24779 | Graph._rescale | train | 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] | python | {
"resource": ""
} |
q24780 | Graph._tooltip_data | train | 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:
c... | python | {
"resource": ""
} |
q24781 | Graph._static_value | train | 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... | python | {
"resource": ""
} |
q24782 | Graph._compute_secondary | train | 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)
... | python | {
"resource": ""
} |
q24783 | Graph._format | train | 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 se... | python | {
"resource": ""
} |
q24784 | Graph._serie_format | train | 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, ... | python | {
"resource": ""
} |
q24785 | Graph._draw | train | 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()
... | python | {
"resource": ""
} |
q24786 | Graph._has_data | train | 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
]) | python | {
"resource": ""
} |
q24787 | Funnel.funnel | train | 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(
... | python | {
"resource": ""
} |
q24788 | Box.set_polar_box | train | 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 | python | {
"resource": ""
} |
q24789 | Box.fix | train | 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 -= ... | python | {
"resource": ""
} |
q24790 | ReverseView.y | train | def y(self, y):
"""Project reversed y"""
if y is None:
return None
return (self.height * (y - self.box.ymin) / self.box.height) | python | {
"resource": ""
} |
q24791 | date_to_datetime | train | def date_to_datetime(x):
"""Convert a date into a datetime"""
if not isinstance(x, datetime) and isinstance(x, date):
return datetime.combine(x, time())
return x | python | {
"resource": ""
} |
q24792 | time_to_datetime | train | def time_to_datetime(x):
"""Convert a time into a datetime"""
if isinstance(x, time):
return datetime.combine(date(1970, 1, 1), x)
return x | python | {
"resource": ""
} |
q24793 | time_to_seconds | train | def time_to_seconds(x):
"""Convert a time in a seconds sum"""
if isinstance(x, time):
return ((((x.hour * 60) + x.minute) * 60 + x.second) * 10**6 +
x.microsecond) / 10**6
if is_str(x):
return x
# Clamp to valid time
return x and max(0, min(x, 24 * 3600 - 10**-6)) | python | {
"resource": ""
} |
q24794 | seconds_to_time | train | def seconds_to_time(x):
"""Convert a number of second into a time"""
t = int(x * 10**6)
ms = t % 10**6
t = t // 10**6
s = t % 60
t = t // 60
m = t % 60
t = t // 60
h = t
return time(h, m, s, ms) | python | {
"resource": ""
} |
q24795 | Gauge.needle | train | 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.... | python | {
"resource": ""
} |
q24796 | Gauge._y_axis | train | 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(
... | python | {
"resource": ""
} |
q24797 | Gauge._x_axis | train | 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) | python | {
"resource": ""
} |
q24798 | Style.get_colors | train | 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'
)... | python | {
"resource": ""
} |
q24799 | Style.to_dict | train | 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 ... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.