Convert string chart into text markup with the correct attributes.

    chart -- palette chart as a string
    convert -- function that converts a single palette entry to an
        (attr, text) tuple, or None if no match is found
6086
def parse_chart(chart, convert):
    
    out = []
    for match in re.finditer(ATTR_RE, chart):
        if match.group('whitespace'):
            out.append(match.group('whitespace'))
        entry = match.group('entry')
        entry = entry.replace("_", " ")
        while entry:
            # try the first four characters
            attrtext = convert(entry[:SHORT_ATTR])
            if attrtext:
                elen = SHORT_ATTR
                entry = entry[SHORT_ATTR:].strip()
            else: # try the whole thing
                attrtext = convert(entry.strip())
                assert attrtext, "Invalid palette entry: %r" % entry
                elen = len(entry)
                entry = ""
            attr, text = attrtext
            out.append((attr, text.ljust(elen)))
    return out
375141
def html(data, options, center=False, save=False,
         save_name=None, save_path='saved', dated=True, notebook=True):
    

    def json_dumps(obj):
        return pd.io.json.dumps(obj)

    _options = dict(options)
    _data = data

    def clean_function_str(key, n=15):
        """
        Remove new line characters in the first say 15 characters
        of the value corresponding to key in dictionary _options.
        This value is a string that potentially starts with
        'function' or ' function' or '[newline]function' or '[newline]function', etc
        This cleaning makes js string parsing easier to recognize functions.
        """
        if key in _options.keys():
            new_str = _options[key][:n].replace('\n', '')
            new_str = new_str.replace('\r', '')
            new_str = new_str + _options[key][n:]
            _options[key] = new_str

    clean_function_str('tooltip')
    clean_function_str('xValueLabel')
    clean_function_str('yValueLabel')
    clean_function_str('zValueLabel')

    chart_id = str(uuid.uuid4()).replace('-', '_')

    js_init = """
    var options = %s;
    %s
    window.opt = jQuery.extend(true, {}, options);
    console.log('vis3d options accessible as opt');
    
    var data = %s;
    %s
    window.dta = jQuery.extend(true, [], data);
    console.log('vis3d data accessible as dta');
    """ % (json_dumps(_options), JS_JSON_PARSE_OPTION,
           json_dumps(_data), JS_JSON_PARSE_DATA)

    js_call = """
    var container = document.getElementById('%s');
    console.log(options);
    console.log(data);
    graph3d = new vis.Graph3d(container, data, options);
    """ % (chart_id)

    if center:
        if not 'width' in _options.keys():
            # Explicitly sets width to default value
            _options['width'] = '750px'

        html = """
        <div id="%s" style="margin: auto; width: %s;"></div>
        """ % (chart_id, _options['width'])
    else:
        html = """
        <div id="%s"></div>
        """ % (chart_id)

    css = """
    <link href="%s" rel="stylesheet" type="text/css" />
    """ % (CSS_LIBS_ONE)

    js = """<script>
    // the Jupyter notebook loads jquery.min.js  and require.js and at the top of the page
    // then to make jquery available inside a require module
    // the trick is http://www.manuel-strehl.de/dev/load_jquery_before_requirejs.en.html
    require(%s, function(lib) {
        window.vis = jQuery.extend(true, {}, lib);
        %s
        %s
    });
    </script>""" % (JS_LIBS_ONE, js_init, js_call)

    # save
    js_load = ''.join(['<script src="%s"></script>' % e for e in JS_SAVE])
    if save == True:
        if not os.path.exists(save_path):
            os.makedirs(save_path)
        tag = save_name if save_name else 'plot'
        dated = dt.datetime.now().strftime('_%Y%m%d_%H%M%S') if dated else ''

        with open(os.path.join(save_path, tag + dated + '.html'), 'w') as f:
            f.write(js_load + html + js)

    if notebook:
        return html + js
    else:
        return js_load + html + js

    return html + css + js
