import Canvas from 'canvas';
547309
function imageToImageData ( image ) {
	if ( image instanceof HTMLImageElement ) {
		// http://stackoverflow.com/a/3016076/229189
		if ( ! image.naturalWidth || ! image.naturalHeight || image.complete === false ) {
			throw new Error( "This this image hasn't finished loading: " + image.src );
		}

		const canvas = new Canvas( image.naturalWidth, image.naturalHeight );
		const ctx = canvas.getContext( '2d' );
		
		ctx.drawImage( image, 0, 0, canvas.width, canvas.height );

		const imageData = ctx.getImageData( 0, 0, canvas.width, canvas.height );

		if ( imageData.data && imageData.data.length ) {
			if ( typeof imageData.width === 'undefined' ) {
				imageData.width = image.naturalWidth;
			}

			if ( typeof imageData.height === 'undefined' ) {
				imageData.height = image.naturalHeight;
			}
		}
		
		return imageData;
	} else {
		throw new Error( 'This object does not seem to be an image.' );
		return;
	}
}
782643
def _repaint(self, drawing_context: DrawingContext.DrawingContext):
        """"""

        # canvas size
        canvas_width = self.canvas_size.width
        canvas_height = self.canvas_size.height

        with drawing_context.saver():
            if self.__color_map_data is not None:
                rgba_image = numpy.empty((4,) + self.__color_map_data.shape[:-1], dtype=numpy.uint32)
                Image.get_rgb_view(rgba_image)[:] = self.__color_map_data[numpy.newaxis, :, :]  # scalar data assigned to each component of rgb view
                Image.get_alpha_view(rgba_image)[:] = 255
                drawing_context.draw_image(rgba_image, 0, 0, canvas_width, canvas_height)
689129
def load_image(self, imagepath, width=None, height=None):
        """"""

        if width:
            self.width = width
            self.canvas["width"] = width
        if height:
            self.height = height
            self.canvas["height"] = height

        self.image = imagepath
        size = (self.width, self.height)
        load_image(self.canvas, self.image, bounds=size)
        self.canvas.update_idletasks()
683432
def visit_importfrom(self, node):
        """"""
        return "from %s import %s" % (
            "." * (node.level or 0) + node.modname,
            _import_string(node.names),
        )
969818
function findCanvas(canvasId) {	
	for (var i = 0; i < canvases.length; i++)
		if(canvases[i].id == canvasId)
			return canvases[i];
	return null;
}
1096896
function convertToImage (canvasId, x, y, width, height, type, done = () => {}) {
  if (type === undefined) { type = 'png' }
  type = fixType(type)
  if (/bmp/.test(type)) {
    getImageData(canvasId, x, y, width, height, (data, err) => {
      const strData = genBitmapImage(data)
      isFunc(done) && done(makeURI(strData, 'image/' + type), err)
    })
  } else {
    console.error('暂不支持生成\'' + type + '\'类型的base64图片')
  }
}
88230
function Canvas(width, height, gmsmith) {
  // Ignore width/height
  // DEV: Our canvas dimensions are dynamically defined by x/y of each image
  var canvas = gmsmith.gm(1, 1, 'transparent');

  // Override the -size options (won't work otherwise)
  canvas._in = ['-background', 'transparent'];

  // Save the canvas
  this.canvas = canvas;
}
953991
function(cb){
      this.toCanvas(function(canvas){
        var canvasData = canvas.toDataURL("image/png");
        var img = document.createElement('img');

        img.onload = function(){
          cb(img);
        };

        // Make pngImg's source the canvas data.
        img.setAttribute('src', canvasData);
      });
    }
