WeixiangYan/CodeTransOcean huggingface dataset:
Task: Entropy

C: #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
 
#define MAXLEN 100 
 
int makehist(unsigned char *S,int *hist,int len){
	int wherechar[256];
	int i,histlen;
	histlen=0;
	for(i=0;i<256;i++)wherechar[i]=-1;
	for(i=0;i<len;i++){
		if(wherechar[(int)S[i]]==-1){
			wherechar[(int)S[i]]=histlen;
			histlen++;
		}
		hist[wherechar[(int)S[i]]]++;
	}
	return histlen;
}
 
double entropy(int *hist,int histlen,int len){
	int i;
	double H;
	H=0;
	for(i=0;i<histlen;i++){
		H-=(double)hist[i]/len*log2((double)hist[i]/len);
	}
	return H;
}
 
int main(void){
	unsigned char S[MAXLEN];
	int len,*hist,histlen;
	double H;
	scanf("%[^\n]",S);
	len=strlen(S);
	hist=(int*)calloc(len,sizeof(int));
	histlen=makehist(S,hist,len);
	
	H=entropy(hist,histlen,len);
	printf("%lf\n",H);
	return 0;
}



C#: using System;
using System.Collections.Generic;
namespace Entropy
{
	class Program
	{
		public static double logtwo(double num)
		{
			return Math.Log(num)/Math.Log(2);
		}
		public static void Main(string[] args)
		{
		label1:
			string input = Console.ReadLine();
			double infoC=0;
			Dictionary<char,double> table = new Dictionary<char, double>();

			
			foreach (char c in input)
			{
				if (table.ContainsKey(c))
					table[c]++;
				    else
				    	table.Add(c,1);
	
			}
			double freq;
			foreach (KeyValuePair<char,double> letter in table)
			{
				freq=letter.Value/input.Length;
				infoC+=freq*logtwo(freq);
			}
			infoC*=-1;
			Console.WriteLine("The Entropy of {0} is {1}",input,infoC);
			goto label1;
		
		}
	}
}
Task: Tokenize a string with escaping

C: #include <stdlib.h>
#include <stdio.h>

#define STR_DEMO "one^|uno||three^^^^|four^^^|^cuatro|"
#define SEP '|'
#define ESC '^'

typedef char* Str; 


unsigned int ElQ( const char *s, char sep, char esc );
Str *Tokenize( char *s, char sep, char esc, unsigned int *q );



int main() {
    char s[] = STR_DEMO;
    unsigned int i, q;

    Str *list = Tokenize( s, SEP, ESC, &q );

    if( list != NULL ) {
        printf( "\n Original string: %s\n\n", STR_DEMO );
        printf( " %d tokens:\n\n", q );

        for( i=0; i<q; ++i )
            printf( " %4d. %s\n", i+1, list[i] );

        free( list );
    }

    return 0;
}



unsigned int ElQ( const char *s, char sep, char esc ) {
    unsigned int q, e;
    const char *p;

    for( e=0, q=1, p=s; *p; ++p ) {
        if( *p == esc )
            e = !e;
        else if( *p == sep )
            q += !e;
        else e = 0;
    }

    return q;
}



Str *Tokenize( char *s, char sep, char esc, unsigned int *q ) {
    Str *list = NULL;

    *q = ElQ( s, sep, esc );
    list = malloc( *q * sizeof(Str) );

    if( list != NULL ) {
        unsigned int e, i;
        char *p;

        i = 0;
        list[i++] = s;

        for( e=0, p=s; *p; ++p ) {
            if( *p == esc ) {
                e = !e;
            }
            else if( *p == sep && !e ) {
                list[i++] = p+1;
                *p = '\0';
            }
            else {
                e = 0;
            }
        }
    }

    return list;
}



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

public class TokenizeAStringWithEscaping
{
    public static void Main() {
        string testcase = "one^|uno||three^^^^|four^^^|^cuatro|";
        foreach (var token in testcase.Tokenize(separator: '|', escape: '^')) {
            Console.WriteLine(": " + token); 
        }
    }
}

