WeixiangYan/CodeTransOcean huggingface dataset:
Task: Call a function in a shared library



C#: using System.Runtime.InteropServices;

class Program {
    [DllImport("fakelib.dll")]
    public static extern int fakefunction(int args);

    static void Main(string[] args) {
        int r = fakefunction(10);
    }
}








Fortran: function  add_nf(a,b) bind(c, name='add_nf')
use, intrinsic :: iso_c_binding
implicit none
real(c_double), intent(in) :: a,b
real(c_double) :: add_nf

add_nf = a + b
end function add_nf
Task: Call a function in a shared library

C: #include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

int myopenimage(const char *in)
{
  static int handle=0;
  fprintf(stderr, "internal openimage opens %s...\n", in);
  return handle++;
}

int main()
{
  void *imglib;
  int (*extopenimage)(const char *);
  int imghandle;

  imglib = dlopen("./fakeimglib.so", RTLD_LAZY);
  if ( imglib != NULL ) {
    
    *(void **)(&extopenimage) = dlsym(imglib, "openimage");
    
    
    imghandle = extopenimage("fake.img");
  } else {
    imghandle = myopenimage("fake.img");
  }
  printf("opened with handle %d\n", imghandle);
  
  if (imglib != NULL ) dlclose(imglib);
  return EXIT_SUCCESS;
}










Fortran: function  add_nf(a,b) bind(c, name='add_nf')
use, intrinsic :: iso_c_binding
implicit none
real(c_double), intent(in) :: a,b
real(c_double) :: add_nf

add_nf = a + b
end function add_nf
Task: Call a function in a shared library





Java: 

import java.util.Collections;
import java.util.Random;

public class TrySort {
    static boolean useC;
    static {
	try {
	    System.loadLibrary("TrySort");
	    useC = true;
	} catch(UnsatisfiedLinkError e) {
	    useC = false;
	}
    }
    
    static native void sortInC(int[] ary);
    
    static class IntList extends java.util.AbstractList<Integer> {
	int[] ary;
	IntList(int[] ary) { this.ary = ary; }
	public Integer get(int i) { return ary[i]; }
	public Integer set(int i, Integer j) {
	    Integer o = ary[i]; ary[i] = j; return o;
	}
	public int size() { return ary.length; }
    }

    static class ReverseAbsCmp
	implements java.util.Comparator<Integer>
    {
	public int compare(Integer pa, Integer pb) {
	    
	    int a = pa > 0 ? -pa : pa;
	    int b = pb > 0 ? -pb : pb;
	    return a < b ? -1 : a > b ? 1 : 0;
	}
    }
    
    static void sortInJava(int[] ary) {
	Collections.sort(new IntList(ary), new ReverseAbsCmp());
    }

    public static void main(String[] args) {
	
	int[] ary = new int[1000000];
	Random rng = new Random();
	for (int i = 0; i < ary.length; i++)
	    ary[i] = rng.nextInt();

	
	if (useC) {
	    System.out.print("Sorting in C...  ");
	    sortInC(ary);
	} else {
	    System.out.print
		("Missing library for C!  Sorting in Java...  ");
	    sortInJava(ary);
	}

	for (int i = 0; i < ary.length - 1; i++) {
	    int a = ary[i];
	    int b = ary[i + 1];
	    if ((a > 0 ? -a : a) > (b > 0 ? -b : b)) {
		System.out.println("*BUG IN SORT*");
		System.exit(1);
	    }
	}
	System.out.println("ok");
    }
}






Fortran: function  add_nf(a,b) bind(c, name='add_nf')
use, intrinsic :: iso_c_binding
implicit none
real(c_double), intent(in) :: a,b
real(c_double) :: add_nf

add_nf = a + b
end function add_nf
Task: Call a function in a shared library







Python: import ctypes
  
user32_dll = ctypes.cdll.LoadLibrary('User32.dll')
print user32_dll.GetDoubleClickTime()




Fortran: function  add_nf(a,b) bind(c, name='add_nf')
use, intrinsic :: iso_c_binding
implicit none
real(c_double), intent(in) :: a,b
real(c_double) :: add_nf

add_nf = a + b
end function add_nf
Task: Call a function in a shared library








VB: Declare Dynamic Library "Kernel32"
    Sub SetLastError (ByVal dwErr As Long)
    Function GetLastError& ()
End Declare

SetLastError 20
Print GetLastError



Fortran: function  add_nf(a,b) bind(c, name='add_nf')
use, intrinsic :: iso_c_binding
implicit none
real(c_double), intent(in) :: a,b
real(c_double) :: add_nf

