Create rows in Exercises.csv and ExerciseQuestions.csv from a Studio channel,
        specified based on a studio_id (e.g. studio_id of main_tree for some channel)'
509768
def generate_exercises_from_importstudioid(self, args, options):
        
        print('Generating Exercises.csv and ExerciseQuestions.csv from a Studio channel')
        self.studioapi = StudioApi(token=args['token'])
        channel_dict = self.studioapi.get_tree_for_studio_id(args['importstudioid'])
        json.dump(channel_dict, open('chefdata/studiotree.json', 'w'), indent=4, ensure_ascii=False, sort_keys=True)

        soure_ids_seen = []
        def _generate_source_id(subtree):
            """
            Creates a Source ID form title and ensures it is unique withing channel.
            """
            candidate = subtree['title'].replace(' ', '_')
            if candidate not in soure_ids_seen:
                source_id = candidate
                soure_ids_seen.append(source_id)
            else:
                source_id = candidate + subtree['node_id'][0:7]
                soure_ids_seen.append(source_id)
            return source_id

        def _write_subtree(path_tuple, subtree, is_root=False):
            print('    '*len(path_tuple) + '  - ', subtree['title'])
            kind = subtree['kind']

            # TOPIC ############################################################
            if kind == 'topic':

                if is_root:
                    self.write_topic_row_from_studio_dict(path_tuple, subtree, is_root=is_root)
                    for child in subtree['children']:
                        _write_subtree(path_tuple, child)
                else:
                    self.write_topic_row_from_studio_dict(path_tuple, subtree)
                    for child in subtree['children']:
                        _write_subtree(path_tuple+[subtree['title']], child)

            # EXERCISE #########################################################
            elif kind == 'exercise':
                source_id = _generate_source_id(subtree)
                self.write_exercice_row_from_studio_dict(path_tuple, subtree, source_id)
                for question_dict in subtree['assessment_items']:
                    self.write_question_row_from_question_dict(source_id, question_dict)

            else:
                print('skipping node', subtree['title'])

        path_tuple = [ self.channeldir.split('/')[-1] ]
        _write_subtree(path_tuple, channel_dict, is_root=True)
782171
def write(self, data, method='w'):
        
        # Create list of lists from flat list
        data = data if isinstance(data[0], (list, set, tuple)) else [[d] for d in data]

        # Open file and write rows
        with open(self.file_path, method) as write:
            wr = csv_builtin.writer(write)
            wr.writerows(data)
        return self.file_path
417690
def write_csv(fileobj, rows, encoding=ENCODING, dialect=DIALECT):
    """"""
    csvwriter = csv.writer(fileobj, dialect=dialect)
    csv_writerows(csvwriter, rows, encoding)
278088
def _createComboBoxes(self, row):
        
        tree = self.tree
        model = self.tree.model()
        self._setColumnCountForContents()

        for col, _ in enumerate(self._axisNames, self.COL_FIRST_COMBO):
            logger.debug("Adding combobox at ({}, {})".format(row, col))
            comboBox = QtWidgets.QComboBox()
            comboBox.setSizeAdjustPolicy(QtWidgets.QComboBox.AdjustToContents)
            comboBox.activated.connect(self._comboBoxActivated)
            self._comboBoxes.append(comboBox)

            #editor = LabeledWidget(QtWidgets.QLabel(comboLabel), comboBox)
            tree.setIndexWidget(model.index(row, col), comboBox)
722456
def nested_row(self, obj, nested):
        ''''''
        row = self.to_row(obj)
        for name, getter in self.get_nested_fields():
            content = ''
            if getter is not None:
                try:
                    content = safestr(getter(nested))
                except Exception, e:  # Catch all errors intentionally.
                    log.error('Error exporting CSV for {name}: {error}'.format(
                        name=self.__class__.__name__, error=e))
            row.append(content)
        return row
