WeixiangYan/CodeTransOcean huggingface dataset:
Task: Just in time processing on a character stream



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

namespace JustInTimeProcessing {
    struct UserInput {
        public UserInput(string ff, string lf, string tb, string sp) {
            FormFeed = (char)int.Parse(ff);
            LineFeed = (char)int.Parse(lf);
            Tab = (char)int.Parse(tb);
            Space = (char)int.Parse(sp);
        }

        public char FormFeed { get; }
        public char LineFeed { get; }
        public char Tab { get; }
        public char Space { get; }
    }

    class Program {
        static List<UserInput> GetUserInput() {
            string h = "0 18 0 0 0 68 0 1 0 100 0 32 0 114 0 45 0 38 0 26 0 16 0 21 0 17 0 59 0 11 "
                + "0 29 0 102 0 0 0 10 0 50 0 39 0 42 0 33 0 50 0 46 0 54 0 76 0 47 0 84 2 28";
            return h.Split(' ')
                .Select((x, idx) => new { x, idx })
                .GroupBy(x => x.idx / 4)
                
                .Select(g => {
                    var ge = g.Select(a => a.x).ToArray();
                    return new UserInput(ge[0], ge[1], ge[2], ge[3]);
                })
                .ToList();
        }

        static void Decode(string filename, List<UserInput> uiList) {
            string text = System.IO.File.ReadAllText(filename);

            bool Decode2(UserInput ui) {
                char f = (char)0;
                char l = (char)0;
                char t = (char)0;
                char s = (char)0;

                foreach (char c in text) {
                    if (f == ui.FormFeed && l == ui.LineFeed && t == ui.Tab && s == ui.Space) {
                        if (c == '!') return false;
                        Console.Write(c);
                        return true;
                    }
                    if (c == '\u000c') {
                        f++; l = (char)0; t = (char)0; s = (char)0;
                    } else if (c == '\n') {
                        l++; t = (char)0; s = (char)0;
                    } else if (c == '\t') {
                        t++; s = (char)0;
                    } else {
                        s++;
                    }
                }

                return false;
            }

            foreach (UserInput ui in uiList) {
                if (!Decode2(ui)) {
                    break;
                }
            }
            Console.WriteLine();
        }

        static void Main(string[] args) {
            var uiList = GetUserInput();
            Decode("theraven.txt", uiList);

            Console.ReadLine();
        }
    }
}
Task: Montgomery reduction



C#: using System;
using System.Numerics;

namespace MontgomeryReduction {
    public static class Helper {
        public static int BitLength(this BigInteger v) {
            if (v < 0) {
                v *= -1;
            }

            int result = 0;
            while (v > 0) {
                v >>= 1;
                result++;
            }

            return result;
        }
    }

    struct Montgomery {
        public static readonly int BASE = 2;

        public BigInteger m;
        public BigInteger rrm;
        public int n;

        public Montgomery(BigInteger m) {
            if (m < 0 || m.IsEven) throw new ArgumentException();

            this.m = m;
            n = m.BitLength();
            rrm = (BigInteger.One << (n * 2)) % m;
        }

        public BigInteger Reduce(BigInteger t) {
            var a = t;

            for (int i = 0; i < n; i++) {
                if (!a.IsEven) a += m;
                a = a >> 1;
            }
            if (a >= m) a -= m;
            return a;
        }
    }

    class Program {
        static void Main(string[] args) {
            var m = BigInteger.Parse("750791094644726559640638407699");
            var x1 = BigInteger.Parse("540019781128412936473322405310");
            var x2 = BigInteger.Parse("515692107665463680305819378593");

            var mont = new Montgomery(m);
            var t1 = x1 * mont.rrm;
            var t2 = x2 * mont.rrm;

            var r1 = mont.Reduce(t1);
            var r2 = mont.Reduce(t2);
            var r = BigInteger.One << mont.n;

            Console.WriteLine("b :  {0}", Montgomery.BASE);
            Console.WriteLine("n :  {0}", mont.n);
            Console.WriteLine("r :  {0}", r);
            Console.WriteLine("m :  {0}", mont.m);
            Console.WriteLine("t1:  {0}", t1);
            Console.WriteLine("t2:  {0}", t2);
            Console.WriteLine("r1:  {0}", r1);
            Console.WriteLine("r2:  {0}", r2);
            Console.WriteLine();
            Console.WriteLine("Original x1       : {0}", x1);
            Console.WriteLine("Recovered from r1 : {0}", mont.Reduce(r1));
            Console.WriteLine("Original x2       : {0}", x2);
            Console.WriteLine("Recovered from r2 : {0}", mont.Reduce(r2));

            Console.WriteLine();
            Console.WriteLine("Montgomery computation of x1 ^ x2 mod m :");
            var prod = mont.Reduce(mont.rrm);
            var @base = mont.Reduce(x1 * mont.rrm);
            var exp = x2;
            while (exp.BitLength() > 0) {
                if (!exp.IsEven) prod = mont.Reduce(prod * @base);
                exp >>= 1;
                @base = mont.Reduce(@base * @base);
            }
            Console.WriteLine(mont.Reduce(prod));
            Console.WriteLine();
            Console.WriteLine("Alternate computation of x1 ^ x2 mod m :");
            Console.WriteLine(BigInteger.ModPow(x1, x2, m));
        }
    }
}
Task: Commatizing numbers



