create TV gradient executor with input binded on img
11607
def get_tv_grad_executor(img, ctx, tv_weight):
    
    if tv_weight <= 0.0:
        return None
    nchannel = img.shape[1]
    simg = mx.sym.Variable("img")
    skernel = mx.sym.Variable("kernel")
    channels = mx.sym.SliceChannel(simg, num_outputs=nchannel)
    out = mx.sym.Concat(*[
        mx.sym.Convolution(data=channels[i], weight=skernel,
                           num_filter=1,
                           kernel=(3, 3), pad=(1,1),
                           no_bias=True, stride=(1,1))
        for i in range(nchannel)])
    kernel = mx.nd.array(np.array([[0, -1, 0],
                                   [-1, 4, -1],
                                   [0, -1, 0]])
                         .reshape((1, 1, 3, 3)),
                         ctx) / 8.0
    out = out * tv_weight
    return out.bind(ctx, args={"img": img,
                               "kernel": kernel})
3390
function (imagen, width, height, quality, type, ratio, centerCrop, resizeIf) {
    var deferred = $q.defer();
    var canvasElement = document.createElement('canvas');
    var imageElement = document.createElement('img');
    imageElement.setAttribute('style', 'visibility:hidden;position:fixed;z-index:-100000');
    document.body.appendChild(imageElement);

    imageElement.onload = function () {
      var imgWidth = imageElement.width, imgHeight = imageElement.height;
      imageElement.parentNode.removeChild(imageElement);
      if (resizeIf != null && resizeIf(imgWidth, imgHeight) === false) {
        deferred.reject('resizeIf');
        return;
      }
      try {
        if (ratio) {
          var ratioFloat = upload.ratioToFloat(ratio);
          var imgRatio = imgWidth / imgHeight;
          if (imgRatio < ratioFloat) {
            width = imgWidth;
            height = width / ratioFloat;
          } else {
            height = imgHeight;
            width = height * ratioFloat;
          }
        }
        if (!width) {
          width = imgWidth;
        }
        if (!height) {
          height = imgHeight;
        }
        var dimensions = calculateAspectRatioFit(imgWidth, imgHeight, width, height, centerCrop);
        canvasElement.width = Math.min(dimensions.width, width);
        canvasElement.height = Math.min(dimensions.height, height);
        var context = canvasElement.getContext('2d');
        context.drawImage(imageElement,
          Math.min(0, -dimensions.marginX / 2), Math.min(0, -dimensions.marginY / 2),
          dimensions.width, dimensions.height);
        deferred.resolve(canvasElement.toDataURL(type || 'image/WebP', quality || 0.934));
      } catch (e) {
        deferred.reject(e);
      }
    };
    imageElement.onerror = function () {
      imageElement.parentNode.removeChild(imageElement);
      deferred.reject();
    };
    imageElement.src = imagen;
    return deferred.promise;
  }
825813
public static void boundImage( GrayF64 img , double min , double max ) {
		ImplPixelMath.boundImage(img,min,max);
	}
649366
function init(input) {

            // Gradients
            if (input && input.stops) {
                stops = map(input.stops, function (stop) {
                    return Color(stop[1]);
                });

                // Solid colors
            } else {
                // rgba
                result = rgbaRegEx.exec(input);
                if (result) {
                    rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
                } else {
                    // hex
                    result = hexRegEx.exec(input);
                    if (result) {
                        rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1];
                    } else {
                        // rgb
                        result = rgbRegEx.exec(input);
                        if (result) {
                            rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
                        }
                    }
                }
            }

        }
794140
function pasteGradient(property, gradients) {
		var rule = property.parent;
		var alignVendor = prefs.get('css.alignVendor');
		var omitDir = prefs.get('css.gradient.omitDefaultDirection');
		
		// we may have aligned gradient definitions: find the smallest value
		// separator
		var sep = property.styleSeparator;
		var before = property.styleBefore;
		
		// first, remove all properties within CSS rule with the same name and
		// gradient definition
		rule.getAll(similarPropertyNames(property)).forEach(function(item) {
			if (item != property && /gradient/i.test(item.value())) {
				if (item.styleSeparator.length < sep.length) {
					sep = item.styleSeparator;
				}
				if (item.styleBefore.length < before.length) {
					before = item.styleBefore;
				}
				rule.remove(item);
			}
		});
		
		if (alignVendor) {
			// update prefix
			if (before != property.styleBefore) {
				var fullRange = property.fullRange();
				rule._updateSource(before, fullRange.start, fullRange.start + property.styleBefore.length);
				property.styleBefore = before;
			}
			
			// update separator value
			if (sep != property.styleSeparator) {
				rule._updateSource(sep, property.nameRange().end, property.valueRange().start);
				property.styleSeparator = sep;
			}
		}
		
		var value = property.value();

		// create list of properties to insert
		var propsToInsert = getPropertiesForGradient(gradients, property);
		
		// align prefixed values
		if (alignVendor) {
			var names = [], values = [];
			propsToInsert.forEach(function(item) {
				names.push(item.name);
				values.push(item.value);
			});
			values.push(property.value());
			names.push(property.name());
			
			var valuePads = utils.getStringsPads(values.map(function(v) {
				return v.substring(0, v.indexOf('('));
			}));
			
			var namePads = utils.getStringsPads(names);
			property.name(namePads[namePads.length - 1] + property.name());
			
			propsToInsert.forEach(function(prop, i) {
				prop.name = namePads[i] + prop.name;
				prop.value = valuePads[i] + prop.value;
			});
			
			property.value(valuePads[valuePads.length - 1] + property.value());
		}
		
		// put vendor-prefixed definitions before current rule
		propsToInsert.forEach(function(prop) {
			rule.add(prop.name, prop.value, rule.indexOf(property));
		});

		// put vanilla-clean gradient definition into current rule
		property.value(insertGradientsIntoCSSValue(gradients, value, {
			placeholder: '${2}',
			omitDefaultDirection: omitDir
		}));
	}
