Replace the spectrum of an existing source with a
        FileFunction.
766462
def _create_filefunction(self, name, spectrum_pars):
        """"""

        spectrum_pars = {} if spectrum_pars is None else spectrum_pars

        if 'loge' in spectrum_pars:
            loge = spectrum_pars.get('loge')
        else:
            ebinsz = (self.log_energies[-1] -
                      self.log_energies[0]) / self.enumbins
            loge = utils.extend_array(self.log_energies, ebinsz, 0.5, 6.5)

        # Get the values
        dnde = np.zeros(len(loge))
        if 'dnde' in spectrum_pars:
            dnde = spectrum_pars.get('dnde')
        else:
            dnde = np.array([self.like[name].spectrum()(pyLike.dArg(10 ** egy))
                             for egy in loge])

        filename = \
            os.path.join(self.workdir,
                         '%s_filespectrum.txt' % (name.lower().replace(' ', '_')))

        # Create file spectrum txt file
        np.savetxt(filename, np.vstack((10**loge, dnde)).T)
        self.like.setSpectrum(name, str('FileFunction'))

        self.roi[name]['Spectrum_Filename'] = filename
        # Update
        for c in self.components:
            src = c.like.logLike.getSource(str(name))
            spectrum = src.spectrum()

            spectrum.getParam(str('Normalization')).setBounds(1E-3, 1E3)

            file_function = pyLike.FileFunction_cast(spectrum)
            file_function.readFunction(str(filename))
            c.roi[name]['Spectrum_Filename'] = filename
641469
def brf(path, f, t):
    """"""
    from .tools.file import batch_rename_file
    batch_rename_file(path, f, t)
1158755
function replaceFilePlaceholders(oFile, aReplacementRules) {
  // parse file
  const sRaw = oFile.contents.toString('utf8')
  const sUpdatedFile = aReplacementRules.reduce((oResult, oRule) => {
    return oResult.replace(oRule.identifier, oRule.content)
  }, sRaw)

  // update new raw content
  oFile.contents = new Buffer(sUpdatedFile)

  // return updated file
  return oFile
}
1022102
function copyReplace( src, dest, replacements ){

        if ( replacements ){
            var source = grunt.file.read( src );
            for ( var s in replacements ){
                var r = replacements[s];
                var re = new RegExp( s, "g" );
                source = source.replace( re, r );
            }
            grunt.file.write( dest, source );
        }
        else{
            grunt.file.copy( src, dest );
        }

	}
1046937
def replace(self, source, dest):
        """"""
        for i, broker in enumerate(self.replicas):
            if broker == source:
                self.replicas[i] = dest
                return
155424
public static FileStatus replaceScheme(FileStatus st, String replace, String replacement) {
    if (replace != null && replace.equals(replacement)) {
      return st;
    }
    try {
      return new FileStatus(st.getLen(), st.isDir(), st.getReplication(), st.getBlockSize(), st.getModificationTime(),
          st.getAccessTime(), st.getPermission(), st.getOwner(), st.getGroup(), st.isSymlink() ? st.getSymlink() : null,
          replaceScheme(st.getPath(), replace, replacement));
    } catch (IOException ioe) {
      throw new RuntimeException(ioe);
    }
  }
777543
function replace(content, filename) {
    var dirname = nps.dirname(filename)

    return content.replace(
      new RegExp(
        '(^\\s*)' + prefix + '\\s*(.+?)\\s*' + suffix + '(\\s*\\n?)$',
        'gm'
      ),
      // /@\s*(.+?)\s*@/g,
      function(m, preappend, path, newlineOrNull) {
        var currLink = path.trim()
        var fullpath = ''

        // link::[why-need-require]../refs/why-need-require.md
        if (disableValue !== 'link' && currLink.startsWith('link::')) {
          var title = ''
          path = ''

          if (/^link::\[(.+?)\](.+)/.test(currLink)) {
            title = RegExp.$1
            path = RegExp.$2
            title = title && title.trim() ? title.trim() : path
          } else if (/^link::(.+)/.test(currLink)) {
            title = RegExp.$1
            path = RegExp.$1
          }

          fullpath = checkPath(path, dirname, selfFilename, true, alias)

          if (fullpath) {
            var link = findLink(filesMap, fullpath)
            if (link !== false) {
              return preappend + '[' + title + '](' + link + ')' + newlineOrNull
            }
          }
        }

        if (disableValue !== 'file-content') {
          fullpath = checkPath(currLink, dirname, filename, false, alias)
          if (fullpath) {
            var fileContent = fs.readFileSync(fullpath).toString()
            if (deep) {
              fileContent = replace(fileContent, fullpath)
            }

            return fileContent + newlineOrNull
          }
        }

        return m
      }
    )
  }
747788
def replace_in_file(workspace, src_file_path, from_str, to_str):
  
  from_bytes = from_str.encode('ascii')
  to_bytes = to_str.encode('ascii')
  data = read_file(os.path.join(workspace, src_file_path), binary_mode=True)
  if from_bytes not in data and from_str not in src_file_path:
    return None

  dst_file_path = src_file_path.replace(from_str, to_str)
  safe_file_dump(os.path.join(workspace, dst_file_path),
                 data.replace(from_bytes, to_bytes),
                 mode='wb')
  if src_file_path != dst_file_path:
    os.unlink(os.path.join(workspace, src_file_path))
  return dst_file_path
