WeixiangYan/CodeTransOcean huggingface dataset:
Task: Perceptron




Go: package main

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

const c = 0.00001

func linear(x float64) float64 {
    return x*0.7 + 40
}

type trainer struct {
    inputs []float64
    answer int
}

func newTrainer(x, y float64, a int) *trainer {
    return &trainer{[]float64{x, y, 1}, a}
}

type perceptron struct {
    weights  []float64
    training []*trainer
}

func newPerceptron(n, w, h int) *perceptron {
    weights := make([]float64, n)
    for i := 0; i < n; i++ {
        weights[i] = rand.Float64()*2 - 1
    }

    training := make([]*trainer, 2000)
    for i := 0; i < 2000; i++ {
        x := rand.Float64() * float64(w)
        y := rand.Float64() * float64(h)
        answer := 1
        if y < linear(x) {
            answer = -1
        }
        training[i] = newTrainer(x, y, answer)
    }
    return &perceptron{weights, training}
}

func (p *perceptron) feedForward(inputs []float64) int {
    if len(inputs) != len(p.weights) {
        panic("weights and input length mismatch, program terminated")
    }
    sum := 0.0
    for i, w := range p.weights {
        sum += inputs[i] * w
    }
    if sum > 0 {
        return 1
    }
    return -1
}

func (p *perceptron) train(inputs []float64, desired int) {
    guess := p.feedForward(inputs)
    err := float64(desired - guess)
    for i := range p.weights {
        p.weights[i] += c * err * inputs[i]
    }
}

func (p *perceptron) draw(dc *gg.Context, iterations int) {
    le := len(p.training)
    for i, count := 0, 0; i < iterations; i, count = i+1, (count+1)%le {
        p.train(p.training[count].inputs, p.training[count].answer)
    }
    x := float64(dc.Width())
    y := linear(x)
    dc.SetLineWidth(2)
    dc.SetRGB255(0, 0, 0) 
    dc.DrawLine(0, linear(0), x, y)
    dc.Stroke()
    dc.SetLineWidth(1)
    for i := 0; i < le; i++ {
        guess := p.feedForward(p.training[i].inputs)
        x := p.training[i].inputs[0] - 4
        y := p.training[i].inputs[1] - 4
        if guess > 0 {
            dc.SetRGB(0, 0, 1) 
        } else {
            dc.SetRGB(1, 0, 0) 
        }
        dc.DrawCircle(x, y, 8)
        dc.Stroke()
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    w, h := 640, 360
    perc := newPerceptron(3, w, h)
    dc := gg.NewContext(w, h)
    dc.SetRGB(1, 1, 1) 
    dc.Clear()
    perc.draw(dc, 2000)
    dc.SavePNG("perceptron.png")
}
Task: URL shortener




Go: 
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "math/rand"
    "net/http"
    "time"
)

const (
    chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    host  = "localhost:8000"
)

type database map[string]string

type shortener struct {
    Long string `json:"long"`
}