public static class Extensions
{
    public static IEnumerable<string> Tokenize(this string input, char separator, char escape) {
        if (input == null) yield break;
        var buffer = new StringBuilder();
        bool escaping = false;
        foreach (char c in input) {
            if (escaping) {
                buffer.Append(c);
                escaping = false;
            } else if (c == escape) {
                escaping = true;
            } else if (c == separator) {
                yield return buffer.Flush();
            } else {
                buffer.Append(c);
            }
        }
        if (buffer.Length > 0 || input[input.Length-1] == separator) yield return buffer.Flush();
    }
    
    public static string Flush(this StringBuilder stringBuilder) {
        string result = stringBuilder.ToString();
        stringBuilder.Clear();
        return result;
    }
}
Task: Hello world_Text

C: const hello = "Hello world!\n"

print(hello)



C#: Using System;
namespace HelloWorld {
  class Program
  {
    static void Main()
    {
      Console.Writeln("Hello World!");
    }
  }
}
Task: Forward difference

C: #include <stdlib.h>
#include <string.h>
#include <stdio.h>

double* fwd_diff(double* x, unsigned int len, unsigned int order)
{
	unsigned int i, j;
	double* y;

	
	if (order >= len) return 0;

	y = malloc(sizeof(double) * len);
	if (!order) {
		memcpy(y, x, sizeof(double) * len);
		return y;
	}

	
	for (j = 0; j < order; j++, x = y)
		for (i = 0, len--; i < len; i++)
			y[i] = x[i + 1] - x[i];

	y = realloc(y, sizeof(double) * len);
	return y;
}

int main(void)
{
	double *y, x[] = {90, 47, 58, 29, 22, 32, 55, 5, 55, 73};
	int i, len = sizeof(x) / sizeof(x[0]);

	y = fwd_diff(x, len, 1);
	for (i = 0; i < len - 1; i++)
		printf("%g ", y[i]);
	putchar('\n');

	return 0;
}



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

class Program
{
    static IEnumerable<int> ForwardDifference(IEnumerable<int> sequence, uint order = 1u)
    {
        switch (order)
        {
            case 0u:
                return sequence;
            case 1u:
                return sequence.Skip(1).Zip(sequence, (next, current) => next - current);
            default:
                return ForwardDifference(ForwardDifference(sequence), order - 1u);
        }
    }

    static void Main()
    {
        IEnumerable<int> sequence = new[] { 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 };
        do
        {
            Console.WriteLine(string.Join(", ", sequence));
        } while ((sequence = ForwardDifference(sequence)).Any());
    }
}
Task: Primality by trial division

C: int is_prime(unsigned int n)
{
	unsigned int p;
	if (!(n & 1) || n < 2 ) return n == 2;

	
	for (p = 3; p <= n/p; p += 2)
		if (!(n % p)) return 0;
	return 1;
}



C#: static bool isPrime(int n)
        {
            if (n <= 1) return false;
            for (int i = 2; i * i <= n; i++)            
                if (n % i == 0) return false;            
            return true;
        }
Task: Evaluate binomial coefficients

C: #include <stdio.h>
#include <limits.h>



static unsigned long gcd_ui(unsigned long x, unsigned long y) {
  unsigned long t;
  if (y < x) { t = x; x = y; y = t; }
  while (y > 0) {
    t = y;  y = x % y;  x = t;  
  }
  return x;
}

unsigned long binomial(unsigned long n, unsigned long k) {
  unsigned long d, g, r = 1;
  if (k == 0) return 1;
  if (k == 1) return n;
  if (k >= n) return (k == n);
  if (k > n/2) k = n-k;
  for (d = 1; d <= k; d++) {
    if (r >= ULONG_MAX/n) {  
      unsigned long nr, dr;  
      g = gcd_ui(n, d);  nr = n/g;  dr = d/g;
      g = gcd_ui(r, dr);  r = r/g;  dr = dr/g;
      if (r >= ULONG_MAX/nr) return 0;  
      r *= nr;
      r /= dr;
      n--;
    } else {
      r *= n--;
      r /= d;
    }
  }
  return r;
}

int main() {
    printf("%lu\n", binomial(5, 3));
    printf("%lu\n", binomial(40, 19));
    printf("%lu\n", binomial(67, 31));
    return 0;
}



