WeixiangYan/CodeTransOcean huggingface dataset:
Task: Permutations with repetitions




Go: package main

import "fmt"

var (
    n      = 3
    values = []string{"A", "B", "C", "D"}
    k      = len(values)
    decide = func(p []string) bool {
        return p[0] == "B" && p[1] == "C"
    }
)

func main() {
    pn := make([]int, n)
    p := make([]string, n)
    for {
        
        for i, x := range pn {
            p[i] = values[x]
        }
        
        fmt.Println(p)
        
        if decide(p) {
            return 
        }
        
        for i := 0; ; {
            pn[i]++
            if pn[i] < k {
                break
            }
            pn[i] = 0
            i++
            if i == n {
                return 
            }
        }
    }
}


Java: import java.util.function.Predicate;

public class PermutationsWithRepetitions {

    public static void main(String[] args) {
        char[] chars = {'a', 'b', 'c', 'd'};
        
        permute(chars, 3, i -> i[0] == 1 && i[1] == 1 && i[2] == 0);
    }

    static void permute(char[] a, int k, Predicate<int[]> decider) {
        int n = a.length;
        if (k < 1 || k > n)
            throw new IllegalArgumentException("Illegal number of positions.");

        int[] indexes = new int[n];
        int total = (int) Math.pow(n, k);

        while (total-- > 0) {
            for (int i = 0; i < n - (n - k); i++)
                System.out.print(a[indexes[i]]);
            System.out.println();

            if (decider.test(indexes))
                break;

            for (int i = 0; i < n; i++) {
                if (indexes[i] >= n - 1) {
                    indexes[i] = 0;
                } else {
                    indexes[i]++;
                    break;
                }
            }
        }
    }
}
Task: Selective file copy




Go: package main

import (
    "encoding/json"
    "log"
    "os"
    "bytes"
    "errors"
    "strings"
)


type s1 struct {
    A string
    B string
    C int
    D string
}


type s2 struct {
    A string
    C intString 
    X string
}

type intString string

func (i *intString) UnmarshalJSON(b []byte) error {
    if len(b) == 0 || bytes.IndexByte([]byte("0123456789-"), b[0]) < 0 {
        return errors.New("Unmarshal intString expected JSON number")
    }
    *i = intString(b)
    return nil
}


func NewS2() *s2 {
    return &s2{X: "XXXXX"}
}

func main() {
    
    o1, err := os.Create("o1.json")
    if err != nil {
        log.Fatal(err)
    }
    e := json.NewEncoder(o1)
    for i := 1; i <= 5; i++ {
        err := e.Encode(s1{
            strings.Repeat("A", i),
            strings.Repeat("B", i),
            i,
            strings.Repeat("D", i),
        })
        if err != nil {
            log.Fatal(err)
        }
    }
    o1.Close()

    
    in, err := os.Open("o1.json")
    if err != nil {
        log.Fatal(err)
    }
    out, err := os.Create("out.json")
    if err != nil {
        log.Fatal(err)
    }
    
    d := json.NewDecoder(in)
    e = json.NewEncoder(out)
    for d.More() {
        
        
        
        
        s := NewS2()
        if err = d.Decode(s); err != nil {
            log.Fatal(err)
        }
        if err = e.Encode(s); err != nil {
            log.Fatal(err)
        }
    }
}


Java: import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;

class CopysJ {

