WeixiangYan/CodeTransOcean huggingface dataset:
Task: Retrieve and search chat history

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

#define MAX_LEN 1000

void searchChatLogs(char* searchString){
	char* baseURL = "http:
	time_t t;
	struct tm* currentDate;
	char dateString[30],dateStringFile[30],lineData[MAX_LEN],targetURL[100];
	int i,flag;
	FILE *fp;
	
	CURL *curl;
	CURLcode res;
	
	time(&t);
	currentDate = localtime(&t);
	
	strftime(dateString, 30, "%Y-%m-%d", currentDate);
	printf("Today is : %s",dateString);
	
	if((curl = curl_easy_init())!=NULL){
		for(i=0;i<=10;i++){
			
		flag = 0;
		sprintf(targetURL,"%s%s.tcl",baseURL,dateString);
		
		strcpy(dateStringFile,dateString);
		
		printf("\nRetrieving chat logs from %s\n",targetURL);
		
		if((fp = fopen("nul","w"))==0){
			printf("Cant's read from %s",targetURL);
		}
		else{
			curl_easy_setopt(curl, CURLOPT_URL, targetURL);
		curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
		
		res = curl_easy_perform(curl);
		
		if(res == CURLE_OK){
			while(fgets(lineData,MAX_LEN,fp)!=NULL){
				if(strstr(lineData,searchString)!=NULL){
					flag = 1;
					fputs(lineData,stdout);
				}
			}
			
			if(flag==0)
				printf("\nNo matching lines found.");
		}
		fflush(fp);
		fclose(fp);
		}
		
		currentDate->tm_mday--;
		mktime(currentDate);
		strftime(dateString, 30, "%Y-%m-%d", currentDate);	
			
	}
	curl_easy_cleanup(curl);
	
	}
}

int main(int argC,char* argV[])
{
	if(argC!=2)
		printf("Usage : %s <followed by search string, enclosed by \" if it contains spaces>",argV[0]);
	else
		searchChatLogs(argV[1]);
	return 0;
}







Python: 
import datetime
import re
import urllib.request
import sys

def get(url):
    with urllib.request.urlopen(url) as response:
       html = response.read().decode('utf-8')
    if re.match(r'<!Doctype HTML[\s\S]*<Title>URL Not Found</Title>', html):
        return None
    return html

def main():
    template = 'http://tclers.tk/conferences/tcl/%Y-%m-%d.tcl'
    today = datetime.datetime.utcnow()
    back = 10
    needle = sys.argv[1]
    
    
    
    for i in range(-back, 2):
        day = today + datetime.timedelta(days=i)
        url = day.strftime(template)
        haystack = get(url)
        if haystack:
            mentions = [x for x in haystack.split('\n') if needle in x]
            if mentions:
                print('{}\n------\n{}\n------\n'
                          .format(url, '\n'.join(mentions)))

main()
Task: Terminal control_Unicode output

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

int
main ()
{
  int i;
  char *str = getenv ("LANG");

  for (i = 0; str[i + 2] != 00; i++)
    {
      if ((str[i] == 'u' && str[i + 1] == 't' && str[i + 2] == 'f')
          || (str[i] == 'U' && str[i + 1] == 'T' && str[i + 2] == 'F'))
        {
          printf
            ("Unicode is supported on this terminal and U+25B3 is : \u25b3");
          i = -1;
          break;
        }
    }

  if (i != -1)
    printf ("Unicode is not supported on this terminal.");

  return 0;
}







Python: import sys

if "UTF-8" in sys.stdout.encoding:
    print("△")
else:
    raise Exception("Terminal can't handle UTF-8")
Task: Find adjacent primes which differ by a square integer

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

int isprime( int p ) {
    int i;
    if(p==2) return 1;
    if(!(p%2)) return 0;
    for(i=3; i*i<=p; i+=2) {
       if(!(p%i)) return 0;
    }
    return 1;
}