C#: using System;

namespace BinomialCoefficients
{
    class Program
    {
        static void Main(string[] args)
        {
            ulong n = 1000000, k = 3;
            ulong result = biCoefficient(n, k);
            Console.WriteLine("The Binomial Coefficient of {0}, and {1}, is equal to: {2}", n, k, result);
            Console.ReadLine();
        }

        static int fact(int n)
        {
            if (n == 0) return 1;
            else return n * fact(n - 1);
        }

        static ulong biCoefficient(ulong n, ulong k)
        {
            if (k > n - k)
            {
                k = n - k;
            }

            ulong c = 1;
            for (uint i = 0; i < k; i++)
            {
                c = c * (n - i);
                c = c / (i + 1);
            }
            return c;
        }
    }
}
Task: Collections

C: #define cSize( a )  ( sizeof(a)/sizeof(a[0]) ) 
int ar[10];               
ar[0] = 1;                
ar[1] = 2;

int* p;                   
for (p=ar;                
       p<(ar+cSize(ar));  
       p++) {             
  printf("%d\n",*p);      
}                         



C#: 
int[] intArray = new int[5] { 1, 2, 3, 4, 5 };

int[] intArray = new int[]{ 1, 2, 3, 4, 5 };

int[] intArray = { 1, 2, 3, 4, 5 };


string[] stringArr = new string[5];
stringArr[0] = "string";
Task: Singly-linked list_Traversal

C: struct link *first;

struct link *iter;
for(iter = first; iter != NULL; iter = iter->next) {
  
}



C#: var current = [head of list to traverse]
while(current != null)
{
    

    current = current.Next;
}
Task: Bitmap_Write a PPM file

C: #include <stdlib.h>
#include <stdio.h>

int main(void)
{
  const int dimx = 800, dimy = 800;
  int i, j;
  FILE *fp = fopen("first.ppm", "wb"); 
  (void) fprintf(fp, "P6\n%d %d\n255\n", dimx, dimy);
  for (j = 0; j < dimy; ++j)
  {
    for (i = 0; i < dimx; ++i)
    {
      static unsigned char color[3];
      color[0] = i % 256;  
      color[1] = j % 256;  
      color[2] = (i * j) % 256;  
      (void) fwrite(color, 1, 3, fp);
    }
  }
  (void) fclose(fp);
  return EXIT_SUCCESS;
}



C#: using System;
using System.IO;
class PPMWriter
{
    public static void WriteBitmapToPPM(string file, Bitmap bitmap)
        {
            
            var writer = new StreamWriter(file);
            writer.WriteLine("P6");
            writer.WriteLine($"{bitmap.Width}  {bitmap.Height}");
            writer.WriteLine("255");
            writer.Close();
            
            var writerB = new BinaryWriter(new FileStream(file, FileMode.Append));
            for (int x = 0; x < bitmap.Height; x++)
                for (int y = 0; y < bitmap.Width; y++)
                {
                    Color color = bitmap.GetPixel(y, x);
                    writerB.Write(color.R);
                    writerB.Write(color.G);
                    writerB.Write(color.B);
                }
            writerB.Close();
        }
}
Task: Delete a file

C: #include <stdio.h>

int main() {
  remove("input.txt");
  remove("/input.txt");
  remove("docs");
  remove("/docs");
  return 0;
}



C#: using System;
using System.IO;

namespace DeleteFile {
  class Program {
    static void Main() {
      File.Delete("input.txt");
      Directory.Delete("docs");
      File.Delete("/input.txt");
      Directory.Delete("/docs");
    }
  }
}
Task: Bitwise operations




Go: package main

import "fmt"