add_nf = a + b
end function add_nf
Task: Call a function in a shared library

C: #include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

int myopenimage(const char *in)
{
  static int handle=0;
  fprintf(stderr, "internal openimage opens %s...\n", in);
  return handle++;
}

int main()
{
  void *imglib;
  int (*extopenimage)(const char *);
  int imghandle;

  imglib = dlopen("./fakeimglib.so", RTLD_LAZY);
  if ( imglib != NULL ) {
    
    *(void **)(&extopenimage) = dlsym(imglib, "openimage");
    
    
    imghandle = extopenimage("fake.img");
  } else {
    imghandle = myopenimage("fake.img");
  }
  printf("opened with handle %d\n", imghandle);
  
  if (imglib != NULL ) dlclose(imglib);
  return EXIT_SUCCESS;
}









COBOL:        identification division.
       program-id. callsym.

       data division.
       working-storage section.
       01 handle usage pointer.
       01 addr   usage program-pointer.

       procedure division.
       call "dlopen" using
           by reference null
           by value 1
           returning handle
           on exception
               display function exception-statement upon syserr
               goback
       end-call
       if handle equal null then
           display function module-id ": error getting dlopen handle"
             upon syserr
           goback
       end-if

       call "dlsym" using
           by value handle
           by content z"perror"
           returning addr
       end-call
       if addr equal null then
           display function module-id ": error getting perror symbol"
              upon syserr
       else
           call addr returning omitted
       end-if

       goback.
       end program callsym.
Task: Call a function in a shared library



C#: using System.Runtime.InteropServices;

class Program {
    [DllImport("fakelib.dll")]
    public static extern int fakefunction(int args);

    static void Main(string[] args) {
        int r = fakefunction(10);
    }
}







COBOL:        identification division.
       program-id. callsym.

       data division.
       working-storage section.
       01 handle usage pointer.
       01 addr   usage program-pointer.

       procedure division.
       call "dlopen" using
           by reference null
           by value 1
           returning handle
           on exception
               display function exception-statement upon syserr
               goback
       end-call
       if handle equal null then
           display function module-id ": error getting dlopen handle"
             upon syserr
           goback
       end-if

       call "dlsym" using
           by value handle
           by content z"perror"
           returning addr
       end-call
       if addr equal null then
           display function module-id ": error getting perror symbol"
              upon syserr
       else
           call addr returning omitted
       end-if

       goback.
       end program callsym.
Task: Call a function in a shared library





Java: 

import java.util.Collections;
import java.util.Random;

public class TrySort {
    static boolean useC;
    static {
	try {
	    System.loadLibrary("TrySort");
	    useC = true;
	} catch(UnsatisfiedLinkError e) {
	    useC = false;
	}
    }
    
    static native void sortInC(int[] ary);
    
    static class IntList extends java.util.AbstractList<Integer> {
	int[] ary;
	IntList(int[] ary) { this.ary = ary; }
	public Integer get(int i) { return ary[i]; }
	public Integer set(int i, Integer j) {
	    Integer o = ary[i]; ary[i] = j; return o;
	}
	public int size() { return ary.length; }
    }

    static class ReverseAbsCmp
	implements java.util.Comparator<Integer>
    {
	public int compare(Integer pa, Integer pb) {
	    
	    int a = pa > 0 ? -pa : pa;
	    int b = pb > 0 ? -pb : pb;
	    return a < b ? -1 : a > b ? 1 : 0;
	}
    }
    
    static void sortInJava(int[] ary) {
	Collections.sort(new IntList(ary), new ReverseAbsCmp());
    }

    public static void main(String[] args) {
	
	int[] ary = new int[1000000];
	Random rng = new Random();
	for (int i = 0; i < ary.length; i++)
	    ary[i] = rng.nextInt();

	
	if (useC) {
	    System.out.print("Sorting in C...  ");
	    sortInC(ary);
	} else {
	    System.out.print
		("Missing library for C!  Sorting in Java...  ");
	    sortInJava(ary);
	}

	for (int i = 0; i < ary.length - 1; i++) {
	    int a = ary[i];
	    int b = ary[i + 1];
	    if ((a > 0 ? -a : a) > (b > 0 ? -b : b)) {
		System.out.println("*BUG IN SORT*");
		System.exit(1);
	    }
	}
	System.out.println("ok");
    }
}





