WeixiangYan/CodeTransOcean huggingface dataset:
Task: Draw a sphere







Python: import math

shades = ('.',':','!','*','o','e','&','

def normalize(v):
	len = math.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
	return (v[0]/len, v[1]/len, v[2]/len)

def dot(x,y):
	d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]
	return -d if d < 0 else 0

def draw_sphere(r, k, ambient, light):
	for i in range(int(math.floor(-r)),int(math.ceil(r)+1)):
		x = i + 0.5
		line = ''

		for j in range(int(math.floor(-2*r)),int(math.ceil(2*r)+1)):
			y = j/2 + 0.5
			if x*x + y*y <= r*r:
				vec = normalize((x,y,math.sqrt(r*r - x*x - y*y)))
				b = dot(light,vec)**k + ambient
				intensity = int((1-b)*(len(shades)-1))
				line += shades[intensity] if 0 <= intensity < len(shades) else shades[0]
			else:
				line += ' '

		print(line)

light = normalize((30,30,-50))
draw_sphere(20,4,0.1, light)
draw_sphere(10,2,0.4, light)





Ada: with Glib;                use Glib;
with Cairo;               use Cairo;
with Cairo.Png;           use Cairo.Png;
with Cairo.Pattern;       use Cairo.Pattern;
with Cairo.Image_Surface; use Cairo.Image_Surface;
with Ada.Numerics;

procedure Sphere is
   subtype Dub is Glib.Gdouble;

   Surface    : Cairo_Surface;
   Cr         : Cairo_Context;
   Pat        : Cairo_Pattern;
   Status_Out : Cairo_Status;
   M_Pi       : constant Dub := Dub (Ada.Numerics.Pi);

begin
   Surface := Create (Cairo_Format_ARGB32, 512, 512);
   Cr      := Create (Surface);
   Pat     :=
      Cairo.Pattern.Create_Radial (230.4, 204.8, 51.1, 204.8, 204.8, 256.0);
   Cairo.Pattern.Add_Color_Stop_Rgba (Pat, 0.0, 1.0, 1.0, 1.0, 1.0);
   Cairo.Pattern.Add_Color_Stop_Rgba (Pat, 1.0, 0.0, 0.0, 0.0, 1.0);
   Cairo.Set_Source (Cr, Pat);
   Cairo.Arc (Cr, 256.0, 256.0, 153.6, 0.0, 2.0 * M_Pi);
   Cairo.Fill (Cr);
   Cairo.Pattern.Destroy (Pat);
   Status_Out := Write_To_Png (Surface, "SphereAda.png");
   pragma Assert (Status_Out = Cairo_Status_Success);
end Sphere;
Task: Thiele's interpolation formula







Python: 

import math

def thieleInterpolator(x, y):
    ρ = [[yi]*(len(y)-i) for i, yi in enumerate(y)]
    for i in range(len(ρ)-1):
        ρ[i][1] = (x[i] - x[i+1]) / (ρ[i][0] - ρ[i+1][0])
    for i in range(2, len(ρ)):
        for j in range(len(ρ)-i):
            ρ[j][i] = (x[j]-x[j+i]) / (ρ[j][i-1]-ρ[j+1][i-1]) + ρ[j+1][i-2]
    ρ0 = ρ[0]
    def t(xin):
        a = 0
        for i in range(len(ρ0)-1, 1, -1):
            a = (xin - x[i-1]) / (ρ0[i] - ρ0[i-2] + a)
        return y[0] + (xin-x[0]) / (ρ0[1]+a)
    return t


xVal = [i*.05 for i in range(32)]
tSin = [math.sin(x) for x in xVal]
tCos = [math.cos(x) for x in xVal]
tTan = [math.tan(x) for x in xVal]

iSin = thieleInterpolator(tSin, xVal)
iCos = thieleInterpolator(tCos, xVal)
iTan = thieleInterpolator(tTan, xVal)

print('{:16.14f}'.format(6*iSin(.5)))
print('{:16.14f}'.format(3*iCos(.5)))
print('{:16.14f}'.format(4*iTan(1)))





Ada: with Ada.Numerics.Generic_Real_Arrays;

generic
   type Real is digits <>;
