WeixiangYan/CodeTransOcean huggingface dataset:
Task: Enforced immutability


C++: #include <iostream>

class MyOtherClass
{
public:
  const int m_x;
  MyOtherClass(const int initX = 0) : m_x(initX) { }

};

int main()
{
  MyOtherClass mocA, mocB(7);

  std::cout << mocA.m_x << std::endl; 
  std::cout << mocB.m_x << std::endl; 

  
  

  return 0;
}








COBOL: ENVIRONMENT DIVISION.
CONFIGURATION SECTION.
SPECIAL-NAMES.
    SYMBOLIC CHARACTERS NUL IS 0, TAB IS 9.
Task: Shortest common supersequence



C#: public class ShortestCommonSupersequence
{
    Dictionary<(string, string), string> cache = new();

    public string scs(string x, string y)
    {
        if (x.Length == 0) return y;
        if (y.Length == 0) return x;

        if (cache.TryGetValue((x, y), out var result)) return result;

        if (x[0] == y[0])
        {
            return cache[(x, y)] = x[0] + scs(x.Substring(1), y.Substring(1));
        }

        var xr = scs(x.Substring(1), y);
        var yr = scs(x, y.Substring(1));
        if (yr.Length <= xr.Length)
        {
            return cache[(x, y)] = y[0] + yr;
        }
        else
        {
            return cache[(x, y)] = x[0] + xr;
        }
    }

    public static void Main(string[] args)
    {
        var scs = new ShortestCommonSupersequence();
        Console.WriteLine(scs.scs("abcbdab", "bdcaba"));
    }
}









Ada: with Ada.Text_IO;