209607
def get(img, light=False):
    """"""
    cols = gen_colors(img)

    if len(cols) < 6:
        logging.error("colorz failed to generate enough colors.")
        logging.error("Try another backend or another image. (wal --backend)")
        sys.exit(1)

    return adjust(cols, light)
782515
function (cssText) {
            cssText = cssText.replace(/\burl\s*\(\s*["']?([^"'\r\n,]+|[^'\r\n,]+|[^"\r\n,]+)["']?\s*\)/gi, ariaUtilsFunction.bind(function (match, urlpart) {
                var prefixedUrl = ariaCoreAppEnvironment.applicationSettings.imgUrlMapping(urlpart, this.tplClasspath);
                return this._parseImgUrl(prefixedUrl);
            }, this));

            return cssText;
        }
783274
function minimizeImage(src, dest, cb) {
    squirrel(
        IMIN_MODULES, IMIN_OPTIONS,
        (err, Imagemin) => {
            const safeCb = (err) => {
                if (err) {
                    logger.error(err);
                }
                cb();
            };

            if (err) {
                safeCb(err);
            } else {
                const imin = new Imagemin()
                    .src(src)
                    .dest(dest)
                    .use(Imagemin.jpegtran({progressive: true}))
                    .use(Imagemin.optipng({optimizationLevel: 3}))
                    .use(Imagemin.gifsicle({interlaced: true}))
                    .use(Imagemin.svgo());

                imin.run(safeCb);
            }
        }
    );
}
222000
def _bar(s, align, colors, width=100, vmin=None, vmax=None):
        
        # Get input value range.
        smin = s.min() if vmin is None else vmin
        if isinstance(smin, ABCSeries):
            smin = smin.min()
        smax = s.max() if vmax is None else vmax
        if isinstance(smax, ABCSeries):
            smax = smax.max()
        if align == 'mid':
            smin = min(0, smin)
            smax = max(0, smax)
        elif align == 'zero':
            # For "zero" mode, we want the range to be symmetrical around zero.
            smax = max(abs(smin), abs(smax))
            smin = -smax
        # Transform to percent-range of linear-gradient
        normed = width * (s.values - smin) / (smax - smin + 1e-12)
        zero = -width * smin / (smax - smin + 1e-12)

        def css_bar(start, end, color):
            """
            Generate CSS code to draw a bar from start to end.
            """
            css = 'width: 10em; height: 80%;'
            if end > start:
                css += 'background: linear-gradient(90deg,'
                if start > 0:
                    css += ' transparent {s:.1f}%, {c} {s:.1f}%, '.format(
                        s=start, c=color
                    )
                css += '{c} {e:.1f}%, transparent {e:.1f}%)'.format(
                    e=min(end, width), c=color,
                )
            return css

        def css(x):
            if pd.isna(x):
                return ''

            # avoid deprecated indexing `colors[x > zero]`
            color = colors[1] if x > zero else colors[0]

            if align == 'left':
                return css_bar(0, x, color)
            else:
                return css_bar(min(x, zero), max(x, zero), color)

        if s.ndim == 1:
            return [css(x) for x in normed]
        else:
            return pd.DataFrame(
                [[css(x) for x in row] for row in normed],
                index=s.index, columns=s.columns
            )
896324
function buildGradient() {
            if (!chartGradientEl && chartGradientColors) {
                chartGradientEl = svg.select('.metadata-group')
                  .append('linearGradient')
                    .attr('id', chartGradientId)
                    .attr('x1', '0%')
                    .attr('y1', '0%')
                    .attr('x2', '100%')
                    .attr('y2', '100%')
                    .attr('gradientUnits', 'userSpaceOnUse')
                    .selectAll('stop')
                     .data([
                        {offset:'0%', color: chartGradientColors[0]},
                        {offset:'50%', color: chartGradientColors[1]}
                    ])
                    .enter()
                      .append('stop')
                        .attr('offset', ({offset}) => offset)
                        .attr('stop-color', ({color}) => color)
            }
        }
646761
def gen_colors(img):
    """"""
    # pylint: disable=not-callable
    raw_colors = colorz.colorz(img, n=6, bold_add=0)
    return [util.rgb_to_hex([*color[0]]) for color in raw_colors]
