Parameters
    ----------
    hw : HandwrittenData object
    filename : string
        Path, where the SCG INK file gets written
350786
def write_hw_scgink(hw, filename='mathbrush-test.txt'):
    
    with open(filename, 'w') as f:
        f.write('SCG_INK\n')
        f.write('%i\n' % len(hw.get_pointlist()))
        for stroke in hw.get_pointlist():
            f.write('%i\n' % len(stroke))
            for point in stroke:
                f.write('%i %i\n' % (point['x'], point['y']))
512736
def rewrite_record_file(workspace, src_record_file, mutated_file_tuples):
  
  mutated_files = set()
  dst_record_file = None
  for src, dst in mutated_file_tuples:
    if src == src_record_file:
      dst_record_file = dst
    else:
      mutated_files.add(dst)
  if not dst_record_file:
    raise Exception('Malformed whl or bad globs: `{}` was not rewritten.'.format(src_record_file))

  output_records = []
  file_name = os.path.join(workspace, dst_record_file)
  for line in read_file(file_name).splitlines():
    filename, fingerprint_str, size_str = line.rsplit(',', 3)
    if filename in mutated_files:
      fingerprint_str, size_str = fingerprint_file(workspace, filename)
      output_line = ','.join((filename, fingerprint_str, size_str))
    else:
      output_line = line
    output_records.append(output_line)

  safe_file_dump(file_name, '\r\n'.join(output_records) + '\r\n')
305277
def svgdump(self, filename=None, **kargs):
        
        from scapy.config import conf
        from scapy.utils import get_temp_file, ContextManagerSubprocess
        canvas = self.canvas_dump(**kargs)
        if filename is None:
            fname = get_temp_file(autoext=kargs.get("suffix", ".svg"))
            canvas.writeSVGfile(fname)
            if WINDOWS and conf.prog.svgreader is None:
                os.startfile(fname)
            else:
                with ContextManagerSubprocess("svgdump()",
                                              conf.prog.svgreader):
                    subprocess.Popen([conf.prog.svgreader, fname])
        else:
            canvas.writeSVGfile(filename)
        print()
698179
def printMcmcSamplesToFile(self, profile, numSamples, outFileName):
        

        wmg = profile.getWmg(True)
        V = self.getInitialSample(wmg)

        # Print the number of candidates, phi, and the number of samples.
        outFile = open(outFileName, 'w')
        outFile.write("m," + str(profile.numCands) + '\n')
        outFile.write("phi," + str(self.phi) + '\n')
        outFile.write("numSamples," + str(numSamples))
        
        for i in range(0, numSamples):
            V = self.sampleGenerator.getNextSample(V)
            outFile.write("\n" + json.dumps(V))
        outFile.close()
268254
def imgwriteincr(fn: Path, imgs, imgslice):
    
    if isinstance(imgslice, int):
        if imgslice and not (imgslice % 2000):
            print(f'appending images {imgslice} to {fn}')

    if isinstance(fn, Path):
        # avoid accidental overwriting of source file due to misspecified command line
        assert fn.suffix == '.h5', 'Expecting to write .h5 file'

        with h5py.File(fn, 'r+') as f:
            f['/rawimg'][imgslice, :, :] = imgs
    elif isinstance(fn, h5py.File):
        f['/rawimg'][imgslice, :, :] = imgs
    else:
        raise TypeError(
            f'{fn} must be Path or h5py.File instead of {type(fn)}')
750075
def _write(self, session, openFile, replaceParamFile):
        
        # Enforce cards that must be written in certain order
        PRIORITY_CARDS = ('WMS', 'MASK_WATERSHED', 'REPLACE_LINE',
                          'REPLACE_PARAMS', 'REPLACE_VALS', 'REPLACE_FOLDER')

        filename = os.path.split(openFile.name)[1]
        name = filename.split('.')[0]

        # Write lines
        openFile.write('GSSHAPROJECT\n')

        # Write priority lines
        for card_key in PRIORITY_CARDS:
            card = self.getCard(card_key)

            # Write the card
            if card is not None:
                openFile.write(card.write(originalPrefix=self.name, newPrefix=name))

        # Initiate write on each ProjectCard that belongs to this ProjectFile
        for card in self.projectCards:
            if card.name not in PRIORITY_CARDS:
                openFile.write(card.write(originalPrefix=self.name, newPrefix=name))
701195
public String createWthFileName(Map wthData) {

        String hash = getValueOr(wthData, "wst_id", "") + getValueOr(wthData, "clim_id", "");

        if (hashToName.containsKey(hash)) {
            return hashToName.get(hash);
        } else {
            String insiName = getWthInsiCodeOr(wthData);
            String yearDur = getWthYearDuration(wthData);
            String wst_id = insiName;
            if (insiName.length() == 4) {
                String clim_id = getValueOr(wthData, "clim_id", "0XXX");
                if (!clim_id.startsWith("0")) {
                    wst_id += clim_id;
                    yearDur = clim_id;
                } else {
                    wst_id += yearDur;
                }
            }
            while (names.contains(wst_id)) {
                wst_id = getNextDefName() + yearDur;
            }
            names.add(wst_id);
            if (hash.equals("")) {
                hash = wst_id;
            }
            hashToName.put(hash, wst_id);
            return wst_id;
        }
    }