COBOL:        identification division.
       program-id. callsym.

       data division.
       working-storage section.
       01 handle usage pointer.
       01 addr   usage program-pointer.

       procedure division.
       call "dlopen" using
           by reference null
           by value 1
           returning handle
           on exception
               display function exception-statement upon syserr
               goback
       end-call
       if handle equal null then
           display function module-id ": error getting dlopen handle"
             upon syserr
           goback
       end-if

       call "dlsym" using
           by value handle
           by content z"perror"
           returning addr
       end-call
       if addr equal null then
           display function module-id ": error getting perror symbol"
              upon syserr
       else
           call addr returning omitted
       end-if

       goback.
       end program callsym.
Task: Call a function in a shared library







Python: import ctypes
  
user32_dll = ctypes.cdll.LoadLibrary('User32.dll')
print user32_dll.GetDoubleClickTime()



COBOL:        identification division.
       program-id. callsym.

       data division.
       working-storage section.
       01 handle usage pointer.
       01 addr   usage program-pointer.

       procedure division.
       call "dlopen" using
           by reference null
           by value 1
           returning handle
           on exception
               display function exception-statement upon syserr
               goback
       end-call
       if handle equal null then
           display function module-id ": error getting dlopen handle"
             upon syserr
           goback
       end-if

       call "dlsym" using
           by value handle
           by content z"perror"
           returning addr
       end-call
       if addr equal null then
           display function module-id ": error getting perror symbol"
              upon syserr
       else
           call addr returning omitted
       end-if

       goback.
       end program callsym.
Task: Call a function in a shared library








VB: Declare Dynamic Library "Kernel32"
    Sub SetLastError (ByVal dwErr As Long)
    Function GetLastError& ()
End Declare

SetLastError 20
Print GetLastError


COBOL:        identification division.
       program-id. callsym.

       data division.
       working-storage section.
       01 handle usage pointer.
       01 addr   usage program-pointer.

       procedure division.
       call "dlopen" using
           by reference null
           by value 1
           returning handle
           on exception
               display function exception-statement upon syserr
               goback
       end-call
       if handle equal null then
           display function module-id ": error getting dlopen handle"
             upon syserr
           goback
       end-if

       call "dlsym" using
           by value handle
           by content z"perror"
           returning addr
       end-call
       if addr equal null then
           display function module-id ": error getting perror symbol"
              upon syserr
       else
           call addr returning omitted
       end-if

       goback.
       end program callsym.
Task: Call a function in a shared library




Go: package main


import "C"
import (
    "fmt"
    "os"
    "unsafe"
)

var handle = -1

func myOpenImage(s string) int {
    fmt.Fprintf(os.Stderr, "internal openImage opens %s...\n", s)
    handle++
    return handle
}

func main() {
    libpath := C.CString("./fakeimglib.so")
    defer C.free(unsafe.Pointer(libpath))
    imglib := C.dlopen(libpath, C.RTLD_LAZY)
    var imghandle int
    if imglib != nil {
        openimage := C.CString("openimage")
        defer C.free(unsafe.Pointer(openimage))
        fp := C.dlsym(imglib, openimage)
        if fp != nil {
            fi := C.CString("fake.img")
            defer C.free(unsafe.Pointer(fi))
            imghandle = int(C.bridge_someFunc(C.someFunc(fp), fi))

        } else {
            imghandle = myOpenImage("fake.img")
        }
        C.dlclose(imglib)
    } else {
        imghandle = myOpenImage("fake.img")
    }
    fmt.Printf("opened with handle %d\n", imghandle)
}






COBOL:        identification division.
       program-id. callsym.

       data division.
       working-storage section.
       01 handle usage pointer.
       01 addr   usage program-pointer.

       procedure division.
       call "dlopen" using
           by reference null
           by value 1
           returning handle
           on exception
               display function exception-statement upon syserr
               goback
       end-call
       if handle equal null then
           display function module-id ": error getting dlopen handle"
             upon syserr
           goback
       end-if

       call "dlsym" using
           by value handle
           by content z"perror"
           returning addr
       end-call
       if addr equal null then
           display function module-id ": error getting perror symbol"
              upon syserr
       else
           call addr returning omitted
       end-if

       goback.
       end program callsym.
Task: Reduced row echelon form



C#: using System;