func (db database) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    switch req.Method {
    case http.MethodPost: 
        body, err := ioutil.ReadAll(req.Body)
        if err != nil {
            w.WriteHeader(http.StatusBadRequest) 
            return
        }
        var sh shortener
        err = json.Unmarshal(body, &sh)
        if err != nil {
            w.WriteHeader(http.StatusUnprocessableEntity) 
            return
        }
        short := generateKey(8)
        db[short] = sh.Long
        fmt.Fprintf(w, "The shortened URL: http:
    case http.MethodGet: 
        path := req.URL.Path[1:]
        if v, ok := db[path]; ok {
            http.Redirect(w, req, v, http.StatusFound) 
        } else {
            w.WriteHeader(http.StatusNotFound) 
            fmt.Fprintf(w, "No such shortened url: http:
        }
    default:
        w.WriteHeader(http.StatusNotFound) 
        fmt.Fprintf(w, "Unsupprted method: %s\n", req.Method)
    }
}

func generateKey(size int) string {
    key := make([]byte, size)
    le := len(chars)
    for i := 0; i < size; i++ {
        key[i] = chars[rand.Intn(le)]
    }
    return string(key)
}

func main() {
    rand.Seed(time.Now().UnixNano())
    db := make(database)
    log.Fatal(http.ListenAndServe(host, db))
}
Task: Find URI in text




Go: package main

import (
    "fmt"
    "github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre"
)

var pattern = 
    "(*UTF)(*UCP)" +                    
    "[a-z][-a-z0-9+.]*:" +              
    "(?=[/\\w])" +                      
    "(?:
    "[-\\w.~/%!$&'()*+,;=]*" +          
    "(?:\\?[-\\w.~%!$&'()*+,;=/?]*)?" + 
    "(?:\\#[-\\w.~%!$&'()*+,;=/?]*)?"   

func main() {
    text := `
this URI contains an illegal character, parentheses and a misplaced full stop:
http:
and another one just to confuse the parser: http:
")" is handled the wrong way by the mediawiki parser.
ftp:
ftp:
ftp:
leading junk ftp:
leading junk ftp:
if you have other interesting URIs for testing, please add them here:
http:
http:
`
    descs := []string{"URIs:-", "IRIs:-"}
    patterns := []string{pattern[12:], pattern}
    for i := 0; i <= 1; i++ {
        fmt.Println(descs[i])
        re := pcre.MustCompile(patterns[i], 0)
        t := text
        for {
            se := re.FindIndex([]byte(t), 0)
            if se == nil {
                break
            }
            fmt.Println(t[se[0]:se[1]])
            t = t[se[1]:]
        }
        fmt.Println()
    }
}
Task: Pseudorandom number generator image




Go: package main

import (
    "image"
    "image/color"
    "image/png"
    "log"
    "math/rand"
    "os"
    "time"
)

func main() {
    rand.Seed(time.Now().UnixNano())
    img := image.NewNRGBA(image.Rect(0, 0, 1000, 1000))
    for x := 0; x < 1000; x++ {
        for y := 0; y < 1000; y++ {
            col := color.RGBA{uint8(rand.Intn(256)), uint8(rand.Intn(256)), uint8(rand.Intn(256)), 255}
            img.Set(x, y, col)
        }
    }
    fileName := "pseudorandom_number_generator.png"
    imgFile, err := os.Create(fileName)
    if err != nil {
        log.Fatal(err)
    }
    defer imgFile.Close()

    if err := png.Encode(imgFile, img); err != nil {
        imgFile.Close()
        log.Fatal(err)
    }
}
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")
		}
	}
}
Task: Find duplicate files




Go: package main

import (
    "fmt"
    "crypto/md5"
    "io/ioutil"
    "log"
    "os"
    "path/filepath"
    "sort"
    "time"
)

type fileData struct {
    filePath string
    info     os.FileInfo
}

type hash [16]byte

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

func checksum(filePath string) hash {
    bytes, err := ioutil.ReadFile(filePath)
    check(err)
    return hash(md5.Sum(bytes))
}

func findDuplicates(dirPath string, minSize int64) [][2]fileData {
    var dups [][2]fileData
    m := make(map[hash]fileData)
    werr := filepath.Walk(dirPath, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if !info.IsDir() && info.Size() >= minSize {
            h := checksum(path)
            fd, ok := m[h]
            fd2 := fileData{path, info}
            if !ok {
                m[h] = fd2
            } else {
                dups = append(dups, [2]fileData{fd, fd2})
            }
        }
        return nil
    })
    check(werr)
    return dups
}