package Thiele is
   package Real_Arrays is new Ada.Numerics.Generic_Real_Arrays (Real);
   subtype Real_Array is Real_Arrays.Real_Vector;

   type Thiele_Interpolation (Length : Natural) is private;

   function Create (X, Y : Real_Array) return Thiele_Interpolation;
   function Inverse (T : Thiele_Interpolation; X : Real) return Real;
private
   type Thiele_Interpolation (Length : Natural) is record
      X, Y, RhoX : Real_Array (1 .. Length);
   end record;
end Thiele;
Task: Use another language to call a function







Python: 

def query(buffer_length):
    message = b'Here am I'
    L = len(message)
    return message[0:L*(L <= buffer_length)]
Task: Pascal matrix generation





Java: import static java.lang.System.out;
import java.util.List;
import java.util.function.Function;
import java.util.stream.*;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;

public class PascalMatrix {
    static int binomialCoef(int n, int k) {
        int result = 1;
        for (int i = 1; i <= k; i++)
            result = result * (n - i + 1) / i;
        return result;
    }

    static List<IntStream> pascal(int n, Function<Integer, IntStream> f) {
        return range(0, n).mapToObj(i -> f.apply(i)).collect(toList());
    }

    static List<IntStream> pascalUpp(int n) {
        return pascal(n, i -> range(0, n).map(j -> binomialCoef(j, i)));
    }

    static List<IntStream> pascalLow(int n) {
        return pascal(n, i -> range(0, n).map(j -> binomialCoef(i, j)));
    }

    static List<IntStream> pascalSym(int n) {
        return pascal(n, i -> range(0, n).map(j -> binomialCoef(i + j, i)));
    }

    static void print(String label, List<IntStream> result) {
        out.println("\n" + label);
        for (IntStream row : result) {
            row.forEach(i -> out.printf("%2d ", i));
            System.out.println();
        }
    }

    public static void main(String[] a) {
        print("Upper: ", pascalUpp(5));
        print("Lower: ", pascalLow(5));
        print("Symmetric:", pascalSym(5));
    }
}






Fortran: module pascal

implicit none

contains
    function pascal_lower(n) result(a)
        integer :: n, i, j
        integer, allocatable :: a(:, :)
        allocate(a(n, n))
        a = 0
        do i = 1, n
            a(i, 1) = 1
        end do
        do i = 2, n
            do j = 2, i
                a(i, j) = a(i - 1, j) + a(i - 1, j - 1)
            end do
        end do
    end function
    
    function pascal_upper(n) result(a)
        integer :: n, i, j
        integer, allocatable :: a(:, :)
        allocate(a(n, n))
        a = 0
        do i = 1, n
            a(1, i) = 1
        end do
        do i = 2, n
            do j = 2, i
                a(j, i) = a(j, i - 1) + a(j - 1, i - 1)
            end do
        end do
    end function

    function pascal_symmetric(n) result(a)
        integer :: n, i, j
        integer, allocatable :: a(:, :)
        allocate(a(n, n))
        a = 0
        do i = 1, n
            a(i, 1) = 1
            a(1, i) = 1
        end do
        do i = 2, n
            do j = 2, n
                a(i, j) = a(i - 1, j) + a(i, j - 1)
            end do
        end do
    end function

    subroutine print_matrix(a)
        integer :: a(:, :)
        integer :: n, i
        n = ubound(a, 1)
        do i = 1, n
            print *, a(i, :)
        end do
    end subroutine
end module

program ex_pascal
    use pascal
    implicit none
    integer :: n
    integer, allocatable :: a(:, :)
    print *, "Size?"
    read *, n
    print *, "Lower Pascal Matrix"
    a = pascal_lower(n)
    call print_matrix(a)
    print *, "Upper Pascal Matrix"
    a = pascal_upper(n)
    call print_matrix(a)
    print *, "Symmetric Pascal Matrix"
    a = pascal_symmetric(n)
    call print_matrix(a)
end program
Task: Long year





Java: import java.time.LocalDate;
import java.time.temporal.WeekFields;

public class LongYear {

