WeixiangYan/CodeTransOcean huggingface dataset:
Task: Colour bars_Display




Go: package main

import "github.com/fogleman/gg"

var colors = [8]string{
    "000000", 
    "FF0000", 
    "00FF00", 
    "0000FF", 
    "FF00FF", 
    "00FFFF", 
    "FFFF00", 
    "FFFFFF", 
}

func drawBars(dc *gg.Context) {
    w := float64(dc.Width() / len(colors))
    h := float64(dc.Height())
    for i := range colors {
        dc.SetHexColor(colors[i])
        dc.DrawRectangle(w*float64(i), 0, w, h)
        dc.Fill()
    }
}

func main() {
    dc := gg.NewContext(400, 400)
    drawBars(dc)
    dc.SavePNG("color_bars.png")
}
Task: Decision tables




Go: package main

import (
    "errors"
    "fmt"
    "os"
)

type dtText struct {
    rules, text string
}

var ptText = []dtText{
    {"YYYYNNNN", "Printer does not print"},
    {"YYNNYYNN", "A red light is flashing"},
    {"YNYNYNYN", "Printer is unrecognised"},
    {"--------", ""},
    {"  X     ", "Check the power cable"},
    {"X X     ", "Check the printer-computer cable"},
    {"X X X X ", "Ensure printer software is installed"},
    {"XX  XX  ", "Check/replace ink"},
    {" X X    ", "Check for paper jam"},
}

type dtMap map[string][]string

func compileDT(t []dtText) (dtMap, error) {
    if len(t) == 0 {
        return nil, errors.New("Empty decision table")
    }
    var conditions, actions []dtText
    ruleColumns := len(t[0].rules)
    for i, row := range t {
        if len(row.rules) != ruleColumns {
            return nil, errors.New("Inconsistent number of rule columns")
        }
        if len(row.text) == 0 {
            if conditions != nil {
                return nil, errors.New("Multple separator lines")
            }
            if i == 0 {
                return nil, errors.New("No conditions specified")
            }
            if i == len(t)-1 {
                return nil, errors.New("No actions specified")
            }
            conditions = t[:i]
            actions = t[i+1:]
        }
    }
    if conditions == nil {
        return nil, errors.New("Missing separator line")
    }
    m := make(map[string][]string, ruleColumns)
    kb := make([]byte, len(conditions))
    for col := 0; col < ruleColumns; col++ {
        for i, c := range conditions {
            kb[i] = c.rules[col]
        }
        key := string(kb)
        for _, a := range actions {
            if a.rules[col] != ' ' {
                m[key] = append(m[key], a.text)
            }
        }
    }
    return m, nil
}

func init() {
    var err error
    if ptMap, err = compileDT(ptText); err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
}

var ptMap dtMap

func main() {
    for _, a := range ptMap["NYY"] {
        fmt.Println(a)
    }
}
Task: Digit fifth powers







Python: from time import time


st = time()
print(sum([n for n in range(2, 6*9**5) if sum(int(i)**5 for i in str(n)) == n]), "  ", (time() - st) * 1000, "ms")