1332751
function (data, colorFunc, state) {
        var gradientPixels = this._gradientPixels;
        var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
        var color = [0, 0, 0, 0];
        var off = 0;
        for (var i = 0; i < 256; i++) {
            colorFunc[state](i / 255, true, color);
            pixelsSingleState[off++] = color[0];
            pixelsSingleState[off++] = color[1];
            pixelsSingleState[off++] = color[2];
            pixelsSingleState[off++] = color[3];
        }
        return pixelsSingleState;
    }
754496
function Gradient(size, start) {
  this.size = size;
  this.canvas = new Canvas(1, 1);
  this.setStartPosition(start);
  this.ctx = this.canvas.getContext('2d');
  this.grad = this.ctx.createLinearGradient(
      this.from[0], this.from[1],
      this.to[0], this.to[1]);
}
1088830
function( rgb ){
      var ret;
      var number = $$.util.regex.number;

      var m = new RegExp("^" + $$.util.regex.rgba + "$").exec(rgb);
      if( m ){
        ret = [];

        var isPct = [];
        for( var i = 1; i <= 3; i++ ){
          var channel = m[i];

          if( channel[ channel.length - 1 ] === "%" ){
            isPct[i] = true;
          }
          channel = parseFloat( channel );

          if( isPct[i] ){
            channel = channel/100 * 255; // normalise to [0, 255]
          }

          if( channel < 0 || channel > 255 ){ return; } // invalid channel value

          ret.push( Math.floor(channel) );
        }

        var atLeastOneIsPct = isPct[1] || isPct[2] || isPct[3];
        var allArePct = isPct[1] && isPct[2] && isPct[3];
        if( atLeastOneIsPct && !allArePct ){ return; } // must all be percent values if one is

        var alpha = m[4];
        if( alpha !== undefined ){
          alpha = parseFloat( alpha );

          if( alpha < 0 || alpha > 1 ){ return; } // invalid alpha value

          ret.push( alpha );
        }
      }

      return ret;
    }
1011900
function colorgrad() {
    var args = Array.prototype.slice.call(arguments)
      , arraymath = require('./arraymath')
      , spec
      , cstep
      , c1 = args[0]
      , c2 = null
      , rgb1
      , rgb2
      , outType = isArray(c1) ? 'rgb': 'hex'
      , add = arraymath("+")
      , sub = arraymath("-")
      , div = arraymath("/")
      , mul = arraymath("*")

    /*
     *
     * Unpack specification object
     *
     */
    if(isObj(args[1])) {
      spec = args[1]
    }
    else if (isObj(args[2])) {
      spec = args[2]
      c2 = args[1]
    }
    else
      spec = {}
    /*
     * Or with defaults
     */
    var lum = spec.lum || 1
      , n = spec.nshades || 100
      , type = spec.type || "linear"

    /*
     *
     * Design the color step array which will be
     * a length 3 vector.
     *
     */
    rgb1 = isArray(c1) ? c1 : hex2rgb(c1)
    if(c2) // If two hexcolors supplied
      rgb2 = isArray(c2) ? c2 : hex2rgb(c2)
    else // 2nd color is lum% incr/decr of color1
      rgb2 = add( mul(rgb1,[lum]), rgb1)

    // Create step size to step through color gradient
    cstep = div( sub(rgb2, rgb1), [n-1])

    var i
      , nc = []
    nc[0] = rgb1
    for (i = 1; i < n; ++i) {
      nc[i] = add(nc[i-1], cstep)
    }

    function clims(c) {
      if(c > 255)
        return 255
      else if(c < 0)
        return 0
      else return c
    }

    var result = []
    nc.forEach(function (ar) {
      ar = ar.map(Math.round).map(clims)
      if(outType === 'hex')
        ar = rgb2hex(ar)
      result.push( ar )
    })
    return result
  }
954687
function normalize(property, value, prefix){
  var result = value.toString(),
      args;

  /* Fixing the gradients */
  if (~result.indexOf('gradient(')) {

    /* Normalize color stops */
    result = result.replace(RE_GRADIENT_STOPS,'$1$4$3$2');

    /* Normalize legacy gradients */
    result = result.replace(RE_GRADIENT_VAL, function(){
        args = [].slice.call(arguments, 1);
        return normalizeGradient(args, prefix);
    });

    /* Adding prefixes to the legacy gradients */
    if (prefix) result = result.replace(RE_GRADIENT_TYPE, '-' + prefix + '-$1');
  }

  /* Adding prefixes to the `transform` values of legacy `transition` property */
  if (prefix && (property == "'transition'" || property == "'transition-property'")) {
    result = result.replace(RE_TRANSFORM, '-' + prefix + '-$1');
  }

  /* Removing `fill` keyword from the legacy `border-image` property */
  if (prefix && (property == "'border-image'" || property == "'border-image-slice'")) {
    result = result.replace(RE_FILL_KEYWORD, ' ');
  }

  return result;
}
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( "\')" );
    }