WeixiangYan/CodeTransOcean huggingface dataset:
Task: Element-wise operations







Python: >>> import random
>>> from operator import add, sub, mul, floordiv
>>> from pprint import pprint as pp
>>> 
>>> def ewise(matrix1, matrix2, op):
	return [[op(e1,e2) for e1,e2 in zip(row1, row2)] for row1,row2 in zip(matrix1, matrix2)]

>>> m,n = 3,4 	
>>> a0 = [[random.randint(1,9) for y in range(n)] for x in range(m)]
>>> a1 = [[random.randint(1,9) for y in range(n)] for x in range(m)]
>>> pp(a0); pp(a1)
[[7, 8, 7, 4], [4, 9, 4, 1], [2, 3, 6, 4]]
[[4, 5, 1, 6], [6, 8, 3, 4], [2, 2, 6, 3]]
>>> pp(ewise(a0, a1, add))
[[11, 13, 8, 10], [10, 17, 7, 5], [4, 5, 12, 7]]
>>> pp(ewise(a0, a1, sub))
[[3, 3, 6, -2], [-2, 1, 1, -3], [0, 1, 0, 1]]
>>> pp(ewise(a0, a1, mul))
[[28, 40, 7, 24], [24, 72, 12, 4], [4, 6, 36, 12]]
>>> pp(ewise(a0, a1, floordiv))
[[1, 1, 7, 0], [0, 1, 1, 0], [1, 1, 1, 1]]
>>> pp(ewise(a0, a1, pow))
[[2401, 32768, 7, 4096], [4096, 43046721, 64, 1], [4, 9, 46656, 64]]
>>> pp(ewise(a0, a1, lambda x, y:2*x - y))
[[10, 11, 13, 2], [2, 10, 5, -2], [2, 4, 6, 5]]
>>> 
>>> def s_ewise(scalar1, matrix1, op):
	return [[op(scalar1, e1) for e1 in row1] for row1 in matrix1]

>>> scalar = 10
>>> a0
[[7, 8, 7, 4], [4, 9, 4, 1], [2, 3, 6, 4]]
>>> for op in ( add, sub, mul, floordiv, pow, lambda x, y:2*x - y ):
	print("%10s :" % op.__name__, s_ewise(scalar, a0, op))

	
       add : [[17, 18, 17, 14], [14, 19, 14, 11], [12, 13, 16, 14]]
       sub : [[3, 2, 3, 6], [6, 1, 6, 9], [8, 7, 4, 6]]
       mul : [[70, 80, 70, 40], [40, 90, 40, 10], [20, 30, 60, 40]]
  floordiv : [[1, 1, 1, 2], [2, 1, 2, 10], [5, 3, 1, 2]]
       pow : [[10000000, 100000000, 10000000, 10000], [10000, 1000000000, 10000, 10], [100, 1000, 1000000, 10000]]
  <lambda> : [[13, 12, 13, 16], [16, 11, 16, 19], [18, 17, 14, 16]]
>>>




Fortran: program element_operations
  implicit none

  real(kind=4), dimension(3,3) :: a,b
  integer :: i

  a=reshape([(i,i=1,9)],shape(a))

  print*,'addition'
  b=a+a
  call print_arr(b)

  print*,'multiplication'
  b=a*a
  call print_arr(b)

  print*,'division'
  b=a/b
  call print_arr(b)

  print*,'exponentiation'
  b=a**a
  call print_arr(b)

  print*,'trignometric'
  b=cos(a)
  call print_arr(b)

  print*,'mod'
  b=mod(int(a),3)
  call print_arr(b)

  print*,'element selection'
  b=0
  where(a>3) b=1
  call print_arr(b)  

  print*,'elemental functions can be applied to single values:'
  print*,square(3.0)
  print*,'or element wise to arrays:'
  b=square(a)
  call print_arr(b)


contains

  elemental real function square(a)
    real, intent(in) :: a
    square=a*a
  end function square

  subroutine print_arr(arr)
    real, intent(in) :: arr(:,:)
    integer :: i
    do i=1,size(arr,dim=2)
       print*,arr(:,i)
    end do
  end subroutine print_arr
  
  
end program element_operations
Task: Terminal control_Cursor positioning



C#: static void Main(string[] args)
{
    Console.SetCursorPosition(3, 6);
    Console.Write("Hello");
}









Ada: with Ada.Text_IO;

procedure Cursor_Pos is