C#: static string[] inputs = {
	"pi=3.14159265358979323846264338327950288419716939937510582097494459231",
	"The author has two Z$100000000000000 Zimbabwe notes (100 trillion).",
	"\"-in Aus$+1411.8millions\"",
	"===US$0017440 millions=== (in 2000 dollars)"
};

void Main()
{
	inputs.Select(s => Commatize(s, 0, 3, ","))
              .ToList()
              .ForEach(Console.WriteLine);
}

string Commatize(string text, int startPosition, int interval, string separator)
{
	var matches = Regex.Matches(text.Substring(startPosition), "[0-9]*");
	var x = matches.Cast<Match>().Select(match => Commatize(match, interval, separator, text)).ToList();
	return string.Join("", x);
}


string Commatize(Match match, int interval, string separator, string original)
{
	if (match.Length <= interval)
		return original.Substring(match.Index, 
                match.Index == original.Length ? 0 : Math.Max(match.Length, 1));
	
	return string.Join(separator, match.Value.Split(interval));
}

public static class Extension
{
	public static string[] Split(this string source, int interval)
	{
		return SplitImpl(source, interval).ToArray();
	}
	
	static IEnumerable<string>SplitImpl(string source, int interval)
	{
		for	(int i = 1; i < source.Length; i++)
		{
			if (i % interval != 0) continue;
			
			yield return source.Substring(i - interval, interval);
		}
	}
}
Task: Suffix tree



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

namespace SuffixTree {
    class Node {
        public string sub;                     
        public List<int> ch = new List<int>(); 

        public Node() {
            sub = "";
        }

        public Node(string sub, params int[] children) {
            this.sub = sub;
            ch.AddRange(children);
        }
    }

    class SuffixTree {
        readonly List<Node> nodes = new List<Node>();

        public SuffixTree(string str) {
            nodes.Add(new Node());
            for (int i = 0; i < str.Length; i++) {
                AddSuffix(str.Substring(i));
            }
        }

        public void Visualize() {
            if (nodes.Count == 0) {
                Console.WriteLine("<empty>");
                return;
            }

            void f(int n, string pre) {
                var children = nodes[n].ch;
                if (children.Count == 0) {
                    Console.WriteLine("- {0}", nodes[n].sub);
                    return;
                }
                Console.WriteLine("+ {0}", nodes[n].sub);

                var it = children.GetEnumerator();
                if (it.MoveNext()) {
                    do {
                        var cit = it;
                        if (!cit.MoveNext()) break;

                        Console.Write("{0}+-", pre);
                        f(it.Current, pre + "| ");
                    } while (it.MoveNext());
                }

                Console.Write("{0}+-", pre);
                f(children[children.Count-1], pre+"  ");
            }

            f(0, "");
        }

        private void AddSuffix(string suf) {
            int n = 0;
            int i = 0;
            while (i < suf.Length) {
                char b = suf[i];
                int x2 = 0;
                int n2;
                while (true) {
                    var children = nodes[n].ch;
                    if (x2 == children.Count) {
                        
                        n2 = nodes.Count;
                        nodes.Add(new Node(suf.Substring(i)));
                        nodes[n].ch.Add(n2);
                        return;
                    }
                    n2 = children[x2];
                    if (nodes[n2].sub[0] == b) {
                        break;
                    }
                    x2++;
                }
                
                var sub2 = nodes[n2].sub;
                int j = 0;
                while (j < sub2.Length) {
                    if (suf[i + j] != sub2[j]) {
                        
                        var n3 = n2;
                        
                        n2 = nodes.Count;
                        nodes.Add(new Node(sub2.Substring(0, j), n3));
                        nodes[n3].sub = sub2.Substring(j); 
                        nodes[n].ch[x2] = n2;
                        break; 
                    }
                    j++;
                }
                i += j; 
                n = n2; 
            }
        }
    }

