WeixiangYan/CodeTransOcean huggingface dataset:
Task: Write to Windows event log

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

int main(int argC,char* argV[])
{
	char str[1000];
	
	if(argC!=5)
		printf("Usage : %s < Followed by level, id, source string and description>",argV[0]);
	else{
		sprintf(str,"EventCreate /t %s /id %s /l APPLICATION /so %s /d \"%s\"",argV[1],argV[2],argV[3],argV[4]);
		system(str);
	}
	
	return 0;
}
Task: XXXX redacted

C: #include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

typedef enum {
    whole_word = 1,
    overkill = 2,
    case_insensitive = 4
} redact_options;

bool is_word_char(char ch) {
    return ch == '-' || isalpha((unsigned char)ch);
}


void redact(char* text, const char* target, redact_options options) {
    size_t target_length = strlen(target);
    if (target_length == 0)
        return;
    char* start = text;
    char* end = text + strlen(text);
    while (start < end) {
        
        
        char* str = (options & case_insensitive) ? strcasestr(start, target)
                        : strstr(start, target);
        if (str == NULL)
            break;
        char* word_start = str;
        char* word_end = str + target_length;
        if (options & (overkill | whole_word)) {
            while (word_start > start && is_word_char(*(word_start - 1)))
                --word_start;
            while (word_end < end && is_word_char(*word_end))
                ++word_end;
        }
        if (!(options & whole_word) ||
            (word_start == str && word_end == str + target_length))
            memset(word_start, 'X', word_end - word_start);
        start = word_end;
    }
}

void do_basic_test(const char* target, redact_options options) {
    char text[] = "Tom? Toms bottom tomato is in his stomach while playing the "
        "\"Tom-tom\" brand tom-toms. That's so tom.";
    redact(text, target, options);
    printf("[%c|%c|%c]: %s\n", (options & whole_word) ? 'w' : 'p',
           (options & case_insensitive) ? 'i' : 's',
           (options & overkill) ? 'o' : 'n', text);
}

void do_basic_tests(const char* target) {
    printf("Redact '%s':\n", target);
    do_basic_test(target, whole_word);
    do_basic_test(target, whole_word | case_insensitive);
    do_basic_test(target, 0);
    do_basic_test(target, case_insensitive);
    do_basic_test(target, overkill);
    do_basic_test(target, case_insensitive | overkill);
}

int main() {
    do_basic_tests("Tom");
    printf("\n");
    do_basic_tests("tom");
    return 0;
}
Task: Getting the number of decimal places

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

int findNumOfDec(const char *s) {
    int pos = 0;
    while (s[pos] && s[pos++] != '.') {}
    return strlen(s + pos);
}

void test(const char *s) {
    int num = findNumOfDec(s);
    const char *p  = num != 1 ? "s" : "";
    printf("%s has %d decimal%s\n", s, num, p);
}

int main() {
    test("12");
    test("12.0");
    test("12.345");
    test("12.345555555555");
    test("12.3450");
    test("12.34555555555555555555");
    char str[64];
    sprintf(str, "%f", 1.2345e+54);
    test(str);
    return 0;
}
Task: Vibrating rectangles

C: 

#include<graphics.h>

void vibratingRectangles(int winWidth,int winHeight,int leastLength,int leastWidth,int num, int msec)
{
	int color = 1,i,x = winWidth/2, y = winHeight/2;
	
	while(!kbhit()){
		setcolor(color++);
		for(i=num;i>0;i--){
			rectangle(x - i*leastLength,y - i*leastWidth,x + i*leastLength,y + i*leastWidth);
			delay(msec);
		}

		if(color>MAXCOLORS){
			color = 1;
		}
	}
}

int main()
{
	initwindow(1000,1000,"Vibrating Rectangles...");
	
	vibratingRectangles(1000,1000,30,15,20,500);
	
	closegraph();
	
	return 0;
}
Task: Metronome