begin
   Ada.Text_IO.Set_Line(6);
   Ada.Text_IO.Set_Col(3);
   Ada.Text_IO.Put("Hello");
end Cursor_Pos;
Task: Terminal control_Cursor positioning

C: #include <stdio.h>
int main()
{
	printf("\033[6;3HHello\n");
	return 0;
}











Ada: with Ada.Text_IO;

procedure Cursor_Pos is

begin
   Ada.Text_IO.Set_Line(6);
   Ada.Text_IO.Set_Col(3);
   Ada.Text_IO.Put("Hello");
end Cursor_Pos;
Task: Terminal control_Cursor positioning




Go: package main

import (
    "bytes"
    "fmt"
    "os"
    "os/exec"
)

func main() {
    cmd := exec.Command("tput", "-S")
    cmd.Stdin = bytes.NewBufferString("clear\ncup 5 2")
    cmd.Stdout = os.Stdout
    cmd.Run()
    fmt.Println("Hello")
}








Ada: with Ada.Text_IO;

procedure Cursor_Pos is

begin
   Ada.Text_IO.Set_Line(6);
   Ada.Text_IO.Set_Col(3);
   Ada.Text_IO.Put("Hello");
end Cursor_Pos;
Task: Terminal control_Cursor positioning







Python: print("\033[6;3HHello")





Ada: with Ada.Text_IO;

procedure Cursor_Pos is

begin
   Ada.Text_IO.Set_Line(6);
   Ada.Text_IO.Set_Col(3);
   Ada.Text_IO.Put("Hello");
end Cursor_Pos;
Task: Terminal control_Cursor positioning

C: #include <stdio.h>
int main()
{
	printf("\033[6;3HHello\n");
	return 0;
}
Task: Terminal control_Cursor positioning



C#: static void Main(string[] args)
{
    Console.SetCursorPosition(3, 6);
    Console.Write("Hello");
}
Task: Terminal control_Cursor positioning




Go: package main

import (
    "bytes"
    "fmt"
    "os"
    "os/exec"
)

func main() {
    cmd := exec.Command("tput", "-S")
    cmd.Stdin = bytes.NewBufferString("clear\ncup 5 2")
    cmd.Stdout = os.Stdout
    cmd.Run()
    fmt.Println("Hello")
}
Task: Terminal control_Cursor positioning







Python: print("\033[6;3HHello")
Task: Terminal control_Cursor positioning



C#: static void Main(string[] args)
{
    Console.SetCursorPosition(3, 6);
    Console.Write("Hello");
}








Fortran: program textposition
    use kernel32
    implicit none
    integer(HANDLE) :: hConsole
    integer(BOOL) :: q
    
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE)
    q = SetConsoleCursorPosition(hConsole, T_COORD(3, 6))
    q = WriteConsole(hConsole, loc("Hello"), 5, NULL, NULL)
end program
Task: Terminal control_Cursor positioning

C: #include <stdio.h>
int main()
{
	printf("\033[6;3HHello\n");
	return 0;
}










Fortran: program textposition
    use kernel32
    implicit none
    integer(HANDLE) :: hConsole
    integer(BOOL) :: q
    
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE)
    q = SetConsoleCursorPosition(hConsole, T_COORD(3, 6))
    q = WriteConsole(hConsole, loc("Hello"), 5, NULL, NULL)
end program
Task: Terminal control_Cursor positioning







Python: print("\033[6;3HHello")




Fortran: program textposition
    use kernel32
    implicit none
    integer(HANDLE) :: hConsole
    integer(BOOL) :: q
    
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE)
    q = SetConsoleCursorPosition(hConsole, T_COORD(3, 6))
    q = WriteConsole(hConsole, loc("Hello"), 5, NULL, NULL)
end program
Task: Terminal control_Cursor positioning






PHP: echo "\033[".$x.",".$y."H"; // Position line $y and column $x.
echo "\033[".$n."A"; // Up $n lines.
echo "\033[".$n."B"; // Down $n lines.
echo "\033[".$n."C"; // Forward $n columns.
echo "\033[".$n."D"; // Backward $n columns.
echo "\033[2J"; // Clear the screen, move to (0,0).





Fortran: program textposition
    use kernel32
    implicit none
    integer(HANDLE) :: hConsole
    integer(BOOL) :: q
    
    hConsole = GetStdHandle(STD_OUTPUT_HANDLE)
    q = SetConsoleCursorPosition(hConsole, T_COORD(3, 6))
    q = WriteConsole(hConsole, loc("Hello"), 5, NULL, NULL)