    class Program {
        static void Main() {
            new SuffixTree("banana$").Visualize();
        }
    }
}
Task: Reflection_List properties



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

public static class Reflection
{
    public static void Main() {
        var t = new TestClass();
        var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
        foreach (var prop in GetPropertyValues(t, flags)) {
            Console.WriteLine(prop);
        }
        foreach (var field in GetFieldValues(t, flags)) {
            Console.WriteLine(field);
        }
    }

    public static IEnumerable<(string name, object value)> GetPropertyValues<T>(T obj, BindingFlags flags) =>
        from p in typeof(T).GetProperties(flags)
        where p.GetIndexParameters().Length == 0 
        select (p.Name, p.GetValue(obj, null));
    
    public static IEnumerable<(string name, object value)> GetFieldValues<T>(T obj, BindingFlags flags) =>
        typeof(T).GetFields(flags).Select(f => (f.Name, f.GetValue(obj)));
    
    class TestClass
    {
        private int privateField = 7;
        public int PublicNumber { get; } = 4;
        private int PrivateNumber { get; } = 2;
    }

}
Task: Eertree



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

namespace Eertree {
    class Node {
        public Node(int length) {
            this.Length = length;
            
            this.Edges = new Dictionary<char, int>();
        }

        public Node(int length, Dictionary<char, int> edges, int suffix) {
            this.Length = length;
            this.Edges = edges;
            this.Suffix = suffix;
        }

        public int Length { get; set; }
        public Dictionary<char, int> Edges { get; set; }
        public int Suffix { get; set; }
    }

    class Program {
        const int EVEN_ROOT = 0;
        const int ODD_ROOT = 1;

        static List<Node> Eertree(string s) {
            List<Node> tree = new List<Node> {
                
                new Node(0, new Dictionary<char, int>(), ODD_ROOT),
                
                new Node(-1, new Dictionary<char, int>(), ODD_ROOT)
            };
            int suffix = ODD_ROOT;
            int n, k;
            for (int i = 0; i < s.Length; i++) {
                char c = s[i];
                for (n = suffix; ; n = tree[n].Suffix) {
                    k = tree[n].Length;
                    int b = i - k - 1;
                    if (b >= 0 && s[b] == c) {
                        break;
                    }
                }
                if (tree[n].Edges.ContainsKey(c)) {
                    suffix = tree[n].Edges[c];
                    continue;
                }
                suffix = tree.Count;
                tree.Add(new Node(k + 2));
                tree[n].Edges[c] = suffix;
                if (tree[suffix].Length == 1) {
                    tree[suffix].Suffix = 0;
                    continue;
                }
                while (true) {
                    n = tree[n].Suffix;
                    int b = i - tree[n].Length - 1;
                    if (b >= 0 && s[b] == c) {
                        break;
                    }
                }
                tree[suffix].Suffix = tree[n].Edges[c];
            }
            return tree;
        }

        static List<string> SubPalindromes(List<Node> tree) {
            List<string> s = new List<string>();
            SubPalindromes_children(0, "", tree, s);
            foreach (var c in tree[1].Edges.Keys) {
                int m = tree[1].Edges[c];
                string ct = c.ToString();
                s.Add(ct);
                SubPalindromes_children(m, ct, tree, s);
            }
            return s;
        }

        static void SubPalindromes_children(int n, string p, List<Node> tree, List<string> s) {
            foreach (var c in tree[n].Edges.Keys) {
                int m = tree[n].Edges[c];
                string p1 = c + p + c;
                s.Add(p1);
                SubPalindromes_children(m, p1, tree, s);
            }
        }

        static void Main(string[] args) {
            List<Node> tree = Eertree("eertree");
            List<string> result = SubPalindromes(tree);
            string listStr = string.Join(", ", result);
            Console.WriteLine("[{0}]", listStr);
        }
    }
}
Task: Base58Check encoding



C#: using System;
using System.Collections.Generic;
using System.Numerics;
using System.Text;

namespace Base58CheckEncoding {
    class Program {
        const string ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

        static BigInteger ToBigInteger(string value, int @base) {
            const string HEX = "0123456789ABCDEF";
            if (@base < 1 || @base > HEX.Length) {
                throw new ArgumentException("Base is out of range.");
            }

            BigInteger bi = BigInteger.Zero;
            foreach (char c in value) {
                char c2 = Char.ToUpper(c);
                int idx = HEX.IndexOf(c2);
                if (idx == -1 || idx >= @base) {
                    throw new ArgumentOutOfRangeException("Illegal character encountered.");
                }
                bi = bi * @base + idx;
            }

            return bi;
        }

