Grab the percentage change from previous snapshots
 @since 0.1.5
 @param file [String]
 @param browser_output [Hash]
 @return [Hash]
342967
def wraith_percentage(file, browser_output)
        file_object = File.open(file, 'rb')
        browser_output[:percent_changed] ||= {}
        browser_output[:percent_changed][File.basename(file).split('_')[0].to_i] = file_object.read.to_f

        file_object.close

        browser_output
      end
1280449
def any_file_changed(filenames, hash_type='md5'):
    
    changed = False
    for filename in filenames:
        if callable(filename):
            filename = str(filename())
        else:
            filename = str(filename)
        old_hash = unitdata.kv().get('reactive.files_changed.%s' % filename)
        new_hash = host.file_hash(filename, hash_type=hash_type)
        if old_hash != new_hash:
            unitdata.kv().set('reactive.files_changed.%s' % filename, new_hash)
            changed = True  # mark as changed, but keep updating hashes
    return changed
106099
function stripify(file) {
  if (/\.json$/.test(file)) return through();

  var code = '';

  function transform(chunk, encoding, next) {
    code += chunk;
    next();
  }

  function flush(done) {
    /* jshint validthis: true */
    var ast = rocambole.parse(code);

    code = rocambole.moonwalk(ast, function strip(node) {
      if (( // var debug = function() {};
          'VariableDeclaration' === node.type
        && 'debug' === node.declarations[0].id.name
      ) || ( // if (process.env.NODE_ENV !== 'production') { debug = ... }
          'IfStatement' === node.type
        && 'BinaryExpression' === node.test.type
        && 'production' === node.test.right.value
      ) || ( // debug( ... );
          'ExpressionStatement' === node.type
        && 'CallExpression' === node.expression.type
        && 'debug' === node.expression.callee.name
      )) {
        return remove(node);
      }
    });

    this.push(code.toString());
    done();
  }

  return through(transform, flush);
}
652315
def showDiffResults(self):
        
        try:
            oldWarnings = self.parseWarnings(self._readDiffFile())
        except:
            sys.stderr.write(self.errorResultRead % self.diffOption)
            return 1

        newWarnings = self.parseWarnings(self.streamForDiff.getvalue())

        diffWarnings = self.generateDiff(oldWarnings, newWarnings)

        if diffWarnings:
            diffResult = self.formatWarnings(diffWarnings)
            self.outputStream.write(diffResult + "\n")
            return len(diffWarnings)
        else:
            return 0