end program
Task: Terminal control_Cursor positioning

C: #include <stdio.h>
int main()
{
	printf("\033[6;3HHello\n");
	return 0;
}









COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. cursor-positioning.

       PROCEDURE DIVISION.
           DISPLAY "Hello" AT LINE 6, COL 3

           GOBACK
           .
Task: Terminal control_Cursor positioning



C#: static void Main(string[] args)
{
    Console.SetCursorPosition(3, 6);
    Console.Write("Hello");
}







COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. cursor-positioning.

       PROCEDURE DIVISION.
           DISPLAY "Hello" AT LINE 6, COL 3

           GOBACK
           .
Task: Terminal control_Cursor positioning







Python: print("\033[6;3HHello")



COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. cursor-positioning.

       PROCEDURE DIVISION.
           DISPLAY "Hello" AT LINE 6, COL 3

           GOBACK
           .
Task: Terminal control_Cursor positioning




Go: package main

import (
    "bytes"
    "fmt"
    "os"
    "os/exec"
)

func main() {
    cmd := exec.Command("tput", "-S")
    cmd.Stdin = bytes.NewBufferString("clear\ncup 5 2")
    cmd.Stdout = os.Stdout
    cmd.Run()
    fmt.Println("Hello")
}






COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. cursor-positioning.

       PROCEDURE DIVISION.
           DISPLAY "Hello" AT LINE 6, COL 3

           GOBACK
           .
Task: Terminal control_Cursor positioning






PHP: echo "\033[".$x.",".$y."H"; // Position line $y and column $x.
echo "\033[".$n."A"; // Up $n lines.
echo "\033[".$n."B"; // Down $n lines.
echo "\033[".$n."C"; // Forward $n columns.
echo "\033[".$n."D"; // Backward $n columns.
echo "\033[2J"; // Clear the screen, move to (0,0).






Ada: with Ada.Text_IO;

procedure Cursor_Pos is

begin
   Ada.Text_IO.Set_Line(6);
   Ada.Text_IO.Set_Col(3);
   Ada.Text_IO.Put("Hello");
end Cursor_Pos;
Task: Terminal control_Cursor positioning






PHP: echo "\033[".$x.",".$y."H"; // Position line $y and column $x.
echo "\033[".$n."A"; // Up $n lines.
echo "\033[".$n."B"; // Down $n lines.
echo "\033[".$n."C"; // Forward $n columns.
echo "\033[".$n."D"; // Backward $n columns.
echo "\033[2J"; // Clear the screen, move to (0,0).
Task: Terminal control_Cursor positioning






PHP: echo "\033[".$x.",".$y."H"; // Position line $y and column $x.
echo "\033[".$n."A"; // Up $n lines.
echo "\033[".$n."B"; // Down $n lines.
echo "\033[".$n."C"; // Forward $n columns.
echo "\033[".$n."D"; // Backward $n columns.
echo "\033[2J"; // Clear the screen, move to (0,0).




COBOL:        IDENTIFICATION DIVISION.
       PROGRAM-ID. cursor-positioning.

       PROCEDURE DIVISION.
           DISPLAY "Hello" AT LINE 6, COL 3

           GOBACK
           .
Task: Break OO privacy



C#: using System;
using System.Reflection;

public class MyClass
{
    private int answer = 42;
}

public class Program
{
    public static void Main()
    {
        var myInstance = new MyClass();
        var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance);
        var answer = fieldInfo.GetValue(myInstance);
        Console.WriteLine(answer);
    }
}









Ada: package OO_Privacy is

   type Confidential_Stuff is tagged private;
   subtype Password_Type is String(1 .. 8);

private
   type Confidential_Stuff is tagged record
      Password: Password_Type := "default!"; 
   end record;
end OO_Privacy;
Task: Break OO privacy


C++: #include <iostream>

class CWidget; 

class CFactory
{
  friend class CWidget;
private:
  unsigned int m_uiCount;
public:
  CFactory();
  ~CFactory();
  CWidget* GetWidget();
};

class CWidget
{
private:
  CFactory& m_parent;

private:
  CWidget(); 
  CWidget(const CWidget&); 
  CWidget& operator=(const CWidget&); 
public:
  CWidget(CFactory& parent);
  ~CWidget();
};


