WeixiangYan/CodeTransOcean huggingface dataset:
Task: Ramsey's theorem




Go: package main

import "fmt"

var (
    a   [17][17]int
    idx [4]int
)

func findGroup(ctype, min, max, depth int) bool {
    if depth == 4 {
        cs := ""
        if ctype == 0 {
            cs = "un"
        }
        fmt.Printf("Totally %sconnected group:", cs)
        for i := 0; i < 4; i++ {
            fmt.Printf(" %d", idx[i])
        }
        fmt.Println()
        return true
    }

    for i := min; i < max; i++ {
        n := 0
        for ; n < depth; n++ {
            if a[idx[n]][i] != ctype {
                break
            }
        }

        if n == depth {
            idx[n] = i
            if findGroup(ctype, 1, max, depth+1) {
                return true
            }
        }
    }
    return false
}

func main() {
    const mark = "01-"

    for i := 0; i < 17; i++ {
        a[i][i] = 2
    }

    for k := 1; k <= 8; k <<= 1 {
        for i := 0; i < 17; i++ {
            j := (i + k) % 17
            a[i][j], a[j][i] = 1, 1
        }
    }

    for i := 0; i < 17; i++ {
        for j := 0; j < 17; j++ {
            fmt.Printf("%c ", mark[a[i][j]])
        }
        fmt.Println()
    }

    
    

    
    for i := 0; i < 17; i++ {
        idx[0] = i
        if findGroup(1, i+1, 17, 1) || findGroup(0, i+1, 17, 1) {
            fmt.Println("No good.")
            return
        }
    }
    fmt.Println("All good.")
}




Python: range17 = range(17)
a = [['0'] * 17 for i in range17]
idx = [0] * 4


def find_group(mark, min_n, max_n, depth=1):
    if (depth == 4):
        prefix = "" if (mark == '1') else "un"
        print("Fail, found totally {}connected group:".format(prefix))
        for i in range(4):
            print(idx[i])
        return True

    for i in range(min_n, max_n):
        n = 0
        while (n < depth):
            if (a[idx[n]][i] != mark):
                break
            n += 1

        if (n == depth):
            idx[n] = i
            if (find_group(mark, 1, max_n, depth + 1)):
                return True

    return False


if __name__ == '__main__':
    for i in range17:
        a[i][i] = '-'
    for k in range(4):
        for i in range17:
            j = (i + pow(2, k)) % 17
            a[i][j] = a[j][i] = '1'

    
    

    for row in a:
        print(' '.join(row))

    for i in range17:
        idx[0] = i
        if (find_group('1', i + 1, 17) or find_group('0', i + 1, 17)):
            print("no good")
            exit()

    print("all good")
Task: GUI_Maximum window dimensions




Go: package main

import (
    "fmt"
    "github.com/go-vgo/robotgo"
)

func main() {
    w, h := robotgo.GetScreenSize()
    fmt.Printf("Screen size: %d x %d\n", w, h)
    fpid, err := robotgo.FindIds("firefox")
    if err == nil && len(fpid) > 0 {
        pid := fpid[0]
        robotgo.ActivePID(pid)
        robotgo.MaxWindow(pid)
        _, _, w, h = robotgo.GetBounds(pid)
        fmt.Printf("Max usable : %d x %d\n", w, h)
    }
}




Python: 

import tkinter as tk 

root = tk.Tk() 
root.state('zoomed') 
root.update_idletasks() 
tk.Label(root, text=(str(root.winfo_width())+ " x " +str(root.winfo_height())),
         font=("Helvetica", 25)).pack() 
root.mainloop()
Task: Terminal control_Inverse video




Go: package main

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

func main() {
    tput("rev")
    fmt.Print("Rosetta")
    tput("sgr0")
    fmt.Println(" Code")
}

func tput(arg string) error {
    cmd := exec.Command("tput", arg)
    cmd.Stdout = os.Stdout
    return cmd.Run()
}




Python: 

print "\033[7mReversed\033[m Normal"
Task: Getting the number of decimals




Go: package main

import (
    "fmt"
    "log"
    "math"
    "strings"
)

var error = "Argument must be a numeric literal or a decimal numeric string."

