WeixiangYan/CodeTransOcean huggingface dataset:
Task: Print debugging statement

C: #include <stdio.h>

#define DEBUG_INT(x) printf( #x " at line %d\nresult: %d\n\n", __LINE__, x)

int add(int x, int y) {
  int result = x + y;
  DEBUG_INT(x);
  DEBUG_INT(y);
  DEBUG_INT(result);
  DEBUG_INT(result+1);
  return result;
}

int main() {
  add(2, 7);
  return 0;
}





Java: import java.util.Objects;

public class PrintDebugStatement {
    
    private static void printDebug(String message) {
        Objects.requireNonNull(message);

        RuntimeException exception = new RuntimeException();
        StackTraceElement[] stackTrace = exception.getStackTrace();
        
        
        StackTraceElement stackTraceElement = stackTrace[1];
        String fileName = stackTraceElement.getFileName();
        String className = stackTraceElement.getClassName();
        String methodName = stackTraceElement.getMethodName();
        int lineNumber = stackTraceElement.getLineNumber();

        System.out.printf("[DEBUG][%s %s.%s#%d] %s\n", fileName, className, methodName, lineNumber, message);
    }

    private static void blah() {
        printDebug("Made It!");
    }

    public static void main(String[] args) {
        printDebug("Hello world.");
        blah();

        Runnable oops = () -> printDebug("oops");
        oops.run();
    }
}
Task: Range extraction

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

size_t rprint(char *s, int *x, int len)
{
#define sep (a > s ? "," : "") 
#define ol (s ? 100 : 0)       
	int i, j;
	char *a = s;
	for (i = j = 0; i < len; i = ++j) {
		for (; j < len - 1 && x[j + 1] == x[j] + 1; j++);

		if (i + 1 < j)
			a += snprintf(s?a:s, ol, "%s%d-%d", sep, x[i], x[j]);
		else
			while (i <= j)
				a += snprintf(s?a:s, ol, "%s%d", sep, x[i++]);
	}
	return a - s;
#undef sep
#undef ol
}

int main()
{
	int x[] = {	0,  1,  2,  4,  6,  7,  8, 11, 12, 14,
			15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
			25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
			37, 38, 39 };

	char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1);
	rprint(s, x, sizeof(x) / sizeof(int));
	printf("%s\n", s);

	return 0;
}





Java: public class RangeExtraction {

    public static void main(String[] args) {
        int[] arr = {0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
            37, 38, 39};

        int len = arr.length;
        int idx = 0, idx2 = 0;
        while (idx < len) {
            while (++idx2 < len && arr[idx2] - arr[idx2 - 1] == 1);
            if (idx2 - idx > 2) {
                System.out.printf("%s-%s,", arr[idx], arr[idx2 - 1]);
                idx = idx2;
            } else {
                for (; idx < idx2; idx++)
                    System.out.printf("%s,", arr[idx]);
            }
        }
    }
}
Task: Type detection

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

void typeDetector(char* str){	
	if(isalnum(str[0])!=0)
		printf("\n%c is alphanumeric",str[0]);
	if(isalpha(str[0])!=0)
		printf("\n%c is alphabetic",str[0]);
	if(iscntrl(str[0])!=0)
		printf("\n%c is a control character",str[0]);
	if(isdigit(str[0])!=0)
		printf("\n%c is a digit",str[0]);
	if(isprint(str[0])!=0)
		printf("\n%c is printable",str[0]);
	if(ispunct(str[0])!=0)
		printf("\n%c is a punctuation character",str[0]);
	if(isxdigit(str[0])!=0)
		printf("\n%c is a hexadecimal digit",str[0]);
}

int main(int argC, char* argV[])
{
	int i;
	
	if(argC==1)
		printf("Usage : %s <followed by ASCII characters>");
	else{
		for(i=1;i<argC;i++)
			typeDetector(argV[i]);
	}
	return 0;
}





