Export events to CSV
        
        Parameters
        ----------
        filename : str
            path of export file
        evt_type : list of str
            event types to export
168100
def export_events(self, filename, evt_type):
        
        filename = splitext(filename)[0] + '.csv'
        headings_row = ['Index',
                       'Start time',
                       'End time',
                       'Stitches',
                       'Stage',
                       'Cycle',
                       'Event type',
                       'Channel']
        
        events = []
        for et in evt_type:
            events.extend(self.get_events(name=et))
            
        events = sorted(events, key=lambda evt: evt['start'])
        
        if events is None:
            lg.info('No events found.')
            return
        
        with open(filename, 'w', newline='') as f:
            lg.info('Writing to ' + str(filename))
            csv_file = writer(f)
            csv_file.writerow(['Wonambi v{}'.format(__version__)])
            csv_file.writerow(headings_row)
            
            for i, ev in enumerate(events):
                csv_file.writerow([i + 1,
                                   ev['start'],
                                   ev['end'],
                                   0,
                                   ev['stage'],
                                   '',
                                   ev['name'],
                                   ', '.join(ev['chan']),
                                   ])
697672
def to_file(self, filename):
        
        filename = os.path.expanduser(filename)
        libfn = utils.get_lib_fn('toFile%s'%self._libsuffix)
        libfn(self.pointer, filename)
2940
def write_csv(file_name, records)
      line_number = exporter.connection_adapter.write(local_file(file_name), records)
    end
942868
def export_csv_action(description="Export selected objects as CSV file", fields=None, exclude=None, header=True):
    

    def export_as_csv(modeladmin, request, queryset):
        """Generic csv export admin action.

        based on http://djangosnippets.org/snippets/1697/

        """
        opts = modeladmin.model._meta
        field_names = set([field.name for field in opts.fields])
        if fields:
            fieldset = set(fields)
            field_names = field_names & fieldset
        elif exclude:
            excludeset = set(exclude)
            field_names = field_names - excludeset

        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename=%s.csv' % str(opts).replace('.', '_')

        writer = csv.writer(response)
        if header:
            writer.writerow(list(field_names))
        for obj in queryset:
            writer.writerow([str(getattr(obj, field)) for field in field_names])
        return response

    export_as_csv.short_description = description
    return export_as_csv
556786
def _get_content_type(self, filename):
        
        mntype = mimetypes.guess_type(filename)[0]
        filename, fileExtension = os.path.splitext(filename)
        if mntype is None and\
            fileExtension.lower() == ".csv":
            mntype = "text/csv"
        elif mntype is None and \
            fileExtension.lower() == ".sd":
            mntype = "File/sd"
        elif mntype is None:
            #mntype = 'application/octet-stream'
            mntype= "File/%s" % fileExtension.replace('.', '')
        return mntype
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!')
34543
def event_text(self, event):
        
        logger.debug("error text for %s" % hex(event.EvtCode))
        len_ = 1024
        text_type = ctypes.c_char * len_
        text = text_type()
        error = self.library.Srv_EventText(ctypes.byref(event),
                                           ctypes.byref(text), len_)
        check_error(error)
        if six.PY2:
            return text.value
        else:
            return text.value.decode('ascii')
507563
def ParseFileObject(self, parser_mediator, file_object):
    
    evt_file = pyevt.file()
    evt_file.set_ascii_codepage(parser_mediator.codepage)

    try:
      evt_file.open_file_object(file_object)
    except IOError as exception:
      parser_mediator.ProduceExtractionWarning(
          'unable to open file with error: {0!s}'.format(exception))
      return

    try:
      self._ParseRecords(parser_mediator, evt_file)
    finally:
      evt_file.close()
202067
def save_to_file(self, filename: str) -> ConfigFile:
        
        newclass = ConfigFile(fd=filename, load_hook=self.normal_class_hook[0],
                              dump_hook=self.normal_class_hook[1], safe_load=self.safe_load)
        return newclass
1264494
def WriteEventBody(self, event):
    
    output_values = []
    for field_name in self._fields:
      output_value = self._dynamic_fields_helper.GetFormattedField(
          event, field_name)

      output_value = self._SanitizeField(output_value)
      output_values.append(output_value)

    output_line = '{0:s}\n'.format(self._field_delimiter.join(output_values))
    self._output_writer.Write(output_line)
