Write acceptance_fraction data to file. Results are written to
        the ``[sampler_group]/acceptance_fraction``.

        Parameters
        -----------
        acceptance_fraction : numpy.ndarray
            Array of acceptance fractions to write.
772639
def write_acceptance_fraction(self, acceptance_fraction):
        
        group = self.sampler_group + '/acceptance_fraction'
        try:
            self[group][:] = acceptance_fraction
        except KeyError:
            # dataset doesn't exist yet, create it
            self[group] = acceptance_fraction
1314866
def write_to_files_np(features, tokenizer, max_seq_length,
                      max_predictions_per_seq, output_files):
    # pylint: disable=unused-argument
    """"""
    next_sentence_labels = []
    valid_lengths = []

    assert len(output_files) == 1, 'numpy format only support single output file'
    output_file = output_files[0]
    (input_ids, segment_ids, masked_lm_positions, masked_lm_ids,
     masked_lm_weights, next_sentence_labels, valid_lengths) = features
    total_written = len(next_sentence_labels)

    # store variable length numpy array object directly.
    outputs = collections.OrderedDict()
    outputs['input_ids'] = np.array(input_ids, dtype=object)
    outputs['segment_ids'] = np.array(segment_ids, dtype=object)
    outputs['masked_lm_positions'] = np.array(masked_lm_positions, dtype=object)
    outputs['masked_lm_ids'] = np.array(masked_lm_ids, dtype=object)
    outputs['masked_lm_weights'] = np.array(masked_lm_weights, dtype=object)
    outputs['next_sentence_labels'] = np.array(next_sentence_labels, dtype='int32')
    outputs['valid_lengths'] = np.array(valid_lengths, dtype='int32')

    np.savez_compressed(output_file, **outputs)
    logging.info('Wrote %d total instances', total_written)
187851
def write_ensemble(ensemble, options):
    

    # set output file name
    size = len(ensemble)
    filename = '%s_%s_queries.csv' % (options.outname, size)
    file = os.path.join(os.getcwd(), filename)

    f = open(file, 'w')

    out = ', '.join(ensemble)

    f.write(out)

    f.close()
517218
def write(self, timeunit, timepoints) -> None:
        """"""
        with netcdf4.Dataset(self.filepath, "w") as ncfile:
            ncfile.Conventions = 'CF-1.6'
            self._insert_timepoints(ncfile, timepoints, timeunit)
            for variable in self.variables.values():
                variable.write(ncfile)
1146256
def write(self, data):
    
    ctx = context.get()
    if len(data) != 2:
      logging.error("Got bad tuple of length %d (2-tuple expected): %s",
                    len(data), data)

    try:
      key = str(data[0])
      value = str(data[1])
    except TypeError:
      logging.error("Expecting a tuple, but got %s: %s",
                    data.__class__.__name__, data)

    file_index = key.__hash__() % len(self._filehandles)

    # Work-around: Since we don't have access to the context in the to_json()
    # function, but we need to flush each pool before we serialize the
    # filehandle, we rely on a member variable instead of using context for
    # pool management.
    pool = self._pools[file_index]
    if pool is None:
      filehandle = self._filehandles[file_index]
      pool = output_writers.GCSRecordsPool(filehandle=filehandle, ctx=ctx)
      self._pools[file_index] = pool

    proto = kv_pb.KeyValue()
    proto.set_key(key)
    proto.set_value(value)
    pool.append(proto.Encode())
379566
def _write_data(self, file):
        
        self.write_case_data(file)

        file.write("Bus Data\n")
        file.write("-" * 8 + "\n")
        self.write_bus_data(file)
        file.write("\n")

        file.write("Branch Data\n")
        file.write("-" * 11 + "\n")
        self.write_branch_data(file)
        file.write("\n")

        file.write("Generator Data\n")
        file.write("-" * 14 + "\n")
        self.write_generator_data(file)
        file.write("\n")
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))
528039
def sndwrite_like(samples:np.ndarray, likefile:str, outfile:str) -> None:
    
    info = sndinfo(likefile)
    sndwrite(samples, info.samplerate, outfile, encoding=info.encoding)