479238
function string_to_color(str) {
	// Generate a Hash for the String
	var hash = function(word) {
		var h = 0;
		for (var i = 0; i < word.length; i++) {
			h = word.charCodeAt(i) + ((h << 5) - h);
		}
		return h;
	};

	// Change the darkness or lightness
	var shade = function(color, prc) {
		var num = parseInt(color, 16),
		    amt = Math.round(2.55 * prc),
		    R = (num >> 16) + amt,
		    G = (num >> 8 & 0x00FF) + amt,
		    B = (num & 0x0000FF) + amt;
		return (0x1000000 + (R < 255 ? R < 1 ? 0 : R : 255) * 0x10000 +
			(G < 255 ? G < 1 ? 0 : G : 255) * 0x100 +
			(B < 255 ? B < 1 ? 0 : B : 255))
			.toString(16)
			.slice(1);
	};

	// Convert init to an RGBA
	var int_to_rgba = function(i) {
		var color = ((i >> 24) & 0xFF).toString(16) +
			((i >> 16) & 0xFF).toString(16) +
			((i >> 8) & 0xFF).toString(16) +
			(i & 0xFF).toString(16);
		return color;
	};

	return shade(
		int_to_rgba(hash(str)),
		-10
	);
}
27381
def convert_value_to_text r
        str = []
        fmt = nil
        field = nil
        # we need to loop through chash and get index from it and get that row from r
        each_column {|c,i|
          e = r[c.index]
          w = c.width
          l = e.to_s.length
          # if value is longer than width, then truncate it
          if l > w
            fmt = "%.#{w}s "
          else
            case c.align
            when :right
              fmt = "%#{w}s "
            else
              fmt = "%-#{w}s "
            end
          end
          field = fmt % e
          # if we really want to print a single column with color, we need to print here itself
          # each cell. If we want the user to use tmux formatting in the column itself ...
          # FIXME - this must not be done for headers.
          #if c.color
          #field = "#[fg=#{c.color}]#{field}#[/end]"
          #end
          str << field
        }
        return str
      end
938690
function transformColor(string) {
  return parser(string).walk(function(node) {
    if (node.type !== "function" || node.value !== "color") {
      return
    }

    node.value = colorFn.convert(parser.stringify(node))
    node.type = "word"
  }).toString()
}
524773
def convert(cls, style_dict, num_format_str=None):
        

        # Create a XlsxWriter format object.
        props = {}

        if num_format_str is not None:
            props['num_format'] = num_format_str

        if style_dict is None:
            return props

        if 'borders' in style_dict:
            style_dict = style_dict.copy()
            style_dict['border'] = style_dict.pop('borders')

        for style_group_key, style_group in style_dict.items():
            for src, dst in cls.STYLE_MAPPING.get(style_group_key, []):
                # src is a sequence of keys into a nested dict
                # dst is a flat key
                if dst in props:
                    continue
                v = style_group
                for k in src:
                    try:
                        v = v[k]
                    except (KeyError, TypeError):
                        break
                else:
                    props[dst] = v

        if isinstance(props.get('pattern'), str):
            # TODO: support other fill patterns
            props['pattern'] = 0 if props['pattern'] == 'none' else 1

        for k in ['border', 'top', 'right', 'bottom', 'left']:
            if isinstance(props.get(k), str):
                try:
                    props[k] = ['none', 'thin', 'medium', 'dashed', 'dotted',
                                'thick', 'double', 'hair', 'mediumDashed',
                                'dashDot', 'mediumDashDot', 'dashDotDot',
                                'mediumDashDotDot',
                                'slantDashDot'].index(props[k])
                except ValueError:
                    props[k] = 2

        if isinstance(props.get('font_script'), str):
            props['font_script'] = ['baseline', 'superscript',
                                    'subscript'].index(props['font_script'])

        if isinstance(props.get('underline'), str):
            props['underline'] = {'none': 0, 'single': 1, 'double': 2,
                                  'singleAccounting': 33,
                                  'doubleAccounting': 34}[props['underline']]

        return props
