Try to optimise a JPG file.

    The original will be saved at the same place with '.original' appended to its name.

    Once a .original exists the function will ignore this file unless force is True.
492566
def jpgMin(file, force=False):
    
    if not os.path.isfile(file+'.original') or force:
        data = _read(file, 'rb')
        _save(file+'.original', data, 'w+b')
        print 'Optmising JPG {} - {:.2f}kB'.format(file, len(data)/1024.0),
        url = 'http://jpgoptimiser.com/optimise'
        parts, headers = encode_multipart({}, {'input': {'filename': 'wherever.jpg', 'content': data}})
        req = urllib2.Request(url, data=parts, headers=headers)
        try:
            f = urllib2.urlopen(req)
            response = f.read()
            f.close()
            print ' - {:.2f} - {:.1f}%'.format(len(response)/1024.0, 100.0*len(response)/len(data))
            _save(file, response, 'w+b')
        except:
            print 'Oops!! Failed :('
            return 1
    else:
        print 'Ignoring file: {}'.format(file)
    return 0
703111
def save_image(self, file_obj):
        
        manager = pyglet.image.get_buffer_manager()
        colorbuffer = manager.get_color_buffer()

        # if passed a string save by name
        if hasattr(file_obj, 'write'):
            colorbuffer.save(file=file_obj)
        else:
            colorbuffer.save(filename=file_obj)
500356
def copy(self, src, chunk_size=None, progress_callback=None):
        
        fp = src.open(mode='rb')
        try:
            return self.save(
                fp, chunk_size=chunk_size, progress_callback=progress_callback)
        finally:
            fp.close()
1319305
function(file, opts) {
	if (util.isObject(file) || util.isArray(file)) {
		return file;
	}

	var options = util.extend({
		asText: false, // true, false, 'pretty'
		javascript: false, // true, false
		scope: '', // directory to look for initial file
		variables: {
			// contains a key->value object with variables to @extends
		}
	}, opts);

	file = util.template(file, options.variables);

	/*****************************************************************************
	*  Initialize
	*****************************************************************************/

	var file_path;

	// If the file path is absolute use it
	// If not then prepend the current scope of the previous file.
	if (path.resolve(file) === path.normalize(file)) {
		file_path = path.normalize(file);
	}
	else {
		file_path = path.normalize(
			options.scope ? options.scope + '/' + file : file
		);
	}
	var class_json = parseFile(file_path, options);

	// Stores JSON objects of files that have to be merged together:
	// ["a", "b"]
	var file_list = util.isArray(class_json[indicators.EXTENDS]) ?
		class_json[indicators.EXTENDS] :
		class_json[indicators.EXTENDS] != null ?
			[ class_json[indicators.EXTENDS] ] :
			[];

	// Delete @extends from base_json to avoid infinitive recursion
	delete class_json[indicators.EXTENDS];

	// Push class_json to the path list:
	file_list.push(class_json);
	/*****************************************************************************
	*  Merge file by file
	*****************************************************************************/

	// default config for each file required:
	// set asText = false so we get an object returned
	// set scope = file's directory so there can be relative references
	var json_config = util.defaults({
		asText: false,
		scope: path.dirname(file_path),

		// _as is a hack so that we know its we are calling the function recursive
		_as: ANTI_SANITIZER
	}, options);

	// super_json is our output, start by containing first file in array
	var super_json = fromFile(file_list.shift(), json_config);

	// TODO: Figure out when to sanitize super_json hopefully we don't have to
	//   santize all returns. I'm not sure about this, and I'm not sure if we
	//   can even sanitize super_json when we return it.
	//   Is super_json used by anyone recursively?

	while (file_list.length) {
		var json = fromFile(file_list.shift(), json_config);

		merge(super_json, json);
	}

	// If this file is called from the outside eg json_merger.from...
	//   File('file_which_doesnt_extends_another_file.json')
	//   we need to sanitize the file and remove all indicators
	if (options._as != ANTI_SANITIZER) {
		super_json = util.sanitizeValue(super_json);
	}

	/*****************************************************************************
	*  Return super_json
	*****************************************************************************/
	if (options.asText) {
		return stringify(super_json, options);
	}
	else {
		return super_json;
	}
}
991452
function (filename, fn) {

		fn = fn || function () {};

		this._image.pack().pipe(fs.createWriteStream(filename)).once('close', function () {
			this._image.removeListener('error', fn);
			fn(undefined, this);
		}.bind(this)).once('error', function (err) {
			this._image.removeListener('close', fn);
			fn(err, this);
		}.bind(this));
	}
