Embed svg symbols
179519
def embed_script(names=nil)
      if production?
        embeds = buildable_svgs(names).map(&:embed)
      else
        embeds = find_svgs(names).map(&:embed)
      end

      write_cache if cache_stale?

      if !embeds.empty?
        "<script>#{js(embeds.join("\n"))}</script>"
      end

    end
529808
def svg
      x = 0
      height = 60

      builder = Builder::XmlMarkup.new(indent: 2)
      builder.instruct!(:xml, version: '1.0', encoding: 'UTF-8')
      builder.svg(xmlns: 'http://www.w3.org/2000/svg', width: 113, height: height) do |svg|
        svg.rect(x: 0, y: 0, width: 113, height: 60, fill: 'white')
        band_patterns.each do |band_pattern|
          svg.g(class: band_pattern.class.name.split('::').last) do |group|
            band_pattern.bands.each do |band|
              group.rect(x: x,  y: 0, width: band.width, height: height, fill: band.color)
              x += band.width
            end
          end
        end
      end
    end
939989
function (el, evalScripts, pngFallback, callback) {

    // Grab the src or data-src attribute
    var imgUrl = el.getAttribute('data-src') || el.getAttribute('src');

    // We can only inject SVG
    if (!(/\.svg/i).test(imgUrl)) {
      callback('Attempted to inject a file with a non-svg extension: ' + imgUrl);
      return;
    }

    // If we don't have SVG support try to fall back to a png,
    // either defined per-element via data-fallback or data-png,
    // or globally via the pngFallback directory setting
    if (!hasSvgSupport) {
      var perElementFallback = el.getAttribute('data-fallback') || el.getAttribute('data-png');

      // Per-element specific PNG fallback defined, so use that
      if (perElementFallback) {
        el.setAttribute('src', perElementFallback);
        callback(null);
      }
      // Global PNG fallback directoriy defined, use the same-named PNG
      else if (pngFallback) {
        el.setAttribute('src', pngFallback + '/' + imgUrl.split('/').pop().replace('.svg', '.png'));
        callback(null);
      }
      // um...
      else {
        callback('This browser does not support SVG and no PNG fallback was defined.');
      }

      return;
    }

    // Make sure we aren't already in the process of injecting this element to
    // avoid a race condition if multiple injections for the same element are run.
    // :NOTE: Using indexOf() only _after_ we check for SVG support and bail,
    // so no need for IE8 indexOf() polyfill
    if (injectedElements.indexOf(el) !== -1) {
      return;
    }

    // Remember the request to inject this element, in case other injection
    // calls are also trying to replace this element before we finish
    injectedElements.push(el);

    // Try to avoid loading the orginal image src if possible.
    el.setAttribute('src', '');

    // Load it up
    loadSvg(imgUrl, function (svg) {

      if (typeof svg === 'undefined' || typeof svg === 'string') {
        callback(svg);
        return false;
      }

      var imgId = el.getAttribute('id');
      if (imgId) {
        svg.setAttribute('id', imgId);
      }

      var imgTitle = el.getAttribute('title');
      if (imgTitle) {
        svg.setAttribute('title', imgTitle);
      }

      // Concat the SVG classes + 'injected-svg' + the img classes
      var classMerge = [].concat(svg.getAttribute('class') || [], 'injected-svg', el.getAttribute('class') || []).join(' ');
      svg.setAttribute('class', uniqueClasses(classMerge));

      var imgStyle = el.getAttribute('style');
      if (imgStyle) {
        svg.setAttribute('style', imgStyle);
      }

      // Copy all the data elements to the svg
      var imgData = [].filter.call(el.attributes, function (at) {
        return (/^data-\w[\w\-]*$/).test(at.name);
      });
      forEach.call(imgData, function (dataAttr) {
        if (dataAttr.name && dataAttr.value) {
          svg.setAttribute(dataAttr.name, dataAttr.value);
        }
      });

      // Make sure any internally referenced clipPath ids and their
      // clip-path references are unique.
      //
      // This addresses the issue of having multiple instances of the
      // same SVG on a page and only the first clipPath id is referenced.
      //
      // Browsers often shortcut the SVG Spec and don't use clipPaths
      // contained in parent elements that are hidden, so if you hide the first
      // SVG instance on the page, then all other instances lose their clipping.
      // Reference: https://bugzilla.mozilla.org/show_bug.cgi?id=376027

      // Handle all defs elements that have iri capable attributes as defined by w3c: http://www.w3.org/TR/SVG/linking.html#processingIRI
      // Mapping IRI addressable elements to the properties that can reference them:
      var iriElementsAndProperties = {
        'clipPath': ['clip-path'],
        'color-profile': ['color-profile'],
        'cursor': ['cursor'],
        'filter': ['filter'],
        'linearGradient': ['fill', 'stroke'],
        'marker': ['marker', 'marker-start', 'marker-mid', 'marker-end'],
        'mask': ['mask'],
        'pattern': ['fill', 'stroke'],
        'radialGradient': ['fill', 'stroke']
      };

      var element, elementDefs, properties, currentId, newId;
      Object.keys(iriElementsAndProperties).forEach(function (key) {
        element = key;
        properties = iriElementsAndProperties[key];

        elementDefs = svg.querySelectorAll('defs ' + element + '[id]');
        for (var i = 0, elementsLen = elementDefs.length; i < elementsLen; i++) {
          currentId = elementDefs[i].id;
          newId = currentId + '-' + injectCount;

          // All of the properties that can reference this element type
          var referencingElements;
          forEach.call(properties, function (property) {
            // :NOTE: using a substring match attr selector here to deal with IE "adding extra quotes in url() attrs"
            referencingElements = svg.querySelectorAll('[' + property + '*="' + currentId + '"]');
            for (var j = 0, referencingElementLen = referencingElements.length; j < referencingElementLen; j++) {
              referencingElements[j].setAttribute(property, 'url(#' + newId + ')');
            }
          });

          elementDefs[i].id = newId;
        }
      });

      // Remove any unwanted/invalid namespaces that might have been added by SVG editing tools
      svg.removeAttribute('xmlns:a');

      // Post page load injected SVGs don't automatically have their script
      // elements run, so we'll need to make that happen, if requested

      // Find then prune the scripts
      var scripts = svg.querySelectorAll('script');
      var scriptsToEval = [];
      var script, scriptType;

      for (var k = 0, scriptsLen = scripts.length; k < scriptsLen; k++) {
        scriptType = scripts[k].getAttribute('type');

        // Only process javascript types.
        // SVG defaults to 'application/ecmascript' for unset types
        if (!scriptType || scriptType === 'application/ecmascript' || scriptType === 'application/javascript') {

          // innerText for IE, textContent for other browsers
          script = scripts[k].innerText || scripts[k].textContent;

          // Stash
          scriptsToEval.push(script);

          // Tidy up and remove the script element since we don't need it anymore
          svg.removeChild(scripts[k]);
        }
      }

      // Run/Eval the scripts if needed
      if (scriptsToEval.length > 0 && (evalScripts === 'always' || (evalScripts === 'once' && !ranScripts[imgUrl]))) {
        for (var l = 0, scriptsToEvalLen = scriptsToEval.length; l < scriptsToEvalLen; l++) {

          // :NOTE: Yup, this is a form of eval, but it is being used to eval code
          // the caller has explictely asked to be loaded, and the code is in a caller
          // defined SVG file... not raw user input.
          //
          // Also, the code is evaluated in a closure and not in the global scope.
          // If you need to put something in global scope, use 'window'
          new Function(scriptsToEval[l])(window); // jshint ignore:line
        }

        // Remember we already ran scripts for this svg
        ranScripts[imgUrl] = true;
      }

      // :WORKAROUND:
      // IE doesn't evaluate <style> tags in SVGs that are dynamically added to the page.
      // This trick will trigger IE to read and use any existing SVG <style> tags.
      //
      // Reference: https://github.com/iconic/SVGInjector/issues/23
      var styleTags = svg.querySelectorAll('style');
      forEach.call(styleTags, function (styleTag) {
        styleTag.textContent += '';
      });

      // Replace the image with the svg
      el.parentNode.replaceChild(svg, el);

      // Now that we no longer need it, drop references
      // to the original element so it can be GC'd
      delete injectedElements[injectedElements.indexOf(el)];
      el = null;

      // Increment the injected count
      injectCount++;

      callback(svg);
    });
  }