1272847
function message( data , color ) {
	var k , messageString = '' ;

	if ( data.mon ) {
		messageString = '\n' ;

		if ( color ) {
			for ( k in data.mon ) {
				messageString += string.ansi.green + k + string.ansi.reset + ': ' +
					string.ansi.cyan + data.mon[ k ] + string.ansi.reset + '\n' ;
			}
		}
		else {
			for ( k in data.mon ) { messageString += k + ': ' + data.mon[ k ] + '\n' ; }
		}
	}
	else if ( Array.isArray( data.messageData ) && data.isFormat ) {
		//if ( color ) { messageString = string.ansi.italic + string.formatMethod.apply( { color: true } , data.messageData ) ; }
		//else { messageString = string.formatMethod.apply( { color: false } , data.messageData ) ; }

		messageString = string.formatMethod.apply( color ? formatColor : format , data.messageData ) ;
	}
	else if ( data.messageData instanceof Error ) {
		messageString = string.inspectError( { style: color ? 'color' : 'none' } , data.messageData ) ;
	}
	else if ( typeof data.messageData !== 'string' ) {
		messageString = string.inspect( { style: color ? 'color' : 'none' } , data.messageData ) ;
	}
	else {
		// Even if messageData is not an array, it may contains markup, so it should be formated anyway
		//messageString = data.messageData ;
		messageString = string.formatMethod.call( color ? formatColor : format , data.messageData ) ;
	}

	return messageString ;
}
617305
def foreground_chart(chart, background, colors):
    
    def convert_foreground(entry):
        try:
            attr = urwid.AttrSpec(entry, background, colors)
        except urwid.AttrSpecError:
            return None
        return attr, entry
    return parse_chart(chart, convert_foreground)
418850
function text ({str, x, y}){
  return [
    svg(`text fill=#010101 fill-opacity=.3 x=${x} y=${y + 1}`, str),
    svg(`text fill=#fff x=${x} y=${y}`, str)
  ]
}
1304337
public static String collectChar(String string, CharToCharFunction function)
    {
        int size = string.length();
        StringBuilder builder = new StringBuilder(size);
        for (int i = 0; i < size; i++)
        {
            builder.append(function.valueOf(string.charAt(i)));
        }
        return builder.toString();
    }
647461
def make_palette(self):
        

        p = array('B')
        t = array('B')

        for x in self.palette:
            p.extend(x[0:3])
            if len(x) > 3:
                t.append(x[3])
        p = tostring(p)
        t = tostring(t)
        if t:
            return p,t
        return p,None
739129
function (str, x, y, options, redraw) {
            if (typeof options === "undefined") { options = {}; }
            if (typeof redraw === "undefined") { redraw = false; }
            var defaults = {
                font: 'Helvetica',
                fontSize: 12,
                // lineWidth:  0.05,
                textColor: 'rgba(0, 0, 0, 1)'
            }, ctx, prop, opts;

            ctx = this.ctx;

            opts = MathLib.Canvas.convertOptions(MathLib.extendObject(defaults, options));

            for (prop in opts) {
                if (opts.hasOwnProperty(prop)) {
                    ctx[prop] = opts[prop];
                }
            }

            ctx.fillStyle = MathLib.colorConvert(options.textColor || options.color || defaults.textColor);
            ctx.strokeStyle = MathLib.colorConvert(options.textColor || options.color || defaults.textColor);

            ctx.font = opts.fontSize + 'px ' + opts.font;
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';

            var tf = this.screen.transformation;

            ctx.save();
            ctx.transform(1 / tf[0][0], 0, 0, 1 / tf[1][1], 0, 0);
            ctx.fillText(str, tf[0][0] * x, tf[1][1] * y);
            ctx.restore();

            if (!redraw) {
                this.stack.push({
                    type: 'text',
                    object: str,
                    x: x,
                    y: y,
                    options: options
                });
            }

            return this;
        }
1175083
function charType(c){
    if(/[a-z]/.test(c)) return LOWER;
    if(/[A-Z]/.test(c)) return UPPER;
    if(/[0-9]/.test(c)) return NUMBER;
    if(/[\/\-_\.]/.test(c)) return COMMON_DELIMS;
    return OTHER;
  }
303805
def _convert_label(label):
    
    style = qt_font_to_style(label.get("font"), label.get("color"))
    return {
        "text": html.escape(label["text"]),
        "rotation": 0,
        "style": style,
        "x": int(label["x"]),
        "y": int(label["y"])
    }