1106533
def _write_bin(self, data, stream, byte_order):
        '''
        

        '''
        _write_array(stream, _np.dtype(self.dtype(byte_order)).type(data))
1192832
def write_file(fname_parts, content):
    

    fname_parts = [str(part) for part in fname_parts]
    # try to create the directory
    if len(fname_parts) > 1:
        try:
            os.makedirs(os.path.join(*fname_parts[:-1]))
        except OSError:
            pass
    # write file
    fhandle = open(os.path.join(*fname_parts), "w")
    fhandle.write(content)
    fhandle.close()
1086617
def write_to(self, group):
        
        # The HDF5 group where to write data
        items_group = group[self.name]

        nitems = items_group.shape[0]
        items_group.resize((nitems + len(self.data),))
        items_group[nitems:] = self.data
381566
def write_file(self, file_name, vasp4_compatible=False):
        

        def _print_fortran_float(f):
            """
            Fortran codes print floats with a leading zero in scientific
            notation. When writing CHGCAR files, we adopt this convention
            to ensure written CHGCAR files are byte-to-byte identical to
            their input files as far as possible.
            :param f: float
            :return: str
            """
            s = "{:.10E}".format(f)
            if f >= 0:
                return "0." + s[0] + s[2:12] + 'E' + "{:+03}".format(int(s[13:]) + 1)
            else:
                return "-." + s[1] + s[3:13] + 'E' + "{:+03}".format(int(s[14:]) + 1)

        with zopen(file_name, "wt") as f:
            p = Poscar(self.structure)

            # use original name if it's been set (e.g. from Chgcar)
            comment = getattr(self, 'name', p.comment)

            lines = comment + "\n"
            lines += "   1.00000000000000\n"
            latt = self.structure.lattice.matrix
            lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[0, :])
            lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[1, :])
            lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[2, :])
            if not vasp4_compatible:
                lines += "".join(["%5s" % s for s in p.site_symbols]) + "\n"
            lines += "".join(["%6d" % x for x in p.natoms]) + "\n"
            lines += "Direct\n"
            for site in self.structure:
                lines += "%10.6f%10.6f%10.6f\n" % tuple(site.frac_coords)
            lines += " \n"
            f.write(lines)
            a = self.dim

            def write_spin(data_type):
                lines = []
                count = 0
                f.write("   {}   {}   {}\n".format(a[0], a[1], a[2]))
                for (k, j, i) in itertools.product(list(range(a[2])),
                                                   list(range(a[1])),
                                                   list(range(a[0]))):
                    lines.append(_print_fortran_float(self.data[data_type][i, j, k]))
                    count += 1
                    if count % 5 == 0:
                        f.write(" " + "".join(lines) + "\n")
                        lines = []
                    else:
                        lines.append(" ")
                f.write(" " + "".join(lines) + " \n")
                f.write("".join(self.data_aug.get(data_type, [])))

            write_spin("total")
            if self.is_spin_polarized and self.is_soc:
                write_spin("diff_x")
                write_spin("diff_y")
                write_spin("diff_z")
            elif self.is_spin_polarized:
                write_spin("diff")
1187507
def _prepare_sample_data(self, submission_type):
    
    # write images
    images = np.random.randint(0, 256,
                               size=[BATCH_SIZE, 299, 299, 3], dtype=np.uint8)
    for i in range(BATCH_SIZE):
      Image.fromarray(images[i, :, :, :]).save(
          os.path.join(self._sample_input_dir, IMAGE_NAME_PATTERN.format(i)))
    # write target class for targeted attacks
    if submission_type == 'targeted_attack':
      target_classes = np.random.randint(1, 1001, size=[BATCH_SIZE])
      target_class_filename = os.path.join(self._sample_input_dir,
                                           'target_class.csv')
      with open(target_class_filename, 'w') as f:
        for i in range(BATCH_SIZE):
          f.write((IMAGE_NAME_PATTERN + ',{1}\n').format(i, target_classes[i]))