110581
def _repaint(self, drawing_context):
        """"""

        # canvas size
        canvas_width = self.canvas_size[1]
        canvas_height = self.canvas_size[0]

        left = self.display_limits[0]
        right = self.display_limits[1]

        # draw left display limit
        if left > 0.0:
            with drawing_context.saver():
                drawing_context.begin_path()
                drawing_context.move_to(left * canvas_width, 1)
                drawing_context.line_to(left * canvas_width, canvas_height-1)
                drawing_context.line_width = 2
                drawing_context.stroke_style = "#000"
                drawing_context.stroke()

        # draw right display limit
        if right < 1.0:
            with drawing_context.saver():
                drawing_context.begin_path()
                drawing_context.move_to(right * canvas_width, 1)
                drawing_context.line_to(right * canvas_width, canvas_height-1)
                drawing_context.line_width = 2
                drawing_context.stroke_style = "#FFF"
                drawing_context.stroke()

        # draw border
        with drawing_context.saver():
            drawing_context.begin_path()
            drawing_context.move_to(0,canvas_height)
            drawing_context.line_to(canvas_width,canvas_height)
            drawing_context.line_width = 1
            drawing_context.stroke_style = "#444"
            drawing_context.stroke()
50091
function importAll(context) {
  const storyStore = window.__STORYBOOK_CLIENT_API__._storyStore; // eslint-disable-line no-undef, no-underscore-dangle

  context.keys().forEach(filename => {
    const fileExports = context(filename);

    // A old-style story file
    if (!fileExports.default) {
      return;
    }

    const { default: component, ...examples } = fileExports;
    let componentOptions = component;
    if (component.prototype && component.prototype.isReactComponent) {
      componentOptions = { component };
    }
    const kindName = componentOptions.title || componentOptions.component.displayName;

    if (previousExports[filename]) {
      if (previousExports[filename] === fileExports) {
        return;
      }

      // Otherwise clear this kind
      storyStore.removeStoryKind(kindName);
      storyStore.incrementRevision();
    }

    // We pass true here to avoid the warning about HMR. It's cool clientApi, we got this
    const kind = storiesOf(kindName, true);

    (componentOptions.decorators || []).forEach(decorator => {
      kind.addDecorator(decorator);
    });
    if (componentOptions.parameters) {
      kind.addParameters(componentOptions.parameters);
    }

    Object.keys(examples).forEach(key => {
      const example = examples[key];
      const { title = key, parameters } = example;
      kind.add(title, example, parameters);
    });

    previousExports[filename] = fileExports;
  });
}
1099708
def image_import(infile, force):
    """"""
    ecode = 0
    
    try:
        with open(infile, 'r') as FH:
            savelist = json.loads(FH.read())
    except Exception as err:
        anchore_print_err("could not load input file: " + str(err))
        ecode = 1

    if ecode == 0:
        for record in savelist:
            try:
                imageId = record['image']['imageId']
                if contexts['anchore_db'].is_image_present(imageId) and not force:
                    anchore_print("image ("+str(imageId)+") already exists in DB, skipping import.")
                else:
                    imagedata = record['image']['imagedata']
                    try:
                        rc = contexts['anchore_db'].save_image_new(imageId, report=imagedata)
                        if not rc:
                            contexts['anchore_db'].delete_image(imageId)
                            raise Exception("save to anchore DB failed")
                    except Exception as err:
                        contexts['anchore_db'].delete_image(imageId)
                        raise err
            except Exception as err:
                anchore_print_err("could not store image ("+str(imageId)+") from import file: "+ str(err))
                ecode = 1

    sys.exit(ecode)
828705
def clear_canvas(self):
        """"""
        self.fig = None
        self.fmt = None
        self._qpix_buffer = []
        self.repaint()
