Write all of the HostsEntry instances back to the hosts file
        :param path: override the write path
        :return: Dictionary containing counts
505474
def write(self, path=None):
        
        written_count = 0
        comments_written = 0
        blanks_written = 0
        ipv4_entries_written = 0
        ipv6_entries_written = 0
        if path:
            output_file_path = path
        else:
            output_file_path = self.hosts_path
        try:
            with open(output_file_path, 'w') as hosts_file:
                for written_count, line in enumerate(self.entries):
                    if line.entry_type == 'comment':
                        hosts_file.write(line.comment + "\n")
                        comments_written += 1
                    if line.entry_type == 'blank':
                        hosts_file.write("\n")
                        blanks_written += 1
                    if line.entry_type == 'ipv4':
                        hosts_file.write(
                            "{0}\t{1}\n".format(
                                line.address,
                                ' '.join(line.names),
                            )
                        )
                        ipv4_entries_written += 1
                    if line.entry_type == 'ipv6':
                        hosts_file.write(
                            "{0}\t{1}\n".format(
                                line.address,
                                ' '.join(line.names), ))
                        ipv6_entries_written += 1
        except:
            raise UnableToWriteHosts()
        return {'total_written': written_count + 1,
                'comments_written': comments_written,
                'blanks_written': blanks_written,
                'ipv4_entries_written': ipv4_entries_written,
                'ipv6_entries_written': ipv6_entries_written}
491466
def dump_by_server(self, hosts):
        
        dump_by_endpoint = {}

        for endpoint in self._to_endpoints(hosts):
            try:
                out = self.cmd([endpoint], "dump")
            except self.CmdFailed as ex:
                out = ""
            dump_by_endpoint[endpoint] = out

        return dump_by_endpoint