901389
def diff_snapshots(self,snapshot_a,snapshot_b,save = True, diff=None):

        

        file_revisions_a = snapshot_a.file_revisions
        file_revisions_b = snapshot_b.file_revisions

        file_revisions_diff = diff_objects(file_revisions_a,
                                           file_revisions_b,
                                           file_revision_key,
                                           file_revision_comparator)

        #We just generate code objects and issues
        #for the modified file revisions, to save time when diffing.

        logger.debug("Generating list of modified file revisions...")
        modified_file_revisions_by_path = {}
        for fr_type in ('modified','added','deleted'):
            for fr in file_revisions_diff[fr_type]:
                if not fr.path in modified_file_revisions_by_path:
                    modified_file_revisions_by_path[fr.path] = fr

        logger.debug("Generating list of modified issues...")

        modified_file_revisions_a = [fr for fr in file_revisions_a
                                     if fr.path in modified_file_revisions_by_path]
        modified_file_revisions_b = [fr for fr in file_revisions_b
                                     if fr.path in modified_file_revisions_by_path]

        if modified_file_revisions_a:
            #to do: check the file revisions chunk-wise to avoid DB query errors
            issue_occurrences_a = self.project.backend.filter(IssueOccurrence,
                                         {
                                            'file_revision' : {'$in' : modified_file_revisions_a}
                                         },
                                      include = ('file_revision','issue'))
        else:
            issue_occurrences_a = []

        if modified_file_revisions_b:
            #to do: check the file revisions chunk-wise to avoid DB query errors
            issue_occurrences_b = self.project.backend.filter(IssueOccurrence,
                                           {
                                            'file_revision' : {'$in' : modified_file_revisions_b}
                                            },
                                      include = ('file_revision','issue'))
        else:
            issue_occurrences_b = []

        logger.debug("Diffing issues (%d in A, %d in B)" % (len(issue_occurrences_a),
                                                           len(issue_occurrences_b)))


        issue_occurrences_diff = diff_objects(issue_occurrences_a,
                                              issue_occurrences_b,
                                              issue_occurrence_key,
                                              issue_occurrence_comparator)

        logger.debug("Diffing summary...")
        summary_diff = self.diff_summaries(snapshot_a,snapshot_b)

        if diff is None:
            diff = Diff({'summary' : summary_diff,
                        'snapshot_a' : snapshot_a,
                        'project' : self.project,
                        'configuration' : self.project.configuration,
                        'snapshot_b' : snapshot_b})
            #we generate the hash value for this diff
            hasher = Hasher()
            hasher.add(diff.snapshot_a.hash)
            hasher.add(diff.snapshot_b.hash)
            diff.hash = hasher.digest.hexdigest()
        elif save:
            with self.project.backend.transaction():
                self.project.backend.filter(DiffFileRevision,{'diff' : diff}).delete()
                self.project.backend.filter(DiffIssueOccurrence,{'diff' : diff}).delete()
        if save:
            with self.project.backend.transaction():
                self.project.backend.save(diff)

        diff_file_revisions = []

        with self.project.backend.transaction():
            for key,file_revisions in file_revisions_diff.items():
                for file_revision in file_revisions:
                    hasher = Hasher()
                    hasher.add(file_revision.hash)
                    hasher.add(diff.hash)
                    hasher.add(key)
                    diff_file_revision = DiffFileRevision({
                                            'diff' : diff,
                                            'file_revision' : file_revision,
                                            'hash' : hasher.digest.hexdigest(),
                                            'key' : key})
                    if save:
                        self.project.backend.save(diff_file_revision)
                    diff_file_revisions.append(diff_file_revision)

        diff_issue_occurrences = []
        mapping = {'deleted' : 'fixed','added' : 'added'}
        with self.project.backend.transaction():
            for key,issue_occurrences in issue_occurrences_diff.items():
                if not key in mapping:
                    continue
                for issue_occurrence in issue_occurrences:
                    hasher = Hasher()
                    hasher.add(issue_occurrence.hash)
                    hasher.add(diff.hash)
                    hasher.add(mapping[key])
                    diff_issue_occurrence = DiffIssueOccurrence({
                            'diff' : diff,
                            'hash' : hasher.digest.hexdigest(),
                            'issue_occurrence' : issue_occurrence,
                            'key' : mapping[key]
                        })
                    if save:
                        self.project.backend.save(diff_issue_occurrence)
                    diff_issue_occurrences.append(diff_issue_occurrence)

        return diff,diff_file_revisions,diff_issue_occurrences