29691
def _write(self, session, openFile, replaceParamFile):
        
        # Write Lines
        openFile.write('GRIDPIPEFILE\n')
        openFile.write('PIPECELLS %s\n' % self.pipeCells)

        for cell in self.gridPipeCells:
            openFile.write('CELLIJ    %s  %s\n' % (cell.cellI, cell.cellJ))
            openFile.write('NUMPIPES  %s\n' % cell.numPipes)

            for node in cell.gridPipeNodes:
                openFile.write('SPIPE     %s  %s  %.6f\n' % (
                    node.linkNumber,
                    node.nodeNumber,
                    node.fractPipeLength))
334720
def writeRegeneratedFile(outFile, makeBackup, checkNoChanges)
      puts "writeRegeneratedFile, #{outFile}, makeBackup = #{makeBackup}, checkNoChanges = #{checkNoChanges}"
      if makeBackup
        backupFileName = makeBackupFile(outFile)
      end
      File.open(outFile, "w") do |f|
        for component in @components do
          f.write(component.output)
        end
      end
      puts " wrote regenerated page to #{outFile}"
      if checkNoChanges
        if !makeBackup
          raise Exception.new("writeRegeneratedFile #{outFile}: checkNoChanges specified, but no backup was made")
        end
        checkAndEnsureOutputFileUnchanged(outFile, backupFileName)
      end
    end
883434
def read_folder(folder):
    
    recordings = []
    for filename in glob.glob(os.path.join(folder, '*.ink')):
        recording = parse_scg_ink_file(filename)
        recordings.append(recording)
    return recordings
552442
def write_src(hdf5_out, gctoo_object, out_file_name):
    
    if gctoo_object.src == None:
        hdf5_out.attrs[src_attr] = out_file_name
    else:
        hdf5_out.attrs[src_attr] = gctoo_object.src
925737
protected synchronized String getWthFileName(Map data) {

//        String agmipFileHack = getValueOr(wthFile, "wst_name", "");
//        if (agmipFileHack.length() == 8) {
//            return agmipFileHack;
//        }
        String ret = getObjectOr(data, "wst_id", "");
        if (ret.equals("") || ret.length() > 8) {
            ret = wthHelper.createWthFileName(getObjectOr(data, "weather", data));
            if (ret.equals("")) {
                ret = "AGMP";
            }
        }

        return ret;
    }
331086
def write(self,fileName):
        '''
        '''
        f = open(fileName, 'ab')
        f.write('%s%s' % (self.polarisText,
                          Synset.linebreak)
                )
        f.close()
1201663
def _write(self, session, openFile, replaceParamFile):
        
        # Retrieve TimeStep objects
        timeSteps = self.timeSteps

        # Write Lines
        openFile.write('%s\n' % self.name)
        openFile.write('NUM_LINKS     %s\n' % self.numLinks)
        openFile.write('TIME_STEP     %s\n' % self.timeStepInterval)
        openFile.write('NUM_TS        %s\n' % self.numTimeSteps)
        openFile.write('START_TIME    %s\n' % self.startTime)

        for timeStep in timeSteps:
            openFile.write('TS    %s\n' % timeStep.timeStep)

            # Retrieve LinkDataset objects
            linkDatasets = timeStep.linkDatasets

            for linkDataset in linkDatasets:
                # Write number of node datasets values
                openFile.write('{0}   '.format(linkDataset.numNodeDatasets))

                # Retrieve NodeDatasets
                nodeDatasets = linkDataset.nodeDatasets

                if linkDataset.numNodeDatasets > 0:
                    for nodeDataset in nodeDatasets:
                        # Write status and value
                        openFile.write('{0}  {1:.5f}   '.format(nodeDataset.status, nodeDataset.value))
                else:
                    for nodeDataset in nodeDatasets:
                        # Write status and value

                        if linkDataset.numNodeDatasets < 0:
                            openFile.write('{0:.5f}'.format(nodeDataset.value))
                        else:
                            openFile.write('{0:.3f}'.format(nodeDataset.value))

                # Write new line character after each link dataset
                openFile.write('\n')

            # Insert empty line between time steps
            openFile.write('\n')
1340419
def is_file_writable(test_file):
    
    p = Path(test_file)

    if p.is_symlink():
        p = p.resolve(strict=False)

    # p.is_file() throws an exception in some cases
    if p.exists() and p.is_file():
        return os.access(
            os.fspath(p),
            os.W_OK,
            effective_ids=(os.access in os.supports_effective_ids),
        )
    else:
        try:
            fp = p.open('wb')
        except OSError:
            return False
        else:
            fp.close()
            with suppress(OSError):
                p.unlink()
        return True
137298
def filter_and_save(raw, symbol_ids, destination_path):
    
    logging.info('Start filtering...')
    new_hw_ds = []
    for el in raw['handwriting_datasets']:
        if el['formula_id'] in symbol_ids:
            el['formula_id'] = symbol_ids[el['formula_id']]
            el['handwriting'].formula_id = symbol_ids[el['formula_id']]
            new_hw_ds.append(el)
    raw['handwriting_datasets'] = new_hw_ds

    # pickle
    logging.info('Start dumping %i recordings...', len(new_hw_ds))
    pickle.dump(raw, open(destination_path, "wb"), 2)
469320
def file():
        
        return (
            Optional(Word(alphanums).setResultsName('alias') +
                Suppress(Literal('.'))) + Suppress(White()) +
            Word(approved_printables).setResultsName('filename')
            )