WeixiangYan/CodeTransOcean huggingface dataset:
Task: One of n lines in a file




Go: package main

import (
    "bufio"
    "fmt"
    "io"
    "math/rand"
    "time"
)







func choseLineRandomly(r io.Reader) (s string, ln int, err error) {
    br := bufio.NewReader(r)
    s, err = br.ReadString('\n')
    if err != nil {
        return
    }
    ln = 1
    lnLast := 1.
    var sLast string
    for {
        
        
        sLast, err = br.ReadString('\n')
        if err == io.EOF {
            return s, ln, nil 
        }
        if err != nil {
            break
        }
        lnLast++
        if rand.Float64() < 1/lnLast {
            s = sLast
            ln = int(lnLast)
        }
    }
    return 
}





func oneOfN(n int, file io.Reader) int {
    _, ln, err := choseLineRandomly(file)
    if err != nil {
        panic(err)
    }
    return ln
}


type simReader int

func (r *simReader) Read(b []byte) (int, error) {
    if *r <= 0 {
        return 0, io.EOF
    }
    b[0] = '\n'
    *r--
    return 1, nil
}

func main() {
    
    
    n := 10
    freq := make([]int, n)
    rand.Seed(time.Now().UnixNano())
    for times := 0; times < 1e6; times++ {
        sr := simReader(n)
        freq[oneOfN(n, &sr)-1]++
    }

    
    fmt.Println(freq)
}




Python: from random import randrange
try:
    range = xrange
except: pass

def one_of_n(lines): 
    choice = None
    for i, line in enumerate(lines):
        if randrange(i+1) == 0:
            choice = line
    return choice
            
def one_of_n_test(n=10, trials=1000000):
    bins = [0] * n
    if n:
        for i in range(trials):
            bins[one_of_n(range(n))] += 1
    return bins

print(one_of_n_test())
Task: Self-describing numbers




Go: package main

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


func sdn(n int64) bool {
    if n >= 1e10 {
        return false
    }
    s := strconv.FormatInt(n, 10)
    for d, p := range s {
        if int(p)-'0' != strings.Count(s, strconv.Itoa(d)) {
            return false
        }
    }
    return true
}


func main() {
    for n := int64(0); n < 1e10; n++ {
        if sdn(n) {
            fmt.Println(n)
        }
    }
}




Python: >>> def isSelfDescribing(n):
	s = str(n)
	return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))

>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
Task: Repeat




Go: package main

import "fmt"

func repeat(n int, f func()) {
  for i := 0; i < n; i++ {
    f()
  }
}

func fn() {
  fmt.Println("Example")
}

func main() {
  repeat(4, fn)
}




Python: 
def repeat(f,n):
  for i in range(n):
    f();

def procedure():
  print("Example");

repeat(procedure,3);
Task: Sparkline in unicode




Go: package main

import (
    "bufio"
    "errors"
    "fmt"
    "math"
    "os"
    "regexp"
    "strconv"
    "strings"
)

func main() {
    fmt.Println("Numbers please separated by space/commas:")
    sc := bufio.NewScanner(os.Stdin)
    sc.Scan()
    s, n, min, max, err := spark(sc.Text())
    if err != nil {
        fmt.Println(err)
        return
    }
    if n == 1 {
        fmt.Println("1 value =", min)
    } else {
        fmt.Println(n, "values.  Min:", min, "Max:", max)
    }
    fmt.Println(s)
}

var sep = regexp.MustCompile(`[\s,]+`)

func spark(s0 string) (sp string, n int, min, max float64, err error) {
    ss := sep.Split(s0, -1)
    n = len(ss)
    vs := make([]float64, n)
    var v float64
    min = math.Inf(1)
    max = math.Inf(-1)
    for i, s := range ss {
        switch v, err = strconv.ParseFloat(s, 64); {
        case err != nil:
        case math.IsNaN(v):
            err = errors.New("NaN not supported.")
        case math.IsInf(v, 0):
            err = errors.New("Inf not supported.")
        default:
            if v < min {
                min = v
            }
            if v > max {
                max = v
            }
            vs[i] = v
            continue
        }
        return
    }
    if min == max {
        sp = strings.Repeat("▄", n)
    } else {
        rs := make([]rune, n)
        f := 8 / (max - min)
        for j, v := range vs {
            i := rune(f * (v - min))
            if i > 7 {
                i = 7
            }
            rs[j] = '▁' + i
        }
        sp = string(rs)
    }
    return
}




Python: 


bar = '▁▂▃▄▅▆▇█'
barcount = len(bar)