        static string ConvertToBase58(string hash, int @base = 16) {
            BigInteger x;
            if (@base == 16 && hash.Substring(0, 2) == "0x") {
                x = ToBigInteger(hash.Substring(2), @base);
            } else {
                x = ToBigInteger(hash, @base);
            }

            StringBuilder sb = new StringBuilder();
            while (x > 0) {
                BigInteger r = x % 58;
                sb.Append(ALPHABET[(int)r]);
                x = x / 58;
            }

            char[] ca = sb.ToString().ToCharArray();
            Array.Reverse(ca);
            return new string(ca);
        }

        static void Main(string[] args) {
            string s = "25420294593250030202636073700053352635053786165627414518";
            string b = ConvertToBase58(s, 10);
            Console.WriteLine("{0} -> {1}", s, b);

            List<string> hashes = new List<string>() {
                "0x61",
                "0x626262",
                "0x636363",
                "0x73696d706c792061206c6f6e6720737472696e67",
                "0x516b6fcd0f",
                "0xbf4f89001e670274dd",
                "0x572e4794",
                "0xecac89cad93923c02321",
                "0x10c8511e",
            };
            foreach (string hash in hashes) {
                string b58 = ConvertToBase58(hash);
                Console.WriteLine("{0,-56} -> {1}", hash, b58);
            }
        }
    }
}
Task: Kosaraju



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

class Node
{
	public enum Colors
	{
		Black, White, Gray
	}

	public Colors color { get; set; }
	public int N { get; }
	
	public Node(int n)
	{
		N = n;
		color = Colors.White;
	}
}

class Graph
{
	public HashSet<Node> V { get; }
	public Dictionary<Node, HashSet<Node>> Adj { get; }

	
	
	
	public void Kosaraju()
	{
		var L = new HashSet<Node>();

		Action<Node> Visit = null;
		Visit = (u) =>
		{
			if (u.color == Node.Colors.White)
			{
				u.color = Node.Colors.Gray;

				foreach (var v in Adj[u])
					Visit(v);

				L.Add(u);
			}
		};

		Action<Node, Node> Assign = null;
		Assign = (u, root) =>
		{
			if (u.color != Node.Colors.Black)
			{
				if (u == root)
					Console.Write("SCC: ");

				Console.Write(u.N + " ");
				u.color = Node.Colors.Black;

				foreach (var v in Adj[u])
					Assign(v, root);

				if (u == root)
					Console.WriteLine();
			}
		};

		foreach (var u in V)
			Visit(u);

		foreach (var u in L)
			Assign(u, u);
	}
}
Task: Simulate input_Keyboard




Go: package main

import (
    "github.com/micmonay/keybd_event"
    "log"
    "runtime"
    "time"
)

func main() {
    kb, err := keybd_event.NewKeyBonding()
    if err != nil {
        log.Fatal(err)
    }

    
    if runtime.GOOS == "linux" {
        time.Sleep(2 * time.Second)
    }

    
    kb.SetKeys(keybd_event.VK_D, keybd_event.VK_I, keybd_event.VK_R, keybd_event.VK_ENTER)

    
    err = kb.Launching()
    if err != nil {
        log.Fatal(err)
    }
}
Task: Scope_Function names and labels




Go: package main

import (
    "fmt"
    "runtime"

    "ex"
)

func main() {
    

    
    f := func() {
        
        
        pc, _, _, _ := runtime.Caller(0)
        fmt.Println(runtime.FuncForPC(pc).Name(), "here!")
    }

    ex.X(f) 

    
}
Task: Largest palindrome product




Go: package main

import "fmt"

func reverse(n uint64) uint64 {
    r := uint64(0)
    for n > 0 {
        r = n%10 + r*10
        n /= 10
    }
    return r
}

func main() {
    pow := uint64(10)
nextN:
    for n := 2; n < 10; n++ {
        low := pow * 9
        pow *= 10
        high := pow - 1
        fmt.Printf("Largest palindromic product of two %d-digit integers: ", n)
        for i := high; i >= low; i-- {
            j := reverse(i)
            p := i*pow + j
            
            for k := high; k > low; k -= 2 {
                if k % 10 == 5 {
                    continue
                }
                l := p / k
                if l > high {
                    break
                }
                if p%k == 0 {
                    fmt.Printf("%d x %d = %d\n", k, l, p)
                    continue nextN
                }
            }
        }
    }
}
Task: Special pythagorean triplet