Java: class Metronome{
	double bpm;
	int measure, counter;
	public Metronome(double bpm, int measure){
		this.bpm = bpm;
		this.measure = measure;	
	}
	public void start(){
		while(true){
			try {
				Thread.sleep((long)(1000*(60.0/bpm)));
			}catch(InterruptedException e) {
				e.printStackTrace();
			}
			counter++;
			if (counter%measure==0){
				 System.out.println("TICK");
			}else{
				 System.out.println("TOCK");
			}
		}
	}
}
public class test {
	public static void main(String[] args) {
		Metronome metronome1 = new Metronome(120,4);
		metronome1.start();
	}
}
Task: Sum of elements below main diagonal of matrix





Java: public static void main(String[] args) {
    int[][] matrix = {{1, 3, 7, 8, 10},
                      {2, 4, 16, 14, 4},
                      {3, 1, 9, 18, 11},
                      {12, 14, 17, 18, 20},
                      {7, 1, 3, 9, 5}};
    int sum = 0;
    for (int row = 1; row < matrix.length; row++) {
        for (int col = 0; col < row; col++) {
            sum += matrix[row][col];
        }
    }
    System.out.println(sum);
}
Task: Sequence_ smallest number greater than previous term with exactly n divisors





Java: public class AntiPrimesPlus {

    static int count_divisors(int n) {
        int count = 0;
        for (int i = 1; i * i <= n; ++i) {
            if (n % i == 0) {
                if (i == n / i)
                    count++;
                else
                    count += 2;
            }
        }
        return count;
    }

    public static void main(String[] args) {
        final int max = 15;
        System.out.printf("The first %d terms of the sequence are:\n", max);
        for (int i = 1, next = 1; next <= max; ++i) {
            if (next == count_divisors(i)) {           
                System.out.printf("%d ", i);
                next++;
            }
        }
        System.out.println();
    }
}
Task: Idiomatically determine all the lowercase and uppercase letters





Java: import java.util.stream.IntStream;

public class Letters {
    public static void main(String[] args) throws Exception {
        System.out.print("Upper case: ");
        IntStream.rangeClosed(0, 0x10FFFF)
                 .filter(Character::isUpperCase)
                 .limit(72)
                 .forEach(n -> System.out.printf("%c", n));
        System.out.println("...");

        System.out.print("Lower case: ");
        IntStream.rangeClosed(0, 0x10FFFF)
                 .filter(Character::isLowerCase)
                 .limit(72)
                 .forEach(n -> System.out.printf("%c", n));
        System.out.println("...");
    }
}
Task: Numbers with equal rises and falls





Java: public class EqualRisesFalls {
    public static void main(String[] args) {
        final int limit1 = 200;
        final int limit2 = 10000000;
        System.out.printf("The first %d numbers in the sequence are:\n", limit1);
        int n = 0;
        for (int count = 0; count < limit2; ) {
            if (equalRisesAndFalls(++n)) {
                ++count;
                if (count <= limit1)
                    System.out.printf("%3d%c", n, count % 20 == 0 ? '\n' : ' ');
            }
        }
        System.out.printf("\nThe %dth number in the sequence is %d.\n", limit2, n);
    }

    private static boolean equalRisesAndFalls(int n) {
        int total = 0;
        for (int previousDigit = -1; n > 0; n /= 10) {
            int digit = n % 10;
            if (previousDigit > digit)
                ++total;
            else if (previousDigit >= 0 && previousDigit < digit)
                --total;
            previousDigit = digit;
        }
        return total == 0;
    }
}
Task: Self-describing numbers





Java: public class SelfDescribingNumbers{
    public static boolean isSelfDescribing(int a){
        String s = Integer.toString(a);
        for(int i = 0; i < s.length(); i++){
            String s0 = s.charAt(i) + "";
            int b = Integer.parseInt(s0); 
            int count = 0;
            for(int j = 0; j < s.length(); j++){
                int temp = Integer.parseInt(s.charAt(j) + "");
                if(temp == i){
                    count++;
                }
                if (count > b) return false;
            }
            if(count != b) return false;
        }
        return true;
    }

    public static void main(String[] args){
        for(int i = 0; i < 100000000; i++){
            if(isSelfDescribing(i)){
                System.out.println(i);
             }
        }
    }
}
Task: Changeable words





