Parses {@link Vector} from the given CSV string.

@param csv the CSV string representing a vector

@return a parsed vector
339767
public static Vector fromCSV(String csv) {
        StringTokenizer tokenizer = new StringTokenizer(csv, ", ");
        int estimatedLength = csv.length() / (5 + 2) + 1; // 5 symbols per element "0.000"
                                                          // 2 symbols for delimiter ", "
        Vector result = DenseVector.zero(estimatedLength);

        int i = 0;
        while (tokenizer.hasMoreTokens()) {
            if (result.length() == i) {
                result = result.copyOfLength((i * 3) / 2 + 1);
            }

            double x = Double.parseDouble(tokenizer.nextToken());
            result.set(i++, x);
        }

        return result.copyOfLength(i);
    }
584927
public static DenseMatrix fromCSV(String csv) {
        return Matrix.fromCSV(csv).to(Matrices.DENSE);
    }
435302
private <T> String serializeToCsv(T obj) {
	  if(obj == null) {
	        return "";
	  }
	  
	  for (Method method: obj.getClass().getMethods()) {
		  if ("java.util.List".equals(method.getReturnType().getName())) {
			  try {
		          @SuppressWarnings("rawtypes")
				  java.util.List itemList = (java.util.List) method.invoke(obj);
		          Object entry = itemList.get(0);
		          
		          List<String> stringList = new ArrayList<String>();
		          char delimiter = ',';
				  String lineSep = "\n";
	
				  CsvMapper mapper = new CsvMapper();
				  mapper.enable(JsonGenerator.Feature.IGNORE_UNKNOWN);
				  CsvSchema schema = mapper.schemaFor(entry.getClass());
				  for (int i = 0; i < itemList.size(); i++) {
					  if (i == 0) {
						  schema = schema.withHeader();
					  } else {
						  schema = schema.withoutHeader();
					  }
					  String csv = mapper.writer(schema
			                .withColumnSeparator(delimiter)
			                .withoutQuoteChar()
			                .withLineSeparator(lineSep)).writeValueAsString(itemList.get(i));
	
					  stringList.add(csv);
				  }
				  return StringUtil.join(stringList.toArray(new String[0]), "");
		  	  } catch (JsonProcessingException e) {
		          System.out.println(e);
		  	  } catch (IllegalAccessException e) {
		          System.out.println(e);
			} catch (IllegalArgumentException e) {
		          System.out.println(e);
			} catch (InvocationTargetException e) {
		          System.out.println(e);
			}
		  }
	  }
	  
	  return "";
  }
1262956
public List<String[]> parse(InputStream stream) throws IOException
    {
        int columnCount = -1;
        List<String[]> lines = new ArrayList<String[]>();
        rows.clear();

        // Excel spreadsheet
        if(CommonFiles.isExcelFile(name))
        {
            if(worksheet != null && worksheet.length() > 0)
            {
                SimpleDateFormat df = new SimpleDateFormat(Formats.DATETIME_FORMAT);
                df.setTimeZone(TimeZone.getTimeZone("GMT"));

                Workbook workbook = Workbook.getWorkbook(name, stream);
                Worksheet sheet = workbook.getSheet(worksheet);
                if(sheet != null)
                {
                    columnCount = sheet.getColumns();
                    for(int i = 0; i < sheet.getRows(); i++)
                    {
                        String[] values = sheet.getRow(i, df);
                        if(values != null)
                            lines.add(values);
                    }
                }
                else
                {
                    throw new IllegalStateException("Worksheet '"+worksheet+"' not found");
                }

                workbook.close();
            }
            else
            {
                throw new IllegalArgumentException("Worksheet not specified");
            }
        }
        else if(CommonFiles.isCsvFile(name))
        {
            Reader reader = new InputStreamReader(stream);
            CSVReader csv = new CSVReader(reader, delimiter.separator().charAt(0));
            String [] line;
            while ((line = csv.readNext()) != null) 
            {
                if(columnCount == -1)
                    columnCount = line.length;
                lines.add(line);
            }
            reader.close();
        }

        int lineCount = lines.size();

        logger.fine("InputFileReader.parse: lines="+lineCount+" columns="+columnCount);

        // Error if the file is empty
        if(lineCount <= 0 || columnCount == 0)
            throw new IllegalStateException("input file does not contain any data");

        // Parse the file headers and rows
        int count = 0;
        for(String[] line : lines)
        {
            // Ignore the line if there is no data
            if(isBlankRow(line))
                continue;

            String[] row = new String[columnCount];  // the row of data

            for(int column = 0; column < columnCount; column++)
            {

                // Check that the row column count matches the header column count
                if(column >= line.length)
                {
                    if(line.length > 0 && isCompleteLine(line))
                        break;
                    else
                        throw new IllegalStateException("Row "+count+" has more columns than the header row");
                }

                // The first row gives the column headers
                if(count == 0)
                {
                    try
                    {
                        row[column] = line[column].trim();
                    }
                    catch(NoSuchElementException e)
                    {
                        row[column] = "";
                    }
                }
                else // The subsequent rows give the actual data
                {
                    try
                    {
                        String token = line[column];

                        // Remove quotes
                        if(removeQuotes && token.startsWith("\""))
                        {
                            token = token.substring(1);
                            if(token.endsWith("\""))
                                token = token.substring(0,token.length()-1);

                            // Replace all other double quotes with a single quote
                            token = token.replaceAll("\"\"", "\"");
                        }

                        // Trim the value (if required)
                        if(trim)
                            token.trim();

                        // Put the processed token in the array
                        row[column] = token;
                        logger.fine("InputFileReader.parse: row["+count+","+headers[column]+"]="+token);
                    }
                    catch(NoSuchElementException e)
                    {
                        row[column] = "";
                    }
                }
            }

            if(count == 0)
                headers = row;
            else
                rows.add(row);
            ++count;
        }

        return rows;
    }
