Allows the user to edit the imagefindpars configObj in a TEAL GUI
346320
def edit_imagefindpars():
    
    teal.teal(imagefindpars.__taskname__, returnAs=None,
              autoClose=True, loadOnly=False, canExecute=False)
1158724
def cli(yaml_paths, pptx_template_path, font_size, master_slide_idx, slide_layout_idx, dst_dir, font_name,
        slide_txt_alignment, validate):
    

    dst_dir = Path(dst_dir)

    pptx_template_path = Path(pptx_template_path)
    pptx_template = pick_master_slide(pptx_template_path)

    yamlfiles = []
    for yaml_path in yaml_paths:
        yaml_path = Path(yaml_path)
        if yaml_path.is_dir():
            yamlfiles.extend([yml for yml in yaml_path.iterdir()])
        else:
            yamlfiles.append(yaml_path)

    if validate:
        exit_fail = False
        for yamlfile in yamlfiles:
            try:
                validate_yaml_file(SCHEMA_FOR_YAML, Path(yamlfile))
                msg = f"VALIDATE: Validation of {yamlfile} passed"
                click.echo(click.style(msg, fg="blue"))
            except jsonschema.exceptions.ValidationError as err:
                msg = f"ERR: {yamlfile} {str(err.message)} {err.path}"
                click.echo(click.style(msg, fg="red"), nl=True)
                exit_fail = True
            except Exception:
                raise
        if exit_fail:
            sys.exit(1)

    for yamlfile in yamlfiles:
        try:
            r = build_slide(
                    Path(yamlfile),
                    pptx_template,
                    master_slide_idx,
                    slide_layout_idx,
                    font_size,
                    dst_dir,
                    font_name,
                    slide_txt_alignment
                )
            msg = f"PPTX: {r}"
            click.echo(click.style(msg, fg="green"))
        except Exception:
            raise
1354385
def editColormap(self):
        """"""
        self.editor = pg.ImageView()
        # remove the ROI and Norm buttons
        self.editor.ui.roiBtn.setVisible(False)
        self.editor.ui.menuBtn.setVisible(False)
        self.editor.setImage(self.imageArray)
        if self.imgArgs['state'] is not None:
            self.editor.getHistogramWidget().item.gradient.restoreState(self.imgArgs['state'])
            self.editor.getHistogramWidget().item.setLevels(*self.imgArgs['levels'])
        
        self.editor.closeEvent = self._editor_close
        self.editor.setWindowModality(QtCore.Qt.ApplicationModal)
        self.editor.show()
11511
function normalizeOpts(obj, basedir, pkg) {
    obj = obj || {};

    u.each(OPTSKEYS, function(key) {
      obj[key] = normalizeOptsKey(obj[key], basedir, pkg);
    });

    normalizeFqImages(obj);

    return obj;
  }
986429
def run(configObj=None, input_dict={}, loadOnly=False):
    
    # If called from interactive user-interface, configObj will not be
    # defined yet, so get defaults using EPAR/TEAL.
    #
    # Also insure that the input_dict (user-specified values) are folded in
    # with a fully populated configObj instance.
    configObj = util.getDefaultConfigObj(__taskname__,configObj,input_dict,loadOnly=loadOnly)
    if configObj is None:
        return
    # Define list of imageObject instances and output WCSObject instance
    # based on input paramters
    imgObjList,outwcs = processInput.setCommonInput(configObj)

    # Build DQ masks for all input images.
    buildMask(imgObjList,configObj)
917754
def hl_canvas2table(self, canvas, button, data_x, data_y):
        """"""
        self.treeview.clear_selection()

        # Remove existing highlight
        if self.markhltag:
            try:
                canvas.delete_object_by_tag(self.markhltag, redraw=True)
            except Exception:
                pass

        # Nothing to do if no markings are displayed
        try:
            obj = canvas.get_object_by_tag(self.marktag)
        except Exception:
            return

        if obj.kind != 'compound':
            return

        # Nothing to do if table has no data
        if (len(self._xarr) == 0 or len(self._yarr) == 0 or
                len(self._treepaths) == 0):
            return

        sr = 10  # self.settings.get('searchradius', 10)
        dx = data_x - self._xarr
        dy = data_y - self._yarr
        dr = np.sqrt(dx * dx + dy * dy)
        mask = dr <= sr

        for hlpath in self._treepaths[mask]:
            self._highlight_path(hlpath)