func main() {
    dups := findDuplicates(".", 1)
    fmt.Println("The following pairs of files have the same size and the same hash:\n")
    fmt.Println("File name                 Size      Date last modified")
    fmt.Println("==========================================================")
    sort.Slice(dups, func(i, j int) bool {
        return dups[i][0].info.Size() > dups[j][0].info.Size() 
    })
    for _, dup := range dups {
        for i := 0; i < 2; i++ {
            d := dup[i]
            fmt.Printf("%-20s  %8d    %v\n", d.filePath, d.info.Size(), d.info.ModTime().Format(time.ANSIC))
        }
        fmt.Println()
    }
}
Task: Legendre prime counting function




Go: package main

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

func cantorPair(x, y int) int {
    if x < 0 || y < 0 {
        log.Fatal("Arguments must be non-negative integers.")
    }
    return (x*x + 3*x + 2*x*y + y + y*y) / 2
}

func pi(n int) int {
    if n < 2 {
        return 0
    }
    if n == 2 {
        return 1
    }
    primes := rcu.Primes(int(math.Sqrt(float64(n))))
    a := len(primes)
    memoPhi := make(map[int]int)

    var phi func(x, a int) int 
    phi = func(x, a int) int {
        if a < 1 {
            return x
        }
        if a == 1 {
            return x - (x >> 1)
        }
        pa := primes[a-1]
        if x <= pa {
            return 1
        }
        key := cantorPair(x, a)
        if v, ok := memoPhi[key]; ok {
            return v
        }
        memoPhi[key] = phi(x, a-1) - phi(x/pa, a-1)
        return memoPhi[key]
    }

    return phi(n, a) + a - 1
}

func main() {
    for i, n := 0, 1; i <= 9; i, n = i+1, n*10 {
        fmt.Printf("10^%d  %d\n", i, pi(n))
    }
}
Task: Rosetta Code_Find bare lang tags




Go: package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
    "regexp"
    "strings"
)

type header struct {
    start, end int
    lang       string
}

type data struct {
    count int
    names *[]string
}

func newData(count int, name string) *data {
    return &data{count, &[]string{name}}
}

var bmap = make(map[string]*data)

func add2bmap(lang, name string) {
    pd := bmap[lang]
    if pd != nil {
        pd.count++
        *pd.names = append(*pd.names, name)
    } else {
        bmap[lang] = newData(1, name)
    }
}

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

func main() {
    expr := `==\s*{{\s*header\s*\|\s*([^\s\}]+)\s*}}\s*==`
    expr2 := fmt.Sprintf("<%s>.*?</%s>", "lang", "lang")  
    r := regexp.MustCompile(expr)
    r2 := regexp.MustCompile(expr2)
    fileNames := []string{"example.txt", "example2.txt", "example3.txt"}
    for _, fileName := range fileNames {
        f, err := os.Open(fileName)
        check(err)
        b, err := ioutil.ReadAll(f)
        check(err)
        f.Close()
        text := string(b)
        fmt.Printf("Contents of %s:\n\n%s\n\n", fileName, text)
        m := r.FindAllStringIndex(text, -1)
        headers := make([]header, len(m))
        if len(m) > 0 {
            for i, p := range m {
                headers[i] = header{p[0], p[1] - 1, ""}
            }
            m2 := r.FindAllStringSubmatch(text, -1)
            for i, s := range m2 {
                headers[i].lang = strings.ToLower(s[1])
            }
        }
        last := len(headers) - 1
        if last == -1 { 
            headers = append(headers, header{-1, -1, "no language"})
            last = 0
        }
        m3 := r2.FindAllStringIndex(text, -1)
        for _, p := range m3 {
            if p[1] < headers[0].start {
                add2bmap("no language", fileName)
            } else if p[0] > headers[last].end {
                add2bmap(headers[last].lang, fileName)
            } else {
                for i := 0; i < last; i++ {
                    if p[0] > headers[i].end && p[0] < headers[i+1].start {
                        add2bmap(headers[i].lang, fileName)
                        break
                    }
                }
            }
        }
    }
    fmt.Println("Results:\n")
    count := 0
    for _, v := range bmap {
        count += v.count
    }
    fmt.Printf(" %d bare language tags.\n\n", count)
    for k, v := range bmap {
        fmt.Printf("  %d in %-11s %v\n", v.count, k, *v.names)
    }
}
Task: Permuted multiples