    public static void main(String[] args) {
        System.out.printf("Long years this century:%n");
        for (int year = 2000 ; year < 2100 ; year++ ) {
            if ( longYear(year) ) {
                System.out.print(year + "  ");
            }
        }
    }
    
    private static boolean longYear(int year) {
        return LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53;
    }

}






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





Java: import java.util.Random;
import java.util.Scanner;

public class MagicEightBall {

    public static void main(String[] args) {
        new MagicEightBall().run();
    }
    
    private static String[] ANSWERS = new String[] {"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.", "Yes.", "Signs point to yes.",
            "Reply hazy, try again.", "Ask again later.", "Better not tell you now.", "Cannot predict now.", "Concentrate and ask again.",
            "Don't count on it.", "My reply is no.", "My sources say no.", "Outlook not so good.", "Very doubtful. "};

    public void run() {
        Random random = new Random();
        System.out.printf("Hello.  The Magic 8 Ball knows all.  Type your question.%n%n");
        try ( Scanner in = new Scanner(System.in); ) {
            System.out.printf("?  ");
            while ( (in.nextLine()).length() > 0 ) {
                System.out.printf("8 Ball Response:  %s%n", ANSWERS[random.nextInt(ANSWERS.length)]);
                System.out.printf("?  ");
            }
        }
        System.out.printf("%n8 Ball Done.  Bye.");
    }
}






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: Validate International Securities Identification Number





Java: public class ISIN {
 
    public static void main(String[] args) {
        String[] isins = {
            "US0378331005", 
            "US0373831005", 
            "U50378331005", 
            "US03378331005",
            "AU0000XVGZA3", 
            "AU0000VXGZA3", 
            "FR0000988040"
        };
        for (String isin : isins)
            System.out.printf("%s is %s\n", isin, ISINtest(isin) ? "valid" : "not valid");
    }
 
    static boolean ISINtest(String isin) {
        isin = isin.trim().toUpperCase();
 
        if (!isin.matches("^[A-Z]{2}[A-Z0-9]{9}\\d$"))
            return false;
 
        StringBuilder sb = new StringBuilder();
        for (char c : isin.substring(0, 12).toCharArray())
            sb.append(Character.digit(c, 36));
 
        return luhnTest(sb.toString());
    }

    static boolean luhnTest(String number) {
        int s1 = 0, s2 = 0;
        String reverse = new StringBuffer(number).reverse().toString();
        for (int i = 0; i < reverse.length(); i++){
            int digit = Character.digit(reverse.charAt(i), 10);
            
            if (i % 2 == 0){
                s1 += digit;
            } else { 
                s2 += 2 * digit;
                if(digit >= 5){
                    s2 -= 9;
                }
            }
        }
        return (s1 + s2) % 10 == 0;
    }
}






Fortran: program isin
    use ctype
    implicit none
    character(20) :: test(7) = ["US0378331005        ", &
                                "US0373831005        ", &
                                "U50378331005        ", &
                                "US03378331005       ", &
                                "AU0000XVGZA3        ", &
                                "AU0000VXGZA3        ", &
                                "FR0000988040        "]
    print *, check_isin(test)
contains
    elemental logical function check_isin(a)
        character(*), intent(in) :: a
        integer :: s(24)
        integer :: i, j, k, n, v

        check_isin = .false.

        n = len_trim(a)
        if (n /= 12) return
        
        
        j = 0
        do i = 1, n
            k = iachar(a(i:i))
            if (k >= 48 .and. k <= 57) then
                if (i < 3) return
                k = k - 48
                j = j + 1
                s(j) = k
            else if (k >= 65 .and. k <= 90) then
                if (i == 12) return
                k = k - 65 + 10
                j = j + 1
                s(j) = k / 10
                j = j + 1
                s(j) = mod(k, 10)
            else
                return
            end if
        end do

        
        v = 0
        do i = j - 1, 1, -2
            k = 2 * s(i)
            if (k > 9) k = k - 9
            v = v + k
        end do
        do i = j, 1, -2
            v = v + s(i)
        end do
        
        check_isin = 0 == mod(v, 10)
    end function
end program
Task: Input_Output for pairs of numbers





Java: import java.util.Scanner;

public class Main {

	public static int doStuff(int a, int b){
	    int sum = a+b;
	    return sum;
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);

