_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 data: # pragma: no cover return 0 entropy = 0 for x in self.charset: p_x = float(data.count(x)) / len(data) if p_x > 0: entropy += - p_x * math.log(p_x, 2) return entropy
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): if self._is_sequential_string(result): continue secret = PotentialSecret(self.secret_type, filename, result, line_num) output[secret] = secret return output
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 reference it. :type strict: bool :param strict: if True, the regex will match the entire string. """ old_regex = self.regex regex_alternative = r'([{}]+)'.format(re.escape(self.charset)) if strict: regex_alternative = r'^' + regex_alternative + r'$' self.regex = re.compile(regex_alternative) try: yield finally: self.regex = old_regex
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. We do this by noting that the maximum shannon entropy for this charset is ~3.32 (e.g. "0123456789", with every digit different), and we want to lower that below the standard limit, 3. However, at the same time, we also want to accommodate the fact that longer strings have a higher chance of being a true positive, which means "01234567890123456789" should be closer to the maximum entropy than the shorter version. """ entropy = super(HexHighEntropyString, self).calculate_shannon_entropy(data) if len(data) == 1: return entropy try: int(data) # This multiplier was determined through trial and error, with the # intent of keeping it simple, yet achieving our goals. entropy -= 1.2 / math.log(len(data), 2) except ValueError: pass return entropy
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 initialize the SecretsCollection with. :type exclude_files_regex: str|None :type exclude_lines_regex: str|None :type path: str :type scan_all_files: bool :rtype: SecretsCollection """ output = SecretsCollection( plugins, exclude_files=exclude_files_regex, exclude_lines=exclude_lines_regex, ) if os.path.isfile(path): # This option allows for much easier adhoc usage. files_to_scan = [path] elif scan_all_files: files_to_scan = _get_files_recursively(path) else: files_to_scan = _get_git_tracked_files(path) if not files_to_scan: return output if exclude_files_regex: exclude_files_regex = re.compile(exclude_files_regex, re.IGNORECASE) files_to_scan = filter( lambda file: ( not exclude_files_regex.search(file) ), files_to_scan, ) for file in files_to_scan: output.scan_file(file) return output
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 old_results.items(): if filename not in new_results: continue old_secrets_mapping = dict() for old_secret in old_secrets: old_secrets_mapping[old_secret['hashed_secret']] = old_secret for new_secret in new_results[filename]: if new_secret['hashed_secret'] not in old_secrets_mapping: # We don't join the two secret sets, because if the newer # result set did not discover an old secret, it probably # moved. continue old_secret = old_secrets_mapping[new_secret['hashed_secret']] # Only propagate 'is_secret' if it's not already there if 'is_secret' in old_secret and 'is_secret' not in new_secret: new_secret['is_secret'] = old_secret['is_secret'] return new_results
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 being entered in a shared place. :type rootdir: str :param rootdir: root directory of where you want to list files from :rtype: set|None :returns: filepaths to files which git currently tracks (locally) """ try: with open(os.devnull, 'w') as fnull: git_files = subprocess.check_output( [ 'git', 'ls-files', rootdir, ], stderr=fnull, ) return set(git_files.decode('utf-8').split()) except subprocess.CalledProcessError: return None
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 output
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.exclude_files += r'|{}'.format(baseline_name_regex)
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 for ignored lines. """ klass = globals()[plugin_classname] # Make sure the instance is a BasePlugin type, before creating it. if not issubclass(klass, BasePlugin): raise TypeError try: instance = klass(exclude_lines_regex=exclude_lines_regex, **kwargs) except TypeError: log.warning( 'Unable to initialize plugin!', ) raise return instance
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: pass return mapping
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 * margin, point_estimate + alpha * margin)
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_estimate if percentage: p /= 100 margin = sqrt(p * (1 - p) / sample_size) if bias: margin += .5 / sample_size if percentage: margin *= 100 return (point_estimate - alpha * margin, point_estimate + alpha * margin)
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._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)
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: 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)
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 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
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(**kwargs)
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_protocol', 'https') open_in_browser(self.render_tree(**kwargs), encoding='utf-8')
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) ).decode('utf-8').replace('\n', '') )
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, 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)
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 '') ) 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) )
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_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)
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, 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
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(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)
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_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))
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( '//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(u('xml-stylesheet'), u('href="%s"' % css)) ) self.node( self.defs, 'style', type='text/css' ).text = '\n'.join(all_css)
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.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)
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) 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] = to_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)
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) 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)
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'], 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) ) )
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 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)
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_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
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.width)) self.root.set('height', str(self.graph.height))
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.graph.no_data_text
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 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
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 '') ] 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)
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 [] values_step = sorted_values[1] - sorted_values[0] full_range = sorted_values[-1] - sorted_values[0] step = 10**int(log10(full_range)) if step == values_step: step *= 10 step_factor = 10**(int(log10(step)) + 1) if round(step * step_factor) % (round(values_step * step_factor) or 1): # TODO: Find lower common multiple instead step *= values_step if full_range <= 2 * step: step *= .5 elif full_range >= 5 * step: step *= 5 major_values = [ value for value in values if value / step == round(value / step) ] return [value for value in sorted_values if value in major_values]
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 <= 1: return [] detail = 10. while amplitude * detail < min_scale * 5: detail *= 2 while amplitude * detail > max_scale * 3: detail /= 2 for order in range(min_order, max_order + 1): for i in range(int(detail)): tick = (10 * i / detail or 1) * 10**order tick = round_to_scale(tick, tick) if min_ <= tick <= max_ and tick not in positions: positions.append(tick) return positions
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, max_scale) if log_scale: return log_scale # else we fallback to normal scalling order = round(log10(max(abs(min_), abs(max_)))) - 1 if order_min is not None and order < order_min: order = order_min else: while ((max_ - min_) / (10**order) < min_scale and (order_min is None or order > order_min)): order -= 1 step = float(10**order) while (max_ - min_) / step > max_scale: step *= 2. positions = [] position = round_to_scale(min_, step) while position < (max_ + step): rounded = round_to_scale(position, step) if min_ <= rounded <= max_: if rounded not in positions: positions.append(rounded) position += step if len(positions) < 2: return [min_, max_] return positions
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( node, 'desc', class_='xlink' ).text = to_unicode(xlink.get('href')) if 'tooltip' in metadata: svg.node(node, 'title').text = to_unicode(metadata['tooltip']) if 'color' in metadata: color = metadata.pop('color') node.attrib['style'] = 'fill: %s; stroke: %s' % (color, color) if 'style' in metadata: node.attrib['style'] = metadata.pop('style') if 'label' in metadata and metadata['label']: svg.node( node, 'desc', class_='label' ).text = to_unicode(metadata['label']) return 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 = css.replace(css_comment, '') else: remove_next_comment = 1 # >= 2 whitespace becomes one whitespace css = re.sub(r'\s\s+', ' ', css) # no whitespace before end of line css = re.sub(r'\s+\n', '', css) # Remove space before and after certain chars for char in ('{', '}', ':', ';', ','): css = re.sub(char + r'\s', char, css) css = re.sub(r'\s' + char, char, css) css = re.sub(r'}\s(#|\w)', r'}\1', css) # no need for the ; before end of attributes css = re.sub(r';}', r'}', css) css = re.sub(r'}//-->', r'}\n//-->', css) return css.strip()
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: title_part = title_line[:size] i = title_part.rfind(' ') if i == -1: i = len(title_part) titles.append(title_part[:i]) title_line = title_line[i:].strip() titles.append(title_line) return titles
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._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)
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, 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)
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 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)) )
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 = ( self._y_2nd_labels, self._x_2nd_labels ) self.show_y_guides, self.show_x_guides = ( self.show_x_guides, self.show_y_guides )
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, self._box )
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 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
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( 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')
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, y=i * (self.style.title_font_size + self.spacing) ).text = title_line
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'], '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
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', 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
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( interpolate( x, y, self.interpolation_precision, **self.interpolation_parameters ) )
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: classes.append('left') if y > self.view.height / 2: classes.append('top') classes = ' '.join(classes) self.svg.node(node, 'desc', class_="x " + classes).text = to_str(x) self.svg.node(node, 'desc', class_="y " + classes).text = to_str(y) if xlabel: self.svg.node(node, 'desc', class_="x_label").text = to_str(xlabel)
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] 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 ''
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) 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
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 self.formatter or self._value_format) kwargs = filter_kwargs(formatter, kwargs) return formatter(value, **kwargs)
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, **kwargs)
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() self._decorate() if self.series and self._has_data() and self._values: self._plot() else: self.svg.draw_no_data()
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( 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)
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 -= xmargin self.xmax += xmargin if with_margin: ymargin = self.margin * self.height self.ymin -= ymargin self.ymax += ymargin
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._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)
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( 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)
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' ) % (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)) ) )
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 config
python
{ "resource": "" }