func getNumDecimals(n interface{}) int {
    switch v := n.(type) {
    case int:
        return 0
    case float64:
        if v == math.Trunc(v) {
            return 0
        }
        s := fmt.Sprintf("%g", v)
        return len(strings.Split(s, ".")[1])
    case string:
        if v == "" {
            log.Fatal(error)
        }
        if v[0] == '+' || v[0] == '-' {
            v = v[1:]
        }
        for _, c := range v {
            if strings.IndexRune("0123456789.", c) == -1 {
                log.Fatal(error)
            }
        }
        s := strings.Split(v, ".")
        ls := len(s)
        if ls == 1 {
            return 0
        } else if ls == 2 {
            return len(s[1])
        } else {
            log.Fatal("Too many decimal points")
        }
    default:
        log.Fatal(error)
    }
    return 0
}

func main() {
    var a = []interface{}{12, 12.345, 12.345555555555, "12.3450", "12.34555555555555555555", 12.345e53}
    for _, n := range a {
        d := getNumDecimals(n)
        switch v := n.(type) {
        case string:
            fmt.Printf("%q has %d decimals\n", v, d)
        case float32, float64:
            fmt.Printf("%g has %d decimals\n", v, d)
        default:
            fmt.Printf("%d has %d decimals\n", v, d)
        }
    }
}




Python: In [6]: def dec(n):
   ...:     return len(n.rsplit('.')[-1]) if '.' in n else 0

In [7]: dec('12.345')
Out[7]: 3

In [8]: dec('12.3450')
Out[8]: 4

In [9]:
Task: Enumerations




Go: const (
	apple = iota
	banana
	cherry
)




Python: >>> from enum import Enum
>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE')
>>> Contact.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact.FIRST_NAME: 1>), ('LAST_NAME', <Contact.LAST_NAME: 2>), ('PHONE', <Contact.PHONE: 3>)]))
>>> 
>>> 
>>> class Contact2(Enum):
	FIRST_NAME = 1
	LAST_NAME = 2
	PHONE = 3

	
>>> Contact2.__members__
mappingproxy(OrderedDict([('FIRST_NAME', <Contact2.FIRST_NAME: 1>), ('LAST_NAME', <Contact2.LAST_NAME: 2>), ('PHONE', <Contact2.PHONE: 3>)]))
>>>
Task: Paraffins




Go: package main

import (
    "fmt"
    "math/big"
)

const branches = 4
const nMax = 500

var rooted, unrooted [nMax + 1]big.Int
var c [branches]big.Int
var tmp = new(big.Int)
var one = big.NewInt(1)

func tree(br, n, l, sum int, cnt *big.Int) {
    for b := br + 1; b <= branches; b++ {
        sum += n
        if sum > nMax {
            return
        }
        if l*2 >= sum && b >= branches {
            return
        }
        if b == br+1 {
            c[br].Mul(&rooted[n], cnt)
        } else {
            tmp.Add(&rooted[n], tmp.SetInt64(int64(b-br-1)))
            c[br].Mul(&c[br], tmp)
            c[br].Div(&c[br], tmp.SetInt64(int64(b-br)))
        }
        if l*2 < sum {
            unrooted[sum].Add(&unrooted[sum], &c[br])
        }
        if b < branches {
            rooted[sum].Add(&rooted[sum], &c[br])
        }
        for m := n - 1; m > 0; m-- {
            tree(b, m, l, sum, &c[br])
        }
    }
}

func bicenter(s int) {
    if s&1 == 0 {
        tmp.Rsh(tmp.Mul(&rooted[s/2], tmp.Add(&rooted[s/2], one)), 1)
        unrooted[s].Add(&unrooted[s], tmp)
    }
}

func main() {
    rooted[0].SetInt64(1)
    rooted[1].SetInt64(1)
    unrooted[0].SetInt64(1)
    unrooted[1].SetInt64(1)
    for n := 1; n <= nMax; n++ {
        tree(0, n, n, 1, big.NewInt(1))
        bicenter(n)
        fmt.Printf("%d: %d\n", n, &unrooted[n])
    }
}




Python: try:
    import psyco
    psyco.full()
except ImportError:
    pass

MAX_N = 300
BRANCH = 4

ra = [0] * MAX_N
unrooted = [0] * MAX_N

def tree(br, n, l, sum = 1, cnt = 1):
    global ra, unrooted, MAX_N, BRANCH
    for b in xrange(br + 1, BRANCH + 1):
        sum += n
        if sum >= MAX_N:
            return

        
        if l * 2 >= sum and b >= BRANCH:
            return

        if b == br + 1:
            c = ra[n] * cnt
        else:
            c = c * (ra[n] + (b - br - 1)) / (b - br)

        if l * 2 < sum:
            unrooted[sum] += c

        if b < BRANCH:
            ra[sum] += c;
            for m in range(1, n):
                tree(b, m, l, sum, c)