		int n = in.nextInt();
		for(int i=0; i<n; i++){
			int a = in.nextInt();
			int b= in.nextInt();
			int result = doStuff(a, b);
			System.out.println(result);
		}
	}
}






Fortran: program i_o_pairs
  implicit none

  integer :: npairs
  integer :: i
  integer, allocatable :: pairs(:,:)

  read(*,*) npairs
  allocate(pairs(npairs,2))
 
  do i = 1, npairs
    read(*,*) pairs(i,:)
  end do
  write(*, "(i0)") sum(pairs, 2)

end program
Task: Kahan summation





Java: public class KahanSummation {
    private static float kahanSum(float... fa) {
        float sum = 0.0f;
        float c = 0.0f;
        for (float f : fa) {
            float y = f - c;
            float t = sum + y;
            c = (t - sum) - y;
            sum = t;
        }
        return sum;
    }

    private static float epsilon() {
        float eps = 1.0f;
        while (1.0f + eps != 1.0f) eps /= 2.0f;
        return eps;
    }

    public static void main(String[] args) {
        float a = 1.0f;
        float b = epsilon();
        float c = -b;
        System.out.println("Epsilon      = " + b);
        System.out.println("(a + b) + c  = " + ((a + b) + c));
        System.out.println("Kahan sum    = " + kahanSum(a, b, c));
    }
}






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: Two identical strings





Java: public class TwoIdenticalStrings {
    public static void main(String[] args) {
        System.out.println("Decimal Binary");
        for (int i = 0; i < 1_000; i++) {
            String binStr = Integer.toBinaryString(i);
            if (binStr.length() % 2 == 0) {
                int len = binStr.length() / 2;
                if (binStr.substring(0, len).equals(binStr.substring(len))) {
                    System.out.printf("%7d %s%n", i, binStr);
                }
            }
        }
    }
}






Fortran:       program IdentStr
          implicit none
          integer n, concat, bits
          
          n = 1
  100     if (concat(n) .lt. 1000) then
              write (*,'(I3,2X,I11)') concat(n), bits(concat(n))
              n = n + 1
              goto 100
          end if
          stop
      end

C     Concatenate binary representation of number with itself      
      integer function concat(num)
          integer num, sl, sr
          sl = num
          sr = num
  100     if (sr .gt. 0) then
              sl = sl * 2
              sr = sr / 2
              goto 100
          end if
          concat = num + sl
      end

C     Calculate binary representation of number
      integer function bits(num)
          integer num, n, bx
          n = num
          bits = 0
          bx = 1
  100     if (n .gt. 0) then
              bits = bits + bx * mod(n,2)
              bx = bx * 10
              n = n / 2
              goto 100
          end if
      end
Task: Verify distribution uniformity_Chi-squared test





Java: import static java.lang.Math.pow;
import java.util.Arrays;
import static java.util.Arrays.stream;
import org.apache.commons.math3.special.Gamma;

public class Test {

    static double x2Dist(double[] data) {
        double avg = stream(data).sum() / data.length;
        double sqs = stream(data).reduce(0, (a, b) -> a + pow((b - avg), 2));
        return sqs / avg;
    }

    static double x2Prob(double dof, double distance) {
        return Gamma.regularizedGammaQ(dof / 2, distance / 2);
    }

    static boolean x2IsUniform(double[] data, double significance) {
        return x2Prob(data.length - 1.0, x2Dist(data)) > significance;
    }

    public static void main(String[] a) {
        double[][] dataSets = {{199809, 200665, 199607, 200270, 199649},
        {522573, 244456, 139979, 71531, 21461}};

        System.out.printf(" %4s %12s  %12s %8s   %s%n",
                "dof", "distance", "probability", "Uniform?", "dataset");

        for (double[] ds : dataSets) {
            int dof = ds.length - 1;
            double dist = x2Dist(ds);
            double prob = x2Prob(dof, dist);
            System.out.printf("%4d %12.3f  %12.8f    %5s    %6s%n",
                    dof, dist, prob, x2IsUniform(ds, 0.05) ? "YES" : "NO",
                    Arrays.toString(ds));
        }
    }
}