func bitwise(a, b int16) {
	fmt.Printf("a:   %016b\n", uint16(a))
	fmt.Printf("b:   %016b\n", uint16(b))

	
	fmt.Printf("and: %016b\n", uint16(a&b))
	fmt.Printf("or:  %016b\n", uint16(a|b))
	fmt.Printf("xor: %016b\n", uint16(a^b))
	fmt.Printf("not: %016b\n", uint16(^a))

	if b < 0 {
		fmt.Println("Right operand is negative, but all shifts require an unsigned right operand (shift distance).")
		return
	}
	ua := uint16(a)
	ub := uint32(b)

	
	fmt.Printf("shl: %016b\n", uint16(ua<<ub))
	fmt.Printf("shr: %016b\n", uint16(ua>>ub))

	
	fmt.Printf("las: %016b\n", uint16(a<<ub))
	fmt.Printf("ras: %016b\n", uint16(a>>ub))

	
	fmt.Printf("rol: %016b\n", uint16(a<<ub|int16(uint16(a)>>(16-ub))))
	fmt.Printf("ror: %016b\n", uint16(int16(uint16(a)>>ub)|a<<(16-ub)))
}

func main() {
	var a, b int16 = -460, 6
	bitwise(a, b)
}





VB: Debug.Print Hex(&HF0F0 And &HFF00)  
Debug.Print Hex(&HF0F0 Or &HFF00)   
Debug.Print Hex(&HF0F0 Xor &HFF00)  
Debug.Print Hex(Not &HF0F0)         
Debug.Print Hex(&HF0F0 Eqv &HFF00)  
Debug.Print Hex(&HF0F0 Imp &HFF00)
Task: Read a file line by line




Go: package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
)

func init() {
	log.SetFlags(log.Lshortfile)
}

func main() {
	
	inputFile, err := os.Open("byline.go")
	if err != nil {
		log.Fatal("Error opening input file:", err)
	}

	
	
	
	defer inputFile.Close()

	scanner := bufio.NewScanner(inputFile)

	
	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}

	
	
	if err := scanner.Err(); err != nil {
		log.Fatal(scanner.Err())
	}
}





VB: $Include "Rapidq.inc"
dim file as qfilestream

if file.open("c:\A Test.txt", fmOpenRead) then
    while not File.eof
        print File.readline
    wend
else
    print "Cannot read file"
end if

input "Press enter to exit: ";a$
Task: Doubly-linked list_Element insertion




Go: package main

import "fmt"

type dlNode struct {
    string
    next, prev *dlNode
}

type dlList struct {
    head, tail *dlNode
}

func (list *dlList) String() string {
    if list.head == nil {
        return fmt.Sprint(list.head)
    }
    r := "[" + list.head.string
    for p := list.head.next; p != nil; p = p.next {
        r += " " + p.string
    }
    return r + "]"
}

func (list *dlList) insertTail(node *dlNode) {
    if list.tail == nil {
        list.head = node
    } else {
        list.tail.next = node
    }
    node.next = nil
    node.prev = list.tail
    list.tail = node
}

func (list *dlList) insertAfter(existing, insert *dlNode) {
    insert.prev = existing
    insert.next = existing.next
    existing.next.prev = insert
    existing.next = insert
    if existing == list.tail {
        list.tail = insert
    }
}

func main() {
    dll := &dlList{}
    fmt.Println(dll)
    a := &dlNode{string: "A"}
    dll.insertTail(a)
    dll.insertTail(&dlNode{string: "B"})
    fmt.Println(dll)
    dll.insertAfter(a, &dlNode{string: "C"})
    fmt.Println(dll)
}





VB: Public Sub Insert(ByVal a As Node(Of T), ByVal b As Node(Of T), ByVal c As T)
    Dim node As New Node(Of T)(value)
    a.Next = node
    node.Previous = a
    b.Previous = node
    node.Next = b
End Sub
Task: Quickselect algorithm




Go: package main

import "fmt"

func quickselect(list []int, k int) int {
    for {
        
        px := len(list) / 2
        pv := list[px]
        last := len(list) - 1
        list[px], list[last] = list[last], list[px]
        i := 0
        for j := 0; j < last; j++ {
            if list[j] < pv {
                list[i], list[j] = list[j], list[i]
                i++
            }
        }
        
        if i == k {
            return pv
        }
        if k < i {
            list = list[:i]
        } else {
            list[i], list[last] = list[last], list[i]
            list = list[i+1:]
            k -= i + 1
        }
    }
}

func main() {
    for i := 0; ; i++ {
        v := []int{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}
        if i == len(v) {
            return
        }
        fmt.Println(quickselect(v, i))
    }
}