def sparkline(numbers):
    mn, mx = min(numbers), max(numbers)
    extent = mx - mn
    sparkline = ''.join(bar[min([barcount - 1,
                                 int((n - mn) / extent * barcount)])]
                        for n in numbers)
    return mn, mx, sparkline

if __name__ == '__main__':
    import re
    
    for line in ("0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;"
                 "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;"
                 "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 ").split(';'):
        print("\nNumbers:", line)
        numbers = [float(n) for n in re.split(r'[\s,]+', line.strip())]
        mn, mx, sp = sparkline(numbers)
        print('  min: %5f; max: %5f' % (mn, mx))
        print("  " + sp)
Task: Modular inverse




Go: package main

import (
	"fmt"
	"math/big"
)

func main() {
	a := big.NewInt(42)
	m := big.NewInt(2017)
	k := new(big.Int).ModInverse(a, m)
	fmt.Println(k)
}




Python: >>> def extended_gcd(aa, bb):
    lastremainder, remainder = abs(aa), abs(bb)
    x, lastx, y, lasty = 0, 1, 1, 0
    while remainder:
        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
        x, lastx = lastx - quotient*x, x
        y, lasty = lasty - quotient*y, y
    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)

>>> def modinv(a, m):
	g, x, y = extended_gcd(a, m)
	if g != 1:
		raise ValueError
	return x % m

>>> modinv(42, 2017)
1969
>>>
Task: Simulate input_Mouse




Go: package main

import "github.com/go-vgo/robotgo"

func main() {
    robotgo.MouseClick("left", false) 
    robotgo.MouseClick("right", true) 
}




Python: import ctypes

def click():
    ctypes.windll.user32.mouse_event(0x2, 0,0,0,0)    
    ctypes.windll.user32.mouse_event(0x4, 0,0,0,0)    

click()
Task: Hello world_Web server




Go: package main

import (
  "fmt"
  "log"
  "net/http"
)

func main() {
  http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintln(w, "Goodbye, World!")
  })
  log.Fatal(http.ListenAndServe(":8080", nil))
}




Python: from wsgiref.simple_server import make_server