def bicenter(s):
    global ra, unrooted
    if not (s & 1):
        aux = ra[s / 2]
        unrooted[s] += aux * (aux + 1) / 2


def main():
    global ra, unrooted, MAX_N
    ra[0] = ra[1] = unrooted[0] = unrooted[1] = 1

    for n in xrange(1, MAX_N):
        tree(0, n, n)
        bicenter(n)
        print "%d: %d" % (n, unrooted[n])

main()
Task: Minimum number of cells after, before, above and below NxN squares




Go: package main

import "fmt"

func printMinCells(n int) {
    fmt.Printf("Minimum number of cells after, before, above and below %d x %d square:\n", n, n)
    p := 1
    if n > 20 {
        p = 2
    }
    for r := 0; r < n; r++ {
        cells := make([]int, n)
        for c := 0; c < n; c++ {
            nums := []int{n - r - 1, r, c, n - c - 1}
            min := n
            for _, num := range nums {
                if num < min {
                    min = num
                }
            }
            cells[c] = min
        }
        fmt.Printf("%*d \n", p, cells)
    }
}

func main() {
    for _, n := range []int{23, 10, 9, 2, 1} {
        printMinCells(n)
        fmt.Println()
    }
}




Python: def min_cells_matrix(siz):
    return [[min(row, col, siz - row - 1, siz - col - 1) for col in range(siz)] for row in range(siz)]

def display_matrix(mat):
    siz = len(mat)
    spaces = 2 if siz < 20 else 3 if siz < 200 else 4
    print(f"\nMinimum number of cells after, before, above and below {siz} x {siz} square:")
    for row in range(siz):
        print("".join([f"{n:{spaces}}" for n in mat[row]]))

def test_min_mat():
    for siz in [23, 10, 9, 2, 1]:
        display_matrix(min_cells_matrix(siz))

if __name__ == "__main__":
    test_min_mat()
Task: Pentagram




Go: package main

import (
    "github.com/fogleman/gg"
    "math"
)

func Pentagram(x, y, r float64) []gg.Point {
    points := make([]gg.Point, 5)
    for i := 0; i < 5; i++ {
        fi := float64(i)
        angle := 2*math.Pi*fi/5 - math.Pi/2
        points[i] = gg.Point{x + r*math.Cos(angle), y + r*math.Sin(angle)}
    }
    return points
}

func main() {
    points := Pentagram(320, 320, 250)
    dc := gg.NewContext(640, 640)
    dc.SetRGB(1, 1, 1) 
    dc.Clear()
    for i := 0; i <= 5; i++ {
        index := (i * 2) % 5
        p := points[index]
        dc.LineTo(p.X, p.Y)
    }
    dc.SetHexColor("#6495ED") 
    dc.SetFillRule(gg.FillRuleWinding)
    dc.FillPreserve()
    dc.SetRGB(0, 0, 0) 
    dc.SetLineWidth(5)
    dc.Stroke()
    dc.SavePNG("pentagram.png")
}




Python: import turtle

turtle.bgcolor("green")
t = turtle.Turtle()
t.color("red", "blue")
t.begin_fill()
for i in range(0, 5):
    t.forward(200)
    t.right(144)
t.end_fill()
Task: Parse an IP Address




Go: package main

import (
	"encoding/hex"
	"fmt"
	"io"
	"net"
	"os"
	"strconv"
	"strings"
	"text/tabwriter"
)



func parseIPPort(address string) (net.IP, *uint64, error) {
	ip := net.ParseIP(address)
	if ip != nil {
		return ip, nil, nil
	}

	host, portStr, err := net.SplitHostPort(address)
	if err != nil {
		return nil, nil, fmt.Errorf("splithostport failed: %w", err)
	}

	port, err := strconv.ParseUint(portStr, 10, 16)
	if err != nil {
		return nil, nil, fmt.Errorf("failed to parse port: %w", err)
	}

	ip = net.ParseIP(host)
	if ip == nil {
		return nil, nil, fmt.Errorf("failed to parse ip address")
	}

	return ip, &port, nil
}

func ipVersion(ip net.IP) int {
	if ip.To4() == nil {
		return 6
	}

	return 4
}