st = time()
nums = list(range(10))
nu = list(range(((6 * 9**5) // 100000) + 1))
numbers = []
p5 = []
for i in nums: p5.append(i**5)
for i in nu:
    im = i * 100000
    ip = p5[i]
    for j in nums:
        jm = im + 10000 * j
        jp = ip + p5[j]
        for k in nums:
            km = jm + 1000 * k
            kp = jp + p5[k]
            for l in nums:
                lm = km + 100 * l
                lp = kp + p5[l]
                for m in nums:
                    mm = lm + 10 * m
                    mp = lp + p5[m]
                    for n in nums:
                        nm = mm + n
                        np = mp + p5[n]
                        if np == nm:
                            if nm > 1: numbers.append(nm)
print(sum(numbers), "  ", (time() - st) * 1000, "ms", end = "")
Task: File size distribution







Python: import sys, os
from collections import Counter

def dodir(path):
    global h

    for name in os.listdir(path):
        p = os.path.join(path, name)

        if os.path.islink(p):
            pass
        elif os.path.isfile(p):
            h[os.stat(p).st_size] += 1
        elif os.path.isdir(p):
            dodir(p)
        else:
            pass

def main(arg):
    global h
    h = Counter()
    for dir in arg:
        dodir(dir)

    s = n = 0
    for k, v in sorted(h.items()):
        print("Size %d -> %d file(s)" % (k, v))
        n += v
        s += k * v
    print("Total %d bytes for %d files" % (s, n))

main(sys.argv[1:])
Task: Mutex







Python: import threading
from time import sleep



res = 2
sema = threading.Semaphore(res)

class res_thread(threading.Thread):
    def run(self):
        global res
        n = self.getName()
        for i in range(1, 4):
            
            
            
            sema.acquire()
            res = res - 1
            print n, "+  res count", res
            sleep(2)

                        
            res = res + 1
            print n, "-  res count", res
            sema.release()


for i in range(1, 5):
    t = res_thread()
    t.start()
Task: Pseudo-random numbers_PCG32







Python: mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
CONST = 6364136223846793005


class PCG32():
    
    def __init__(self, seed_state=None, seed_sequence=None):
        if all(type(x) == int for x in (seed_state, seed_sequence)):
            self.seed(seed_state, seed_sequence)
        else:
            self.state = self.inc = 0
    
    def seed(self, seed_state, seed_sequence):
        self.state = 0
        self.inc = ((seed_sequence << 1) | 1) & mask64
        self.next_int()
        self.state = (self.state + seed_state)
        self.next_int()
        
    def next_int(self):
        "return random 32 bit unsigned int"
        old = self.state
        self.state = ((old * CONST) + self.inc) & mask64
        xorshifted = (((old >> 18) ^ old) >> 27) & mask32
        rot = (old >> 59) & mask32
        answer = (xorshifted >> rot) | (xorshifted << ((-rot) & 31))
        answer = answer &mask32
        
        return answer
    
    def  next_float(self):
        "return random float between 0 and 1"
        return self.next_int() / (1 << 32)
    

if __name__ == '__main__':
    random_gen = PCG32()
    random_gen.seed(42, 54)
    for i in range(5):
        print(random_gen.next_int())
        
    random_gen.seed(987654321, 1)
    hist = {i:0 for i in range(5)}
    for i in range(100_000):
        hist[int(random_gen.next_float() *5)] += 1
    print(hist)
Task: Pseudo-random numbers_Xorshift star







Python: mask64 = (1 << 64) - 1
mask32 = (1 << 32) - 1
const = 0x2545F4914F6CDD1D



class Xorshift_star():
    
    def __init__(self, seed=0):
        self.state = seed & mask64

    def seed(self, num):
        self.state =  num & mask64
    
    def next_int(self):
        "return random int between 0 and 2**32"
        x = self.state
        x = (x ^ (x >> 12)) & mask64
        x = (x ^ (x << 25)) & mask64
        x = (x ^ (x >> 27)) & mask64
        self.state = x
        answer = (((x * const) & mask64) >> 32) & mask32 
        return answer
    
    def  next_float(self):
        "return random float between 0 and 1"
        return self.next_int() / (1 << 32)
    

if __name__ == '__main__':
    random_gen = Xorshift_star()
    random_gen.seed(1234567)
    for i in range(5):
        print(random_gen.next_int())
        
    random_gen.seed(987654321)
    hist = {i:0 for i in range(5)}
    for i in range(100_000):
        hist[int(random_gen.next_float() *5)] += 1
    print(hist)
Task: Changeable words







Python: from collections import defaultdict, Counter


def getwords(minlength=11, fname='unixdict.txt'):
    "Return set of lowercased words of > given number of characters"
    with open(fname) as f:
        words = f.read().strip().lower().split()
    return {w for w in words if len(w) > minlength}

words11 = getwords()
word_minus_1 = defaultdict(list)    
minus_1_to_word = defaultdict(list) 

for w in words11:
    for i in range(len(w)):
        minus_1 = w[:i] + w[i+1:]
        word_minus_1[minus_1].append((w, i))   
        if minus_1 in words11:
            minus_1_to_word[minus_1].append(w)
    
cwords = set()  
for _, v in word_minus_1.items():
    if len(v) >1:
        change_indices = Counter(i for wrd, i in v)
        change_words = set(wrd for wrd, i in v)
        words_changed = None
        if len(change_words) > 1 and change_indices.most_common(1)[0][1] > 1:
            words_changed = [wrd for wrd, i in v
                             if change_indices[i] > 1]
        if words_changed:
            cwords.add(tuple(sorted(words_changed)))

print(f"{len(minus_1_to_word)} words that are from deleting a char from other words:")
for k, v in sorted(minus_1_to_word.items()):
    print(f"  {k:12} From {', '.join(v)}")

print(f"\n{len(cwords)} words that are from changing a char from other words:")
for v in sorted(cwords):
    print(f"  {v[0]:12} From {', '.join(v[1:])}")
Task: Exactly three adjacent 3 in lists







Python: 

from itertools import dropwhile, takewhile



def nnPeers(n):
    
    def p(x):
        return n == x

    def go(xs):
        fromFirstMatch = list(dropwhile(
            lambda v: not p(v),
            xs
        ))
        ns = list(takewhile(p, fromFirstMatch))
        rest = fromFirstMatch[len(ns):]

        return p(len(ns)) and (
            not any(p(x) for x in rest)
        )

    return go




def main():
    
    print(
        '\n'.join([
            f'{xs} -> {nnPeers(3)(xs)}' for xs in [
                [9, 3, 3, 3, 2, 1, 7, 8, 5],
                [5, 2, 9, 3, 3, 7, 8, 4, 1],
                [1, 4, 3, 6, 7, 3, 8, 3, 2],
                [1, 2, 3, 4, 5, 6, 7, 8, 9],
                [4, 6, 8, 7, 2, 3, 3, 3, 1]
            ]
        ])
    )



if __name__ == '__main__':
    main()
Task: Input_Output for lines of text







Python: try: input = raw_input
except: pass

def do_stuff(words):
	print(words)

linecount = int(input())
for x in range(linecount):
	line = input()
	do_stuff(line)
Task: Length of an arc between two angles







Python: import math

def arc_length(r, angleA, angleB):
    return (360.0 - abs(angleB - angleA)) * math.pi * r / 180.0
Task: Joystick position







Python: import sys
import pygame

pygame.init()


clk = pygame.time.Clock()


if pygame.joystick.get_count() == 0:
    raise IOError("No joystick detected")
joy = pygame.joystick.Joystick(0)
joy.init()


size = width, height = 600, 600
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Joystick Tester")


frameRect = pygame.Rect((45, 45), (510, 510))


crosshair = pygame.surface.Surface((10, 10))
crosshair.fill(pygame.Color("magenta"))
pygame.draw.circle(crosshair, pygame.Color("blue"), (5,5), 5, 0)
crosshair.set_colorkey(pygame.Color("magenta"), pygame.RLEACCEL)
crosshair = crosshair.convert()


writer = pygame.font.Font(pygame.font.get_default_font(), 15)
buttons = {}
for b in range(joy.get_numbuttons()):
    buttons[b] = [
        writer.render(
            hex(b)[2:].upper(),
            1,
            pygame.Color("red"),
            pygame.Color("black")
        ).convert(),
        
        
        ((15*b)+45, 560)
    ]

while True:
    
    pygame.event.pump()
    for events in pygame.event.get():
        if events.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    
    screen.fill(pygame.Color("black"))

    
    x = joy.get_axis(0)
    y = joy.get_axis(1)

    
    
    screen.blit(crosshair, ((x*250)+300-5, (y*250)+300-5))
    pygame.draw.rect(screen, pygame.Color("red"), frameRect, 1)

    
    for b in range(joy.get_numbuttons()):
        if joy.get_button(b):
            screen.blit(buttons[b][0], buttons[b][1])

    
    pygame.display.flip()
    clk.tick(40)
Task: De Polignac numbers







Python: 

from sympy import isprime
from math import log
from numpy import ndarray

max_value = 1_000_000

all_primes = [i for i in range(max_value + 1) if isprime(i)]
powers_of_2 = [2**i for i in range(int(log(max_value, 2)))]

allvalues = ndarray(max_value, dtype=bool)
allvalues[:] = True

for i in all_primes:
    for j in powers_of_2:
        if i + j < max_value:
            allvalues[i + j] = False
        
dePolignac = [n for n in range(1, max_value) if n & 1 == 1 and allvalues[n]]

print('First fifty de Polignac numbers:')
for i, n in enumerate(dePolignac[:50]):
    print(f'{n:5}', end='\n' if (i + 1) % 10 == 0 else '')
    
print(f'\nOne thousandth: {dePolignac[999]:,}')
print(f'\nTen thousandth: {dePolignac[9999]:,}')
Task: Playing cards



C#: using System;
using System.Linq;
using System.Collections.Generic;

public struct Card
{
    public Card(string rank, string suit) : this()
    {
        Rank = rank;
        Suit = suit;
    }

    public string Rank { get; }
    public string Suit { get; }

    public override string ToString() => $"{Rank} of {Suit}";
}

public class Deck : IEnumerable<Card>
{
    static readonly string[] ranks = { "Two", "Three", "Four", "Five", "Six",
        "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" };
    static readonly string[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };
    readonly List<Card> cards;
 
    public Deck() {
        cards = (from suit in suits
                from rank in ranks
                select new Card(rank, suit)).ToList();
    }

    public int Count => cards.Count;

    public void Shuffle() {
        
        var random = new Random();
        for (int i = 0; i < cards.Count; i++) {
            int r = random.Next(i, cards.Count);
            var temp = cards[i];
            cards[i] = cards[r];
            cards[r] = temp;
        }
    }

    public Card Deal() {
        int last = cards.Count - 1;
        Card card = cards[last];
        
        
        cards.RemoveAt(last);
        return card;
    }

    public IEnumerator<Card> GetEnumerator() {
        
        
        for (int i = cards.Count - 1; i >= 0; i--)
            yield return cards[i];
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
}
Task: Find the last Sunday of each month



C#: using System;

namespace LastSundayOfEachMonth
{
    class Program
    {
        static void Main()
        {
            Console.Write("Year to calculate: ");

            string strYear = Console.ReadLine();
            int year = Convert.ToInt32(strYear);

            DateTime date;
            for (int i = 1; i <= 12; i++)
            {
                date = new DateTime(year, i, DateTime.DaysInMonth(year, i), System.Globalization.CultureInfo.CurrentCulture.Calendar);
                
                
                int daysOffset = date.DayOfWeek - dayOfWeek; 
                if (daysOffset < 0) daysOffset += 7; 
                date = date.AddDays(-daysOffset ); 
                Console.WriteLine(date.ToString("yyyy-MM-dd"));
            }
        }
    }
}
Task: Longest increasing subsequence



C#: using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public static class LIS
{
    public static IEnumerable<T> FindRec<T>(IList<T> values, IComparer<T> comparer = null) =>
        values == null ? throw new ArgumentNullException() :
            FindRecImpl(values, Sequence<T>.Empty, 0, comparer ?? Comparer<T>.Default).Reverse();

    private static Sequence<T> FindRecImpl<T>(IList<T> values, Sequence<T> current, int index, IComparer<T> comparer) {
        if (index == values.Count) return current;
        if (current.Length > 0 && comparer.Compare(values[index], current.Value) <= 0)
            return FindRecImpl(values, current, index + 1, comparer);
        return Max(
            FindRecImpl(values, current, index + 1, comparer),
            FindRecImpl(values, current + values[index], index + 1, comparer)
        );
    }

    private static Sequence<T> Max<T>(Sequence<T> a, Sequence<T> b) => a.Length < b.Length ? b : a;

    class Sequence<T> : IEnumerable<T>
    {
        public static readonly Sequence<T> Empty = new Sequence<T>(default(T), null);

        public Sequence(T value, Sequence<T> tail)
        {
            Value = value;
            Tail = tail;
            Length = tail == null ? 0 : tail.Length + 1;
        }

        public T Value { get; }
        public Sequence<T> Tail { get; }
        public int Length { get; }

        public static Sequence<T> operator +(Sequence<T> s, T value) => new Sequence<T>(value, s);

        public IEnumerator<T> GetEnumerator()
        {
            for (var s = this; s.Length > 0; s = s.Tail) yield return s.Value;
        }

        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    }
}
Task: Dynamic variable names



C#: using System;
using System.Dynamic;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        string varname = Console.ReadLine();
        
        dynamic expando = new ExpandoObject();
        var map = expando as IDictionary<string, object>;
        map.Add(varname, "Hello world!");
 
        Console.WriteLine(expando.foo);
    }
}
Task: Read a configuration file







Python: def readconf(fn):
    ret = {}
    with file(fn) as fp:
        for line in fp:
            
            line = line.strip()
            if not line or line.startswith('
            
            boolval = True
            
            if line.startswith(';'):
                
                line = line.lstrip(';')
                
                if len(line.split()) != 1: continue
                boolval = False
            
            bits = line.split(None, 1)
            if len(bits) == 1:
                
                k = bits[0]
                v = boolval
            else:
                
                k, v = bits
            ret[k.lower()] = v
    return ret


if __name__ == '__main__':
    import sys
    conf = readconf(sys.argv[1])
    for k, v in sorted(conf.items()):
        print k, '=', v
Task: Truncate a file







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: Topswops







Python: >>> from itertools import permutations
>>> def f1(p):
	i = 0
	while True:
		p0  = p[0]
		if p0 == 1: break
		p[:p0] = p[:p0][::-1]
		i  += 1
	return i

>>> def fannkuch(n):
	return max(f1(list(p)) for p in permutations(range(1, n+1)))

>>> for n in range(1, 11): print(n,fannkuch(n))

1 0
2 1
3 2
4 4
5 7
6 10
7 16
8 22
9 30
10 38
>>>
Task: Runtime evaluation







Python: >>> exec 
10
Task: Numeric error propagation





Java: public class Approx {
    private double value;
    private double error;
    
    public Approx(){this.value = this.error = 0;}
    
    public Approx(Approx b){
        this.value = b.value;
        this.error = b.error;
    }
    
    public Approx(double value, double error){
        this.value = value;
        this.error = error;
    }
    
    public Approx add(Approx b){
        value+= b.value;
        error = Math.sqrt(error * error + b.error * b.error);
        return this;
    }
    
    public Approx add(double b){
        value+= b;
        return this;
    }
    
    public Approx sub(Approx b){
        value-= b.value;
        error = Math.sqrt(error * error + b.error * b.error);
        return this;
    }
    
    public Approx sub(double b){
        value-= b;
        return this;
    }
    
    public Approx mult(Approx b){
        double oldVal = value;
        value*= b.value;
        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +
                                  (b.error*b.error) / (b.value*b.value));
        return this;
    }

    public Approx mult(double b){
        value*= b;
        error = Math.abs(b * error);
        return this;
    }
    
    public Approx div(Approx b){
        double oldVal = value;
        value/= b.value;
        error = Math.sqrt(value * value * (error*error) / (oldVal*oldVal) +
                                  (b.error*b.error) / (b.value*b.value));
        return this;
    }

    public Approx div(double b){
        value/= b;
        error = Math.abs(b * error);
        return this;
    }
    
    public Approx pow(double b){
        double oldVal = value;
        value = Math.pow(value, b);
        error = Math.abs(value * b * (error / oldVal));
        return this;
    }
    
    @Override
    public String toString(){return value+"±"+error;}
    
    public static void main(String[] args){
        Approx x1 = new Approx(100, 1.1);
        Approx y1 = new Approx(50, 1.2);
        Approx x2 = new Approx(200, 2.2);
        Approx y2 = new Approx(100, 2.3);
        
        x1.sub(x2).pow(2).add(y1.sub(y2).pow(2)).pow(0.5);
        
        System.out.println(x1);
    }
}
Task: Pseudo-random numbers_Xorshift star





Java: public class XorShiftStar {
    private static final long MAGIC = Long.parseUnsignedLong("2545F4914F6CDD1D", 16);
    private long state;

    public void seed(long num) {
        state = num;
    }

    public int nextInt() {
        long x;
        int answer;

        x = state;
        x = x ^ (x >>> 12);
        x = x ^ (x << 25);
        x = x ^ (x >>> 27);
        state = x;
        answer = (int) ((x * MAGIC) >> 32);

        return answer;
    }

    public float nextFloat() {
        return (float) Integer.toUnsignedLong(nextInt()) / (1L << 32);
    }

    public static void main(String[] args) {
        var rng = new XorShiftStar();
        rng.seed(1234567);
        System.out.println(Integer.toUnsignedString(rng.nextInt()));
        System.out.println(Integer.toUnsignedString(rng.nextInt()));
        System.out.println(Integer.toUnsignedString(rng.nextInt()));
        System.out.println(Integer.toUnsignedString(rng.nextInt()));
        System.out.println(Integer.toUnsignedString(rng.nextInt()));
        System.out.println();

        int[] counts = {0, 0, 0, 0, 0};
        rng.seed(987654321);
        for (int i = 0; i < 100_000; i++) {
            int j = (int) Math.floor(rng.nextFloat() * 5.0);
            counts[j]++;
        }
        for (int i = 0; i < counts.length; i++) {
            System.out.printf("%d: %d\n", i, counts[i]);
        }
    }
}
Task: Countdown







Python: best = 0
best_out = ""
target = 952
nbrs = [100, 75, 50, 25, 6, 3]
    
def sol(target, nbrs, out=""):
    global best, best_out
    if abs(target - best) > abs(target - nbrs[0]): 
        best = nbrs[0]
        best_out = out
    if target == nbrs[0]:
        print(out)
    elif len(nbrs) > 1:
        for i1 in range(0, len(nbrs)-1):
            for i2 in range(i1+1, len(nbrs)):
                remains = nbrs[:i1] + nbrs[i1+1:i2] + nbrs[i2+1:]
                a, b = nbrs[i1], nbrs[i2]
                if a > b: a, b = b, a
                res = b + a
                op = str(b) + " + " + str(a) + " = " + str(res) + " ; "
                sol(target, [res] + remains, out + op)
                if b != a:
                    res = b - a
                    op = str(b) + " - " + str(a) + " = " + str(res) + " ; "
                    sol(target, [res] + remains, out + op)
                if a != 1:
                    res = b * a
                    op = str(b) + " * " + str(a) + " = " + str(res) + " ; "
                    sol(target, [res] + remains, out + op)
                    if b % a == 0:
                        res = int(b / a)
                        op = str(b) + " / " + str(a) + " = " + str(res) + " ; "
                        sol(target, [res] + remains, out + op)

sol(target, nbrs)
if best != target: 
    print("Best solution " + str(best))
    print(best_out)
Task: Search in paragraph's text







Python: with open('Traceback.txt', 'r' ) as f:
    rawText = f.read()

paragraphs = rawText.split( "\n\n" )

for p in paragraphs:
    if "SystemError" in p:

        index = p.find( "Traceback (most recent call last):" )

        if -1 != index:
            print( p[index:] )
            print( "----------------" )