Exports to the given path an ASCII file containing all the scalars written
        so far by this instance, with the following format:
        {writer_id : [[timestamp, step, value], ...], ...}
10003
def export_scalars(self, path):
        
        if os.path.exists(path) and os.path.isfile(path):
            logging.warning('%s already exists and will be overwritten by scalar dict', path)
        with open(path, "w") as f:
            json.dump(self._scalar_dict, f)
980129
def load_csv(path):
    
    meta = []
    data = []
    with codecs.open(path, encoding="ASCII") as in_file:
        for line in in_file:
            if line.startswith("#"):
                key, value = line[1:].strip().split(" ", 1)
                meta.append((key, value))   # TODO: There are duplicit entries :-()
            else:
                try:
                    data.append([float(frag) for frag in line.split(",")])
                except:
                    pass
    data = np.asarray(data)
    ndim = int(_get(meta, "dimension"))
    if ndim == 1:
        return _create_h1(data, meta)
    elif ndim == 2:
        return _create_h2(data, meta)
488037
def write_attribute_adj_list(self, path):
        
        att_mappings = self.get_attribute_mappings()

        with open(path, mode="w") as file:
            for k, v in att_mappings.items():
                print("{} {}".format(k, " ".join(str(e) for e in v)), file=file)
1005337
def _get_ascii_field(self, values):
        ''''''

        empty_space = ' '

        # This formats as field[x][y]
        field = [[empty_space for y in range(max(values) + 1)] for x in range(len(values))]

        # Draw graph into field
        for x in range(len(values)):
            y = values[x]
            y_prev = values[x - 1] if x - 1 in range(len(values)) else y
            y_next = values[x + 1] if x + 1 in range(len(values)) else y
            # Fill empty space
            if abs(y_prev - y) > 1:
                # Fill space between y and y_prev
                step = 1 if y_prev - y > 0 else -1

                # We don't want the first item to be inclusive, so we use step instead of y+1 since step can be negative
                for h in range(y + step, y_prev, step):
                    if field[x][h] is empty_space:
                        field[x][h] = '|'

            # Assign the character to be placed into the graph
            char = self._assign_ascii_character(y_prev, y, y_next)

            field[x][y] = char
        return field
532133
def write_json(self, path, contents, message):
        
        log.debug(message.format(path=path))
        makedirs(os.path.dirname(path))
        with open(path, "w") as fh:
            json.dump(contents, fh, indent=2, sort_keys=True)
376109
def read_key_value_pairs_from_file(*path):
    
    with open(os.path.join(*path)) as f:
        for line in f:
            yield line.split(' ', 1)
1187646
def prt_paths(paths, prt=sys.stdout):
        """"""
        pat = "PATHES: {GO} L{L:02} D{D:02}\n"
        for path in paths:
            for go_obj in path:
                prt.write(pat.format(GO=go_obj.id, L=go_obj.level, D=go_obj.depth))
            prt.write("\n")
1205684
def write_gct(df, file_path):
    
    with open(file_path, 'w') as file:
        file.write('#1.2\n' + str(len(df.index)) + '\t' + str(len(df.columns)) + '\n')
        df.to_csv(file, sep='\t', mode='w+')
704512
def dump(obj, path, **kw):
    
    open_kw = {'mode': 'w'}
    if PY3:  # pragma: no cover
        open_kw['encoding'] = 'utf-8'

    # avoid indented lines ending with ", " on PY2
    if kw.get('indent') and kw.get('separators') is None:
        kw['separators'] = (',', ': ')

    with open(str(path), **open_kw) as fp:
        return json.dump(obj, fp, **kw)
259480
def write_json(data, path, file_name):
    
    if os.path.exists(path) and not os.path.isdir(path):
        return
    elif not os.path.exists(path):
        mkdir_p(path)
    with open(os.path.join(path, file_name), 'w') as f:
        json_tricks.dump(data, f, indent=4, primitives=True, allow_nan=True)
30537
def write(self, path, data, offset, fh):  # pragma: no cover
        
        # print("write {}".format(path))
        with self.attr_lock:
            base = self.attr[path][BASE_KEY]
            staged = self.attr[path][STAGED_KEY]
            if not staged.closed:
                base.st_size += len(data)
                staged.write(data)
        return len(data)