VB: Dim s As Variant
Private Function quick_select(ByRef s As Variant, k As Integer) As Integer
    Dim left As Integer, right As Integer, pos As Integer
    Dim pivotValue As Integer, tmp As Integer
    left = 1: right = UBound(s)
    Do While left < right
        pivotValue = s(k)
        tmp = s(k)
        s(k) = s(right)
        s(right) = tmp
        pos = left
        For i = left To right
            If s(i) < pivotValue Then
                tmp = s(i)
                s(i) = s(pos)
                s(pos) = tmp
                pos = pos + 1
            End If
        Next i
        tmp = s(right)
        s(right) = s(pos)
        s(pos) = tmp
        If pos = k Then
            Exit Do
        End If
        If pos < k Then
            left = pos + 1
        Else
            right = pos - 1
        End If
    Loop
    quick_select = s(k)
End Function
Public Sub main()
    Dim r As Integer, i As Integer
    s = [{9, 8, 7, 6, 5, 0, 1, 2, 3, 4}]
    For i = 1 To 10
        r = quick_select(s, i) 
        Debug.Print IIf(i < 10, r & ", ", "" & r);
    Next i
End Sub
Task: Non-decimal radices_Convert




Go: package main

import (
    "fmt"
    "math/big"
    "strconv"
)

func main () {
    s := strconv.FormatInt(26, 16) 
    fmt.Println(s)

    i, err := strconv.ParseInt("1a", 16, 64) 
    if err == nil {
        fmt.Println(i)
    }
    b, ok := new(big.Int).SetString("1a", 16) 
    if ok {
        fmt.Println(b)
    }
}





VB: Private Function to_base(ByVal number As Long, base As Integer) As String
    Dim digits As String, result As String
    Dim i As Integer, digit As Integer
    digits = "0123456789abcdefghijklmnopqrstuvwxyz"
    Do While number > 0
        digit = number Mod base
        result = Mid(digits, digit + 1, 1) & result
        number = number \ base
    Loop
    to_base = result
End Function
Private Function from_base(number As String, base As Integer) As Long
    Dim digits As String, result As Long
    Dim i As Integer
    digits = "0123456789abcdefghijklmnopqrstuvwxyz"
    result = Val(InStr(1, digits, Mid(number, 1, 1), vbTextCompare) - 1)
    For i = 2 To Len(number)
        result = result * base + Val(InStr(1, digits, Mid(number, i, 1), vbTextCompare) - 1)
    Next i
    from_base = result
End Function
Public Sub Non_decimal_radices_Convert()
    Debug.Print "26 decimal in base 16 is: "; to_base(26, 16); ". Conversely, hexadecimal 1a in decimal is: "; from_base("1a", 16)
End Sub
Task: Walk a directory_Recursively




Go: package main

import (
    "fmt"
    "os"
    "path/filepath"
)

func VisitFile(fp string, fi os.FileInfo, err error) error {
    if err != nil {
        fmt.Println(err) 
        return nil       
    }
    if fi.IsDir() {
        return nil 
    }
    matched, err := filepath.Match("*.mp3", fi.Name())
    if err != nil {
        fmt.Println(err) 
        return err       
    }
    if matched {
        fmt.Println(fp)
    }
    return nil
}

func main() {
    filepath.Walk("/", VisitFile)
}





VB: Sub printFiles(parentDir As FolderItem, pattern As String)
  For i As Integer = 1 To parentDir.Count
    If parentDir.Item(i).Directory Then
      printFiles(parentDir.Item(i), pattern)
    Else
      Dim rg as New RegEx
      Dim myMatch as RegExMatch
      rg.SearchPattern = pattern
      myMatch = rg.search(parentDir.Item(i).Name)
      If myMatch <> Nil Then Print(parentDir.Item(i).AbsolutePath)
    End If
  Next
End Sub
Task: CRC-32




Go: package main

import (
    "fmt"
    "hash/crc32"
)

func main() {
    s := []byte("The quick brown fox jumps over the lazy dog")
    result := crc32.ChecksumIEEE(s)
    fmt.Printf("%X\n", result)
}





VB: dim crctbl(255)
const crcc =&hEDB88320