245518
public void generateCSV() {
        
        int cont = 0;
        int algorithmSize = this.streams.get(0).algorithm.size();
        int streamSize = this.streams.size();
        int measureSize = this.streams.get(0).algorithm.get(0).measures.size();
        
        while (cont != measureSize) {
            String output = "";
            output += "Algorithm,";
            output += this.streams.get(0).algorithm.get(0).name;
            //Inicialize summary table
            
            for (int i = 1; i < algorithmSize; i++) {
                output += "," + this.streams.get(0).algorithm.get(i).name;
               
            }
            output += "\n";

            for (int i = 0; i < streamSize; i++) {
                List<Algorithm> alg = this.streams.get(i).algorithm;
                output += this.streams.get(i).name;
                for (int j = 0; j < algorithmSize; j++) {
                    output += "," + alg.get(j).measures.get(cont).getValue();
                    
                }
                output += "\n";
            }
            //PrintStream out = null;
            String name = this.streams.get(0).algorithm.get(0).measures.get(cont).getName();
//            try {
//                out = new PrintStream(new BufferedOutputStream(new FileOutputStream(path + name + ".csv")));
//            } catch (FileNotFoundException ex) {
//                Logger.getLogger(Summary.class.getName()).log(Level.SEVERE, null, ex);
//            }
//            System.setOut(out);
//            System.out.println(output);
//            out.close();
            try {
            BufferedWriter out = new BufferedWriter(new FileWriter(path + name + ".csv"));
            out.write(output);  //Replace with the string 
            //you are trying to write  
            out.close();
        } catch (IOException e) {
            System.out.println(name + ".csv");

        }
            cont++;
        }

    }
1316021
def _dump_csv(self, rows):
        
        self.logger.debug('Writing %r', rows)
        csv = self._maybe_import('csv')
        buff = io.StringIO() if _PYTHON3 else io.BytesIO()
        writer = csv.DictWriter(
            buff,
            sorted(set([k for r in rows for k in r.keys()])),
            dialect='excel')
        writer.writeheader()
        writer.writerows(rows)
        value = buff.getvalue()
        buff.close()
        return value
979197
def write_csv(path, rows, dialect='excel', fieldnames=None, quoting=csv.QUOTE_ALL, extrasaction='ignore', *args, **kwargs):
        '''  '''
        if not quoting:
            quoting = csv.QUOTE_MINIMAL
        if 'lineterminator' not in kwargs:
            kwargs['lineterminator'] = '\n'  # use \n to fix double-line in Windows
        with open(path, mode='wt', newline='') as csvfile:
            if fieldnames:
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames, dialect=dialect, quoting=quoting, extrasaction=extrasaction, *args, **kwargs)
                writer.writeheader()
                for row in rows:
                    writer.writerow(row)
            else:
                writer = csv.writer(csvfile, dialect=dialect, quoting=quoting, *args, **kwargs)
                for row in rows:
                    writer.writerow(row)
700282
private void writeRowsToCSV(List<String[]> rows) throws BindException
  {
    int numBytes;
    int rowNum = 0;
    int fileCount = 0;

    while (rowNum < rows.size())
    {
      File file = getFile(++fileCount);

      try (OutputStream out = openFile(file))
      {
        // until we reach the last row or the file is too big, write to the file
        numBytes = 0;
        while (numBytes < fileSize && rowNum < rows.size())
        {
          byte[] csv = createCSVRecord(rows.get(rowNum));
          numBytes += csv.length;
          out.write(csv);
          rowNum++;
        }
      }
      catch (IOException ex)
      {
        throw new BindException(
            String.format("Exception encountered while writing to file: %s", ex.getMessage()), BindException.Type.SERIALIZATION);
      }
    }
  }
386965
def create_from_user_input(raw_properties, jamfile_module, location):
    """'"""
    assert is_iterable_typed(raw_properties, basestring)
    assert isinstance(jamfile_module, basestring)
    assert isinstance(location, basestring)
    properties = property.create_from_strings(raw_properties, True)
    properties = property.translate_paths(properties, location)
    properties = property.translate_indirect(properties, jamfile_module)

    project_id = get_manager().projects().attributeDefault(jamfile_module, 'id', None)
    if not project_id:
        project_id = os.path.abspath(location)
    properties = property.translate_dependencies(properties, project_id, location)
    properties = property.expand_subfeatures_in_conditions(properties)
    return create(properties)