50217
public String calculateVersionFrom(@NotNull File file){
        Objects.requireNonNull(file, "file argument cannot be null");
        //optimise by store hash against file modified time, on subsequent calls, check file modified time first to determine file and time is present and return previous data.
        final long lastModified = file.lastModified();
        final String key = file.getAbsolutePath() + lastModified;
        final String storedHashValue = fixedSizeCache.get(key);
        if(!StringUtils.isEmpty(storedHashValue)){
            return storedHashValue;
        }
        final String digestHex;
        try {
            digestHex = getHashFromBytes(Files.readAllBytes(file.toPath()));
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
        fixedSizeCache.put(key, digestHex);
        return digestHex;
    }
291633
function(data) {
  var output = {
    name: data.fileName
  };

  var statements = _.without(data.lines, null);

  output.statementsTotal = statements.length;
  output.statementsCovered = _.compact(statements).length;
  output.percentage = percentage(output.statementsCovered, output.statementsTotal);

  if (this.options.branchTracking) {
    output = _.assign(output, branchCoverage(data));
  }
  return output;

}
1324091
def percentage_diff(org, fresh)
      diff_images(org, fresh)
      @total_px = @images.first.pixels.length
      @changed_px = @diff_index.length
      @percentage_changed = ( (@diff_index.length.to_f / @images.first.pixels.length) * 100 ).round(2)
    end
881912
function (file) {
        var self = this;
        this.state = 'pending';

        this.pc.isInitiator = true;

        this.sender = new FileTransfer.Sender();
        this.sender.on('progress', function (sent, size) {
            self._log('info', 'Send progress ' + sent + '/' + size);
        });
        this.sender.on('sentFile', function (meta) {
            self._log('info', 'Sent file', meta.name);

            var content = self.pc.localDescription.contents[0];
            delete content.transport;

            content.application = {
                applicationType: 'filetransfer',
                offer: {
                    hash: {
                        algo: meta.algo,
                        value: meta.hash
                    }
                }
            };

            self.send('description-info', {
                contents: [content]
            });
            self.emit('sentFile', self, meta);
        });

        var sendChannel = this.pc.createDataChannel('filetransfer');
        sendChannel.onopen = function () {
            self.sender.send(file, sendChannel);
        };

        var constraints = {
            mandatory: {
                OfferToReceiveAudio: false,
                OfferToReceiveVideo: false
            }
        };

        this.pc.offer(constraints, function (err, offer) {
            if (err) {
                self._log('error', 'Could not create WebRTC offer', err);
                return self.end('failed-application', true);
            }

            offer.jingle.contents[0].application = {
                applicationType: 'filetransfer',
                offer: {
                    date: file.lastModifiedDate,
                    name: file.name,
                    size: file.size,
                    hash: {
                        algo: 'sha-1',
                        value: ''
                    }
                }
            };

            self.send('session-initiate', offer.jingle);
        });
    }
229643
function (percentListener, stepListener) {
		this.previousPercent = 0;
		// Function gets updated and has a percentage value.
		this.updatePercentage = function (value, callback) {
			var newVal = Math.floor(parseFloat(value.toFixed(1)));
			if(newVal !== upgradeProgressListener.previousPercent) {
				if (callback !== undefined) {
					percentListener(newVal)
					.then(callback);
				}
				upgradeProgressListener.previousPercent = newVal;
			}
		};

		// Function gets updated during various steps of the update procedure.
		// Text: 1. "", "", ""
		this.updateStepName = function (value, callback) {
			if (callback !== undefined) {
				stepListener(value)
				.then(callback);
			}
		};
		var upgradeProgressListener = this;
	}
916796
def fetchAfterStateFile(self, file_folder):
        

        if u"true" == self.after:
            self.log.info("This file has been deleted successfully.")
        else:
            self.log.info("Fetching final file of this Change<%s>:" % self)
            return self._fetchFile(self.after, file_folder)
418067
function _segment(file) {
  console.log();
  process.stdout.write(util.format('%s ', file));
}
596981
function File(file, options) {
  file = file || {};
  this.file = file;
  this.options = file.options || options || {};
  this.type = this.file.type;
  this.origPath = file.origPath;

  // Record path change
  var history = file.path ? [file.path] : file.history;
  this.history = history || [];

  this.cwd = file.cwd || process.cwd();
  this.base = file.base || this.cwd;

  // Stat = files stats object
  this.stat = file.stat || null;
  this._isFile = true;
}
87782
function ResumableFile(resumableObj, file, uniqueIdentifier){
      var $ = this;
      $.opts = {};
      $.getOpt = resumableObj.getOpt;
      $._prevProgress = 0;
      $.resumableObj = resumableObj;
      $.file = file;
      $.fileName = file.fileName||file.name; // Some confusion in different versions of Firefox
      $.size = file.size;
      $.relativePath = file.relativePath || file.webkitRelativePath || $.fileName;
      $.uniqueIdentifier = uniqueIdentifier;
      $._pause = false;
      $.container = '';
      $.preprocessState = 0; // 0 = unprocessed, 1 = processing, 2 = finished
      var _error = uniqueIdentifier !== undefined;

      // Callback when something happens within the chunk
      var chunkEvent = function(event, message){
        // event can be 'progress', 'success', 'error' or 'retry'
        switch(event){
        case 'progress':
          $.resumableObj.fire('fileProgress', $, message);
          break;
        case 'error':
          $.abort();
          _error = true;
          $.chunks = [];
          $.resumableObj.fire('fileError', $, message);
          break;
        case 'success':
          if(_error) return;
          $.resumableObj.fire('fileProgress', $, message); // it's at least progress
          if($.isComplete()) {
            $.resumableObj.fire('fileSuccess', $, message);
          }
          break;
        case 'retry':
          $.resumableObj.fire('fileRetry', $);
          break;
        }
      };

      // Main code to set up a file object with chunks,
      // packaged to be able to handle retries if needed.
      $.chunks = [];
      $.abort = function(){
        // Stop current uploads
        var abortCount = 0;
        $h.each($.chunks, function(c){
          if(c.status()=='uploading') {
            c.abort();
            abortCount++;
          }
        });
        if(abortCount>0) $.resumableObj.fire('fileProgress', $);
      };
      $.cancel = function(){
        // Reset this file to be void
        var _chunks = $.chunks;
        $.chunks = [];
        // Stop current uploads
        $h.each(_chunks, function(c){
          if(c.status()=='uploading')  {
            c.abort();
            $.resumableObj.uploadNextChunk();
          }
        });
        $.resumableObj.removeFile($);
        $.resumableObj.fire('fileProgress', $);
      };
      $.retry = function(){
        $.bootstrap();
        var firedRetry = false;
        $.resumableObj.on('chunkingComplete', function(){
          if(!firedRetry) $.resumableObj.upload();
          firedRetry = true;
        });
      };
      $.bootstrap = function(){
        $.abort();
        _error = false;
        // Rebuild stack of chunks from file
        $.chunks = [];
        $._prevProgress = 0;
        var round = $.getOpt('forceChunkSize') ? Math.ceil : Math.floor;
        var maxOffset = Math.max(round($.file.size/$.getOpt('chunkSize')),1);
        for (var offset=0; offset<maxOffset; offset++) {(function(offset){
            window.setTimeout(function(){
                $.chunks.push(new ResumableChunk($.resumableObj, $, offset, chunkEvent));
                $.resumableObj.fire('chunkingProgress',$,offset/maxOffset);
            },0);
        })(offset)}
        window.setTimeout(function(){
            $.resumableObj.fire('chunkingComplete',$);
        },0);
      };
      $.progress = function(){
        if(_error) return(1);
        // Sum up progress across everything
        var ret = 0;
        var error = false;
        $h.each($.chunks, function(c){
          if(c.status()=='error') error = true;
          ret += c.progress(true); // get chunk progress relative to entire file
        });
        ret = (error ? 1 : (ret>0.99999 ? 1 : ret));
        ret = Math.max($._prevProgress, ret); // We don't want to lose percentages when an upload is paused
        $._prevProgress = ret;
        return(ret);
      };
      $.isUploading = function(){
        var uploading = false;
        $h.each($.chunks, function(chunk){
          if(chunk.status()=='uploading') {
            uploading = true;
            return(false);
          }
        });
        return(uploading);
      };
      $.isComplete = function(){
        var outstanding = false;
        if ($.preprocessState === 1) {
          return(false);
        }
        $h.each($.chunks, function(chunk){
          var status = chunk.status();
          if(status=='pending' || status=='uploading' || chunk.preprocessState === 1) {
            outstanding = true;
            return(false);
          }
        });
        return(!outstanding);
      };
      $.pause = function(pause){
          if(typeof(pause)==='undefined'){
              $._pause = ($._pause ? false : true);
          }else{
              $._pause = pause;
          }
      };
      $.isPaused = function() {
        return $._pause;
      };
      $.preprocessFinished = function(){
        $.preprocessState = 2;
        $.upload();
      };
      $.upload = function () {
        var found = false;
        if ($.isPaused() === false) {
          var preprocess = $.getOpt('preprocessFile');
          if(typeof preprocess === 'function') {
            switch($.preprocessState) {
            case 0: $.preprocessState = 1; preprocess($); return(true);
            case 1: return(true);
            case 2: break;
            }
          }
          $h.each($.chunks, function (chunk) {
            if (chunk.status() == 'pending' && chunk.preprocessState !== 1) {
              chunk.send();
              found = true;
              return(false);
            }
          });
        }
        return(found);
      }
      $.markChunksCompleted = function (chunkNumber) {
        if (!$.chunks || $.chunks.length <= chunkNumber) {
            return;
        }
        for (var num = 0; num < chunkNumber; num++) {
            $.chunks[num].markComplete = true;
        }
      };

      // Bootstrap and return
      $.resumableObj.fire('chunkingStart', $);
      $.bootstrap();
      return(this);
    }
931976
def version_from_file
      if File.exist?(Rails.root.join("REVISION"))
        File.read(Rails.root.join("REVISION")).chomp
      end
    end
1059162
def open_in_browser(self, session, output_filename=None):
        
        if output_filename is None:
            output_file = tempfile.NamedTemporaryFile(suffix='.html', delete=False)
            output_filename = output_file.name
            with codecs.getwriter('utf-8')(output_file) as f:
                f.write(self.render(session))
        else:
            with codecs.open(output_filename, 'w', 'utf-8') as f:
                f.write(self.render(session))

        from pyinstrument.vendor.six.moves import urllib
        url = urllib.parse.urlunparse(('file', '', output_filename, '', '', ''))
        webbrowser.open(url)
        return output_filename
604030
def breakdown_by_file
      @file_breakdown ||= begin
        breakdown = Hash.new { |h,k| h[k] = Array.new }
        cache.each do |filename, (language, _)|
          breakdown[language] << filename.dup.force_encoding("UTF-8").scrub
        end
        breakdown
      end
    end