967382
function svgUrl(name, collection) {
  for (var i = 0, result; i < COLLECTION_FILTERS.length; i++) {
    if (COLLECTION_FILTERS[i][0].test(collection)) {
      result = COLLECTION_FILTERS[i][1];
      collection = _.isFunction(result)? result(collection) : result;
      break;
    }
  }
  return 'https://raw.github.com/fontello/' + collection +
         '/master/src/svg/' + name + '.svg';
}
947202
function svgStyle($critere_style, $attribs, $element)
	{
		$path_style = '';
		$fill_gradient = '';
		$w = '';
		$style = '';
		if (substr_count($critere_style['fill'], 'url') > 0 && $element != 'line') {
			//
			// couleur degradé
			$id_gradient = preg_replace("/url\(#([\w_]*)\)/i", "$1", $critere_style['fill']);
			if ($id_gradient != $critere_style['fill']) {
				if (isset($this->svg_gradient[$id_gradient])) {
					$fill_gradient = $this->svgGradient($this->svg_gradient[$id_gradient], $attribs, $element);
					if ($fill_gradient) {
						$path_style = "q ";
						$w = "W";
						$style .= 'N';
					}
				}
			}
		} // Used as indirect setting for currentColor
		else if (strtolower($critere_style['fill']) == 'currentcolor' && $element != 'line') {
			$col = $this->colorConverter->convert($critere_style['color'], $this->mpdf->PDFAXwarnings);
			if ($col) {
				if ($col{0} == 5 && is_numeric($col{4})) {
					$critere_style['fill-opacity'] = ord($col{4} / 100);
				} // RGBa
				if ($col{0} == 6 && is_numeric($col{5})) {
					$critere_style['fill-opacity'] = ord($col{5} / 100);
				} // CMYKa
				$path_style .= $this->mpdf->SetFColor($col, true) . ' ';
				$style .= 'F';
			}
		} else if ($critere_style['fill'] != 'none' && $element != 'line') {
			$col = $this->colorConverter->convert($critere_style['fill'], $this->mpdf->PDFAXwarnings);
			if ($col) {
				if ($col{0} == 5 && is_numeric($col{4})) {
					$critere_style['fill-opacity'] = ord($col{4} / 100);
				} // RGBa
				if ($col{0} == 6 && is_numeric($col{5})) {
					$critere_style['fill-opacity'] = ord($col{5} / 100);
				} // CMYKa
				$path_style .= $this->mpdf->SetFColor($col, true) . ' ';
				$style .= 'F';
			}
		}
		if (substr_count($critere_style['stroke'], 'url') > 0) {
			/*
			  // Cannot put a gradient on a "stroke" in PDF?
			  $id_gradient = preg_replace("/url\(#([\w_]*)\)/i","$1",$critere_style['stroke']);
			  if ($id_gradient != $critere_style['stroke']) {
			  if (isset($this->svg_gradient[$id_gradient])) {
			  $fill_gradient = $this->svgGradient($this->svg_gradient[$id_gradient], $attribs, $element);
			  if ($fill_gradient) {
			  $path_style = "q ";
			  $w = "W";
			  $style .= 'D';
			  }
			  }
			  }
			 */
		} // Used as indirect setting for currentColor
		else if (strtolower($critere_style['stroke']) == 'currentcolor') {
			$col = $this->colorConverter->convert($critere_style['color'], $this->mpdf->PDFAXwarnings);
			if ($col) {
				if ($col{0} == 5 && is_numeric($col{4})) {
					$critere_style['stroke-opacity'] = ord($col{4} / 100);
				} // RGBa
				if ($col{0} == 6 && is_numeric($col{5})) {
					$critere_style['stroke-opacity'] = ord($col{5} / 100);
				} // CMYKa
				$path_style .= $this->mpdf->SetDColor($col, true) . ' ';
				$style .= 'D';
				$lw = $this->ConvertSVGSizePixels($critere_style['stroke-width']);
				$path_style .= sprintf('%.3F w ', $lw * $this->kp);
			}
		} else if ($critere_style['stroke'] != 'none') {
			$col = $this->colorConverter->convert($critere_style['stroke'], $this->mpdf->PDFAXwarnings);
			if ($col) {
				// mPDF 5.0.051
				// mPDF 5.3.74
				if ($col{0} == 5 && is_numeric($col{4})) {
					$critere_style['stroke-opacity'] = ord($col{4} / 100);
				} // RGBa
				if ($col{0} == 6 && is_numeric($col{5})) {
					$critere_style['stroke-opacity'] = ord($col{5} / 100);
				} // CMYKa
				$path_style .= $this->mpdf->SetDColor($col, true) . ' ';
				$style .= 'D';
				$lw = $this->ConvertSVGSizePixels($critere_style['stroke-width']);
				$path_style .= sprintf('%.3F w ', $lw * $this->kp);
			}
		}


		if ($critere_style['stroke'] != 'none') {
			if ($critere_style['stroke-linejoin'] == 'miter') {
				$path_style .= ' 0 j ';
			} else if ($critere_style['stroke-linejoin'] == 'round') {
				$path_style .= ' 1 j ';
			} else if ($critere_style['stroke-linejoin'] == 'bevel') {
				$path_style .= ' 2 j ';
			}

			if ($critere_style['stroke-linecap'] == 'butt') {
				$path_style .= ' 0 J ';
			} else if ($critere_style['stroke-linecap'] == 'round') {
				$path_style .= ' 1 J ';
			} else if ($critere_style['stroke-linecap'] == 'square') {
				$path_style .= ' 2 J ';
			}

			if (isset($critere_style['stroke-miterlimit'])) {
				if ($critere_style['stroke-miterlimit'] == 'none') {
				} else if (preg_match('/^[\d.]+$/', $critere_style['stroke-miterlimit'])) {
					$path_style .= sprintf('%.2F M ', $critere_style['stroke-miterlimit']);
				}
			}
			if (isset($critere_style['stroke-dasharray'])) {
				$off = 0;
				$d = preg_split('/(,\s?|\s)/', $critere_style['stroke-dasharray']);
				if (count($d) == 1 && $d[0] == 0) {
					$path_style .= '[] 0 d ';
				} else {
					if (count($d) % 2 == 1) {
						$d = array_merge($d, $d);
					} // 5, 3, 1 => 5,3,1,5,3,1  OR 3 => 3,3
					$arr = '';
					for ($i = 0; $i < count($d); $i+=2) {
						$arr .= sprintf('%.3F %.3F ', $d[$i] * $this->kp, $d[$i + 1] * $this->kp);
					}
					if (isset($critere_style['stroke-dashoffset'])) {
						$off = $critere_style['stroke-dashoffset'] + 0;
					}
					$path_style .= sprintf('[%s] %.3F d ', $arr, $off * $this->kp);
				}
			}
		}

		if ($critere_style['fill-rule'] == 'evenodd') {
			$fr = '*';
		} else {
			$fr = '';
		}

		if (isset($critere_style['fill-opacity'])) {
			$opacity = 1;
			if ($critere_style['fill-opacity'] == 0) {
				$opacity = 0;
			} else if ($critere_style['fill-opacity'] > 1) {
				$opacity = 1;
			} else if ($critere_style['fill-opacity'] > 0) {
				$opacity = $critere_style['fill-opacity'];
			} else if ($critere_style['fill-opacity'] < 0) {
				$opacity = 0;
			}
			$gs = $this->mpdf->AddExtGState(['ca' => $opacity, 'BM' => '/Normal']);
			$this->mpdf->extgstates[$gs]['fo'] = true;
			$path_style .= sprintf(' /GS%d gs ', $gs);
		}

		if (isset($critere_style['stroke-opacity'])) {
			$opacity = 1;
			if ($critere_style['stroke-opacity'] == 0) {
				$opacity = 0;
			} else if ($critere_style['stroke-opacity'] > 1) {
				$opacity = 1;
			} else if ($critere_style['stroke-opacity'] > 0) {
				$opacity = $critere_style['stroke-opacity'];
			} else if ($critere_style['stroke-opacity'] < 0) {
				$opacity = 0;
			}
			$gs = $this->mpdf->AddExtGState(['CA' => $opacity, 'BM' => '/Normal']);
			$this->mpdf->extgstates[$gs]['fo'] = true;
			$path_style .= sprintf(' /GS%d gs ', $gs);
		}

		switch ($style) {
			case 'F':
				$op = 'f';
				break;
			case 'FD':
				$op = 'B';
				break;
			case 'ND':
				$op = 'S';
				break;
			case 'D':
				$op = 'S';
				break;
			default:
				$op = 'n';
		}

		$prestyle = $path_style . ' ';
		$poststyle = $w . ' ' . $op . $fr . ' ' . $fill_gradient . "\n";
		return [$prestyle, $poststyle];
	}
