WeixiangYan/CodeTransOcean huggingface dataset:
Task: Long multiplication




Go: 








package main

import "fmt"


func d(b byte) byte {
    if b < '0' || b > '9' {
        panic("digit 0-9 expected")
    }
    return b - '0'
}


func add(x, y string) string {
    if len(y) > len(x) {
        x, y = y, x
    }
    b := make([]byte, len(x)+1)
    var c byte
    for i := 1; i <= len(x); i++ {
        if i <= len(y) {
            c += d(y[len(y)-i])
        }
        s := d(x[len(x)-i]) + c
        c = s / 10
        b[len(b)-i] = (s % 10) + '0'
    }
    if c == 0 {
        return string(b[1:])
    }
    b[0] = c + '0'
    return string(b)
}


func mulDigit(x string, y byte) string {
    if y == '0' {
        return "0"
    }
    y = d(y)
    b := make([]byte, len(x)+1)
    var c byte
    for i := 1; i <= len(x); i++ {
        s := d(x[len(x)-i])*y + c
        c = s / 10
        b[len(b)-i] = (s % 10) + '0'
    }
    if c == 0 {
        return string(b[1:])
    }
    b[0] = c + '0'
    return string(b)
}


func mul(x, y string) string {
    result := mulDigit(x, y[len(y)-1])
    for i, zeros := 2, ""; i <= len(y); i++ {
        zeros += "0"
        result = add(result, mulDigit(x, y[len(y)-i])+zeros)
    }
    return result
}


const n = "18446744073709551616"

func main() {
    fmt.Println(mul(n, n))
}



PHP: <?php
function longMult($a, $b)
{
  $as = (string) $a;
  $bs = (string) $b;
  for($pi = 0, $ai = strlen($as) - 1; $ai >= 0; $pi++, $ai--)
    {
      for($p = 0; $p < $pi; $p++)
        {
          $regi[$ai][] = 0;
        }
      for($bi = strlen($bs) - 1; $bi >= 0; $bi--)
        {
          $regi[$ai][] = $as[$ai] * $bs[$bi];
        }
    }
  return $regi;
}

function longAdd($arr)
{
  $outer = count($arr);
  $inner = count($arr[$outer-1]) + $outer;
  for($i = 0; $i <= $inner; $i++)
    {
      for($o = 0; $o < $outer; $o++)
        {
          $val  = isset($arr[$o][$i]) ? $arr[$o][$i] : 0;
          @$sum[$i] += $val;
        }
    }
  return $sum;
}

function carry($arr)
{
  for($i = 0; $i < count($arr); $i++)
    {
      $s = (string) $arr[$i];
      switch(strlen($s))
        {
          case 2:
            $arr[$i] = $s{1};
            @$arr[$i+1] += $s{0};
            break;
          case 3:
            $arr[$i] = $s{2};
            @$arr[$i+1] += $s{0}.$s{1};
            break;
        }
    }
  return ltrim(implode('',array_reverse($arr)),'0');
}

function lm($a,$b)
{
  return carry(longAdd(longMult($a,$b)));
}

if(lm('18446744073709551616','18446744073709551616') == '340282366920938463463374607431768211456')
  {
    echo 'pass!';
  }; // 2^64 * 2^64
Task: Bulls and cows




Go: package main

import (
    "bufio"
    "bytes"
    "fmt"
    "math/rand"
    "os"
    "strings"
    "time"
)