Java: import java.io.*;
import java.util.*;

public class ChangeableWords {
    public static void main(String[] args) {
        try {
            final String fileName = "unixdict.txt";
            List<String> dictionary = new ArrayList<>();
            try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.length() > 11)
                        dictionary.add(line);
                }
            }
            System.out.printf("Changeable words in %s:\n", fileName);
            int n = 1;
            for (String word1 : dictionary) {
                for (String word2 : dictionary) {
                    if (word1 != word2 && hammingDistance(word1, word2) == 1)
                        System.out.printf("%2d: %-14s -> %s\n", n++, word1, word2);
                }
            }
        } catch (Exception e)  {
            e.printStackTtexture();
        }
    }

    private static int hammingDistance(String str1, String str2) {
        int len1 = str1.length();
        int len2 = str2.length();
        if (len1 != len2)
            return 0;
        int count = 0;
        for (int i = 0; i < len1; ++i) {
            if (str1.charAt(i) != str2.charAt(i))
                ++count;
            
            if (count == 2)
                break;
        }
        return count;
    }
}
Task: Decision tables





Java: import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Objects;

public class DecisionTables {
    private static class Pair<T, U> {
        private final T t;
        private final U u;

        public static <T, U> Pair<T, U> of(T t, U u) {
            return new Pair<>(t, u);
        }

        public Pair(T t, U u) {
            this.t = t;
            this.u = u;
        }

        public T getFirst() {
            return t;
        }

        public U getSecond() {
            return u;
        }
    }

    private static final List<Pair<String, String>> conditions = List.of(
        Pair.of("Printer prints", "NNNNYYYY"),
        Pair.of("A red light is flashing", "YYNNYYNN"),
        Pair.of("Printer is recognized by computer", "NYNYNYNY")
    );

    private static final List<Pair<String, String>> actions = List.of(
        Pair.of("Check the power cable", "NNYNNNNN"),
        Pair.of("Check the printer-computer cable", "YNYNNNNN"),
        Pair.of("Ensure printer software is installed", "YNYNYNYN"),
        Pair.of("Check/replace ink", "YYNNNYNN"),
        Pair.of("Check for paper jam", "NYNYNNNN")
    );

    public static void main(String[] args) throws IOException {
        final int nc = conditions.size();
        final int na = actions.size();
        final int nr = conditions.get(0).getSecond().length();
        final int np = 7;

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Please answer the following questions with a y or n:");
        final boolean[] answers = new boolean[nc];
        for (int c = 0; c < nc; ++c) {
            String input;
            do {
                System.out.printf("  %s ? ", conditions.get(c).getFirst());
                input = br.readLine().toUpperCase();
            } while (!Objects.equals(input, "Y") && !Objects.equals(input, "N"));
            answers[c] = Objects.equals(input, "Y");
        }
        System.out.println("\nRecommended action(s)");

        outer:
        for (int r = 0; r < nr; ++r) {
            for (int c = 0; c < nc; ++c) {
                char yn = answers[c] ? 'Y' : 'N';
                if (conditions.get(c).getSecond().charAt(r) != yn) {
                    continue outer;
                }
            }
            if (r == np) {
                System.out.println("  None (no problem detected)");
            } else {
                for (Pair<String, String> action : actions) {
                    if (action.getSecond().charAt(r) == 'Y') {
                        System.out.printf("  %s\n", action.getFirst());
                    }
                }
            }
            break;
        }
    }
}
Task: Mosaic matrix





Java: 

size(1000,1000);

textSize(50);