Go: package main

import (
    "fmt"
    "rcu"
    "sort"
)


func areSame(l1, l2 []int) bool {
    if len(l1) != len(l2) {
        return false
    }
    sort.Ints(l2)
    for i := 0; i < len(l1); i++ {
        if l1[i] != l2[i] {
            return false
        }
    }
    return true
}

func main() {
    i := 100 
    nextPow := 1000
    for {
        digits := rcu.Digits(i, 10)
        if digits[0] != 1 {
            i = nextPow
            nextPow *= 10
            continue
        }
        sort.Ints(digits)
        allSame := true
        for j := 2; j <= 6; j++ {
            digits2 := rcu.Digits(i*j, 10)
            if !areSame(digits, digits2) {
                allSame = false
                break
            }
        }
        if allSame {
            fmt.Println("The smallest positive integer n for which the following")
            fmt.Println("multiples contain exactly the same digits is:")
            fmt.Println("    n =", i)
            for k := 2; k <= 6; k++ {
                fmt.Printf("%d x n = %d\n", k, k*i)
            }
            return
        }
        i = i + 1
    }
}
Task: Wagstaff primes




Go: package main

import (
    "fmt"
    big "github.com/ncw/gmp"
    "rcu"
)

func main() {
    const limit = 29
    count := 0
    p := 1
    one := big.NewInt(1)
    three := big.NewInt(3)
    w := new(big.Int)
    for count < limit {
        for {
            p += 2
            if rcu.IsPrime(p) {
                break
            }
        }
        w.SetUint64(1)
        w.Lsh(w, uint(p))
        w.Add(w, one)
        w.Quo(w, three)
        if w.ProbablyPrime(15) {
            count++
            ws := w.String()
            le := len(ws)
            if le >= 34 {
                ws = ws[0:15] + "..." + ws[le-15:]
            }
            fmt.Printf("%5d: %s", p, ws)
            if le >= 34 {
                fmt.Printf(" (%d digits)", le)
            }
            println()
        }
    }
}
Task: Palindromic gapful numbers




Go: package main

import "fmt"

func reverse(s uint64) uint64 {
    e := uint64(0)
    for s > 0 {
        e = e*10 + (s % 10)
        s /= 10
    }
    return e
}

func commatize(n uint) 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 ord(n uint) string {
    var suffix string
    if n > 10 && ((n-11)%100 == 0 || (n-12)%100 == 0 || (n-13)%100 == 0) {
        suffix = "th"
    } else {
        switch n % 10 {
        case 1:
            suffix = "st"
        case 2:
            suffix = "nd"
        case 3:
            suffix = "rd"
        default:
            suffix = "th"
        }
    }
    return fmt.Sprintf("%s%s", commatize(n), suffix)
}