Java: public class TypeDetection {
    private static void showType(Object a) {
        if (a instanceof Integer) {
            System.out.printf("'%s' is an integer\n", a);
        } else if (a instanceof Double) {
            System.out.printf("'%s' is a double\n", a);
        } else if (a instanceof Character) {
            System.out.printf("'%s' is a character\n", a);
        } else {
            System.out.printf("'%s' is some other type\n", a);
        }
    }

    public static void main(String[] args) {
        showType(5);
        showType(7.5);
        showType('d');
        showType(true);
    }
}
Task: Maximum triangle path sum

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

#define max(x,y)  ((x) > (y) ? (x) : (y))

int tri[] = {
        55,
	94, 48,
	95, 30, 96,
	77, 71, 26, 67,
	97, 13, 76, 38, 45,
	7, 36, 79, 16, 37, 68,
	48, 7, 9, 18, 70, 26, 6,
	18, 72, 79, 46, 59, 79, 29, 90,
	20, 76, 87, 11, 32, 7, 7, 49, 18,
	27, 83, 58, 35, 71, 11, 25, 57, 29, 85,
	14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,
	2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,
	92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,
	56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,
	44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,
	85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,
	6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,
	27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93
};

int main(void)
{
    const int len  = sizeof(tri) / sizeof(tri[0]);
    const int base = (sqrt(8*len + 1) - 1) / 2;
    int step       = base - 1;
    int stepc      = 0;

    int i;
    for (i = len - base - 1; i >= 0; --i) {
        tri[i] += max(tri[i + step], tri[i + step + 1]);
        if (++stepc == step) {
            step--;
            stepc = 0;
        }
    }

    printf("%d\n", tri[0]);
    return 0;
}





Java: import java.nio.file.*;
import static java.util.Arrays.stream;

public class MaxPathSum {

    public static void main(String[] args) throws Exception {
        int[][] data = Files.lines(Paths.get("triangle.txt"))
                .map(s -> stream(s.trim().split("\\s+"))
                        .mapToInt(Integer::parseInt)
                        .toArray())
                .toArray(int[][]::new);

        for (int r = data.length - 1; r > 0; r--)
            for (int c = 0; c < data[r].length - 1; c++)
                data[r - 1][c] += Math.max(data[r][c], data[r][c + 1]);

        System.out.println(data[0][0]);
    }
}
Task: Variable declaration reset

C: #include <stdio.h>

int main() {
    int i, gprev = 0;
    int s[7] = {1, 2, 2, 3, 4, 4, 5};

    
    for (i = 0; i < 7; ++i) {

        int curr = s[i];
        int prev = 0;

        if (i > 0 && curr == prev) printf("%d\n", i);
        prev = curr;
    }

    
    for (i = 0; i < 7; ++i) {
        int curr = s[i];
        if (i > 0 && curr == gprev) printf("%d\n", i);
        gprev = curr;
    }

    return 0;
}





Java: public class VariableDeclarationReset {
    public static void main(String[] args) {
        int[] s = {1, 2, 2, 3, 4, 4, 5};

        
        
        for (int i = 0; i < s.length; ++i) {
            int curr = s[i];
            int prev = 0;

            if (i > 0 && curr == prev) System.out.println(i);
            prev = curr;
        }

        int gprev = 0;

        
        
        for (int i = 0; i < s.length; ++i) {
            int curr = s[i];
            if (i > 0 && curr == gprev) System.out.println(i);
            gprev = curr;
        }
    }
}
Task: Find first and last set bit of a long integer

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

uint32_t msb32(uint32_t n)
{
	uint32_t b = 1;
	if (!n) return 0;

#define step(x) if (n >= ((uint32_t)1) << x) b <<= x, n >>= x
	step(16); step(8); step(4); step(2); step(1);
#undef step
	return b;
}

int msb32_idx(uint32_t n)
{
	int b = 0;
	if (!n) return -1;

#define step(x) if (n >= ((uint32_t)1) << x) b += x, n >>= x
	step(16); step(8); step(4); step(2); step(1);
#undef step
	return b;
}

#define lsb32(n) ( (uint32_t)(n) & -(int32_t)(n) )


inline int lsb32_idx(uint32_t n) { return msb32_idx(lsb32(n)); }