1150832
def run(configobj=None,editpars=False):
    

    if configobj is None:
        configobj =teal.teal(__taskname__,loadOnly=(not editpars))

    update(configobj['input'],configobj['refdir'],
        local=configobj['local'],interactive=configobj['interactive'],
        wcsupdate=configobj['wcsupdate'])
458309
function Editor(container_id, options) {
    options = options || {};

    //fill container
    var html =
        "<div class='header'><div class='tools tools-left'></div><div class='tools tools-right'></div></div>";
    html +=
        "<div class='content'><div class='editor-area'><canvas class='graphcanvas' width='1000' height='500' tabindex=10></canvas></div></div>";
    html +=
        "<div class='footer'><div class='tools tools-left'></div><div class='tools tools-right'></div></div>";

    var root = document.createElement("div");
    this.root = root;
    root.className = "litegraph-editor";
    root.innerHTML = html;

    this.tools = root.querySelector(".tools");
    this.footer = root.querySelector(".footer");

    var canvas = root.querySelector(".graphcanvas");

    //create graph
    var graph = (this.graph = new LGraph());
    var graphcanvas = (this.graphcanvas = new LGraphCanvas(canvas, graph));
    graphcanvas.background_image = "imgs/grid.png";
    graph.onAfterExecute = function() {
        graphcanvas.draw(true);
    };

    //add stuff
    //this.addToolsButton("loadsession_button","Load","imgs/icon-load.png", this.onLoadButton.bind(this), ".tools-left" );
    //this.addToolsButton("savesession_button","Save","imgs/icon-save.png", this.onSaveButton.bind(this), ".tools-left" );
    this.addLoadCounter();
    this.addToolsButton(
        "playnode_button",
        "Play",
        "imgs/icon-play.png",
        this.onPlayButton.bind(this),
        ".tools-right"
    );
    this.addToolsButton(
        "playstepnode_button",
        "Step",
        "imgs/icon-playstep.png",
        this.onPlayStepButton.bind(this),
        ".tools-right"
    );

    if (!options.skip_livemode) {
        this.addToolsButton(
            "livemode_button",
            "Live",
            "imgs/icon-record.png",
            this.onLiveButton.bind(this),
            ".tools-right"
        );
    }
    if (!options.skip_maximize) {
        this.addToolsButton(
            "maximize_button",
            "",
            "imgs/icon-maximize.png",
            this.onFullscreenButton.bind(this),
            ".tools-right"
        );
    }
    if (options.miniwindow) {
        this.addMiniWindow(300, 200);
    }

    //append to DOM
    var parent = document.getElementById(container_id);
    if (parent) {
        parent.appendChild(root);
    }

    graphcanvas.resize();
    //graphcanvas.draw(true,true);
}
1033341
function Images(el, options) {
        this.el = el;
        this.$el = $(el);
        this.$currentImage = null;
        this.templates = window.MediumInsert.Templates;
        this.core = this.$el.data('plugin_' + pluginName);

        this.options = $.extend(true, {}, defaults, options);

        this._defaults = defaults;
        this._name = pluginName;

        // Allow image preview only in browsers, that support's that
        if (this.options.preview && !window.FileReader) {
            this.options.preview = false;
        }

        // Extend editor's functions
        if (this.core.getEditor()) {
            this.core.getEditor()._serializePreImages = this.core.getEditor().serialize;
            this.core.getEditor().serialize = this.editorSerialize;
        }

        this.init();
    }