int nextprime( int p ) {
    int i=0;
    if(p==0) return 2;
    if(p<3) return p+1;
    while(!isprime(++i + p));
    return i+p;
}

int issquare( int p ) {
    int i;
    for(i=0;i*i<p;i++);
    return i*i==p;
}

int main(void) {
    int i=3, j=2;
    for(i=3;j<=1000000;i=j) {
        j=nextprime(i);
        if(j-i>36&&issquare(j-i)) printf( "%d %d %d\n", i, j, j-i );
    }
    return 0;
}







Python: import math
print("working...")
limit = 1000000
Primes = []
oldPrime = 0
newPrime = 0
x = 0

def isPrime(n):
    for i in range(2,int(n**0.5)+1):
        if n%i==0:
            return False
    return True

def issquare(x):
	for n in range(x):
		if (x == n*n):
			return 1
	return 0

for n in range(limit):
    if isPrime(n):
       Primes.append(n)

for n in range(2,len(Primes)):
    pr1 = Primes[n]
    pr2 = Primes[n-1]
    diff = pr1 - pr2
    flag = issquare(diff)
    if (flag == 1 and diff > 36):
       print(str(pr1) + " " + str(pr2) + " diff = " + str(diff))

print("done...")
Task: Truncate a file

C: #include <windows.h>
#include <stdio.h>
#include <wchar.h>


void
oops(const wchar_t *message)
{
	wchar_t *buf;
	DWORD error;

	buf = NULL;
	error = GetLastError();
	FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
	    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
	    NULL, error, 0, (wchar_t *)&buf, 0, NULL);

	if (buf) {
		fwprintf(stderr, L"%ls: %ls", message, buf);
		LocalFree(buf);
	} else {
		
		fwprintf(stderr, L"%ls: unknown error 0x%x\n",
		    message, error);
	}
}