Fortran: module gsl_mini_bind_m

    use iso_c_binding
    implicit none
    private

    public :: p_value

    interface
        function gsl_cdf_chisq_q(x, nu) bind(c, name='gsl_cdf_chisq_Q')
            import
            real(c_double), value :: x
            real(c_double), value :: nu
            real(c_double) :: gsl_cdf_chisq_q
        end function gsl_cdf_chisq_q
    end interface

contains

    
    real function p_value(x, df)
        real, intent(in) :: x
        integer, intent(in) :: df

        p_value = real(gsl_cdf_chisq_q(real(x, c_double), real(df, c_double)))

    end function p_value

end module gsl_mini_bind_m
Task: CSV to HTML translation





Java: 

grammar csv2html;
dialog : {System.out.println("<HTML><Table>");}header body+{System.out.println("</Table></HTML>");} ;
header : {System.out.println("<THEAD align=\"center\"><TR bgcolor=\"blue\">");}row{System.out.println("</TR></THEAD");};
body   : {System.out.println("<TBODY><TR>");}row{System.out.println("</TR></TBODY");};
row    : field ',' field '\r'? '\n';
field  : Field{System.out.println("<TD>" + $Field.text.replace("<","&lt;").replace(">","&gt;") + "</TD>");};
Field  : ~[,\n\r]+;






Fortran:       SUBROUTINE CSVTEXT2HTML(FNAME,HEADED)	
Converts without checking field counts, or noting special characters.
       CHARACTER*(*) FNAME	
       LOGICAL HEADED		
       INTEGER MANY		
       PARAMETER (MANY=666)	
       CHARACTER*(MANY) ALINE	
       INTEGER MARK(0:MANY + 1)	
       INTEGER I,L,N		
       CHARACTER*2 WOT(2)	
       PARAMETER (WOT = (/"th","td"/))	
       INTEGER IT		
       INTEGER KBD,MSG,IN		
       COMMON /IOUNITS/ KBD,MSG,IN	
        OPEN(IN,FILE=FNAME,STATUS="OLD",ACTION="READ",ERR=661)	
        WRITE (MSG,1)			
    1   FORMAT ("<Table border=1>")	
        MARK(0) = 0		
        N = 0			

   10   READ (IN,11,END = 20) L,ALINE(1:MIN(L,MANY))	
   11   FORMAT (Q,A)		
        N = N + 1		
        IF (L.GT.MANY) THEN	
          WRITE (MSG,12) N,L,MANY	
   12     FORMAT ("Line ",I0," has length ",I0,"
          L = MANY			
        END IF			
        IF (N.EQ.1 .AND. HEADED) THEN	
          WRITE (MSG,*) "<tHead>"	
          IT = 1			
         ELSE				
          IT = 2			
        END IF			
        NCOLS = 0		
        DO I = 1,L		
          IF (ICHAR(ALINE(I:I)).EQ.ICHAR(",")) THEN	
            NCOLS = NCOLS + 1		
            MARK(NCOLS) = I		
          END IF			
        END DO			
        NCOLS = NCOLS + 1	
        MARK(NCOLS) = L + 1	
        WRITE (MSG,13)		
     1   (WOT(IT),				
     2    ALINE(MARK(I - 1) + 1:MARK(I) - 1),	
     3    WOT(IT),				
     4    I = 1,NCOLS),			
     5   "/tr"			
   13   FORMAT (" <tr>",666("<",A,">",A,"</",A,">"))	
        IF (N.EQ.1 .AND. HEADED) WRITE (MSG,*) "</tHead>"	
        GO TO 10		

   20   CLOSE (IN)		
        WRITE (MSG,21)		
   21   FORMAT ("</Table>")	
       RETURN			
Confusions.
  661   WRITE (MSG,*) "Can't open file ",FNAME	
      END			

      INTEGER KBD,MSG,IN
      COMMON /IOUNITS/ KBD,MSG,IN
      KBD = 5	
      MSG = 6	
      IN = 10	

      CALL CSVTEXT2HTML("Text.csv",.FALSE.)	
      WRITE (MSG,*)
      CALL CSVTEXT2HTML("Text.csv",.TRUE.)	
      END