1236905
function svgToPng(rootFolder, currentFile, $) {
    var currentDirectory = path.dirname(currentFile);

    return editHTMLElement($, 'img', function($img) {
        var src = $img.attr('src');
        if (path.extname(src) !== '.svg') {
            return;
        }

        // Calcul absolute path for this
        src = LocationUtils.toAbsolute(src, currentDirectory, '.');

        // We avoid generating twice the same PNG
        var hash = crc.crc32(src).toString(16);
        var fileName = hash + '.png';

        // Input file path
        var inputPath = path.join(rootFolder, src);

        // Result file path
        var filePath = path.join(rootFolder, fileName);

        return fs.assertFile(filePath, function() {
            return imagesUtil.convertSVGToPNG(inputPath, filePath);
        })
        .then(function() {
            // Convert filename to a relative filename
            fileName = LocationUtils.relative(currentDirectory, fileName);

            // Replace src
            $img.attr('src', fileName);
        });
    });
}
729952
function processSVGContent(text) {
        if (destroyed) {
            return;
        }

        var query = config.queryString.replace('&', '&#38;'),
            dataUrlCount;

        dataUrlCount = util.countInStr(text, 'xlink:href="data:image');
        // remove data:urls from the SVG content if the number exceeds MAX_DATA_URLS
        if (dataUrlCount > MAX_DATA_URLS) {
            // remove all data:url images that are smaller than 5KB
            text = text.replace(/<image[\s\w-_="]*xlink:href="data:image\/[^"]{0,5120}"[^>]*>/ig, '');
        }

        // @TODO: remove this, because we no longer use any external assets in this way
        // modify external asset urls for absolute path
        text = text.replace(/href="([^"#:]*)"/g, function (match, group) {
            return 'href="' + config.url + group + query + '"';
        });

        return scope.get('stylesheet').then(function (cssText) {
            return interpolateCSSText(text, cssText);
        });
    }
944789
def badge_svg_text(self):
        """"""

        # Identify whether template is a file or the actual template text
        if len(self.template.split('\n')) == 1:
            with open(self.template, mode='r') as file_handle:
                badge_text = file_handle.read()
        else:
            badge_text = self.template

        return badge_text.replace('{{ badge width }}', str(self.badge_width)) \
            .replace('{{ font name }}', self.font_name) \
            .replace('{{ font size }}', str(self.font_size)) \
            .replace('{{ label }}', self.label) \
            .replace('{{ value }}', self.value_text) \
            .replace('{{ label anchor }}', str(self.label_anchor)) \
            .replace('{{ label anchor shadow }}', str(self.label_anchor_shadow)) \
            .replace('{{ value anchor }}', str(self.value_anchor)) \
            .replace('{{ value anchor shadow }}', str(self.value_anchor_shadow)) \
            .replace('{{ color }}', self.badge_color_code) \
            .replace('{{ label text color }}', self.label_text_color) \
            .replace('{{ value text color }}', self.value_text_color) \
            .replace('{{ color split x }}', str(self.color_split_position)) \
            .replace('{{ value width }}', str(self.badge_width - self.color_split_position))
1038674
def svg2rlg(path, **kwargs):
    ""

    # unzip .svgz file into .svg
    unzipped = False
    if isinstance(path, str) and os.path.splitext(path)[1].lower() == ".svgz":
        with gzip.open(path, 'rb') as f_in, open(path[:-1], 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out)
        path = path[:-1]
        unzipped = True

    svg_root = load_svg_file(path)
    if svg_root is None:
        return

    # convert to a RLG drawing
    svgRenderer = SvgRenderer(path, **kwargs)
    drawing = svgRenderer.render(svg_root)

    # remove unzipped .svgz file (.svg)
    if unzipped:
        os.remove(path)

    return drawing
815074
function _legends(id, makeSVG) {
  let classed = 'chart-legends', 
      theme = 'light',
      background = undefined,
      width = DEFAULT_SIZE,
      height = null,
      margin = DEFAULT_MARGIN,
      inset = DEFAULT_INSET,
      padding = DEFAULT_INSET,
      textPadding = DEFAULT_INSET,
      style = undefined,
      legendSize = DEFAULT_LEGEND_SIZE,
      radius = DEFAULT_LEGEND_RADIUS,
      msize = DEFAULT_LEGEND_TEXT_SCALE,
      fontSize = undefined,
      fontFill = undefined,
      orientation = 'bottom',
      fill = null,
      scale = 1.0;
 
  function _makeFillFn() {
    let colors = () => fill;
    if (fill == null) {
      let c = presentation10.standard;
      colors = (d, i) => (c[i % c.length]);
    } else if (typeof fill === 'function') {
      colors = fill;
    } else if (Array.isArray(fill)) {
      colors = (d, i) => fill[ i % fill.length ];
    }
    return colors;  
  }  

  function _impl(context) {
    let selection = context.selection ? context.selection() : context,
        transition = (context.selection !== undefined);
      
    let _inset = _impl.canonicalInset();
    let _style = style;
    if (_style === undefined) {
      _style = _impl.defaultStyle();
    }       
    selection.each(function() {
      let node = select(this);  
      let _height = height || Math.round(width * DEFAULT_ASPECT);
      
      let elmS = node,
          w = width,
          h = _height;
          
      if (makeSVG === true) {
        let _background = background;
        if (_background === undefined) {
          _background = display[theme].background;
        }
        // SVG element
        let sid = null;
        if (id) sid = 'svg-' + id;
        let root = chartSVG(sid).width(w).height(h).margin(margin).scale(scale).style(_style).background(_background);
        let tnode = node;
        if (transition === true) {
          tnode = node.transition(context);
        }
        tnode.call(root);
        
        elmS = node.select(root.self()).select(root.child());
        w = root.childWidth();
        h = root.childHeight();
      }
      
      // Create required elements
      let g = elmS.select(_impl.self())
      if (g.empty()) {
        g = elmS.append('g').attr('class', classed).attr('id', id);
      }

      let legend = node.datum() || [];
      
      let lg = g.selectAll('g').data(legend);
      lg.exit().remove();
      let newlg = lg.enter().append('g');
      
      newlg.append('rect');
      newlg.append('text')
        .attr('dominant-baseline', 'central');
            
      let rect = g.selectAll('g rect').data(legend);
      let text = g.selectAll('g text').data(legend).text(d => d);

      let lens = legend.map(d => d == null ?  0 : d.length * msize + legendSize + textPadding + padding);
      
      if (orientation === 'left' || orientation === 'right') {
        let groups = g.selectAll('g').data(lens);
        groups = transition === true ? groups.transition(context) : groups;

        let idx = -1;
        let remap = legend.map(d => (d == null ? idx : ++idx));
        groups.attr('transform', (d, i) => 'translate(' + 0 + ',' + (remap[i] * (legendSize + padding)) + ')');
      } else {
        let clens = []
        let total = lens.reduce((p, c) => (clens.push(p) , p + c), 0) - padding; // trim the last padding
        let offset = -total / 2;
        let groups = g.selectAll('g').data(clens);
        
        groups = transition === true ? groups.transition(context) : groups;
        groups.attr('transform', (d) => 'translate(' + (offset + d) + ',0)');
      }
            
      if (transition === true) {
          g = g.transition(context);
          rect = rect.transition(context);
          text = text.transition(context);
      }      
      
      if (orientation === 'top') {
        g.attr('transform', 'translate(' + (w/2) + ',' + (_inset.top) + ')');
      } else if (orientation === 'left') {
        g.attr('transform', 'translate(' + _inset.left + ',' + ((h - legend.length * (legendSize + padding) + padding)/2) + ')');
      } else if (orientation === 'right') {
        g.attr('transform', 'translate(' + (w - _inset.right - legendSize) + ',' + ((h - legend.length * (legendSize + padding) + padding)/2) + ')');
      } else {
        g.attr('transform', 'translate(' + (w/2) + ',' + (h - _inset.bottom - legendSize) + ')');
      }

      let colors = _makeFillFn();
      
      rect.attr('rx', radius)
            .attr('ry', radius)
            .attr('width', d => d != null ? legendSize : 0)
            .attr('height', d => d != null ? legendSize : 0)
            .attr('fill', colors);

      text.attr('y', legendSize / 2)
          .attr('fill', fontFill === undefined ? display[theme].text : fontFill)
          .attr('font-size', fontSize === undefined ? fonts.fixed.sizeForWidth(w) : fontSize);
      if (orientation === 'right') {
        text.attr('x', () => -textPadding).attr('text-anchor', 'end');
      } else {
        text.attr('x', () => legendSize + textPadding).attr('text-anchor', 'start');
      }
      


    });
    
  }
  
  _impl.self = function() { return 'g' + (id ?  '#' + id : '.' + classed); }

  _impl.id = function() {
    return id;
  };
  
  _impl.defaultStyle = () => `${fonts.fixed.cssImport}
                              ${_impl.self()} text { 
                                font-family: ${fonts.fixed.family}; 
                                font-weight: ${fonts.fixed.weightMonochrome}; }
  `;
      
  _impl.childWidth = function() {
    let _inset = _impl.canonicalInset();
    return _inset.left + _inset.right + legendSize;
  };
  
  _impl.childHeight = function() {
    let _inset = _impl.canonicalInset();
    return _inset.top + _inset.bottom + legendSize;
  };
  
  _impl.childInset = function(inset) {
    if (inset == null) inset = 0;
    
    if (typeof inset !== 'object') {
      inset = { top: inset, left: inset, right: inset, bottom: inset };
    } else {
      inset = { top: inset.top, left: inset.left, right: inset.right, bottom: inset.bottom };
    }
    let legendOrientation = _impl.orientation();
    if (legendOrientation === 'top') {
      inset.top = inset.top + _impl.childHeight();
    } else if (legendOrientation === 'left') {
      inset.left = inset.left + _impl.childWidth();
    } else if (legendOrientation === 'right') { 
      inset.right = inset.right + _impl.childWidth();
    } else {
      inset.bottom = inset.bottom + _impl.childHeight();
    }   
    return inset;
  };        

  _impl.canonicalMargin = function() {
    let _margin = margin;
    if (_margin == null) _margin = 0;
    if (typeof _margin === 'object') {
      _margin = { top: _margin.top, bottom: _margin.bottom, left: _margin.left, right: _margin.right };
    } else {
      _margin = { top: _margin, bottom: _margin, left: _margin, right: _margin };
    }
    
    return _margin;    
  };  

  _impl.canonicalInset = function() {
    let _inset = inset;
    if (_inset == null) _inset = 0;
    if (typeof _inset === 'object') {
      _inset = { top: _inset.top, bottom: _inset.bottom, left: _inset.left, right: _inset.right };
    } else {
      _inset = { top: _inset, bottom: _inset, left: _inset, right: _inset };
    }
    
    return _inset;    
  };  
    
  _impl.classed = function(value) {
    return arguments.length ? (classed = value, _impl) : classed;
  };
    
  _impl.background = function(value) {
    return arguments.length ? (background = value, _impl) : background;
  };

  _impl.theme = function(value) {
    return arguments.length ? (theme = value, _impl) : theme;
  };  

  _impl.size = function(value) {
    return arguments.length ? (width = value, height = null, _impl) : width;
  };
    
  _impl.width = function(value) {
    return arguments.length ? (width = value, _impl) : width;
  };  

  _impl.height = function(value) {
    return arguments.length ? (height = value, _impl) : height;
  }; 

  _impl.scale = function(value) {
    return arguments.length ? (scale = value, _impl) : scale;
  }; 

  _impl.margin = function(value) {
    return arguments.length ? (margin = value, _impl) : margin;
  };   

  _impl.inset = function(value) {
    return arguments.length ? (inset = value, _impl) : inset;
  };  

  _impl.style = function(value) {
    return arguments.length ? (style = value, _impl) : style;
  }; 
  
  _impl.padding = function(value) {
    return arguments.length ? (padding = value, _impl) : padding;
  };   
  
  _impl.fill = function(value) {
    return arguments.length ? (fill = value, _impl) : fill;
  };    

  _impl.textPadding = function(value) {
    return arguments.length ? (textPadding = value, _impl) : textPadding;
  };  

  _impl.msize = function(value) {
    return arguments.length ? (msize = value, _impl) : msize;
  };   

  _impl.legendSize = function(value) {
    return arguments.length ? (legendSize = value, _impl) : legendSize;
  };  
      
  _impl.radius = function(value) {
    return arguments.length ? (radius = value, _impl) : radius;
  };    
  
  _impl.inset = function(value) {
    return arguments.length ? (inset = value, _impl) : inset;
  }; 
  
  _impl.orientation = function(value) {
    return arguments.length ? (orientation = value, _impl) : orientation;
  };     
              
  _impl.fontSize = function(value) {
    return arguments.length ? (fontSize = value, _impl) : fontSize;
  };                 

  _impl.fontFill = function(value) {
    return arguments.length ? (fontFill = value, _impl) : fontFill;
  };  

              
  return _impl;
}
1213673
function drawVerticalLegend() {
            svg.select('.legend-group')
                .selectAll('g')
                .remove();

            entries = svg.select('.legend-group')
                .selectAll('g.legend-line')
                .data(data);

            // Enter
            entries.enter()
              .append('g')
                .classed('legend-line', true)
                  .append('g')
                    .classed('legend-entry', true)
                    .attr('data-item', getId)
                    .attr('transform', function(d, i) {
                        let horizontalOffset = markerSize + getLineElementMargin(),
                            lineHeight = chartHeight/ (data.length + 1),
                            verticalOffset = (i + 1) * lineHeight;

                        return `translate(${horizontalOffset},${verticalOffset})`;
                    })
                    .merge(entries)
                  .append('circle')
                    .classed('legend-circle', true)
                    .attr('cx', markerSize/2)
                    .attr('cy', markerYOffset)
                    .attr('r', markerSize/2 )
                    .style('fill', getCircleFill)
                    .style('stroke-width', 1);

            svg.select('.legend-group')
                .selectAll('g.legend-line')
                .selectAll('g.legend-entry')
              .append('text')
                .classed('legend-entry-name', true)
                .text(getName)
                .attr('x', getLineElementMargin())
                .style('font-size', `${textSize}px`)
                .style('letter-spacing', `${textLetterSpacing}px`);

            if (hasQuantities) {
                writeEntryValues();
            } else {
                centerVerticalLegendOnSVG();
            }

            // Exit
            svg.select('.legend-group')
                .selectAll('g.legend-line')
                .exit()
                .transition()
                .style('opacity', 0)
                .remove();
        }
1258678
def generate_badge_png(title, value, color='#007ec6'):
    """"""
    badge = generate_badge_svg(title, value, color)
    return cairosvg.svg2png(badge)
883994
function svgShapesToPathRectToPath(attributes) {
  const x = 'undefined' !== typeof attributes.x ? parseFloat(attributes.x) : 0;
  const y = 'undefined' !== typeof attributes.y ? parseFloat(attributes.y) : 0;
  const width =
    'undefined' !== typeof attributes.width ? parseFloat(attributes.width) : 0;
  const height =
    'undefined' !== typeof attributes.height
      ? parseFloat(attributes.height)
      : 0;
  const rx =
    'undefined' !== typeof attributes.rx
      ? parseFloat(attributes.rx)
      : 'undefined' !== typeof attributes.ry ? parseFloat(attributes.ry) : 0;
  const ry =
    'undefined' !== typeof attributes.ry ? parseFloat(attributes.ry) : rx;

  return (
    '' +
    // start at the left corner
    'M' +
    (x + rx) +
    ' ' +
    y +
    // top line
    'h' +
    (width - rx * 2) +
    // upper right corner
    (rx || ry ? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx + ' ' + ry : '') +
    // Draw right side
    'v' +
    (height - ry * 2) +
    // Draw bottom right corner
    (rx || ry ? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx * -1 + ' ' + ry : '') +
    // Down the down side
    'h' +
    (width - rx * 2) * -1 +
    // Draw bottom right corner
    (rx || ry
      ? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx * -1 + ' ' + ry * -1
      : '') +
    // Down the left side
    'v' +
    (height - ry * 2) * -1 +
    // Draw bottom right corner
    (rx || ry ? 'a ' + rx + ' ' + ry + ' 0 0 1 ' + rx + ' ' + ry * -1 : '') +
    // Close path
    'z'
  );
}
54719
function (str, x, y) {
		var defaultChartStyle = defaultOptions.chart.style,
			wrapper = this.createElement('span'),
			attrSetters = wrapper.attrSetters,
			element = wrapper.element,
			renderer = wrapper.renderer;

		// Text setter
		attrSetters.text = function (value) {
			if (value !== element.innerHTML) {
				delete this.bBox;
			}
			element.innerHTML = value;
			return false;
		};

		// Various setters which rely on update transform
		attrSetters.x = attrSetters.y = attrSetters.align = function (value, key) {
			if (key === 'align') {
				key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
			}
			wrapper[key] = value;
			wrapper.htmlUpdateTransform();
			return false;
		};

		// Set the default attributes
		wrapper.attr({
				text: str,
				x: mathRound(x),
				y: mathRound(y)
			})
			.css({
				position: ABSOLUTE,
				whiteSpace: 'nowrap',
				fontFamily: defaultChartStyle.fontFamily,
				fontSize: defaultChartStyle.fontSize
			});

		// Use the HTML specific .css method
		wrapper.css = wrapper.htmlCss;

		// This is specific for HTML within SVG
		if (renderer.isSVG) {
			wrapper.add = function (svgGroupWrapper) {

				var htmlGroup,
					container = renderer.box.parentNode,
					parentGroup,
					parents = [];

				// Create a mock group to hold the HTML elements
				if (svgGroupWrapper) {
					htmlGroup = svgGroupWrapper.div;
					if (!htmlGroup) {

						// Read the parent chain into an array and read from top down
						parentGroup = svgGroupWrapper;
						while (parentGroup) {

							parents.push(parentGroup);

							// Move up to the next parent group
							parentGroup = parentGroup.parentGroup;
						}

						// Ensure dynamically updating position when any parent is translated
						each(parents.reverse(), function (parentGroup) {
							var htmlGroupStyle;

							// Create a HTML div and append it to the parent div to emulate
							// the SVG group structure
							htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, {
								className: attr(parentGroup.element, 'class')
							}, {
								position: ABSOLUTE,
								left: (parentGroup.translateX || 0) + PX,
								top: (parentGroup.translateY || 0) + PX
							}, htmlGroup || container); // the top group is appended to container

							// Shortcut
							htmlGroupStyle = htmlGroup.style;

							// Set listeners to update the HTML div's position whenever the SVG group
							// position is changed
							extend(parentGroup.attrSetters, {
								translateX: function (value) {
									htmlGroupStyle.left = value + PX;
								},
								translateY: function (value) {
									htmlGroupStyle.top = value + PX;
								},
								visibility: function (value, key) {
									htmlGroupStyle[key] = value;
								}
							});
						});

					}
				} else {
					htmlGroup = container;
				}

				htmlGroup.appendChild(element);

				// Shared with VML:
				wrapper.added = true;
				if (wrapper.alignOnAdd) {
					wrapper.htmlUpdateTransform();
				}

				return wrapper;
			};
		}
		return wrapper;
	}