int
dotruncate(wchar_t *fn, LARGE_INTEGER fp)
{
	HANDLE fh;

	fh = CreateFileW(fn, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
	if (fh == INVALID_HANDLE_VALUE) {
		oops(fn);
		return 1;
	}

	if (SetFilePointerEx(fh, fp, NULL, FILE_BEGIN) == 0 ||
	    SetEndOfFile(fh) == 0) {
		oops(fn);
		CloseHandle(fh);
		return 1;
	}

	CloseHandle(fh);
	return 0;
}


int
main()
{
	LARGE_INTEGER fp;
	int argc;
	wchar_t **argv, *fn, junk[2];

	
	argv = CommandLineToArgvW(GetCommandLineW(), &argc);
	if (argv == NULL) {
		oops(L"CommandLineToArgvW");
		return 1;
	}

	if (argc != 3) {
		fwprintf(stderr, L"usage: %ls filename length\n", argv[0]);
		return 1;
	}

	fn = argv[1];

	
	if (swscanf(argv[2], L"%lld%1ls", &fp.QuadPart, &junk) != 1) {
		fwprintf(stderr, L"%ls: not a number\n", argv[2]);
		return 1;
	}

	return dotruncate(fn, fp);
}







Python: def truncate_file(name, length):
    if not os.path.isfile(name):
        return False
    if length >= os.path.getsize(name):
        return False
    with open(name, 'ab') as f:
        f.truncate(length)
    return True
Task: Video display modes

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "wren.h"

void C_xrandr(WrenVM* vm) {
     const char *arg = wrenGetSlotString(vm, 1);
     char command[strlen(arg) + 8];
     strcpy(command, "xrandr ");
     strcat(command, arg);
     system(command);
}

void C_usleep(WrenVM* vm) {
    useconds_t usec = (useconds_t)wrenGetSlotDouble(vm, 1);
    usleep(usec);
}

WrenForeignMethodFn bindForeignMethod(
    WrenVM* vm,
    const char* module,
    const char* className,
    bool isStatic,
    const char* signature) {
    if (strcmp(module, "main") == 0) {
        if (strcmp(className, "C") == 0) {
            if (isStatic && strcmp(signature, "xrandr(_)") == 0) return C_xrandr;
            if (isStatic && strcmp(signature, "usleep(_)") == 0) return C_usleep;
        }
    }
    return NULL;
}

static void writeFn(WrenVM* vm, const char* text) {
    printf("%s", text);
}

char *readFile(const char *fileName) {
    FILE *f = fopen(fileName, "r");
    fseek(f, 0, SEEK_END);
    long fsize = ftell(f);
    rewind(f);
    char *script = malloc(fsize + 1);
    fread(script, 1, fsize, f);
    fclose(f);
    script[fsize] = 0;
    return script;
}

int main(int argc, char **argv) {
    WrenConfiguration config;
    wrenInitConfiguration(&config);
    config.writeFn = &writeFn;
    config.bindForeignMethodFn = &bindForeignMethod;
    WrenVM* vm = wrenNewVM(&config);
    const char* module = "main";
    const char* fileName = "video_display_modes.wren";
    char *script = readFile(fileName);
    wrenInterpret(vm, module, script);
    wrenFreeVM(vm);
    free(script);
    return 0;
}







Python: import win32api
import win32con
import pywintypes
devmode=pywintypes.DEVMODEType()
devmode.PelsWidth=640
devmode.PelsHeight=480
devmode.Fields=win32con.DM_PELSWIDTH | win32con.DM_PELSHEIGHT
win32api.ChangeDisplaySettings(devmode,0)
Task: Keyboard input_Flush the keyboard buffer

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

int main(int argc, char* argv[])
{
    
    
    char text[256];
    getchar();

    
    
    
    

    
    
    fseek(stdin, 0, SEEK_END);

    
    
    

    
    
    fgets(text, sizeof(text), stdin);
    puts(text);

    return EXIT_SUCCESS;
}







Python: def flush_input():
    try:
        import msvcrt
        while msvcrt.kbhit():
            msvcrt.getch()
    except ImportError:
        import sys, termios
        termios.tcflush(sys.stdin, termios.TCIOFLUSH)
Task: Numerical integration_Adaptive Simpson's method

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

typedef struct { double m; double fm; double simp; } triple;


triple _quad_simpsons_mem(double (*f)(double), double a, double fa, double b, double fb) {
    
    double m = (a + b) / 2;
    double fm = f(m);
    double simp = fabs(b - a) / 6 * (fa + 4*fm + fb);
    triple t = {m, fm, simp};
    return t;
}

double _quad_asr(double (*f)(double), double a, double fa, double b, double fb, double eps, double whole, double m, double fm) {
    
    
    triple lt = _quad_simpsons_mem(f, a, fa, m, fm);
    triple rt = _quad_simpsons_mem(f, m, fm, b, fb);
    double delta = lt.simp + rt.simp - whole;
    if (fabs(delta) <= eps * 15) return lt.simp + rt.simp + delta/15;
    return _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +
           _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm);
}

double quad_asr(double (*f)(double), double a, double b, double eps) {
    
    double fa = f(a);
    double fb = f(b);
    triple t = _quad_simpsons_mem(f, a, fa, b, fb);
    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm);
}

int main(){
    double a = 0.0, b = 1.0;
    double sinx = quad_asr(sin, a, b, 1e-09);
    printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx);
    return 0;
}







Python: 



import math

import collections
triple = collections.namedtuple('triple', 'm fm simp')

def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:
    
    m = a + (b - a) / 2
    fm = f(m)
    simp = abs(b - a) / 6 * (fa + 4*fm + fb)
    return triple(m, fm, simp,)
 