func main() {
	testCases := []string{
		"127.0.0.1",
		"127.0.0.1:80",
		"::1",
		"[::1]:443",
		"2605:2700:0:3::4713:93e3",
		"[2605:2700:0:3::4713:93e3]:80",
	}

	w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)

	writeTSV := func(w io.Writer, args ...interface{}) {
		fmt.Fprintf(w, strings.Repeat("%s\t", len(args)), args...)
		fmt.Fprintf(w, "\n")
	}

	writeTSV(w, "Input", "Address", "Space", "Port")

	for _, addr := range testCases {
		ip, port, err := parseIPPort(addr)
		if err != nil {
			panic(err)
		}

		portStr := "n/a"
		if port != nil {
			portStr = fmt.Sprint(*port)
		}

		ipVersion := fmt.Sprintf("IPv%d", ipVersion(ip))

		writeTSV(w, addr, hex.EncodeToString(ip), ipVersion, portStr)
	}

	w.Flush()
}




Python: from ipaddress import ip_address
from urllib.parse import urlparse

tests = [
    "127.0.0.1",
    "127.0.0.1:80",
    "::1",
    "[::1]:80",
    "::192.168.0.1",
    "2605:2700:0:3::4713:93e3",
    "[2605:2700:0:3::4713:93e3]:80" ]

def parse_ip_port(netloc):
    try:
        ip = ip_address(netloc)
        port = None
    except ValueError:
        parsed = urlparse('//{}'.format(netloc))
        ip = ip_address(parsed.hostname)
        port = parsed.port
    return ip, port

for address in tests:
    ip, port = parse_ip_port(address)
    hex_ip = {4:'{:08X}', 6:'{:032X}'}[ip.version].format(int(ip))
    print("{:39s}  {:>32s}  IPv{}  port={}".format(
        str(ip), hex_ip, ip.version, port ))
Task: Increasing gaps between consecutive Niven numbers




Go: package main

import "fmt"

type is func() uint64

func newSum() is {
    var ms is
    ms = func() uint64 {
        ms = newSum()
        return ms()
    }
    var msd, d uint64
    return func() uint64 {
        if d < 9 {
            d++
        } else {
            d = 0
            msd = ms()
        }
        return msd + d
    }
}

func newHarshard() is {
    i := uint64(0)
    sum := newSum()
    return func() uint64 {
        for i++; i%sum() != 0; i++ {
        }
        return i
    }
}

func commatize(n uint64) string {
    s := fmt.Sprintf("%d", n)
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    return s
}

func main() {
    fmt.Println("Gap    Index of gap   Starting Niven")
    fmt.Println("===   =============   ==============")
    h := newHarshard()
    pg := uint64(0) 
    pn := h()       
    for i, n := uint64(1), h(); n <= 20e9; i, n = i+1, h() {
        g := n - pn
        if g > pg {
            fmt.Printf("%3d   %13s   %14s\n", g, commatize(i), commatize(pn))
            pg = g
        }
        pn = n
    }
}




Python: 





def digit_sum(n, sum):
    sum += 1
    while n > 0 and n % 10 == 0:
        sum -= 9
        n /= 10
    
    return sum
    
previous = 1
gap = 0
sum = 0
niven_index = 0
gap_index = 1
 
print("Gap index  Gap    Niven index    Niven number")

niven = 1

while gap_index <= 22:
    sum = digit_sum(niven, sum)
    if niven % sum == 0:
        if niven > previous + gap:
            gap = niven - previous;
            print('{0:9d} {1:4d}  {2:13d}     {3:11d}'.format(gap_index, gap, niven_index, previous))
            gap_index += 1
        previous = niven
        niven_index += 1
    niven += 1
Task: Print debugging statement




Go: package main

import (
    "fmt"
    "runtime"
)

type point struct {
    x, y float64
}

func add(x, y int) int {
    result := x + y
    debug("x", x)
    debug("y", y)
    debug("result", result)
    debug("result+1", result+1)
    return result
}

func debug(s string, x interface{}) {
    _, _, lineNo, _ := runtime.Caller(1)
    fmt.Printf("%q at line %d type '%T'\nvalue: %#v\n\n", s, lineNo, x, x)
}

func main() {
    add(2, 7)
    b := true
    debug("b", b)
    s := "Hello"
    debug("s", s)
    p := point{2, 3}
    debug("p", p)
    q := &p
    debug("q", q)
}




Python: import logging, logging.handlers

LOG_FILENAME = "logdemo.log"
FORMAT_STRING = "%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s"
LOGLEVEL = logging.DEBUG