CFactory::CFactory() : m_uiCount(0) {}
CFactory::~CFactory() {}


CWidget* CFactory::GetWidget()
{
  
  return new CWidget(*this);
}


CWidget::CWidget(CFactory& parent) : m_parent(parent)
{
  ++m_parent.m_uiCount;

  std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}

CWidget::~CWidget()
{
  --m_parent.m_uiCount;

  std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}

int main()
{
  CFactory factory;

  CWidget* pWidget1 = factory.GetWidget();
  CWidget* pWidget2 = factory.GetWidget();
  delete pWidget1;

  CWidget* pWidget3 = factory.GetWidget();
  delete pWidget3;
  delete pWidget2;
}










Ada: package OO_Privacy is

   type Confidential_Stuff is tagged private;
   subtype Password_Type is String(1 .. 8);

private
   type Confidential_Stuff is tagged record
      Password: Password_Type := "default!"; 
   end record;
end OO_Privacy;
Task: Break OO privacy




Go: package main

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"reflect"
	"unsafe"
)

type foobar struct {
	Exported   int 
	unexported int 
}

func main() {
	obj := foobar{12, 42}
	fmt.Println("obj:", obj)

	examineAndModify(&obj)
	fmt.Println("obj:", obj)

	anotherExample()
}





func examineAndModify(any interface{}) {
	v := reflect.ValueOf(any) 
	v = v.Elem()              
	fmt.Println(" v:", v, "=", v.Interface())
	t := v.Type()
	
	fmt.Printf("    %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet")
	for i := 0; i < v.NumField(); i++ {
		f := v.Field(i) 
		fmt.Printf("    %2d: %-10s %-4s %t\n", i,
			t.Field(i).Name, f.Type(), f.CanSet())
	}

	
	v.Field(0).SetInt(16)
	
	
	
	

	
	
	
	vp := v.Field(1).Addr()            
	up := unsafe.Pointer(vp.Pointer()) 
	p := (*int)(up)                    
	fmt.Printf("  vp has type %-14T = %v\n", vp, vp)
	fmt.Printf("  up has type %-14T = %#0x\n", up, up)
	fmt.Printf("   p has type %-14T = %v pointing at %v\n", p, p, *p)
	*p = 43 
	
	*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++

	
	
	
	
	
	
	
}






func anotherExample() {
	r := bufio.NewReader(os.Stdin)

	
	errp := (*error)(unsafe.Pointer(
		reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer()))
	*errp = errors.New("unsafely injected error value into bufio inner workings")

	_, err := r.ReadByte()
	fmt.Println("bufio.ReadByte returned error:", err)
}








Ada: package OO_Privacy is

   type Confidential_Stuff is tagged private;
   subtype Password_Type is String(1 .. 8);

private
   type Confidential_Stuff is tagged record
      Password: Password_Type := "default!"; 
   end record;
end OO_Privacy;
Task: Break OO privacy





Java: module BreakOO
    {
    
    class Exposed
        {
        public    String pub = "public";
        protected String pro = "protected";
        private   String pri = "private";

        @Override
        String toString()
            {
            return $"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}";
            }
        }

    void run()
        {
        @Inject Console console;

        Exposed expo = new Exposed();
        console.print($"before: {expo}");

        
        expo.pub = $"this was {expo.pub}";
     
     

        
        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));
        expoPro.pro = $"this was {expoPro.pro}";
     

        
        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));
        expoPri.pri = $"this was {expoPri.pri}";

        
        
        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));
        expoStr.pub = $"{expoStr.pub}!!!";
        expoStr.pro = $"{expoStr.pro}!!!";
        expoStr.pri = $"{expoStr.pri}!!!";

        console.print($"after: {expo}");
        }
    }







Ada: package OO_Privacy is

   type Confidential_Stuff is tagged private;
   subtype Password_Type is String(1 .. 8);

private
   type Confidential_Stuff is tagged record
      Password: Password_Type := "default!"; 
   end record;
end OO_Privacy;
Task: Break OO privacy







Python: >>> class MyClassName:
	__private = 123
	non_private = __private * 2

	
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
  File "<pyshell
    mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>





Ada: package OO_Privacy is

   type Confidential_Stuff is tagged private;
   subtype Password_Type is String(1 .. 8);

private
   type Confidential_Stuff is tagged record
      Password: Password_Type := "default!"; 
   end record;
end OO_Privacy;
Task: Break OO privacy