1155912
def create_new_csv(samples, args):
    """"""
    out_fn = os.path.splitext(args.csv)[0] + "-merged.csv"
    logger.info("Preparing new csv: %s" % out_fn)
    with file_transaction(out_fn) as tx_out:
        with open(tx_out, 'w') as handle:
            handle.write(_header(args.csv))
            for s in samples:
                sample_name = s['name'] if isinstance(s['out_file'], list) else os.path.basename(s['out_file'])
                handle.write("%s,%s,%s\n" % (sample_name, s['name'], ",".join(s['anno'])))
405568
public void generateCsv(OutputStream out, List<Map<String, Object>> rows, List<ColumnDef> columns) {
        ICsvMapWriter csvWriter = null;
        try {
            csvWriter = new CsvMapWriter(new OutputStreamWriter(out), CsvPreference.STANDARD_PREFERENCE);
            // the header elements are used to map the bean values to each column (names must match)
            String[] header = new String[] {};
            CellProcessor[] processors = new CellProcessor[] {};
            if (columns != null)
            {
                header = (String[])CollectionUtils.collect(columns, new Transformer() {
                    @Override
                    public Object transform(Object input) {
                        ColumnDef column = (ColumnDef)input;
                        return column.getName();
                    }
                }).toArray(new String[0]) ;
                processors = (CellProcessor[]) CollectionUtils.collect(columns, new Transformer() {
                    @Override
                    public Object transform(Object input) {
                        return new Optional();
                    }
                }).toArray(new CellProcessor[0]);
            } else if (rows.size() > 0)
            {
                header = new ArrayList<String>(rows.get(0).keySet()).toArray(new String[0]);
                processors = (CellProcessor[]) CollectionUtils.collect(rows.get(0).keySet(), new Transformer() {
                    @Override
                    public Object transform(Object input) {
                        return new Optional();
                    }
                }).toArray(new CellProcessor[0]);
            }
            if (header.length > 0)
                csvWriter.writeHeader(header);
            if (rows != null)
                for (Map<String, Object> row : rows)
                {
                    csvWriter.write(row, header, processors);
                }
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            if( csvWriter != null ) {
                try {
                    csvWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }
        }
    }
890632
def construct_channel(self, *args, **kwargs):
        
        channel = self.get_channel(*args, **kwargs)   # creates ChannelNode from data in self.channel_info
        _build_tree(channel, SAMPLE_TREE)
        raise_for_invalid_channel(channel)

        return channel
886857
def csv_dumper(**kwargs):
    """"""
    logging.info("dumping to csv")
    barn = kwargs["barn"]
    farms = kwargs["farms"]
    experiments = kwargs["experiments"]
    for experiment, farm in zip(experiments, farms):
        name = experiment.journal.name
        project = experiment.journal.project
        project_dir, batch_dir, raw_dir = \
            experiment.journal.paginate()
        if batch_dir is None:
            logging.info("have to generate folder-name on the fly")
            out_data_dir, project_dir, batch_dir, raw_dir = \
                generate_folder_names(name, project)

        if barn == "batch_dir":
            out_dir = batch_dir
        elif barn == "project_dir":
            out_dir = project_dir
        elif barn == "raw_dir":
            out_dir = raw_dir
        else:
            out_dir = barn

        for animal in farm:
            file_name = os.path.join(
                out_dir, "summary_%s_%s.csv" % (
                    animal.name,
                    name
                )
            )
            logging.info(f"> {file_name}")
            animal.to_csv(file_name, sep=prms.Reader.sep)
170634
def load_csv(vs):
    ''
    with vs.source.open_text() as fp:
        for i in range(options.skip):
            wrappedNext(fp)  # discard initial lines

        if options.safety_first:
            rdr = csv.reader(removeNulls(fp), **csvoptions())
        else:
            rdr = csv.reader(fp, **csvoptions())

        vs.rows = []

        # headers first, to setup columns before adding rows
        headers = [wrappedNext(rdr) for i in range(int(options.header))]

        if headers:
            # columns ideally reflect the max number of fields over all rows
            vs.columns = ArrayNamedColumns('\\n'.join(x) for x in zip(*headers))
        else:
            r = wrappedNext(rdr)
            vs.addRow(r)
            vs.columns = ArrayColumns(len(vs.rows[0]))

        if not vs.columns:
            vs.columns = [ColumnItem(0)]

        vs.recalc()  # make columns usable
        with Progress(total=vs.source.filesize) as prog:
            try:
                samplelen = 0
                for i in range(options_num_first_rows):  # for progress below
                    row = wrappedNext(rdr)
                    vs.addRow(row)
                    samplelen += sum(len(x) for x in row)

                samplelen //= options_num_first_rows  # avg len of first n rows

                while True:
                    vs.addRow(wrappedNext(rdr))
                    prog.addProgress(samplelen)
            except StopIteration:
                pass  # as expected

    vs.recalc()
    return vs
487751
def _make_datablock(self):
        ''''''
        section_ids = sorted(self.sections)

        # create all insertion id's, this needs to be done ahead of time
        # as some of the children may have a lower id than their parents
        id_to_insert_id = {}
        row_count = 0
        for section_id in section_ids:
            row_count += len(self.sections[section_id].points)
            id_to_insert_id[section_id] = row_count - 1

        datablock = np.empty((row_count, COLS.COL_COUNT), dtype=np.float)
        datablock[:, COLS.ID] = np.arange(len(datablock))
        datablock[:, COLS.P] = datablock[:, COLS.ID] - 1

        sections = []
        insert_index = 0
        for id_ in section_ids:
            sec = self.sections[id_]
            points, section_type, parent_id = sec.points, sec.section_type, sec.parent_id

            idx = slice(insert_index, insert_index + len(points))
            datablock[idx, COLS.XYZR] = points
            datablock[idx, COLS.TYPE] = section_type
            datablock[idx.start, COLS.P] = id_to_insert_id.get(parent_id, ROOT_ID)
            sections.append(DataBlockSection(idx, section_type, parent_id))
            insert_index = idx.stop

        return datablock, sections
1356054
def main():
    parser = argparse.ArgumentParser(description='Shuffle columns in a CSV file')
    parser.add_argument(metavar="FILE", dest='input_file', type=argparse.FileType('r'), nargs='?',
                        default=sys.stdin, help='Input CSV file. If omitted, read standard input.')
    parser.add_argument('-s', '--sattolo',
                        action='store_const', const=shuffle_sattolo,
                        dest='shuffle', default=random.shuffle,
                        help="Use Sattolo's shuffle algorithm.")
    col_group = parser.add_mutually_exclusive_group()
    col_group.add_argument('-c', '--columns', type=column_list,
                           help='Comma-separated list of columns to include.')
    col_group.add_argument('-C', '--no-columns', type=column_list,
                           help='Comma-separated list of columns to exclude.')
    delim_group = parser.add_mutually_exclusive_group()
    delim_group.add_argument('-d', '--delimiter', type=str, default=',',
                             help='Input column delimiter.')
    delim_group.add_argument('-t', '--tabbed', dest='delimiter',
                             action='store_const', const='\t',
                             help='Delimit input with tabs.')
    parser.add_argument('-q', '--quotechar', type=str, default='"',
                        help='Quote character.')
    parser.add_argument('-o', '--output-delimiter', type=str, default=',',
                        help='Output column delimiter.')
    parser.add_argument('-v', '--version', action='version',
                        version='%(prog)s {version}'.format(version=__version__))
    args = parser.parse_args()

    reader = csv.reader(args.input_file, delimiter=args.delimiter, quotechar=args.quotechar)

    """"""
    headers = next(reader)

    """Create a matrix of lists of columns"""
    table = []
    for c in range(len(headers)):
        table.append([])
    for row in reader:
        for c in range(len(headers)):
            table[c].append(row[c])

    cols = args.columns
    if args.no_columns:
        """If columns to exclude are provided, get a list of all other columns"""
        cols = list(set(range(len(headers))) - set(args.no_columns))
    elif not cols:
        """If no columns are provided all columns will be shuffled"""
        cols = range(len(headers))

    for c in cols:
        if c > len(headers):
            sys.stderr.write('Invalid column {0}. Last column is {1}.\n'.format(c, len(headers)))
            exit(1)
        args.shuffle(table[c - 1])

    """Transpose the matrix"""
    table = zip(*table)

    writer = csv.writer(sys.stdout, delimiter=args.output_delimiter)
    writer.writerow(headers)
    for row in table:
        writer.writerow(row)