func main() {
    fmt.Println(`Cows and Bulls
Guess four digit number of unique digits in the range 1 to 9.
A correct digit but not in the correct place is a cow.
A correct digit in the correct place is a bull.`)
    
    pat := make([]byte, 4)
    rand.Seed(time.Now().Unix())
    r := rand.Perm(9)
    for i := range pat {
        pat[i] = '1' + byte(r[i])
    }

    
    valid := []byte("123456789")
guess:
    for in := bufio.NewReader(os.Stdin); ; {
        fmt.Print("Guess: ")
        guess, err := in.ReadString('\n')
        if err != nil {
            fmt.Println("\nSo, bye.")
            return
        }
        guess = strings.TrimSpace(guess)
        if len(guess) != 4 {
            
            fmt.Println("Please guess a four digit number.")
            continue
        }
        var cows, bulls int
        for ig, cg := range guess {
            if strings.IndexRune(guess[:ig], cg) >= 0 {
                
                fmt.Printf("Repeated digit: %c\n", cg)
                continue guess
            }
            switch bytes.IndexByte(pat, byte(cg)) {
            case -1:
                if bytes.IndexByte(valid, byte(cg)) == -1 {
                    
                    fmt.Printf("Invalid digit: %c\n", cg)
                    continue guess
                }
            default: 
                cows++
            case ig:
                bulls++
            }
        }
        fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls)
        if bulls == 4 {
            fmt.Println("You got it.")
            return
        }
    }
}



PHP: <?php
$size = 4;

$chosen = implode(array_rand(array_flip(range(1,9)), $size));

echo "I've chosen a number from $size unique digits from 1 to 9; you need
to input $size unique digits to guess my number\n";

for ($guesses = 1; ; $guesses++) {
    while (true) {
        echo "\nNext guess [$guesses]: ";
        $guess = rtrim(fgets(STDIN));
        if (!checkguess($guess))
            echo "$size digits, no repetition, no 0... retry\n";
        else
            break;
    }
    if ($guess == $chosen) {
        echo "You did it in $guesses attempts!\n";
        break;
    } else {
        $bulls = 0;
        $cows = 0;
        foreach (range(0, $size-1) as $i) {
            if ($guess[$i] == $chosen[$i])
                $bulls++;
            else if (strpos($chosen, $guess[$i]) !== FALSE)
                $cows++;
        }
        echo "$cows cows, $bulls bulls\n";
    }
}

function checkguess($g)
{
  global $size;
  return count(array_unique(str_split($g))) == $size &&
    preg_match("/^[1-9]{{$size}}$/", $g);
}
?>
Task: Sorting algorithms_Bubble sort




Go: package main

import "fmt"

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

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

func bubblesort(a []int) {
    for itemCount := len(a) - 1; ; itemCount-- {
        hasChanged := false
        for index := 0; index < itemCount; index++ {
            if a[index] > a[index+1] {
                a[index], a[index+1] = a[index+1], a[index]
                hasChanged = true
            }
        }
        if hasChanged == false {
            break
        }
    }
}



PHP: function bubbleSort(array $array){
    foreach($array as $i => &$val){
        foreach($array as $k => &$val2){
            if($k <= $i)
                continue;
            if($val > $val2) {
                list($val, $val2) = [$val2, $val];
                break;
            }
        }
    }
    return $array;
}
Task: File input_output




Go: package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    b, err := ioutil.ReadFile("input.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
    if err = ioutil.WriteFile("output.txt", b, 0666); err != nil {
        fmt.Println(err)
    }
}



PHP: <?php

if (!$in = fopen('input.txt', 'r')) {
    die('Could not open input file.');
}

if (!$out = fopen('output.txt', 'w')) {
    die('Could not open output file.');
}

while (!feof($in)) {
    $data = fread($in, 512);
    fwrite($out, $data);
}

fclose($out);
fclose($in);
?>
Task: Arithmetic_Integer




Go: package main

import "fmt"

func main() {
    var a, b int
    fmt.Print("enter two integers: ")
    fmt.Scanln(&a, &b)
    fmt.Printf("%d + %d = %d\n", a, b, a+b)
    fmt.Printf("%d - %d = %d\n", a, b, a-b)
    fmt.Printf("%d * %d = %d\n", a, b, a*b)
    fmt.Printf("%d / %d = %d\n", a, b, a/b)  
    fmt.Printf("%d %% %d = %d\n", a, b, a%b) 
    
}