833089
static void svgGradient( CssFormatter formatter, List<Expression> parameters ) {
        if( parameters.size() < 3 ) {
            throw new LessException( "error evaluating function `svg-gradient expects direction, start_color [start_position], [color position,]..., end_color " );
        }
        String direction = parameters.get( 0 ).stringValue( formatter );
        String gradientType = "linear";
        String rectangleDimension = "x=\"0\" y=\"0\" width=\"1\" height=\"1\"";
        String gradientDirection;
        switch( direction ) {
            case "to bottom":
                gradientDirection = "x1=\"0%\" y1=\"0%\" x2=\"0%\" y2=\"100%\"";
                break;
            case "to right":
                gradientDirection = "x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"0%\"";
                break;
            case "to bottom right":
                gradientDirection = "x1=\"0%\" y1=\"0%\" x2=\"100%\" y2=\"100%\"";
                break;
            case "to top right":
                gradientDirection = "x1=\"0%\" y1=\"100%\" x2=\"100%\" y2=\"0%\"";
                break;
            case "ellipse":
            case "ellipse at center":
                gradientType = "radial";
                gradientDirection = "cx=\"50%\" cy=\"50%\" r=\"75%\"";
                rectangleDimension = "x=\"-50\" y=\"-50\" width=\"101\" height=\"101\"";
                break;
            default:
                throw new LessException( "error evaluating function `svg-gradient`: svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'" );
        }
        StringBuilder builder = new StringBuilder( "<?xml version=\"1.0\" ?><svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"100%\" height=\"100%\" viewBox=\"0 0 1 1\" preserveAspectRatio=\"none\">" );
        builder.append( '<' ).append( gradientType ).append( "Gradient id=\"gradient\" gradientUnits=\"userSpaceOnUse\" " ).append( gradientDirection ).append( '>' );

        for( int i = 1; i < parameters.size(); i++ ) {
            Expression param = parameters.get( i ).unpack( formatter );
            double color;
            double position;
            if( param.getClass() == Operation.class && ((Operation)param).getOperator() == ' ' ) {
                ArrayList<Expression> operands = ((Operation)param).getOperands();
                color = getColor( operands.get( 0 ), formatter );
                position = ColorUtils.getPercent( operands.get( 1 ), formatter );
            } else {
                color = getColor( param, formatter );
                position = (i - 1) / (parameters.size() - 2.0);
            }
            builder.append( "<stop offset=\"" );
            position *= 100;
            if( position == (int)position ) {
                builder.append( (int)position );
            } else {
                builder.append( formatter.getFormat().format( position ) );
            }
            builder.append( "%\" stop-color=\"" );
            formatter.addOutput();
            formatter.appendColor( color, null );
            builder.append( formatter.releaseOutput() );
            builder.append( '\"' );
            double alpha = ColorUtils.alpha( color );
            if( alpha < 1 ) {
                builder.append( " stop-opacity=\"" + alpha ).append( '\"' );
            }
            builder.append( "/>" );
        }
        builder.append( "</" ).append( gradientType ).append( "Gradient><rect " ).append( rectangleDimension ).append( " fill=\"url(#gradient)\" /></svg>" );

        byte[] bytes = builder.toString().getBytes( StandardCharsets.UTF_8 );

        formatter.append( "url('data:image/svg+xml;base64," );
        formatter.append( toBase64( bytes ) );
        formatter.append( "\')" );
    }