for(int i=0;i<10;i++){
  for(int j=0;j<10;j++){
    noFill();
    square(i*100,j*100,100);
    fill(#000000);
    if((i+j)%2==0){
      text("1",i*100+50,j*100+50);
    }
    else{
      text("0",i*100+50,j*100+50);
    } 
  }
}
Task: Input_Output for lines of text





Java: import java.util.Scanner;

public class Main {
	public static void doStuff(String word){
	   System.out.println(word);
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = Integer.parseInt(in.nextLine());  
		for(int i=0; i<n; i++){		
			String word = in.nextLine();
			doStuff(word);
		}
	}
}
Task: Length of an arc between two angles





Java: public static double arcLength(double r, double a1, double a2){
    return (360.0 - Math.abs(a2-a1))*Math.PI/180.0 * r;
}
Task: Shift list elements to left by 3





Java: import java.util.List;
import java.util.Arrays;
import java.util.Collections;

public class RotateLeft {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        System.out.println("original: " + list);
        Collections.rotate(list, -3);
        System.out.println("rotated: " + list);
    }
}
Task: Air mass





Java: public class AirMass {
    public static void main(String[] args) {
        System.out.println("Angle     0 m              13700 m");
        System.out.println("------------------------------------");
        for (double z = 0; z <= 90; z+= 5) {
            System.out.printf("%2.0f      %11.8f      %11.8f\n",
                            z, airmass(0.0, z), airmass(13700.0, z));
        }
    }

    private static double rho(double a) {
        
        return Math.exp(-a / 8500.0);
    }

    private static double height(double a, double z, double d) {
        
        
        
        double aa = RE + a;
        double hh = Math.sqrt(aa * aa + d * d - 2.0 * d * aa * Math.cos(Math.toRadians(180 - z)));
        return hh - RE;
    }

    private static double columnDensity(double a, double z) {
        
        double sum = 0.0, d = 0.0;
        while (d < FIN) {
            
            double delta = Math.max(DD * d, DD);
            sum += rho(height(a, z, d + 0.5 * delta)) * delta;
            d += delta;
        }
        return sum;
    }
     
    private static double airmass(double a, double z) {
        return columnDensity(a, z) / columnDensity(a, 0.0);
    }

    private static final double RE = 6371000.0; 
    private static final double DD = 0.001; 
    private static final double FIN = 10000000.0; 
}
Task: Matrix with two diagonals





Java: package example.diagdiag;

public class Program {

    public static void main(String[] args) {
        DiagonalDiagonalMatrix A = new DiagonalDiagonalMatrix(7);
        System.out.println(A);
    }

}

class DiagonalDiagonalMatrix {

    final int n;
    private double[][] a = null;

    public Matrix(int n) {
        this.n = n;
    }

    public double get(int i, int j) {
        if (a == null) {
            return (i == j || i == n - j + 1) ? 1.0 : 0.0;
        } else {
            return a[i - 1][j - 1];
        }
    }















    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                sb.append('\t');
                sb.append(get(i, j));
            }
            sb.append('\n');
        }
        return sb.toString();
    }

}
Task: Four sides of square





Java: 

size(1000,1000);

textSize(50);

