WeixiangYan/CodeTransOcean huggingface dataset:
Task: Table creation

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

int main()
{
  sqlite3 *db = NULL;
  char *errmsg;
  
	const char *code = 
	"CREATE TABLE employee (\n"
	"    empID		INTEGER PRIMARY KEY AUTOINCREMENT,\n"
	"	firstName	TEXT NOT NULL,\n"
	"	lastName	TEXT NOT NULL,\n"
	"	AGE			INTEGER NOT NULL,\n"
	"	DOB			DATE NOT NULL)\n" ; 
	
  if ( sqlite3_open("employee.db", &db) == SQLITE_OK ) {
    sqlite3_exec(db, code, NULL, NULL,  &errmsg);
    sqlite3_close(db);
  } else {
    fprintf(stderr, "cannot open db...\n");
    sqlite3_close(db);
    exit(EXIT_FAILURE);
  }
  return 0;
}




Go: package main

import (
    "encoding/binary"
    "encoding/json"
    "fmt"
    "github.com/boltdb/bolt"
    "log"
)

type StockTrans struct {
    Id       int 
    Date     string
    Trans    string
    Symbol   string
    Quantity int
    Price    float32
    Settled  bool
}


func (st *StockTrans) save(db *bolt.DB, bucket string) error {
    err := db.Update(func(tx *bolt.Tx) error {
        b := tx.Bucket([]byte(bucket))
        id, _ := b.NextSequence()
        st.Id = int(id)
        encoded, err := json.Marshal(st)
        if err != nil {
            return err
        }
        return b.Put(itob(st.Id), encoded)
    })
    return err
}


func itob(i int) []byte {
    b := make([]byte, 8)
    binary.BigEndian.PutUint64(b, uint64(i))
    return b
}

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

func main() {
    
    db, err := bolt.Open("store.db", 0600, nil)
    check(err)
    defer db.Close()

    
    err = db.Update(func(tx *bolt.Tx) error {
        _, err := tx.CreateBucketIfNotExists([]byte("stocks"))
        return err
    })
    check(err)

    transactions := []*StockTrans{
        {0, "2006-01-05", "BUY", "RHAT", 100, 35.14, true},
        {0, "2006-03-28", "BUY", "IBM", 1000, 45, true},
        {0, "2006-04-06", "SELL", "IBM", 500, 53, true},
        {0, "2006-04-05", "BUY", "MSOFT", 1000, 72, false},
    }

    
    for _, trans := range transactions {
        err := trans.save(db, "stocks")
        check(err)
    }

    
    fmt.Println("Id     Date    Trans  Sym    Qty  Price  Settled")
    fmt.Println("------------------------------------------------")
    db.View(func(tx *bolt.Tx) error {
        b := tx.Bucket([]byte("stocks"))
        b.ForEach(func(k, v []byte) error {
            st := new(StockTrans)
            err := json.Unmarshal(v, st)
            check(err)
            fmt.Printf("%d  %s  %-4s  %-5s  %4d  %2.2f  %t\n",
                st.Id, st.Date, st.Trans, st.Symbol, st.Quantity, st.Price, st.Settled)
            return nil
        })
        return nil
    })
}
Task: Append numbers at same position in strings

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

int main(void) {
    int list[3][9], i;
    for(i=0;i<27;i++) list[i/9][i%9]=1+i;
    for(i=0;i<9;i++) printf( "%d%d%d  ", list[0][i], list[1][i], list[2][i] );
    return 0;
}




Go: package main

import "fmt"

func main() {
    list1 := [9]int{1, 2, 3, 4, 5, 6, 7, 8, 9}
    list2 := [9]int{10, 11, 12, 13, 14, 15, 16, 17, 18}
    list3 := [9]int{19, 20, 21, 22, 23, 24, 25, 26, 27}
    var list [9]int
    for i := 0; i < 9; i++ {
        list[i] = list1[i]*1e4 + list2[i]*1e2 + list3[i]
    }
    fmt.Println(list)
}
Task: Arena storage pool

C: #include <stdlib.h>




Go: package main

import (
    "fmt"
    "runtime"
    "sync"
)





