WeixiangYan/CodeTransOcean huggingface dataset:
Task: Introspection



C#: using System;
using System.Reflection;

namespace Rosetta_Introspection
{
	static public class Program
	{
		static public int bloop = -10;
		static public int bloop2 = -20;

		public static void Main()
		{
			var asm = Assembly.GetExecutingAssembly();
			var version = int.Parse(asm.ImageRuntimeVersion.Split('.')[0].Substring(1));
			if (version < 4)
			{
				Console.WriteLine("Get with the program!  I'm outta here!");
				return;
			}

			FieldInfo bloopField = null;

			foreach (var type in asm.GetExportedTypes())
			{
				foreach (var field in type.GetFields())
				{
					if (field.Name != "bloop")
					{
						continue;
					}
					bloopField = field;
					if (bloopField.FieldType != typeof(int))
					{
						throw new InvalidProgramException("bloop should be an integer");
					}
					break;
				}
				if (bloopField != null)
				{
					break;
				}
			}

			if (bloopField == null)
			{
				throw new InvalidProgramException("No bloop exported value");
			}
			foreach (var refAsm in AppDomain.CurrentDomain.GetAssemblies())
			{
				foreach (var type in refAsm.GetExportedTypes())
				{
					if (type.Name == "Math")
					{
						var absMethod = type.GetMethod("Abs", new Type[] { typeof(int) });
						if (absMethod != null)
						{
							Console.WriteLine("bloop's abs value = {0}", absMethod.Invoke(null, new object[] { bloopField.GetValue(null) }));
						}
					}
				}
			}

			int intCount = 0;
			int total = 0;

			foreach (var type in asm.GetExportedTypes())
			{
				foreach (var field in type.GetFields())
				{
					if (field.FieldType == typeof(int))
					{
						intCount++;
						total += (int)field.GetValue(null);
					}
				}
			}
			Console.WriteLine("{0} exported ints which total to {1}", intCount, total);
			Console.ReadKey();
		}
	}
}









Ada: 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;
Task: Introspection

C: #if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L
 #pragma error("C compiler must adhere to at least C99 for the following code.")
 #else
 
 #endif











Ada: 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;
Task: Introspection


C++: #if !defined(__cplusplus) || __cplusplus < 201103L
    #pragma error("The following code requires at least C++11.")
#else
    
#endif










Ada: 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;
Task: Introspection




Go: 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))
    }
}








Ada: 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;
Task: Introspection





Java: public class VersCheck {
	public static void main(String[] args) {
		String vers = System.getProperty("java.version");
		vers = vers.substring(0,vers.indexOf('.')) + "." +  
			vers.substring(vers.indexOf('.')+1,vers.lastIndexOf('.'));
		if(Double.parseDouble(vers) >= 1.5){
			System.out.println("YAY!");
		}else{
			System.err.println("Must use Java >=1.5");
		}
	}
}







Ada: 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;
Task: Introspection







Python: 
 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)





Ada: 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;
Task: Introspection








VB: If Application.Version < 15 Then Exit Sub




Ada: 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;
Task: Introspection

C: #if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L
 #pragma error("C compiler must adhere to at least C99 for the following code.")
 #else
 
 #endif
Task: Introspection



C#: using System;
using System.Reflection;

namespace Rosetta_Introspection
{
	static public class Program
	{
		static public int bloop = -10;
		static public int bloop2 = -20;

		public static void Main()
		{
			var asm = Assembly.GetExecutingAssembly();
			var version = int.Parse(asm.ImageRuntimeVersion.Split('.')[0].Substring(1));
			if (version < 4)
			{
				Console.WriteLine("Get with the program!  I'm outta here!");
				return;
			}

			FieldInfo bloopField = null;

			foreach (var type in asm.GetExportedTypes())
			{
				foreach (var field in type.GetFields())
				{
					if (field.Name != "bloop")
					{
						continue;
					}
					bloopField = field;
					if (bloopField.FieldType != typeof(int))
					{
						throw new InvalidProgramException("bloop should be an integer");
					}
					break;
				}
				if (bloopField != null)
				{
					break;
				}
			}

			if (bloopField == null)
			{
				throw new InvalidProgramException("No bloop exported value");
			}
			foreach (var refAsm in AppDomain.CurrentDomain.GetAssemblies())
			{
				foreach (var type in refAsm.GetExportedTypes())
				{
					if (type.Name == "Math")
					{
						var absMethod = type.GetMethod("Abs", new Type[] { typeof(int) });
						if (absMethod != null)
						{
							Console.WriteLine("bloop's abs value = {0}", absMethod.Invoke(null, new object[] { bloopField.GetValue(null) }));
						}
					}
				}
			}

			int intCount = 0;
			int total = 0;

			foreach (var type in asm.GetExportedTypes())
			{
				foreach (var field in type.GetFields())
				{
					if (field.FieldType == typeof(int))
					{
						intCount++;
						total += (int)field.GetValue(null);
					}
				}
			}
			Console.WriteLine("{0} exported ints which total to {1}", intCount, total);
			Console.ReadKey();
		}
	}
}
Task: Introspection


C++: #if !defined(__cplusplus) || __cplusplus < 201103L
    #pragma error("The following code requires at least C++11.")
#else
    
#endif
Task: Introspection





Java: public class VersCheck {
	public static void main(String[] args) {
		String vers = System.getProperty("java.version");
		vers = vers.substring(0,vers.indexOf('.')) + "." +  
			vers.substring(vers.indexOf('.')+1,vers.lastIndexOf('.'));
		if(Double.parseDouble(vers) >= 1.5){
			System.out.println("YAY!");
		}else{
			System.err.println("Must use Java >=1.5");
		}
	}
}
Task: Introspection







Python: 
 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)
Task: Introspection








VB: If Application.Version < 15 Then Exit Sub
Task: Introspection




Go: 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))
    }
}
Task: Introspection






PHP: <?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");

?>






Ada: 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;
Task: Introspection






PHP: <?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");

?>
Task: CSV data manipulation



C#: 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);
        }
    }
}









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;
Task: CSV data manipulation




Go: 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)
	}
}








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;
Task: CSV data manipulation





Java: 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) {
        }
    }
}







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;
Task: CSV data manipulation







Python: 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='')





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;
Task: CSV data manipulation








VB: 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




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;
Task: CSV data manipulation



C#: 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);
        }
    }
}
Task: CSV data manipulation


C++: #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;
}