317473
function shouldIgnore(filename, ignore, only) {
  filename = _slash2["default"](filename);

  if (only) {
    var _arr = only;

    for (var _i = 0; _i < _arr.length; _i++) {
      var pattern = _arr[_i];
      if (_shouldIgnore(pattern, filename)) return false;
    }
    return true;
  } else if (ignore.length) {
    var _arr2 = ignore;

    for (var _i2 = 0; _i2 < _arr2.length; _i2++) {
      var pattern = _arr2[_i2];
      if (_shouldIgnore(pattern, filename)) return true;
    }
  }

  return false;
}
121974
function(callback) {
          if (!context.copyOriginal) {
            return callback(null);
          }
          var suffix = 'original.' + context.extension;
          var tempFile = context.tempFolder + '/' + suffix;
          if (context.extension !== 'jpg') {
            // Don't forget to tell the caller that we did the work,
            // even if it was just a copy
            context.adjustedOriginal = tempFile;
            return copyFile(context.workingPath, tempFile, callback);
          }

          var args = [ context.workingPath ];
          if (context.crop) {
            args.push('-crop');
            args.push(context.crop.left);
            args.push(context.crop.top);
            args.push(context.crop.width);
            args.push(context.crop.height);
          }
          args.push('-write');
          args.push(tempFile);
          context.adjustedOriginal = tempFile;

          var proc = childProcess.spawn('imagecrunch', args);
          proc.on('close', function(code) {
            if (code !== 0) {
              return callback(code);
            }
            return callback(null);
          });
        }
963190
def new_file(self):
        

        file = self.get_untitled_file_name()
        LOGGER.debug("> Creating '{0}' file.".format(file))
        self.set_file(file, is_modified=False, is_untitled=True)
        self.__set_document_signals()
        return file
437240
def rerender(self):
        '''
        
        '''
        with self.fs.open(self.original, 'rb') as f_img:
            img = io.BytesIO(f_img.read())  # Store the image in memory to avoid overwritting
        self.save(img, filename=self.filename, bbox=self.bbox, overwrite=True)
375613
def optimize(dirpath, filename):
    
    filepath = os.path.join(dirpath, filename)
    logger.info('optimizing %s', filepath)

    ext = os.path.splitext(filename)[1]
    command, silent, verbose = COMMANDS[ext]
    flags = verbose if SHOW_OUTPUT else silent
    command = command.format(filename=filepath, flags=flags)
    call(command, shell=True)
515640
def pre_save(self, model_instance, add):
        
        file = getattr(model_instance, self.attname)
        if file and not file._committed:
            file.name = self._clean_file_name(model_instance, file.name)
            file.file = self._resize_image(model_instance, file)
            file.save(file.name, file, save=False)
        return file
1302788
def create_existing_file(help_string=NO_HELP, default=NO_DEFAULT, suffixes=None):
        # type: (str, Union[str, NO_DEFAULT_TYPE], Union[List[str], None]) -> str
        
        # noinspection PyTypeChecker
        return ParamFilename(
            help_string=help_string,
            default=default,
            type_name="existing_file",
            suffixes=suffixes,
        )
252056
def save_image(self, img, filename=None, **kwargs):  # floating_point=False,
        
        filename = filename or self.get_filename(**img.data.attrs)
        nt.save(img, filename, **kwargs)
477187
function saveFile() {
      if (currentFile) {
        if (!currentFile.oldName) {
          currentFile.oldName = possibleOldName;
        }

        if (!currentFile.newName) {
          currentFile.newName = possibleNewName;
        }

        if (currentFile.newName) {
          files.push(currentFile);
          currentFile = null;
        }
      }

      possibleOldName = undefined;
      possibleNewName = undefined;
    }
1185800
def optimize_thumbnail(thumbnail):
    ''''''
    try:
        optimize_command = settings.THUMBNAIL_OPTIMIZE_COMMAND[
            determinetype(thumbnail.path)]
        if not optimize_command:
            return
    except (TypeError, KeyError, NotImplementedError):
        return
    storage = thumbnail.storage
    try:
        with NamedTemporaryFile() as temp_file:
            thumbnail.seek(0)
            temp_file.write(thumbnail.read())
            temp_file.flush()
            optimize_command = optimize_command.format(filename=temp_file.name)
            output = check_output(
                optimize_command, stderr=subprocess.STDOUT, shell=True)
            if output:
                logger.warning(
                    '{0} returned {1}'.format(optimize_command, output))
            else:
                logger.info('{0} returned nothing'.format(optimize_command))
            with open(temp_file.name, 'rb') as f:
                thumbnail.file = ContentFile(f.read())
                storage.delete(thumbnail.path)
                storage.save(thumbnail.path, thumbnail)
    except Exception as e:
        logger.error(e)
298192
def savefig(self, filename, **kwargs):
        
        filename = os.path.expanduser(filename)
        kwargs.setdefault('show', False)
        kwargs.setdefault('save', filename)
        kwargs.setdefault('animate', False)
        return self._show_or_save(**kwargs)
202769
async function fileExists(f) {
  debug(`fileExists called with: ${JSON.stringify(arguments)}`);
  try {
    await fs.statAsync(f);
    return f;
  } catch (e) {
    throw e;
  }
}