namespace rref
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] matrix = new int[3, 4]{
                {  1, 2, -1,  -4 },
                {  2, 3, -1, -11 },
                { -2, 0, -3,  22 }
            };
            matrix = rref(matrix);   
        }

        private static int[,] rref(int[,] matrix)
        {            
            int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1);
            for (int r = 0; r < rowCount; r++)
            {
                if (columnCount <= lead) break;
                int i = r;
                while (matrix[i, lead] == 0)
                {
                    i++;
                    if (i == rowCount)
                    {
                        i = r;
                        lead++;
                        if (columnCount == lead)
                        {
                        lead--;
                        break;
                        }
                    }
                }
                for (int j = 0; j < columnCount; j++)
                {
                    int temp = matrix[r, j];
                    matrix[r, j] = matrix[i, j];
                    matrix[i, j] = temp;
                }
                int div = matrix[r, lead];
                if(div != 0)
                    for (int j = 0; j < columnCount; j++) matrix[r, j] /= div;                
                for (int j = 0; j < rowCount; j++)
                {
                    if (j != r)
                    {
                        int sub = matrix[j, lead];
                        for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]);
                    }
                }
                lead++;
            }
            return matrix;
        }
    }
}









Ada: generic
   type Element_Type is private;
   Zero : Element_Type;
   with function "-" (Left, Right : in Element_Type) return Element_Type is <>;
   with function "*" (Left, Right : in Element_Type) return Element_Type is <>;
   with function "/" (Left, Right : in Element_Type) return Element_Type is <>;
package Matrices is
   type Matrix is
     array (Positive range <>, Positive range <>) of Element_Type;
   function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
end Matrices;
Task: Reduced row echelon form




Go: package main

import "fmt"

type matrix [][]float64

func (m matrix) print() {
    for _, r := range m {
        fmt.Println(r)
    }
    fmt.Println("")
}

func main() {
    m := matrix{
        { 1, 2, -1,  -4},
        { 2, 3, -1, -11},
        {-2, 0, -3,  22},
    }
    m.print()
    rref(m)
    m.print()
}

func rref(m matrix) {
    lead := 0
    rowCount := len(m)
    columnCount := len(m[0])
    for r := 0; r < rowCount; r++ {
        if lead >= columnCount {
            return
        }
        i := r
        for m[i][lead] == 0 {
            i++
            if rowCount == i {
                i = r
                lead++
                if columnCount == lead {
                    return
                }
            }
        }
        m[i], m[r] = m[r], m[i]
        f := 1 / m[r][lead]
        for j, _ := range m[r] {
            m[r][j] *= f
        }
        for i = 0; i < rowCount; i++ {
            if i != r {
                f = m[i][lead]
                for j, e := range m[r] {
                    m[i][j] -= e * f
                }
            }
        }
        lead++
    }
}








Ada: generic
   type Element_Type is private;
   Zero : Element_Type;
   with function "-" (Left, Right : in Element_Type) return Element_Type is <>;
   with function "*" (Left, Right : in Element_Type) return Element_Type is <>;
   with function "/" (Left, Right : in Element_Type) return Element_Type is <>;
package Matrices is
   type Matrix is
     array (Positive range <>, Positive range <>) of Element_Type;
   function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
end Matrices;
Task: Reduced row echelon form







Python: def ToReducedRowEchelonForm( M):
    if not M: return
    lead = 0
    rowCount = len(M)
    columnCount = len(M[0])
    for r in range(rowCount):
        if lead >= columnCount:
            return
        i = r
        while M[i][lead] == 0:
            i += 1
            if i == rowCount:
                i = r
                lead += 1
                if columnCount == lead:
                    return
        M[i],M[r] = M[r],M[i]
        lv = M[r][lead]
        M[r] = [ mrx / float(lv) for mrx in M[r]]
        for i in range(rowCount):
            if i != r:
                lv = M[i][lead]
                M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
        lead += 1


mtx = [
   [ 1, 2, -1, -4],
   [ 2, 3, -1, -11],
   [-2, 0, -3, 22],]

ToReducedRowEchelonForm( mtx )

for rw in mtx:
  print ', '.join( (str(rv) for rv in rw) )





Ada: generic
   type Element_Type is private;
   Zero : Element_Type;
   with function "-" (Left, Right : in Element_Type) return Element_Type is <>;
   with function "*" (Left, Right : in Element_Type) return Element_Type is <>;
   with function "/" (Left, Right : in Element_Type) return Element_Type is <>;
package Matrices is
   type Matrix is
     array (Positive range <>, Positive range <>) of Element_Type;
   function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
end Matrices;
Task: Reduced row echelon form