157054
public String getCsv() {

        StringWriter writer = new StringWriter();
        try (CSVWriter csv = new CSVWriter(writer)) {
            List<String> headers = new ArrayList<>();
            for (String col : m_columns) {
                headers.add(col);
            }
            csv.writeNext(headers.toArray(new String[] {}));
            for (List<Object> row : m_data) {
                List<String> colCsv = new ArrayList<>();
                for (Object col : row) {
                    colCsv.add(String.valueOf(col));
                }
                csv.writeNext(colCsv.toArray(new String[] {}));
            }
            return writer.toString();
        } catch (IOException e) {
            return null;
        }
    }
1143469
public String toCsv() {
    StringBuilder sb = new StringBuilder();
    Iterator<Outcome> iter = outcomeIterator();
    while (iter.hasNext()) {
      Outcome outcome = iter.next();
      sb.append(outcome.toCsv());
      if (iter.hasNext()) {
        sb.append("\n");
      }
    }
    return sb.toString();
  }
111146
public static ColumnMajorSparseMatrix fromCSV(String csv) {
        return Matrix.fromCSV(csv).to(Matrices.SPARSE_COLUMN_MAJOR);
    }
1141451
def _parsecsv(x):
        
        for line in x:
            # decode as utf-8, whitespace-strip and split on delimiter
            yield line.decode('utf-8').strip().split(config.DELIMITER)
590146
public static Basic2DMatrix fromCSV(String csv) {
        return Matrix.fromCSV(csv).to(Matrices.BASIC_2D);
    }
877943
public static Vector fromMatrixMarket(InputStream is) throws IOException {

        StreamTokenizer tokenizer = new StreamTokenizer(new BufferedReader(new InputStreamReader(is)));
        tokenizer.wordChars('%', '%');

        tokenizer.nextToken();
        if (!"%%MatrixMarket".equals(tokenizer.sval)) {
            throw new IllegalArgumentException("Wrong input file format: can not read header '%%MatrixMarket'.");
        }

        tokenizer.nextToken();
        String object = tokenizer.sval;
        if (!"vector".equals(object)) {
            throw new IllegalArgumentException("Unexpected object: " + object + ".");
        }

        tokenizer.nextToken();
        String format = tokenizer.sval;
        if (!"coordinate".equals(format) && !"array".equals(format)) {
            throw new IllegalArgumentException("Unknown format: " + format + ".");
        }

        tokenizer.nextToken();
        String field = tokenizer.sval;
        if (!"real".equals(field)) {
            throw new IllegalArgumentException("Unknown field type: " + field + ".");
        }

        tokenizer.nextToken();
        int length = (int) Math.round(tokenizer.nval);
        if ("coordinate".equals(format)) {
            tokenizer.nextToken();
            int cardinality = (int) Math.round(tokenizer.nval);
            Vector result = SparseVector.zero(length, cardinality);

            for (int k = 0; k < cardinality; k++) {
                tokenizer.nextToken();
                int i = (int) Math.round(tokenizer.nval);
                tokenizer.nextToken();
                double x = tokenizer.nval;
                result.set(i - 1, x);
            }

            return result;
        } else {
            Vector result = DenseVector.zero(length);

            for (int i = 0; i < length; i++) {
                tokenizer.nextToken();
                result.set(i, tokenizer.nval);
            }

            return result;
        }
    }
