Task: Checksumcolor




Go: package main

import (
    "bufio"
    "fmt"
    "golang.org/x/crypto/ssh/terminal"
    "log"
    "os"
    "regexp"
    "strconv"
)

type Color struct{ r, g, b int }

type ColorEx struct {
    color Color
    code  string
}

var colors = []ColorEx{
    {Color{15, 0, 0}, "31"},
    {Color{0, 15, 0}, "32"},
    {Color{15, 15, 0}, "33"},
    {Color{0, 0, 15}, "34"},
    {Color{15, 0, 15}, "35"},
    {Color{0, 15, 15}, "36"},
}

func squareDist(c1, c2 Color) int {
    xd := c2.r - c1.r
    yd := c2.g - c1.g
    zd := c2.b - c1.b
    return xd*xd + yd*yd + zd*zd
}

func printColor(s string) {
    n := len(s)
    k := 0
    for i := 0; i < n/3; i++ {
        j := i * 3
        c1 := s[j]
        c2 := s[j+1]
        c3 := s[j+2]
        k = j + 3
        r, err := strconv.ParseInt(fmt.Sprintf("0x%c", c1), 0, 64)
        check(err)
        g, err := strconv.ParseInt(fmt.Sprintf("0x%c", c2), 0, 64)
        check(err)
        b, err := strconv.ParseInt(fmt.Sprintf("0x%c", c3), 0, 64)
        check(err)
        rgb := Color{int(r), int(g), int(b)}
        m := 676
        colorCode := ""
        for _, cex := range colors {
            sqd := squareDist(cex.color, rgb)
            if sqd < m {
                colorCode = cex.code
                m = sqd
            }
        }
        fmt.Printf("\033[%s;1m%c%c%c\033[00m", colorCode, c1, c2, c3)
    }
    for j := k; j < n; j++ {
        c := s[j]
        fmt.Printf("\033[0;1m%c\033[00m", c)
    }
}

var (
    r       = regexp.MustCompile("^([A-Fa-f0-9]+)([ \t]+.+)$")
    scanner = bufio.NewScanner(os.Stdin)
    err     error
)

func colorChecksum() {
    for scanner.Scan() {
        line := scanner.Text()
        if r.MatchString(line) {
            submatches := r.FindStringSubmatch(line)
            s1 := submatches[1]
            s2 := submatches[2]
            printColor(s1)
            fmt.Println(s2)
        } else {
            fmt.Println(line)
        }
    }
    check(scanner.Err())
}

func cat() {
    for scanner.Scan() {
        line := scanner.Text()
        fmt.Println(line)
    }
    check(scanner.Err())
}

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

func main() {
    if terminal.IsTerminal(int(os.Stdout.Fd())) {
        colorChecksum()
    } else {
        cat()
    }
}




Python: 


from __future__ import unicode_literals

import argparse
import fileinput
import os
import sys

from functools import partial
from itertools import count
from itertools import takewhile


ANSI_RESET = "\u001b[0m"

RED = (255, 0, 0)
GREEN = (0, 255, 0)
YELLOW = (255, 255, 0)
BLUE = (0, 0, 255)
MAGENTA = (255, 0, 255)
CYAN = (0, 255, 255)

ANSI_PALETTE = {
    RED: "\u001b[31m",
    GREEN: "\u001b[32m",
    YELLOW: "\u001b[33m",
    BLUE: "\u001b[34m",
    MAGENTA: "\u001b[35m",
    CYAN: "\u001b[36m",
}



