Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Transform the following Tcl implementation into Python, maintaining the same output and logic.
package require Tcl 8.4 ; if {[info exists bloop] && [llength [info functions abs]]} { puts [expr abs($bloop)] }
import sys major, minor, bugfix = sys.version_info[:3] if major < 2: sys.exit('Python 2 is required') def defined(name): return name in globals() or name in locals() or name in vars(__builtins__) def defined2(name): try: eval(name) return True except NameError: return False if defined('bloop') and defined('abs') and callable(abs): print abs(bloop) if defined2('bloop') and defined2('abs') and callable(abs): print abs(bloop)
Maintain the same structure and functionality when rewriting this code in VB.
package require Tcl 8.4 ; if {[info exists bloop] && [llength [info functions abs]]} { puts [expr abs($bloop)] }
If Application.Version < 15 Then Exit Sub
Convert the following code from Tcl to Go, ensuring the logic remains intact.
package require Tcl 8.4 ; if {[info exists bloop] && [llength [info functions abs]]} { puts [expr abs($bloop)] }
package main import ( "debug/elf" "debug/gosym" "fmt" "log" "math" "os" "runtime" ) var bloop = -3.4 func main() { fmt.Println("task 1: verify version") fmt.Println(" program compiled with", runtime.Version()) fmt.Println("task 2: check for presence of variable and function") f, err := elf.Open(os.Args[0]) if err != nil { log.Fatal(err) } defer f.Close() symSection := f.Section(".gosymtab") lineSection := f.Section(".gopclntab") textSection := f.Section(".text") if symSection == nil || lineSection == nil || textSection == nil { log.Fatal("symbolic information not found") } symData, err := symSection.Data() if err != nil { log.Fatal(err) } lineData, err := lineSection.Data() if err != nil { log.Fatal(err) } table, err := gosym.NewTable(symData, gosym.NewLineTable(lineData, textSection.Addr)) if err != nil { log.Fatal(" ", err) } var foundBloop, foundFabs bool for _, s := range table.Syms { if s.Name == "main.bloop" { foundBloop = true fmt.Println(" bloop symbol table entry:", s) } else if s.Name == "math.Abs" { foundFabs = true fmt.Println(" abs symbol table entry:", s) } } if foundBloop && foundFabs { fmt.Println(" bloop: ", bloop) fmt.Println(" abs(bloop): ", math.Abs(bloop)) } }
Convert this Ada snippet to PHP and keep its semantics consistent.
with Ada.Integer_Text_IO, Ada.Text_IO; procedure Introspection is use Ada.Integer_Text_IO, Ada.Text_IO; begin Put ("Integer range: "); Put (Integer'First); Put (" .. "); Put (Integer'Last); New_Line; Put ("Float digits: "); Put (Float'Digits); New_Line; end Introspection;
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Transform the following Arturo implementation into PHP, maintaining the same output and logic.
if not? sys\version > 0.9.0 -> panic "version too old!" bloop: 3 - 5 if? set? 'bloop -> "variable 'bloop' is set" else -> "variable 'bloop' is not set" if set? 'abs -> print ["the absolute value of bloop is:" abs bloop] print [ "The sum of all globally defined integers is:" sum map select keys symbols 'sym -> integer? var sym 'sym -> var sym ]
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Translate this program into PHP but keep the logic exactly as in AutoHotKey.
if (A_AhkVersion < "1.0.48.03") { MsgBox % "you are using" . A_AhkVersion . "`nplease upgrade to" . "1.0.48.03" ExitApp } bloop = -3 if bloop if IsFunc("abs") MsgBox % abs(bloop) return
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Port the following code from AWK to PHP with equivalent syntax and logic.
BEGIN { if (PROCINFO["version"] < "4.1.0") { print("version is too old") exit(1) } bloop = -1 if (PROCINFO["identifiers"]["abs"] == "user" && bloop != "") { printf("bloop = %s\n",bloop) printf("abs(bloop) = %s\n",abs(bloop)) } exit(0) } function abs(x) { if (x >= 0) { return x } else { return -x } }
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Can you help me rewrite this code in PHP instead of BBC_Basic, keeping it the same logically?
IF VAL(FNversion) < 5.94 THEN PRINT "Version is too old" : END ON ERROR LOCAL PRINT "Variable 'bloop' doesn't exist" : END test = bloop RESTORE ERROR ON ERROR LOCAL PRINT "Function 'FNabs()' is not defined" : END test = ^FNabs() RESTORE ERROR PRINT FNabs(bloop) END DEF FNversion LOCAL F%, V$ F% = OPENOUT(@tmp$+"version.txt") OSCLI "OUTPUT "+STR$F% *HELP *OUTPUT 0 PTR #F% = 0 INPUT #F%,V$ CLOSE #F% = RIGHT$(V$,5)
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Translate the given Clojure code snippet into PHP without altering its behavior.
(let [version (Double/parseDouble (re-find #"\d*\.\d*" (System/getProperty "java.version")))] (if (>= version 1.5) (println "Version ok") (throw (Error. "Bad version")))) (let [version (Double/parseDouble (re-find #"\d*\.\d*" (clojure-version)))] (if (>= version 1.0) (println "Version ok") (throw (Error. "Bad version"))))
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Can you help me rewrite this code in PHP instead of Common_Lisp, keeping it the same logically?
(let* ((ver (lisp-implementation-version)) (major (parse-integer ver :start 0 :end (position #\. ver)))) #+lispworks (assert (>= 5 major) () "Requires Lispworks version 5 or above") #+clisp (assert (>= 2 major) () "Requires CLISP 2.n") )
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Preserve the algorithm and functionality while converting the code from D to PHP.
immutable x = 3, y = 100, z = 3_000; short w = 1; immutable s = "some string"; void main() { import std.compiler, std.math, std.traits; static assert(version_major > 1 && version_minor > 50, "I can't cope with this compiler version."); immutable bloop = 10; static if (__traits(compiles, bloop.abs)) { pragma(msg, "The expression is compilable."); auto x = bloop.abs; } else { pragma(msg, "The expression can't be compiled."); } import std.stdio; immutable s = 10_000; int tot = 0; foreach (name; __traits(allMembers, mixin(__MODULE__))) static if (name != "object" && is(int == Unqual!(typeof(mixin("." ~ name))))) tot += mixin("." ~ name); writeln("Total of the module-level ints (could overflow): ", tot); }
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Change the following Erlang code into PHP without altering its purpose.
-module( introspection ). -export( [task/0] ). task() -> exit_if_too_old( erlang:system_info(otp_release) ), Bloop = lists:keyfind( bloop, 1, ?MODULE:module_info(functions) ), Abs = lists:keyfind( abs, 1, erlang:module_info(exports) ), io:fwrite( "abs( bloop ) => ~p~n", [call_abs_with_bloop(Abs, Bloop)] ), io:fwrite( "Number of modules: ~p~n", [erlang:length(code:all_loaded())] ). bloop() -> -1. call_abs_with_bloop( {abs, 1}, {bloop, 0} ) -> erlang:abs( bloop() ); call_abs_with_bloop( _Missing, _Not_here ) -> abs_and_bloop_missing. exit_if_too_old( Release ) when Release < "R13A" -> erlang:exit( too_old_release ); exit_if_too_old( _Release ) -> ok.
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Change the following Factor code into PHP without altering its purpose.
: if-older ( n true false -- ) [ build > ] 2dip if ; inline : when-older ( n true -- ) [ ] if-older ; inline : unless-older ( n false -- ) [ [ ] ] dip if-older ; inline 900 [ "Your version of Factor is too old." print 1 exit ] when-older
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Write the same code in PHP as shown below in Forth.
s" MAX-U" environment? [IF] 0xffffffff <> [IF] . bye [THEN] [THEN] [defined] bloop [if] [defined] abs [if] bloop @ abs [then] [then]
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Convert this Haskell block to PHP, preserving its control flow and logic.
import Data.Version import Control.Monad import System.Info minGHCVersion = Version [6, 8] [] main = when (compilerName == "ghc" && compilerVersion < minGHCVersion) $ fail "Compiler too old."
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Generate a PHP translation of this J snippet without changing its computational steps.
6 (2!:55@:]^:>) 0 ". 1 { 9!:14''
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Port the provided Julia code into PHP while preserving the original functionality.
@show VERSION VERSION < v"0.4" && exit(1) if isdefined(Base, :bloop) && !isempty(methods(abs)) @show abs(bloop) end a, b, c = 1, 2, 3 vars = filter(x -> eval(x) isa Integer, names(Main)) println("Integer variables: ", join(vars, ", "), ".") println("Sum of integers in the global scope: ", sum(eval.(vars)), ".")
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Port the following code from Lua to PHP with equivalent syntax and logic.
if _VERSION:sub(5) + 0 < 5.1 then print"too old" end if bloop and math.abs then print(math.abs(bloop)) end
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Rewrite this program in PHP while keeping its functionality equivalent to the Mathematica version.
If[$VersionNumber < 8, Quit[]] If[NameQ["bloop"] && NameQ["Abs"], Print[Abs[bloop]]]
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Maintain the same structure and functionality when rewriting this code in PHP.
v = version; v(v=='.')=' '; v = str2num(v); if v(2)>10; v(2) = v(2)/10; end; ver = v(1)+v(2)/10; if exist('OCTAVE_VERSION','builtin') if ver < 3.0, exit end; else if ver < 7.0, exit end; end if exist('bloob','var') && any(exist('abs')==[2,3,5]) printf('abs(bloob) is return; end;
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Port the following code from Nim to PHP with equivalent syntax and logic.
when NimVersion < "1.2": error "This compiler is too old" assert NimVersion >= "1.4", "This compiler is too old." var bloop = -12 when compiles abs(bloop): echo abs(bloop)
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Write a version of this OCaml function in PHP with identical behavior.
# Sys.ocaml_version;; - : string = "3.10.2"
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Port the following code from Perl to PHP with equivalent syntax and logic.
require v5.6.1; require 5.6.1; require 5.006_001;
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Translate the given PowerShell code snippet into PHP without altering its behavior.
if ($PSVersionTable['PSVersion'] -lt '2.0') { exit } if ((Test-Path Variable:bloop) -and ([Math]::Abs)) { [Math]::Abs($bloop) } Get-Variable -Scope global ` | Where-Object { $_.Value -is [int] } ` | Measure-Object -Sum Value ` | Select-Object Count,Sum
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Change the following R code into PHP without altering its purpose.
if(getRversion() < "2.14.1") { warning("Your version of R is older than 2.14.1") q() }
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Port the provided Racket code into PHP while preserving the original functionality.
#lang racket (unless (string<=? "5.3" (version)) (error "ancient version"))
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Ensure the translated PHP code behaves exactly like the original REXX snippet.
options replace format comments java crossref symbols binary runSample(arg) return -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) private static parse arg minVersion . if minVersion = '' then minVersion = 2.0 parse version lang ver bdate if ver < minVersion then do say - lang 'version' ver - '[Build date:' bdate']' - 'is less than' minVersion.format(null, 2)'; exiting...' exit end else do say - lang 'version' ver - '[Build date:' bdate']' - 'meets minimum requirements of' minVersion.format(null, 2) end return
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Ensure the translated PHP code behaves exactly like the original Ruby snippet.
exit if RUBY_VERSION < '1.8.6' puts bloop.abs if defined?(bloop) and bloop.respond_to?(:abs)
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Change the following Scala code into PHP without altering its purpose.
import java.lang.reflect.Method val bloop = -3 val i = 4 val j = 5 val k = 6 fun main(args: Array<String>) { val version = System.getProperty("java.version") if (version >= "1.6") println("The current JVM version is $version") else println("Must use version 1.6 or later") val topLevel = Class.forName("IntroKt") val math = Class.forName("java.lang.Math") val abs = math.getDeclaredMethod("abs", Int::class.java) val methods = topLevel.getDeclaredMethods() for (method in methods) { if (method.name == "getBloop" && method.returnType == Int::class.java) { println("\nabs(bloop) = ${abs.invoke(null, method.invoke(null))}") break } } var count = 0 var sum = 0 for (method in methods) { if (method.returnType == Int::class.java) { count++ sum += method.invoke(null) as Int } } println("\nThere are $count global integer variables and their sum is $sum") }
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Rewrite this program in PHP while keeping its functionality equivalent to the Tcl version.
package require Tcl 8.4 ; if {[info exists bloop] && [llength [info functions abs]]} { puts [expr abs($bloop)] }
<?php if (version_compare(PHP_VERSION, '5.3.0', '<' )) { echo("You are using PHP Version " . PHP_VERSION . ". Please upgrade to Version 5.3.0\n"); exit(); } $bloop = -3; if (isset($bloop) && function_exists('abs')) { echo(abs($bloop)); } echo(count($GLOBALS) . " variables in global scope.\n"); echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n"); ?>
Keep all operations the same but rewrite the snippet in C#.
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;
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); } } }
Translate this program into C# but keep the logic exactly as in Ada.
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;
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); } } }
Rewrite this program in C while keeping its functionality equivalent to the Ada version.
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;
#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; }
Port the provided Ada code into C while preserving the original functionality.
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;
#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; }
Convert this Ada block to C++, preserving its control flow 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;
#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 C++.
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;
#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 Ada code into Go without altering its purpose.
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;
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 Ada code into Go without altering its purpose.
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;
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) } }
Can you help me rewrite this code in Java instead of Ada, keeping it the same logically?
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;
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) { } } }
Produce a functionally identical Java code for the snippet given in Ada.
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;
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 Ada.
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;
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 Ada code snippet into Python without altering its behavior.
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;
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 the same algorithm in VB as shown in this Ada implementation.
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;
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
Ensure the translated VB 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;
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
Generate an equivalent C version of this Arturo code.
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 "" ]
#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.
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 "" ]
#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; }
Convert this Arturo block to C#, preserving its control flow and logic.
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 "" ]
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); } } }
Rewrite this program in C# while keeping its functionality equivalent to the Arturo version.
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 "" ]
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); } } }
Produce a functionally identical C++ code for the snippet given in Arturo.
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 "" ]
#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 a C++ translation of this Arturo snippet without changing its computational steps.
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 "" ]
#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 Arturo code into Java without altering its purpose.
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 "" ]
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) { } } }
Transform the following Arturo implementation into Java, maintaining the same output and logic.
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 "" ]
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) { } } }
Write the same code in Python as shown below in Arturo.
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 "" ]
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='')
Transform the following Arturo implementation into Python, maintaining the same output and logic.
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 "" ]
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 Arturo block to VB, preserving its control flow and logic.
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 "" ]
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
Generate an equivalent VB version of this Arturo code.
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 "" ]
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.
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 "" ]
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 Arturo snippet to Go and keep its semantics consistent.
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 "" ]
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 AutoHotKey to C, ensuring the logic remains intact.
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
#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; }
Convert the following code from AutoHotKey to C, ensuring the logic remains intact.
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
#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; }
Produce a functionally identical C# code for the snippet given in AutoHotKey.
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
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 an equivalent C# version of this 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
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); } } }
Produce a language-to-language conversion: from AutoHotKey to C++, same semantics.
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
#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; }
Write the same algorithm in C++ as shown in this AutoHotKey implementation.
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
#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; }
Port the provided AutoHotKey code into Java while preserving the original functionality.
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
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 this program in Java while keeping its functionality equivalent to the AutoHotKey version.
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
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 AutoHotKey to Python without modifying what it does.
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
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='')
Ensure the translated Python code behaves exactly like the original AutoHotKey snippet.
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
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='')
Port the provided AutoHotKey code into VB while preserving the original functionality.
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
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
Can you help me rewrite this code in VB instead of AutoHotKey, keeping it the same logically?
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
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
Ensure the translated Go code behaves exactly like the original AutoHotKey snippet.
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
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) } }
Port the provided AutoHotKey code into Go while preserving the original functionality.
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
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) } }
Maintain the same structure and functionality when rewriting this code in C.
BEGIN { FS = OFS = "," } NR==1 { print $0, "SUM" next } { sum = 0 for (i=1; i<=NF; i++) { sum += $i } print $0, sum }
#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 this program in C while keeping its functionality equivalent to the AWK version.
BEGIN { FS = OFS = "," } NR==1 { print $0, "SUM" next } { sum = 0 for (i=1; i<=NF; i++) { sum += $i } print $0, sum }
#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; }
Can you help me rewrite this code in C# instead of AWK, keeping it the same logically?
BEGIN { FS = OFS = "," } NR==1 { print $0, "SUM" next } { sum = 0 for (i=1; i<=NF; i++) { sum += $i } print $0, sum }
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); } } }
Translate the given AWK code snippet into C# without altering its behavior.
BEGIN { FS = OFS = "," } NR==1 { print $0, "SUM" next } { sum = 0 for (i=1; i<=NF; i++) { sum += $i } print $0, sum }
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 AWK code into C++ while preserving the original functionality.
BEGIN { FS = OFS = "," } NR==1 { print $0, "SUM" next } { sum = 0 for (i=1; i<=NF; i++) { sum += $i } print $0, sum }
#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 AWK block to C++, preserving its control flow and logic.
BEGIN { FS = OFS = "," } NR==1 { print $0, "SUM" next } { sum = 0 for (i=1; i<=NF; i++) { sum += $i } print $0, sum }
#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 AWK code into Java without altering its purpose.
BEGIN { FS = OFS = "," } NR==1 { print $0, "SUM" next } { sum = 0 for (i=1; i<=NF; i++) { sum += $i } print $0, sum }
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 AWK code into Java while preserving the original functionality.
BEGIN { FS = OFS = "," } NR==1 { print $0, "SUM" next } { sum = 0 for (i=1; i<=NF; i++) { sum += $i } print $0, sum }
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 an equivalent Python 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 }
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 following AWK code into Python without altering its purpose.
BEGIN { FS = OFS = "," } NR==1 { print $0, "SUM" next } { sum = 0 for (i=1; i<=NF; i++) { sum += $i } print $0, sum }
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 AWK function in VB with identical behavior.
BEGIN { FS = OFS = "," } NR==1 { print $0, "SUM" next } { sum = 0 for (i=1; i<=NF; i++) { sum += $i } print $0, sum }
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 following code from AWK to VB with equivalent syntax and logic.
BEGIN { FS = OFS = "," } NR==1 { print $0, "SUM" next } { sum = 0 for (i=1; i<=NF; i++) { sum += $i } print $0, sum }
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 a version of this AWK function in Go with identical behavior.
BEGIN { FS = OFS = "," } NR==1 { print $0, "SUM" next } { sum = 0 for (i=1; i<=NF; i++) { sum += $i } print $0, sum }
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 AWK snippet to Go and keep its semantics consistent.
BEGIN { FS = OFS = "," } NR==1 { print $0, "SUM" next } { sum = 0 for (i=1; i<=NF; i++) { sum += $i } print $0, sum }
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 Clojure to C, ensuring the logic remains intact.
(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)))))
#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; }
Convert the following code from Clojure to C, ensuring the logic remains intact.
(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)))))
#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 Clojure code into C# without altering its purpose.
(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)))))
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 Clojure block to C#, preserving its control flow and logic.
(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)))))
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 Clojure.
(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)))))
#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; }
Port the following code from Clojure to C++ with equivalent syntax and logic.
(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)))))
#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 Clojure implementation into Java, maintaining the same output and logic.
(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)))))
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) { } } }
Write a version of this Clojure function in Java with identical behavior.
(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)))))
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 the following code from Clojure to Python, ensuring the logic remains intact.
(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)))))
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='')
Port the provided Clojure code into Python while preserving the original functionality.
(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)))))
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 Clojure block to VB, preserving its control flow and logic.
(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)))))
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
Generate a VB 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)))))
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
Rewrite the snippet below in Go 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)))))
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 Clojure.
(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)))))
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) } }