int main()
{
	int32_t n;
	int i;

	for (i = 0, n = 1; ; i++, n *= 42) {
		printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n",
			i, n, n,
			msb32(n), msb32_idx(n),
			lsb32(n), lsb32_idx(n));

		if (n >= INT32_MAX / 42) break;
	}

	return 0;
}





Java: public class FirstLastBits {

    
    public static int mssb(int x) {
        return Integer.highestOneBit(x);
    }

    public static long mssb(long x) {
        return Long.highestOneBit(x);
    }

    public static int mssb_idx(int x) {
        return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(x);
    }

    public static int mssb_idx(long x) {
        return Long.SIZE - 1 - Long.numberOfLeadingZeros(x);
    }

    public static int mssb_idx(BigInteger x) {
	return x.bitLength() - 1;
    }

    
    public static int lssb(int x) {
        return Integer.lowestOneBit(x);
    }

    public static long lssb(long x) {
        return Long.lowestOneBit(x);
    }

    public static int lssb_idx(int x) {
        return Integer.numberOfTrailingZeros(x);
    }

    public static int lssb_idx(long x) {
        return Long.numberOfTrailingZeros(x);
    }

    public static int lssb_idx(BigInteger x) {
	return x.getLowestSetBit();
    }

    public static void main(String[] args) {
        System.out.println("int:");
        int n1 = 1;
        for (int i = 0; ; i++, n1 *= 42) {
            System.out.printf("42**%d = %10d(x%08x): M x%08x(%2d) L x%03x(%2d)\n",
                              i, n1, n1,
                              mssb(n1), mssb_idx(n1),
                              lssb(n1), lssb_idx(n1));
            if (n1 >= Integer.MAX_VALUE / 42)
                break;
        }
        System.out.println();
        System.out.println("long:");
        long n2 = 1;
        for (int i = 0; ; i++, n2 *= 42) {
            System.out.printf("42**%02d = %20d(x%016x): M x%016x(%2d) L x%06x(%2d)\n",
                              i, n2, n2,
                              mssb(n2), mssb_idx(n2),
                              lssb(n2), lssb_idx(n2));
            if (n2 >= Long.MAX_VALUE / 42)
                break;
        }
	System.out.println();
	System.out.println("BigInteger:");
	BigInteger n3 = BigInteger.ONE;
	BigInteger k = BigInteger.valueOf(1302);
	for (int i = 0; i < 10; i++, n3 = n3.multiply(k)) {
	    System.out.printf("1302**%02d = %30d(x%28x): M %2d L %2d\n",
			      i, n3, n3,
			      mssb_idx(n3),
			      lssb_idx(n3));
	}
    }
}
Task: Numbers with equal rises and falls

C: #include <stdio.h>


int riseEqFall(int num) {
    int rdigit = num % 10;
    int netHeight = 0;
    while (num /= 10) {
        netHeight += ((num % 10) > rdigit) - ((num % 10) < rdigit);
        rdigit = num % 10;
    }
    return netHeight == 0;
}


int nextNum() {
    static int num = 0;
    do {num++;} while (!riseEqFall(num));
    return num;
}

int main(void) {
    int total, num;
    
    
    printf("The first 200 numbers are: \n");
    for (total = 0; total < 200; total++)
        printf("%d ", nextNum());
    
    
    printf("\n\nThe 10,000,000th number is: ");
    for (; total < 10000000; total++) num = nextNum();
    printf("%d\n", num);
    
    return 0;
}





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: Koch curve

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

#define pi M_PI

typedef struct{
	double x,y;
}point;

void kochCurve(point p1,point p2,int times){
	point p3,p4,p5;
	double theta = pi/3;
	
	if(times>0){
		p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3};
		p5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3};
		
		p4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)};
		
		kochCurve(p1,p3,times-1);
		kochCurve(p3,p4,times-1);
		kochCurve(p4,p5,times-1);
		kochCurve(p5,p2,times-1);
	}
	
	else{
		line(p1.x,p1.y,p2.x,p2.y);
	}
}