_8BIT_PALETTE = {
    (0xAF, 0x00, 0x00): "\u001b[38;5;124m",
    (0xAF, 0x00, 0x5F): "\u001b[38;5;125m",
    (0xAF, 0x00, 0x87): "\u001b[38;5;126m",
    (0xAF, 0x00, 0xAF): "\u001b[38;5;127m",
    (0xAF, 0x00, 0xD7): "\u001b[38;5;128m",
    (0xAF, 0x00, 0xFF): "\u001b[38;5;129m",
    (0xAF, 0x5F, 0x00): "\u001b[38;5;130m",
    (0xAF, 0x5F, 0x5F): "\u001b[38;5;131m",
    (0xAF, 0x5F, 0x87): "\u001b[38;5;132m",
    (0xAF, 0x5F, 0xAF): "\u001b[38;5;133m",
    (0xAF, 0x5F, 0xD7): "\u001b[38;5;134m",
    (0xAF, 0x5F, 0xFF): "\u001b[38;5;135m",
    (0xAF, 0x87, 0x00): "\u001b[38;5;136m",
    (0xAF, 0x87, 0x5F): "\u001b[38;5;137m",
    (0xAF, 0x87, 0x87): "\u001b[38;5;138m",
    (0xAF, 0x87, 0xAF): "\u001b[38;5;139m",
    (0xAF, 0x87, 0xD7): "\u001b[38;5;140m",
    (0xAF, 0x87, 0xFF): "\u001b[38;5;141m",
    (0xAF, 0xAF, 0x00): "\u001b[38;5;142m",
    (0xAF, 0xAF, 0x5F): "\u001b[38;5;143m",
    (0xAF, 0xAF, 0x87): "\u001b[38;5;144m",
    (0xAF, 0xAF, 0xAF): "\u001b[38;5;145m",
    (0xAF, 0xAF, 0xD7): "\u001b[38;5;146m",
    (0xAF, 0xAF, 0xFF): "\u001b[38;5;147m",
    (0xAF, 0xD7, 0x00): "\u001b[38;5;148m",
    (0xAF, 0xD7, 0x5F): "\u001b[38;5;149m",
    (0xAF, 0xD7, 0x87): "\u001b[38;5;150m",
    (0xAF, 0xD7, 0xAF): "\u001b[38;5;151m",
    (0xAF, 0xD7, 0xD7): "\u001b[38;5;152m",
    (0xAF, 0xD7, 0xFF): "\u001b[38;5;153m",
    (0xAF, 0xFF, 0x00): "\u001b[38;5;154m",
    (0xAF, 0xFF, 0x5F): "\u001b[38;5;155m",
    (0xAF, 0xFF, 0x87): "\u001b[38;5;156m",
    (0xAF, 0xFF, 0xAF): "\u001b[38;5;157m",
    (0xAF, 0xFF, 0xD7): "\u001b[38;5;158m",
    (0xAF, 0xFF, 0xFF): "\u001b[38;5;159m",
}


def error(msg):
    
    sys.stderr.write(msg)
    sys.stderr.write(os.linesep)
    sys.exit(1)


def rgb(group):
    
    nibbles_per_channel = len(group) // 3
    max_val = 16 ** nibbles_per_channel - 1
    nibbles = chunked(group, nibbles_per_channel)

    
    return tuple((int(n, 16) * 255) // max_val for n in nibbles)


def distance(color, other):
    
    return sum((o - s) ** 2 for s, o in zip(color, other))


def chunked(seq, n):
    
    return takewhile(len, (seq[i : i + n] for i in count(0, n)))


def escape(group, palette):
    
    key = partial(distance, other=rgb(group.ljust(3, "0")))
    ansi_color = min(palette, key=key)
    return "".join([palette[ansi_color], group, ANSI_RESET])


def colorize(line, group_size=3, palette=ANSI_PALETTE):
    
    checksum, filename = line.split(None, 1)
    escaped = [escape(group, palette) for group in chunked(checksum, group_size)]
    sys.stdout.write("  ".join(["".join(escaped), filename]))


def html_colorize(checksum, group_size=3, palette=ANSI_PALETTE):
    

    def span(group):
        key = partial(distance, other=rgb(group.ljust(3, "0")))
        ansi_color = min(palette, key=key)
        int_val = int.from_bytes(ansi_color, byteorder="big")
        hex_val = hex(int_val)[2:].rjust(6, "0")
        return '<span style="color:

    checksum, filename = line.split(None, 1)
    escaped = [span(group) for group in chunked(checksum, group_size)]
    sys.stdout.write("  ".join(["".join(escaped), filename]))


if __name__ == "__main__":
    
    parser = argparse.ArgumentParser(description="Color checksum.")

    parser.add_argument(
        "-n",
        type=int,
        default=3,
        help="Color the checksum in groups of size N. Defaults to 3.",
    )

    parser.add_argument(
        "-e",
        "--extended-palette",
        action="store_true",
        help="Use the extended 8-bit palette. Defaults to False.",
    )

    parser.add_argument(
        "--html",
        action="store_true",
        help="Output checksum groups wrapped with 'span' tags instead of ANSI escape sequences.",
    )

    parser.add_argument("files", nargs="*", default="-", metavar="FILE")

    args = parser.parse_args()

    if sys.stdout.isatty():

        palette = ANSI_PALETTE
        if args.extended_palette:
            palette = _8BIT_PALETTE

        colorize_func = colorize
        if args.html:
            colorize_func = html_colorize

        for line in fileinput.input(files=args.files):
            colorize_func(line, group_size=args.n, palette=palette)
    else:
        
        for line in fileinput.input(files=args.files):
            sys.stdout.write(line)