  public static void main(String[] args) {
    String ddname_IN  = "copys.in.txt";
    String ddname_OUT = "copys.out.txt";
    if (args.length >= 1) { ddname_IN  = args[0].length() > 0 ? args[0] : ddname_IN; }
    if (args.length >= 2) { ddname_OUT = args[1].length() > 0 ? args[1] : ddname_OUT; }

    File dd_IN = new File(ddname_IN);
    File dd_OUT = new File(ddname_OUT);

    try (
      Scanner scanner_IN = new Scanner(dd_IN);
      BufferedWriter writer_OUT = new BufferedWriter(new FileWriter(dd_OUT))
      ) {
      String a;
      String b;
      String c;
      String d;
      String c1;
      String x = "XXXXX";
      String data_IN;
      String data_OUT;
      int ib;

      while (scanner_IN.hasNextLine()) {
        data_IN = scanner_IN.nextLine();
        ib = 0;
        a = data_IN.substring(ib, ib += 5);
        b = data_IN.substring(ib, ib += 5);
        c = data_IN.substring(ib, ib += 4);
        c1=Integer.toHexString(new Byte((c.getBytes())[0]).intValue());
        if (c1.length()<2) { c1="0" + c1; }
        data_OUT = a + c1 + x;
        writer_OUT.write(data_OUT);
        writer_OUT.newLine();
        System.out.println(data_IN);
        System.out.println(data_OUT);
        System.out.println();
      }
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
    return;
  }
}
Task: Idiomatically determine all the characters that can be used for symbols




Go: package main

import (
	"fmt"
	"go/ast"
	"go/parser"
	"strings"
	"unicode"
)

func isValidIdentifier(identifier string) bool {
	node, err := parser.ParseExpr(identifier)
	if err != nil {
		return false
	}
	ident, ok := node.(*ast.Ident)
	return ok && ident.Name == identifier
}

type runeRanges struct {
	ranges   []string
	hasStart bool
	start    rune
	end      rune
}

func (r *runeRanges) add(cp rune) {
	if !r.hasStart {
		r.hasStart = true
		r.start = cp
		r.end = cp
		return
	}

	if cp == r.end+1 {
		r.end = cp
		return
	}

	r.writeTo(&r.ranges)

	r.start = cp
	r.end = cp
}

func (r *runeRanges) writeTo(ranges *[]string) {
	if r.hasStart {
		if r.start == r.end {
			*ranges = append(*ranges, fmt.Sprintf("%U", r.end))
		} else {
			*ranges = append(*ranges, fmt.Sprintf("%U-%U", r.start, r.end))
		}
	}
}

func (r *runeRanges) String() string {
	ranges := r.ranges
	r.writeTo(&ranges)
	return strings.Join(ranges, ", ")
}

func main() {
	var validFirst runeRanges
	var validFollow runeRanges
	var validOnlyFollow runeRanges

	for r := rune(0); r <= unicode.MaxRune; r++ {
		first := isValidIdentifier(string([]rune{r}))
		follow := isValidIdentifier(string([]rune{'_', r}))
		if first {
			validFirst.add(r)
		}
		if follow {
			validFollow.add(r)
		}
		if follow && !first {
			validOnlyFollow.add(r)
		}
	}

	_, _ = fmt.Println("Valid first:", validFirst.String())
	_, _ = fmt.Println("Valid follow:", validFollow.String())
	_, _ = fmt.Println("Only follow:", validOnlyFollow.String())
}


Java: import java.util.function.IntPredicate;
import java.util.stream.IntStream;

public class Test {
    public static void main(String[] args) throws Exception {
        print("Java Identifier start:     ", 0, 0x10FFFF, 72,
                Character::isJavaIdentifierStart, "%c");

        print("Java Identifier part:      ", 0, 0x10FFFF, 25,
                Character::isJavaIdentifierPart, "[%d]");

        print("Identifier ignorable:      ", 0, 0x10FFFF, 25,
                Character::isIdentifierIgnorable, "[%d]");

        print("Unicode Identifier start:  ", 0, 0x10FFFF, 72,
                Character::isUnicodeIdentifierStart, "%c");

        print("Unicode Identifier part :  ", 0, 0x10FFFF, 25,
                Character::isUnicodeIdentifierPart, "[%d]");
    }

    static void print(String msg, int start, int end, int limit, 
        IntPredicate p, String fmt) {

        System.out.print(msg);
        IntStream.rangeClosed(start, end)
                .filter(p)
                .limit(limit)
                .forEach(cp -> System.out.printf(fmt, cp));
        System.out.println("...");
    }
}
Task: Assertions in design by contract




Go: func assert(t bool, s string) {
	if !t {
		panic(s)
	}
}