635727
function getVariablesFromFile(file, data) {
    const regex = /(\$[\w-]*)\s*:\s*(.*);/g;
    let match = regex.exec(data);

    while (match) {

        /* check if variable is an background icon, if so replace it directly by the SVG */
        if (match[0].indexOf('../../images/backgrounds') >= 0) {

            const iconregex = /(\$[\w-]+)\s*:\s*"\.\.\/\.\.\/images\/backgrounds\/([\w./-]+)" !default;/g;
            const iconmatch = iconregex.exec(match[0]);
            let svg = fs.readFileSync(`src/images/backgrounds/${iconmatch[2]}`).toString();
            svg = `"${svg.replace(/\r?\n|\r/g, '%0A')
                .replace(/"/g, '\'')
                .replace(/\s/g, '%20')
                .replace(/</g, '%3C')
                .replace(/=/g, '%3D')
                .replace(/'/g, '%22')
                .replace(/:/g, '%3A')
                .replace(/\//g, '%2F')
                .replace(/>/g, '%3E')
                .replace(/%3Csvg/, 'data:image/svg+xml;charset=UTF-8,%3Csvg')}"`;

            /* add SVG to the coreVar and themeVar only if it is a theme file and make it optional */
            if (file.indexOf('theme/') < 0) {
                coreVar[iconmatch[1]] = {value: `${svg} !default;`, dependencies: []};
            }

            themeVar[iconmatch[1]] = {value: `${svg} !default;`, dependencies: []};

            /* add SVG to the variable within the file itself as well */
            const inlineSVG = `${iconmatch[1]}: ${svg} !default;`;
            data = data.replace(match[0], inlineSVG);

            /* when it is not an SVG add the variable and search for its dependencies */
        } else {

            const variablesRegex = /(\$[\w-]+)/g;
            let variablesMatch = variablesRegex.exec(match[2]);
            const dependencies = [];

            while (variablesMatch) {
                dependencies.push(variablesMatch[1]);
                variablesMatch = variablesRegex.exec(match[2]);
            }

            /* add variables only to the core Variables if it is not a theme file */
            if (file.indexOf('theme/') < 0) {
                coreVar[match[1]] = {value: `${match[2]};`, dependencies: Array.from(dependencies)};
            }

            themeVar[match[1]] = {value: `${match[2]};`, dependencies: Array.from(dependencies)};
        }

        match = regex.exec(data);
    }

    return data;
}
219667
def edit(id: int, parent: int, alloc: Decimal):
    
    saved = False

    # load
    app = AppAggregate()
    item = app.get(id)
    if not item:
        raise KeyError("Asset Class with id %s not found.", id)

    if parent:
        assert parent != id, "Parent can not be set to self."

        # TODO check if parent exists?

        item.parentid = parent
        saved = True
        # click.echo(f"parent set to {parent}")

    if alloc:
        assert alloc != Decimal(0)

        item.allocation = alloc
        saved = True

    app.save()
    if saved:
        click.echo("Data saved.")
    else:
        click.echo("No data modified. Use --help to see possible parameters.")