func main() {
    
    
    p := sync.Pool{New: func() interface{} {
        fmt.Println("pool empty")
        return new(int)
    }}
    
    i := new(int)
    j := new(int)
    
    *i = 1
    *j = 2
    fmt.Println(*i + *j) 
    
    
    
    
    p.Put(i)
    p.Put(j)
    
    
    i = nil
    j = nil
    
    
    
    i = p.Get().(*int)
    j = p.Get().(*int)
    *i = 4
    *j = 5
    fmt.Println(*i + *j) 
    
    p.Put(i)
    p.Put(j)
    i = nil
    j = nil
    runtime.GC()
    i = p.Get().(*int)
    j = p.Get().(*int)
    *i = 7
    *j = 8
    fmt.Println(*i + *j) 
}
Task: Idiomatically determine all the lowercase and uppercase letters

C: #include <stdio.h>

int main(int argc, char const *argv[]) {
  for (char c = 0x41; c < 0x5b; c ++) putchar(c);
  putchar('\n');
  for (char c = 0x61; c < 0x7b; c ++) putchar(c);
  putchar('\n');
  return 0;
}




Go: package main

import (
	"fmt"
	"unicode"
)

const (
	lcASCII = "abcdefghijklmnopqrstuvwxyz"
	ucASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
)

func main() {
	fmt.Println("ASCII lower case:")
	fmt.Println(lcASCII)
	for l := 'a'; l <= 'z'; l++ {
		fmt.Print(string(l))
	}
	fmt.Println()

	fmt.Println("\nASCII upper case:")
	fmt.Println(ucASCII)
	for l := 'A'; l <= 'Z'; l++ {
		fmt.Print(string(l))
	}
	fmt.Println()

	fmt.Println("\nUnicode version " + unicode.Version)
	showRange16("Lower case 16-bit code points:", unicode.Lower.R16)
	showRange32("Lower case 32-bit code points:", unicode.Lower.R32)
	showRange16("Upper case 16-bit code points:", unicode.Upper.R16)
	showRange32("Upper case 32-bit code points:", unicode.Upper.R32)
}

func showRange16(hdr string, rList []unicode.Range16) {
	fmt.Print("\n", hdr, "\n")
	fmt.Printf("%d ranges:\n", len(rList))
	for _, rng := range rList {
		fmt.Printf("%U: ", rng.Lo)
		for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
			fmt.Printf("%c", r)
		}
		fmt.Println()
	}
}

func showRange32(hdr string, rList []unicode.Range32) {
	fmt.Print("\n", hdr, "\n")
	fmt.Printf("%d ranges:\n", len(rList))
	for _, rng := range rList {
		fmt.Printf("%U: ", rng.Lo)
		for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
			fmt.Printf("%c", r)
		}
		fmt.Println()
	}
}
Task: Sum of elements below main diagonal of matrix

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

typedef struct{
	int rows,cols;
	int** dataSet;
}matrix;

matrix readMatrix(char* dataFile){
	FILE* fp = fopen(dataFile,"r");
	matrix rosetta;
	int i,j;
	
	fscanf(fp,"%d%d",&rosetta.rows,&rosetta.cols);
	
	rosetta.dataSet = (int**)malloc(rosetta.rows*sizeof(int*));
	
	for(i=0;i<rosetta.rows;i++){
		rosetta.dataSet[i] = (int*)malloc(rosetta.cols*sizeof(int));
		for(j=0;j<rosetta.cols;j++)
			fscanf(fp,"%d",&rosetta.dataSet[i][j]);
	}
	
	fclose(fp);
	return rosetta;
}

void printMatrix(matrix rosetta){
	int i,j;
	
	for(i=0;i<rosetta.rows;i++){
		printf("\n");
		for(j=0;j<rosetta.cols;j++)
			printf("%3d",rosetta.dataSet[i][j]);
	}
}

int findSum(matrix rosetta){
	int i,j,sum = 0;
	
	for(i=1;i<rosetta.rows;i++){
		for(j=0;j<i;j++){
			sum += rosetta.dataSet[i][j];
		}
	}
	
	return sum;
}

int main(int argC,char* argV[])
{
	if(argC!=2)
		return printf("Usage : %s <filename>",argV[0]);
	
	matrix data = readMatrix(argV[1]);
	
	printf("\n\nMatrix is : \n\n");
	printMatrix(data);
	
	printf("\n\nSum below main diagonal : %d",findSum(data));
	
	return 0;
}




Go: package main

import (
    "fmt"
    "log"
)