	assert(c == 0, "some text here")


Java: (...)
int feedForward(double[] inputs) {
    assert inputs.length == weights.length : "weights and input length mismatch";

    double sum = 0;
    for (int i = 0; i < weights.length; i++) {
        sum += inputs[i] * weights[i];
    }
    return activate(sum);
}
(...)
Task: Quoting constructs




Go: package main

import (
    "fmt"
    "os"
    "regexp"
    "strconv"
)








var (
    rl1 = 'a'
    rl2 = '\'' 
)



var (
    is1 = "abc"
    is2 = "\"ab\tc\"" 
)







var (
    rs1 = `
first"
second'
third"
`
    rs2 = `This is one way of including a ` + "`" + ` in a raw string literal.`
    rs3 = `\d+` 
)

func main() {
    fmt.Println(rl1, rl2) 
    fmt.Println(is1, is2)
    fmt.Println(rs1)
    fmt.Println(rs2)
    re := regexp.MustCompile(rs3)
    fmt.Println(re.FindString("abcd1234efgh"))

    

    
    n := 3
    fmt.Printf("\nThere are %d quoting constructs in Go.\n", n)

    
    
    s := "constructs"
    fmt.Println("There are", n, "quoting", s, "in Go.")

    
    
    mapper := func(placeholder string) string {
        switch placeholder {
        case "NUMBER":
            return strconv.Itoa(n)
        case "TYPES":
            return s
        }
        return ""
    }
    fmt.Println(os.Expand("There are ${NUMBER} quoting ${TYPES} in Go.", mapper))
}


Java: module test
    {
    @Inject Console console;
    void run()
        {
        
        Char ch = 'x';
        console.print( $"ch={ch.quoted()}");

        
        String greeting = "Hello";
        console.print( $"greeting={greeting.quoted()}");

        
        
        
        String lines = \|first line
                        |second line\
                        | continued
                       ;
        console.print($|lines=
                       |{lines}
                     );

        
        
        String name = "Bob";
        String msg  = $|{greeting} {name},
                       |Have a nice day!
                       |{ch}{ch}{ch}
                      ;
        console.print($|msg=
                       |{msg}
                     );
        }
    }
Task: Chinese remainder theorem



C#: using System;
using System.Linq;

namespace ChineseRemainderTheorem
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] n = { 3, 5, 7 };
            int[] a = { 2, 3, 2 };

            int result = ChineseRemainderTheorem.Solve(n, a);

            int counter = 0;
            int maxCount = n.Length - 1;
            while (counter <= maxCount)
            {
                Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})");
                counter++;
            }
        }
    }

    public static class ChineseRemainderTheorem
    {
        public static int Solve(int[] n, int[] a)
        {
            int prod = n.Aggregate(1, (i, j) => i * j);
            int p;
            int sm = 0;
            for (int i = 0; i < n.Length; i++)
            {
                p = prod / n[i];
                sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p;
            }
            return sm % prod;
        }

        private static int ModularMultiplicativeInverse(int a, int mod)
        {
            int b = a % mod;
            for (int x = 1; x < mod; x++)
            {
                if ((b * x) % mod == 1)
                {
                    return x;
                }
            }
            return 1;
        }
    }
}





Python: 
def chinese_remainder(n, a):
    sum = 0
    prod = reduce(lambda a, b: a*b, n)

    for n_i, a_i in zip(n, a):
        p = prod / n_i
        sum += a_i * mul_inv(p, n_i) * p
    return sum % prod


def mul_inv(a, b):
    b0 = b
    x0, x1 = 0, 1
    if b == 1: return 1
    while a > 1:
        q = a / b
        a, b = b, a%b
        x0, x1 = x1 - q * x0, x0
    if x1 < 0: x1 += b0
    return x1