133537
def entries(path)
      if File.directory?(path)
        Dir.entries(path).reject { |entry| entry =~ /^\.|~$|^\#.*\#$/ }.sort
      else
        []
      end
    end
674349
def write(path):
    
    pid = os.getpid()
    logging.info("Writing PID %s to '%s'", pid, path)
    try:
        pidfile = open(path, 'wb')
        # get a non-blocking exclusive lock
        fcntl.flock(pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
        # clear out the file
        pidfile.seek(0)
        pidfile.truncate(0)
        # write the pid
        pidfile.write(str(pid))
    finally:
        try:
            pidfile.close()
        except:
            pass
827735
def WritePathHashHistory(self, client_path, hash_entries):
    
    client_path_history = ClientPathHistory()
    for timestamp, hash_entry in iteritems(hash_entries):
      client_path_history.AddHashEntry(timestamp, hash_entry)

    self.MultiWritePathHistory({client_path: client_path_history})
814909
function(path){
        var hosts = this.hosts,
            count = hosts.length;
        return hosts[parseInt(mod_md5(path),16) % count];
    }
640833
def write(entries):
    
    try:
        with open(get_rc_path(), 'w') as rc:
            rc.writelines(entries)
    except IOError:
        print('Error writing your ~/.vacationrc file!')
1172292
def writeCsv(self, path):
    
    self._createConfluence()
    with open(path, "w") as outputFile:
      writer = csv.writer(outputFile)
      headers = self.getStreamIds()
      fieldNames = ["timestamp"] + headers
      flags = ["T"] + ["" for h in headers]
      types = ["datetime"] + self._confluence.getDataTypes()
      writer.writerow(fieldNames)
      writer.writerow(types)
      writer.writerow(flags)
      for row in self._confluence:
        writer.writerow(row)
    print "Wrote CSV data to %s." % path
288714
def listdir(self, path):
        
        bucket, obj = self._path_to_bucket_and_key(path)

        obj_prefix = self._add_path_delimiter(obj)
        if self._is_root(obj_prefix):
            obj_prefix = ''

        obj_prefix_len = len(obj_prefix)
        for it in self._list_iter(bucket, obj_prefix):
            yield self._add_path_delimiter(path) + it['name'][obj_prefix_len:]
1008216
def path_entry(self, path):
        
        if path[0] != '/':
            return None
        path_parts = path.split('/')
        # Note that here the first element will be '' because it's before the
        # first separator.  That's OK, the join puts it back together.
        directory = '/'.join(path_parts[:-1])
        name = path_parts[-1]
        if directory not in self.listings:
            return None
        if name not in self.listings[directory]['entries']:
            return None
        return self.listings[directory]['entries'][name]
195833
def write(gmt, out_path):
    
    with open(out_path, 'w') as f:
        for _, each_dict in enumerate(gmt):
            f.write(each_dict[SET_IDENTIFIER_FIELD] + '\t')
            f.write(each_dict[SET_DESC_FIELD] + '\t')
            f.write('\t'.join([str(entry) for entry in each_dict[SET_MEMBERS_FIELD]]))
            f.write('\n')
1062866
def _recurse(self, path):
        '''
        
        '''
        files = {}
        empty_dirs = []
        try:
            sub_paths = os.listdir(path)
        except OSError as exc:
            if exc.errno == errno.ENOENT:
                # Path does not exist
                sys.stderr.write('{0} does not exist\n'.format(path))
                sys.exit(42)
            elif exc.errno in (errno.EINVAL, errno.ENOTDIR):
                # Path is a file (EINVAL on Windows, ENOTDIR otherwise)
                files[path] = self._mode(path)
        else:
            if not sub_paths:
                empty_dirs.append(path)
            for fn_ in sub_paths:
                files_, empty_dirs_ = self._recurse(os.path.join(path, fn_))
                files.update(files_)
                empty_dirs.extend(empty_dirs_)

        return files, empty_dirs
985633
def _MultiWritePathInfos(self, path_infos, connection=None):
    """"""
    query = ""

    path_info_count = 0
    path_info_values = []

    parent_path_info_count = 0
    parent_path_info_values = []

    has_stat_entries = False
    has_hash_entries = False

    for client_id, client_path_infos in iteritems(path_infos):
      for path_info in client_path_infos:
        path = mysql_utils.ComponentsToPath(path_info.components)

        path_info_values.append(db_utils.ClientIDToInt(client_id))
        path_info_values.append(int(path_info.path_type))
        path_info_values.append(path_info.GetPathID().AsBytes())
        path_info_values.append(path)
        path_info_values.append(bool(path_info.directory))
        path_info_values.append(len(path_info.components))

        if path_info.HasField("stat_entry"):
          path_info_values.append(path_info.stat_entry.SerializeToString())
          has_stat_entries = True
        else:
          path_info_values.append(None)
        if path_info.HasField("hash_entry"):
          path_info_values.append(path_info.hash_entry.SerializeToString())
          path_info_values.append(path_info.hash_entry.sha256.AsBytes())
          has_hash_entries = True
        else:
          path_info_values.append(None)
          path_info_values.append(None)

        path_info_count += 1

        # TODO(hanuszczak): Implement a trie in order to avoid inserting
        # duplicated records.
        for parent_path_info in path_info.GetAncestors():
          path = mysql_utils.ComponentsToPath(parent_path_info.components)

          parent_path_info_values.append(db_utils.ClientIDToInt(client_id))
          parent_path_info_values.append(int(parent_path_info.path_type))
          parent_path_info_values.append(parent_path_info.GetPathID().AsBytes())
          parent_path_info_values.append(path)
          parent_path_info_values.append(len(parent_path_info.components))

          parent_path_info_count += 1

    query += """
    CREATE TEMPORARY TABLE client_path_infos(
      client_id BIGINT UNSIGNED NOT NULL,
      path_type INT UNSIGNED NOT NULL,
      path_id BINARY(32) NOT NULL,
      path TEXT NOT NULL,
      directory BOOLEAN NOT NULL,
      depth INT NOT NULL,
      stat_entry MEDIUMBLOB NULL,
      hash_entry MEDIUMBLOB NULL,
      sha256 BINARY(32) NULL,
      timestamp TIMESTAMP(6) NOT NULL DEFAULT now(6)
    );"""

    if path_info_count > 0:
      query += """
      INSERT INTO client_path_infos(client_id, path_type, path_id,
                                    path, directory, depth,
                                    stat_entry, hash_entry, sha256)
      VALUES {};
      """.format(mysql_utils.Placeholders(num=9, values=path_info_count))

      query += """
      INSERT INTO client_paths(client_id, path_type, path_id, path,
                               directory, depth)
           SELECT client_id, path_type, path_id, path, directory, depth
             FROM client_path_infos
      ON DUPLICATE KEY UPDATE
        client_paths.directory = client_paths.directory OR VALUES(client_paths.directory),
        client_paths.timestamp = now(6);
      """

    if parent_path_info_count > 0:
      placeholders = ["(%s, %s, %s, %s, TRUE, %s)"] * parent_path_info_count

      query += """
      INSERT INTO client_paths(client_id, path_type, path_id, path,
                               directory, depth)
      VALUES {}
      ON DUPLICATE KEY UPDATE
        directory = TRUE,
        timestamp = now();
      """.format(", ".join(placeholders))

    if has_stat_entries:
      query += """
      INSERT INTO client_path_stat_entries(client_id, path_type, path_id,
                                           stat_entry, timestamp)
           SELECT client_id, path_type, path_id, stat_entry, timestamp
             FROM client_path_infos
            WHERE stat_entry IS NOT NULL;
      """

      query += """
      UPDATE client_paths, client_path_infos
         SET client_paths.last_stat_entry_timestamp = client_path_infos.timestamp
       WHERE client_paths.client_id = client_path_infos.client_id
         AND client_paths.path_type = client_path_infos.path_type
         AND client_paths.path_id = client_path_infos.path_id
         AND client_path_infos.stat_entry IS NOT NULL;
      """

    if has_hash_entries:
      query += """
      INSERT INTO client_path_hash_entries(client_id, path_type, path_id,
                                           hash_entry, sha256, timestamp)
           SELECT client_id, path_type, path_id, hash_entry, sha256, timestamp
             FROM client_path_infos
            WHERE hash_entry IS NOT NULL;
      """

      query += """
      UPDATE client_paths, client_path_infos
         SET client_paths.last_hash_entry_timestamp = client_path_infos.timestamp
       WHERE client_paths.client_id = client_path_infos.client_id
         AND client_paths.path_type = client_path_infos.path_type
         AND client_paths.path_id = client_path_infos.path_id
         AND client_path_infos.hash_entry IS NOT NULL;
      """

    try:
      with contextlib.closing(connection.cursor()) as cursor:
        cursor.execute(query, path_info_values + parent_path_info_values)
    finally:
      # Drop the temporary table in a separate cursor. This ensures that
      # even if the previous cursor.execute fails mid-way leaving the
      # temporary table created (as table creation can't be rolled back), the
      # table would still be correctly dropped.
      #
      # This is important since connections are reused in the MySQL connection
      # pool.
      with contextlib.closing(connection.cursor()) as cursor:
        cursor.execute("DROP TEMPORARY TABLE IF EXISTS client_path_infos")
54076
def write_installed_files(self, paths, prefix, dry_run=False):
        
        prefix = os.path.join(prefix, '')
        base = os.path.dirname(self.path)
        base_under_prefix = base.startswith(prefix)
        base = os.path.join(base, '')
        record_path = self.get_distinfo_file('RECORD')
        logger.info('creating %s', record_path)
        if dry_run:
            return None
        with CSVWriter(record_path) as writer:
            for path in paths:
                if os.path.isdir(path) or path.endswith(('.pyc', '.pyo')):
                    # do not put size and hash, as in PEP-376
                    hash_value = size = ''
                else:
                    size = '%d' % os.path.getsize(path)
                    with open(path, 'rb') as fp:
                        hash_value = self.get_hash(fp.read())
                if path.startswith(base) or (base_under_prefix and
                                             path.startswith(prefix)):
                    path = os.path.relpath(path, base)
                writer.writerow((path, hash_value, size))

            # add the RECORD file itself
            if record_path.startswith(base):
                record_path = os.path.relpath(record_path, base)
            writer.writerow((record_path, '', ''))
        return record_path
1003755
def write_dict_to_yaml(dictionary, path, **kwargs):
    
    with open(path, 'w') as f:
        yaml.dump(dictionary, f, indent=4, **kwargs)
851657
def write(self, path):
        """"""
        meta = {
            'generated_at': self.generated_at,
            'elapsed_time': self.elapsed_time,
        }
        sources = {}
        for result in self.results:
            unique_id = result.node.unique_id
            if result.error is not None:
                result_dict = {
                    'error': result.error,
                    'state': 'runtime error'
                }
            else:
                result_dict = {
                    'max_loaded_at': result.max_loaded_at,
                    'snapshotted_at': result.snapshotted_at,
                    'max_loaded_at_time_ago_in_s': result.age,
                    'state': result.status,
                    'criteria': result.node.freshness,
                }
            sources[unique_id] = result_dict
        output = FreshnessRunOutput(meta=meta, sources=sources)
        output.write(path)
583854
def write_to_file(self, file_path: str) -> None:
        
        data = self.encode()
        with open(file_path, "w") as f:
            json.dump(data, f, indent=1)