Export epochwise annotations to csv file.

        Parameters
        ----------
        file_to_export : path to file
            file to write to
505517
def export(self, file_to_export, xformat='csv'):
        
        if 'csv' == xformat:
        
            with open(file_to_export, 'w', newline='') as f:
                csv_file = writer(f)
                csv_file.writerow(['Wonambi v{}'.format(__version__)])
                csv_file.writerow(('clock start time', 'start', 'end',
                                   'stage'))
    
                for epoch in self.epochs:
                    epoch_time = (self.start_time +
                                  timedelta(seconds=epoch['start']))
                    csv_file.writerow((epoch_time.strftime('%H:%M:%S'),
                                       epoch['start'],
                                       epoch['end'],
                                       epoch['stage']))
                    
        if 'remlogic' in xformat:
            
            columns = 'Time [hh:mm:ss]\tEvent\tDuration[s]\n'
            if 'remlogic_fr' == xformat:
                columns = 'Heure [hh:mm:ss]\tEvénement\tDurée[s]\n'
                
            patient_id = splitext(basename(self.dataset))[0]
            rec_date = self.start_time.strftime('%d/%m/%Y')
            stkey = {v:k for k, v in REMLOGIC_STAGE_KEY.items()}
            stkey['Artefact'] = 'SLEEP-UNSCORED'
            stkey['Unknown'] = 'SLEEP-UNSCORED'
            stkey['Movement'] = 'SLEEP-UNSCORED'
            
            with open(file_to_export, 'w') as f:
                f.write('RemLogic Event Export\n')
                f.write('Patient:\t' + patient_id + '\n')
                f.write('Patient ID:\t' + patient_id + '\n')
                f.write('Recording Date:\t' + rec_date + '\n')
                f.write('\n')
                f.write('Events Included:\n')
                
                for i in sorted(set([stkey[x['stage']] for x in self.epochs])):
                    f.write(i + '\n')
                
                f.write('\n')
                f.write(columns)
                
                for epoch in self.epochs:
                    epoch_time = (self.start_time +
                                  timedelta(seconds=epoch['start']))
                    f.write((epoch_time.strftime('%Y-%m-%dT%H:%M:%S.000000') + 
                             '\t' + 
                             stkey[epoch['stage']] + 
                             '\t' + 
                             str(self.epoch_length) + 
                             '\n'))
636213
def to_file(file_):
        
        from sevenbridges.models.file import File
        if not file_:
            raise SbgError('File is required!')
        elif isinstance(file_, File):
            return file_.id
        elif isinstance(file_, six.string_types):
            return file_
        else:
            raise SbgError('Invalid file parameter!')
15926
def to_file(self, path, mode="w"):
        
        with open(path, mode=mode) as f:
            for tree in self:
                for label, line in tree.to_labeled_lines():
                    f.write(line + "\n")
1303662
def save_to_file!(file)
      data = {}
      data['networks']     = Network.serialize_all     @conf[:networks], @conf
      data['integrations'] = Integration.serialize_all @conf[:integrations],
                                                       @conf
      File.write file, Psych.dump(data)
    end