sub gencrctable
for i= 0 to 255
   k=i
   for j=1 to 8
    if k and 1 then 
      k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0)) 
      k=k xor crcc
    else 
      k=(k and &h7fffffff)\2 or (&h40000000 and ((k and &h80000000)<>0))
   end if
   next 
   crctbl(i)=k
 next
end sub
 
 function crc32 (buf) 
  dim r,r1,i 
  r=&hffffffff 
  for i=1 to len(buf) 
      r1=(r and &h7fffffff)\&h100 or (&h800000 and (r and &h80000000)<>0)
    r=r1 xor crctbl((asc(mid(buf,i,1))xor r) and 255) 
  next 
  crc32=r xor &hffffffff
end function

  

gencrctable
wscript.stdout.writeline hex(crc32("The quick brown fox jumps over the lazy dog"))
Task: CSV to HTML translation




Go: package main

import (
    "bytes"
    "encoding/csv"
    "fmt"
    "html/template"
    "strings"
)

var c = `Character,Speech
The multitude,The messiah! Show us the messiah!
Brians mother,<angry>Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!</angry>
The multitude,Who are you?
Brians mother,I'm his mother; that's who!
The multitude,Behold his mother! Behold his mother!`

func main() {
    if h, err := csvToHtml(c); err != nil {
        fmt.Println(err)
    } else {
        fmt.Print(h)
    }
}

func csvToHtml(c string) (string, error) {
    data, err := csv.NewReader(bytes.NewBufferString(c)).ReadAll()
    if err != nil {
        return "", err
    }
    var b strings.Builder
    err = template.Must(template.New("").Parse(`<table>
{{range .}}    <tr>{{range .}}<td>{{.}}</td>{{end}}</tr>
{{end}}</table>
`)).Execute(&b, data)
    return b.String(), err
}





VB: Public Sub CSV_TO_HTML()
    input_ = "Character,Speech\n" & _
        "The multitude,The messiah! Show us the messiah!\n" & _
        "Brians mother,<angry>Now you listen here! He
            "he
        "The multitude,Who are you?\n" & _
        "Brians mother,I
        "The multitude,Behold his mother! Behold his mother!"
     
    Debug.Print "<table>" & vbCrLf & "<tr><td>"
    For i = 1 To Len(input_)
        Select Case Mid(input_, i, 1)
            Case "\"
                If Mid(input_, i + 1, 1) = "n" Then
                    Debug.Print "</td></tr>" & vbCrLf & "<tr><td>";
                    i = i + 1
                Else
                    Debug.Print Mid(input_, i, 1);
                End If
            Case ",": Debug.Print "</td><td>";
            Case "<": Debug.Print "&lt;";
            Case ">": Debug.Print "&gt;";
            Case "&": Debug.Print "&amp;";
            Case Else: Debug.Print Mid(input_, i, 1);
        End Select
    Next i
    Debug.Print "</td></tr>" & vbCrLf & "</table>"
End Sub
Task: Classes




Go: package main

import "fmt"




type picnicBasket struct {
    nServings int 
    corkscrew bool
}


func (b *picnicBasket) happy() bool {
    return b.nServings > 1 && b.corkscrew
}









func newPicnicBasket(nPeople int) *picnicBasket {
    
    
    
    
    return &picnicBasket{nPeople, nPeople > 0}
}


func main() {
    var pb picnicBasket          
    pbl := picnicBasket{}        
    pbp := &picnicBasket{}       
    pbn := new(picnicBasket)     
    forTwo := newPicnicBasket(2) 
    
    forToo := &picnicBasket{nServings: 2, corkscrew: true}

    fmt.Println(pb.nServings, pb.corkscrew)
    fmt.Println(pbl.nServings, pbl.corkscrew)
    fmt.Println(pbp)
    fmt.Println(pbn)
    fmt.Println(forTwo)
    fmt.Println(forToo)
}





VB: Class NumberContainer
  Private TheNumber As Integer
  Sub Constructor(InitialNumber As Integer)
    TheNumber = InitialNumber
  End Sub

  Function Number() As Integer
    Return TheNumber
  End Function

  Sub Number(Assigns NewNumber As Integer)
    TheNumber = NewNumber
  End Sub
End Class