def app(environ, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    yield b"<h1>Goodbye, World!</h1>"

server = make_server('127.0.0.1', 8080, app)
server.serve_forever()
Task: Sunflower fractal




Go: package main

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

func main() {
    dc := gg.NewContext(400, 400)
    dc.SetRGB(1, 1, 1)
    dc.Clear()
    dc.SetRGB(0, 0, 1)
    c := (math.Sqrt(5) + 1) / 2
    numberOfSeeds := 3000
    for i := 0; i <= numberOfSeeds; i++ {
        fi := float64(i)
        fn := float64(numberOfSeeds)
        r := math.Pow(fi, c) / fn
        angle := 2 * math.Pi * c * fi
        x := r*math.Sin(angle) + 200
        y := r*math.Cos(angle) + 200
        fi /= fn / 5
        dc.DrawCircle(x, y, fi)
    }
    dc.SetLineWidth(1)
    dc.Stroke()
    dc.SavePNG("sunflower_fractal.png")
}




Python: from turtle import *
from math import *



iter = 3000
diskRatio = .5

factor = .5 + sqrt(1.25)

screen = getscreen()

(winWidth, winHeight) = screen.screensize()





x = 0.0
y = 0.0

maxRad = pow(iter,factor)/iter;

bgcolor("light blue")

hideturtle()

tracer(0, 0)

for i in range(iter+1):
    r = pow(i,factor)/iter;
    
    if r/maxRad < diskRatio:
        pencolor("black")
    else:
        pencolor("yellow")
 
    theta = 2*pi*factor*i;
        
    up()
    
    setposition(x + r*sin(theta), y + r*cos(theta))
    
    down()
       
    circle(10.0 * i/(1.0*iter))
    
update()

done()
Task: Vogel's approximation method




Go: #include <stdio.h>
#include <limits.h>
 
#define TRUE 1
#define FALSE 0
#define N_ROWS 5
#define N_COLS 5
 
typedef int bool;
 
int supply[N_ROWS] = { 461, 277, 356, 488,  393 };
int demand[N_COLS] = { 278,  60, 461, 116, 1060 };
 
int costs[N_ROWS][N_COLS] = {
    { 46,  74,  9, 28, 99 },
    { 12,  75,  6, 36, 48 },
    { 35, 199,  4,  5, 71 },
    { 61,  81, 44, 88,  9 },
    { 85,  60, 14, 25, 79 }
};


 
int main() {
    

    printf("     A    B    C    D    E\n");
    for (i = 0; i < N_ROWS; ++i) {
        printf("%c", 'V' + i);
        for (j = 0; j < N_COLS; ++j) printf("  %3d", results[i][j]);
        printf("\n");
    }
    printf("\nTotal cost = %d\n", total_cost);
    return 0;
}




Python: from collections import defaultdict

costs  = {'W': {'A': 16, 'B': 16, 'C': 13, 'D': 22, 'E': 17},
          'X': {'A': 14, 'B': 14, 'C': 13, 'D': 19, 'E': 15},
          'Y': {'A': 19, 'B': 19, 'C': 20, 'D': 23, 'E': 50},
          'Z': {'A': 50, 'B': 12, 'C': 50, 'D': 15, 'E': 11}}
demand = {'A': 30, 'B': 20, 'C': 70, 'D': 30, 'E': 60}
cols = sorted(demand.iterkeys())
supply = {'W': 50, 'X': 60, 'Y': 50, 'Z': 50}
res = dict((k, defaultdict(int)) for k in costs)
g = {}
for x in supply:
    g[x] = sorted(costs[x].iterkeys(), key=lambda g: costs[x][g])
for x in demand:
    g[x] = sorted(costs.iterkeys(), key=lambda g: costs[g][x])

while g:
    d = {}
    for x in demand:
        d[x] = (costs[g[x][1]][x] - costs[g[x][0]][x]) if len(g[x]) > 1 else costs[g[x][0]][x]
    s = {}
    for x in supply:
        s[x] = (costs[x][g[x][1]] - costs[x][g[x][0]]) if len(g[x]) > 1 else costs[x][g[x][0]]
    f = max(d, key=lambda n: d[n])
    t = max(s, key=lambda n: s[n])
    t, f = (f, g[f][0]) if d[f] > s[t] else (g[t][0], t)
    v = min(supply[f], demand[t])
    res[f][t] += v
    demand[t] -= v
    if demand[t] == 0:
        for k, n in supply.iteritems():
            if n != 0:
                g[k].remove(t)
        del g[t]
        del demand[t]
    supply[f] -= v
    if supply[f] == 0:
        for k, n in demand.iteritems():
            if n != 0:
                g[k].remove(f)
        del g[f]
        del supply[f]

for n in cols:
    print "\t", n,
print
cost = 0
for g in sorted(costs):
    print g, "\t",
    for n in cols:
        y = res[g][n]
        if y != 0:
            print y,
        cost += y * costs[g][n]
        print "\t",
    print
print "\n\nTotal Cost = ", cost
Task: Air mass




Go: package main

import (
    "fmt"
    "math"
)

const (
    RE  = 6371000 
    DD  = 0.001   
    FIN = 1e7     
)


func rho(a float64) float64 { return math.Exp(-a / 8500) }


func radians(degrees float64) float64 { return degrees * math.Pi / 180 }




func height(a, z, d float64) float64 {
    aa := RE + a
    hh := math.Sqrt(aa*aa + d*d - 2*d*aa*math.Cos(radians(180-z)))
    return hh - RE
}


func columnDensity(a, z float64) float64 {
    sum := 0.0
    d := 0.0
    for d < FIN {
        delta := math.Max(DD, DD*d) 
        sum += rho(height(a, z, d+0.5*delta)) * delta
        d += delta
    }
    return sum
}

func airmass(a, z float64) float64 {
    return columnDensity(a, z) / columnDensity(a, 0)
}

func main() {
    fmt.Println("Angle     0 m              13700 m")
    fmt.Println("------------------------------------")
    for z := 0; z <= 90; z += 5 {
        fz := float64(z)
        fmt.Printf("%2d      %11.8f      %11.8f\n", z, airmass(0, fz), airmass(13700, fz))
    }
}




Python: 

from math import sqrt, cos, exp

DEG = 0.017453292519943295769236907684886127134  
RE = 6371000                                     
dd = 0.001      
FIN = 10000000  
 
def rho(a):
    
    return exp(-a / 8500.0)
 
def height(a, z, d):
     
    return sqrt((RE + a)**2 + d**2 - 2 * d * (RE + a) * cos((180 - z) * DEG)) - RE
 
def column_density(a, z):
    
    dsum, d = 0.0, 0.0
    while d < FIN:
        delta = max(dd, (dd)*d)  
        dsum += rho(height(a, z, d + 0.5 * delta)) * delta
        d += delta
    return dsum

def airmass(a, z):
    return column_density(a, z) / column_density(a, 0)

print('Angle           0 m          13700 m\n', '-' * 36)
for z in range(0, 91, 5):
    print(f"{z: 3d}      {airmass(0, z): 12.7f}    {airmass(13700, z): 12.7f}")
Task: Own digits power sum




Go: package main

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

func main() {
    powers := [10]int{0, 1, 4, 9, 16, 25, 36, 49, 64, 81}
    fmt.Println("Own digits power sums for N = 3 to 9 inclusive:")
    for n := 3; n < 10; n++ {
        for d := 2; d < 10; d++ {
            powers[d] *= d
        }
        i := int(math.Pow(10, float64(n-1)))
        max := i * 10
        lastDigit := 0
        sum := 0
        var digits []int
        for i < max {
            if lastDigit == 0 {
                digits = rcu.Digits(i, 10)
                sum = 0
                for _, d := range digits {
                    sum += powers[d]
                }
            } else if lastDigit == 1 {
                sum++
            } else {
                sum += powers[lastDigit] - powers[lastDigit-1]
            }
            if sum == i {
                fmt.Println(i)
                if lastDigit == 0 {
                    fmt.Println(i + 1)
                }
                i += 10 - lastDigit
                lastDigit = 0
            } else if sum > i {
                i += 10 - lastDigit
                lastDigit = 0
            } else if lastDigit < 9 {
                i++
                lastDigit++
            } else {
                i++
                lastDigit = 0
            }
        }
    }
}




Python: 

def isowndigitspowersum(integer):
    
    digits = [int(c) for c in str(integer)]
    exponent = len(digits)
    return sum(x ** exponent for x in digits) == integer

print("Own digits power sums for N = 3 to 9 inclusive:")
for i in range(100, 1000000000):
    if isowndigitspowersum(i):
        print(i)
Task: Bitmap_Bézier curves_Cubic




Go: package raster

const b3Seg = 30

func (b *Bitmap) Bézier3(x1, y1, x2, y2, x3, y3, x4, y4 int, p Pixel) {
    var px, py [b3Seg + 1]int
    fx1, fy1 := float64(x1), float64(y1)
    fx2, fy2 := float64(x2), float64(y2)
    fx3, fy3 := float64(x3), float64(y3)
    fx4, fy4 := float64(x4), float64(y4)
    for i := range px {
        d := float64(i) / b3Seg
        a := 1 - d
        b, c := a * a, d * d
        a, b, c, d = a*b, 3*b*d, 3*a*c, c*d
        px[i] = int(a*fx1 + b*fx2 + c*fx3 + d*fx4)
        py[i] = int(a*fy1 + b*fy2 + c*fy3 + d*fy4)
    }
    x0, y0 := px[0], py[0]
    for i := 1; i <= b3Seg; i++ {
        x1, y1 := px[i], py[i]
        b.Line(x0, y0, x1, y1, p)
        x0, y0 = x1, y1
    }
}

func (b *Bitmap) Bézier3Rgb(x1, y1, x2, y2, x3, y3, x4, y4 int, c Rgb) {
    b.Bézier3(x1, y1, x2, y2, x3, y3, x4, y4, c.Pixel())
}




Python: def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):
    pts = []
    for i in range(n+1):
        t = i / n
        a = (1. - t)**3
        b = 3. * t * (1. - t)**2
        c = 3.0 * t**2 * (1.0 - t)
        d = t**3
        
        x = int(a * x0 + b * x1 + c * x2 + d * x3)
        y = int(a * y0 + b * y1 + c * y2 + d * y3)
        pts.append( (x, y) )
    for i in range(n):
        self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])