int main(int argC, char** argV)
{
	int w,h,r;
	point p1,p2;
	
	if(argC!=4){
		printf("Usage : %s <window width> <window height> <recursion level>",argV[0]);
	}
	
	else{
		w = atoi(argV[1]);
		h = atoi(argV[2]);
		r = atoi(argV[3]);
		
		initwindow(w,h,"Koch Curve");
		
		p1 = (point){10,h-10};
		p2 = (point){w-10,h-10};
		
		kochCurve(p1,p2,r);
		
		getch();
	
		closegraph();
	}
	
	return 0;
}





Java: int l = 300;

void setup() {
  size(400, 400);
  background(0, 0, 255);
  stroke(255);
  
  translate(width/2.0, height/2.0);
  
  translate(-l/2.0, l*sqrt(3)/6.0);
  for (int i = 1; i <= 3; i++) {
    kcurve(0, l);
    rotate(radians(120));
    translate(-l, 0);
  }
}

void kcurve(float x1, float x2) {
  float s = (x2-x1)/3;
  if (s < 5) {
    pushMatrix();
    translate(x1, 0);
    line(0, 0, s, 0);
    line(2*s, 0, 3*s, 0);
    translate(s, 0);
    rotate(radians(60));
    line(0, 0, s, 0);
    translate(s, 0);
    rotate(radians(-120));
    line(0, 0, s, 0);
    popMatrix();
    return;
  }
  pushMatrix();
  translate(x1, 0);
  kcurve(0, s);
  kcurve(2*s, 3*s);
  translate(s, 0);
  rotate(radians(60));
  kcurve(0, s);
  translate(s, 0);
  rotate(radians(-120));
  kcurve(0, s);
  popMatrix();
}
Task: Draw pixel 2

C: #include<graphics.h>
#include<stdlib.h>
#include<time.h>

int main()
{
	srand(time(NULL));
	
	initwindow(640,480,"Yellow Random Pixel");
	
	putpixel(rand()%640,rand()%480,YELLOW);
	
	getch();
	
	return 0;
}





Java: 

size(640,480);

stroke(#ffff00);

ellipse(random(640),random(480),1,1);
Task: Draw a pixel

C: #include<graphics.h>

int main()
{
	initwindow(320,240,"Red Pixel");
	
	putpixel(100,100,RED);
	
	getch();
	
	return 0;
}





Java: import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;

public class DrawAPixel extends JFrame{
	public DrawAPixel() {
		super("Red Pixel");
		setSize(320, 240);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}
	@Override
	public void paint(Graphics g) {
		g.setColor(new Color(255, 0, 0));
		g.drawRect(100, 100, 1, 1);
	}
	public static void main(String[] args) {
		new DrawAPixel();
	}
}
Task: Words from neighbour ones

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

#define MAX_WORD_SIZE 80
#define MIN_LENGTH 9
#define WORD_SIZE (MIN_LENGTH + 1)

void fatal(const char* message) {
    fprintf(stderr, "%s\n", message);
    exit(1);
}

void* xmalloc(size_t n) {
    void* ptr = malloc(n);
    if (ptr == NULL)
        fatal("Out of memory");
    return ptr;
}

void* xrealloc(void* p, size_t n) {
    void* ptr = realloc(p, n);
    if (ptr == NULL)
        fatal("Out of memory");
    return ptr;
}

int word_compare(const void* p1, const void* p2) {
    return memcmp(p1, p2, WORD_SIZE);
}

int main(int argc, char** argv) {
    const char* filename = argc < 2 ? "unixdict.txt" : argv[1];
    FILE* in = fopen(filename, "r");
    if (!in) {
        perror(filename);
        return EXIT_FAILURE;
    }
    char line[MAX_WORD_SIZE];
    size_t size = 0, capacity = 1024;
    char* words = xmalloc(WORD_SIZE * capacity);
    while (fgets(line, sizeof(line), in)) {
        size_t len = strlen(line) - 1; 
        if (len < MIN_LENGTH)
            continue;
        line[len] = '\0';
        if (size == capacity) {
            capacity *= 2;
            words = xrealloc(words, WORD_SIZE * capacity);
        }
        memcpy(&words[size * WORD_SIZE], line, WORD_SIZE);
        ++size;
    }
    fclose(in);
    qsort(words, size, WORD_SIZE, word_compare);
    int count = 0;
    char prev_word[WORD_SIZE] = { 0 };
    for (size_t i = 0; i + MIN_LENGTH <= size; ++i) {
        char word[WORD_SIZE] = { 0 };
        for (size_t j = 0; j < MIN_LENGTH; ++j)
            word[j] = words[(i + j) * WORD_SIZE + j];
        if (word_compare(word, prev_word) == 0)
            continue;
        if (bsearch(word, words, size, WORD_SIZE, word_compare))
            printf("%2d. %s\n", ++count, word);
        memcpy(prev_word, word, WORD_SIZE);
    }
    free(words);
    return EXIT_SUCCESS;
}





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

public class NeighbourWords {
    public static void main(String[] args) {
        try {
            int minLength = 9;
            List<String> words = new ArrayList<>();
            try (BufferedReader reader = new BufferedReader(new FileReader("unixdict.txt"))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (line.length() >= minLength)
                        words.add(line);
                }
            }
            Collections.sort(words);
            String previousWord = null;
            int count = 0;
            for (int i = 0, n = words.size(); i + minLength <= n; ++i) {
                StringBuilder sb = new StringBuilder(minLength);
                for (int j = 0; j < minLength; ++j)
                    sb.append(words.get(i + j).charAt(j));
                String word = sb.toString();
                if (word.equals(previousWord))
                    continue;
                if (Collections.binarySearch(words, word) >= 0)
                    System.out.printf("%2d. %s\n", ++count, word);
                previousWord = word;
            }
        } catch (Exception e)  {
            e.printStackTrace();
        }
    }
}
Task: Generate Chess960 starting position

