WeixiangYan/CodeTransOcean huggingface dataset:
Task: Soundex




Go: package main

import (
    "errors"
    "fmt"
    "unicode"
)

var code = []byte("01230127022455012623017202")

func soundex(s string) (string, error) {
    var sx [4]byte
    var sxi int
    var cx, lastCode byte
    for i, c := range s {
        switch {
        case !unicode.IsLetter(c):
            if c < ' ' || c == 127 {
                return "", errors.New("ASCII control characters disallowed")
            }
            if i == 0 {
                return "", errors.New("initial character must be a letter")
            }
            lastCode = '0'
            continue
        case c >= 'A' && c <= 'Z':
            cx = byte(c - 'A')
        case c >= 'a' && c <= 'z':
            cx = byte(c - 'a')
        default:
            return "", errors.New("non-ASCII letters unsupported")
        }
        
        if i == 0 {
            sx[0] = cx + 'A'
            sxi = 1
            continue
        }
        switch x := code[cx]; x {
        case '7', lastCode:
        case '0':
            lastCode = '0'
        default:
            sx[sxi] = x
            if sxi == 3 {
                return string(sx[:]), nil
            }
            sxi++
            lastCode = x
        }
    }
    if sxi == 0 {
        return "", errors.New("no letters present")
    }
    for ; sxi < 4; sxi++ {
        sx[sxi] = '0'
    }
    return string(sx[:]), nil
}

func main() {
    for _, s := range []string{
        "Robert",   
        "Rupert",   
        "Rubin",    
        "ashcroft", 
        "ashcraft", 
        "moses",    
        "O'Mally",  
        "d jay",    
        "R2-D2",    
        "12p2",     
        "naïve",    
        "",         
        "bump\t",   
    } {
        if x, err := soundex(s); err == nil {
            fmt.Println("soundex", s, "=", x)
        } else {
            fmt.Printf("\"%s\" fail. %s\n", s, err)
        }
    }
}




Python: from itertools import groupby

def soundex(word):
   codes = ("bfpv","cgjkqsxz", "dt", "l", "mn", "r")
   soundDict = dict((ch, str(ix+1)) for ix,cod in enumerate(codes) for ch in cod)
   cmap2 = lambda kar: soundDict.get(kar, '9')
   sdx =  ''.join(cmap2(kar) for kar in word.lower())
   sdx2 = word[0].upper() + ''.join(k for k,g in list(groupby(sdx))[1:] if k!='9')
   sdx3 = sdx2[0:4].ljust(4,'0')
   return sdx3
Task: List rooted trees




Go: package main

import (
    "fmt"
    "log"
    "os"
    "strconv"
)

type tree uint64

var (
    list   []tree
    offset = [32]uint{1: 1}
)

func add(t tree) {
    list = append(list, 1|t<<1)
}

func show(t tree, l uint) {
    for ; l > 0; t >>= 1 {
        l--
        var paren byte
        if (t & 1) != 0 {
            paren = '('
        } else {
            paren = ')'
        }
        fmt.Printf("%c", paren)
    }
}

func listTrees(n uint) {
    for i := offset[n]; i < offset[n+1]; i++ {
        show(list[i], n*2)
        fmt.Println()
    }
}



func assemble(n uint, t tree, sl, pos, rem uint) {
    if rem == 0 {
        add(t)
        return
    }

    if sl > rem { 
        sl = rem
        pos = offset[sl]
    } else if pos >= offset[sl+1] {
        
        sl--
        if sl == 0 {
            return
        }
        pos = offset[sl]
    }

    assemble(n, t<<(2*sl)|list[pos], sl, pos, rem-sl)
    assemble(n, t, sl, pos+1, rem)
}

func mktrees(n uint) {
    if offset[n+1] > 0 {
        return
    }
    if n > 0 {
        mktrees(n - 1)
    }

    assemble(n, 0, n-1, offset[n-1], n-1)
    offset[n+1] = uint(len(list))
}

func main() {
    if len(os.Args) != 2 {
        log.Fatal("There must be exactly 1 command line argument")
    }
    n, err := strconv.Atoi(os.Args[1])
    if err != nil {
        log.Fatal("Argument is not a valid number")
    }
    if n <= 0 || n > 19 { 
        n = 5
    }
    
    add(0)

    mktrees(uint(n))
    fmt.Fprintf(os.Stderr, "Number of %d-trees: %d\n", n, offset[n+1]-offset[n])
    listTrees(uint(n))
}