for(int i=0;i<10;i++){
  for(int j=0;j<10;j++){
    noFill();
    square(i*100,j*100,100);
    fill(#000000);
    if(i==0||i==9||j==0||j==9){
      text("1",i*100+50,j*100+50);
    }
    else{
      text("0",i*100+50,j*100+50);
    } 
  }
}
Task: Longest common suffix





Java: import java.util.List;

public class App {
    private static String lcs(List<String> a) {
        var le = a.size();
        if (le == 0) {
            return "";
        }
        if (le == 1) {
            return a.get(0);
        }
        var le0 = a.get(0).length();
        var minLen = le0;
        for (int i = 1; i < le; i++) {
            if (a.get(i).length() < minLen) {
                minLen = a.get(i).length();
            }
        }
        if (minLen == 0) {
            return "";
        }
        var res = "";
        var a1 = a.subList(1, a.size());
        for (int i = 1; i < minLen; i++) {
            var suffix = a.get(0).substring(le0 - i);
            for (String e : a1) {
                if (!e.endsWith(suffix)) {
                    return res;
                }
            }
            res = suffix;
        }
        return "";
    }

    public static void main(String[] args) {
        var tests = List.of(
            List.of("baabababc", "baabc", "bbbabc"),
            List.of("baabababc", "baabc", "bbbazc"),
            List.of("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"),
            List.of("longest", "common", "suffix"),
            List.of("suffix"),
            List.of("")
        );
        for (List<String> test : tests) {
            System.out.printf("%s -> `%s`\n", test, lcs(test));
        }
    }
}
Task: Numeric separator syntax





Java: public class NumericSeparatorSyntax {

    public static void main(String[] args) {
        runTask("Underscore allowed as seperator", 1_000);
        runTask("Multiple consecutive underscores allowed:", 1__0_0_0);
        runTask("Many multiple consecutive underscores allowed:", 1________________________00);
        runTask("Underscores allowed in multiple positions", 1__4__4);
        runTask("Underscores allowed in negative number", -1__4__4);
        runTask("Underscores allowed in floating point number", 1__4__4e-5);
        runTask("Underscores allowed in floating point exponent", 1__4__440000e-1_2);
        
        
        
        
    }
    
    private static void runTask(String description, long n) {
        runTask(description, n, "%d");
    }

    private static void runTask(String description, double n) {
        runTask(description, n, "%3.7f");
    }

    private static void runTask(String description, Number n, String format) {
        System.out.printf("%s:  " + format + "%n", description, n);
    }

}
Task: Hello world_Newbie





Java: public class HelloWorld {
    public static void main(String[] args) {
        
        System.out.println("Hello world!");
    }
}
Task: Safe mode





Java: frink.parser.Frink interp = new frink.parser.Frink();
interp.setRestrictiveSecurity(true);
Task: Enforced immutability




Go: package main

func main() {
    s := "immutable"
    s[0] = 'a'
}
Task: User input_Graphical




Go: package main

import (
    "github.com/gotk3/gotk3/gtk"
    "log"
    "math/rand"
    "strconv"
    "time"
)

func validateInput(window *gtk.Window, str1, str2 string) bool {
    n, err := strconv.ParseFloat(str2, 64)
    if len(str1) == 0 || err != nil || n != 75000 {
        dialog := gtk.MessageDialogNew(
            window,
            gtk.DIALOG_MODAL,
            gtk.MESSAGE_ERROR,
            gtk.BUTTONS_OK,
            "Invalid input",
        )
        dialog.Run()
        dialog.Destroy()
        return false
    }
    return true
}

func check(err error, msg string) {
    if err != nil {
        log.Fatal(msg, err)
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    gtk.Init(nil)

    window, err := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
    check(err, "Unable to create window:")
    window.SetTitle("Rosetta Code")
    window.SetPosition(gtk.WIN_POS_CENTER)
    window.Connect("destroy", func() {
        gtk.MainQuit()
    })

    vbox, err := gtk.BoxNew(gtk.ORIENTATION_VERTICAL, 1)
    check(err, "Unable to create vertical box:")
    vbox.SetBorderWidth(1)

    hbox1, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
    check(err, "Unable to create first horizontal box:")

    hbox2, err := gtk.BoxNew(gtk.ORIENTATION_HORIZONTAL, 1)
    check(err, "Unable to create second horizontal box:")

    label, err := gtk.LabelNew("Enter a string and the number 75000   \n")
    check(err, "Unable to create label:")

    sel, err := gtk.LabelNew("String:      ")
    check(err, "Unable to create string entry label:")

    nel, err := gtk.LabelNew("Number: ")
    check(err, "Unable to create number entry label:")

    se, err := gtk.EntryNew()
    check(err, "Unable to create string entry:")

    ne, err := gtk.EntryNew()
    check(err, "Unable to create number entry:")

    hbox1.PackStart(sel, false, false, 2)
    hbox1.PackStart(se, false, false, 2)

    hbox2.PackStart(nel, false, false, 2)
    hbox2.PackStart(ne, false, false, 2)

    
    ab, err := gtk.ButtonNewWithLabel("Accept")
    check(err, "Unable to create accept button:")
    ab.Connect("clicked", func() {
        
        str1, _ := se.GetText()
        str2, _ := ne.GetText()
        if validateInput(window, str1, str2) {
            window.Destroy() 
        }
    })

    vbox.Add(label)
    vbox.Add(hbox1)
    vbox.Add(hbox2)
    vbox.Add(ab)
    window.Add(vbox)

    window.ShowAll()
    gtk.Main()
}
Task: Pascal's triangle_Puzzle




Go: package main

import "fmt"


type expr struct {
    x, y, z float64 
    c       float64 
}


func addExpr(a, b expr) expr {
    return expr{a.x + b.x, a.y + b.y, a.z + b.z, a.c + b.c}
}   
    

func subExpr(a, b expr) expr {
    return expr{a.x - b.x, a.y - b.y, a.z - b.z, a.c - b.c}
}   


func mulExpr(a expr, c float64) expr {
    return expr{a.x * c, a.y * c, a.z * c, a.c * c}
}



func addRow(l []expr) []expr {
    if len(l) == 0 {
        panic("wrong")
    }
    r := make([]expr, len(l)-1)
    for i := range r {
        r[i] = addExpr(l[i], l[i+1])
    }
    return r
}   



func substX(a, b expr) expr {
    if b.x == 0 {
        panic("wrong")
    }
    return subExpr(a, mulExpr(b, a.x/b.x))
}

func substY(a, b expr) expr {
    if b.y == 0 {
        panic("wrong")
    }
    return subExpr(a, mulExpr(b, a.y/b.y))
}

func substZ(a, b expr) expr {
    if b.z == 0 {
        panic("wrong")
    }
    return subExpr(a, mulExpr(b, a.z/b.z))
}


func solveX(a expr) float64 {
    if a.x == 0 || a.y != 0 || a.z != 0 {
        panic("wrong")
    }
    return -a.c / a.x
}

func solveY(a expr) float64 {
    if a.x != 0 || a.y == 0 || a.z != 0 {
        panic("wrong")
    }
    return -a.c / a.y
}

func solveZ(a expr) float64 {
    if a.x != 0 || a.y != 0 || a.z == 0 {
        panic("wrong")
    }
    return -a.c / a.z
}

func main() {
    
    r5 := []expr{{x: 1}, {c: 11}, {y: 1}, {c: 4}, {z: 1}}
    fmt.Println("bottom row:", r5)

    
    r4 := addRow(r5)
    fmt.Println("next row up:", r4)
    r3 := addRow(r4)
    fmt.Println("middle row:", r3)

    
    xyz := subExpr(expr{y: 1}, expr{x: 1, z: 1})
    fmt.Println("xyz relation:", xyz)
    
    r3[2] = substZ(r3[2], xyz)
    fmt.Println("middle row after substituting for z:", r3)

    
    b := expr{c: 40}
    
    xy := subExpr(r3[0], b)
    fmt.Println("xy relation:", xy)
    
    r3[0] = b

    
    r3[2] = substX(r3[2], xy)
    fmt.Println("middle row after substituting for x:", r3)
    
    
    r2 := addRow(r3)
    fmt.Println("next row up:", r2)
    r1 := addRow(r2)
    fmt.Println("top row:", r1)

    
    y := subExpr(r1[0], expr{c: 151})
    fmt.Println("y relation:", y)
    
    x := substY(xy, y)
    fmt.Println("x relation:", x)
    
    z := substX(substY(xyz, y), x)
    fmt.Println("z relation:", z)

    
    fmt.Println("x =", solveX(x))
    fmt.Println("y =", solveY(y))
    fmt.Println("z =", solveZ(z)) 
}