496017
def write_event(self, event):
    
    self._lock.acquire()
    try:
      self._events_writer.WriteEvent(event)
      self._event_count += 1
      if self._always_flush:
        # We flush on every event within the integration test.
        self._events_writer.Flush()

      if self._event_count == self._check_this_often:
        # Every so often, we check whether the size of the file is too big.
        self._event_count = 0

        # Flush to get an accurate size check.
        self._events_writer.Flush()

        file_path = os.path.join(self._events_directory,
                                 self.get_current_file_name())
        if not tf.io.gfile.exists(file_path):
          # The events file does not exist. Perhaps the user had manually
          # deleted it after training began. Create a new one.
          self._events_writer.Close()
          self._events_writer = self._create_events_writer(
              self._events_directory)
        elif tf.io.gfile.stat(file_path).length > self._single_file_size_cap_bytes:
          # The current events file has gotten too big. Close the previous
          # events writer. Make a new one.
          self._events_writer.Close()
          self._events_writer = self._create_events_writer(
              self._events_directory)
    except IOError as err:
      logger.error(
          "Writing to %s failed: %s", self.get_current_file_name(), err)
    self._lock.release()
1142585
def exportProfile(self, filename=''):
        
        if not (filename and isinstance(filename, basestring)):
            filename = QtGui.QFileDialog.getSaveFileName(self,
                                                         'Export Layout as...',
                                                         QtCore.QDir.currentPath(),
                                                         'XView (*.xview)')
            
            if type(filename) == tuple:
                filename = filename[0]
        
        filename = nativestring(filename)
        if not filename:
            return
        
        if not filename.endswith('.xview'):
            filename += '.xview'
        
        profile = self.saveProfile()
        profile.save(filename)
673652
def GenericPump(filenames, use_jppy=False, name="GenericPump", **kwargs):
    """"""
    if isinstance(filenames, str):
        filenames = [filenames]

    try:
        iter(filenames)
    except TypeError:
        log.critical("Don't know how to iterate through filenames.")
        raise TypeError("Invalid filenames.")

    extensions = set(os.path.splitext(fn)[1] for fn in filenames)

    if len(extensions) > 1:
        log.critical("Mixed filetypes, please use only files of the same type")
        raise IOError("Mixed filetypes.")

    extension = list(extensions)[0]

    io = {
        '.evt': EvtPump,
        '.h5': HDF5Pump,
        '.root': EventPump if use_jppy else AanetPump,
        '.dat': DAQPump,
        '.dqd': CLBPump,
    }

    if extension not in io:
        log.critical(
            "No pump found for file extension '{0}'".format(extension)
        )
        raise ValueError("Unknown filetype")

    missing_files = [fn for fn in filenames if not os.path.exists(fn)]
    if missing_files:
        if len(missing_files) == len(filenames):
            message = "None of the given files could be found."
            log.critical(message)
            raise SystemExit(message)
        else:
            log.warning(
                "The following files are missing and ignored: {}".format(
                    ', '.join(missing_files)
                )
            )

    input_files = set(filenames) - set(missing_files)

    if len(input_files) == 1:
        return io[extension](filename=filenames[0], name=name, **kwargs)
    else:
        return io[extension](filenames=filenames, name=name, **kwargs)
804569
def export(self, filename, exporter=None):
        
        filename = nativestring(filename)
        if exporter is None:
            ext = os.path.splitext(filename)[1]
            exporter = self.exporter(ext)
        
        if exporter:
            return exporter.exportTree(self, filename)
        else:
            return False
357846
private boolean isFileType(WatchEvent event, String fileType) {
        return event.context().toString().contains(fileType);
    }
931726
def _ExportEvent(self, output_module, event, deduplicate_events=True):
    
    if event.timestamp != self._export_event_timestamp:
      self._FlushExportBuffer(
          output_module, deduplicate_events=deduplicate_events)
      self._export_event_timestamp = event.timestamp

    self._export_event_heap.PushEvent(event)
477433
def _export_csv(self, filepath, data, preview_data):
        

        # Get csv info

        csv_info = \
            self.main_window.interfaces.get_csv_export_info(preview_data)

        if csv_info is None:
            return

        try:
            dialect, digest_types, has_header = csv_info
        except TypeError:
            return

        # Export CSV file

        csv_interface = CsvInterface(self.main_window, filepath, dialect,
                                     digest_types, has_header)

        try:
            csv_interface.write(data)

        except IOError, err:
            msg = _("The file {filepath} could not be fully written\n \n"
                    "Error message:\n{msg}")
            msg = msg.format(filepath=filepath, msg=err)
            short_msg = _('Error writing CSV file')
            self.main_window.interfaces.display_warning(msg, short_msg)