func main() {
    const max = 10_000_000
    data := [][3]uint{{1, 20, 7}, {86, 100, 8}, {991, 1000, 10}, {9995, 10000, 12}, {1e5, 1e5, 14},
        {1e6, 1e6, 16}, {1e7, 1e7, 18}}
    results := make(map[uint][]uint64)
    for _, d := range data {
        for i := d[0]; i <= d[1]; i++ {
            results[i] = make([]uint64, 9)
        }
    }
    var p uint64
outer:
    for d := uint64(1); d < 10; d++ {
        count := uint(0)
        pow := uint64(1)
        fl := d * 11
        for nd := 3; nd < 20; nd++ {
            slim := (d + 1) * pow
            for s := d * pow; s < slim; s++ {
                e := reverse(s)
                mlim := uint64(1)
                if nd%2 == 1 {
                    mlim = 10
                }
                for m := uint64(0); m < mlim; m++ {
                    if nd%2 == 0 {
                        p = s*pow*10 + e
                    } else {
                        p = s*pow*100 + m*pow*10 + e
                    }
                    if p%fl == 0 {
                        count++
                        if _, ok := results[count]; ok {
                            results[count][d-1] = p
                        }
                        if count == max {
                            continue outer
                        }
                    }
                }
            }
            if nd%2 == 1 {
                pow *= 10
            }
        }
    }

    for _, d := range data {
        if d[0] != d[1] {
            fmt.Printf("%s to %s palindromic gapful numbers (> 100) ending with:\n", ord(d[0]), ord(d[1]))
        } else {
            fmt.Printf("%s palindromic gapful number (> 100) ending with:\n", ord(d[0]))
        }
        for i := 1; i <= 9; i++ {
            fmt.Printf("%d: ", i)
            for j := d[0]; j <= d[1]; j++ {
                fmt.Printf("%*d ", d[2], results[j][i-1])
            }
            fmt.Println()
        }
        fmt.Println()
    }
}
Task: Chernick's Carmichael numbers




Go: package main

import (
    "fmt"
    "math/big"
)

var (
    zero = new(big.Int)
    prod = new(big.Int)
    fact = new(big.Int)
)

func ccFactors(n, m uint64) (*big.Int, bool) {
    prod.SetUint64(6*m + 1)
    if !prod.ProbablyPrime(0) {
        return zero, false
    }
    fact.SetUint64(12*m + 1)
    if !fact.ProbablyPrime(0) { 
        return zero, false
    }
    prod.Mul(prod, fact)
    for i := uint64(1); i <= n-2; i++ {
        fact.SetUint64((1<<i)*9*m + 1)
        if !fact.ProbablyPrime(0) {
            return zero, false
        }
        prod.Mul(prod, fact)
    }
    return prod, true
}

func ccNumbers(start, end uint64) {
    for n := start; n <= end; n++ {
        m := uint64(1)
        if n > 4 {
            m = 1 << (n - 4)
        }
        for {
            num, ok := ccFactors(n, m)
            if ok {
                fmt.Printf("a(%d) = %d\n", n, num)
                break
            }
            if n <= 4 {
                m++
            } else {
                m += 1 << (n - 4)
            }
        }
    }
}

func main() {
    ccNumbers(3, 9)
}
Task: The sieve of Sundaram




Go: package main

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

func sos(n int) []int {
    if n < 3 {
        return []int{}
    }
    var primes []int
    k := (n-3)/2 + 1
    marked := make([]bool, k) 
    limit := (int(math.Sqrt(float64(n)))-3)/2 + 1
    for i := 0; i < limit; i++ {
        p := 2*i + 3
        s := (p*p - 3) / 2
        for j := s; j < k; j += p {
            marked[j] = true
        }
    }
    for i := 0; i < k; i++ {
        if !marked[i] {
            primes = append(primes, 2*i+3)
        }
    }
    return primes
}


func soe(n int) []int {
    if n < 3 {
        return []int{}
    }
    var primes []int
    k := (n-3)/2 + 1
    marked := make([]bool, k) 
    limit := (int(math.Sqrt(float64(n)))-3)/2 + 1
    for i := 0; i < limit; i++ {
        if !marked[i] {
            p := 2*i + 3
            s := (p*p - 3) / 2
            for j := s; j < k; j += p {
                marked[j] = true
            }
        }
    }
    for i := 0; i < k; i++ {
        if !marked[i] {
            primes = append(primes, 2*i+3)
        }
    }
    return primes
}