743632
function findImages(templateName, source, deps, options) {
  var imgReg = /(<img\s.*?src\s?=\s?['"])([^'"]+)(['"][^/>]*\/?>)/g,
    referenceReg = /[{}]/,
    result = null;

  // search source & add a dependency for each match
  while ((result = imgReg.exec(source)) !== null) {
    const src = result[2];
    const imageTemplateName = `${templateName}dep${deps.length}`;

    // skip this image if a) it has a dustJS reference in it or b) an optional excludeImageRegex matches
    if (referenceReg.test(src)) {
      log(options, `skipping image ${src} (src includes a DustJS reference)`);
      continue
    }
    if (options.excludeImageRegex && options.excludeImageRegex.test(src)) {
      log(options, `skipping image ${src} (src matches excludeImageRegex)`);
      continue;
    }

    log(options, `requiring image ${src}`);

    // do our own custom registration of a template-like function that will use require to get the actual path
    const srcTemplate = `(function() {
      var path = require('${src}');
      dust.register('${imageTemplateName}', body_0);

      function body_0(chk, ctx) {
          return chk.write(path);
      }
      return body_0;
    })();`
    deps.push(srcTemplate);

    // replace the original image path with a partial template call to our method that will return the path.
    const replace = `${result[1]}{>"${imageTemplateName}"/}${result[3]}`
    source = source.replace(result[0], replace);

    // update regex index
    imgReg.lastIndex += (replace.length - result[0].length);
  }

  return source;
}
1280725
function(options){
	
	/**
	 *	@var
	 *	@desc Default sharper configuration options  
	**/
	var defaultOptions = {
		
		/**
		 *	@member {string}
		 *	@desc name of the image file field in multipart for data
		**/
		field : 'file',
		
		/**
		 *	@member {string}
		 *	@desc location of file upload
		**/
		location : '/var/www/uploads/',
		
		/**
		 *	@member {string}
		 *	@desc date-format to create upload directory
		**/
		dirFormat : 'yyyy/mmm/d',

		/**
		 *	@member {Number}
		 *	@desc length of the filename to be created
		**/
		fileNameLen : 50,

		/**
		 *	@member {string}
		 *	@desc maximum size of the file to be uploaded
		**/
		maxFileSize : '10mb',

		/**
		 *	@member {Array}
		 *	@desc type of files to be accepted (file extensions)
		**/
		accept : ['png','jpeg','jpg'],

		/**
		 *	@member {string}
		 *	@desc output extension of the image file
		**/
		output : 'jpg',

		/**
		 *	@member {Array}
		 *	@desc output images sizes and name suffix
		**/
		sizes : [
		    {suffix : 'lg', width : 500, height:500},
		],

		/*
		 *	sharp-libvips options
		 *	to process an image
		**/
		resize : true,
		crop : false,
		background : {r:200, g:200, b:200, a:1},
		embed : false,
		max : false,
		min : false,
		withoutEnlargement : false,
		ignoreAspectRatio : false,
		extract : false,
		trim : false,
		flatten : false,
		extend : false,
		negate : false,
		rotate : false,
		flip : false,
		flop : false,
		blur : false,
		sharpen : false,
		gamma : false,
		grayscale : false,
		greyscale : false,
		normalize : false,
		normalise : false,
		progressive : false,
		quality : false,
	};


	/**
	 *	@var
	 *	@desc Transformed options to be applied to sharper  
	**/
	var options = _.assign(defaultOptions, options);


	/********************************************************************/


	/**
	 *	@function middleware
	 *	@desc Express middleware function to be returned by sharper
	**/
	return function(req, res, next){
		
		/**
		 *	@name waterfall
		 *	@desc using async waterfall function,
		 *	run multiple tasks in series
		**/
		async.waterfall(
			[
				/**
				 *	@function masterUpload
				 *	@desc Upload master image file using multer
				 *	@param {Function} callback async callback function
				**/
				function(callback){
					// Create config variables
					var dir = dateformat(new Date(), options.dirFormat);
					var destination = options.location + dir;
					var filename = randomstring.generate(
						options.fileNameLen
					);

					// Create master upload function
					var masterUploader = multer({
						storage : multer.diskStorage({
							destination: destination,
							filename: function(req, file, cb){
								cb(null, filename);
							}
						}),
						limits : {
							// this will return error object
							fileSize : bytes(options.maxFileSize),
							files : 1
						},
						fileFilter : function(req, file, cb){
							var fileExt = mime.extension(file.mimetype);
							if(!_.includes(options.accept, fileExt)){
								cb(new sError('file not acceptable', 'FILE_TYPE_UNSUPPORTED', fileExt));
							}
							else{
								cb(null, true);
							}
						}
					}).single(options.field);

					// Run master uploader
					masterUploader(req, res, function(err){
						if(err) return callback(err);
						
						callback(null, {
							dir : dir,
							destination : destination,
							filename : filename
						});
					});
				},


				/**
				 *	@function processImages
				 *	@desc Process all images in sharp
				 *	@param {Object} state upload state object received from
				 *	masterUpload callback function
				 *	@param {Function} callback async callback function
				**/
				function(state, callback){
					// Get instance of sharp with master image file
					var master = sharp(state.destination + '/' + state.filename);

					// Process images with sizes [in config options]
					async.each(
						options.sizes,
						function(size, _cb){
							// resize by default
							var $query = master.background(options.background);

							// check resize
							if(options.resize == true){
								$query = $query.resize(size.width, size.height);
							}

							// check crop (on valid crop option)
							if(options.crop != false && _.has(sharp.gravity, options.crop)){
								$query = $query.crop(sharp.gravity[options.crop]);
							}

							// check embed
							if(options.embed == true){
								$query = $query.embed();
							}

							// check max
							if(options.max == true){
								$query = $query.max();
							}

							// check min
							if(options.min == true){
								$query = $query.min();
							}

							// check withoutEnlargement
							if(options.withoutEnlargement == true){
								$query = $query.withoutEnlargement();
							}

							// check ignoreAspectRatio
							if(options.ignoreAspectRatio == true){
								$query = $query.ignoreAspectRatio();
							}

							// check extract
							if(options.extract != false){
								$query = $query.extract(options.extract);
							}

							// check trim
							if(options.trim != false){
								$query = $query.trim(_.toInteger(options.trim));
							}

							// check flatten
							if(options.flatten == true){
								$query = $query.flatten();
							}

							// check extend
							if(options.extend != false){
								$query = $query.extend(options.extend);
							}

							// check negate
							if(options.negate == true){
								$query = $query.negate();
							}

							// check rotate
							if(_.includes([0,90,180,270], options.rotate)){
								$query = $query.rotate(options.rotate);
							}

							// check flip
							if(options.flip == true){
								$query = $query.flip();
							}

							// check flop
							if(options.flop == true){
								$query = $query.flop();
							}

							// check blur
							if(options.blur != false){
								if(options.blur == true) $query = $query.blur();
								else $query = $query.blur(_.toNumber(options.blur));
							}

							// check sharpen
							if(options.sharpen == true){
								$query = $query.sharpen();
							}

							// check gamma
							if(options.gamma != false){
								if(options.gamma == true) $query = $query.gamma();
								else $query = $query.gamma(_.toNumber(options.gamma));
							}

							// check grayscale
							if(options.grayscale == true || options.greyscale == true){
								$query = $query.grayscale();
							}

							// check normalize
							if(options.normalize == true || options.normalise == true){
								$query = $query.normalize();
							}

							// check quality
							if(options.quality != false){
								$query = $query.quality(_.toInteger(options.quality));
							}

							// check progressive
							if(options.progressive == true){
								$query = $query.progressive();
							}


							// run query
							$query.toFile(
								state.destination + '/' + state.filename + '.' +
								size.suffix + '.' + options.output, 
								function(err){
									if(err) return _cb(err)
									_cb(null);
								}
							);
						},

						// each callback
						function(err){
							if(err) return callback(err);
							callback(null, state);
						}
					);
				},


				/**
				 *	@function deleteMaster
				 *	@desc Delete master image file from file system
				 *	@param {Object} state upload state object received from
				 *	masterUpload callback function
				 *	@param {Function} callback async callback function
				**/
				function(state, callback){
					// Unlock master image
					sharp.cache(false);
					
					// Unlink file
					fs.unlink(state.destination + '/' + state.filename, function(err){
						if(err)	return callback(err);
						callback(null, state);
					});
				}
			],


			/**
			 *	@function waterfallCallback
			 *	@desc callback function for async watefall
			 *	@param {Error} err Error received from waterfall functions
			 *	@param {Function} state upload state object received from
			 *	deleteMaster callback function
			**/
			function(err, state){
				// Call next error middleware
				if(err) return next(err);

				// Add state to express response object
				res.sharper = state;
				
				// Call next middleware
				next();
			}
		);
	}
}
79603
def AstroDrizzle(input=None, mdriztab=False, editpars=False, configobj=None,
                 wcsmap=None, **input_dict):
    
    # Support input of filenames from command-line without a parameter name
    # then copy this into input_dict for merging with TEAL ConfigObj
    # parameters.

    # Load any user-specified configobj
    if isinstance(configobj, (str, bytes)):
        if configobj == 'defaults':
            # load "TEAL"-defaults (from ~/.teal/):
            configobj = teal.load(__taskname__)
        else:
            if not os.path.exists(configobj):
                raise RuntimeError('Cannot find .cfg file: '+configobj)
            configobj = teal.load(configobj, strict=False)
    elif configobj is None:
        # load 'astrodrizzle' parameter defaults as described in the docs:
        configobj = teal.load(__taskname__, defaults=True)

    if input and not util.is_blank(input):
        input_dict['input'] = input
    elif configobj is None:
        raise TypeError("AstroDrizzle() needs either 'input' or "
                        "'configobj' arguments")

    if 'updatewcs' in input_dict: # user trying to explicitly turn on updatewcs
        configobj['updatewcs'] = input_dict['updatewcs']
        del input_dict['updatewcs']

    # If called from interactive user-interface, configObj will not be
    # defined yet, so get defaults using EPAR/TEAL.
    #
    # Also insure that the input_dict (user-specified values) are folded in
    # with a fully populated configObj instance.
    try:
        configObj = util.getDefaultConfigObj(__taskname__, configobj,
                                             input_dict,
                                             loadOnly=(not editpars))
        log.debug('')
        log.debug("INPUT_DICT:")
        util.print_cfg(input_dict, log.debug)
        log.debug('')
        # If user specifies optional parameter for final_wcs specification in input_dict,
        #    insure that the final_wcs step gets turned on
        util.applyUserPars_steps(configObj, input_dict, step='3a')
        util.applyUserPars_steps(configObj, input_dict, step='7a')

    except ValueError:
        print("Problem with input parameters. Quitting...", file=sys.stderr)
        return

    if not configObj:
        return

    configObj['mdriztab'] = mdriztab
    # If 'editpars' was set to True, util.getDefaultConfigObj() will have
    # already called 'run()'.
    if not editpars:
        run(configObj, wcsmap=wcsmap)