VB: Imports System.Reflection


Public Class MyClazz
    Private answer As Integer = 42
End Class

Public Class Program
    Public Shared Sub Main()
        Dim myInstance = New MyClazz()
        Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance)
        Dim answer = fieldInfo.GetValue(myInstance)
        Console.WriteLine(answer)
    End Sub
End Class




Ada: package OO_Privacy is

   type Confidential_Stuff is tagged private;
   subtype Password_Type is String(1 .. 8);

private
   type Confidential_Stuff is tagged record
      Password: Password_Type := "default!"; 
   end record;
end OO_Privacy;
Task: Break OO privacy



C#: using System;
using System.Reflection;

public class MyClass
{
    private int answer = 42;
}

public class Program
{
    public static void Main()
    {
        var myInstance = new MyClass();
        var fieldInfo = typeof(MyClass).GetField("answer", BindingFlags.NonPublic | BindingFlags.Instance);
        var answer = fieldInfo.GetValue(myInstance);
        Console.WriteLine(answer);
    }
}
Task: Break OO privacy


C++: #include <iostream>

class CWidget; 

class CFactory
{
  friend class CWidget;
private:
  unsigned int m_uiCount;
public:
  CFactory();
  ~CFactory();
  CWidget* GetWidget();
};

class CWidget
{
private:
  CFactory& m_parent;

private:
  CWidget(); 
  CWidget(const CWidget&); 
  CWidget& operator=(const CWidget&); 
public:
  CWidget(CFactory& parent);
  ~CWidget();
};


CFactory::CFactory() : m_uiCount(0) {}
CFactory::~CFactory() {}


CWidget* CFactory::GetWidget()
{
  
  return new CWidget(*this);
}


CWidget::CWidget(CFactory& parent) : m_parent(parent)
{
  ++m_parent.m_uiCount;

  std::cout << "Widget spawning. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}

CWidget::~CWidget()
{
  --m_parent.m_uiCount;

  std::cout << "Widget dieing. There are now " << m_parent.m_uiCount << " Widgets instanciated." << std::endl;
}

int main()
{
  CFactory factory;

  CWidget* pWidget1 = factory.GetWidget();
  CWidget* pWidget2 = factory.GetWidget();
  delete pWidget1;

  CWidget* pWidget3 = factory.GetWidget();
  delete pWidget3;
  delete pWidget2;
}
Task: Break OO privacy





Java: module BreakOO
    {
    
    class Exposed
        {
        public    String pub = "public";
        protected String pro = "protected";
        private   String pri = "private";

        @Override
        String toString()
            {
            return $"pub={pub.quoted()}, pro={pro.quoted()}, pri={pri.quoted()}";
            }
        }

    void run()
        {
        @Inject Console console;

        Exposed expo = new Exposed();
        console.print($"before: {expo}");

        
        expo.pub = $"this was {expo.pub}";
     
     

        
        assert (protected Exposed) expoPro := &expo.revealAs((protected Exposed));
        expoPro.pro = $"this was {expoPro.pro}";
     

        
        assert (private Exposed) expoPri := &expo.revealAs((private Exposed));
        expoPri.pri = $"this was {expoPri.pri}";

        
        
        assert (struct Exposed) expoStr := &expo.revealAs((struct Exposed));
        expoStr.pub = $"{expoStr.pub}!!!";
        expoStr.pro = $"{expoStr.pro}!!!";
        expoStr.pri = $"{expoStr.pri}!!!";

        console.print($"after: {expo}");
        }
    }
Task: Break OO privacy







Python: >>> class MyClassName:
	__private = 123
	non_private = __private * 2

	
>>> mine = MyClassName()
>>> mine.non_private
246
>>> mine.__private
Traceback (most recent call last):
  File "<pyshell
    mine.__private
AttributeError: 'MyClassName' object has no attribute '__private'
>>> mine._MyClassName__private
123
>>>
Task: Break OO privacy








VB: Imports System.Reflection


Public Class MyClazz
    Private answer As Integer = 42
End Class

Public Class Program
    Public Shared Sub Main()
        Dim myInstance = New MyClazz()
        Dim fieldInfo = GetType(MyClazz).GetField("answer", BindingFlags.NonPublic Or BindingFlags.Instance)
        Dim answer = fieldInfo.GetValue(myInstance)
        Console.WriteLine(answer)
    End Sub
End Class
Task: Break OO privacy




Go: package main

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"reflect"
	"unsafe"
)