procedure Shortest is

   function Scs (Left, Right : in String) return String is
      Left_Tail  : String renames Left  (Left'First  + 1 .. Left'Last);
      Right_Tail : String renames Right (Right'First + 1 .. Right'Last);
   begin
      if Left  = "" then return Right; end if;
      if Right = "" then return Left;  end if;

      if Left (Left'First) = Right (Right'First) then
         return Left (Left'First) & Scs (Left_Tail, Right_Tail);
      end if;

      declare
         S1 : constant String := Scs (Left, Right_Tail);
         S2 : constant String := Scs (Left_Tail, Right);
      begin
         return (if S1'Length <= S2'Length
                 then Right (Right'First) & S1
                 else Left  (Left'First)  & S2);
      end;
   end Scs;

   procedure Exercise (Left, Right : String) is
      use Ada.Text_Io;
   begin
      Put ("scs ( "); Put (Left); Put (" , "); Put (Right); Put ( " ) -> ");
      Put (Scs (Left, Right));
      New_Line;
   end Exercise;

begin
   Exercise ("abcbdab", "bdcaba");
   Exercise ("WEASELS", "WARDANCE");
end Shortest;
Task: Long year



C#: using static System.Console;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;

public static class Program
{
    public static void Main()
    {
        WriteLine("Long years in the 21st century:");
        WriteLine(string.Join(" ", 2000.To(2100).Where(y => ISOWeek.GetWeeksInYear(y) == 53)));
    }
    
    public static IEnumerable<int> To(this int start, int end) {
        for (int i = start; i < end; i++) yield return i;
    }
    
}









Ada: 



with Ada.Text_IO;             use Ada.Text_IO;
with Ada.Calendar;            use Ada.Calendar;
with Ada.Calendar.Formatting; use Ada.Calendar.Formatting;

procedure Main is
   First_Day : Time;
   Last_Day  : Time;
   package AC renames Ada.Calendar;
   type Counter is mod 10;
   Count : Counter := 0;
begin
   for Yr in Year_Number loop

      First_Day := AC.Time_Of (Year => Yr, Month => 1, Day => 1);
      Last_Day  := AC.Time_Of (Year => Yr, Month => 12, Day => 31);
      
      
      
      
      if Day_Of_Week (First_Day) = Thursday
        or else Day_Of_Week (Last_Day) = Thursday
      then
         if Count = 0 then
            New_Line;
         end if;
         Put (Yr'Image);
         Count := Count + 1;
      end if;
   end loop;
end Main;
Task: Mian-Chowla sequence



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

static class Program {
    static int[] MianChowla(int n) {
        int[] mc = new int[n - 1 + 1];
        HashSet<int> sums = new HashSet<int>(), ts = new HashSet<int>();
        int sum; mc[0] = 1; sums.Add(2);
        for (int i = 1; i <= n - 1; i++) {
            for (int j = mc[i - 1] + 1; ; j++) {
                mc[i] = j;
                for (int k = 0; k <= i; k++) {
                    sum = mc[k] + j;
                    if (sums.Contains(sum)) { ts.Clear(); break; }
                    ts.Add(sum);
                }
                if (ts.Count > 0) { sums.UnionWith(ts); break; }
            }
        }
        return mc;
    }

    static void Main(string[] args)
    {
        const int n = 100; Stopwatch sw = new Stopwatch();
        string str = " of the Mian-Chowla sequence are:\n";
        sw.Start(); int[] mc = MianChowla(n); sw.Stop();
        Console.Write("The first 30 terms{1}{2}{0}{0}Terms 91 to 100{1}{3}{0}{0}" +
            "Computation time was {4}ms.{0}", '\n', str, string.Join(" ", mc.Take(30)),
            string.Join(" ", mc.Skip(n - 10)), sw.ElapsedMilliseconds);
    }
}









Ada: with Ada.Text_IO;
with Ada.Containers.Hashed_Sets;

procedure Mian_Chowla_Sequence
is
   type Natural_Array is array(Positive range <>) of Natural;

   function Hash(P : in Positive) return Ada.Containers.Hash_Type is
   begin
      return Ada.Containers.Hash_Type(P);
   end Hash;

   package Positive_Sets is new Ada.Containers.Hashed_Sets(Positive, Hash, "=");

   function Mian_Chowla(N : in Positive) return Natural_Array
   is
      return_array : Natural_Array(1 .. N) := (others => 0);
      nth : Positive := 1;
      candidate : Positive := 1;
      seen : Positive_Sets.Set;
   begin
      while nth <= N loop
         declare
            sums : Positive_Sets.Set;
            terms : constant Natural_Array := return_array(1 .. nth-1) & candidate;
            found : Boolean := False;
         begin
            for term of terms loop
               if seen.Contains(term + candidate) then
                  found := True;
                  exit;
               else
                  sums.Insert(term + candidate);
               end if;
            end loop;

            if not found then
               return_array(nth) := candidate;
               seen.Union(sums);
               nth := nth + 1;
            end if;
            candidate := candidate + 1;
         end;
      end loop;
      return return_array;
   end Mian_Chowla;

   length : constant Positive := 100;
   sequence : constant Natural_Array(1 .. length) := Mian_Chowla(length);
begin
   Ada.Text_IO.Put_Line("Mian Chowla sequence first 30 terms :");
   for term of sequence(1 .. 30) loop
      Ada.Text_IO.Put(term'Img);
   end loop;
   Ada.Text_IO.New_Line;
   Ada.Text_IO.Put_Line("Mian Chowla sequence terms 91 to 100 :");
   for term of sequence(91 .. 100) loop
      Ada.Text_IO.Put(term'Img);
   end loop;
end Mian_Chowla_Sequence;
Task: Start from a main routine








VB: SUB Main()
  
END
Task: Long year






PHP: function isLongYear($year) {
  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));
}

for ($y=1995; $y<=2045; ++$y) {
  if (isLongYear($y)) {
    printf("%s\n", $y);
  }
}





Fortran: program longyear
    use iso_fortran_env, only: output_unit, input_unit
    implicit none

    integer             :: start, ende, i, counter
    integer, parameter  :: line_break=10

    write(output_unit,*) "Enter beginning of interval"
    read(input_unit,*) start
    write(output_unit,*) "Enter end of interval"
    read(input_unit,*) ende

    if (start>=ende) error stop "Last year must be after first year

    counter = 0
    do i = start, ende
        if (is_long_year(i)) then
            write(output_unit,'(I0,x)', advance="no") i
            counter = counter + 1
            if (modulo(counter,line_break) == 0) write(output_unit,*)
        end if
    end do
contains
    pure function p(year)
        integer, intent(in) :: year
        integer             :: p

        p = modulo(year + year/4 - year/100 + year/400, 7)
    end function p

    pure function is_long_year(year)
        integer, intent(in) :: year
        logical             :: is_long_year

        is_long_year = p(year) == 4 .or. p(year-1) == 3
    end function is_long_year
end program longyear
Task: Magic 8-ball






PHP: <?php

$fortunes = array(
	"It is certain",
	"It is decidedly so",
	"Without a doubt",
	"Yes, definitely",
	"You may rely on it",
	"As I see it, yes",
	"Most likely",
	"Outlook good",
	"Signs point to yes",
	"Yes",
	"Reply hazy, try again",
	"Ask again later",
	"Better not tell you now",
	"Cannot predict now",
	"Concentrate and ask again",
	"Don't bet on it",
	"My reply is no",
	"My sources say no",
	"Outlook not so good",
	"Very doubtful"
);


function cli_prompt( $prompt='> ', $default=false ) {

	do {

		echo $prompt;

		$cmd = chop( fgets( STDIN ) );

	} while ( empty( $default ) and empty( $cmd ) );

	return $cmd ?: $default;

}

$question = cli_prompt( 'What is your question? ' );

echo 'Q: ', $question, PHP_EOL;

echo 'A: ', $fortunes[ array_rand( $fortunes ) ], PHP_EOL;





Fortran: PROGRAM EIGHT_BALL
    CHARACTER(LEN=100) :: RESPONSE
    CHARACTER(LEN=100) :: QUESTION
    CHARACTER(LEN=100), DIMENSION(20) :: RESPONSES
    REAL :: R

    CALL RANDOM_SEED()

    RESPONSES(1) = "It is certain" 
    RESPONSES(2) = "It is decidedly so"
    RESPONSES(3) = "Without a doubt"
    RESPONSES(4) = "Yes, definitely"
    RESPONSES(5) = "You may rely on it"
    RESPONSES(6) = "As I see it, yes"
    RESPONSES(7) = "Most likely"
    RESPONSES(8) = "Outlook good"
    RESPONSES(9) = "Signs point to yes"
    RESPONSES(10) = "Yes"
    RESPONSES(11) = "Reply hazy, try again"
    RESPONSES(12) = "Ask again later"
    RESPONSES(13) = "Better not tell you now"
    RESPONSES(14) = "Cannot predict now"
    RESPONSES(15) = "Concentrate and ask again"
    RESPONSES(16) = "Don't bet on it"
    RESPONSES(17) = "My reply is no"
    RESPONSES(18) = "My sources say no"
    RESPONSES(19) = "Outlook not so good"
    RESPONSES(20) = "Very doubtful"

    WRITE(*,*) "Welcome to 8 Ball
    WRITE(*,*) "you seek, type either 'quit' or 'q' to exit", NEW_LINE('A')

    DO WHILE(.TRUE.)
        PRINT*, "Ask your question: "
        READ(*,*) QUESTION
        IF(QUESTION == "q" .OR. QUESTION == "quit") THEN
            CALL EXIT(0)
        ENDIF
        CALL RANDOM_NUMBER(R)
        PRINT*, "Response: ", TRIM(RESPONSES(FLOOR(R*20))), NEW_LINE('A')
    ENDDO
END PROGRAM EIGHT_BALL
Task: Kahan summation






PHP: <?php





function kahansum($input) {
    $sum = $c = 0;
    foreach($input as $item) {
        $y = $item + $c;
        $t = $sum + $y;
        $c = ($t - $sum) - $y;
        $sum = $t;
    }
    return $sum;
}


$input = array(10000.0, 3.14159, 2.71828);
list($a, $b, $c) = $input;


$sumabc = ($a + $b) + $c;
echo "Main task - Left to right summation: ";
echo sprintf("%6.1f", $sumabc).PHP_EOL;



echo "Main task - Kahan summation: ";
echo sprintf("%6.1f", kahansum($input)).PHP_EOL;


$epsilon = 1.0;
while ((1.0 + $epsilon) != 1.0) {
    $epsilon /= 2.0;
}
echo "Trying the subtask".PHP_EOL."epsilon: ";
echo $epsilon.PHP_EOL;


$a = 1.0;
$b = $epsilon;
$c = -$epsilon;

$input = array($a, $b, $c);

$sumabc = ($a + $b) + $c;
echo "Sub task - Left to right summation: ";
echo sprintf("%.1f", $sumabc).PHP_EOL;

echo "Sub task - Kahan summation: ";
echo sprintf("%.1f", kahansum($input)).PHP_EOL;

echo "Are the results the same?".PHP_EOL;
var_dump((($a + $b) + $c) === kahansum($input));

echo "Difference between the operations: ";
$diff = (($a + $b) + $c) - kahansum($input);
echo $diff.PHP_EOL;





Fortran:       FUNCTION SUMC(A,N)
COMPENSATED SUMMATION. C WILL NOT STAY ZERO, DESPITE MATHEMATICS.
       DIMENSION A(12345)
        S = 0.0
        C = 0.0
        DO 1 I = 1,N
          Y = A(I) - C
          T = S + Y
          C = (T - S) - Y
          S = T
    1   CONTINUE
        SUMC = S
      END
      DIMENSION A(3)
      A(1) = 10000.0
      A(2) = 3.14159
      A(3) = 2.71828
      TYPE 1, A(1) + A(2) + A(3)
      TYPE 1, SUMC(A,3)
    1 FORMAT (6HSUM = ,F12.1)
      END
Task: Pythagorean triples






PHP: <?php
 
function gcd($a, $b)
{
    if ($a == 0)
       return $b;
    if ($b == 0)
       return $a;
    if($a == $b)
        return $a;
    if($a > $b)
        return gcd($a-$b, $b);
    return gcd($a, $b-$a);
}

$pytha = 0;
$prim = 0;
$max_p = 100;

for ($a = 1; $a <= $max_p / 3; $a++) {
    $aa = $a**2;
    for ($b = $a + 1; $b < $max_p/2; $b++) {
        $bb = $b**2;
        for ($c = $b + 1; $c < $max_p/2; $c++) {
            $cc = $c**2;
            if ($aa + $bb < $cc) break;
            if ($a + $b + $c > $max_p) break;

            if ($aa + $bb == $cc) {
                $pytha++;
                if (gcd($a, $b) == 1) $prim++;
            }
        }
    }
}

echo 'Up to ' . $max_p . ', there are ' . $pytha . ' triples, of which ' . $prim . ' are primitive.';





Fortran: module triples
  implicit none
  
  integer :: max_peri, prim, total
  integer :: u(9,3) = reshape((/ 1, -2, 2,  2, -1, 2,  2, -2, 3, &
                                 1,  2, 2,  2,  1, 2,  2,  2, 3, &
                                -1,  2, 2, -2,  1, 2, -2,  2, 3 /), &
                                (/ 9, 3 /))
                                
contains

recursive subroutine new_tri(in)
  integer, intent(in) :: in(:)
  integer :: i
  integer :: t(3), p

  p = sum(in)
  if (p > max_peri) return

  prim = prim + 1
  total = total + max_peri / p
  do i = 1, 3
    t(1) = sum(u(1:3, i) * in)
    t(2) = sum(u(4:6, i) * in)
    t(3) = sum(u(7:9, i) * in)
    call new_tri(t);
  end do
end subroutine new_tri
end module triples

program Pythagorean
  use triples
  implicit none

  integer :: seed(3) = (/ 3, 4, 5 /)
  
  max_peri = 10
  do
    total = 0
    prim = 0
    call new_tri(seed)
    write(*, "(a, i10, 2(i10, a))") "Up to", max_peri, total, " triples",  prim, " primitives"
    if(max_peri == 100000000) exit
    max_peri = max_peri * 10
  end do
end program Pythagorean
Task: Call a foreign-language function






PHP: $ffi = FFI::cdef("char *_strdup(const char *strSource);", "msvcrt.dll");

$cstr = $ffi->_strdup("success");
$str = FFI::string($cstr);
echo $str;
FFI::free($cstr);





Fortran: module c_api
    use iso_c_binding
    implicit none

    interface
        function strdup(ptr) bind(C)
            import c_ptr
            type(c_ptr), value :: ptr
            type(c_ptr) :: strdup
        end function
    end interface
    
    interface
        subroutine free(ptr) bind(C)
            import c_ptr
            type(c_ptr), value :: ptr
        end subroutine
    end interface
    
    interface
        function puts(ptr) bind(C)
            import c_ptr, c_int
            type(c_ptr), value :: ptr
            integer(c_int) :: puts
        end function
    end interface
end module

program c_example
    use c_api
    implicit none

    character(20), target :: str = "Hello, World
    type(c_ptr) :: ptr
    integer(c_int) :: res
    
    ptr = strdup(c_loc(str))
    
    res = puts(c_loc(str))
    res = puts(ptr)
    
    print *, transfer(c_loc(str), 0_c_intptr_t), &
             transfer(ptr, 0_c_intptr_t)
    call free(ptr)
end program
Task: Gray code






PHP: <?php




function gray_encode($binary){
	return $binary ^ ($binary >> 1);
}


function gray_decode($gray){
	$binary = $gray;
	while($gray >>= 1) $binary ^= $gray;
	return $binary;
}

for($i=0;$i<32;$i++){
	$gray_encoded = gray_encode($i);
	printf("%2d : %05b => %05b => %05b : %2d \n",$i, $i, $gray_encoded, $gray_encoded, gray_decode($gray_encoded));
}





Fortran:       PROGRAM GRAY
      IMPLICIT NONE
      INTEGER IGRAY,I,J,K
      CHARACTER*5 A,B,C
      DO 10 I=0,31
      J=IGRAY(I,1)
      K=IGRAY(J,-1)
      CALL BINARY(A,I,5)
      CALL BINARY(B,J,5)
      CALL BINARY(C,K,5)
      PRINT 99,I,A,B,C,K
   10 CONTINUE
   99 FORMAT(I2,3H : ,A5,4H => ,A5,4H => ,A5,3H : ,I2)
      END

      FUNCTION IGRAY(N,D)
      IMPLICIT NONE
      INTEGER D,K,N,IGRAY
      IF(D.LT.0) GO TO 10
      IGRAY=IEOR(N,ISHFT(N,-1))
      RETURN
   10 K=N
      IGRAY=0
   20 IGRAY=IEOR(IGRAY,K)
      K=K/2
      IF(K.NE.0) GO TO 20
      END

      SUBROUTINE BINARY(S,N,K)
      IMPLICIT NONE
      INTEGER I,K,L,N
      CHARACTER*(*) S
      L=LEN(S)
      DO 10 I=0,K-1
C The following line may replace the next block-if,
C on machines using ASCII code :
C     S(L-I:L-I)=CHAR(48+IAND(1,ISHFT(N,-I)))
C On EBCDIC machines, use 240 instead of 48.
      IF(BTEST(N,I)) THEN
      S(L-I:L-I)='1'
      ELSE
      S(L-I:L-I)='0'
      END IF
   10 CONTINUE
      S(1:L-K)=''
      END
Task: File extension is in extensions list






PHP: $allowed = ['zip', 'rar', '7z', 'gz', 'archive', 'A##', 'tar.bz2'];
$lc_allowed = array_map('strtolower', $allowed);

$tests = [
    ['MyData.a##',true],
    ['MyData.tar.Gz',true],
    ['MyData.gzip',false],
    ['MyData.7z.backup',false],
    ['MyData...',false],
    ['MyData',false],
    ['archive.tar.gz', true]
];

foreach ($tests as $test) {
    $ext = pathinfo($test[0], PATHINFO_EXTENSION);
    if (in_array(strtolower($ext), $lc_allowed)) {
        $result = 'true';
    } else {
        $result = 'false';
    }
    printf("%20s : %s \n", $test[0],$result);
}





Fortran:         IT = ICHAR(TEXT(I:I)) - ICHAR("a")	
        IF (IT.GE.0 .AND. IT.LE.25) TEXT(I:I) = CHAR(IT + ICHAR("A"))
Task: Flow-control structures






PHP: <?php
goto a;
echo 'Foo';
 
a:
echo 'Bar';
?>





Fortran:       ...
      ASSIGN 1101 to WHENCE   
      GO TO 1000              
 1101 CONTINUE                
      ... 
      ASSIGN 1102 to WHENCE   
      GO TO 1000              
 1102 CONTINUE                
      ...
Common code, far away.
 1000 do something            
      GO TO WHENCE
Task: Return multiple values






PHP: function addsub($x, $y) {
  return array($x + $y, $x - $y);
}





Fortran: module multiple_values
implicit none
type res
  integer :: p, m
end type

contains

function addsub(x,y) result(r)
  integer :: x, y
  type(res) :: r 
  r%p = x+y
  r%m = x-y
end function
end module

program main
  use multiple_values 
  print *, addsub(33, 22)
end program
Task: Substring_Top and tail






PHP: <?php
echo substr("knight", 1), "\n";       // strip first character
echo substr("socks", 0, -1), "\n";    // strip last character
echo substr("brooms", 1, -1), "\n";   // strip both first and last characters
?>





Fortran: program substring

  character(len=5) :: string
  string = "Hello"
  
  write (*,*) string
  write (*,*) string(2:)
  write (*,*) string( :len(string)-1)
  write (*,*) string(2:len(string)-1)

end program substring
Task: Bitmap_Histogram






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!';
}





Fortran: module RCImageProcess
  use RCImageBasic
  implicit none
contains

  subroutine get_histogram(img, histogram)
    type(scimage), intent(in) :: img
    integer, dimension(0:255), intent(out) :: histogram
    
    integer :: i

    histogram = 0
    do i = 0,255
       histogram(i) = sum(img%channel, img%channel == i)
    end do
  end subroutine get_histogram

  function histogram_median(histogram)
    integer, dimension(0:255), intent(in) :: histogram
    integer :: histogram_median
    
    integer :: from, to, left, right

    from = 0
    to = 255
    left = histogram(from)
    right = histogram(to)
    do while ( from /= to )
       if ( left < right ) then
          from = from + 1
          left = left + histogram(from)
       else
          to = to - 1
          right = right + histogram(to)
       end if
    end do
    histogram_median = from
  end function histogram_median
  
end module RCImageProcess
Task: Long year






PHP: function isLongYear($year) {
  return (53 == strftime('%V', gmmktime(0,0,0,12,28,$year)));
}

for ($y=1995; $y<=2045; ++$y) {
  if (isLongYear($y)) {
    printf("%s\n", $y);
  }
}






Ada: 



with Ada.Text_IO;             use Ada.Text_IO;
with Ada.Calendar;            use Ada.Calendar;
with Ada.Calendar.Formatting; use Ada.Calendar.Formatting;

procedure Main is
   First_Day : Time;
   Last_Day  : Time;
   package AC renames Ada.Calendar;
   type Counter is mod 10;
   Count : Counter := 0;
begin
   for Yr in Year_Number loop

      First_Day := AC.Time_Of (Year => Yr, Month => 1, Day => 1);
      Last_Day  := AC.Time_Of (Year => Yr, Month => 12, Day => 31);
      
      
      
      
      if Day_Of_Week (First_Day) = Thursday
        or else Day_Of_Week (Last_Day) = Thursday
      then
         if Count = 0 then
            New_Line;
         end if;
         Put (Yr'Image);
         Count := Count + 1;
      end if;
   end loop;
end Main;
Task: MAC vendor lookup






PHP: <?php
$apiRoot = "https://api.macvendors.com";
$macList = array("88:53:2E:67:07:BE", "D4:F4:6F:C9:EF:8D", 
		 "FC:FB:FB:01:FA:21", "4c:72:b9:56:fe:bc", "00-14-22-01-23-45");

$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
foreach ($macList as $burger) {
  curl_setopt($curl, CURLOPT_URL, "$apiRoot/$burger");
  echo(curl_exec($curl));
  echo("\n");
  sleep(2);
}
curl_close($curl);
?>






Ada: with Ada.Text_IO;

with AWS.Client;
with AWS.Response;
with AWS.Messages;

procedure MAC_Vendor is

   procedure Lookup (MAC : in String) is
      use AWS.Response;
      use AWS.Messages;
      URL     : constant String := "http://api.macvendors.com/" & MAC;
      Page    : constant Data   := AWS.Client.Get (URL);
      use Ada.Text_IO;
   begin
      Put (MAC);
      Set_Col (20);
      case AWS.Response.Status_Code (Page) is
         when S200   => Put_Line (Message_Body (Page));
         when S404   => Put_Line ("N/A");
         when others => Put_Line ("Error");
      end case;
   end Lookup;

begin
   
   Lookup ("88:53:2E:67:07:BE");   delay 1.500;
   Lookup ("D4:F4:6F:C9:EF:8D");   delay 1.500;
   Lookup ("FC:FB:FB:01:FA:21");   delay 1.500;
   Lookup ("4c:72:b9:56:fe:bc");   delay 1.500;
   Lookup ("00-14-22-01-23-45");   delay 1.500;
   Lookup ("23-45-67");            delay 1.500;
   Lookup ("foobar");
end MAC_Vendor;