PHP: <?php
$a = fgets(STDIN);
$b = fgets(STDIN);

echo
    "sum:                 ", $a + $b, "\n",
    "difference:          ", $a - $b, "\n",
    "product:             ", $a * $b, "\n",
    "truncating quotient: ", (int)($a / $b), "\n",
    "flooring quotient:   ", floor($a / $b), "\n",
    "remainder:           ", $a % $b, "\n",
    "power:               ", $a ** $b, "\n"; // PHP 5.6+ only
?>
Task: Matrix transposition




Go: package main

import (
    "fmt"

    "gonum.org/v1/gonum/mat"
)

func main() {
    m := mat.NewDense(2, 3, []float64{
        1, 2, 3,
        4, 5, 6,
    })
    fmt.Println(mat.Formatted(m))
    fmt.Println()
    fmt.Println(mat.Formatted(m.T()))
}



PHP: function transpose($m) {
  if (count($m) == 0) // special case: empty matrix
    return array();
  else if (count($m) == 1) // special case: row matrix
    return array_chunk($m[0], 1);

  array_unshift($m, NULL); // the original matrix is not modified because it was passed by value
  return call_user_func_array('array_map', $m);
}
Task: Man or boy test




Go: package main
import "fmt"

func a(k int, x1, x2, x3, x4, x5 func() int) int {
	var b func() int
	b = func() int {
		k--
		return a(k, b, x1, x2, x3, x4)
	}
	if k <= 0 {
		return x4() + x5()
	}
	return b()
}

func main() {
	x := func(i int) func() int { return func() int { return i } }
	fmt.Println(a(10, x(1), x(-1), x(-1), x(1), x(0)))
}



PHP: <?php
function A($k,$x1,$x2,$x3,$x4,$x5) {
    $b = function () use (&$b,&$k,$x1,$x2,$x3,$x4) {
        return A(--$k,$b,$x1,$x2,$x3,$x4);
    };
    return $k <= 0 ? $x4() + $x5() : $b();
}  

echo A(10, function () { return  1; },
           function () { return -1; },
           function () { return -1; },
           function () { return  1; }, 
           function () { return  0; }) . "\n";
?>
Task: Find limit of recursion




Go: package main

import (
	"flag"
	"fmt"
	"runtime/debug"
)

func main() {
	stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default")
	flag.Parse()
	if *stack > 0 {
		debug.SetMaxStack(*stack)
	}
	r(1)
}

func r(l int) {
	if l%1000 == 0 {
		fmt.Println(l)
	}
	r(l + 1)
}



PHP: <?php
function a() {
    static $i = 0;
    print ++$i . "\n";
    a();
}
a();
Task: Perfect numbers




Go: package main

import "fmt"

func computePerfect(n int64) bool {
    var sum int64
    for i := int64(1); i < n; i++ {
        if n%i == 0 {
            sum += i
        }
    }
    return sum == n
}



func isPerfect(n int64) bool {
    switch n {
    case 6, 28, 496, 8128, 33550336, 8589869056,
        137438691328, 2305843008139952128:
        return true
    }
    return false
}


func main() {
    for n := int64(1); ; n++ {
        if isPerfect(n) != computePerfect(n) {
            panic("bug")
        }
        if n%1e3 == 0 {
            fmt.Println("tested", n)
        }
    }
}



PHP: function is_perfect($number)
{
    $sum = 0;
    for($i = 1; $i < $number; $i++)
    {
        if($number % $i == 0)
            $sum += $i;
    }
    return $sum == $number;
}

echo "Perfect numbers from 1 to 33550337:" . PHP_EOL;
for($num = 1; $num < 33550337; $num++)
{
    if(is_perfect($num))
        echo $num . PHP_EOL;
}
Task: Sorting algorithms_Bead sort




Go: package main

import (
    "fmt"
    "sync"
)