if __name__ == '__main__':
    n = [3, 5, 7]
    a = [2, 3, 2]
    print chinese_remainder(n, a)
Task: Pi



C#: using System;
using System.Numerics;

namespace PiCalc {
    internal class Program {
        private readonly BigInteger FOUR = new BigInteger(4);
        private readonly BigInteger SEVEN = new BigInteger(7);
        private readonly BigInteger TEN = new BigInteger(10);
        private readonly BigInteger THREE = new BigInteger(3);
        private readonly BigInteger TWO = new BigInteger(2);

        private BigInteger k = BigInteger.One;
        private BigInteger l = new BigInteger(3);
        private BigInteger n = new BigInteger(3);
        private BigInteger q = BigInteger.One;
        private BigInteger r = BigInteger.Zero;
        private BigInteger t = BigInteger.One;

        public void CalcPiDigits() {
            BigInteger nn, nr;
            bool first = true;
            while (true) {
                if ((FOUR*q + r - t).CompareTo(n*t) == -1) {
                    Console.Write(n);
                    if (first) {
                        Console.Write(".");
                        first = false;
                    }
                    nr = TEN*(r - (n*t));
                    n = TEN*(THREE*q + r)/t - (TEN*n);
                    q *= TEN;
                    r = nr;
                } else {
                    nr = (TWO*q + r)*l;
                    nn = (q*(SEVEN*k) + TWO + r*l)/(t*l);
                    q *= k;
                    t *= l;
                    l += TWO;
                    k += BigInteger.One;
                    n = nn;
                    r = nr;
                }
            }
        }

        private static void Main(string[] args) {
            new Program().CalcPiDigits();
        }
    }
}





Python: def calcPi():
    q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
    while True:
        if 4*q+r-t < n*t:
            yield n
            nr = 10*(r-n*t)
            n  = ((10*(3*q+r))//t)-10*n
            q  *= 10
            r  = nr
        else:
            nr = (2*q+r)*l
            nn = (q*(7*k)+2+(r*l))//(t*l)
            q  *= k
            t  *= l
            l  += 2
            k += 1
            n  = nn
            r  = nr

import sys
pi_digits = calcPi()
i = 0
for d in pi_digits:
    sys.stdout.write(str(d))
    i += 1
    if i == 40: print(""); i = 0
Task: Y combinator



C#: using System;

static class YCombinator<T, TResult>
{
    
    private delegate Func<T, TResult> RecursiveFunc(RecursiveFunc r);

    public static Func<Func<Func<T, TResult>, Func<T, TResult>>, Func<T, TResult>> Fix { get; } =
        f => ((RecursiveFunc)(g => f(x => g(g)(x))))(g => f(x => g(g)(x)));
}

static class Program
{
    static void Main()
    {
        var fac = YCombinator<int, int>.Fix(f => x => x < 2 ? 1 : x * f(x - 1));
        var fib = YCombinator<int, int>.Fix(f => x => x < 2 ? x : f(x - 1) + f(x - 2));

        Console.WriteLine(fac(10));
        Console.WriteLine(fib(10));
    }
}





Python: >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))
>>> [ Y(fac)(i) for i in range(10) ]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))
>>> [ Y(fib)(i) for i in range(10) ]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Task: Van Eck sequence



C#: using System.Linq; class Program { static void Main() {
    int a, b, c, d, e, f, g; int[] h = new int[g = 1000];
    for (a = 0, b = 1, c = 2; c < g; a = b, b = c++)
        for (d = a, e = b - d, f = h[b]; e <= b; e++)
            if (f == h[d--]) { h[c] = e; break; }
    void sho(int i) { System.Console.WriteLine(string.Join(" ",
        h.Skip(i).Take(10))); } sho(0); sho(990); } }





Python: def van_eck():
    n, seen, val = 0, {}, 0
    while True:
        yield val
        last = {val: n}
        val = n - seen.get(val, n)
        seen.update(last)
        n += 1

if __name__ == '__main__':
    print("Van Eck: first 10 terms:  ", list(islice(van_eck(), 10)))
    print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