C: #include<stdlib.h>
#include<locale.h>
#include<wchar.h>
#include<stdio.h>
#include<time.h>

char rank[9];

int pos[8];

void swap(int i,int j){
	int temp = pos[i];
	pos[i] = pos[j];
	pos[j] = temp;
}

void generateFirstRank(){
	 int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i;
	 
	 for(i=0;i<8;i++){
		 rank[i] = 'e';
		 pos[i] = i;
	 }
		 
	 do{
		 kPos = rand()%8;
		 rPos1 = rand()%8;
		 rPos2 = rand()%8;
	 }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2));

	 rank[pos[rPos1]] = 'R';
	 rank[pos[kPos]] = 'K';
	 rank[pos[rPos2]] = 'R';
	 
	 swap(rPos1,7);
	 swap(rPos2,6);
	 swap(kPos,5);
	 
	 do{
		 bPos1 = rand()%5;
		 bPos2 = rand()%5;
	 }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2));

	 rank[pos[bPos1]] = 'B';
	 rank[pos[bPos2]] = 'B';
	 
	 swap(bPos1,4);
	 swap(bPos2,3);
	 
	 do{
		 qPos = rand()%3;
		 nPos1 = rand()%3;
	 }while(qPos==nPos1);
	 
	 rank[pos[qPos]] = 'Q';
	 rank[pos[nPos1]] = 'N';
	 
	 for(i=0;i<8;i++)
		 if(rank[i]=='e'){
			 rank[i] = 'N';
			 break;
		 }		
}

void printRank(){
	int i;
	
	#ifdef _WIN32
		printf("%s\n",rank);
	#else
	{
		setlocale(LC_ALL,"");
		printf("\n");
		for(i=0;i<8;i++){
			if(rank[i]=='K')
				printf("%lc",(wint_t)9812);
			else if(rank[i]=='Q')
				printf("%lc",(wint_t)9813);
			else if(rank[i]=='R')
				printf("%lc",(wint_t)9814);
			else if(rank[i]=='B')
				printf("%lc",(wint_t)9815);
			if(rank[i]=='N')
				printf("%lc",(wint_t)9816);
		}
	}
	#endif
}

int main()
{
	int i;
	
	srand((unsigned)time(NULL));
	
	for(i=0;i<9;i++){
		generateFirstRank();
		printRank();
	}
	
	return 0;
}





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

public class Chess960{
	private static List<Character> pieces = Arrays.asList('R','B','N','Q','K','N','B','R');