var a = []int{170, 45, 75, 90, 802, 24, 2, 66}
var aMax = 1000

const bead = 'o'

func main() {
    fmt.Println("before:", a)
    beadSort()
    fmt.Println("after: ", a)
}

func beadSort() {
    
    all := make([]byte, aMax*len(a))
    
    
    abacus := make([][]byte, aMax)
    for pole, space := 0, all; pole < aMax; pole++ {
        abacus[pole] = space[:len(a)]
        space = space[len(a):]
    }
    
    var wg sync.WaitGroup
    
    
    
    wg.Add(len(a))
    for row, n := range a {
        go func(row, n int) {
            for pole := 0; pole < n; pole++ {
                abacus[pole][row] = bead
            }
            wg.Done()
        }(row, n)
    }
    wg.Wait()
    
    wg.Add(aMax)
    for _, pole := range abacus {
        go func(pole []byte) {
            
            top := 0
            for row, space := range pole {
                if space == bead {
                    
                    
                    
                    
                    
                    pole[row] = 0
                    pole[top] = bead
                    top++
                }
            }
            wg.Done()
        }(pole)
    }
    wg.Wait()
    
    for row := range a {
        x := 0
        for pole := 0; pole < aMax && abacus[pole][row] == bead; pole++ {
            x++
        }
        a[len(a)-1-row] = x
    }
}



PHP: <?php
function columns($arr) {
    if (count($arr) == 0)
        return array();
    else if (count($arr) == 1)
        return array_chunk($arr[0], 1);

    array_unshift($arr, NULL);

    $transpose = call_user_func_array('array_map', $arr);
    return array_map('array_filter', $transpose);
}

function beadsort($arr) {
    foreach ($arr as $e)
        $poles []= array_fill(0, $e, 1);
    return array_map('count', columns(columns($poles)));
}

print_r(beadsort(array(5,3,1,7,4,1,1)));
?>
Task: Arbitrary-precision integers (included)




Go: package main

import (
	"fmt"
	"math/big"
)

func main() {
	x := big.NewInt(2)
	x = x.Exp(big.NewInt(3), x, nil)
	x = x.Exp(big.NewInt(4), x, nil)
	x = x.Exp(big.NewInt(5), x, nil)
	str := x.String()
	fmt.Printf("5^(4^(3^2)) has %d digits: %s ... %s\n",
		len(str),
		str[:20],
		str[len(str)-20:],
	)
}



PHP: <?php
$y = bcpow('5', bcpow('4', bcpow('3', '2')));
printf("5**4**3**2 = %s...%s and has %d digits\n", substr($y,0,20), substr($y,-20), strlen($y));
?>
Task: Least common multiple




Go: package main

import (
    "fmt"
    "math/big"
)

var m, n, z big.Int

func init() {
    m.SetString("2562047788015215500854906332309589561", 10)
    n.SetString("6795454494268282920431565661684282819", 10)
}

func main() {
    fmt.Println(z.Mul(z.Div(&m, z.GCD(nil, nil, &m, &n)), &n))
}



PHP: echo lcm(12, 18) == 36;

function lcm($m, $n) {
    if ($m == 0 || $n == 0) return 0;
    $r = ($m * $n) / gcd($m, $n);
    return abs($r);
}

function gcd($a, $b) {
    while ($b != 0) {
        $t = $b;
        $b = $a % $b;
        $a = $t;
    }
    return $a;
}
Task: Loops_Break




Go: package main

import "fmt"
import "math/rand"
import "time"

func main() {
    rand.Seed(time.Now().UnixNano())
    for {
        a := rand.Intn(20)
        fmt.Println(a)
        if a == 10 {
            break
        }
        b := rand.Intn(20)
        fmt.Println(b)
    }
}



PHP: while (true) {
    $a = rand(0,19);
    echo "$a\n";
    if ($a == 10)
        break;
    $b = rand(0,19);
    echo "$b\n";
}
Task: Hello world_Line printer