Task: Loops_Continue



C#: using System;

class Program {
    static void Main(string[] args) {
        for (int i = 1; i <= 10; i++) {
            Console.Write(i);

            if (i % 5 == 0) {
                Console.WriteLine();
                continue;
            }

            Console.Write(", ");
        }
    }
}





Python: for i in range(1, 11):
    if i % 5 == 0:
        print(i)
        continue
    print(i, end=', ')
Task: General FizzBuzz



C#: using System;

public class GeneralFizzBuzz
{
    public static void Main() 
    {
        int i;
        int j;
        int k;
        
        int limit;
        
        string iString;
        string jString;
        string kString;

        Console.WriteLine("First integer:");
        i = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("First string:");
        iString = Console.ReadLine();

        Console.WriteLine("Second integer:");
        j = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Second string:");
        jString = Console.ReadLine();

        Console.WriteLine("Third integer:");
        k = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Third string:");
        kString = Console.ReadLine();

        Console.WriteLine("Limit (inclusive):");
        limit = Convert.ToInt32(Console.ReadLine());

        for(int n = 1; n<= limit; n++)
        {
            bool flag = true;
            if(n%i == 0)
            {
                Console.Write(iString);
                flag = false;
            }

            if(n%j == 0)
            {
                Console.Write(jString);
                flag = false;
            }

            if(n%k == 0)
            {
                Console.Write(kString);
                flag = false;
            }
            if(flag)
                Console.Write(n);
            Console.WriteLine();
        }
    }
}





Python: def genfizzbuzz(factorwords, numbers):
    
    factorwords.sort(key=lambda factor_and_word: factor_and_word[0])
    lines = []
    for num in numbers:
        words = ''.join(word for factor, word in factorwords if (num % factor) == 0)
        lines.append(words if words else str(num))
    return '\n'.join(lines)

if __name__ == '__main__':
    print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
Task: Checkpoint synchronization



C#: using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Rosetta.CheckPointSync;

public class Program
{
    public async Task Main()
    {
        RobotBuilder robotBuilder = new RobotBuilder();
        Task work = robotBuilder.BuildRobots(
            "Optimus Prime", "R. Giskard Reventlov", "Data", "Marvin",
            "Bender", "Number Six", "C3-PO", "Dolores");
        await work;
    }

    public class RobotBuilder
    {
        static readonly string[] parts = { "Head", "Torso", "Left arm", "Right arm", "Left leg", "Right leg" };
        static readonly Random rng = new Random();
        static readonly object key = new object();

        public Task BuildRobots(params string[] robots)
        {
            int r = 0;
            Barrier checkpoint = new Barrier(parts.Length, b => {
                Console.WriteLine($"{robots[r]} assembled. Hello, {robots[r]}!");
                Console.WriteLine();
                r++;
            });
            var tasks = parts.Select(part => BuildPart(checkpoint, part, robots)).ToArray();
            return Task.WhenAll(tasks);
        }

        private static int GetTime()
        {
            
            
            lock (key) {
                return rng.Next(100, 1000);
            }
        }

        private async Task BuildPart(Barrier barrier, string part, string[] robots)
        {
            foreach (var robot in robots) {
                int time = GetTime();
                Console.WriteLine($"Constructing {part} for {robot}. This will take {time}ms.");
                await Task.Delay(time);
                Console.WriteLine($"{part} for {robot} finished.");
                barrier.SignalAndWait();
            }
        }

    }
    
}





Python: 

import threading
import time
import random


def worker(workernum, barrier):
    
    sleeptime = random.random()
    print('Starting worker '+str(workernum)+" task 1, sleeptime="+str(sleeptime))
    time.sleep(sleeptime)
    print('Exiting worker'+str(workernum))
    barrier.wait()
    
    sleeptime = random.random()
    print('Starting worker '+str(workernum)+" task 2, sleeptime="+str(sleeptime))
    time.sleep(sleeptime)
    print('Exiting worker'+str(workernum))