576378
def write_output_files(self):
        
        os.mkdir("analysis")
        os.chdir("analysis")
        os.mkdir("hydrogen_bonds")
        os.chdir("hydrogen_bonds")
        for traj in range(len(self.trajectory)):
            with open('hbonds_data_total_'+str(traj)+'.csv', 'wb') as outfile:
                hwriter = csv.writer(outfile, delimiter=' ')
                for time in self.hbonds_by_time[traj]:
                    hwriter.writerow([time[0],time[1]])
            for bond in self.hbonds_by_type[traj]:
                if bond["donor_resnm"]=="LIG" and (bond["acceptor_idx"],bond["donor_idx"]) in [(k[0],k[3]) for k,v in self.hbonds_for_drawing.items()]:
                    with open('hbond_'+bond["acceptor_resnm"]+"_"+str(bond["acceptor_resid"])+"_"+bond["donor_atom"]+"_"+str(traj)+".csv","wb") as outfile:
                        hwriter = csv.writer(outfile, delimiter=' ')
                        for time in self.hbonds_timesteps[traj]:
                            result = [1 if x[0]==time and x["acceptor_idx"]==bond["acceptor_idx"] else 0 for x in self.hbonds[traj]][0]
                            hwriter.writerow([time,result])
                if bond["donor_resnm"]!="LIG" and (bond["donor_idx"],bond["acceptor_idx"]) in [(k[0],k[3]) for k,v in self.hbonds_for_drawing.items()]:
                    with open('hbond_'+bond["donor_resnm"]+"_"+str(bond["donor_resid"])+"_"+bond["acceptor_atom"]+"_"+str(traj)+".csv","wb") as outfile:
                        hwriter = csv.writer(outfile, delimiter=' ')
                        for time in self.hbonds_timesteps[traj]:
                            result = [1 if x[0]==time and x["donor_idx"]==bond["donor_idx"] else 0 for x in self.hbonds[traj]][0]
                            hwriter.writerow([time,result])
        os.chdir("../../")
1137668
def _writen(fd, data):
    """"""
    while data:
        n = os.write(fd, data)
        data = data[n:]
1297042
def write_files(self):
        
        warnings = self.validate_data()

        print('-I- Writing all saved data to files')
        if self.measurements:
            self.write_measurements_file()
        for dtype in ['specimen', 'sample', 'site']:
            if self.data_lists[dtype][0]:
                do_pmag = dtype in self.incl_pmag_data
                self.write_magic_file(dtype, do_er=True, do_pmag=do_pmag)
                if not do_pmag:
                    pmag_file = os.path.join(self.WD, 'pmag_' + dtype + 's.txt')
                    if os.path.isfile(pmag_file):
                        os.remove(pmag_file)

        if self.locations:
            self.write_magic_file('location', do_er=True, do_pmag=False)

        self.write_age_file()

        if self.results:
            self.write_result_file()

        if warnings:
            print('-W- ' + str(warnings))
            return False, warnings

        return True, None
122720
def _write_single_sample(self, sample):
        
        bytes = sample.extras.get("responseHeadersSize", 0) + 2 + sample.extras.get("responseBodySize", 0)

        message = sample.error_msg
        if not message:
            message = sample.extras.get("responseMessage")
        if not message:
            for sample in sample.subsamples:
                if sample.error_msg:
                    message = sample.error_msg
                    break
                elif sample.extras.get("responseMessage"):
                    message = sample.extras.get("responseMessage")
                    break
        self.writer.writerow({
            "timeStamp": int(1000 * sample.start_time),
            "elapsed": int(1000 * sample.duration),
            "Latency": 0,  # TODO
            "label": sample.test_case,

            "bytes": bytes,

            "responseCode": sample.extras.get("responseCode"),
            "responseMessage": message,
            "allThreads": self.concurrency,  # TODO: there will be a problem aggregating concurrency for rare samples
            "success": "true" if sample.status == "PASSED" else "false",
        })
        self.out_stream.flush()