def _quad_asr(f: callable, a: float, fa: float, b: float, fb: float, eps: float, whole: float, m: float, fm: float)->float:
    
    lt = _quad_simpsons_mem(f, a, fa, m, fm)
    rt = _quad_simpsons_mem(f, m, fm, b, fb)
    delta = lt.simp + rt.simp - whole
    return (lt.simp + rt.simp + delta/15
        if (abs(delta) <= eps * 15) else
            _quad_asr(f, a, fa, m, fm, eps/2, lt.simp, lt.m, lt.fm) +
            _quad_asr(f, m, fm, b, fb, eps/2, rt.simp, rt.m, rt.fm)
    )

def quad_asr(f: callable, a: float, b: float, eps: float)->float:
    
    fa = f(a)
    fb = f(b)
    t = _quad_simpsons_mem(f, a, fa, b, fb)
    return _quad_asr(f, a, fa, b, fb, eps, t.simp, t.m, t.fm)

def main():
    (a, b,) = (0.0, 1.0,)
    sinx = quad_asr(math.sin, a, b, 1e-09);
    print("Simpson's integration of sine from {} to {} = {}\n".format(a, b, sinx))

main()
Task: FASTA format

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

void main()
{
	FILE * fp;
	char * line = NULL;
	size_t len = 0;
	ssize_t read;

	fp = fopen("fasta.txt", "r");
	if (fp == NULL)
		exit(EXIT_FAILURE);

	int state = 0;
	while ((read = getline(&line, &len, fp)) != -1) {
		
		if (line[read - 1] == '\n')
			line[read - 1] = 0;
		
		if (line[0] == '>') {
			if (state == 1)
				printf("\n");
			printf("%s: ", line+1);
			state = 1;
		} else {
			
			printf("%s", line);
		}
	}
	printf("\n");

	fclose(fp);
	if (line)
		free(line);
	exit(EXIT_SUCCESS);
}







Python: import io

FASTA=

infile = io.StringIO(FASTA)

def fasta_parse(infile):
    key = ''
    for line in infile:
        if line.startswith('>'):
            if key:
                yield key, val
            key, val = line[1:].rstrip().split()[0], ''
        elif key:
            val += line.rstrip()
    if key:
        yield key, val

print('\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile)))
Task: Cousin primes

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

#define LIMIT 1000

void sieve(int max, char *s) {
    int p, k;
    memset(s, 0, max);
    for (p=2; p*p<=max; p++)
        if (!s[p]) 
            for (k=p*p; k<=max; k+=p) 
                s[k]=1;
}

int main(void) {
    char primes[LIMIT+1];
    int p, count=0;
    
    sieve(LIMIT, primes);
    for (p=2; p<=LIMIT; p++) {
        if (!primes[p] && !primes[p+4]) {
            count++;
            printf("%4d: %4d\n", p, p+4);
        }
    }
    
    printf("There are %d cousin prime pairs below %d.\n", count, LIMIT);
    return 0;
}







Python: 

from itertools import chain, takewhile



def cousinPrimes():
    
    def go(x):
        n = 4 + x
        return [(x, n)] if isPrime(n) else []

    return chain.from_iterable(
        map(go, primes())
    )




def main():
    

    pairs = list(
        takewhile(
            lambda ab: 1000 > ab[1],
            cousinPrimes()
        )
    )

    print(f'{len(pairs)} cousin pairs below 1000:\n')
    print(
        spacedTable(list(
            chunksOf(4)([
                repr(x) for x in pairs
            ])
        ))
    )





def chunksOf(n):
    
    def go(xs):
        return (
            xs[i:n + i] for i in range(0, len(xs), n)
        ) if 0 < n else None
    return go



def isPrime(n):
    
    if n in (2, 3):
        return True
    if 2 > n or 0 == n % 2:
        return False
    if 9 > n:
        return True
    if 0 == n % 3:
        return False

    def p(x):
        return 0 == n % x or 0 == n % (2 + x)

    return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))



def primes():
    
    n = 2
    dct = {}
    while True:
        if n in dct:
            for p in dct[n]:
                dct.setdefault(n + p, []).append(p)
            del dct[n]
        else:
            yield n
            dct[n * n] = [n]
        n = 1 + n