Go: package main

import (
	"fmt"
	"os"
)

func main() {
	lp0, err := os.Create("/dev/lp0")

	if err != nil {
		panic(err)
	}

	defer lp0.Close()

	fmt.Fprintln(lp0, "Hello World!")
}



PHP: <?php
file_put_contents('/dev/lp0', 'Hello world!');
?>
Task: Trabb Pardo–Knuth algorithm




Go: package main

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

func main() {
    
    fmt.Print("Enter 11 numbers: ")
    
    var s [11]float64
    for i := 0; i < 11; {
        if n, _ := fmt.Scan(&s[i]); n > 0 {
            i++
        }
    }
    
    for i, item := range s[:5] {
        s[i], s[10-i] = s[10-i], item
    }
    
    for _, item := range s {
        if result, overflow := f(item); overflow {
            
            log.Printf("f(%g) overflow", item)
        } else {
            
            fmt.Printf("f(%g) = %g\n", item, result)
        }
    }
}

func f(x float64) (float64, bool) {
    result := math.Sqrt(math.Abs(x)) + 5*x*x*x
    return result, result > 400
}



PHP: <?php



function f($n)
{
    return sqrt(abs($n)) + 5 * $n * $n * $n;
}

$sArray = [];
echo "Enter 11 numbers.\n";
for ($i = 0; $i <= 10; $i++) {
    echo $i + 1, " - Enter number: "; 
    array_push($sArray, (float)fgets(STDIN)); 
}
echo PHP_EOL;

$sArray = array_reverse($sArray);

foreach ($sArray as $s) {
    $r = f($s);
    echo "f(", $s, ") = ";
    if ($r > 400) 
        echo "overflow\n";
    else
        echo $r, PHP_EOL;
}
?>
Task: Middle three digits




Go: package m3

import (
    "errors"
    "strconv"
)

var (
    ErrorLT3  = errors.New("N of at least three digits required.")
    ErrorEven = errors.New("N with odd number of digits required.")
)

func Digits(i int) (string, error) {
    if i < 0 {
        i = -i
    }
    if i < 100 {
        return "", ErrorLT3
    }
    s := strconv.Itoa(i)
    if len(s)%2 == 0 {
        return "", ErrorEven
    }
    m := len(s) / 2
    return s[m-1 : m+2], nil
}



PHP: 


function middlethree($integer)
{
	$int 	= (int)str_replace('-','',$integer);
	$length = strlen($int);

	if(is_int($int))
	{
		if($length >= 3)
		{
			if($length % 2 == 1)
			{
				$middle = floor($length / 2) - 1;
				return substr($int,$middle, 3);
			}
			else
			{
				return 'The value must contain an odd amount of digits...';	
			}
		}
		else
		{
			return 'The value must contain at least three digits...';	
		}
	}
	else
	{
		return 'The value does not appear to be an integer...';
	}
}

$numbers = array(123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0);

foreach($numbers as $nums)
{
	echo $nums.' : '.middlethree($nums). '<br>';
}
Task: Odd word problem




Go: package main

import (
    "bytes"
    "fmt"
    "io"
    "os"
    "unicode"
)

func main() {
    owp(os.Stdout, bytes.NewBufferString("what,is,the;meaning,of:life."))
    fmt.Println()
    owp(os.Stdout, bytes.NewBufferString("we,are;not,in,kansas;any,more."))
    fmt.Println()
}

func owp(dst io.Writer, src io.Reader) {
    byte_in := func () byte {
        bs := make([]byte, 1)
        src.Read(bs)
        return bs[0]
    }
    byte_out := func (b byte) { dst.Write([]byte{b}) }    
    var odd func() byte
    odd = func() byte {
        s := byte_in()
        if unicode.IsPunct(rune(s)) {
            return s
        }
        b := odd()
        byte_out(s)
        return b
    }
    for {
        for {
            b := byte_in()
            byte_out(b)
            if b == '.' {
                return
            }
            if unicode.IsPunct(rune(b)) {
                break
            }
        }
        b := odd()
        byte_out(b)
        if b == '.' {
            return
        }
    }
}