func main() {
    const limit = int(16e6) 
    start := time.Now()
    primes := sos(limit)
    elapsed := int(time.Since(start).Milliseconds())
    climit := rcu.Commatize(limit)
    celapsed := rcu.Commatize(elapsed)
    million := rcu.Commatize(1e6)
    millionth := rcu.Commatize(primes[1e6-1])
    fmt.Printf("Using the Sieve of Sundaram generated primes up to %s in %s ms.\n\n", climit, celapsed)
    fmt.Println("First 100 odd primes generated by the Sieve of Sundaram:")
    for i, p := range primes[0:100] {
        fmt.Printf("%3d ", p)
        if (i+1)%10 == 0 {
            fmt.Println()
        }
    }
    fmt.Printf("\nThe %s Sundaram prime is %s\n", million, millionth)

    start = time.Now()
    primes = soe(limit)
    elapsed = int(time.Since(start).Milliseconds())
    celapsed = rcu.Commatize(elapsed)
    millionth = rcu.Commatize(primes[1e6-1])
    fmt.Printf("\nUsing the Sieve of Eratosthenes would have generated them in %s ms.\n", celapsed)
    fmt.Printf("\nAs a check, the %s Sundaram prime would again have been %s\n", million, millionth)
}
Task: Consecutive primes with ascending or descending differences




Go: package main

import (
    "fmt"
    "rcu"
)

const LIMIT = 999999

var primes = rcu.Primes(LIMIT)

func longestSeq(dir string) {
    pd := 0
    longSeqs := [][]int{{2}}
    currSeq := []int{2}
    for i := 1; i < len(primes); i++ {
        d := primes[i] - primes[i-1]
        if (dir == "ascending" && d <= pd) || (dir == "descending" && d >= pd) {
            if len(currSeq) > len(longSeqs[0]) {
                longSeqs = [][]int{currSeq}
            } else if len(currSeq) == len(longSeqs[0]) {
                longSeqs = append(longSeqs, currSeq)
            }
            currSeq = []int{primes[i-1], primes[i]}
        } else {
            currSeq = append(currSeq, primes[i])
        }
        pd = d
    }
    if len(currSeq) > len(longSeqs[0]) {
        longSeqs = [][]int{currSeq}
    } else if len(currSeq) == len(longSeqs[0]) {
        longSeqs = append(longSeqs, currSeq)
    }
    fmt.Println("Longest run(s) of primes with", dir, "differences is", len(longSeqs[0]), ":")
    for _, ls := range longSeqs {
        var diffs []int
        for i := 1; i < len(ls); i++ {
            diffs = append(diffs, ls[i]-ls[i-1])
        }
        for i := 0; i < len(ls)-1; i++ {
            fmt.Print(ls[i], " (", diffs[i], ") ")
        }
        fmt.Println(ls[len(ls)-1])
    }
    fmt.Println()
}

func main() {
    fmt.Println("For primes < 1 million:\n")
    for _, dir := range []string{"ascending", "descending"} {
        longestSeq(dir)
    }
}
Task: Wilson primes of order n




Go: package main

import (
    "fmt"
    "math/big"
    "rcu"
)

func main() {
    const LIMIT = 11000
    primes := rcu.Primes(LIMIT)
    facts := make([]*big.Int, LIMIT)
    facts[0] = big.NewInt(1)
    for i := int64(1); i < LIMIT; i++ {
        facts[i] = new(big.Int)
        facts[i].Mul(facts[i-1], big.NewInt(i))
    }
    sign := int64(1)
    f := new(big.Int)
    zero := new(big.Int)
    fmt.Println(" n:  Wilson primes")
    fmt.Println("--------------------")
    for n := 1; n < 12; n++ {
        fmt.Printf("%2d:  ", n)
        sign = -sign
        for _, p := range primes {
            if p < n {
                continue
            }
            f.Mul(facts[n-1], facts[p-n])
            f.Sub(f, big.NewInt(sign))
            p2 := int64(p * p)
            bp2 := big.NewInt(p2)
            if f.Rem(f, bp2).Cmp(zero) == 0 {
                fmt.Printf("%d ", p)
            }
        }
        fmt.Println()
    }
}