def print_squares(number):
    logger.info("In print_squares")
    for i in range(number):
        print("square of {0} is {1}".format(i , i*i))
        logger.debug(f'square of {i} is {i*i}')

def print_cubes(number):
    logger.info("In print_cubes")
    for j in range(number):
        print("cube of {0} is {1}".format(j, j*j*j))
        logger.debug(f'cube of {j} is {j*j*j}')

if __name__ == "__main__":

    logger = logging.getLogger("logdemo")
    logger.setLevel(LOGLEVEL)
    handler = logging.FileHandler(LOG_FILENAME)
    handler.setFormatter(logging.Formatter(FORMAT_STRING))
    logger.addHandler(handler)

    print_squares(10)
    print_cubes(10)

    logger.info("All done")
Task: Find prime n such that reversed n is also prime




Go: package main

import "fmt"

func sieve(limit int) []bool {
    limit++
    
    c := make([]bool, limit) 
    c[0] = true
    c[1] = true
    for i := 4; i < limit; i += 2 {
        c[i] = true
    }
    p := 3 
    for {
        p2 := p * p
        if p2 >= limit {
            break
        }
        for i := p2; i < limit; i += 2 * p {
            c[i] = true
        }
        for {
            p += 2
            if !c[p] {
                break
            }
        }
    }
    return c
}

func reversed(n int) int {
    rev := 0
    for n > 0 {
        rev = rev*10 + n%10
        n /= 10
    }
    return rev
}

func main() {
    c := sieve(999)
    reversedPrimes := []int{2}
    for i := 3; i < 500; i += 2 {
        if !c[i] && !c[reversed(i)] {
            reversedPrimes = append(reversedPrimes, i)
        }
    }
    fmt.Println("Primes under 500 which are also primes when the digits are reversed:")
    for i, p := range reversedPrimes {
        fmt.Printf("%5d", p)
        if (i+1) % 10 == 0 {
            fmt.Println()
        }
    }
    fmt.Printf("\n\n%d such primes found.\n", len(reversedPrimes))
}




Python: 

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

def isBackPrime(n):
    if not isPrime(n):
        return False
    m = 0
    while n:
        m *= 10
        m += n % 10
        n //= 10
    return isPrime(m)

if __name__ == '__main__':
    for n in range(2, 499):
        if isBackPrime(n):
            print(n, end=' ');
Task: Superellipse




Go: package main

import (
    "github.com/fogleman/gg"
    "math"
)


func superEllipse(dc *gg.Context, n float64, a int) {
    hw := float64(dc.Width() / 2)
    hh := float64(dc.Height() / 2)

    
    y := make([]float64, a+1)
    for x := 0; x <= a; x++ {
        aa := math.Pow(float64(a), n)
        xx := math.Pow(float64(x), n)
        y[x] = math.Pow(aa-xx, 1.0/n)
    }

    
    for x := a; x >= 0; x-- {
        dc.LineTo(hw+float64(x), hh-y[x])
    }
    for x := 0; x <= a; x++ {
        dc.LineTo(hw+float64(x), hh+y[x])
    }
    for x := a; x >= 0; x-- {
        dc.LineTo(hw-float64(x), hh+y[x])
    }
    for x := 0; x <= a; x++ {
        dc.LineTo(hw-float64(x), hh-y[x])
    }

    dc.SetRGB(1, 1, 1) 
    dc.Fill()
}

func main() {
    dc := gg.NewContext(500, 500)
    dc.SetRGB(0, 0, 0) 
    dc.Clear()
    superEllipse(dc, 2.5, 200)
    dc.SavePNG("superellipse.png")
}




Python: 


import matplotlib.pyplot as plt
from math import sin, cos, pi

def sgn(x):
	return ((x>0)-(x<0))*1

a,b,n=200,200,2.5 
na=2/n
step=100 
piece=(pi*2)/step
xp=[];yp=[]

t=0
for t1 in range(step+1):
	
	x=(abs((cos(t)))**na)*a*sgn(cos(t))
	y=(abs((sin(t)))**na)*b*sgn(sin(t))
	xp.append(x);yp.append(y)
	t+=piece

plt.plot(xp,yp) 
plt.title("Superellipse with parameter "+str(n))
plt.show()
Task: Range extraction




Go: package main

import (
    "errors"
    "fmt"
    "strconv"
    "strings"
)

