Export a given dataset to a `CSV` file.

        This method is a slot connected to the `export` QAction. See the
        :meth:`addEntry` method for details.
166941
def plot(self):
        
        # The PyTables node tied to the current leaf of the databases tree
        current = self.vtgui.dbs_tree_view.currentIndex()
        leaf = self.vtgui.dbs_tree_model.nodeFromIndex(current).node

        data_name = leaf.name

        hists_1d = ['HistRelBcid', 'HistErrorCounter', 'HistTriggerErrorCounter', 'HistServiceRecord', 'HistTot', 'HistTdc', 'HistClusterTot', 'HistClusterSize']
        hists_2d = ['HistOcc', 'Enable', 'Imon', 'C_High', 'EnableDigInj', 'C_Low', 'FDAC', 'TDAC', 'HistTdcPixel', 'HistTotPixel', 'HistThreshold', 'HistNoise', 'HistThresholdFitted', 'HistNoiseFitted', 'HistThresholdFittedCalib', 'HistNoiseFittedCalib']

        if data_name in hists_1d:
            plot_1d_hist(hist=leaf[:], title=data_name)
        elif data_name in hists_2d:
            if data_name == 'HistOcc':
                leaf = np.sum(leaf[:], axis=2)
            plot_2d_hist(hist=leaf[:], title=data_name)
        elif 'Table' in str(type(leaf)) and len(leaf[:].dtype.names) <= 3:  # detect tables with less than 4 columns
            plot_table(leaf[:], title=data_name)
        elif data_name == 'HitOrCalibration':
            print 'Comming soon'
        else:
            print 'Plotting', data_name, '(%s) is not supported!' % type(leaf)
582927
def write_to_csv(file_name, mode = "w")
      File.open(file_name, mode) do |file|
        all.copy_csv(file)
      end
    end
1125385
def insertDataset(self, dataset):
        
        try:
            models.Dataset.create(
                id=dataset.getId(),
                name=dataset.getLocalId(),
                description=dataset.getDescription(),
                attributes=json.dumps(dataset.getAttributes()))
        except Exception:
            raise exceptions.DuplicateNameException(
                dataset.getLocalId())
803897
def export(self, storage_client, overwrite=True):
    
        '''
            
        '''
        
        title = '%s.export' % self.__class__.__name__
        
    # validate storage client
        method_list = [ 'save', 'load', 'list', 'export', 'delete', 'remove', '_import', 'collection_name' ]
        for method in method_list:
            if not getattr(storage_client, method, None):
                from labpack.parsing.grammar import join_words
                raise ValueError('%s(storage_client=...) must be a client object with %s methods.' % (title, join_words(method_list)))
    
    # define copy record function
        def _copy_record(_record, _storage_client):
            record_key = _record['key']
            record_data, record_metadata = self.s3.read_record(self.bucket_name, record_key)
            encryption = ''
            if 'encryption' in record_metadata['metadata'].keys():
                encryption = record_metadata['metadata']['encryption']
            last_modified = 0.0
            if 'last_modified' in record_metadata['metadata'].keys():
                try:
                    last_modified = float(record_metadata['metadata']['last_modified'])
                except:
                    pass
            outcome = _storage_client._import(record_key, record_data, overwrite=overwrite, encryption=encryption, last_modified=last_modified)
            return outcome
            
    # retrieve list of records in bucket
        count = 0
        skipped = 0
        record_list, next_key = self.s3.list_records(self.bucket_name)
        for record in record_list:
            outcome = _copy_record(record, storage_client)
            if outcome:
                count += 1
            else:
                skipped += 1
        
    # continue through bucket
        if next_key:
            while next_key:
                record_list, next_key = self.s3.list_records(self.bucket_name, starting_key=next_key)
                for record in record_list:
                    outcome = _copy_record(record, storage_client)
                    if outcome:
                        count += 1
                    else:
                        skipped += 1
    
    # report outcome
        from os import path
        plural = ''
        skip_insert = ''
        new_root, new_folder = path.split(storage_client.collection_folder)
        if count != 1:
            plural = 's'
        if skipped > 0:
            skip_plural = ''
            if skipped > 1:
                skip_plural = 's'
            skip_insert = ' %s record%s skipped to avoid overwrite.' % (str(skipped), skip_plural)
        exit_msg = '%s record%s exported to %s.%s' % (str(count), plural, new_folder, skip_insert)
        return exit_msg