PHP: $odd = function ($prev) use ( &$odd ) {
	$a = fgetc(STDIN);
	if (!ctype_alpha($a)) {
		$prev();
		fwrite(STDOUT, $a);
		return $a != '.';
	}
	$clos = function () use ($a , $prev) {
		fwrite(STDOUT, $a);
		$prev();
	};
	return $odd($clos);
};
$even = function () {
	while (true) {
		$c = fgetc(STDIN);
		fwrite(STDOUT, $c);
		if (!ctype_alpha($c)) {
			return $c != ".";
		}
	}
};
$prev = function(){};
$e = false;
while ($e ? $odd($prev) : $even()) {
	$e = !$e;
}
Task: Table creation_Postal addresses




Go: package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/mattn/go-sqlite3"
)

func main() {
    
    db, err := sql.Open("sqlite3", "rc.db")
    if err != nil {
        log.Print(err)
        return
    }
    defer db.Close()
    
    _, err = db.Exec(`create table addr (
        id     int unique,
        street text,
        city   text,
        state  text,
        zip    text
    )`)
    if err != nil {
        log.Print(err)
        return
    }
    
    rows, err := db.Query(`pragma table_info(addr)`)
    if err != nil {
        log.Print(err)
        return
    }
    var field, storage string
    var ignore sql.RawBytes
    for rows.Next() {
        err = rows.Scan(&ignore, &field, &storage, &ignore, &ignore, &ignore)
        if err != nil {
            log.Print(err)
            return
        }
        fmt.Println(field, storage)
    }
}