Python: def bags(n,cache={}):
	if not n: return [(0, "")]

	upto = sum([bags(x) for x in range(n-1, 0, -1)], [])
	return [(c+1, '('+s+')') for c,s in bagchain((0, ""), n-1, upto)]

def bagchain(x, n, bb, start=0):
	if not n: return [x]

	out = []
	for i in range(start, len(bb)):
		c,s = bb[i]
		if c <= n: out += bagchain((x[0] + c, x[1] + s), n-c, bb, i)
	return out


def replace_brackets(s):
	depth,out = 0,[]
	for c in s:
		if c == '(':
			out.append("([{"[depth%3])
			depth += 1
		else:
			depth -= 1
			out.append(")]}"[depth%3])
	return "".join(out)

for x in bags(5): print(replace_brackets(x[1]))
Task: Documentation




Go: 



package example


var (
    
    X, Y, Z int 
)


func XP() { 
    
}


func nonXP() {}



var MEMEME int




Python: class Doc(object):
   
   def method(self, num):
      
      pass
Task: Table creation




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
    })
}




Python: >>> import sqlite3
>>> conn = sqlite3.connect(':memory:')
>>> c = conn.cursor()
>>> c.execute()
<sqlite3.Cursor object at 0x013263B0>
>>> 
c.execute()

<sqlite3.Cursor object at 0x013263B0>
>>> for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
         ]:
	c.execute('insert into stocks values (?,?,?,?,?)', t)

	
<sqlite3.Cursor object at 0x013263B0>
<sqlite3.Cursor object at 0x013263B0>
<sqlite3.Cursor object at 0x013263B0>
>>> 
>>> c = conn.cursor()
>>> c.execute('select * from stocks order by price')
<sqlite3.Cursor object at 0x01326530>
>>> for row in c:
	print row

	
(u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.140000000000001)
(u'2006-03-28', u'BUY', u'IBM', 1000.0, 45.0)
(u'2006-04-06', u'SELL', u'IBM', 500.0, 53.0)
(u'2006-04-05', u'BUY', u'MSOFT', 1000.0, 72.0)
>>>
Task: Problem of Apollonius




Go: package main

import (
    "fmt"
    "math"
)

type circle struct {
    x, y, r float64
}

func main() {
    c1 := circle{0, 0, 1}
    c2 := circle{4, 0, 1}
    c3 := circle{2, 4, 2}
    fmt.Println(ap(c1, c2, c3, true))
    fmt.Println(ap(c1, c2, c3, false))
}

func ap(c1, c2, c3 circle, s bool) circle {
    x1sq := c1.x * c1.x
    y1sq := c1.y * c1.y
    r1sq := c1.r * c1.r
    x2sq := c2.x * c2.x
    y2sq := c2.y * c2.y
    r2sq := c2.r * c2.r
    x3sq := c3.x * c3.x
    y3sq := c3.y * c3.y
    r3sq := c3.r * c3.r
    v11 := 2 * (c2.x - c1.x)
    v12 := 2 * (c2.y - c1.y)
    v13 := x1sq - x2sq + y1sq - y2sq - r1sq + r2sq
    v14 := 2 * (c2.r - c1.r)
    v21 := 2 * (c3.x - c2.x)
    v22 := 2 * (c3.y - c2.y)
    v23 := x2sq - x3sq + y2sq - y3sq - r2sq + r3sq
    v24 := 2 * (c3.r - c2.r)
    if s {
        v14 = -v14
        v24 = -v24
    }
    w12 := v12 / v11
    w13 := v13 / v11
    w14 := v14 / v11
    w22 := v22/v21 - w12
    w23 := v23/v21 - w13
    w24 := v24/v21 - w14
    p := -w23 / w22
    q := w24 / w22
    m := -w12*p - w13
    n := w14 - w12*q
    a := n*n + q*q - 1
    b := m*n - n*c1.x + p*q - q*c1.y
    if s {
        b -= c1.r
    } else {
        b += c1.r
    }
    b *= 2
    c := x1sq + m*m - 2*m*c1.x + p*p + y1sq - 2*p*c1.y - r1sq
    d := b*b - 4*a*c
    rs := (-b - math.Sqrt(d)) / (2 * a)
    return circle{m + n*rs, p + q*rs, rs}
}