Bitmap.cubicbezier = cubicbezier

bitmap = Bitmap(17,17)
bitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)
bitmap.chardisplay()
Task: Sorting algorithms_Pancake sort




Go: package main

import "fmt"

func main() {
    list := pancake{31, 41, 59, 26, 53, 58, 97, 93, 23, 84}
    fmt.Println("unsorted:", list)

    list.sort()
    fmt.Println("sorted!  ", list)
}

type pancake []int

func (a pancake) sort() {
    for uns := len(a) - 1; uns > 0; uns-- {
        
        lx, lg := 0, a[0]
        for i := 1; i <= uns; i++ {
            if a[i] > lg {
                lx, lg = i, a[i]
            }
        }
        
        a.flip(lx)
        a.flip(uns)
    }
}

func (a pancake) flip(r int) {
    for l := 0; l < r; l, r = l+1, r-1 {
        a[l], a[r] = a[r], a[l]
    }
}




Python: tutor = False

def pancakesort(data):
    if len(data) <= 1:
        return data
    if tutor: print()
    for size in range(len(data), 1, -1):
        maxindex = max(range(size), key=data.__getitem__)
        if maxindex+1 != size:
            
            if maxindex != 0:
                
                if tutor: print('With: %r doflip  %i'
                                % ( ' '.join(str(x) for x in data), maxindex+1 ))
                data[:maxindex+1] = reversed(data[:maxindex+1])
            
            if tutor: print('With: %r  doflip %i'
                                % ( ' '.join(str(x) for x in data), size ))
            data[:size] = reversed(data[:size])
    if tutor: print()