478106
function (item) {
            var legend = this,
              chart = legend.chart,
              renderer = chart.renderer,
              options = legend.options,
              horizontal = options.layout === 'horizontal',
              symbolWidth = legend.symbolWidth,
              symbolPadding = options.symbolPadding,
              itemStyle = legend.itemStyle,
              itemHiddenStyle = legend.itemHiddenStyle,
              padding = legend.padding,
              itemDistance = horizontal ? pick(options.itemDistance, 20) : 0,
              ltr = !options.rtl,
              itemHeight,
              widthOption = options.width,
              itemMarginBottom = options.itemMarginBottom || 0,
              itemMarginTop = legend.itemMarginTop,
              initialItemX = legend.initialItemX,
              bBox,
              itemWidth,
              li = item.legendItem,
              series = item.series && item.series.drawLegendSymbol ? item.series : item,
              seriesOptions = series.options,
              showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox,
              useHTML = options.useHTML;

            if (!li) { // generate it once, later move it

                // Generate the group box
                // A group to hold the symbol and text. Text is to be appended in Legend class.
                item.legendGroup = renderer.g('legend-item')
                  .attr({ zIndex: 1 })
                  .add(legend.scrollGroup);

                // Generate the list item text and add it to the group
                item.legendItem = li = renderer.text(
                  options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item),
                  ltr ? symbolWidth + symbolPadding : -symbolPadding,
                    legend.baseline || 0,
                  useHTML
                  )
                  .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021)
                  .attr({
                      align: ltr ? 'left' : 'right',
                      zIndex: 2
                  })
                  .add(item.legendGroup);

                // Get the baseline for the first item - the font size is equal for all
                if (!legend.baseline) {
                    legend.baseline = renderer.fontMetrics(itemStyle.fontSize, li).f + 3 + itemMarginTop;
                    li.attr('y', legend.baseline);
                }

                // Draw the legend symbol inside the group box
                series.drawLegendSymbol(legend, item);

                if (legend.setItemEvents) {
                    legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle);
                }

                // Colorize the items
                legend.colorizeItem(item, item.visible);

                // add the HTML checkbox on top
                if (showCheckbox) {
                    legend.createCheckboxForItem(item);
                }
            }

            // calculate the positions for the next line
            bBox = li.getBBox();

            itemWidth = item.checkboxOffset =
              options.itemWidth ||
              item.legendItemWidth ||
              symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0);
            legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height);

            // if the item exceeds the width, start a new line
            if (horizontal && legend.itemX - initialItemX + itemWidth >
              (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) {
                legend.itemX = initialItemX;
                legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
                legend.lastLineHeight = 0; // reset for next line
            }

            // If the item exceeds the height, start a new column
            /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
             legend.itemY = legend.initialItemY;
             legend.itemX += legend.maxItemWidth;
             legend.maxItemWidth = 0;
             }*/

            // Set the edge positions
            legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth);
            legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
            legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915

            // cache the position of the newly generated or reordered items
            item._legendItemPos = [legend.itemX, legend.itemY];

            // advance
            if (horizontal) {
                legend.itemX += itemWidth;

            } else {
                legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
                legend.lastLineHeight = itemHeight;
            }

            // the width of the widest item
            legend.offsetWidth = widthOption || mathMax(
                (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding,
                legend.offsetWidth
              );
        }
954273
def to_xml_string(str = '')
      super(str) do
        str << '<c:scatterChart>'
        str << ('<c:scatterStyle val="' << scatter_style.to_s << '"/>')
        str << ('<c:varyColors val="' << vary_colors.to_s << '"/>')
        @series.each { |ser| ser.to_xml_string(str) }
        d_lbls.to_xml_string(str) if @d_lbls
        axes.to_xml_string(str, :ids => true)
        str << '</c:scatterChart>'
        axes.to_xml_string(str)
      end
      str
    end
1314399
def _chart(self, x, y, chart_type, opts, style, label, options, **kwargs):
		
		if opts is not None:
			self.chart_opts = opts
		if style is not None:
			self.chart_style = style
		if label is not None:
			self.label = label
		self.x = x
		self.y = y
		if chart_type is None:
			return
		try:
			chart_obj = self._get_chart(chart_type, x, y, style=style,
										opts=opts, label=label,
										options=options, **kwargs)
			return chart_obj
		except Exception as e:
			self.err(e)