func main() {
    m := [][]int{
        {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},
    }
    if len(m) != len(m[0]) {
        log.Fatal("Matrix must be square.")
    }
    sum := 0
    for i := 1; i < len(m); i++ {
        for j := 0; j < i; j++ {
            sum = sum + m[i][j]
        }
    }
    fmt.Println("Sum of elements below main diagonal is", sum)
}
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;
}




Go: package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"
	"time"
)

func get(url string) (res string, err error) {
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	buf, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	return string(buf), nil
}

func grep(needle string, haystack string) (res []string) {
	for _, line := range strings.Split(haystack, "\n") {
		if strings.Contains(line, needle) {
			res = append(res, line)
		}
	}
	return res
}

func genUrl(i int, loc *time.Location) string {
	date := time.Now().In(loc).AddDate(0, 0, i)
	return date.Format("http:
}

func main() {
	needle := os.Args[1]
	back := -10
	serverLoc, err := time.LoadLocation("Europe/Berlin")
	if err != nil {
		log.Fatal(err)
	}
	for i := back; i <= 0; i++ {
		url := genUrl(i, serverLoc)
		contents, err := get(url)
		if err != nil {
			log.Fatal(err)
		}
		found := grep(needle, contents)
		if len(found) > 0 {
			fmt.Printf("%v\n------\n", url)
			for _, line := range found {
				fmt.Printf("%v\n", line)
			}
			fmt.Printf("------\n\n")
		}
	}
}
Task: Multiline shebang




Go: #!/bin/bash
sed -n -e '12,$p' < "$0" > ttmmpp.go
go build ttmmpp.go
rm ttmmpp.go
binfile="${0%.*}"
mv ttmmpp $binfile
$binfile "$@"
STATUS=$?
rm $binfile
exit $STATUS
######## Go Code start on line 12
package main
import (
  "fmt"
  "os"
)
 
func main() {
  for i, x := range os.Args {
    if i == 0 {
      fmt.Printf("This program is named %s.\n", x)
    } else {
      fmt.Printf("the argument #%d is %s\n", i, x)
    }
  }
}
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;
}




Go: package main

import (
    "fmt"
    "os"
    "strings"
)

func main() {
    lang := strings.ToUpper(os.Getenv("LANG"))
    if strings.Contains(lang, "UTF") {
        fmt.Printf("This terminal supports unicode and U+25b3 is : %c\n", '\u25b3')
    } else {
        fmt.Println("This terminal does not support unicode")
    }
}
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;
}




Go: package main

import (
    "fmt"
    "math"
    "rcu"
)

func main() {
    limit := 999999
    primes := rcu.Primes(limit)
    fmt.Println("Adjacent primes under 1,000,000 whose difference is a square > 36:")
    for i := 1; i < len(primes); i++ {
        diff := primes[i] - primes[i-1]
        if diff > 36 {
            s := int(math.Sqrt(float64(diff)))
            if diff == s*s {
                cp1 := rcu.Commatize(primes[i])
                cp2 := rcu.Commatize(primes[i-1])
                fmt.Printf("%7s - %7s = %3d = %2d x %2d\n", cp1, cp2, diff, s, s)
            }
        }
    }
}
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);
}




Go: import (
    "fmt"
    "os"
)

if err := os.Truncate("filename", newSize); err != nil {
    fmt.Println(err)
}
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;
}




Go: package main

import (
    "fmt"
    "log"
    "os/exec"
    "time"
)

func main() {
    
    out, err := exec.Command("xrandr", "-q").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(out))
    time.Sleep(3 * time.Second)

    
    err = exec.Command("xrandr", "-s", "1024x768").Run()
    if err != nil {
        log.Fatal(err)
    }
    time.Sleep(3 * time.Second)

    
    err = exec.Command("xrandr", "-s", "1366x768").Run()
    if err != nil {
        log.Fatal(err)
    }
}
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;
}




Go: package main

import (
    "log"

    gc "code.google.com/p/goncurses"
)

func main() {
    _, err := gc.Init()
    if err != nil {
        log.Fatal("init:", err)
    }
    defer gc.End()
    gc.FlushInput()
}
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;
}




Go: package main

import (
    "fmt"
    "math"
)

type F = func(float64) float64