1233372
function svgs(req, res) {
  const bundle = new Bundle(
    req.url.slice(1, -5).split('-').map(function map(name) {
      return assets[name];
    })
  );

  bundle.run(function (err, output) {
    if (err) throw err;

    res.setHeader('Content-Length', Buffer(output).length);
    res.writeHead(200, { 'Content-Type': 'text/plain' });

    res.end(output);
  });
}
462873
def parse_args():
    """"""
    import argparse
    import textwrap
    parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
                                     description=textwrap.dedent('''\
Command line utility to generate .svg badges.

This utility can be used to generate .svg badge images, using configurable
thresholds for coloring.  Values can be passed as string, integer or floating
point.  The type will be detected automatically.

Running the utility with a --file option will result in the .svg image being
written to file.  Without the --file option the .svg file content will be
written to stdout, so can be redirected to a file.

Some thresholds have been built in to save time.  To use these thresholds you
can simply specify the template name instead of threshold value/color pairs.

examples:

    Here are some usage specific examples that may save time on defining
    thresholds.

    Pylint
        anybadge.py --value=2.22 --file=pylint.svg pylint

        anybadge.py --label=pylint --value=2.22 --file=pylint.svg \\
          2=red 4=orange 8=yellow 10=green

    Coverage
        anybadge.py --value=65 --file=coverage.svg coverage

        anybadge.py --label=coverage --value=65 --suffix='%%' --file=coverage.svg \\
          50=red 60=orange 80=yellow 100=green

    CI Pipeline
        anybadge.py --label=pipeline --value=passing --file=pipeline.svg \\
          passing=green failing=red

'''))
    parser.add_argument('-l', '--label', type=str, help='The badge label.')
    parser.add_argument('-v', '--value', type=str, help='The badge value.', required=True)
    parser.add_argument('-m', '--value-format', type=str, default=None,
                        help='Formatting string for value (e.g. "%%.2f" for 2dp floats)')
    parser.add_argument('-c', '--color', type=str, help='For fixed color badges use --color'
                                                        'to specify the badge color.',
                        default=DEFAULT_COLOR)
    parser.add_argument('-p', '--prefix', type=str, help='Optional prefix for value.',
                        default='')
    parser.add_argument('-s', '--suffix', type=str, help='Optional suffix for value.',
                        default='')
    parser.add_argument('-d', '--padding', type=int, help='Number of characters to pad on '
                                                          'either side of the badge text.',
                        default=NUM_PADDING_CHARS)
    parser.add_argument('-n', '--font', type=str,
                        help='Font name.  Supported fonts: '
                             ','.join(['"%s"' % x for x in FONT_WIDTHS.keys()]),
                        default=DEFAULT_FONT)
    parser.add_argument('-z', '--font-size', type=int, help='Font size.',
                        default=DEFAULT_FONT_SIZE)
    parser.add_argument('-t', '--template', type=str, help='Location of alternative '
                                                           'template .svg file.',
                        default=TEMPLATE_SVG)
    parser.add_argument('-u', '--use-max', action='store_true',
                        help='Use the maximum threshold color when the value exceeds the '
                             'maximum threshold.')
    parser.add_argument('-f', '--file', type=str, help='Output file location.')
    parser.add_argument('-o', '--overwrite', action='store_true',
                        help='Overwrite output file if it already exists.')
    parser.add_argument('-r', '--text-color', type=str, help='Text color. Single value affects both label'
                                                             'and value colors.  A comma separated pair '
                                                             'affects label and value text respectively.',
                        default=DEFAULT_TEXT_COLOR)
    parser.add_argument('args', nargs=argparse.REMAINDER, help='Pairs of <upper>=<color>. '
                        'For example 2=red 4=orange 6=yellow 8=good. '
                        'Read this as "Less than 2 = red, less than 4 = orange...".')
    return parser.parse_args()