type foobar struct {
	Exported   int 
	unexported int 
}

func main() {
	obj := foobar{12, 42}
	fmt.Println("obj:", obj)

	examineAndModify(&obj)
	fmt.Println("obj:", obj)

	anotherExample()
}





func examineAndModify(any interface{}) {
	v := reflect.ValueOf(any) 
	v = v.Elem()              
	fmt.Println(" v:", v, "=", v.Interface())
	t := v.Type()
	
	fmt.Printf("    %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet")
	for i := 0; i < v.NumField(); i++ {
		f := v.Field(i) 
		fmt.Printf("    %2d: %-10s %-4s %t\n", i,
			t.Field(i).Name, f.Type(), f.CanSet())
	}

	
	v.Field(0).SetInt(16)
	
	
	
	

	
	
	
	vp := v.Field(1).Addr()            
	up := unsafe.Pointer(vp.Pointer()) 
	p := (*int)(up)                    
	fmt.Printf("  vp has type %-14T = %v\n", vp, vp)
	fmt.Printf("  up has type %-14T = %#0x\n", up, up)
	fmt.Printf("   p has type %-14T = %v pointing at %v\n", p, p, *p)
	*p = 43 
	
	*(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++

	
	
	
	
	
	
	
}






func anotherExample() {
	r := bufio.NewReader(os.Stdin)

	
	errp := (*error)(unsafe.Pointer(
		reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer()))
	*errp = errors.New("unsafely injected error value into bufio inner workings")

	_, err := r.ReadByte()
	fmt.Println("bufio.ReadByte returned error:", err)
}
Task: Break OO privacy






PHP: <?php
class SimpleClass {
    private $answer = "hello\"world\nforever :)";
}
 
$class = new SimpleClass;
ob_start();



var_export($class);
$class_content = ob_get_clean();
 
$class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content);
$class_content = preg_replace('"\)$"', ';', $class_content);

$new_class = eval($class_content);
echo $new_class['answer'];






Ada: package OO_Privacy is

   type Confidential_Stuff is tagged private;
   subtype Password_Type is String(1 .. 8);

private
   type Confidential_Stuff is tagged record
      Password: Password_Type := "default!"; 
   end record;
end OO_Privacy;
Task: Break OO privacy






PHP: <?php
class SimpleClass {
    private $answer = "hello\"world\nforever :)";
}
 
$class = new SimpleClass;
ob_start();



var_export($class);
$class_content = ob_get_clean();
 
$class_content = preg_replace('"^SimpleClass::__set_state\("', 'return ', $class_content);
$class_content = preg_replace('"\)$"', ';', $class_content);

$new_class = eval($class_content);
echo $new_class['answer'];
Task: Amicable pairs



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

namespace RosettaCode.AmicablePairs
{
    internal static class Program {
        private const int Limit = 20000;        

        private static void Main()
        {
            foreach (var pair in GetPairs(Limit))
            {
                Console.WriteLine("{0} {1}", pair.Item1, pair.Item2);
            }
        }

        private static IEnumerable<Tuple<int, int>> GetPairs(int max)
        {
            List<int> divsums =
                Enumerable.Range(0, max + 1).Select(i => ProperDivisors(i).Sum()).ToList();
            for(int i=1; i<divsums.Count; i++) {
                int sum = divsums[i];
                if(i < sum && sum <= divsums.Count && divsums[sum] == i) {
                    yield return new Tuple<int, int>(i, sum);
                }
            }
        }

        private static IEnumerable<int> ProperDivisors(int number)
        {
            return
                Enumerable.Range(1, number / 2)
                    .Where(divisor => number % divisor == 0);
        }
    }
}









Ada: with Ada.Text_IO, Generic_Divisors; use Ada.Text_IO;
 
procedure Amicable_Pairs is
   
   function Same(P: Positive) return Positive is (P);
   
   package Divisor_Sum is new Generic_Divisors
     (Result_Type => Natural, None => 0, One => Same, Add =>  "+");
   
   Num2 : Integer;
begin
   for Num1 in 4 .. 20_000 loop
      Num2 := Divisor_Sum.Process(Num1);
      if Num1 < Num2 then
	 if Num1 = Divisor_Sum.Process(Num2) then
	   Put_Line(Integer'Image(Num1) & "," & Integer'Image(Num2));
	 end if;
      end if;
   end loop;
end Amicable_Pairs;