429458
def save_dataset(self, out_file_name):
        

        for time_tag, script in self.data_sets.items():
            script.save(os.path.join(out_file_name, '{:s}.b26s'.format(time_tag)))
587463
def write_data_set(file_path, dataset, output_dir, color_array_info, new_name=None, compress=True):
    """"""
    fileName = new_name if new_name else os.path.basename(file_path)
    dataset_dir = os.path.join(output_dir, fileName)
    data_dir = os.path.join(dataset_dir, 'data')

    if not os.path.exists(data_dir):
        os.makedirs(data_dir)

    root = {}
    root['metadata'] = {}
    root['metadata']['name'] = fileName

    writer = writer_mapping[dataset.GetClassName()]
    if writer:
        writer(dataset_dir, data_dir, dataset, color_array_info, root, compress)
    else:
        print(dataObject.GetClassName(), 'is not supported')

    with open(os.path.join(dataset_dir, "index.json"), 'w') as f:
        f.write(json.dumps(root, indent=2))

    return dataset_dir
901132
def make_csv(data):
    
    # Convert sub-dicts to news cols
    for entry in data:
        rval = entry
        if isinstance(data, dict):
            rval = data[entry]
        todel = []
        toadd = {}
        for key, val in rval.items():
            if isinstance(val, dict):
                for key2, val2 in val.items():
                    toadd[str(key) + "[" + str(key2) + "]"] = val2
                todel.append(key)
        for k in todel:
            del rval[k]
        for k, v in toadd.items():
            rval[k] = v

    # Convert everything to CSV
    columns = set()
    output = [[]]
    if isinstance(data, dict):
        output[0].append("id")
        for entry in data:
            for col in data[entry]:
                columns.add(col)
    else:
        for entry in data:
            for col in entry:
                columns.add(col)

    columns = sorted(columns)

    for col in columns:
        output[0].append(col)

    if isinstance(data, dict):
        for entry in data:
            new_output = [str(entry)]
            for col in columns:
                new_output.append(str(data[entry][col]) if col in data[entry] else "")
            output.append(new_output)
    else:
        for entry in data:
            new_output = []
            for col in columns:
                new_output.append(str(entry[col]) if col in entry else "")
            output.append(new_output)

    csv_string = io.StringIO()
    csv_writer = UnicodeWriter(csv_string)
    for row in output:
        csv_writer.writerow(row)
    csv_string.seek(0)
    web.header('Content-Type', 'text/csv; charset=utf-8')
    web.header('Content-disposition', 'attachment; filename=export.csv')
    return csv_string.read()
598012
public void exportFromResultSet(Connection connection, ResultSet res, File fileName, ProgressVisitor progress, String encoding) throws SQLException {
        Csv csv = new Csv();
        String csvOptions = "charset=UTF-8 fieldSeparator=\t fieldDelimiter=\t";
        if (encoding != null) {
            csvOptions = String.format("charset=%s fieldSeparator=\t fieldDelimiter=\t", encoding);
        }
        csv.setOptions(csvOptions);
        csv.write(fileName.getPath(), res, null);
    }
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)
760096
private void exportToCsv(File exportFile) {
        FileWriter fileWriter = null;
        exportStatus=true;
        try {
            fileWriter = new FileWriter(exportFile);
            CSVWriter writer = new CSVWriter(fileWriter);
            List<Marker> markers = datastore.getBookmarksAsMarkers(getmMapView());
            String[] headers = new String[] {"Latitude","Longitude","Description","Title"};
            writer.writeNext(headers);
            for (Marker m: markers) {
                String[] items = new String[4];
                items[0] = m.getPosition().getLatitude()+"";
                items[1] = m.getPosition().getLongitude()+"";
                items[2] = m.getSubDescription();
                items[3] = m.getTitle();
                writer.writeNext(items);
            }
        }catch (Exception ex) {
            exportStatus=false;
            ex.printStackTrace();
        } finally {
            if (fileWriter!=null)
                try {
                    fileWriter.close();
                }catch (Exception ex) {}
        }
        final Activity act = getActivity();
        if (act!=null) {
            act.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (exportStatus) {
                        Toast.makeText(act, "Export Complete", Toast.LENGTH_LONG).show();
                    } else
                        Toast.makeText(act, "Export Failed", Toast.LENGTH_LONG).show();
                }
            });
        }
    }