def listTranspose(xss):
    
    def go(xss):
        if xss:
            h, *t = xss
            return (
                [[h[0]] + [xs[0] for xs in t if xs]] + (
                    go([h[1:]] + [xs[1:] for xs in t])
                )
            ) if h and isinstance(h, list) else go(t)
        else:
            return []
    return go(xss)



def spacedTable(rows):
    
    columnWidths = [
        len(str(row[-1])) for row in listTranspose(rows)
    ]
    return '\n'.join([
        ' '.join(
            map(
                lambda w, s: s.rjust(w, ' '),
                columnWidths, row
            )
        ) for row in rows
    ])



if __name__ == '__main__':
    main()
Task: Find palindromic numbers in both binary and ternary bases

C: #include <stdio.h>
typedef unsigned long long xint;

int is_palin2(xint n)
{
	xint x = 0;
	if (!(n&1)) return !n;
	while (x < n) x = x<<1 | (n&1), n >>= 1;
	return n == x || n == x>>1;
}

xint reverse3(xint n)
{
	xint x = 0;
	while (n) x = x*3 + (n%3), n /= 3;
	return x;
}

void print(xint n, xint base)
{
	putchar(' ');
	
	do { putchar('0' + (n%base)), n /= base; } while(n);
	printf("(%lld)", base);
}

void show(xint n)
{
	printf("%llu", n);
	print(n, 2);
	print(n, 3);
	putchar('\n');
}

xint min(xint a, xint b) { return a < b ? a : b; }
xint max(xint a, xint b) { return a > b ? a : b; }

int main(void)
{
	xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n;
	int cnt;

	show(0);
	cnt = 1;

	lo = 0;
	hi = pow2 = pow3 = 1;

	while (1) {
		for (i = lo; i < hi; i++) {
			n = (i * 3 + 1) * pow3 + reverse3(i);
			if (!is_palin2(n)) continue;
			show(n);
			if (++cnt >= 7) return 0;
		}

		if (i == pow3)
			pow3 *= 3;
		else
			pow2 *= 4;

		while (1) {
			while (pow2 <= pow3) pow2 *= 4;

			lo2 = (pow2 / pow3 - 1) / 3;
			hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1;
			lo3 = pow3 / 3;
			hi3 = pow3;

			if (lo2 >= hi3)
				pow3 *= 3;
			else if (lo3 >= hi2)
				pow2 *= 4;
			else {
				lo = max(lo2, lo3);
				hi = min(hi2, hi3);
				break;
			}
		}
	}
	return 0;
}







Python: from itertools import islice

digits = "0123456789abcdefghijklmnopqrstuvwxyz"

def baseN(num,b):
  if num == 0: return "0"
  result = ""
  while num != 0:
    num, d = divmod(num, b)
    result += digits[d]
  return result[::-1] 

def pal2(num):
    if num == 0 or num == 1: return True
    based = bin(num)[2:]
    return based == based[::-1]

def pal_23():
    yield 0
    yield 1
    n = 1
    while True:
        n += 1
        b = baseN(n, 3)
        revb = b[::-1]
        
        for trial in ('{0}{1}'.format(b, revb), '{0}0{1}'.format(b, revb),
                      '{0}1{1}'.format(b, revb), '{0}2{1}'.format(b, revb)):
            t = int(trial, 3)
            if pal2(t):
                yield t

for pal23 in islice(pal_23(), 6):
    print(pal23, baseN(pal23, 3), baseN(pal23, 2))
Task: Check input device is a terminal

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

int main(void)
{
	puts(isatty(fileno(stdin))
		? "stdin is tty"
		: "stdin is not tty");
	return 0;
}







Python: from sys import stdin
if stdin.isatty():
    print("Input comes from tty.")
else:
    print("Input doesn't come from tty.")
Task: Window creation_X11