PHP: <?php
$db = new SQLite3(':memory:');
$db->exec("
    CREATE TABLE address (
        addrID     INTEGER PRIMARY KEY AUTOINCREMENT,
        addrStreet TEXT NOT NULL,
        addrCity   TEXT NOT NULL,
        addrState  TEXT NOT NULL,
        addrZIP    TEXT NOT NULL
    )
");
?>
Task: Include a file




Go: 
package main

import "fmt"

func hello() {
    fmt.Println("Hello from main.go")
}

func main() {
    hello()
    hello2()
}



PHP: include("file.php")
Task: Soundex




Go: package main

import (
    "errors"
    "fmt"
    "unicode"
)

var code = []byte("01230127022455012623017202")

func soundex(s string) (string, error) {
    var sx [4]byte
    var sxi int
    var cx, lastCode byte
    for i, c := range s {
        switch {
        case !unicode.IsLetter(c):
            if c < ' ' || c == 127 {
                return "", errors.New("ASCII control characters disallowed")
            }
            if i == 0 {
                return "", errors.New("initial character must be a letter")
            }
            lastCode = '0'
            continue
        case c >= 'A' && c <= 'Z':
            cx = byte(c - 'A')
        case c >= 'a' && c <= 'z':
            cx = byte(c - 'a')
        default:
            return "", errors.New("non-ASCII letters unsupported")
        }
        
        if i == 0 {
            sx[0] = cx + 'A'
            sxi = 1
            continue
        }
        switch x := code[cx]; x {
        case '7', lastCode:
        case '0':
            lastCode = '0'
        default:
            sx[sxi] = x
            if sxi == 3 {
                return string(sx[:]), nil
            }
            sxi++
            lastCode = x
        }
    }
    if sxi == 0 {
        return "", errors.New("no letters present")
    }
    for ; sxi < 4; sxi++ {
        sx[sxi] = '0'
    }
    return string(sx[:]), nil
}

func main() {
    for _, s := range []string{
        "Robert",   
        "Rupert",   
        "Rubin",    
        "ashcroft", 
        "ashcraft", 
        "moses",    
        "O'Mally",  
        "d jay",    
        "R2-D2",    
        "12p2",     
        "naïve",    
        "",         
        "bump\t",   
    } {
        if x, err := soundex(s); err == nil {
            fmt.Println("soundex", s, "=", x)
        } else {
            fmt.Printf("\"%s\" fail. %s\n", s, err)
        }
    }
}



PHP: <?php
echo soundex("Soundex"), "\n"; // S532
echo soundex("Example"), "\n"; // E251
echo soundex("Sownteks"), "\n"; // S532
echo soundex("Ekzampul"), "\n"; // E251
?>
Task: Bitmap_Histogram




Go: package raster

import "math"

func (g *Grmap) Histogram(bins int) []int {
    if bins <= 0 {
        bins = g.cols
    }
    h := make([]int, bins)
    for _, p := range g.px {
        h[int(p)*(bins-1)/math.MaxUint16]++
    }
    return h
}

func (g *Grmap) Threshold(t uint16) {
    for i, p := range g.px {
        if p < t {
            g.px[i] = 0
        } else {
            g.px[i] = math.MaxUint16
        }
    }
}



PHP: define('src_name', 'input.jpg');	// source image
define('dest_name', 'output.jpg');	// destination image

$img = imagecreatefromjpeg(src_name);	// read image

if(empty($img)){
	echo 'Image could not be loaded!'; 
	exit; 
}

$black = imagecolorallocate($img, 0, 0, 0);
$white = imagecolorallocate($img, 255, 255, 255);
$width = imagesx($img);
$height = imagesy($img);

$array_lum = array(); 	// for storage of luminosity of each pixel
$sum_lum = 0;		// total sum of luminosity
$average_lum = 0;	// average luminosity of whole image

for($x = 0; $x < $width; $x++){	
	for($y = 0; $y < $height; $y++){

		$color = imagecolorat($img, $x, $y);
		$r = ($color >> 16) & 0xFF;
		$g = ($color >> 8) & 0xFF;
		$b = $color & 0xFF;

		$array_lum[$x][$y] = ($r + $g + $b);

		$sum_lum += $array_lum[$x][$y];
	}
}

$average_lum = $sum_lum / ($width * $height);

for($x = 0; $x < $width; $x++){	
	for($y = 0; $y < $height; $y++){


		if($array_lum[$x][$y] > $average_lum){
			imagesetpixel($img, $x, $y, $white);
		}
		else{
			imagesetpixel($img, $x, $y, $black);
		}
	}
}

imagejpeg($img, dest_name);

if(!file_exists(dest_name)){
	echo 'Image not saved! Check permission!';
}
Task: Literals_String




Go: ch := 'z'
ch = 122          
ch = '\x7a'       
ch = '\u007a'     
ch = '\U0000007a' 
ch = '\172'       



PHP: 'c';                      # character
'hello';                  # these two strings are the same
"hello";
'Hi $name. How are you?'; # result: "Hi $name. How are you?"
"Hi $name. How are you?"; # result: "Hi Bob. How are you?"
'\n';                     # 2-character string with a backslash and "n"
"\n";                     # newline character
`ls`;                     # runs a command in the shell and returns the output as a string
<<END                     # Here-Document
Hi, whatever goes here gets put into the string,
including newlines and $variables,
until the label we put above
END;
<<'END'                   # Here-Document like single-quoted
Same as above, but no interpolation of $variables.
END;
Task: Enumerations




Go: const (
	apple = iota
	banana
	cherry
)



PHP: 
$fruits = array( "apple", "banana", "cherry" );
$fruits = array( "apple" => 0, "banana" => 1, "cherry" => 2 );

class Fruit {
  const APPLE = 0;
  const BANANA = 1;
  const CHERRY = 2;
}

$value = Fruit::APPLE;

define("FRUIT_APPLE", 0);
define("FRUIT_BANANA", 1);
define("FRUIT_CHERRY", 2);