964457
public static Vector<String> toVector( String[] array )
	{
		if( array == null )
		{
			return new Vector<String>( 0 );
		}
		Vector<String> v = new Vector<String>( array.length );
		v.copyInto( array );
		return v;
	}
487682
public static final Set<String> fromCommaSeparatedValues(String csv) {
        if (csv == null || csv.isEmpty()) {
            return Collections.EMPTY_SET;
        }
        String[] tokens = csv.split(",");
        return new HashSet<String>(Arrays.asList(tokens));
    }
1293418
public static Basic1DMatrix fromCSV(String csv) {
        return Matrix.fromCSV(csv).to(Matrices.BASIC_1D);
    }
326775
def read_csv(filename):
    

    with open(filename, 'r') as f:
        r = csv.reader(f)
        next(r)  # remove header
        wm = list(r)

    # remove header and convert to numeric
    for i, row in enumerate(wm):
        row[1:4] = map(int, row[1:4])
        row[4] = float(row[4])

    return wm
139837
private boolean tokenizeCSVLine(CSVFile             csvFile, 
                                    BufferedReader      reader,
                                    Map<String, String> fieldMap) {
        fieldMap.clear();
        m_token.setLength(0);
        
        // First build a list of tokens found in the order they are found.
        List<String> tokenList = new ArrayList<String>();
        boolean bInQuote = false;
        int aChar = 0;
        try {
            while (true) {
                aChar = reader.read();
                if (aChar < 0) {
                    break;
                }
                
                if (!bInQuote && aChar == ',') {
                    tokenList.add(m_token.toString());
                    m_token.setLength(0);
                } else if (!bInQuote && aChar == '\r') {
                    tokenList.add(m_token.toString());
                    m_token.setLength(0);
                    reader.mark(1);
                    aChar = reader.read();
                    if (aChar == -1) {
                        break; 
                    }
                    if (aChar != '\n') {
                        reader.reset(); // put back non-LF
                    }
                    break;
                } else if (!bInQuote && aChar == '\n') {
                    tokenList.add(m_token.toString());
                    m_token.setLength(0);
                    break;
                } else if (aChar == '"') {
                    bInQuote = !bInQuote;
                } else {
                    m_token.append((char)aChar);
                }
            }
        } catch (IOException e) {
            logErrorThrow("I/O error reading file", e.toString());
        }

        // If we hit EOF without a final EOL, we could have a token in the buffer.
        if (m_token.length() > 0) {
            tokenList.add(m_token.toString());
            m_token.setLength(0);
        }
        
        if (tokenList.size() > 0) {
            for (int index = 0; index < tokenList.size(); index++) {
                String token = tokenList.get(index).trim();
                if (token.length() > 0) {
                    String fieldName = csvFile.m_fieldList.get(index);
                    fieldMap.put(fieldName, token);
                }
            }
            return true;
        }
        
        // No tokens found; return false if EOF.
        return aChar != -1;
    }
1208689
@SuppressWarnings("unchecked")
    public static String vector2JsonString(Object[] vector)
    {
        IStringBuffer sb = new IStringBuffer();
        sb.append('[');
        for ( Object o : vector )
        {
            if ( o instanceof List<?> ) {
                sb.append(list2JsonString((List<Object>)o)).append(',');
            } else if (o instanceof Object[]) {
                sb.append(vector2JsonString((Object[])o)).append(',');
            } else if (o instanceof Map<?,?>) {
                sb.append(map2JsonString((Map<String, Object>)o)).append(',');
            } else if ((o instanceof Boolean) 
                    || (o instanceof Byte) || (o instanceof Short) 
                    || (o instanceof Integer) || (o instanceof Long) 
                    || (o instanceof Float) || (o instanceof Double)) {
                sb.append(o.toString()).append(',');
            } else {
                String v = o.toString();
                int last = v.length() - 1;
                
                // Avoid string like "[Error] there is a problem" treat as a array 
                // and "{error}: there is a problem" treat as object
                if ( v.length() > 1 
                        && ( (v.charAt(0) == '{' && v.charAt(last) == '}' )
                                || (v.charAt(0) == '[' && v.charAt(last) == ']' ) ) 
                ) {
                    sb.append(v).append(',');
                } else {
                    sb.append('"').append(v).append("\",");
                }
            }
        }
        
        if ( sb.length() > 1 ) {
            sb.deleteCharAt(sb.length()-1);
        }
        sb.append(']');
        
        return sb.toString();
    }
586381
private static String getVectorString(Vector vector) {
        StringBuffer buffer = new StringBuffer();
        int[] indices = vector.getIndices();
        double[] values = vector.getValues();
        for (int i = 0; i < indices.length; i++) {
            buffer.append(" ").append(indices[i]).append(":").append(values[i]);
        }
        return buffer.toString();
    }