C: '--- added a flush to exit cleanly   
PRAGMA LDFLAGS `pkg-config --cflags --libs x11`
PRAGMA INCLUDE <X11/Xlib.h>
PRAGMA INCLUDE <X11/Xutil.h>

OPTION PARSE FALSE
 
'---XLIB is so ugly
ALIAS XNextEvent TO EVENT
ALIAS XOpenDisplay TO DISPLAY
ALIAS DefaultScreen TO SCREEN
ALIAS XCreateSimpleWindow TO CREATE
ALIAS XCloseDisplay TO CLOSE_DISPLAY
ALIAS XSelectInput TO EVENT_TYPE
ALIAS XMapWindow TO MAP_EVENT
ALIAS XFillRectangle TO FILL_RECTANGLE
ALIAS XDrawString TO DRAW_STRING
ALIAS XFlush TO FLUSH

 
'---pointer to X Display structure
DECLARE d TYPE  Display*
 
'---pointer to the newly created window		
'DECLARE w TYPE WINDOW
 
'---pointer to the XEvent
DECLARE e TYPE XEvent
 
DECLARE msg TYPE char*
 
'--- number of screen to place the window on
DECLARE s TYPE int
 
 
 
  msg = "Hello, World!"
 
 
   d = DISPLAY(NULL)
   IF d == NULL THEN
	 EPRINT "Cannot open display" FORMAT "%s%s\n"
	 END
   END IF
 
   s = SCREEN(d)
   w = CREATE(d, RootWindow(d, s), 10, 10, 100, 100, 1,BlackPixel(d, s), WhitePixel(d, s))
 
   EVENT_TYPE(d, w, ExposureMask | KeyPressMask)
   MAP_EVENT(d, w)
 
   WHILE  (1) 
	 EVENT(d, &e)
	 IF e.type == Expose THEN
	    FILL_RECTANGLE(d, w, DefaultGC(d, s), 20, 20, 10, 10)
	    DRAW_STRING(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg))
	 END IF
	 IF e.type == KeyPress THEN
	    BREAK
	 END IF   
   WEND
   FLUSH(d)
   CLOSE_DISPLAY(d)







Python: from Xlib import X, display

class Window:
    def __init__(self, display, msg):
        self.display = display
        self.msg = msg
        
        self.screen = self.display.screen()
        self.window = self.screen.root.create_window(
            10, 10, 100, 100, 1,
            self.screen.root_depth,
            background_pixel=self.screen.white_pixel,
            event_mask=X.ExposureMask | X.KeyPressMask,
            )
        self.gc = self.window.create_gc(
            foreground = self.screen.black_pixel,
            background = self.screen.white_pixel,
            )

        self.window.map()

    def loop(self):
        while True:
            e = self.display.next_event()
                
            if e.type == X.Expose:
                self.window.fill_rectangle(self.gc, 20, 20, 10, 10)
                self.window.draw_text(self.gc, 10, 50, self.msg)
            elif e.type == X.KeyPress:
                raise SystemExit

                
if __name__ == "__main__":
    Window(display.Display(), "Hello, World!").loop()
Task: Elementary cellular automaton_Random number generator

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

typedef unsigned long long ull;
#define N (sizeof(ull) * CHAR_BIT)
#define B(x) (1ULL << (x))

void evolve(ull state, int rule)
{
	int i, p, q, b;

	for (p = 0; p < 10; p++) {
		for (b = 0, q = 8; q--; ) {
			ull st = state;
			b |= (st&1) << q;

			for (state = i = 0; i < N; i++)
				if (rule & B(7 & (st>>(i-1) | st<<(N+1-i))))
					state |= B(i);
		}
		printf(" %d", b);
	}
	putchar('\n');
	return;
}

int main(void)
{
	evolve(1, 30);
	return 0;
}







Python: from elementary_cellular_automaton import eca, eca_wrap