176721
def load(self, f):
        """"""
        SUPPORTED_COLOR_TYPES = (COLOR_TYPE_TRUECOLOR, COLOR_TYPE_TRUECOLOR_WITH_ALPHA)
        SAMPLES_PER_PIXEL = { COLOR_TYPE_TRUECOLOR: 3,
                              COLOR_TYPE_TRUECOLOR_WITH_ALPHA: 4 }

        assert f.read(8) == SIGNATURE

        chunks = iter(self.chunks(f))
        header = next(chunks)
        assert header[0] == b'IHDR'

        (width, height, bit_depth, color_type, compression,
         filter_type, interlace) = struct.unpack(b"!2I5B", header[1])

        if bit_depth != 8:
            raise ValueError('Unsupported PNG format (bit depth={}; must be 8)'.format(bit_depth))
        if compression != 0:
            raise ValueError('Unsupported PNG format (compression={}; must be 0)'.format(compression))
        if filter_type != 0:
            raise ValueError('Unsupported PNG format (filter_type={}; must be 0)'.format(filter_type))
        if interlace != 0:
            raise ValueError('Unsupported PNG format (interlace={}; must be 0)'.format(interlace))
        if color_type not in SUPPORTED_COLOR_TYPES:
            raise ValueError('Unsupported PNG format (color_type={}; must one of {})'.format(SUPPORTED_COLOR_TYPES))

        self.width = width
        self.height = height
        self.canvas = bytearray(self.bgcolor * width * height)
        bytes_per_pixel = SAMPLES_PER_PIXEL[color_type]
        bytes_per_row = bytes_per_pixel * width
        bytes_per_rgba_row = SAMPLES_PER_PIXEL[COLOR_TYPE_TRUECOLOR_WITH_ALPHA] * width
        bytes_per_scanline = bytes_per_row + 1

        # Python 2 requires the encode for struct.unpack
        scanline_fmt = ('!%dB' % bytes_per_scanline).encode('ascii')

        reader = ByteReader(chunks)

        old_row = None
        cursor = 0
        for row in range(height):
            scanline = reader.read(bytes_per_scanline)
            unpacked = list(struct.unpack(scanline_fmt, scanline))
            old_row = self.defilter(unpacked[1:], old_row, unpacked[0], bpp=bytes_per_pixel)
            rgba_row = old_row if color_type == COLOR_TYPE_TRUECOLOR_WITH_ALPHA else rgb2rgba(old_row)
            self.canvas[cursor:cursor + bytes_per_rgba_row] = rgba_row
            cursor += bytes_per_rgba_row