barrier = threading.Barrier(3)

w1 = threading.Thread(target=worker, args=((1,barrier)))
w2 = threading.Thread(target=worker, args=((2,barrier)))
w3 = threading.Thread(target=worker, args=((3,barrier)))

w1.start()
w2.start()
w3.start()
Task: String case



C#: using System;

namespace StringCase
{
  class Program
  {
    public static void Main()
    {
      String input = scope .("alphaBETA");
      input.ToUpper();
      Console.WriteLine(input);
      input.ToLower();
      Console.WriteLine(input);
    }
  }
}





Python: s = "alphaBETA"
print s.upper() 
print s.lower() 

print s.swapcase() 

print "fOo bAR".capitalize() 
print "fOo bAR".title() 

import string
print string.capwords("fOo bAR")
Task: MD5



C#: using System.Text;
using System.Security.Cryptography;

byte[] data = Encoding.ASCII.GetBytes("The quick brown fox jumped over the lazy dog's back");
byte[] hash = MD5.Create().ComputeHash(data);
Console.WriteLine(BitConverter.ToString(hash).Replace("-", "").ToLower());





Python: >>> import hashlib
>>> 
>>> tests = (
  (b"", 'd41d8cd98f00b204e9800998ecf8427e'),
  (b"a", '0cc175b9c0f1b6a831c399e269772661'),
  (b"abc", '900150983cd24fb0d6963f7d28e17f72'),
  (b"message digest", 'f96b697d7cb7938d525a2f31aaf161d0'),
  (b"abcdefghijklmnopqrstuvwxyz", 'c3fcd3d76192e4007dfb496cca67e13b'),
  (b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 'd174ab98d277d9f5a5611c2c9f419d9f'),
  (b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", '57edf4a22be3c955ac49da2e2107b67a') )
>>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden

>>>
Task: Date manipulation



C#: class Program
{
    static void Main(string[] args)
    {
        CultureInfo ci=CultureInfo.CreateSpecificCulture("en-US");
        string dateString = "March 7 2009 7:30pm EST";
        string format = "MMMM d yyyy h:mmtt z";
        DateTime myDateTime = DateTime.ParseExact(dateString.Replace("EST","+6"),format,ci) ;
        DateTime newDateTime = myDateTime.AddHours(12).AddDays(1) ;
        Console.WriteLine(newDateTime.ToString(format).Replace("-5","EST")); 

        Console.ReadLine();
    }
}





Python: import datetime

def mt():
	datime1="March 7 2009 7:30pm EST"
	formatting = "%B %d %Y %I:%M%p "
	datime2 = datime1[:-3]  
	tdelta = datetime.timedelta(hours=12)		
	s3 = datetime.datetime.strptime(datime2, formatting)
	datime2 = s3+tdelta
	print datime2.strftime("%B %d %Y %I:%M%p %Z") + datime1[-3:]

mt()
Task: Sorting algorithms_Sleep sort



C#: using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

class Program
{
    static void ThreadStart(object item)
    {
        Thread.Sleep(1000 * (int)item);
        Console.WriteLine(item);
    }

    static void SleepSort(IEnumerable<int> items)
    {
        foreach (var item in items)
        {
            new Thread(ThreadStart).Start(item);
        }
    }

    static void Main(string[] arguments)
    {
        SleepSort(arguments.Select(int.Parse));
    }
}





Python: from time import sleep
from threading import Timer

def sleepsort(values):
    sleepsort.result = []
    def add1(x):
        sleepsort.result.append(x)
    mx = values[0]
    for v in values:
        if mx < v: mx = v
        Timer(v, add1, [v]).start()
    sleep(mx+1)
    return sleepsort.result

if __name__ == '__main__':
    x = [3,2,4,7,3,6,9,1]
    if sleepsort(x) == sorted(x):
        print('sleep sort worked for:',x)
    else:
        print('sleep sort FAILED for:',x)