func quadSimpsonsMem(f F, a, fa, b, fb float64) (m, fm, simp float64) {
    
    m = (a + b) / 2
    fm = f(m)
    simp = math.Abs(b-a) / 6 * (fa + 4*fm + fb)
    return
}

func quadAsrRec(f F, a, fa, b, fb, eps, whole, m, fm float64) float64 {
    
    
    lm, flm, left := quadSimpsonsMem(f, a, fa, m, fm)
    rm, frm, right := quadSimpsonsMem(f, m, fm, b, fb)
    delta := left + right - whole
    if math.Abs(delta) <= eps*15 {
        return left + right + delta/15
    }
    return quadAsrRec(f, a, fa, m, fm, eps/2, left, lm, flm) +
        quadAsrRec(f, m, fm, b, fb, eps/2, right, rm, frm)
}

func quadAsr(f F, a, b, eps float64) float64 {
    
    fa, fb := f(a), f(b)
    m, fm, whole := quadSimpsonsMem(f, a, fa, b, fb)
    return quadAsrRec(f, a, fa, b, fb, eps, whole, m, fm)
}

func main() {
    a, b := 0.0, 1.0
    sinx := quadAsr(math.Sin, a, b, 1e-09)
    fmt.Printf("Simpson's integration of sine from %g to %g = %f\n", a, b, sinx)   
}
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);
}




Go: package main

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

func main() {
        f, err := os.Open("rc.fasta")
        if err != nil {
                fmt.Println(err)
                return
        }
        defer f.Close()
        s := bufio.NewScanner(f)
        headerFound := false
        for s.Scan() {
                line := s.Text()
                switch {
                case line == "":
                        continue
                case line[0] != '>':
                        if !headerFound {
                                fmt.Println("missing header")
                                return
                        }
                        fmt.Print(line)
                case headerFound:
                        fmt.Println()
                        fallthrough
                default:
                        fmt.Printf("%s: ", line[1:])
                        headerFound = true
                }
        }
        if headerFound {
                fmt.Println()
        }
        if err := s.Err(); err != nil {
                fmt.Println(err)
        }
}
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;
}




Go: package main

import "fmt"

func isPrime(n int) bool {
    switch {
    case n < 2:
        return false
    case n%2 == 0:
        return n == 2
    case n%3 == 0:
        return n == 3
    default:
        d := 5
        for d*d <= n {
            if n%d == 0 {
                return false
            }
            d += 2
            if n%d == 0 {
                return false
            }
            d += 4
        }
        return true
    }
}

func main() {
    count := 0
    fmt.Println("Cousin prime pairs whose elements are less than 1,000:")
    for i := 3; i <= 995; i += 2 {
        if isPrime(i) && isPrime(i+4) {
            fmt.Printf("%3d:%3d  ", i, i+4)
            count++
            if count%7 == 0 {
                fmt.Println()
            }
            if i != 3 {
                i += 4
            } else {
                i += 2
            }
        }
    }
    fmt.Printf("\n\n%d pairs found\n", count)
}
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;
}




Go: package main

import (
    "golang.org/x/crypto/ssh/terminal"
    "fmt"
    "os"
)

func main() {
    if terminal.IsTerminal(int(os.Stdin.Fd())) {
        fmt.Println("Hello terminal")
    } else {
        fmt.Println("Who are you?  You're not a terminal.")
    }
}
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;
}




Go: package main

import "fmt"

const n = 64

func pow2(x uint) uint64 {
    return uint64(1) << x
}

func evolve(state uint64, rule int) {
    for p := 0; p < 10; p++ {
        b := uint64(0)
        for q := 7; q >= 0; q-- {
            st := state
            b |= (st & 1) << uint(q)
            state = 0
            for i := uint(0); i < n; i++ {
                var t1, t2, t3 uint64
                if i > 0 {
                    t1 = st >> (i - 1)
                } else {
                    t1 = st >> 63
                }
                if i == 0 {
                    t2 = st << 1
                } else if i == 1 {
                    t2 = st << 63

                } else {
                    t2 = st << (n + 1 - i)
                }
                t3 = 7 & (t1 | t2)
                if (uint64(rule) & pow2(uint(t3))) != 0 {
                    state |= pow2(i)
                }
            }
        }
        fmt.Printf("%d ", b)
    }
    fmt.Println()
}

func main() {
    evolve(1, 30)
}