VB: Private Function ToReducedRowEchelonForm(M As Variant) As Variant
    Dim lead As Integer: lead = 0
    Dim rowCount As Integer: rowCount = UBound(M)
    Dim columnCount As Integer: columnCount = UBound(M(0))
    Dim i As Integer
    For r = 0 To rowCount
        If lead >= columnCount Then
            Exit For
        End If
        i = r
        Do While M(i)(lead) = 0
            i = i + 1
            If i = rowCount Then
                i = r
                lead = lead + 1
                If lead = columnCount Then
                    Exit For
                End If
            End If
        Loop
        Dim tmp As Variant
        tmp = M(r)
        M(r) = M(i)
        M(i) = tmp
        If M(r)(lead) <> 0 Then
            div = M(r)(lead)
            For t = LBound(M(r)) To UBound(M(r))
                M(r)(t) = M(r)(t) / div
            Next t
        End If
        For j = 0 To rowCount
            If j <> r Then
                subt = M(j)(lead)
                For t = LBound(M(j)) To UBound(M(j))
                    M(j)(t) = M(j)(t) - subt * M(r)(t)
                Next t
            End If
        Next j
        lead = lead + 1
    Next r
    ToReducedRowEchelonForm = M
End Function
 
Public Sub main()
    r = ToReducedRowEchelonForm(Array( _
        Array(1, 2, -1, -4), _
        Array(2, 3, -1, -11), _
        Array(-2, 0, -3, 22)))
    For i = LBound(r) To UBound(r)
        Debug.Print Join(r(i), vbTab)
    Next i
End Sub




Ada: generic
   type Element_Type is private;
   Zero : Element_Type;
   with function "-" (Left, Right : in Element_Type) return Element_Type is <>;
   with function "*" (Left, Right : in Element_Type) return Element_Type is <>;
   with function "/" (Left, Right : in Element_Type) return Element_Type is <>;
package Matrices is
   type Matrix is
     array (Positive range <>, Positive range <>) of Element_Type;
   function Reduced_Row_Echelon_form (Source : Matrix) return Matrix;
end Matrices;
Task: Reduced row echelon form



C#: using System;

namespace rref
{
    class Program
    {
        static void Main(string[] args)
        {
            int[,] matrix = new int[3, 4]{
                {  1, 2, -1,  -4 },
                {  2, 3, -1, -11 },
                { -2, 0, -3,  22 }
            };
            matrix = rref(matrix);   
        }

        private static int[,] rref(int[,] matrix)
        {            
            int lead = 0, rowCount = matrix.GetLength(0), columnCount = matrix.GetLength(1);
            for (int r = 0; r < rowCount; r++)
            {
                if (columnCount <= lead) break;
                int i = r;
                while (matrix[i, lead] == 0)
                {
                    i++;
                    if (i == rowCount)
                    {
                        i = r;
                        lead++;
                        if (columnCount == lead)
                        {
                        lead--;
                        break;
                        }
                    }
                }
                for (int j = 0; j < columnCount; j++)
                {
                    int temp = matrix[r, j];
                    matrix[r, j] = matrix[i, j];
                    matrix[i, j] = temp;
                }
                int div = matrix[r, lead];
                if(div != 0)
                    for (int j = 0; j < columnCount; j++) matrix[r, j] /= div;                
                for (int j = 0; j < rowCount; j++)
                {
                    if (j != r)
                    {
                        int sub = matrix[j, lead];
                        for (int k = 0; k < columnCount; k++) matrix[j, k] -= (sub * matrix[r, k]);
                    }
                }
                lead++;
            }
            return matrix;
        }
    }
}
Task: Reduced row echelon form







Python: def ToReducedRowEchelonForm( M):
    if not M: return
    lead = 0
    rowCount = len(M)
    columnCount = len(M[0])
    for r in range(rowCount):
        if lead >= columnCount:
            return
        i = r
        while M[i][lead] == 0:
            i += 1
            if i == rowCount:
                i = r
                lead += 1
                if columnCount == lead:
                    return
        M[i],M[r] = M[r],M[i]
        lv = M[r][lead]
        M[r] = [ mrx / float(lv) for mrx in M[r]]
        for i in range(rowCount):
            if i != r:
                lv = M[i][lead]
                M[i] = [ iv - lv*rv for rv,iv in zip(M[r],M[i])]
        lead += 1


mtx = [
   [ 1, 2, -1, -4],
   [ 2, 3, -1, -11],
   [-2, 0, -3, 22],]

ToReducedRowEchelonForm( mtx )

for rw in mtx:
  print ', '.join( (str(rv) for rv in rw) )