Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Maintain the same structure and functionality when rewriting this code in VB.
write.csv(df, file = "foo.csv",row.names = FALSE)
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Produce a language-to-language conversion: from R to VB, same semantics.
write.csv(df, file = "foo.csv",row.names = FALSE)
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Maintain the same structure and functionality when rewriting this code in Go.
write.csv(df, file = "foo.csv",row.names = FALSE)
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
Change the following R code into Go without altering its purpose.
write.csv(df, file = "foo.csv",row.names = FALSE)
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
Generate a C translation of this Racket snippet without changing its computational steps.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
#define TITLE "CSV data manipulation" #define URL "http: #define _GNU_SOURCE #define bool int #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(","); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf("[Empty table]\n"); return ; } printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf("[|"); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf("%s\t|", content); } printf("]\n"); } printf("\n"); } int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { content = csv_get(old_csv, cur_col, cur_row); free(content); } else { } } } free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); return -1; } int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, "r"); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf("Unable to open %s for reading.", filename); return -1; } int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, "w"); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, ((col == csv->cols-1) ? "" : csv->delim) ); } fprintf(fp, "\n"); } fclose(fp); return 0; } int main(int argc, char ** argv) { CSV * csv; printf("%s\n%s\n\n",TITLE, URL); csv = csv_create(0, 0); csv_open(csv, "fixtures/csv-data-manipulation.csv"); csv_display(csv); csv_set(csv, 0, 0, "Column0"); csv_set(csv, 1, 1, "100"); csv_set(csv, 2, 2, "200"); csv_set(csv, 3, 3, "300"); csv_set(csv, 4, 4, "400"); csv_display(csv); csv_save(csv, "tmp/csv-data-manipulation.result.csv"); csv_destroy(csv); return 0; }
Translate the given Racket code snippet into C without altering its behavior.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
#define TITLE "CSV data manipulation" #define URL "http: #define _GNU_SOURCE #define bool int #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(","); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf("[Empty table]\n"); return ; } printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf("[|"); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf("%s\t|", content); } printf("]\n"); } printf("\n"); } int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { content = csv_get(old_csv, cur_col, cur_row); free(content); } else { } } } free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); return -1; } int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, "r"); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf("Unable to open %s for reading.", filename); return -1; } int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, "w"); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, ((col == csv->cols-1) ? "" : csv->delim) ); } fprintf(fp, "\n"); } fclose(fp); return 0; } int main(int argc, char ** argv) { CSV * csv; printf("%s\n%s\n\n",TITLE, URL); csv = csv_create(0, 0); csv_open(csv, "fixtures/csv-data-manipulation.csv"); csv_display(csv); csv_set(csv, 0, 0, "Column0"); csv_set(csv, 1, 1, "100"); csv_set(csv, 2, 2, "200"); csv_set(csv, 3, 3, "300"); csv_set(csv, 4, 4, "400"); csv_display(csv); csv_save(csv, "tmp/csv-data-manipulation.result.csv"); csv_destroy(csv); return 0; }
Write the same code in C# as shown below in Racket.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
using System.IO; using System.Linq; namespace CSV_data_manipulation { class Program { static void Main() { var input = File.ReadAllLines("test_in.csv"); var output = input.Select((line, i) => { if (i == 0) return line + ",SUM"; var sum = line.Split(',').Select(int.Parse).Sum(); return line + "," + sum; }).ToArray(); File.WriteAllLines("test_out.csv", output); } } }
Port the provided Racket code into C# while preserving the original functionality.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
using System.IO; using System.Linq; namespace CSV_data_manipulation { class Program { static void Main() { var input = File.ReadAllLines("test_in.csv"); var output = input.Select((line, i) => { if (i == 0) return line + ",SUM"; var sum = line.Split(',').Select(int.Parse).Sum(); return line + "," + sum; }).ToArray(); File.WriteAllLines("test_out.csv", output); } } }
Preserve the algorithm and functionality while converting the code from Racket to C++.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) { std::ifstream file( filename ); clear(); if ( file.is_open() ) { open( file, delim ); return true; } return false; } void open( std::istream& istream, char delim = ',' ) { std::string line; clear(); while ( std::getline( istream, line ) ) { unsigned int nCol = 0; std::istringstream lineStream(line); std::string cell; while( std::getline( lineStream, cell, delim ) ) { m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); nCol++; } m_nCols = std::max( m_nCols, nCol ); m_nRows++; } } bool save( const char* pFile, char delim = ',' ) { std::ofstream ofile( pFile ); if ( ofile.is_open() ) { save( ofile ); return true; } return false; } void save( std::ostream& ostream, char delim = ',' ) { for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) { for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) { ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); if ( (nCol+1) < m_nCols ) { ostream << delim; } else { ostream << std::endl; } } } } void clear() { m_oData.clear(); m_nRows = m_nCols = 0; } std::string& operator()( unsigned int nCol, unsigned int nRow ) { m_nCols = std::max( m_nCols, nCol+1 ); m_nRows = std::max( m_nRows, nRow+1 ); return m_oData[std::make_pair(nCol, nRow)]; } inline unsigned int GetRows() { return m_nRows; } inline unsigned int GetCols() { return m_nCols; } private: inline std::string &trim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } private: std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData; unsigned int m_nCols; unsigned int m_nRows; }; int main() { CSV oCSV; oCSV.open( "test_in.csv" ); oCSV( 0, 0 ) = "Column0"; oCSV( 1, 1 ) = "100"; oCSV( 2, 2 ) = "200"; oCSV( 3, 3 ) = "300"; oCSV( 4, 4 ) = "400"; oCSV.save( "test_out.csv" ); return 0; }
Produce a functionally identical C++ code for the snippet given in Racket.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) { std::ifstream file( filename ); clear(); if ( file.is_open() ) { open( file, delim ); return true; } return false; } void open( std::istream& istream, char delim = ',' ) { std::string line; clear(); while ( std::getline( istream, line ) ) { unsigned int nCol = 0; std::istringstream lineStream(line); std::string cell; while( std::getline( lineStream, cell, delim ) ) { m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); nCol++; } m_nCols = std::max( m_nCols, nCol ); m_nRows++; } } bool save( const char* pFile, char delim = ',' ) { std::ofstream ofile( pFile ); if ( ofile.is_open() ) { save( ofile ); return true; } return false; } void save( std::ostream& ostream, char delim = ',' ) { for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) { for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) { ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); if ( (nCol+1) < m_nCols ) { ostream << delim; } else { ostream << std::endl; } } } } void clear() { m_oData.clear(); m_nRows = m_nCols = 0; } std::string& operator()( unsigned int nCol, unsigned int nRow ) { m_nCols = std::max( m_nCols, nCol+1 ); m_nRows = std::max( m_nRows, nRow+1 ); return m_oData[std::make_pair(nCol, nRow)]; } inline unsigned int GetRows() { return m_nRows; } inline unsigned int GetCols() { return m_nCols; } private: inline std::string &trim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } private: std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData; unsigned int m_nCols; unsigned int m_nRows; }; int main() { CSV oCSV; oCSV.open( "test_in.csv" ); oCSV( 0, 0 ) = "Column0"; oCSV( 1, 1 ) = "100"; oCSV( 2, 2 ) = "200"; oCSV( 3, 3 ) = "300"; oCSV( 4, 4 ) = "400"; oCSV.save( "test_out.csv" ); return 0; }
Maintain the same structure and functionality when rewriting this code in Java.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class CSV { private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows; public void open(File file) throws FileNotFoundException, IOException { open(file, ','); } public void open(File file, char delimiter) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); scanner.useDelimiter(Character.toString(delimiter)); clear(); while(scanner.hasNextLine()) { String[] values = scanner.nextLine().split(Character.toString(delimiter)); int col = 0; for ( String value: values ) { _map.put(new Point(col, _rows), value); _cols = Math.max(_cols, ++col); } _rows++; } scanner.close(); } public void save(File file) throws IOException { save(file, ','); } public void save(File file, char delimiter) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Point key = new Point(col, row); if (_map.containsKey(key)) { bw.write(_map.get(key)); } if ((col + 1) < _cols) { bw.write(delimiter); } } bw.newLine(); } bw.flush(); bw.close(); } public String get(int col, int row) { String val = ""; Point key = new Point(col, row); if (_map.containsKey(key)) { val = _map.get(key); } return val; } public void put(int col, int row, String value) { _map.put(new Point(col, row), value); _cols = Math.max(_cols, col+1); _rows = Math.max(_rows, row+1); } public void clear() { _map.clear(); _cols = 0; _rows = 0; } public int rows() { return _rows; } public int cols() { return _cols; } public static void main(String[] args) { try { CSV csv = new CSV(); csv.open(new File("test_in.csv")); csv.put(0, 0, "Column0"); csv.put(1, 1, "100"); csv.put(2, 2, "200"); csv.put(3, 3, "300"); csv.put(4, 4, "400"); csv.save(new File("test_out.csv")); } catch (Exception e) { } } }
Keep all operations the same but rewrite the snippet in Java.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class CSV { private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows; public void open(File file) throws FileNotFoundException, IOException { open(file, ','); } public void open(File file, char delimiter) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); scanner.useDelimiter(Character.toString(delimiter)); clear(); while(scanner.hasNextLine()) { String[] values = scanner.nextLine().split(Character.toString(delimiter)); int col = 0; for ( String value: values ) { _map.put(new Point(col, _rows), value); _cols = Math.max(_cols, ++col); } _rows++; } scanner.close(); } public void save(File file) throws IOException { save(file, ','); } public void save(File file, char delimiter) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Point key = new Point(col, row); if (_map.containsKey(key)) { bw.write(_map.get(key)); } if ((col + 1) < _cols) { bw.write(delimiter); } } bw.newLine(); } bw.flush(); bw.close(); } public String get(int col, int row) { String val = ""; Point key = new Point(col, row); if (_map.containsKey(key)) { val = _map.get(key); } return val; } public void put(int col, int row, String value) { _map.put(new Point(col, row), value); _cols = Math.max(_cols, col+1); _rows = Math.max(_rows, row+1); } public void clear() { _map.clear(); _cols = 0; _rows = 0; } public int rows() { return _rows; } public int cols() { return _cols; } public static void main(String[] args) { try { CSV csv = new CSV(); csv.open(new File("test_in.csv")); csv.put(0, 0, "Column0"); csv.put(1, 1, "100"); csv.put(2, 2, "200"); csv.put(3, 3, "300"); csv.put(4, 4, "400"); csv.save(new File("test_out.csv")); } catch (Exception e) { } } }
Convert this Racket snippet to Python and keep its semantics consistent.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
import fileinput changerow, changecolumn, changevalue = 2, 4, '"Spam"' with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue line = ','.join(fields) + '\n' print(line, end='')
Maintain the same structure and functionality when rewriting this code in Python.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
import fileinput changerow, changecolumn, changevalue = 2, 4, '"Spam"' with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue line = ','.join(fields) + '\n' print(line, end='')
Keep all operations the same but rewrite the snippet in VB.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Port the provided Racket code into VB while preserving the original functionality.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Translate this program into Go but keep the logic exactly as in Racket.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
Convert this Racket snippet to Go and keep its semantics consistent.
#lang racket (require (planet neil/csv:1:=7) net/url) (define make-reader (make-csv-reader-maker '((separator-chars #\,) (strip-leading-whitespace? . #t) (strip-trailing-whitespace? . #t)))) (define (all-rows port) (define read-row (make-reader port)) (define head (append (read-row) '("SUM"))) (define rows (for/list ([row (in-producer read-row '())]) (define xs (map string->number row)) (append row (list (~a (apply + xs)))))) (define (->string row) (string-join row "," #:after-last "\n")) (string-append* (map ->string (cons head rows))))
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
Ensure the translated C code behaves exactly like the original COBOL snippet.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
#define TITLE "CSV data manipulation" #define URL "http: #define _GNU_SOURCE #define bool int #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(","); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf("[Empty table]\n"); return ; } printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf("[|"); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf("%s\t|", content); } printf("]\n"); } printf("\n"); } int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { content = csv_get(old_csv, cur_col, cur_row); free(content); } else { } } } free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); return -1; } int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, "r"); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf("Unable to open %s for reading.", filename); return -1; } int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, "w"); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, ((col == csv->cols-1) ? "" : csv->delim) ); } fprintf(fp, "\n"); } fclose(fp); return 0; } int main(int argc, char ** argv) { CSV * csv; printf("%s\n%s\n\n",TITLE, URL); csv = csv_create(0, 0); csv_open(csv, "fixtures/csv-data-manipulation.csv"); csv_display(csv); csv_set(csv, 0, 0, "Column0"); csv_set(csv, 1, 1, "100"); csv_set(csv, 2, 2, "200"); csv_set(csv, 3, 3, "300"); csv_set(csv, 4, 4, "400"); csv_display(csv); csv_save(csv, "tmp/csv-data-manipulation.result.csv"); csv_destroy(csv); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
#define TITLE "CSV data manipulation" #define URL "http: #define _GNU_SOURCE #define bool int #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(","); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf("[Empty table]\n"); return ; } printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf("[|"); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf("%s\t|", content); } printf("]\n"); } printf("\n"); } int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { content = csv_get(old_csv, cur_col, cur_row); free(content); } else { } } } free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); return -1; } int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, "r"); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf("Unable to open %s for reading.", filename); return -1; } int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, "w"); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, ((col == csv->cols-1) ? "" : csv->delim) ); } fprintf(fp, "\n"); } fclose(fp); return 0; } int main(int argc, char ** argv) { CSV * csv; printf("%s\n%s\n\n",TITLE, URL); csv = csv_create(0, 0); csv_open(csv, "fixtures/csv-data-manipulation.csv"); csv_display(csv); csv_set(csv, 0, 0, "Column0"); csv_set(csv, 1, 1, "100"); csv_set(csv, 2, 2, "200"); csv_set(csv, 3, 3, "300"); csv_set(csv, 4, 4, "400"); csv_display(csv); csv_save(csv, "tmp/csv-data-manipulation.result.csv"); csv_destroy(csv); return 0; }
Please provide an equivalent version of this COBOL code in C#.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
using System.IO; using System.Linq; namespace CSV_data_manipulation { class Program { static void Main() { var input = File.ReadAllLines("test_in.csv"); var output = input.Select((line, i) => { if (i == 0) return line + ",SUM"; var sum = line.Split(',').Select(int.Parse).Sum(); return line + "," + sum; }).ToArray(); File.WriteAllLines("test_out.csv", output); } } }
Generate a C# translation of this COBOL snippet without changing its computational steps.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
using System.IO; using System.Linq; namespace CSV_data_manipulation { class Program { static void Main() { var input = File.ReadAllLines("test_in.csv"); var output = input.Select((line, i) => { if (i == 0) return line + ",SUM"; var sum = line.Split(',').Select(int.Parse).Sum(); return line + "," + sum; }).ToArray(); File.WriteAllLines("test_out.csv", output); } } }
Preserve the algorithm and functionality while converting the code from COBOL to C++.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) { std::ifstream file( filename ); clear(); if ( file.is_open() ) { open( file, delim ); return true; } return false; } void open( std::istream& istream, char delim = ',' ) { std::string line; clear(); while ( std::getline( istream, line ) ) { unsigned int nCol = 0; std::istringstream lineStream(line); std::string cell; while( std::getline( lineStream, cell, delim ) ) { m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); nCol++; } m_nCols = std::max( m_nCols, nCol ); m_nRows++; } } bool save( const char* pFile, char delim = ',' ) { std::ofstream ofile( pFile ); if ( ofile.is_open() ) { save( ofile ); return true; } return false; } void save( std::ostream& ostream, char delim = ',' ) { for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) { for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) { ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); if ( (nCol+1) < m_nCols ) { ostream << delim; } else { ostream << std::endl; } } } } void clear() { m_oData.clear(); m_nRows = m_nCols = 0; } std::string& operator()( unsigned int nCol, unsigned int nRow ) { m_nCols = std::max( m_nCols, nCol+1 ); m_nRows = std::max( m_nRows, nRow+1 ); return m_oData[std::make_pair(nCol, nRow)]; } inline unsigned int GetRows() { return m_nRows; } inline unsigned int GetCols() { return m_nCols; } private: inline std::string &trim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } private: std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData; unsigned int m_nCols; unsigned int m_nRows; }; int main() { CSV oCSV; oCSV.open( "test_in.csv" ); oCSV( 0, 0 ) = "Column0"; oCSV( 1, 1 ) = "100"; oCSV( 2, 2 ) = "200"; oCSV( 3, 3 ) = "300"; oCSV( 4, 4 ) = "400"; oCSV.save( "test_out.csv" ); return 0; }
Change the following COBOL code into C++ without altering its purpose.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) { std::ifstream file( filename ); clear(); if ( file.is_open() ) { open( file, delim ); return true; } return false; } void open( std::istream& istream, char delim = ',' ) { std::string line; clear(); while ( std::getline( istream, line ) ) { unsigned int nCol = 0; std::istringstream lineStream(line); std::string cell; while( std::getline( lineStream, cell, delim ) ) { m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); nCol++; } m_nCols = std::max( m_nCols, nCol ); m_nRows++; } } bool save( const char* pFile, char delim = ',' ) { std::ofstream ofile( pFile ); if ( ofile.is_open() ) { save( ofile ); return true; } return false; } void save( std::ostream& ostream, char delim = ',' ) { for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) { for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) { ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); if ( (nCol+1) < m_nCols ) { ostream << delim; } else { ostream << std::endl; } } } } void clear() { m_oData.clear(); m_nRows = m_nCols = 0; } std::string& operator()( unsigned int nCol, unsigned int nRow ) { m_nCols = std::max( m_nCols, nCol+1 ); m_nRows = std::max( m_nRows, nRow+1 ); return m_oData[std::make_pair(nCol, nRow)]; } inline unsigned int GetRows() { return m_nRows; } inline unsigned int GetCols() { return m_nCols; } private: inline std::string &trim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } private: std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData; unsigned int m_nCols; unsigned int m_nRows; }; int main() { CSV oCSV; oCSV.open( "test_in.csv" ); oCSV( 0, 0 ) = "Column0"; oCSV( 1, 1 ) = "100"; oCSV( 2, 2 ) = "200"; oCSV( 3, 3 ) = "300"; oCSV( 4, 4 ) = "400"; oCSV.save( "test_out.csv" ); return 0; }
Rewrite the snippet below in Java so it works the same as the original COBOL code.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class CSV { private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows; public void open(File file) throws FileNotFoundException, IOException { open(file, ','); } public void open(File file, char delimiter) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); scanner.useDelimiter(Character.toString(delimiter)); clear(); while(scanner.hasNextLine()) { String[] values = scanner.nextLine().split(Character.toString(delimiter)); int col = 0; for ( String value: values ) { _map.put(new Point(col, _rows), value); _cols = Math.max(_cols, ++col); } _rows++; } scanner.close(); } public void save(File file) throws IOException { save(file, ','); } public void save(File file, char delimiter) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Point key = new Point(col, row); if (_map.containsKey(key)) { bw.write(_map.get(key)); } if ((col + 1) < _cols) { bw.write(delimiter); } } bw.newLine(); } bw.flush(); bw.close(); } public String get(int col, int row) { String val = ""; Point key = new Point(col, row); if (_map.containsKey(key)) { val = _map.get(key); } return val; } public void put(int col, int row, String value) { _map.put(new Point(col, row), value); _cols = Math.max(_cols, col+1); _rows = Math.max(_rows, row+1); } public void clear() { _map.clear(); _cols = 0; _rows = 0; } public int rows() { return _rows; } public int cols() { return _cols; } public static void main(String[] args) { try { CSV csv = new CSV(); csv.open(new File("test_in.csv")); csv.put(0, 0, "Column0"); csv.put(1, 1, "100"); csv.put(2, 2, "200"); csv.put(3, 3, "300"); csv.put(4, 4, "400"); csv.save(new File("test_out.csv")); } catch (Exception e) { } } }
Change the programming language of this snippet from COBOL to Java without modifying what it does.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class CSV { private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows; public void open(File file) throws FileNotFoundException, IOException { open(file, ','); } public void open(File file, char delimiter) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); scanner.useDelimiter(Character.toString(delimiter)); clear(); while(scanner.hasNextLine()) { String[] values = scanner.nextLine().split(Character.toString(delimiter)); int col = 0; for ( String value: values ) { _map.put(new Point(col, _rows), value); _cols = Math.max(_cols, ++col); } _rows++; } scanner.close(); } public void save(File file) throws IOException { save(file, ','); } public void save(File file, char delimiter) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Point key = new Point(col, row); if (_map.containsKey(key)) { bw.write(_map.get(key)); } if ((col + 1) < _cols) { bw.write(delimiter); } } bw.newLine(); } bw.flush(); bw.close(); } public String get(int col, int row) { String val = ""; Point key = new Point(col, row); if (_map.containsKey(key)) { val = _map.get(key); } return val; } public void put(int col, int row, String value) { _map.put(new Point(col, row), value); _cols = Math.max(_cols, col+1); _rows = Math.max(_rows, row+1); } public void clear() { _map.clear(); _cols = 0; _rows = 0; } public int rows() { return _rows; } public int cols() { return _cols; } public static void main(String[] args) { try { CSV csv = new CSV(); csv.open(new File("test_in.csv")); csv.put(0, 0, "Column0"); csv.put(1, 1, "100"); csv.put(2, 2, "200"); csv.put(3, 3, "300"); csv.put(4, 4, "400"); csv.save(new File("test_out.csv")); } catch (Exception e) { } } }
Change the programming language of this snippet from COBOL to Python without modifying what it does.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
import fileinput changerow, changecolumn, changevalue = 2, 4, '"Spam"' with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue line = ','.join(fields) + '\n' print(line, end='')
Produce a language-to-language conversion: from COBOL to Python, same semantics.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
import fileinput changerow, changecolumn, changevalue = 2, 4, '"Spam"' with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue line = ','.join(fields) + '\n' print(line, end='')
Translate this program into VB but keep the logic exactly as in COBOL.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Produce a language-to-language conversion: from COBOL to VB, same semantics.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Convert this COBOL block to Go, preserving its control flow and logic.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
Change the programming language of this snippet from COBOL to Go without modifying what it does.
IDENTIFICATION DIVISION. PROGRAM-ID. CSV. AUTHOR. Bill Gunshannon. INSTALLATION. Home. DATE-WRITTEN. 19 December 2021. ************************************************************ ** Program Abstract: ** CSVs are something COBOL does pretty well. ** The commented out CONCATENATE statements are a ** second method other than the STRING method. ************************************************************ ENVIRONMENT DIVISION. CONFIGURATION SECTION. REPOSITORY. FUNCTION ALL INTRINSIC. INPUT-OUTPUT SECTION. FILE-CONTROL. SELECT CSV-File ASSIGN TO "csv.txt" ORGANIZATION IS LINE SEQUENTIAL. SELECT Out-File ASSIGN TO "new.csv.txt" ORGANIZATION IS LINE SEQUENTIAL. DATA DIVISION. FILE SECTION. FD CSV-File DATA RECORD IS CSV-Record. 01 CSV-Record. 05 Field1 PIC X(64). FD Out-File DATA RECORD IS Out-Line. 01 Out-Line PIC X(80). WORKING-STORAGE SECTION. 01 Eof PIC X VALUE 'F'. 01 CSV-Data. 05 CSV-Col1 PIC 9(5). 05 CSV-Col2 PIC 9(5). 05 CSV-Col3 PIC 9(5). 05 CSV-Col4 PIC 9(5). 05 CSV-Col5 PIC 9(5). 01 CSV-Sum PIC ZZZ9. 01 CSV-Sum-Alpha REDEFINES CSV-Sum PIC X(4). PROCEDURE DIVISION. Main-Program. OPEN INPUT CSV-File OPEN OUTPUT Out-File PERFORM Read-a-Record PERFORM Build-Header PERFORM UNTIL Eof = 'T' PERFORM Read-a-Record IF Eof NOT EQUAL 'T' PERFORM Process-a-Record END-PERFORM CLOSE CSV-File CLOSE Out-File STOP RUN. Read-a-Record. READ CSV-File AT END MOVE 'T' TO Eof END-READ. Build-Header. ** MOVE CONCATENATE(TRIM(CSV-Record), ",SUM" ** TO Out-Line. STRING TRIM(CSV-Record), ",SUM" INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. Process-a-Record. UNSTRING CSV-Record DELIMITED BY ',' INTO CSV-Col1 CSV-Col2 CSV-Col3 CSV-Col4 CSV-Col5. COMPUTE CSV-Sum = CSV-Col1 + CSV-Col2 + CSV-Col3 + CSV-Col4 + CSV-Col5. ** MOVE CONCATENATE(TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha)) ** TO Out-Line. STRING TRIM(CSV-Record), "," TRIM(CSV-Sum-Alpha) INTO Out-Line. WRITE Out-Line. MOVE SPACES TO Out-Line. END-PROGRAM.
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
Write the same algorithm in C as shown in this REXX implementation.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
#define TITLE "CSV data manipulation" #define URL "http: #define _GNU_SOURCE #define bool int #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(","); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf("[Empty table]\n"); return ; } printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf("[|"); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf("%s\t|", content); } printf("]\n"); } printf("\n"); } int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { content = csv_get(old_csv, cur_col, cur_row); free(content); } else { } } } free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); return -1; } int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, "r"); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf("Unable to open %s for reading.", filename); return -1; } int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, "w"); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, ((col == csv->cols-1) ? "" : csv->delim) ); } fprintf(fp, "\n"); } fclose(fp); return 0; } int main(int argc, char ** argv) { CSV * csv; printf("%s\n%s\n\n",TITLE, URL); csv = csv_create(0, 0); csv_open(csv, "fixtures/csv-data-manipulation.csv"); csv_display(csv); csv_set(csv, 0, 0, "Column0"); csv_set(csv, 1, 1, "100"); csv_set(csv, 2, 2, "200"); csv_set(csv, 3, 3, "300"); csv_set(csv, 4, 4, "400"); csv_display(csv); csv_save(csv, "tmp/csv-data-manipulation.result.csv"); csv_destroy(csv); return 0; }
Generate an equivalent C version of this REXX code.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
#define TITLE "CSV data manipulation" #define URL "http: #define _GNU_SOURCE #define bool int #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(","); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf("[Empty table]\n"); return ; } printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf("[|"); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf("%s\t|", content); } printf("]\n"); } printf("\n"); } int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { content = csv_get(old_csv, cur_col, cur_row); free(content); } else { } } } free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); return -1; } int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, "r"); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf("Unable to open %s for reading.", filename); return -1; } int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, "w"); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, ((col == csv->cols-1) ? "" : csv->delim) ); } fprintf(fp, "\n"); } fclose(fp); return 0; } int main(int argc, char ** argv) { CSV * csv; printf("%s\n%s\n\n",TITLE, URL); csv = csv_create(0, 0); csv_open(csv, "fixtures/csv-data-manipulation.csv"); csv_display(csv); csv_set(csv, 0, 0, "Column0"); csv_set(csv, 1, 1, "100"); csv_set(csv, 2, 2, "200"); csv_set(csv, 3, 3, "300"); csv_set(csv, 4, 4, "400"); csv_display(csv); csv_save(csv, "tmp/csv-data-manipulation.result.csv"); csv_destroy(csv); return 0; }
Generate a C# translation of this REXX snippet without changing its computational steps.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
using System.IO; using System.Linq; namespace CSV_data_manipulation { class Program { static void Main() { var input = File.ReadAllLines("test_in.csv"); var output = input.Select((line, i) => { if (i == 0) return line + ",SUM"; var sum = line.Split(',').Select(int.Parse).Sum(); return line + "," + sum; }).ToArray(); File.WriteAllLines("test_out.csv", output); } } }
Change the programming language of this snippet from REXX to C# without modifying what it does.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
using System.IO; using System.Linq; namespace CSV_data_manipulation { class Program { static void Main() { var input = File.ReadAllLines("test_in.csv"); var output = input.Select((line, i) => { if (i == 0) return line + ",SUM"; var sum = line.Split(',').Select(int.Parse).Sum(); return line + "," + sum; }).ToArray(); File.WriteAllLines("test_out.csv", output); } } }
Port the provided REXX code into C++ while preserving the original functionality.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) { std::ifstream file( filename ); clear(); if ( file.is_open() ) { open( file, delim ); return true; } return false; } void open( std::istream& istream, char delim = ',' ) { std::string line; clear(); while ( std::getline( istream, line ) ) { unsigned int nCol = 0; std::istringstream lineStream(line); std::string cell; while( std::getline( lineStream, cell, delim ) ) { m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); nCol++; } m_nCols = std::max( m_nCols, nCol ); m_nRows++; } } bool save( const char* pFile, char delim = ',' ) { std::ofstream ofile( pFile ); if ( ofile.is_open() ) { save( ofile ); return true; } return false; } void save( std::ostream& ostream, char delim = ',' ) { for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) { for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) { ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); if ( (nCol+1) < m_nCols ) { ostream << delim; } else { ostream << std::endl; } } } } void clear() { m_oData.clear(); m_nRows = m_nCols = 0; } std::string& operator()( unsigned int nCol, unsigned int nRow ) { m_nCols = std::max( m_nCols, nCol+1 ); m_nRows = std::max( m_nRows, nRow+1 ); return m_oData[std::make_pair(nCol, nRow)]; } inline unsigned int GetRows() { return m_nRows; } inline unsigned int GetCols() { return m_nCols; } private: inline std::string &trim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } private: std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData; unsigned int m_nCols; unsigned int m_nRows; }; int main() { CSV oCSV; oCSV.open( "test_in.csv" ); oCSV( 0, 0 ) = "Column0"; oCSV( 1, 1 ) = "100"; oCSV( 2, 2 ) = "200"; oCSV( 3, 3 ) = "300"; oCSV( 4, 4 ) = "400"; oCSV.save( "test_out.csv" ); return 0; }
Convert this REXX snippet to C++ and keep its semantics consistent.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) { std::ifstream file( filename ); clear(); if ( file.is_open() ) { open( file, delim ); return true; } return false; } void open( std::istream& istream, char delim = ',' ) { std::string line; clear(); while ( std::getline( istream, line ) ) { unsigned int nCol = 0; std::istringstream lineStream(line); std::string cell; while( std::getline( lineStream, cell, delim ) ) { m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); nCol++; } m_nCols = std::max( m_nCols, nCol ); m_nRows++; } } bool save( const char* pFile, char delim = ',' ) { std::ofstream ofile( pFile ); if ( ofile.is_open() ) { save( ofile ); return true; } return false; } void save( std::ostream& ostream, char delim = ',' ) { for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) { for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) { ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); if ( (nCol+1) < m_nCols ) { ostream << delim; } else { ostream << std::endl; } } } } void clear() { m_oData.clear(); m_nRows = m_nCols = 0; } std::string& operator()( unsigned int nCol, unsigned int nRow ) { m_nCols = std::max( m_nCols, nCol+1 ); m_nRows = std::max( m_nRows, nRow+1 ); return m_oData[std::make_pair(nCol, nRow)]; } inline unsigned int GetRows() { return m_nRows; } inline unsigned int GetCols() { return m_nCols; } private: inline std::string &trim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } private: std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData; unsigned int m_nCols; unsigned int m_nRows; }; int main() { CSV oCSV; oCSV.open( "test_in.csv" ); oCSV( 0, 0 ) = "Column0"; oCSV( 1, 1 ) = "100"; oCSV( 2, 2 ) = "200"; oCSV( 3, 3 ) = "300"; oCSV( 4, 4 ) = "400"; oCSV.save( "test_out.csv" ); return 0; }
Translate the given REXX code snippet into Java without altering its behavior.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class CSV { private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows; public void open(File file) throws FileNotFoundException, IOException { open(file, ','); } public void open(File file, char delimiter) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); scanner.useDelimiter(Character.toString(delimiter)); clear(); while(scanner.hasNextLine()) { String[] values = scanner.nextLine().split(Character.toString(delimiter)); int col = 0; for ( String value: values ) { _map.put(new Point(col, _rows), value); _cols = Math.max(_cols, ++col); } _rows++; } scanner.close(); } public void save(File file) throws IOException { save(file, ','); } public void save(File file, char delimiter) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Point key = new Point(col, row); if (_map.containsKey(key)) { bw.write(_map.get(key)); } if ((col + 1) < _cols) { bw.write(delimiter); } } bw.newLine(); } bw.flush(); bw.close(); } public String get(int col, int row) { String val = ""; Point key = new Point(col, row); if (_map.containsKey(key)) { val = _map.get(key); } return val; } public void put(int col, int row, String value) { _map.put(new Point(col, row), value); _cols = Math.max(_cols, col+1); _rows = Math.max(_rows, row+1); } public void clear() { _map.clear(); _cols = 0; _rows = 0; } public int rows() { return _rows; } public int cols() { return _cols; } public static void main(String[] args) { try { CSV csv = new CSV(); csv.open(new File("test_in.csv")); csv.put(0, 0, "Column0"); csv.put(1, 1, "100"); csv.put(2, 2, "200"); csv.put(3, 3, "300"); csv.put(4, 4, "400"); csv.save(new File("test_out.csv")); } catch (Exception e) { } } }
Rewrite the snippet below in Java so it works the same as the original REXX code.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class CSV { private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows; public void open(File file) throws FileNotFoundException, IOException { open(file, ','); } public void open(File file, char delimiter) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); scanner.useDelimiter(Character.toString(delimiter)); clear(); while(scanner.hasNextLine()) { String[] values = scanner.nextLine().split(Character.toString(delimiter)); int col = 0; for ( String value: values ) { _map.put(new Point(col, _rows), value); _cols = Math.max(_cols, ++col); } _rows++; } scanner.close(); } public void save(File file) throws IOException { save(file, ','); } public void save(File file, char delimiter) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Point key = new Point(col, row); if (_map.containsKey(key)) { bw.write(_map.get(key)); } if ((col + 1) < _cols) { bw.write(delimiter); } } bw.newLine(); } bw.flush(); bw.close(); } public String get(int col, int row) { String val = ""; Point key = new Point(col, row); if (_map.containsKey(key)) { val = _map.get(key); } return val; } public void put(int col, int row, String value) { _map.put(new Point(col, row), value); _cols = Math.max(_cols, col+1); _rows = Math.max(_rows, row+1); } public void clear() { _map.clear(); _cols = 0; _rows = 0; } public int rows() { return _rows; } public int cols() { return _cols; } public static void main(String[] args) { try { CSV csv = new CSV(); csv.open(new File("test_in.csv")); csv.put(0, 0, "Column0"); csv.put(1, 1, "100"); csv.put(2, 2, "200"); csv.put(3, 3, "300"); csv.put(4, 4, "400"); csv.save(new File("test_out.csv")); } catch (Exception e) { } } }
Translate this program into Python but keep the logic exactly as in REXX.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
import fileinput changerow, changecolumn, changevalue = 2, 4, '"Spam"' with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue line = ','.join(fields) + '\n' print(line, end='')
Write a version of this REXX function in Python with identical behavior.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
import fileinput changerow, changecolumn, changevalue = 2, 4, '"Spam"' with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue line = ','.join(fields) + '\n' print(line, end='')
Generate a VB translation of this REXX snippet without changing its computational steps.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Translate this program into VB but keep the logic exactly as in REXX.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Write the same code in Go as shown below in REXX.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
Rewrite the snippet below in Go so it works the same as the original REXX code.
options replace format comments java crossref symbols import org.apache.commons.csv. -- ============================================================================= class RCsv public final properties private constant NL = String System.getProperty("line.separator") COL_NAME_SUM = String 'SUM, "integers"' CSV_IFILE = 'data/csvtest_in.csv' CSV_OFILE = 'data/csvtest_sumRexx.csv' -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static Arg = Rexx(args) iCvs = Reader null oCvs = Writer null parse arg ifile ofile . if ifile = '', ifile = '.' then ifile = CSV_IFILE if ofile = '', ofile = '.' then ofile = CSV_OFILE say textFileContentsToString(ifile) do iCvs = BufferedReader(FileReader(ifile)) oCvs = BufferedWriter(FileWriter(ofile)) processCsv(iCvs, oCvs); catch ex = IOException ex.printStackTrace(); finally do if iCvs \= null then iCvs.close() if oCvs \= null then oCvs.close() catch ex = IOException ex.printStackTrace() end end say textFileContentsToString(ofile) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method processCsv(iCvs = Reader, oCvs = Writer) public static binary signals IOException printer = CSVPrinter null do printer = CSVPrinter(oCvs, CSVFormat.DEFAULT.withRecordSeparator(NL)) oCvsHeaders = java.util.List oCvsRecord = java.util.List records = CSVFormat.DEFAULT.withHeader(String[0]).parse(iCvs) irHeader = records.getHeaderMap() oCvsHeaders = ArrayList(Arrays.asList((irHeader.keySet()).toArray(String[0]))) oCvsHeaders.add(COL_NAME_SUM) printer.printRecord(oCvsHeaders) recordIterator = records.iterator() record = CSVRecord loop while recordIterator.hasNext() record = CSVRecord recordIterator.next() oCvsRecord = record2list(record, oCvsHeaders) printer.printRecord(oCvsRecord) end finally if printer \= null then printer.close() end return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method record2list(record = CSVRecord, oCvsHeaders = java.util.List) private static binary returns java.util.List cvsRecord = java.util.List rMap = record.toMap() recNo = record.getRecordNumber() rMap = alterRecord(rMap, recNo) sum = summation(record.iterator()) rMap.put(COL_NAME_SUM, sum) cvsRecord = ArrayList() loop ci = 0 to oCvsHeaders.size() - 1 key = oCvsHeaders.get(ci) cvsRecord.add(rMap.get(key)) end ci return cvsRecord -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method alterRecord(rMap = Map, recNo = long) private static binary returns Map rv = int rg = Random(recNo) rv = rg.nextInt(50) ks = rMap.keySet().toArray(String[0]) ix = rg.nextInt(ks.length) yv = long 0 ky = ks[ix]; xv = String rMap.get(ky) if xv \= null & xv.length() > 0 then do yv = Long.valueOf(xv).longValue() + rv rMap.put(ks[ix], String.valueOf(yv)) end return rMap -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method summation(iColumn = Iterator) private static sum = 0 loop while iColumn.hasNext() nv = Rexx(String iColumn.next()) if nv = null, nv.length() = 0, \nv.datatype('n') then nv = 0 sum = sum + nv end return sum -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method textFileContentsToString(filename) private static lineOut = '' fs = Scanner null do fs = Scanner(File(filename)) lineOut = lineout || filename || NL loop while fs.hasNextLine() line = fs.nextLine() lineOut = lineout || line || NL end catch ex = FileNotFoundException ex.printStackTrace() finally if fs \= null then fs.close() end return lineOut
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
Ensure the translated C code behaves exactly like the original Ruby snippet.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
#define TITLE "CSV data manipulation" #define URL "http: #define _GNU_SOURCE #define bool int #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(","); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf("[Empty table]\n"); return ; } printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf("[|"); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf("%s\t|", content); } printf("]\n"); } printf("\n"); } int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { content = csv_get(old_csv, cur_col, cur_row); free(content); } else { } } } free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); return -1; } int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, "r"); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf("Unable to open %s for reading.", filename); return -1; } int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, "w"); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, ((col == csv->cols-1) ? "" : csv->delim) ); } fprintf(fp, "\n"); } fclose(fp); return 0; } int main(int argc, char ** argv) { CSV * csv; printf("%s\n%s\n\n",TITLE, URL); csv = csv_create(0, 0); csv_open(csv, "fixtures/csv-data-manipulation.csv"); csv_display(csv); csv_set(csv, 0, 0, "Column0"); csv_set(csv, 1, 1, "100"); csv_set(csv, 2, 2, "200"); csv_set(csv, 3, 3, "300"); csv_set(csv, 4, 4, "400"); csv_display(csv); csv_save(csv, "tmp/csv-data-manipulation.result.csv"); csv_destroy(csv); return 0; }
Keep all operations the same but rewrite the snippet in C.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
#define TITLE "CSV data manipulation" #define URL "http: #define _GNU_SOURCE #define bool int #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(","); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf("[Empty table]\n"); return ; } printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf("[|"); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf("%s\t|", content); } printf("]\n"); } printf("\n"); } int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { content = csv_get(old_csv, cur_col, cur_row); free(content); } else { } } } free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); return -1; } int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, "r"); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf("Unable to open %s for reading.", filename); return -1; } int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, "w"); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, ((col == csv->cols-1) ? "" : csv->delim) ); } fprintf(fp, "\n"); } fclose(fp); return 0; } int main(int argc, char ** argv) { CSV * csv; printf("%s\n%s\n\n",TITLE, URL); csv = csv_create(0, 0); csv_open(csv, "fixtures/csv-data-manipulation.csv"); csv_display(csv); csv_set(csv, 0, 0, "Column0"); csv_set(csv, 1, 1, "100"); csv_set(csv, 2, 2, "200"); csv_set(csv, 3, 3, "300"); csv_set(csv, 4, 4, "400"); csv_display(csv); csv_save(csv, "tmp/csv-data-manipulation.result.csv"); csv_destroy(csv); return 0; }
Rewrite the snippet below in C# so it works the same as the original Ruby code.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
using System.IO; using System.Linq; namespace CSV_data_manipulation { class Program { static void Main() { var input = File.ReadAllLines("test_in.csv"); var output = input.Select((line, i) => { if (i == 0) return line + ",SUM"; var sum = line.Split(',').Select(int.Parse).Sum(); return line + "," + sum; }).ToArray(); File.WriteAllLines("test_out.csv", output); } } }
Convert this Ruby snippet to C# and keep its semantics consistent.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
using System.IO; using System.Linq; namespace CSV_data_manipulation { class Program { static void Main() { var input = File.ReadAllLines("test_in.csv"); var output = input.Select((line, i) => { if (i == 0) return line + ",SUM"; var sum = line.Split(',').Select(int.Parse).Sum(); return line + "," + sum; }).ToArray(); File.WriteAllLines("test_out.csv", output); } } }
Write the same code in C++ as shown below in Ruby.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) { std::ifstream file( filename ); clear(); if ( file.is_open() ) { open( file, delim ); return true; } return false; } void open( std::istream& istream, char delim = ',' ) { std::string line; clear(); while ( std::getline( istream, line ) ) { unsigned int nCol = 0; std::istringstream lineStream(line); std::string cell; while( std::getline( lineStream, cell, delim ) ) { m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); nCol++; } m_nCols = std::max( m_nCols, nCol ); m_nRows++; } } bool save( const char* pFile, char delim = ',' ) { std::ofstream ofile( pFile ); if ( ofile.is_open() ) { save( ofile ); return true; } return false; } void save( std::ostream& ostream, char delim = ',' ) { for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) { for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) { ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); if ( (nCol+1) < m_nCols ) { ostream << delim; } else { ostream << std::endl; } } } } void clear() { m_oData.clear(); m_nRows = m_nCols = 0; } std::string& operator()( unsigned int nCol, unsigned int nRow ) { m_nCols = std::max( m_nCols, nCol+1 ); m_nRows = std::max( m_nRows, nRow+1 ); return m_oData[std::make_pair(nCol, nRow)]; } inline unsigned int GetRows() { return m_nRows; } inline unsigned int GetCols() { return m_nCols; } private: inline std::string &trim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } private: std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData; unsigned int m_nCols; unsigned int m_nRows; }; int main() { CSV oCSV; oCSV.open( "test_in.csv" ); oCSV( 0, 0 ) = "Column0"; oCSV( 1, 1 ) = "100"; oCSV( 2, 2 ) = "200"; oCSV( 3, 3 ) = "300"; oCSV( 4, 4 ) = "400"; oCSV.save( "test_out.csv" ); return 0; }
Transform the following Ruby implementation into C++, maintaining the same output and logic.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) { std::ifstream file( filename ); clear(); if ( file.is_open() ) { open( file, delim ); return true; } return false; } void open( std::istream& istream, char delim = ',' ) { std::string line; clear(); while ( std::getline( istream, line ) ) { unsigned int nCol = 0; std::istringstream lineStream(line); std::string cell; while( std::getline( lineStream, cell, delim ) ) { m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); nCol++; } m_nCols = std::max( m_nCols, nCol ); m_nRows++; } } bool save( const char* pFile, char delim = ',' ) { std::ofstream ofile( pFile ); if ( ofile.is_open() ) { save( ofile ); return true; } return false; } void save( std::ostream& ostream, char delim = ',' ) { for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) { for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) { ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); if ( (nCol+1) < m_nCols ) { ostream << delim; } else { ostream << std::endl; } } } } void clear() { m_oData.clear(); m_nRows = m_nCols = 0; } std::string& operator()( unsigned int nCol, unsigned int nRow ) { m_nCols = std::max( m_nCols, nCol+1 ); m_nRows = std::max( m_nRows, nRow+1 ); return m_oData[std::make_pair(nCol, nRow)]; } inline unsigned int GetRows() { return m_nRows; } inline unsigned int GetCols() { return m_nCols; } private: inline std::string &trim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } private: std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData; unsigned int m_nCols; unsigned int m_nRows; }; int main() { CSV oCSV; oCSV.open( "test_in.csv" ); oCSV( 0, 0 ) = "Column0"; oCSV( 1, 1 ) = "100"; oCSV( 2, 2 ) = "200"; oCSV( 3, 3 ) = "300"; oCSV( 4, 4 ) = "400"; oCSV.save( "test_out.csv" ); return 0; }
Ensure the translated Java code behaves exactly like the original Ruby snippet.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class CSV { private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows; public void open(File file) throws FileNotFoundException, IOException { open(file, ','); } public void open(File file, char delimiter) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); scanner.useDelimiter(Character.toString(delimiter)); clear(); while(scanner.hasNextLine()) { String[] values = scanner.nextLine().split(Character.toString(delimiter)); int col = 0; for ( String value: values ) { _map.put(new Point(col, _rows), value); _cols = Math.max(_cols, ++col); } _rows++; } scanner.close(); } public void save(File file) throws IOException { save(file, ','); } public void save(File file, char delimiter) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Point key = new Point(col, row); if (_map.containsKey(key)) { bw.write(_map.get(key)); } if ((col + 1) < _cols) { bw.write(delimiter); } } bw.newLine(); } bw.flush(); bw.close(); } public String get(int col, int row) { String val = ""; Point key = new Point(col, row); if (_map.containsKey(key)) { val = _map.get(key); } return val; } public void put(int col, int row, String value) { _map.put(new Point(col, row), value); _cols = Math.max(_cols, col+1); _rows = Math.max(_rows, row+1); } public void clear() { _map.clear(); _cols = 0; _rows = 0; } public int rows() { return _rows; } public int cols() { return _cols; } public static void main(String[] args) { try { CSV csv = new CSV(); csv.open(new File("test_in.csv")); csv.put(0, 0, "Column0"); csv.put(1, 1, "100"); csv.put(2, 2, "200"); csv.put(3, 3, "300"); csv.put(4, 4, "400"); csv.save(new File("test_out.csv")); } catch (Exception e) { } } }
Port the provided Ruby code into Java while preserving the original functionality.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class CSV { private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows; public void open(File file) throws FileNotFoundException, IOException { open(file, ','); } public void open(File file, char delimiter) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); scanner.useDelimiter(Character.toString(delimiter)); clear(); while(scanner.hasNextLine()) { String[] values = scanner.nextLine().split(Character.toString(delimiter)); int col = 0; for ( String value: values ) { _map.put(new Point(col, _rows), value); _cols = Math.max(_cols, ++col); } _rows++; } scanner.close(); } public void save(File file) throws IOException { save(file, ','); } public void save(File file, char delimiter) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Point key = new Point(col, row); if (_map.containsKey(key)) { bw.write(_map.get(key)); } if ((col + 1) < _cols) { bw.write(delimiter); } } bw.newLine(); } bw.flush(); bw.close(); } public String get(int col, int row) { String val = ""; Point key = new Point(col, row); if (_map.containsKey(key)) { val = _map.get(key); } return val; } public void put(int col, int row, String value) { _map.put(new Point(col, row), value); _cols = Math.max(_cols, col+1); _rows = Math.max(_rows, row+1); } public void clear() { _map.clear(); _cols = 0; _rows = 0; } public int rows() { return _rows; } public int cols() { return _cols; } public static void main(String[] args) { try { CSV csv = new CSV(); csv.open(new File("test_in.csv")); csv.put(0, 0, "Column0"); csv.put(1, 1, "100"); csv.put(2, 2, "200"); csv.put(3, 3, "300"); csv.put(4, 4, "400"); csv.save(new File("test_out.csv")); } catch (Exception e) { } } }
Convert this Ruby block to Python, preserving its control flow and logic.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
import fileinput changerow, changecolumn, changevalue = 2, 4, '"Spam"' with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue line = ','.join(fields) + '\n' print(line, end='')
Change the programming language of this snippet from Ruby to Python without modifying what it does.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
import fileinput changerow, changecolumn, changevalue = 2, 4, '"Spam"' with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue line = ','.join(fields) + '\n' print(line, end='')
Keep all operations the same but rewrite the snippet in VB.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Produce a functionally identical VB code for the snippet given in Ruby.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Convert this Ruby block to Go, preserving its control flow and logic.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
Convert the following code from Ruby to Go, ensuring the logic remains intact.
require 'csv' ar = CSV.table("test.csv").to_a ar.first << "SUM" ar[1..-1].each{|row| row << row.sum} CSV.open("out.csv", 'w') do |csv| ar.each{|line| csv << line} end
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
Write the same code in C as shown below in Scala.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
#define TITLE "CSV data manipulation" #define URL "http: #define _GNU_SOURCE #define bool int #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(","); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf("[Empty table]\n"); return ; } printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf("[|"); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf("%s\t|", content); } printf("]\n"); } printf("\n"); } int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { content = csv_get(old_csv, cur_col, cur_row); free(content); } else { } } } free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); return -1; } int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, "r"); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf("Unable to open %s for reading.", filename); return -1; } int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, "w"); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, ((col == csv->cols-1) ? "" : csv->delim) ); } fprintf(fp, "\n"); } fclose(fp); return 0; } int main(int argc, char ** argv) { CSV * csv; printf("%s\n%s\n\n",TITLE, URL); csv = csv_create(0, 0); csv_open(csv, "fixtures/csv-data-manipulation.csv"); csv_display(csv); csv_set(csv, 0, 0, "Column0"); csv_set(csv, 1, 1, "100"); csv_set(csv, 2, 2, "200"); csv_set(csv, 3, 3, "300"); csv_set(csv, 4, 4, "400"); csv_display(csv); csv_save(csv, "tmp/csv-data-manipulation.result.csv"); csv_destroy(csv); return 0; }
Change the following Scala code into C without altering its purpose.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
#define TITLE "CSV data manipulation" #define URL "http: #define _GNU_SOURCE #define bool int #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(","); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf("[Empty table]\n"); return ; } printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf("[|"); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf("%s\t|", content); } printf("]\n"); } printf("\n"); } int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { content = csv_get(old_csv, cur_col, cur_row); free(content); } else { } } } free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); return -1; } int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, "r"); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf("Unable to open %s for reading.", filename); return -1; } int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, "w"); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, ((col == csv->cols-1) ? "" : csv->delim) ); } fprintf(fp, "\n"); } fclose(fp); return 0; } int main(int argc, char ** argv) { CSV * csv; printf("%s\n%s\n\n",TITLE, URL); csv = csv_create(0, 0); csv_open(csv, "fixtures/csv-data-manipulation.csv"); csv_display(csv); csv_set(csv, 0, 0, "Column0"); csv_set(csv, 1, 1, "100"); csv_set(csv, 2, 2, "200"); csv_set(csv, 3, 3, "300"); csv_set(csv, 4, 4, "400"); csv_display(csv); csv_save(csv, "tmp/csv-data-manipulation.result.csv"); csv_destroy(csv); return 0; }
Change the programming language of this snippet from Scala to C# without modifying what it does.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
using System.IO; using System.Linq; namespace CSV_data_manipulation { class Program { static void Main() { var input = File.ReadAllLines("test_in.csv"); var output = input.Select((line, i) => { if (i == 0) return line + ",SUM"; var sum = line.Split(',').Select(int.Parse).Sum(); return line + "," + sum; }).ToArray(); File.WriteAllLines("test_out.csv", output); } } }
Write the same code in C# as shown below in Scala.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
using System.IO; using System.Linq; namespace CSV_data_manipulation { class Program { static void Main() { var input = File.ReadAllLines("test_in.csv"); var output = input.Select((line, i) => { if (i == 0) return line + ",SUM"; var sum = line.Split(',').Select(int.Parse).Sum(); return line + "," + sum; }).ToArray(); File.WriteAllLines("test_out.csv", output); } } }
Port the following code from Scala to C++ with equivalent syntax and logic.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) { std::ifstream file( filename ); clear(); if ( file.is_open() ) { open( file, delim ); return true; } return false; } void open( std::istream& istream, char delim = ',' ) { std::string line; clear(); while ( std::getline( istream, line ) ) { unsigned int nCol = 0; std::istringstream lineStream(line); std::string cell; while( std::getline( lineStream, cell, delim ) ) { m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); nCol++; } m_nCols = std::max( m_nCols, nCol ); m_nRows++; } } bool save( const char* pFile, char delim = ',' ) { std::ofstream ofile( pFile ); if ( ofile.is_open() ) { save( ofile ); return true; } return false; } void save( std::ostream& ostream, char delim = ',' ) { for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) { for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) { ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); if ( (nCol+1) < m_nCols ) { ostream << delim; } else { ostream << std::endl; } } } } void clear() { m_oData.clear(); m_nRows = m_nCols = 0; } std::string& operator()( unsigned int nCol, unsigned int nRow ) { m_nCols = std::max( m_nCols, nCol+1 ); m_nRows = std::max( m_nRows, nRow+1 ); return m_oData[std::make_pair(nCol, nRow)]; } inline unsigned int GetRows() { return m_nRows; } inline unsigned int GetCols() { return m_nCols; } private: inline std::string &trim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } private: std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData; unsigned int m_nCols; unsigned int m_nRows; }; int main() { CSV oCSV; oCSV.open( "test_in.csv" ); oCSV( 0, 0 ) = "Column0"; oCSV( 1, 1 ) = "100"; oCSV( 2, 2 ) = "200"; oCSV( 3, 3 ) = "300"; oCSV( 4, 4 ) = "400"; oCSV.save( "test_out.csv" ); return 0; }
Generate an equivalent C++ version of this Scala code.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) { std::ifstream file( filename ); clear(); if ( file.is_open() ) { open( file, delim ); return true; } return false; } void open( std::istream& istream, char delim = ',' ) { std::string line; clear(); while ( std::getline( istream, line ) ) { unsigned int nCol = 0; std::istringstream lineStream(line); std::string cell; while( std::getline( lineStream, cell, delim ) ) { m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); nCol++; } m_nCols = std::max( m_nCols, nCol ); m_nRows++; } } bool save( const char* pFile, char delim = ',' ) { std::ofstream ofile( pFile ); if ( ofile.is_open() ) { save( ofile ); return true; } return false; } void save( std::ostream& ostream, char delim = ',' ) { for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) { for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) { ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); if ( (nCol+1) < m_nCols ) { ostream << delim; } else { ostream << std::endl; } } } } void clear() { m_oData.clear(); m_nRows = m_nCols = 0; } std::string& operator()( unsigned int nCol, unsigned int nRow ) { m_nCols = std::max( m_nCols, nCol+1 ); m_nRows = std::max( m_nRows, nRow+1 ); return m_oData[std::make_pair(nCol, nRow)]; } inline unsigned int GetRows() { return m_nRows; } inline unsigned int GetCols() { return m_nCols; } private: inline std::string &trim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } private: std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData; unsigned int m_nCols; unsigned int m_nRows; }; int main() { CSV oCSV; oCSV.open( "test_in.csv" ); oCSV( 0, 0 ) = "Column0"; oCSV( 1, 1 ) = "100"; oCSV( 2, 2 ) = "200"; oCSV( 3, 3 ) = "300"; oCSV( 4, 4 ) = "400"; oCSV.save( "test_out.csv" ); return 0; }
Maintain the same structure and functionality when rewriting this code in Java.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class CSV { private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows; public void open(File file) throws FileNotFoundException, IOException { open(file, ','); } public void open(File file, char delimiter) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); scanner.useDelimiter(Character.toString(delimiter)); clear(); while(scanner.hasNextLine()) { String[] values = scanner.nextLine().split(Character.toString(delimiter)); int col = 0; for ( String value: values ) { _map.put(new Point(col, _rows), value); _cols = Math.max(_cols, ++col); } _rows++; } scanner.close(); } public void save(File file) throws IOException { save(file, ','); } public void save(File file, char delimiter) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Point key = new Point(col, row); if (_map.containsKey(key)) { bw.write(_map.get(key)); } if ((col + 1) < _cols) { bw.write(delimiter); } } bw.newLine(); } bw.flush(); bw.close(); } public String get(int col, int row) { String val = ""; Point key = new Point(col, row); if (_map.containsKey(key)) { val = _map.get(key); } return val; } public void put(int col, int row, String value) { _map.put(new Point(col, row), value); _cols = Math.max(_cols, col+1); _rows = Math.max(_rows, row+1); } public void clear() { _map.clear(); _cols = 0; _rows = 0; } public int rows() { return _rows; } public int cols() { return _cols; } public static void main(String[] args) { try { CSV csv = new CSV(); csv.open(new File("test_in.csv")); csv.put(0, 0, "Column0"); csv.put(1, 1, "100"); csv.put(2, 2, "200"); csv.put(3, 3, "300"); csv.put(4, 4, "400"); csv.save(new File("test_out.csv")); } catch (Exception e) { } } }
Port the provided Scala code into Java while preserving the original functionality.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class CSV { private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows; public void open(File file) throws FileNotFoundException, IOException { open(file, ','); } public void open(File file, char delimiter) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); scanner.useDelimiter(Character.toString(delimiter)); clear(); while(scanner.hasNextLine()) { String[] values = scanner.nextLine().split(Character.toString(delimiter)); int col = 0; for ( String value: values ) { _map.put(new Point(col, _rows), value); _cols = Math.max(_cols, ++col); } _rows++; } scanner.close(); } public void save(File file) throws IOException { save(file, ','); } public void save(File file, char delimiter) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Point key = new Point(col, row); if (_map.containsKey(key)) { bw.write(_map.get(key)); } if ((col + 1) < _cols) { bw.write(delimiter); } } bw.newLine(); } bw.flush(); bw.close(); } public String get(int col, int row) { String val = ""; Point key = new Point(col, row); if (_map.containsKey(key)) { val = _map.get(key); } return val; } public void put(int col, int row, String value) { _map.put(new Point(col, row), value); _cols = Math.max(_cols, col+1); _rows = Math.max(_rows, row+1); } public void clear() { _map.clear(); _cols = 0; _rows = 0; } public int rows() { return _rows; } public int cols() { return _cols; } public static void main(String[] args) { try { CSV csv = new CSV(); csv.open(new File("test_in.csv")); csv.put(0, 0, "Column0"); csv.put(1, 1, "100"); csv.put(2, 2, "200"); csv.put(3, 3, "300"); csv.put(4, 4, "400"); csv.save(new File("test_out.csv")); } catch (Exception e) { } } }
Ensure the translated Python code behaves exactly like the original Scala snippet.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
import fileinput changerow, changecolumn, changevalue = 2, 4, '"Spam"' with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue line = ','.join(fields) + '\n' print(line, end='')
Translate the given Scala code snippet into Python without altering its behavior.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
import fileinput changerow, changecolumn, changevalue = 2, 4, '"Spam"' with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue line = ','.join(fields) + '\n' print(line, end='')
Write a version of this Scala function in VB with identical behavior.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Change the programming language of this snippet from Scala to VB without modifying what it does.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Convert this Scala snippet to Go and keep its semantics consistent.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
Convert the following code from Scala to Go, ensuring the logic remains intact.
import java.io.File fun main(args: Array<String>) { val lines = File("example.csv").readLines().toMutableList() lines[0] += ",SUM" for (i in 1 until lines.size) { lines[i] += "," + lines[i].split(',').sumBy { it.toInt() } } val text = lines.joinToString("\n") File("example2.csv").writeText(text) println(text) }
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
Transform the following Tcl implementation into C, maintaining the same output and logic.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
#define TITLE "CSV data manipulation" #define URL "http: #define _GNU_SOURCE #define bool int #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(","); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf("[Empty table]\n"); return ; } printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf("[|"); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf("%s\t|", content); } printf("]\n"); } printf("\n"); } int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { content = csv_get(old_csv, cur_col, cur_row); free(content); } else { } } } free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); return -1; } int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, "r"); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf("Unable to open %s for reading.", filename); return -1; } int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, "w"); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, ((col == csv->cols-1) ? "" : csv->delim) ); } fprintf(fp, "\n"); } fclose(fp); return 0; } int main(int argc, char ** argv) { CSV * csv; printf("%s\n%s\n\n",TITLE, URL); csv = csv_create(0, 0); csv_open(csv, "fixtures/csv-data-manipulation.csv"); csv_display(csv); csv_set(csv, 0, 0, "Column0"); csv_set(csv, 1, 1, "100"); csv_set(csv, 2, 2, "200"); csv_set(csv, 3, 3, "300"); csv_set(csv, 4, 4, "400"); csv_display(csv); csv_save(csv, "tmp/csv-data-manipulation.result.csv"); csv_destroy(csv); return 0; }
Change the following Tcl code into C without altering its purpose.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
#define TITLE "CSV data manipulation" #define URL "http: #define _GNU_SOURCE #define bool int #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> typedef struct { char * delim; unsigned int rows; unsigned int cols; char ** table; } CSV; int trim(char ** str) { int trimmed; int n; int len; len = strlen(*str); n = len - 1; while((n>=0) && isspace((*str)[n])) { (*str)[n] = '\0'; trimmed += 1; n--; } n = 0; while((n < len) && (isspace((*str)[0]))) { (*str)[0] = '\0'; *str = (*str)+1; trimmed += 1; n++; } return trimmed; } int csv_destroy(CSV * csv) { if (csv == NULL) { return 0; } if (csv->table != NULL) { free(csv->table); } if (csv->delim != NULL) { free(csv->delim); } free(csv); return 0; } CSV * csv_create(unsigned int cols, unsigned int rows) { CSV * csv; csv = malloc(sizeof(CSV)); csv->rows = rows; csv->cols = cols; csv->delim = strdup(","); csv->table = malloc(sizeof(char *) * cols * rows); if (csv->table == NULL) { goto error; } memset(csv->table, 0, sizeof(char *) * cols * rows); return csv; error: csv_destroy(csv); return NULL; } char * csv_get(CSV * csv, unsigned int col, unsigned int row) { unsigned int idx; idx = col + (row * csv->cols); return csv->table[idx]; } int csv_set(CSV * csv, unsigned int col, unsigned int row, char * value) { unsigned int idx; idx = col + (row * csv->cols); csv->table[idx] = value; return 0; } void csv_display(CSV * csv) { int row, col; char * content; if ((csv->rows == 0) || (csv->cols==0)) { printf("[Empty table]\n"); return ; } printf("\n[Table cols=%d rows=%d]\n", csv->cols, csv->rows); for (row=0; row<csv->rows; row++) { printf("[|"); for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); printf("%s\t|", content); } printf("]\n"); } printf("\n"); } int csv_resize(CSV * old_csv, unsigned int new_cols, unsigned int new_rows) { unsigned int cur_col, cur_row, max_cols, max_rows; CSV * new_csv; char * content; bool in_old, in_new; new_csv = csv_create(new_cols, new_rows); if (new_csv == NULL) { goto error; } new_csv->rows = new_rows; new_csv->cols = new_cols; max_cols = (new_cols > old_csv->cols)? new_cols : old_csv->cols; max_rows = (new_rows > old_csv->rows)? new_rows : old_csv->rows; for (cur_col=0; cur_col<max_cols; cur_col++) { for (cur_row=0; cur_row<max_rows; cur_row++) { in_old = (cur_col < old_csv->cols) && (cur_row < old_csv->rows); in_new = (cur_col < new_csv->cols) && (cur_row < new_csv->rows); if (in_old && in_new) { content = csv_get(old_csv, cur_col, cur_row); csv_set(new_csv, cur_col, cur_row, content); } else if (in_old) { content = csv_get(old_csv, cur_col, cur_row); free(content); } else { } } } free(old_csv->table); old_csv->rows = new_rows; old_csv->cols = new_cols; old_csv->table = new_csv->table; new_csv->table = NULL; csv_destroy(new_csv); return 0; error: printf("Unable to resize CSV table: error %d - %s\n", errno, strerror(errno)); return -1; } int csv_open(CSV * csv, char * filename) { FILE * fp; unsigned int m_rows; unsigned int m_cols, cols; char line[2048]; char * lineptr; char * token; fp = fopen(filename, "r"); if (fp == NULL) { goto error; } m_rows = 0; m_cols = 0; while(fgets(line, sizeof(line), fp) != NULL) { m_rows += 1; cols = 0; lineptr = line; while ((token = strtok(lineptr, csv->delim)) != NULL) { lineptr = NULL; trim(&token); cols += 1; if (cols > m_cols) { m_cols = cols; } csv_resize(csv, m_cols, m_rows); csv_set(csv, cols-1, m_rows-1, strdup(token)); } } fclose(fp); csv->rows = m_rows; csv->cols = m_cols; return 0; error: fclose(fp); printf("Unable to open %s for reading.", filename); return -1; } int csv_save(CSV * csv, char * filename) { FILE * fp; int row, col; char * content; fp = fopen(filename, "w"); for (row=0; row<csv->rows; row++) { for (col=0; col<csv->cols; col++) { content = csv_get(csv, col, row); fprintf(fp, "%s%s", content, ((col == csv->cols-1) ? "" : csv->delim) ); } fprintf(fp, "\n"); } fclose(fp); return 0; } int main(int argc, char ** argv) { CSV * csv; printf("%s\n%s\n\n",TITLE, URL); csv = csv_create(0, 0); csv_open(csv, "fixtures/csv-data-manipulation.csv"); csv_display(csv); csv_set(csv, 0, 0, "Column0"); csv_set(csv, 1, 1, "100"); csv_set(csv, 2, 2, "200"); csv_set(csv, 3, 3, "300"); csv_set(csv, 4, 4, "400"); csv_display(csv); csv_save(csv, "tmp/csv-data-manipulation.result.csv"); csv_destroy(csv); return 0; }
Keep all operations the same but rewrite the snippet in C#.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
using System.IO; using System.Linq; namespace CSV_data_manipulation { class Program { static void Main() { var input = File.ReadAllLines("test_in.csv"); var output = input.Select((line, i) => { if (i == 0) return line + ",SUM"; var sum = line.Split(',').Select(int.Parse).Sum(); return line + "," + sum; }).ToArray(); File.WriteAllLines("test_out.csv", output); } } }
Keep all operations the same but rewrite the snippet in C#.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
using System.IO; using System.Linq; namespace CSV_data_manipulation { class Program { static void Main() { var input = File.ReadAllLines("test_in.csv"); var output = input.Select((line, i) => { if (i == 0) return line + ",SUM"; var sum = line.Split(',').Select(int.Parse).Sum(); return line + "," + sum; }).ToArray(); File.WriteAllLines("test_out.csv", output); } } }
Maintain the same structure and functionality when rewriting this code in C++.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) { std::ifstream file( filename ); clear(); if ( file.is_open() ) { open( file, delim ); return true; } return false; } void open( std::istream& istream, char delim = ',' ) { std::string line; clear(); while ( std::getline( istream, line ) ) { unsigned int nCol = 0; std::istringstream lineStream(line); std::string cell; while( std::getline( lineStream, cell, delim ) ) { m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); nCol++; } m_nCols = std::max( m_nCols, nCol ); m_nRows++; } } bool save( const char* pFile, char delim = ',' ) { std::ofstream ofile( pFile ); if ( ofile.is_open() ) { save( ofile ); return true; } return false; } void save( std::ostream& ostream, char delim = ',' ) { for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) { for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) { ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); if ( (nCol+1) < m_nCols ) { ostream << delim; } else { ostream << std::endl; } } } } void clear() { m_oData.clear(); m_nRows = m_nCols = 0; } std::string& operator()( unsigned int nCol, unsigned int nRow ) { m_nCols = std::max( m_nCols, nCol+1 ); m_nRows = std::max( m_nRows, nRow+1 ); return m_oData[std::make_pair(nCol, nRow)]; } inline unsigned int GetRows() { return m_nRows; } inline unsigned int GetCols() { return m_nCols; } private: inline std::string &trim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } private: std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData; unsigned int m_nCols; unsigned int m_nRows; }; int main() { CSV oCSV; oCSV.open( "test_in.csv" ); oCSV( 0, 0 ) = "Column0"; oCSV( 1, 1 ) = "100"; oCSV( 2, 2 ) = "200"; oCSV( 3, 3 ) = "300"; oCSV( 4, 4 ) = "400"; oCSV.save( "test_out.csv" ); return 0; }
Change the programming language of this snippet from Tcl to C++ without modifying what it does.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
#include <map> #include <vector> #include <iostream> #include <fstream> #include <utility> #include <functional> #include <string> #include <sstream> #include <algorithm> #include <cctype> class CSV { public: CSV(void) : m_nCols( 0 ), m_nRows( 0 ) {} bool open( const char* filename, char delim = ',' ) { std::ifstream file( filename ); clear(); if ( file.is_open() ) { open( file, delim ); return true; } return false; } void open( std::istream& istream, char delim = ',' ) { std::string line; clear(); while ( std::getline( istream, line ) ) { unsigned int nCol = 0; std::istringstream lineStream(line); std::string cell; while( std::getline( lineStream, cell, delim ) ) { m_oData[std::make_pair( nCol, m_nRows )] = trim( cell ); nCol++; } m_nCols = std::max( m_nCols, nCol ); m_nRows++; } } bool save( const char* pFile, char delim = ',' ) { std::ofstream ofile( pFile ); if ( ofile.is_open() ) { save( ofile ); return true; } return false; } void save( std::ostream& ostream, char delim = ',' ) { for ( unsigned int nRow = 0; nRow < m_nRows; nRow++ ) { for ( unsigned int nCol = 0; nCol < m_nCols; nCol++ ) { ostream << trim( m_oData[std::make_pair( nCol, nRow )] ); if ( (nCol+1) < m_nCols ) { ostream << delim; } else { ostream << std::endl; } } } } void clear() { m_oData.clear(); m_nRows = m_nCols = 0; } std::string& operator()( unsigned int nCol, unsigned int nRow ) { m_nCols = std::max( m_nCols, nCol+1 ); m_nRows = std::max( m_nRows, nRow+1 ); return m_oData[std::make_pair(nCol, nRow)]; } inline unsigned int GetRows() { return m_nRows; } inline unsigned int GetCols() { return m_nCols; } private: inline std::string &trim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } private: std::map<std::pair<unsigned int, unsigned int>, std::string> m_oData; unsigned int m_nCols; unsigned int m_nRows; }; int main() { CSV oCSV; oCSV.open( "test_in.csv" ); oCSV( 0, 0 ) = "Column0"; oCSV( 1, 1 ) = "100"; oCSV( 2, 2 ) = "200"; oCSV( 3, 3 ) = "300"; oCSV( 4, 4 ) = "400"; oCSV.save( "test_out.csv" ); return 0; }
Please provide an equivalent version of this Tcl code in Java.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class CSV { private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows; public void open(File file) throws FileNotFoundException, IOException { open(file, ','); } public void open(File file, char delimiter) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); scanner.useDelimiter(Character.toString(delimiter)); clear(); while(scanner.hasNextLine()) { String[] values = scanner.nextLine().split(Character.toString(delimiter)); int col = 0; for ( String value: values ) { _map.put(new Point(col, _rows), value); _cols = Math.max(_cols, ++col); } _rows++; } scanner.close(); } public void save(File file) throws IOException { save(file, ','); } public void save(File file, char delimiter) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Point key = new Point(col, row); if (_map.containsKey(key)) { bw.write(_map.get(key)); } if ((col + 1) < _cols) { bw.write(delimiter); } } bw.newLine(); } bw.flush(); bw.close(); } public String get(int col, int row) { String val = ""; Point key = new Point(col, row); if (_map.containsKey(key)) { val = _map.get(key); } return val; } public void put(int col, int row, String value) { _map.put(new Point(col, row), value); _cols = Math.max(_cols, col+1); _rows = Math.max(_rows, row+1); } public void clear() { _map.clear(); _cols = 0; _rows = 0; } public int rows() { return _rows; } public int cols() { return _cols; } public static void main(String[] args) { try { CSV csv = new CSV(); csv.open(new File("test_in.csv")); csv.put(0, 0, "Column0"); csv.put(1, 1, "100"); csv.put(2, 2, "200"); csv.put(3, 3, "300"); csv.put(4, 4, "400"); csv.save(new File("test_out.csv")); } catch (Exception e) { } } }
Generate a Java translation of this Tcl snippet without changing its computational steps.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
import java.io.*; import java.awt.Point; import java.util.HashMap; import java.util.Scanner; public class CSV { private HashMap<Point, String> _map = new HashMap<Point, String>(); private int _cols; private int _rows; public void open(File file) throws FileNotFoundException, IOException { open(file, ','); } public void open(File file, char delimiter) throws FileNotFoundException, IOException { Scanner scanner = new Scanner(file); scanner.useDelimiter(Character.toString(delimiter)); clear(); while(scanner.hasNextLine()) { String[] values = scanner.nextLine().split(Character.toString(delimiter)); int col = 0; for ( String value: values ) { _map.put(new Point(col, _rows), value); _cols = Math.max(_cols, ++col); } _rows++; } scanner.close(); } public void save(File file) throws IOException { save(file, ','); } public void save(File file, char delimiter) throws IOException { FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for (int row = 0; row < _rows; row++) { for (int col = 0; col < _cols; col++) { Point key = new Point(col, row); if (_map.containsKey(key)) { bw.write(_map.get(key)); } if ((col + 1) < _cols) { bw.write(delimiter); } } bw.newLine(); } bw.flush(); bw.close(); } public String get(int col, int row) { String val = ""; Point key = new Point(col, row); if (_map.containsKey(key)) { val = _map.get(key); } return val; } public void put(int col, int row, String value) { _map.put(new Point(col, row), value); _cols = Math.max(_cols, col+1); _rows = Math.max(_rows, row+1); } public void clear() { _map.clear(); _cols = 0; _rows = 0; } public int rows() { return _rows; } public int cols() { return _cols; } public static void main(String[] args) { try { CSV csv = new CSV(); csv.open(new File("test_in.csv")); csv.put(0, 0, "Column0"); csv.put(1, 1, "100"); csv.put(2, 2, "200"); csv.put(3, 3, "300"); csv.put(4, 4, "400"); csv.save(new File("test_out.csv")); } catch (Exception e) { } } }
Translate the given Tcl code snippet into Python without altering its behavior.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
import fileinput changerow, changecolumn, changevalue = 2, 4, '"Spam"' with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue line = ','.join(fields) + '\n' print(line, end='')
Produce a functionally identical Python code for the snippet given in Tcl.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
import fileinput changerow, changecolumn, changevalue = 2, 4, '"Spam"' with fileinput.input('csv_data_manipulation.csv', inplace=True) as f: for line in f: if fileinput.filelineno() == changerow: fields = line.rstrip().split(',') fields[changecolumn-1] = changevalue line = ','.join(fields) + '\n' print(line, end='')
Convert this Tcl snippet to VB and keep its semantics consistent.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Please provide an equivalent version of this Tcl code in VB.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
Sub ReadCSV() Workbooks.Open Filename:="L:\a\input.csv" Range("F1").Value = "Sum" Range("F2:F5").Formula = "=SUM(A2:E2)" ActiveWorkbook.SaveAs Filename:="L:\a\output.csv", FileFormat:=xlCSV ActiveWindow.Close End Sub
Translate the given Tcl code snippet into Go without altering its behavior.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
Write the same code in Go as shown below in Tcl.
package require struct::matrix package require csv proc addSumColumn {filename {title "SUM"}} { set m [struct::matrix] set f [open $filename] csv::read2matrix $f $m "," auto close $f set sumcol [$m columns] $m add column $title for {set i 1} {$i < [$m rows]} {incr i} { $m set cell $sumcol $i 0 $m set cell $sumcol $i [tcl::mathop::+ {*}[$m get row $i]] } set f [open $filename w] csv::writematrix $m $f close $f $m destroy } addSumColumn "example.csv"
package main import ( "encoding/csv" "log" "os" "strconv" ) func main() { rows := readSample() appendSum(rows) writeChanges(rows) } func readSample() [][]string { f, err := os.Open("sample.csv") if err != nil { log.Fatal(err) } rows, err := csv.NewReader(f).ReadAll() f.Close() if err != nil { log.Fatal(err) } return rows } func appendSum(rows [][]string) { rows[0] = append(rows[0], "SUM") for i := 1; i < len(rows); i++ { rows[i] = append(rows[i], sum(rows[i])) } } func sum(row []string) string { sum := 0 for _, s := range row { x, err := strconv.Atoi(s) if err != nil { return "NA" } sum += x } return strconv.Itoa(sum) } func writeChanges(rows [][]string) { f, err := os.Create("output.csv") if err != nil { log.Fatal(err) } err = csv.NewWriter(f).WriteAll(rows) f.Close() if err != nil { log.Fatal(err) } }
Generate an equivalent PHP version of this Rust code.
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Ensure the translated PHP code behaves exactly like the original Rust snippet.
use std::error::Error; use std::num::ParseIntError; use csv::{Reader, Writer}; fn main() -> Result<(), Box<dyn Error>> { let mut reader = Reader::from_path("data.csv")?; let mut writer = Writer::from_path("output.csv")?; let mut headers = reader.headers()?.clone(); headers.push_field("SUM"); writer.write_record(headers.iter())?; for row in reader.records() { let mut row = row?; let sum: Result<_, ParseIntError> = row.iter().try_fold(0, |accum, s| { Ok(accum + s.parse::<i64>()?) }); row.push_field(&sum?.to_string()); writer.write_record(row.iter())?; } writer.flush()?; Ok(()) }
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Ensure the translated PHP code behaves exactly like the original Ada snippet.
package CSV is type Row(<>) is tagged private; function Line(S: String; Separator: Character := ',') return Row; function Next(R: in out Row) return Boolean; function Item(R: Row) return String; private type Row(Length: Natural) is tagged record Str: String(1 .. Length); Fst: Positive; Lst: Natural; Nxt: Positive; Sep: Character; end record; end CSV;
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Port the following code from Ada to PHP with equivalent syntax and logic.
package CSV is type Row(<>) is tagged private; function Line(S: String; Separator: Character := ',') return Row; function Next(R: in out Row) return Boolean; function Item(R: Row) return String; private type Row(Length: Natural) is tagged record Str: String(1 .. Length); Fst: Positive; Lst: Natural; Nxt: Positive; Sep: Character; end record; end CSV;
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Port the provided Arturo code into PHP while preserving the original functionality.
table: read.csv "data.csv" data: [] loop table 'row [ addable: ["SUM"] if row <> first table -> addable: @[to :string sum map row 'x [to :integer x]] 'data ++ @[row ++ addable] ] loop data 'row [ loop row 'column -> prints pad column 6 print "" ]
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Write the same algorithm in PHP as shown in this Arturo implementation.
table: read.csv "data.csv" data: [] loop table 'row [ addable: ["SUM"] if row <> first table -> addable: @[to :string sum map row 'x [to :integer x]] 'data ++ @[row ++ addable] ] loop data 'row [ loop row 'column -> prints pad column 6 print "" ]
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Rewrite the snippet below in PHP so it works the same as the original AutoHotKey code.
Loop, Read, Data.csv { i := A_Index Loop, Parse, A_LoopReadLine, CSV Output .= (i=A_Index && i!=1 ? A_LoopField**2 : A_LoopField) (A_Index=5 ? "`n" : ",") } FileAppend, %Output%, NewData.csv
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Change the following AutoHotKey code into PHP without altering its purpose.
Loop, Read, Data.csv { i := A_Index Loop, Parse, A_LoopReadLine, CSV Output .= (i=A_Index && i!=1 ? A_LoopField**2 : A_LoopField) (A_Index=5 ? "`n" : ",") } FileAppend, %Output%, NewData.csv
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Keep all operations the same but rewrite the snippet in PHP.
BEGIN { FS = OFS = "," } NR==1 { print $0, "SUM" next } { sum = 0 for (i=1; i<=NF; i++) { sum += $i } print $0, sum }
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Generate an equivalent PHP version of this AWK code.
BEGIN { FS = OFS = "," } NR==1 { print $0, "SUM" next } { sum = 0 for (i=1; i<=NF; i++) { sum += $i } print $0, sum }
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Generate a PHP translation of this Clojure snippet without changing its computational steps.
(require '[clojure.data.csv :as csv] '[clojure.java.io :as io]) (defn add-sum-column [coll] (let [titles (first coll) values (rest coll)] (cons (conj titles "SUM") (map #(conj % (reduce + (map read-string %))) values)))) (with-open [in-file (io/reader "test_in.csv")] (doall (let [out-data (add-sum-column (csv/read-csv in-file))] (with-open [out-file (io/writer "test_out.csv")] (csv/write-csv out-file out-data)))))
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>
Rewrite the snippet below in PHP so it works the same as the original Clojure code.
(require '[clojure.data.csv :as csv] '[clojure.java.io :as io]) (defn add-sum-column [coll] (let [titles (first coll) values (rest coll)] (cons (conj titles "SUM") (map #(conj % (reduce + (map read-string %))) values)))) (with-open [in-file (io/reader "test_in.csv")] (doall (let [out-data (add-sum-column (csv/read-csv in-file))] (with-open [out-file (io/writer "test_out.csv")] (csv/write-csv out-file out-data)))))
<?php $handle = fopen('data_in.csv','r'); $handle_output = fopen('data_out.csv','w'); $row = 0; $arr = array(); while ($line = fgetcsv($handle)) { $arr[] = $line; } $arr[1][0] = 0; // 1,5,9,13,17 => 0,5,9,13,17 $arr[2][1] = 0; // 2,6,10,14,18 => 2,0,10,14,18 foreach ($arr as $line) { if ($row==0) { array_push($line,"SUM"); } else { array_push($line,array_sum($line)); } fputcsv($handle_output, $line); $row++; } ?>