def rule30bytes(lencells=100):
    cells = '1' + '0' * (lencells - 1)
    gen = eca(cells, 30)
    while True:
        yield int(''.join(next(gen)[0] for i in range(8)), 2)

if __name__ == '__main__':
    print([b for i,b in zip(range(10), rule30bytes())])
Task: Terminal control_Dimensions

C: #include <sys/ioctl.h>	
#include <err.h>	
#include <fcntl.h>	
#include <stdio.h>	
#include <unistd.h>	

int
main()
{
	struct winsize ws;
	int fd;

	
	fd = open("/dev/tty", O_RDWR);
	if (fd < 0)
		err(1, "/dev/tty");

	 
	if (ioctl(fd, TIOCGWINSZ, &ws) < 0)
		err(1, "/dev/tty");

	printf("%d rows by %d columns\n", ws.ws_row, ws.ws_col);
	printf("(%d by %d pixels)\n", ws.ws_xpixel, ws.ws_ypixel);

	close(fd);	
	return 0;
}







Python: import os

def get_windows_terminal():
    from ctypes import windll, create_string_buffer
    h = windll.kernel32.GetStdHandle(-12)
    csbi = create_string_buffer(22)
    res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)

    
    if not res: return 80, 25 

    import struct
    (bufx, bufy, curx, cury, wattr, left, top, right, bottom, maxx, maxy)\
    = struct.unpack("hhhhHhhhhhh", csbi.raw)
    width = right - left + 1
    height = bottom - top + 1

    return width, height

def get_linux_terminal():
    width = os.popen('tput cols', 'r').readline()
    height = os.popen('tput lines', 'r').readline()

    return int(width), int(height)

print get_linux_terminal() if os.name == 'posix' else get_windows_terminal()
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;
}







Python: import turtle
from itertools import cycle
from time import sleep

def rect(t, x, y):
    x2, y2 = x/2, y/2
    t.setpos(-x2, -y2)
    t.pendown()
    for pos in [(-x2, y2), (x2, y2), (x2, -y2), (-x2, -y2)]: 
        t.goto(pos)
    t.penup()

def rects(t, colour, wait_between_rect=0.1):
    for x in range(550, 0, -25):
        t.color(colour)
        rect(t, x, x*.75)
        sleep(wait_between_rect)

tl=turtle.Turtle()
screen=turtle.Screen()
screen.setup(620,620)
screen.bgcolor('black')
screen.title('Rosetta Code Vibrating Rectangles')
tl.pensize(3)
tl.speed(0)
tl.penup()
tl.ht() 
colours = 'red green blue orange white yellow'.split()
for colour in cycle(colours):
    rects(tl, colour)
    sleep(0.5)
Task: Last list item

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

int compare(const void *a, const void *b) {
    int aa = *(const int *)a;
    int bb = *(const int *)b;
    if (aa < bb) return -1;
    if (aa > bb) return 1;
    return 0;
}

int main() {
    int a[] = {6, 81, 243, 14, 25, 49, 123, 69, 11};
    int isize = sizeof(int);
    int asize = sizeof(a) / isize;
    int i, sum;
    while (asize > 1) {
        qsort(a, asize, isize, compare);
        printf("Sorted list: ");
        for (i = 0; i < asize; ++i) printf("%d ", a[i]);
        printf("\n");
        sum = a[0] + a[1];
        printf("Two smallest: %d + %d = %d\n", a[0], a[1], sum);
        for (i = 2; i < asize; ++i) a[i-2] = a[i];
        a[asize - 2] = sum;
        asize--;
    }
    printf("Last item is %d.\n", a[0]);
    return 0;
}







Python: 

def add_least_reduce(lis):
    
    while len(lis) > 1:
        lis.append(lis.pop(lis.index(min(lis))) + lis.pop(lis.index(min(lis))))
        print('Interim list:', lis)
    return lis

LIST = [6, 81, 243, 14, 25, 49, 123, 69, 11]

print(LIST, ' ==> ', add_least_reduce(LIST.copy()))