	public static List<Character> generateFirstRank(){
		do{
			Collections.shuffle(pieces);
		}while(!check(pieces.toString().replaceAll("[^\\p{Upper}]", ""))); 
		
		return pieces;
	}

	private static boolean check(String rank){
		if(!rank.matches(".*R.*K.*R.*")) return false;			
		if(!rank.matches(".*B(..|....|......|)B.*")) return false;	
		return true;
	}

	public static void main(String[] args){
		for(int i = 0; i < 10; i++){
			System.out.println(generateFirstRank());
		}
	}
}
Task: Modulinos

C: int meaning_of_life();





Java: public class ScriptedMain {
	public static int meaningOfLife() {
		return 42;
	}

	public static void main(String[] args) {
		System.out.println("Main: The meaning of life is " + meaningOfLife());
	}
}
Task: Unix_ls

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>

int cmpstr(const void *a, const void *b)
{
    return strcmp(*(const char**)a, *(const char**)b);
}

int main(void)
{
    DIR *basedir;
    char path[PATH_MAX];
    struct dirent *entry;
    char **dirnames;
    int diralloc = 128;
    int dirsize  = 0;
    
    if (!(dirnames = malloc(diralloc * sizeof(char*)))) {
        perror("malloc error:");
        return 1;
    }

    if (!getcwd(path, PATH_MAX)) {
        perror("getcwd error:");
        return 1;
    }

    if (!(basedir = opendir(path))) {
        perror("opendir error:");
        return 1;
    }

    while ((entry = readdir(basedir))) {
        if (dirsize >= diralloc) {
            diralloc *= 2;
            if (!(dirnames = realloc(dirnames, diralloc * sizeof(char*)))) {
                perror("realloc error:");
                return 1;
            }
        }
        dirnames[dirsize++] = strdup(entry->d_name);
    }

    qsort(dirnames, dirsize, sizeof(char*), cmpstr);

    int i;
    for (i = 0; i < dirsize; ++i) {
        if (dirnames[i][0] != '.') {
            printf("%s\n", dirnames[i]);
        }
    }

    for (i = 0; i < dirsize; ++i)
        free(dirnames[i]);
    free(dirnames);
    closedir(basedir);
    return 0;
}





Java: package rosetta;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class UnixLS {

	public static void main(String[] args) throws IOException {
		Files.list(Path.of("")).sorted().forEach(System.out::println);
	}
}
Task: Keyboard macros

C: #include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/keysym.h>

int main()
{
  Display *d;
  XEvent event;
  
  d = XOpenDisplay(NULL);
  if ( d != NULL ) {
                
    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")), 
	     Mod1Mask,  
	     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);
    XGrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")), 
	     Mod1Mask, 
	     DefaultRootWindow(d), True, GrabModeAsync, GrabModeAsync);

    for(;;)
    {
      XNextEvent(d, &event);
      if ( event.type == KeyPress ) {
	KeySym s = XLookupKeysym(&event.xkey, 0);
	if ( s == XK_F7 ) {
	  printf("something's happened\n");
	} else if ( s == XK_F6 ) {
	  break;
	}
      }
    }

    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F7")), Mod1Mask, DefaultRootWindow(d));
    XUngrabKey(d, XKeysymToKeycode(d, XStringToKeysym("F6")), Mod1Mask, DefaultRootWindow(d));
  }
  return EXIT_SUCCESS;
}





Java: package keybord.macro.demo;

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

class KeyboardMacroDemo {
    public static void main( String [] args ) {
        final JFrame frame = new JFrame();
        
        String directions = "<html><b>Ctrl-S</b> to show frame title<br>"
                                 +"<b>Ctrl-H</b> to hide it</html>";
                                 
        frame.add( new JLabel(directions));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.addKeyListener( new KeyAdapter(){
            public void keyReleased( KeyEvent e ) {
                if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_S){
                    frame.setTitle("Hello there");
                }else if( e.isControlDown() && e.getKeyCode() == KeyEvent.VK_H){
                    frame.setTitle("");
                }
            }
        });
        frame.pack();
        frame.setVisible(true);
    }
}