Go: package main

import (
    "fmt"
    "time"
)

func main() {
    start := time.Now()
    for a := 3; ; a++ {
        for b := a + 1; ; b++ {
            c := 1000 - a - b
            if c <= b {
                break
            }
            if a*a+b*b == c*c {
                fmt.Printf("a = %d, b = %d, c = %d\n", a, b, c)
                fmt.Println("a + b + c =", a+b+c)
                fmt.Println("a * b * c =", a*b*c)
                fmt.Println("\nTook", time.Since(start))
                return
            }
        }
    }
}
Task: Most frequent k chars distance




Go: package main

import (
    "fmt"
    "sort"
)

type cf struct {
    c rune
    f int
}

func reverseStr(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

func indexOfCf(cfs []cf, r rune) int {
    for i, cf := range cfs {
        if cf.c == r {
            return i
        }
    }
    return -1
}

func minOf(i, j int) int {
    if i < j {
        return i
    }
    return j
}

func mostFreqKHashing(input string, k int) string {
    var cfs []cf
    for _, r := range input {
        ix := indexOfCf(cfs, r)
        if ix >= 0 {
            cfs[ix].f++
        } else {
            cfs = append(cfs, cf{r, 1})
        }
    }
    sort.SliceStable(cfs, func(i, j int) bool {
        return cfs[i].f > cfs[j].f 
    })
    acc := ""
    min := minOf(len(cfs), k)
    for _, cf := range cfs[:min] {
        acc += fmt.Sprintf("%c%c", cf.c, cf.f)
    }
    return acc
}

func mostFreqKSimilarity(input1, input2 string) int {
    similarity := 0
    runes1, runes2 := []rune(input1), []rune(input2)
    for i := 0; i < len(runes1); i += 2 {
        for j := 0; j < len(runes2); j += 2 {
            if runes1[i] == runes2[j] {
                freq1, freq2 := runes1[i+1], runes2[j+1]
                if freq1 != freq2 {
                    continue 
                }
                similarity += int(freq1)
            }
        }
    }
    return similarity
}

func mostFreqKSDF(input1, input2 string, k, maxDistance int) {
    fmt.Println("input1 :", input1)
    fmt.Println("input2 :", input2)
    s1 := mostFreqKHashing(input1, k)
    s2 := mostFreqKHashing(input2, k)
    fmt.Printf("mfkh(input1, %d) = ", k)
    for i, c := range s1 {
        if i%2 == 0 {
            fmt.Printf("%c", c)
        } else {
            fmt.Printf("%d", c)
        }
    }
    fmt.Printf("\nmfkh(input2, %d) = ", k)
    for i, c := range s2 {
        if i%2 == 0 {
            fmt.Printf("%c", c)
        } else {
            fmt.Printf("%d", c)
        }
    }
    result := maxDistance - mostFreqKSimilarity(s1, s2)
    fmt.Printf("\nSDF(input1, input2, %d, %d) = %d\n\n", k, maxDistance, result)
}

func main() {
    pairs := [][2]string{
        {"research", "seeking"},
        {"night", "nacht"},
        {"my", "a"},
        {"research", "research"},
        {"aaaaabbbb", "ababababa"},
        {"significant", "capabilities"},
    }
    for _, pair := range pairs {
        mostFreqKSDF(pair[0], pair[1], 2, 10)
    }

    s1 := "LCLYTHIGRNIYYGSYLYSETWNTGIMLLLITMATAFMGYVLPWGQMSFWGATVITNLFSAIPYIGTNLV"
    s2 := "EWIWGGFSVDKATLNRFFAFHFILPFTMVALAGVHLTFLHETGSNNPLGLTSDSDKIPFHPYYTIKDFLG"
    mostFreqKSDF(s1, s2, 2, 100)
    s1 = "abracadabra12121212121abracadabra12121212121"
    s2 = reverseStr(s1)
    mostFreqKSDF(s1, s2, 2, 100)
}
Task: Print itself




Go: package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "path"
)

func main() {
    self := path.Base(os.Args[0]) + ".go"
    bytes, err := ioutil.ReadFile(self)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Print(string(bytes))
}
Task: Untrusted environment




Go: package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

func main() {
    bs := []byte("Hello world!")
    fmt.Println(string(bs))
    g := "globe"
    hdr := (*reflect.SliceHeader)(unsafe.Pointer(&bs))
    for i := 0; i < 5; i++ {
        data := (*byte)(unsafe.Pointer(hdr.Data + uintptr(i) + 6))
        *data = g[i]
    }
    fmt.Println(string(bs))
}