1286915
def addDataset(self, dataset):
        
        id_ = dataset.getId()
        self._datasetIdMap[id_] = dataset
        self._datasetNameMap[dataset.getLocalId()] = dataset
        self._datasetIds.append(id_)
1269539
def export(self, filename, offset=0, length=None):
        
        self.__validate_offset(filename=filename, offset=offset, length=length)

        with open(filename, 'w') as f:
            if length is None:
                length = len(self.data) - offset

            if offset > 0:
                output = self.data[offset:length]
            else:
                output = self.data[:length]

            f.write(output)
668838
def save_dataset(self, dataset, filename=None, fill_value=None, **kwargs):
        """"""
        return self.save_datasets([dataset], filename, **kwargs)
414881
def csv(self, client_id):
        """"""
        logging.info('Exporting CSV file [{}]'.format(client_id))
        query = (
            db.session.query(Query)
            .filter_by(client_id=client_id)
            .one()
        )

        rejected_tables = security_manager.rejected_datasources(
            query.sql, query.database, query.schema)
        if rejected_tables:
            flash(
                security_manager.get_table_access_error_msg('{}'.format(rejected_tables)))
            return redirect('/')
        blob = None
        if results_backend and query.results_key:
            logging.info(
                'Fetching CSV from results backend '
                '[{}]'.format(query.results_key))
            blob = results_backend.get(query.results_key)
        if blob:
            logging.info('Decompressing')
            json_payload = utils.zlib_decompress_to_string(blob)
            obj = json.loads(json_payload)
            columns = [c['name'] for c in obj['columns']]
            df = pd.DataFrame.from_records(obj['data'], columns=columns)
            logging.info('Using pandas to convert to CSV')
            csv = df.to_csv(index=False, **config.get('CSV_EXPORT'))
        else:
            logging.info('Running a query to turn into CSV')
            sql = query.select_sql or query.executed_sql
            df = query.database.get_df(sql, query.schema)
            # TODO(bkyryliuk): add compression=gzip for big files.
            csv = df.to_csv(index=False, **config.get('CSV_EXPORT'))
        response = Response(csv, mimetype='text/csv')
        response.headers['Content-Disposition'] = f'attachment; filename={query.name}.csv'
        logging.info('Ready to return response')
        return response
1088696
def save_dataset(self, dataset_id, filename=None, writer=None, overlay=None, compute=True, **kwargs):
        """"""
        if writer is None and filename is None:
            writer = 'geotiff'
        elif writer is None:
            writer = self.get_writer_by_ext(os.path.splitext(filename)[1])

        writer, save_kwargs = load_writer(writer,
                                          ppp_config_dir=self.ppp_config_dir,
                                          filename=filename,
                                          **kwargs)
        return writer.save_dataset(self[dataset_id],
                                   overlay=overlay, compute=compute,
                                   **save_kwargs)
1121266
def export_by_tag_csv(ekey, dstore):
    
    token, tag = ekey[0].split('/')
    data = extract(dstore, token + '/' + tag)
    fnames = []
    writer = writers.CsvWriter(fmt=writers.FIVEDIGITS)
    for stat, arr in data:
        tup = (ekey[0].replace('/', '-'), stat, ekey[1])
        path = '%s-%s.%s' % tup
        fname = dstore.export_path(path)
        writer.save(arr, fname)
        fnames.append(fname)
    return fnames
777521
def export_admin_action(self, request, queryset):
        
        export_format = request.POST.get('file_format')

        if not export_format:
            messages.warning(request, _('You must select an export format.'))
        else:
            formats = self.get_export_formats()
            file_format = formats[int(export_format)]()

            export_data = self.get_export_data(file_format, queryset, request=request)
            content_type = file_format.get_content_type()
            response = HttpResponse(export_data, content_type=content_type)
            response['Content-Disposition'] = 'attachment; filename=%s' % (
                self.get_export_filename(file_format),
            )
            return response