1281453
def exporter(directory, method, datasets):
    """"""
    if method.lower() == 'json':
        # Convert json_dict to a JSON styled string
        json_string = json.dumps(datasets, indent=4)
        savefile = open('{}/exported.json'.format(directory), 'w+')
        savefile.write(json_string)
        savefile.close()

    if method.lower() == 'csv':
        with open('{}/exported.csv'.format(directory), 'w+') as csvfile:
            csv_writer = csv.writer(
                csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
            for key, values in datasets.items():
                if values is None:
                    csv_writer.writerow([key])
                else:
                    csv_writer.writerow([key] + values)
        csvfile.close()
1364059
def export_file(self, data_object, destination_directory=None,
                    destination_filename=None, retry=False,
                    export_metadata=False, export_raw_file=True):
        
        if not destination_directory:
            destination_directory = os.getcwd()

        # We get filename from the dataobject
        if not destination_filename:
            destination_filename = data_object['value']['filename']

        destination_file_url = os.path.join(destination_directory,
                                            destination_filename)

        logger.info('Exporting file %s@%s ...' % (
            data_object['value']['filename'],
            data_object['uuid']))

        if export_raw_file:
            destination = File(
                destination_file_url, self.storage_settings, retry=retry)
            if destination.exists():
                raise FileAlreadyExistsError(
                    'File already exists at %s' % destination_file_url)
            logger.info('...copying file to %s' % (
                destination.get_url()))

            # Copy from the first file location
            file_resource = data_object.get('value')
            md5 = file_resource.get('md5')
            source_url = data_object['value']['file_url']
            File(source_url, self.storage_settings, retry=retry).copy_to(
                destination, expected_md5=md5)
            data_object['value'] = self._create_new_file_resource(
                data_object['value'], destination.get_url())
        else:
            logger.info('...skipping raw file')

        if export_metadata:
            data_object['value'].pop('link', None)
            data_object['value'].pop('upload_status', None)
            destination_metadata_url = os.path.join(
                destination_file_url + '.metadata.yaml')
            logger.info('...writing metadata to %s' % destination_metadata_url)
            metadata = yaml.safe_dump(data_object, default_flow_style=False)
            metadata_file = File(destination_metadata_url,
                                 self.storage_settings, retry=retry)
            metadata_file.write(metadata)
        else:
            logger.info('...skipping metadata')

        logger.info('...finished file export')
924072
def wr_ann_file(self, write_fs, write_dir=''):
        

        # Calculate the fs bytes to write if present and desired to write
        if write_fs:
            fs_bytes = self.calc_fs_bytes()
        else:
            fs_bytes = []
        # Calculate the custom_labels bytes to write if present
        cl_bytes = self.calc_cl_bytes()
        # Calculate the core field bytes to write
        core_bytes = self.calc_core_bytes()

        # Mark the end of the special annotation types if needed
        if fs_bytes == [] and cl_bytes == []:
            end_special_bytes = []
        else:
            end_special_bytes = [0, 236, 255, 255, 255, 255, 1, 0]

        # Write the file
        with open(os.path.join(write_dir, self.record_name+'.'+self.extension),
                  'wb') as f:
            # Combine all bytes to write: fs (if any), custom annotations (if any), main content, file terminator
            np.concatenate((fs_bytes, cl_bytes, end_special_bytes, core_bytes,
                            np.array([0,0]))).astype('u1').tofile(f)

        return
681253
def save(self):
        
        l = []
        h = {}
        s = {}
        h_r = {}

        idx = 0
        for i in self.map_list.get_obj():
            length = 0

            if isinstance(i, list):
                for j in i:
                    if isinstance(j, AnnotationsDirectoryItem):
                        if idx % 4 != 0:
                            idx = idx + (4 - (idx % 4))

                    l.append(j)

                    c_length = j.get_length()
                    if isinstance(j, StringDataItem):
                        c_length += 1
                    h[j] = idx + length
                    h_r[idx + length] = j
                    s[idx + length] = c_length

                    length += c_length
                    #debug("SAVE" + str(j) + " @ 0x%x" % (idx+length))

                debug("SAVE " + str(i[0]) + " @0x%x (%x)" % (idx, length))

            else:
                if isinstance(i, MapList):
                    if idx % 4 != 0:
                        idx = idx + (4 - (idx % 4))

                l.append(i)
                h[i] = idx
                h_r[idx] = i

                length = i.get_length()

                s[idx] = length

                debug("SAVE " + str(i) + " @0x%x (%x)" % (idx, length))

            idx += length

        self.header.file_size = idx

        for i in l:
            idx = h[i]
            i.set_off(idx)
            if isinstance(i, CodeItem):
                last_idx = idx
                for j in i.get_obj():
                    j.set_off(last_idx)
                    #j.set_debug_info_off(0)
                    last_idx += j.get_size()

        last_idx = 0
        buff = ""
        for i in l:
            idx = h[i]

            if idx != last_idx:
                debug("Adjust alignment @%x with 00 %x" % (idx, idx - last_idx))
                buff += "\x00" * (idx - last_idx)

            buff += i.get_raw()
            if isinstance(i, StringDataItem):
                buff += "\x00"
            last_idx = idx + s[idx]

        debug("GLOBAL SIZE %d" % len(buff))

        return self.fix_checksums(buff)
1285418
def write_to_files_rec(instances, tokenizer, max_seq_length,
                       max_predictions_per_seq, output_files):
    """"""
    writers = []
    for output_file in output_files:
        writers.append(
            mx.recordio.MXIndexedRecordIO(
                os.path.splitext(output_file)[0] + '.idx', output_file, 'w'))

    writer_index = 0
    total_written = 0
    for (inst_index, instance) in enumerate(instances):
        features = transform(instance, tokenizer, max_seq_length, max_predictions_per_seq)
        example = features

        writers[writer_index].write_idx(inst_index, json.dumps(example).encode('UTF-8'))
        writer_index = (writer_index + 1) % len(writers)
        total_written += 1

    for writer in writers:
        writer.close()

    logging.info('Wrote %d total instances', total_written)
198388
def export_txt(cls, feed):
        ''''''
        objects = cls.objects.in_feed(feed)

        # If no records, return None
        if not objects.exists():
            return

        # Get the columns used in the dataset
        column_map = objects.populated_column_map()
        columns, fields = zip(*column_map)
        extra_columns = feed.meta.get(
            'extra_columns', {}).get(cls.__name__, [])

        # Get sort order
        if hasattr(cls, '_sort_order'):
            sort_fields = cls._sort_order
        else:
            sort_fields = []
            for field in fields:
                base_field = field.split('__', 1)[0]
                point_match = re_point.match(base_field)
                if point_match:
                    continue
                field_type = cls._meta.get_field(base_field)
                assert not isinstance(field_type, ManyToManyField)
                sort_fields.append(field)

        # Create CSV writer
        out = StringIO()
        csv_writer = writer(out, lineterminator='\n')

        # Write header row
        header_row = [text_type(c) for c in columns]
        header_row.extend(extra_columns)
        write_text_rows(csv_writer, [header_row])

        # Report the work to be done
        total = objects.count()
        logger.info(
            '%d %s to export...',
            total, cls._meta.verbose_name_plural)

        # Populate related items cache
        model_to_field_name = {}
        cache = {}
        for field_name in fields:
            if '__' in field_name:
                local_field_name, subfield_name = field_name.split('__', 1)
                field = cls._meta.get_field(local_field_name)
                field_type = field.related_model
                model_name = field_type.__name__
                if model_name in model_to_field_name:
                    # Already loaded this model under a different field name
                    cache[field_name] = cache[model_to_field_name[model_name]]
                else:
                    # Load all feed data for this model
                    pairs = field_type.objects.in_feed(
                        feed).values_list('id', subfield_name)
                    cache[field_name] = dict(
                        (i, text_type(x)) for i, x in pairs)
                    cache[field_name][None] = u''
                    model_to_field_name[model_name] = field_name

        # Assemble the rows, writing when we hit batch size
        count = 0
        rows = []
        for item in objects.order_by(*sort_fields).iterator():
            row = []
            for csv_name, field_name in column_map:
                obj = item
                point_match = re_point.match(field_name)
                if '__' in field_name:
                    # Return relations from cache
                    local_field_name = field_name.split('__', 1)[0]
                    field_id = getattr(obj, local_field_name + '_id')
                    row.append(cache[field_name][field_id])
                elif point_match:
                    # Get the lat or long from the point
                    name, index = point_match.groups()
                    field = getattr(obj, name)
                    row.append(field.coords[int(index)])
                else:
                    # Handle other field types
                    field = getattr(obj, field_name) if obj else ''
                    if isinstance(field, date):
                        formatted = field.strftime(u'%Y%m%d')
                        row.append(text_type(formatted))
                    elif isinstance(field, bool):
                        row.append(1 if field else 0)
                    elif field is None:
                        row.append(u'')
                    else:
                        row.append(text_type(field))
            for col in extra_columns:
                row.append(obj.extra_data.get(col, u''))
            rows.append(row)
            if len(rows) % batch_size == 0:  # pragma: no cover
                write_text_rows(csv_writer, rows)
                count += len(rows)
                logger.info(
                    "Exported %d %s",
                    count, cls._meta.verbose_name_plural)
                rows = []

        # Write rows smaller than batch size
        write_text_rows(csv_writer, rows)
        return out.getvalue()
636492
def to_csv(self, file: str, opts: dict = None) -> str:
        
        opts = opts if opts is not None else {}
        ll = self._is_valid()
        if ll:
            if not self.sas.batch:
                print(ll['LOG'])
            else:
                return ll
        else:
            return self.sas.write_csv(file, self.table, self.libref, self.dsopts, opts)
806698
def _export(self, path, variables_saver):
    
    self._saved_model_handler.export(path, variables_saver=variables_saver)

    module_def_proto = module_def_pb2.ModuleDef()
    module_def_proto.format = module_def_pb2.ModuleDef.FORMAT_V3
    module_def_filename = get_module_proto_path(path)
    tf_utils.atomic_write_string_to_file(
        module_def_filename,
        module_def_proto.SerializeToString(),
        overwrite=False)
    logging.info("Exported TF-Hub module to: %s", path)
234951
def save_graph_to_file(graph_file_name, module_spec, class_count):
  """"""
  sess, _, _, _, _, _ = build_eval_session(module_spec, class_count)
  graph = sess.graph

  output_graph_def = tf.graph_util.convert_variables_to_constants(
      sess, graph.as_graph_def(), [FLAGS.final_tensor_name])

  with tf.gfile.GFile(graph_file_name, 'wb') as f:
    f.write(output_graph_def.SerializeToString())
142407
def to_file(output_file, encoder=EliotJSONEncoder):
    
    Logger._destinations.add(
        FileDestination(file=output_file, encoder=encoder)
    )
944771
def serialize_yaml_tofile(filename, resource):
    
    stream = file(filename, "w")
    yaml.dump(resource, stream, default_flow_style=False)
21452
def write_model_to_file(self, mdl, fn):
        
        # Write the model to file
        output = ''.join(self.post_process_model(mdl, self.add_line_refs))
        if fn:
            fqfn = self.dst_dir + '/' + fn
            if os.path.isfile(fqfn):
                self.error("File '%s' exists" % fqfn)
                return
            with open(fqfn, 'w') as of:
                of.write(output)
                of.close()
                self.extracted_models.append(fn)
        else:
            self.error("Output file name can not be determined; YANG file not created")
293297
def export_graph(checkpoint_path, output_nodes):
    
    if not tf.gfile.Exists(checkpoint_path):
        raise AssertionError(
            "Export directory doesn't exists. Please specify an export "
            "directory: %s" % checkpoint_path)

    if not output_nodes:
        print("You need to supply the name of a node to --output_node_names.")
        return -1

        # We retrieve our checkpoint fullpath
    checkpoint = tf.train.get_checkpoint_state(checkpoint_path)
    input_checkpoint = checkpoint.model_checkpoint_path

    # We precise the file fullname of our freezed graph
    output_graph = checkpoint_path + "/frozen_model.pb"

    # We clear devices to allow TensorFlow to control on which device it will load operations
    clear_devices = True

    # We start a session using a temporary fresh Graph
    with tf.Session(graph=tf.Graph()) as sess:
        # We import the meta graph in the current default Graph
        saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices)

        # We restore the weights
        saver.restore(sess, input_checkpoint)

        # We use a built-in TF helper to export variables to constants
        output_graph_def = tf.graph_util.convert_variables_to_constants(
            sess,  # The session is used to retrieve the weights
            tf.get_default_graph().as_graph_def(),  # The graph_def is used to retrieve the nodes
            output_nodes  # The output node names are used to select the useful nodes
        )

        # Finally we serialize and dump the output graph to the filesystem
        with tf.gfile.GFile(output_graph, "wb") as f:
            f.write(output_graph_def.SerializeToString())
        print("%d ops in the final graph." % len(output_graph_def.node))

    return output_graph_def