313850
function replaceStringsInFile(name, rootDir, replacements) {
  return findFirstFile(name, rootDir)
  .then(function (path) {
    return fs.readFileAsync(path, 'utf8')
    .then(function (content) {
      return replaceContent(path, content, replacements);
    })
    .then(function (content) {
      return fs.writeFileAsync(path, content, 'utf8');
    });

  })
  .catch(function (error) {
    console.error(
      'we couldn\'t replace strings in file, error: \'%s\', stack: \'%s\'',
      error.toString(), error.stack
    );
    return Promise.reject(error);
  });
}
144525
def add_spectrum(self, compare_to_existing=True, **kwargs):
        """"""
        spec_key = self._KEYS.SPECTRA
        # Make sure that a source is given, and is valid (nor erroneous)
        source = self._check_cat_dict_source(Spectrum, spec_key, **kwargs)
        if source is None:
            return None

        # Try to create a new instance of `Spectrum`
        new_spectrum = self._init_cat_dict(Spectrum, spec_key, **kwargs)
        if new_spectrum is None:
            return None

        is_dupe = False
        for item in self.get(spec_key, []):
            # Only the `filename` should be compared for duplicates. If a
            # duplicate is found, that means the previous `exclude` array
            # should be saved to the new object, and the old deleted
            if new_spectrum.is_duplicate_of(item):
                if SPECTRUM.EXCLUDE in new_spectrum:
                    item[SPECTRUM.EXCLUDE] = new_spectrum[SPECTRUM.EXCLUDE]
                elif SPECTRUM.EXCLUDE in item:
                    item.update(new_spectrum)
                is_dupe = True
                break

        if not is_dupe:
            self.setdefault(spec_key, []).append(new_spectrum)
        return
1154465
public void addSharedFunction(ISource source) {
		String fileName = source instanceof FileSource ? ((FileSource)source).getFileName() : null;
		doAddSharedFunction(source, fileName);
	}
1026686
def copyFunc(dest, source, env):
    """"""

    if os.path.isdir(source):
        if os.path.exists(dest):
            if not os.path.isdir(dest):
                raise SCons.Errors.UserError("cannot overwrite non-directory `%s' with a directory `%s'" % (str(dest), str(source)))
        else:
            parent = os.path.split(dest)[0]
            if not os.path.exists(parent):
                os.makedirs(parent)
        scons_copytree(source, dest)
    else:
        shutil.copy2(source, dest)
        st = os.stat(source)
        os.chmod(dest, stat.S_IMODE(st[stat.ST_MODE]) | stat.S_IWRITE)

    return 0
100557
def replace(self, uid, ical, filename=None):
        """"""
        return self.replace_vobject(uid, readOne(ical), filename)
1144324
private void addFileToTransform(Map<Transformer,Map<String,Set<URI>>> gs, Transformer t, Source s) {
        Map<String,Set<URI>> fs = gs.get(t);
        if (fs == null) {
            fs = new HashMap<String,Set<URI>>();
            gs.put(t, fs);
        }
        Set<URI> ss = fs.get(s.pkg().name());
        if (ss == null) {
            ss = new HashSet<URI>();
            fs.put(s.pkg().name(), ss);
        }
        ss.add(s.file().toURI());
    }
719657
function( replace ){
        var _buffer = [],
            _url,
            _code,
            _files  = replace.css ,
            _filename;
        for( var i = _files.length; i--; ){
            _url    = Path.join( config.dir.srcDir , _files[ i ] );
            if( grunt.file.exists( _url ) ){
                _code = tool.fixImageUrl( grunt.file.read( _url ).toString() , _url );
                _buffer.push( _code );
            };
        };
        _code = new mincss( config.mincss ).minify( _buffer.join( "" ) );
        _filename   = "css/" + MD5( _code ) + ".css";
        grunt.file.write( Path.join( config.dir.pubDir , _filename ) , _code );
        return _filename;
    }
729004
function(file, list) {
        console.debug('replacing: ', file);
        try {
            var f;
            f =(f=file.split(/\//))[f.length-1];
            var isJS = /\.js/.test(f.substring(f.length-3));
            var isJSON = /\.js/.test(f.substring(f.length-5));

            if ( isJS || isJSON && /config\/app\.json/.test(file) ) {
                var contentFile = fs.readFileSync(file, 'utf8').toString();
                //var contentFile = require(file).toSource();
                var dic = {
                    "Bundle" : self.bundle.substring(0, 1).toUpperCase() + self.bundle.substring(1),
                    "bundle" : self.bundle
                };

                contentFile = whisper(dic, contentFile);//data
                //rewrite file
                fs.writeFileSync(file, contentFile)
            }

            if ( list != undefined && list.indexOf(file) > -1 ) { //end of current dir
                list.splice( list.indexOf(file), 1 )
            }
            return list

        } catch(err) {
            console.error(err.stack);
            process.exit(1)
        }
    }
1287844
def _replace_lines(fn, startswith, new_line):
  """"""
  new_lines = []
  for line in open(fn):
    if line.startswith(startswith):
      new_lines.append(new_line)
    else:
      new_lines.append(line)
  with open(fn, 'w') as f:
    f.write('\n'.join(new_lines))