Python: from collections import namedtuple
import math

Circle = namedtuple('Circle', 'x, y, r')
 
def solveApollonius(c1, c2, c3, s1, s2, s3):
    
    x1, y1, r1 = c1
    x2, y2, r2 = c2
    x3, y3, r3 = c3

    v11 = 2*x2 - 2*x1
    v12 = 2*y2 - 2*y1
    v13 = x1*x1 - x2*x2 + y1*y1 - y2*y2 - r1*r1 + r2*r2
    v14 = 2*s2*r2 - 2*s1*r1
 
    v21 = 2*x3 - 2*x2
    v22 = 2*y3 - 2*y2
    v23 = x2*x2 - x3*x3 + y2*y2 - y3*y3 - r2*r2 + r3*r3
    v24 = 2*s3*r3 - 2*s2*r2
 
    w12 = v12/v11
    w13 = v13/v11
    w14 = v14/v11
 
    w22 = v22/v21-w12
    w23 = v23/v21-w13
    w24 = v24/v21-w14
 
    P = -w23/w22
    Q = w24/w22
    M = -w12*P-w13
    N = w14 - w12*Q
 
    a = N*N + Q*Q - 1
    b = 2*M*N - 2*N*x1 + 2*P*Q - 2*Q*y1 + 2*s1*r1
    c = x1*x1 + M*M - 2*M*x1 + P*P + y1*y1 - 2*P*y1 - r1*r1
 
    
    D = b*b-4*a*c
    rs = (-b-math.sqrt(D))/(2*a)
 
    xs = M+N*rs
    ys = P+Q*rs
 
    return Circle(xs, ys, rs)

if __name__ == '__main__':
    c1, c2, c3 = Circle(0, 0, 1), Circle(4, 0, 1), Circle(2, 4, 2)
    print(solveApollonius(c1, c2, c3, 1, 1, 1))    
    print(solveApollonius(c1, c2, c3, -1, -1, -1))
Task: Append numbers at same position in strings




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)
}




Python: list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = [10, 11, 12, 13, 14, 15, 16, 17, 18]
list3 = [19, 20, 21, 22, 23, 24, 25, 26, 27]

print([
    ''.join(str(n) for n in z) for z
    in zip(list1, list2, list3)
])
Task: Longest common suffix




Go: package main

import (
    "fmt"
    "strings"
)

func lcs(a []string) string {
    le := len(a)
    if le == 0 {
        return ""
    }
    if le == 1 {
        return a[0]
    }
    le0 := len(a[0])
    minLen := le0
    for i := 1; i < le; i++ {
        if len(a[i]) < minLen {
            minLen = len(a[i])
        }
    }
    if minLen == 0 {
        return ""
    }
    res := ""
    a1 := a[1:]
    for i := 1; i <= minLen; i++ {
        suffix := a[0][le0-i:]
        for _, e := range a1 {
            if !strings.HasSuffix(e, suffix) {
                return res
            }
        }
        res = suffix
    }
    return res
}

func main() {
    tests := [][]string{
        {"baabababc", "baabc", "bbbabc"},
        {"baabababc", "baabc", "bbbazc"},
        {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"},
        {"longest", "common", "suffix"},
        {"suffix"},
        {""},
    }
    for _, test := range tests {
        fmt.Printf("%v -> \"%s\"\n", test, lcs(test))
    }
}




Python: 

from itertools import takewhile
from functools import reduce



def longestCommonSuffix(xs):
    
    def allSame(cs):
        h = cs[0]
        return all(h == c for c in cs[1:])

    def firstCharPrepended(s, cs):
        return cs[0] + s
    return reduce(
        firstCharPrepended,
        takewhile(
            allSame,
            zip(*(reversed(x) for x in xs))
        ),
        ''
    )




def main():
    

    samples = [
        [
            "Sunday", "Monday", "Tuesday", "Wednesday",
            "Thursday", "Friday", "Saturday"
        ], [
            "Sondag", "Maandag", "Dinsdag", "Woensdag",
            "Donderdag", "Vrydag", "Saterdag"
        ]
    ]
    for xs in samples:
        print(
            longestCommonSuffix(xs)
        )



if __name__ == '__main__':
    main()
Task: Idiomatically determine all the lowercase and uppercase letters




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()
	}
}