166136
private synchronized void changeImageView() {

		JComponent comp;
		if( control.selectedView < 3 ) {
			BufferedImage img;

			switch (control.selectedView) {
				case 0:
					img = disparityOut;
					break;

				case 1:
					img = colorLeft;
					break;

				case 2:
					img = colorRight;
					break;

				default:
					throw new RuntimeException("Unknown option");
			}

			gui.setImage(img);
			gui.setPreferredSize(new Dimension(origLeft.getWidth(), origLeft.getHeight()));
			comp = gui;
		} else {
			if( !computedCloud ) {
				computedCloud = true;
				DisparityToColorPointCloud d2c = new DisparityToColorPointCloud();

				double baseline = calib.getRightToLeft().getT().norm();
				d2c.configure(baseline, rectK,rectR, leftRectToPixel, control.minDisparity,control.maxDisparity);
				d2c.process(activeAlg.getDisparity(),colorLeft);

				CameraPinhole rectifiedPinhole = PerspectiveOps.matrixToPinhole(
						rectK,colorLeft.getWidth(),colorLeft.getHeight(),null);
				pcv.clearPoints();
				pcv.setCameraHFov(PerspectiveOps.computeHFov(rectifiedPinhole));
				pcv.setTranslationStep(5);
				pcv.addCloud(d2c.getCloud(),d2c.getCloudColor());
			}
			comp = pcv.getComponent();
			comp.requestFocusInWindow();
		}
		panel.remove(gui);
		panel.remove(pcv.getComponent());
		panel.add(comp,BorderLayout.CENTER);
		panel.validate();
		comp.repaint();
		processedImage = true;
	}
439198
def _add_embedding_config(file_path, data_dir, has_metadata=False, label_img_shape=None):
    """"""
    with open(os.path.join(file_path, 'projector_config.pbtxt'), 'a') as f:
        s = 'embeddings {\n'
        s += 'tensor_name: "{}"\n'.format(data_dir)
        s += 'tensor_path: "{}"\n'.format(os.path.join(data_dir, 'tensors.tsv'))
        if has_metadata:
            s += 'metadata_path: "{}"\n'.format(os.path.join(data_dir, 'metadata.tsv'))
        if label_img_shape is not None:
            if len(label_img_shape) != 4:
                logging.warning('expected 4D sprite image in the format NCHW, while received image'
                                ' ndim=%d, skipping saving sprite'
                                ' image info', len(label_img_shape))
            else:
                s += 'sprite {\n'
                s += 'image_path: "{}"\n'.format(os.path.join(data_dir, 'sprite.png'))
                s += 'single_image_dim: {}\n'.format(label_img_shape[3])
                s += 'single_image_dim: {}\n'.format(label_img_shape[2])
                s += '}\n'
        s += '}\n'
        f.write(s)
158202
def get(img, light=False):
    """"""
    cols = gen_colors(img)
    return adjust(cols, light)