933965
public void toSrt(Path srtFile) {
        try (FileOutputStream fos = new FileOutputStream(srtFile.toFile());
             OutputStreamWriter osw = new OutputStreamWriter(fos, Charset.forName("UTF-8"));
             PrintWriter writer = new PrintWriter(osw)) {
            long counter = 1;
            for (Subtitle title : subtitleList) {
                writer.println(counter);
                writer.println(srtFormat.format(title.begin) + " --> " + srtFormat.format(title.end));
                for (StyledString entry : title.listOfStrings) {
                    if (!entry.color.isEmpty()) {
                        writer.print("<font color=\"" + entry.color + "\">");
                    }
                    writer.print(entry.text);
                    if (!entry.color.isEmpty()) {
                        writer.print("</font>");
                    }
                    writer.println();
                }
                writer.println("");
                counter++;
            }
        } catch (Exception ex) {
            Log.errorLog(201036470, ex, "File: " + srtFile);
        }
    }
1076738
def _write_json(filepath, data, kwargs):
    """"""
    with io_stl.open(filepath, 'w', encoding='utf8') as outfile:
        if 'indent' not in kwargs:
            kwargs['indent'] = 4
        if 'sort_keys' not in kwargs:
            kwargs['sort_keys'] = True
        if 'separators' not in kwargs:
            kwargs['separators'] = (',', ': ')
        if 'ensure_ascii' not in kwargs:
            kwargs['ensure_ascii'] = False
        str_ = json.dumps(data, **kwargs)
        outfile.write(to_unicode(str_))
    return data
774281
def flatten_and_write(dotenv_path, dotenv_as_dict, quote_mode='always'):
    
    with open(dotenv_path, 'w') as f:
        for k, v in dotenv_as_dict.items():
            str_format = _get_format(v, quote_mode)
            f.write(str_format.format(key=k, value=v))
    return True
291044
def get_cust_cols(path):
    
    required_keys = ["title", "id", "sType", "visible"]

    with open(path, 'r') as f:
        try:
            cust_cols = ast.literal_eval(f.read())
        except Exception as err:
            sys.stderr.write("Invalid custom columns file: {}\n".format(path))
            sys.stderr.write("{}\n".format(err))
            sys.exit(1)

    # Validate
    for col in cust_cols:
        for required_key in required_keys:
            if required_key not in col:
                sys.stderr.write("Missing required key '{}' in custom "
                                 "column {}\n".format(required_key, col))
                sys.exit(1)
            if "jsonxs" not in col and "tpl" not in col:
                sys.stderr.write("You need to specify 'jsonxs' or 'tpl' "
                                 "for custom column {}\n".format(col))
                sys.exit(1)

    return cust_cols
221426
def exportData(self, datfile):
        

        def ampl_set(name, values):
            def format_entry(e):
                return repr(e).replace(' ', '')

            return 'set {0} := {1};'.format(
                name, ','.join(format_entry(e) for e in values)
            )

        def ampl_param(name, values):
            def format_entry(k, v):
                k = repr(k).strip('()').replace(' ', '')
                if v == inf:
                    v = "Infinity"
                elif v == -inf:
                    v = "-Infinity"
                else:
                    v = repr(v).strip('()').replace(' ', '')
                return '[{0}]{1}'.format(k, v)

            return 'param {0} := {1};'.format(
                name, ''.join(format_entry(k, v) for k, v in values.items())
            )

        with open(datfile, 'w') as f:
            for name, entity in self.getSets():
                values = entity.getValues().toList()
                print(ampl_set(name, values), file=f)
            for name, entity in self.getParameters():
                if entity.isScalar():
                    print(
                        'param {} := {};'.format(name, entity.value()),
                        file=f
                    )
                else:
                    values = entity.getValues().toDict()
                    print(ampl_param(name, values), file=f)
506522
def dump(props, output):
    
    def escape(token):
      return re.sub(r'([=:\s])', r'\\\1', token)

    def write(out):
      for k, v in props.items():
        out.write('%s=%s\n' % (escape(str(k)), escape(str(v))))

    if hasattr(output, 'write') and callable(output.write):
      write(output)
    elif isinstance(output, six.string_types):
      with open(output, 'w+') as out:
        write(out)
    else:
      raise TypeError('Can only dump data to a path or a writable object, given: %s' % output)