480577
function addRectHandle($canvas, parent, px, py) {
	var handle, cursor;

	// Determine cursor to use depending on handle's placement
	if ((px === -1 && py === -1) || (px === 1 && py === 1)) {
		cursor = 'nwse-resize';
	} else if (px === 0 && (py === -1 || py === 1)) {
		cursor = 'ns-resize';
	} else if ((px === -1 || px === 1) && py === 0) {
		cursor = 'ew-resize';
	} else if ((px === 1 && py === -1) || (px === -1 && py === 1)) {
		cursor = 'nesw-resize';
	}

	handle = $.extend({
		// Set cursors for handle
		cursors: {
			mouseover: cursor
		}
	}, parent.handle, {
		// Define constant properties for handle
		layer: true,
		draggable: true,
		x: parent.x + ((px * parent.width / 2) + ((parent.fromCenter) ? 0 : parent.width / 2)),
		y: parent.y + ((py * parent.height / 2) + ((parent.fromCenter) ? 0 : parent.height / 2)),
		_parent: parent,
		_px: px,
		_py: py,
		fromCenter: true,
		dragstart: function (layer) {
			$(this).triggerLayerEvent(layer._parent, 'handlestart');
		},
		// Resize rectangle when dragging a handle
		drag: function (layer) {
			var parent = layer._parent;

			if (parent.width + (layer.dx * layer._px) < parent.minWidth) {
				parent.width = parent.minWidth;
				layer.dx = 0;
			}
			if (parent.height + (layer.dy * layer._py) < parent.minHeight) {
				parent.height = parent.minHeight;
				layer.dy = 0;
			}

			if (!parent.resizeFromCenter) {
				// Optionally constrain proportions
				if (parent.constrainProportions) {
					if (layer._py === 0) {
						// Manage handles whose y is at layer's center
						parent.height = parent.width / parent.aspectRatio;
					} else {
						// Manage every other handle
						parent.width = parent.height * parent.aspectRatio;
						layer.dx = layer.dy * parent.aspectRatio * layer._py * layer._px;
					}
				}
				// Optionally resize rectangle from corner
				if (parent.fromCenter) {
					parent.width += layer.dx * layer._px;
					parent.height += layer.dy * layer._py;
				} else {
					// This is simplified version based on math. Also you can write this using an if statement for each handle
					parent.width += layer.dx * layer._px;
					if (layer._px !== 0) {
						parent.x += layer.dx * ((1 - layer._px) && (1 - layer._px) / Math.abs((1 - layer._px)));
					}
					parent.height += layer.dy * layer._py;
					if (layer._py !== 0) {
						parent.y += layer.dy * ((1 - layer._py) && (1 - layer._py) / Math.abs((1 - layer._py)));
					}
				}
				// Ensure diagonal handle does not move
				if (parent.fromCenter) {
					if (layer._px !== 0) {
						parent.x += layer.dx / 2;
					}
					if (layer._py !== 0) {
						parent.y += layer.dy / 2;
					}
				}
			} else {
				// Otherwise, resize rectangle from center
				parent.width += layer.dx * layer._px * 2;
				parent.height += layer.dy * layer._py * 2;
				// Optionally constrain proportions
				if (parent.constrainProportions) {
					if (layer._py === 0) {
						// Manage handles whose y is at layer's center
						parent.height = parent.width / parent.aspectRatio;
					} else {
						// Manage every other handle
						parent.width = parent.height * parent.aspectRatio;
					}
				}
			}
			updateRectHandles(parent);
			$(this).triggerLayerEvent(parent, 'handlemove');
		},
		dragstop: function (layer) {
			var parent = layer._parent;
			$(this).triggerLayerEvent(parent, 'handlestop');
		},
		dragcancel: function (layer) {
			var parent = layer._parent;
			$(this).triggerLayerEvent(parent, 'handlecancel');
		}
	});
	$canvas.draw(handle);
	// Add handle to parent layer's list of handles
	parent._handles.push($canvas.getLayer(-1));
}
979941
function () {
                var el = document.createElement( 'canvas' ),
                    _canvas = !!( el.getContext && el.getContext( '2d' ) );
    
                this.supportCanvas = function () { return _canvas; };
                return this.supportCanvas();
            }
578844
function importScript(src) {
  // Scan all search paths in order, trying to find the file.
  //var relPath = path.join(path.dirname(process.argv[1]) + '/', src);
  var filePath = src;//path.relative(process.cwd(), relPath);
  for (var n = 0; n < SEARCH_PATHS.length; n++) {
    var searchPath = path.join(process.cwd(), SEARCH_PATHS[n]);
    var searchFilePath = path.join(searchPath, filePath);
    if (fileExistsSync(searchFilePath)) {
      var sourceCode = fs.readFileSync(searchFilePath, 'utf8');
      try {
        vm.runInThisContext(sourceCode, searchFilePath);
      } catch (e) {
        console.log('Error running script ' + src);
        throw e;
      }
      return true;
    }
  }

  // File not found.
  console.log('ERROR: could not find ' + src);
  return false;
}
956930
function acquireContext(item, config) {
		if (typeof item === 'string') {
			item = document.getElementById(item);
		} else if (item.length) {
			// Support for array based queries (such as jQuery)
			item = item[0];
		}

		if (item && item.canvas) {
			// Support for any object associated to a canvas (including a context2d)
			item = item.canvas;
		}

		if (item instanceof HTMLCanvasElement) {
			// To prevent canvas fingerprinting, some add-ons undefine the getContext
			// method, for example: https://github.com/kkapsner/CanvasBlocker
			// https://github.com/chartjs/Chart.js/issues/2807
			var context = item.getContext && item.getContext('2d');
			if (context instanceof CanvasRenderingContext2D) {
				initCanvas(item, config);
				return context;
			}
		}

		return null;
	}