Task: Largest five adjacent number




Go: package main

import (
    "fmt"
    "math/rand"
    "rcu"
    "strings"
    "time"
)

func main() {
    rand.Seed(time.Now().UnixNano())
    var sb strings.Builder
    for i := 0; i < 1000; i++ {
        sb.WriteByte(byte(rand.Intn(10) + 48))
    }
    number := sb.String()
    for i := 99999; i >= 0; i-- {
        quintet := fmt.Sprintf("%05d", i)
        if strings.Contains(number, quintet) {
            ci := rcu.Commatize(i)
            fmt.Printf("The largest  number formed from 5 adjacent digits (%s) is: %6s\n", quintet, ci)
            break
        }
    }
    for i := 0; i <= 99999; i++ {
        quintet := fmt.Sprintf("%05d", i)
        if strings.Contains(number, quintet) {
            ci := rcu.Commatize(i)
            fmt.Printf("The smallest number formed from 5 adjacent digits (%s) is: %6s\n", quintet, ci)
            return
        }
    }
}




Python: 

from random import seed,randint
from datetime import datetime

seed(str(datetime.now()))

largeNum = [randint(1,9)]

for i in range(1,1000):
    largeNum.append(randint(0,9))

maxNum,minNum = 0,99999

for i in range(0,994):
    num = int("".join(map(str,largeNum[i:i+5])))
    if num > maxNum:
        maxNum = num
    elif num < minNum:
        minNum = num

print("Largest 5-adjacent number found ", maxNum)
print("Smallest 5-adjacent number found ", minNum)
Task: Sum of square and cube digits of an integer are primes




Go: package main

import (
    "fmt"
    "rcu"
)

func main() {
    for i := 1; i < 100; i++ {
        if !rcu.IsPrime(rcu.DigitSum(i*i, 10)) {
            continue
        }
        if rcu.IsPrime(rcu.DigitSum(i*i*i, 10)) {
            fmt.Printf("%d ", i)
        }
    }
    fmt.Println()
}




Python: 

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

def digSum(n, b):
    s = 0
    while n:
        s += (n % b)
        n = n // b
    return s

if __name__ == '__main__':
    for n in range(11, 99):
        if isPrime(digSum(n**3, 10)) and isPrime(digSum(n**2, 10)):
            print(n, end = "  ")
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)
}




Python: from numpy import log

def sieve_of_Sundaram(nth, print_all=True):
    
    assert nth > 0, "nth must be a positive integer"
    k = int((2.4 * nth * log(nth)) // 2)  
    integers_list = [True] * k
    for i in range(1, k):
        j = i
        while i + j + 2 * i * j < k:
            integers_list[i + j + 2 * i * j] = False
            j += 1
    pcount = 0
    for i in range(1, k + 1):
        if integers_list[i]:
            pcount += 1
            if print_all:
                print(f"{2 * i + 1:4}", end=' ')
                if pcount % 10 == 0:
                    print()

            if pcount == nth:
                print(f"\nSundaram primes start with 3. The {nth}th Sundaram prime is {2 * i + 1}.\n")
                break



sieve_of_Sundaram(100, True)

sieve_of_Sundaram(1000000, False)
Task: Active Directory_Connect




Go: package main

import (
    "log"
    "github.com/jtblin/go-ldap-client"
)

func main() {
    client := &ldap.LDAPClient{
        Base:         "dc=example,dc=com",
        Host:         "ldap.example.com",
        Port:         389,
        UseSSL:       false,
        BindDN:       "uid=readonlyuser,ou=People,dc=example,dc=com",
        BindPassword: "readonlypassword",
        UserFilter:   "(uid=%s)",
        GroupFilter:  "(memberUid=%s)",
        Attributes:   []string{"givenName", "sn", "mail", "uid"},
    }
    defer client.Close()
    err := client.Connect()
    if err != nil { 
        log.Fatalf("Failed to connect : %+v", err)
    }
    
}




Python: import ldap

l = ldap.initialize("ldap://ldap.example.com")
try:
    l.protocol_version = ldap.VERSION3
    l.set_option(ldap.OPT_REFERRALS, 0)

    bind = l.simple_bind_s("me@example.com", "password")
finally:
    l.unbind()