func main() {
    rf, err := rangeFormat([]int{
        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,
    })
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println("range format:", rf)
}

func rangeFormat(a []int) (string, error) {
    if len(a) == 0 {
        return "", nil
    }
    var parts []string
    for n1 := 0; ; {
        n2 := n1 + 1
        for n2 < len(a) && a[n2] == a[n2-1]+1 {
            n2++
        }
        s := strconv.Itoa(a[n1])
        if n2 == n1+2 {
            s += "," + strconv.Itoa(a[n2-1])
        } else if n2 > n1+2 {
            s += "-" + strconv.Itoa(a[n2-1])
        }
        parts = append(parts, s)
        if n2 == len(a) {
            break
        }
        if a[n2] == a[n2-1] {
            return "", errors.New(fmt.Sprintf(
                "sequence repeats value %d", a[n2]))
        }
        if a[n2] < a[n2-1] {
            return "", errors.New(fmt.Sprintf(
                "sequence not ordered: %d < %d", a[n2], a[n2-1]))
        }
        n1 = n2
    }
    return strings.Join(parts, ","), nil
}




Python: def range_extract(lst):
    'Yield 2-tuple ranges or 1-tuple single elements from list of increasing ints'
    lenlst = len(lst)
    i = 0
    while i< lenlst:
        low = lst[i]
        while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
        hi = lst[i]
        if   hi - low >= 2:
            yield (low, hi)
        elif hi - low == 1:
            yield (low,)
            yield (hi,)
        else:
            yield (low,)
        i += 1

def printr(ranges):
    print( ','.join( (('%i-%i' % r) if len(r) == 2 else '%i' % r)
                     for r in ranges ) )

if __name__ == '__main__':
    for lst in [[-8, -7, -6, -3, -2, -1, 0, 1, 3, 4, 5, 7,
                 8, 9, 10, 11, 14, 15, 17, 18, 19, 20],
                [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]]:
        
        printr(range_extract(lst))
Task: Machine code




Go: package main

import "fmt"


import "C"

func main() {
    code := []byte{
        0x55, 0x48, 0x89, 0xe5, 0x89, 0x7d,
        0xfc, 0x89, 0x75, 0xf8, 0x8b, 0x75,
        0xfc, 0x03, 0x75, 0xf8, 0x89, 0x75,
        0xf4, 0x8b, 0x45, 0xf4, 0x5d, 0xc3,
    }
    le := len(code)
    buf := C.mmap(nil, C.size_t(le), C.PROT_READ|C.PROT_WRITE|C.PROT_EXEC,
        C.MAP_PRIVATE|C.MAP_ANON, -1, 0)
    codePtr := C.CBytes(code)
    C.memcpy(buf, codePtr, C.size_t(le))
    var a, b byte = 7, 12
    fmt.Printf("%d + %d = ", a, b)
    C.runMachineCode(buf, C.byte(a), C.byte(b))
    C.munmap(buf, C.size_t(le))
    C.free(codePtr)
}




Python: import ctypes
import os
from ctypes import c_ubyte, c_int

code = bytes([0x8b, 0x44, 0x24, 0x04, 0x03, 0x44, 0x24, 0x08, 0xc3])

code_size = len(code)

if (os.name == 'posix'):
    import mmap
    executable_map = mmap.mmap(-1, code_size, mmap.MAP_PRIVATE | mmap.MAP_ANON, mmap.PROT_READ | mmap.PROT_WRITE | mmap.PROT_EXEC)
    
    executable_map.write(code)
    
    
    func_address = ctypes.addressof(c_ubyte.from_buffer(executable_map))
elif (os.name == 'nt'):
    
    code_buffer = ctypes.create_string_buffer(code)
    PAGE_EXECUTE_READWRITE = 0x40  
    MEM_COMMIT = 0x1000
    executable_buffer_address = ctypes.windll.kernel32.VirtualAlloc(0, code_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE)
    if (executable_buffer_address == 0):
        print('Warning: Failed to enable code execution, call will likely cause a protection fault.')
        func_address = ctypes.addressof(code_buffer)
    else:
        ctypes.memmove(executable_buffer_address, code_buffer, code_size)
        func_address = executable_buffer_address
else:
    
    code_buffer = ctypes.create_string_buffer(code)
    func_address = ctypes.addressof(code_buffer)

prototype = ctypes.CFUNCTYPE(c_int, c_ubyte, c_ubyte) 
func = prototype(func_address)                        
res = func(7,12)
print(res)