Python: classes = (str.isupper, str.islower, str.isalnum, str.isalpha, str.isdecimal,
           str.isdigit, str.isidentifier, str.isnumeric, str.isprintable,
           str.isspace, str.istitle)

for stringclass in classes:
    chars = ''.join(chr(i) for i in range(0x10FFFF+1) if stringclass(chr(i)))
    print('\nString class %s has %i characters the first of which are:\n  %r'
          % (stringclass.__name__, len(chars), chars[:100]))
Task: Sum of elements below main diagonal of matrix




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)
}




Python: from numpy import array, tril, sum

A = [[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]]

print(sum(tril(A, -1)))
Task: Retrieve and search chat history




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")
		}
	}
}




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: Rosetta Code_Rank languages by number of users




Go: package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "regexp"
    "sort"
    "strconv"
)

type Result struct {
    lang  string
    users int
}

func main() {
    const minimum = 25
    ex := `"Category:(.+?)( User)?"(\}|,"categoryinfo":\{"size":(\d+),)`
    re := regexp.MustCompile(ex)
    page := "http:
    action := "action=query"
    format := "format=json"
    fversion := "formatversion=2"
    generator := "generator=categorymembers"
    gcmTitle := "gcmtitle=Category:Language%20users"
    gcmLimit := "gcmlimit=500"
    prop := "prop=categoryinfo"
    rawContinue := "rawcontinue="
    page += fmt.Sprintf("%s&%s&%s&%s&%s&%s&%s&%s", action, format, fversion,
        generator, gcmTitle, gcmLimit, prop, rawContinue)
    resp, _ := http.Get(page)
    body, _ := ioutil.ReadAll(resp.Body)
    matches := re.FindAllStringSubmatch(string(body), -1)
    resp.Body.Close()
    var results []Result
    for _, match := range matches {
        if len(match) == 5 {
            users, _ := strconv.Atoi(match[4]) 
            if users >= minimum {
                result := Result{match[1], users}
                results = append(results, result)
            }
        }
    }
    sort.Slice(results, func(i, j int) bool {
        return results[j].users < results[i].users
    })

    fmt.Println("Rank  Users  Language")
    fmt.Println("----  -----  --------")
    rank := 0
    lastUsers := 0
    lastRank := 0
    for i, result := range results {
        eq := " "
        rank = i + 1
        if lastUsers == result.users {
            eq = "="
            rank = lastRank
        } else {
            lastUsers = result.users
            lastRank = rank
        }
        fmt.Printf(" %-2d%s   %3d    %s\n", rank, eq, result.users, result.lang)
    }
}




Python: 

import requests


URL = "http://rosettacode.org/mw/api.php"


PARAMS = {
    "action": "query",
    "format": "json",
    "formatversion": 2,
    "generator": "categorymembers",
    "gcmtitle": "Category:Language users",
    "gcmlimit": 500,
    "prop": "categoryinfo",
}


def fetch_data():
    counts = {}
    continue_ = {"continue": ""}

    
    
    while continue_:
        resp = requests.get(URL, params={**PARAMS, **continue_})
        resp.raise_for_status()

        data = resp.json()

        
        counts.update(
            {
                p["title"]: p.get("categoryinfo", {}).get("size", 0)
                for p in data["query"]["pages"]
            }
        )

        continue_ = data.get("continue", {})

    return counts


if __name__ == "__main__":
    
    counts = fetch_data()

    
    at_least_100 = [(lang, count) for lang, count in counts.items() if count >= 100]

    
    top_languages = sorted(at_least_100, key=lambda x: x[1], reverse=True)

    
    for i, lang in enumerate(top_languages):
        print(f"{i+1:<5}{lang[0][9:][:-5]:<20}{lang[1]}")
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)
    }
  }
}




Python: 
"exec" "python" "$0"

print "Hello World"
Task: Terminal control_Unicode output




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")
    }
}




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




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)
            }
        }
    }
}




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




Go: import (
    "fmt"
    "os"
)

if err := os.Truncate("filename", newSize); err != nil {
    fmt.Println(err)
}




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




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)
    }
}




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




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()
}




Python: def flush_input():
    try:
        import msvcrt
        while msvcrt.kbhit():
            msvcrt.getch()
    except ImportError:
        import sys, termios
        termios.tcflush(sys.stdin, termios.TCIOFLUSH)