WeixiangYan/CodeTransOcean huggingface dataset:
Task: Continued fraction_Arithmetic_Construct from rational number





Java: import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ConstructFromRationalNumber {
    private static class R2cf implements Iterator<Integer> {
        private int num;
        private int den;

        R2cf(int num, int den) {
            this.num = num;
            this.den = den;
        }

        @Override
        public boolean hasNext() {
            return den != 0;
        }

        @Override
        public Integer next() {
            int div = num / den;
            int rem = num % den;
            num = den;
            den = rem;
            return div;
        }
    }

    private static void iterate(R2cf generator) {
        generator.forEachRemaining(n -> System.out.printf("%d ", n));
        System.out.println();
    }

    public static void main(String[] args) {
        List<Map.Entry<Integer, Integer>> fracs = List.of(
                Map.entry(1, 2),
                Map.entry(3, 1),
                Map.entry(23, 8),
                Map.entry(13, 11),
                Map.entry(22, 7),
                Map.entry(-151, 77)
        );
        for (Map.Entry<Integer, Integer> frac : fracs) {
            System.out.printf("%4d / %-2d = ", frac.getKey(), frac.getValue());
            iterate(new R2cf(frac.getKey(), frac.getValue()));
        }

        System.out.println("\nSqrt(2) ->");
        List<Map.Entry<Integer, Integer>> root2 = List.of(
                Map.entry(    14_142,     10_000),
                Map.entry(   141_421,    100_000),
                Map.entry( 1_414_214,  1_000_000),
                Map.entry(14_142_136, 10_000_000)
        );
        for (Map.Entry<Integer, Integer> frac : root2) {
            System.out.printf("%8d / %-8d = ", frac.getKey(), frac.getValue());
            iterate(new R2cf(frac.getKey(), frac.getValue()));
        }

        System.out.println("\nPi ->");
        List<Map.Entry<Integer, Integer>> pi = List.of(
                Map.entry(         31,        10),
                Map.entry(        314,       100),
                Map.entry(      3_142,      1_000),
                Map.entry(     31_428,     10_000),
                Map.entry(    314_285,    100_000),
                Map.entry(  3_142_857,   1_000_000),
                Map.entry( 31_428_571,  10_000_000),
                Map.entry(314_285_714, 100_000_000)
        );
        for (Map.Entry<Integer, Integer> frac : pi) {
            System.out.printf("%9d / %-9d = ", frac.getKey(), frac.getValue());
            iterate(new R2cf(frac.getKey(), frac.getValue()));
        }
    }
}
Task: Continued fraction_Arithmetic_Construct from rational number







Python: def r2cf(n1,n2):
  while n2:
    n1, (t1, n2) = n2, divmod(n1, n2)
    yield t1

print(list(r2cf(1,2)))    
print(list(r2cf(3,1)))    
print(list(r2cf(23,8)))    
print(list(r2cf(13,11)))    
print(list(r2cf(22,7)))    
print(list(r2cf(14142,10000)))    
print(list(r2cf(141421,100000)))    
print(list(r2cf(1414214,1000000)))    
print(list(r2cf(14142136,10000000)))
Task: Continued fraction_Arithmetic_Construct from rational number




Go: package cf

import (
	"fmt"
	"strings"
)


type ContinuedFraction func() NextFn



type NextFn func() (term int64, ok bool)




func (cf ContinuedFraction) String() string {
	var buf strings.Builder
	buf.WriteByte('[')
	sep := "; "
	const maxTerms = 20
	next := cf()
	for n := 0; ; n++ {
		t, ok := next()
		if !ok {
			break
		}
		if n > 0 {
			buf.WriteString(sep)
			sep = ", "
		}
		if n >= maxTerms {
			buf.WriteString("...")
			break
		}
		fmt.Fprint(&buf, t)
	}
	buf.WriteByte(']')
	return buf.String()
}


func Sqrt2() NextFn {
	first := true
	return func() (int64, bool) {
		if first {
			first = false
			return 1, true
		}
		return 2, true
	}
}


func Phi() NextFn {
	return func() (int64, bool) { return 1, true }
}



func E() NextFn {
	var i int
	return func() (int64, bool) {
		i++
		switch {
		case i == 1:
			return 2, true
		case i%3 == 0:
			return int64(i/3) * 2, true
		default:
			return 1, true
		}
	}
}
Task: Empty directory



C#: using System;
using System.IO;

class Program
{
    static void Main( string[] args )
    {
        foreach ( string dir in args )
        {
            Console.WriteLine( "'{0}' {1} empty", dir, IsDirectoryEmpty( dir ) ? "is" : "is not" );
        }
    }

    private static bool IsDirectoryEmpty( string dir )
    {
        return ( Directory.GetFiles( dir ).Length == 0 &&
            Directory.GetDirectories( dir ).Length == 0 );
    }
}









Ada: with Ada.Text_IO; use Ada.Text_IO;
with Ada.Directories;
procedure EmptyDir is
   function Empty (path : String) return String is
      use Ada.Directories;
      result : String := "Is empty.";
      procedure check (ent : Directory_Entry_Type) is begin
         if Simple_Name (ent) /= "." and Simple_Name (ent) /= ".." then
            Empty.result := "Not empty";
         end if;
      end check;
   begin
      if not Exists (path) then return "Does not exist.";
      elsif Kind (path) /= Directory then return "Not a Directory.";
      end if;
      Search (path, "", Process => check'Access);
      return result;
   end Empty;
begin
   Put_Line (Empty ("."));
   Put_Line (Empty ("./empty"));
   Put_Line (Empty ("./emptydir.adb"));
   Put_Line (Empty ("./foobar"));
end EmptyDir;
Task: Empty directory

C: #include <stdio.h>
#include <dirent.h>
#include <string.h>

int dir_empty(const char *path)
{
	struct dirent *ent;
	int ret = 1;

	DIR *d = opendir(path);
	if (!d) {
		fprintf(stderr, "%s: ", path);
		perror("");
		return -1;
	}

	while ((ent = readdir(d))) {
		if (!strcmp(ent->d_name, ".") || !(strcmp(ent->d_name, "..")))
			continue;
		ret = 0;
		break;
	}

	closedir(d);
	return ret;
}

int main(int c, char **v)
{
	int ret = 0, i;
	if (c < 2) return -1;

	for (i = 1; i < c; i++) {
		ret = dir_empty(v[i]);
		if (ret >= 0)
			printf("%s: %sempty\n", v[i], ret ? "" : "not ");
	}

	return 0;
}











Ada: with Ada.Text_IO; use Ada.Text_IO;
with Ada.Directories;
procedure EmptyDir is
   function Empty (path : String) return String is
      use Ada.Directories;
      result : String := "Is empty.";
      procedure check (ent : Directory_Entry_Type) is begin
         if Simple_Name (ent) /= "." and Simple_Name (ent) /= ".." then
            Empty.result := "Not empty";
         end if;
      end check;
   begin
      if not Exists (path) then return "Does not exist.";
      elsif Kind (path) /= Directory then return "Not a Directory.";
      end if;
      Search (path, "", Process => check'Access);
      return result;
   end Empty;
begin
   Put_Line (Empty ("."));
   Put_Line (Empty ("./empty"));
   Put_Line (Empty ("./emptydir.adb"));
   Put_Line (Empty ("./foobar"));
end EmptyDir;
Task: Empty directory


C++: #include <iostream>
#include <boost/filesystem.hpp>

using namespace boost::filesystem;

int main(int argc, char *argv[])
{
    for (int i = 1; i < argc; ++i) {
        path p(argv[i]);

        if (exists(p) && is_directory(p))
            std::cout << "'" << argv[i] << "' is" << (!is_empty(p) ? " not" : "") << " empty\n";
        else
            std::cout << "dir '" << argv[i] << "' could not be found\n";
    }
}










Ada: with Ada.Text_IO; use Ada.Text_IO;
with Ada.Directories;
procedure EmptyDir is
   function Empty (path : String) return String is
      use Ada.Directories;
      result : String := "Is empty.";
      procedure check (ent : Directory_Entry_Type) is begin
         if Simple_Name (ent) /= "." and Simple_Name (ent) /= ".." then
            Empty.result := "Not empty";
         end if;
      end check;
   begin
      if not Exists (path) then return "Does not exist.";
      elsif Kind (path) /= Directory then return "Not a Directory.";
      end if;
      Search (path, "", Process => check'Access);
      return result;
   end Empty;
begin
   Put_Line (Empty ("."));
   Put_Line (Empty ("./empty"));
   Put_Line (Empty ("./emptydir.adb"));
   Put_Line (Empty ("./foobar"));
end EmptyDir;
Task: Empty directory




Go: package main

import (
	"fmt"
	"io/ioutil"
	"log"
)

func main() {
	empty, err := IsEmptyDir("/tmp")
	if err != nil {
		log.Fatalln(err)
	}
	if empty {
		fmt.Printf("/tmp is empty\n")
	} else {
		fmt.Printf("/tmp is not empty\n")
	}
}

func IsEmptyDir(name string) (bool, error) {
	entries, err := ioutil.ReadDir(name)
	if err != nil {
		return false, err
	}
	return len(entries) == 0, nil
}








Ada: with Ada.Text_IO; use Ada.Text_IO;
with Ada.Directories;
procedure EmptyDir is
   function Empty (path : String) return String is
      use Ada.Directories;
      result : String := "Is empty.";
      procedure check (ent : Directory_Entry_Type) is begin
         if Simple_Name (ent) /= "." and Simple_Name (ent) /= ".." then
            Empty.result := "Not empty";
         end if;
      end check;
   begin
      if not Exists (path) then return "Does not exist.";
      elsif Kind (path) /= Directory then return "Not a Directory.";
      end if;
      Search (path, "", Process => check'Access);
      return result;
   end Empty;
begin
   Put_Line (Empty ("."));
   Put_Line (Empty ("./empty"));
   Put_Line (Empty ("./emptydir.adb"));
   Put_Line (Empty ("./foobar"));
end EmptyDir;
Task: Empty directory





Java: import java.nio.file.Paths;

public static boolean isEmptyDir(String dirName){
    return Paths.get(dirName).toFile().listFiles().length == 0;
}







Ada: with Ada.Text_IO; use Ada.Text_IO;
with Ada.Directories;
procedure EmptyDir is
   function Empty (path : String) return String is
      use Ada.Directories;
      result : String := "Is empty.";
      procedure check (ent : Directory_Entry_Type) is begin
         if Simple_Name (ent) /= "." and Simple_Name (ent) /= ".." then
            Empty.result := "Not empty";
         end if;
      end check;
   begin
      if not Exists (path) then return "Does not exist.";
      elsif Kind (path) /= Directory then return "Not a Directory.";
      end if;
      Search (path, "", Process => check'Access);
      return result;
   end Empty;
begin
   Put_Line (Empty ("."));
   Put_Line (Empty ("./empty"));
   Put_Line (Empty ("./emptydir.adb"));
   Put_Line (Empty ("./foobar"));
end EmptyDir;
Task: Empty directory







Python: import os;
if os.listdir(raw_input("directory")):
    print "not empty"
else:
    print "empty"





Ada: with Ada.Text_IO; use Ada.Text_IO;
with Ada.Directories;
procedure EmptyDir is
   function Empty (path : String) return String is
      use Ada.Directories;
      result : String := "Is empty.";
      procedure check (ent : Directory_Entry_Type) is begin
         if Simple_Name (ent) /= "." and Simple_Name (ent) /= ".." then
            Empty.result := "Not empty";
         end if;
      end check;
   begin
      if not Exists (path) then return "Does not exist.";
      elsif Kind (path) /= Directory then return "Not a Directory.";
      end if;
      Search (path, "", Process => check'Access);
      return result;
   end Empty;
begin
   Put_Line (Empty ("."));
   Put_Line (Empty ("./empty"));
   Put_Line (Empty ("./emptydir.adb"));
   Put_Line (Empty ("./foobar"));
end EmptyDir;
Task: Empty directory








VB: Sub Main()
    Debug.Print IsEmptyDirectory("C:\Temp")
    Debug.Print IsEmptyDirectory("C:\Temp\")
End Sub

Private Function IsEmptyDirectory(D As String) As Boolean
Dim Sep As String
    Sep = Application.PathSeparator
    D = IIf(Right(D, 1) <> Sep, D & Sep, D)
    IsEmptyDirectory = (Dir(D & "*.*") = "")
End Function




Ada: with Ada.Text_IO; use Ada.Text_IO;
with Ada.Directories;
procedure EmptyDir is
   function Empty (path : String) return String is
      use Ada.Directories;
      result : String := "Is empty.";
      procedure check (ent : Directory_Entry_Type) is begin
         if Simple_Name (ent) /= "." and Simple_Name (ent) /= ".." then
            Empty.result := "Not empty";
         end if;
      end check;
   begin
      if not Exists (path) then return "Does not exist.";
      elsif Kind (path) /= Directory then return "Not a Directory.";
      end if;
      Search (path, "", Process => check'Access);
      return result;
   end Empty;
begin
   Put_Line (Empty ("."));
   Put_Line (Empty ("./empty"));
   Put_Line (Empty ("./emptydir.adb"));
   Put_Line (Empty ("./foobar"));
end EmptyDir;
Task: Empty directory

C: #include <stdio.h>
#include <dirent.h>
#include <string.h>

int dir_empty(const char *path)
{
	struct dirent *ent;
	int ret = 1;

	DIR *d = opendir(path);
	if (!d) {
		fprintf(stderr, "%s: ", path);
		perror("");
		return -1;
	}

	while ((ent = readdir(d))) {
		if (!strcmp(ent->d_name, ".") || !(strcmp(ent->d_name, "..")))
			continue;
		ret = 0;
		break;
	}

	closedir(d);
	return ret;
}

int main(int c, char **v)
{
	int ret = 0, i;
	if (c < 2) return -1;

	for (i = 1; i < c; i++) {
		ret = dir_empty(v[i]);
		if (ret >= 0)
			printf("%s: %sempty\n", v[i], ret ? "" : "not ");
	}

	return 0;
}
Task: Empty directory



C#: using System;
using System.IO;

class Program
{
    static void Main( string[] args )
    {
        foreach ( string dir in args )
        {
            Console.WriteLine( "'{0}' {1} empty", dir, IsDirectoryEmpty( dir ) ? "is" : "is not" );
        }
    }

    private static bool IsDirectoryEmpty( string dir )
    {
        return ( Directory.GetFiles( dir ).Length == 0 &&
            Directory.GetDirectories( dir ).Length == 0 );
    }
}
Task: Empty directory


C++: #include <iostream>
#include <boost/filesystem.hpp>

using namespace boost::filesystem;

int main(int argc, char *argv[])
{
    for (int i = 1; i < argc; ++i) {
        path p(argv[i]);

        if (exists(p) && is_directory(p))
            std::cout << "'" << argv[i] << "' is" << (!is_empty(p) ? " not" : "") << " empty\n";
        else
            std::cout << "dir '" << argv[i] << "' could not be found\n";
    }
}
Task: Empty directory





Java: import java.nio.file.Paths;

public static boolean isEmptyDir(String dirName){
    return Paths.get(dirName).toFile().listFiles().length == 0;
}
Task: Empty directory







Python: import os;
if os.listdir(raw_input("directory")):
    print "not empty"
else:
    print "empty"
Task: Empty directory








VB: Sub Main()
    Debug.Print IsEmptyDirectory("C:\Temp")
    Debug.Print IsEmptyDirectory("C:\Temp\")
End Sub

Private Function IsEmptyDirectory(D As String) As Boolean
Dim Sep As String
    Sep = Application.PathSeparator
    D = IIf(Right(D, 1) <> Sep, D & Sep, D)
    IsEmptyDirectory = (Dir(D & "*.*") = "")
End Function
Task: Empty directory




Go: package main

import (
	"fmt"
	"io/ioutil"
	"log"
)

func main() {
	empty, err := IsEmptyDir("/tmp")
	if err != nil {
		log.Fatalln(err)
	}
	if empty {
		fmt.Printf("/tmp is empty\n")
	} else {
		fmt.Printf("/tmp is not empty\n")
	}
}

func IsEmptyDir(name string) (bool, error) {
	entries, err := ioutil.ReadDir(name)
	if err != nil {
		return false, err
	}
	return len(entries) == 0, nil
}
Task: Empty directory






PHP: $dir = 'path_here';

if(is_dir($dir)){

  $list = array_diff(scandir($dir), array('..', '.'));

  if(empty($list)){
    echo 'dir is empty';
  }
  else{
    echo 'dir is not empty';
  }
}
else{
  echo 'not a directory';
}
Task: Empty directory






PHP: $dir = 'path_here';

if(is_dir($dir)){

  $list = array_diff(scandir($dir), array('..', '.'));

  if(empty($list)){
    echo 'dir is empty';
  }
  else{
    echo 'dir is not empty';
  }
}
else{
  echo 'not a directory';
}






Ada: with Ada.Text_IO; use Ada.Text_IO;
with Ada.Directories;
procedure EmptyDir is
   function Empty (path : String) return String is
      use Ada.Directories;
      result : String := "Is empty.";
      procedure check (ent : Directory_Entry_Type) is begin
         if Simple_Name (ent) /= "." and Simple_Name (ent) /= ".." then
            Empty.result := "Not empty";
         end if;
      end check;
   begin
      if not Exists (path) then return "Does not exist.";
      elsif Kind (path) /= Directory then return "Not a Directory.";
      end if;
      Search (path, "", Process => check'Access);
      return result;
   end Empty;
begin
   Put_Line (Empty ("."));
   Put_Line (Empty ("./empty"));
   Put_Line (Empty ("./emptydir.adb"));
   Put_Line (Empty ("./foobar"));
end EmptyDir;
Task: Loops_Wrong ranges

C: #include <stdio.h>

#define TRUE 1
#define FALSE 0

typedef int bool;

typedef struct {
    int start, stop, incr;
    const char *comment;
} S;

S examples[9] = {
    {-2, 2, 1, "Normal"},
    {-2, 2, 0, "Zero increment"},
    {-2, 2, -1, "Increments away from stop value"},
    {-2, 2, 10, "First increment is beyond stop value"},
    {2, -2, 1, "Start more than stop: positive increment"},
    {2, 2, 1, "Start equal stop: positive increment"},
    {2, 2, -1, "Start equal stop: negative increment"},
    {2, 2, 0, "Start equal stop: zero increment"},
    {0, 0, 0, "Start equal stop equal zero: zero increment"}
};

int main() {
    int i, j, c;
    bool empty;
    S s;
    const int limit = 10;
    for (i = 0; i < 9; ++i) {
        s = examples[i];
        printf("%s\n", s.comment);
        printf("Range(%d, %d, %d) -> [", s.start, s.stop, s.incr);
        empty = TRUE;
        for (j = s.start, c = 0; j <= s.stop && c < limit; j += s.incr, ++c) {
            printf("%d ", j);
            empty = FALSE;
        }
        if (!empty) printf("\b");
        printf("]\n\n");
    }
    return 0;
}











Ada: with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;

procedure Main is
   procedure print_range(start : integer; stop : integer; step : integer) is
      Num : Integer := start;
   begin
      Put("Range(" & start'Image & ", " & stop'image &
            ", " & step'image & ") => ");
      if stop < start then
         Put_Line("Error: stop must be no less than start!");
      elsif step not in positive then
         Put_Line("Error: increment must be greater than 0!");
      elsif start = stop then
         Put_Line(start'image);
      else
         while num <= stop loop
            Put(num'Image);
            num := num + step;
         end loop;
         New_Line;
      end if;
   end print_range;

   type test_record is record
      start   : integer;
      stop    : integer;
      step    : integer;
      comment : unbounded_string := null_unbounded_string;
   end record;

   tests : array(1..9) of test_record :=
     ( 1 => (-2, 2, 1, To_Unbounded_String("Normal")),
       2 => (-2, 2, 0, To_Unbounded_String("Zero increment")),
       3 => (-2, 2, -1, To_Unbounded_String("Increments away from stop value")),
       4 => (-2, 2, 10, To_Unbounded_String("First increment is beyond stop value")),
       5 => (2, -1, 1, To_Unbounded_String("Start more than stop: positive increment")),
       6 => (2, 2, 1, To_Unbounded_String("Start equal stop: positive increment")),
       7 => (2, 2, -1, To_Unbounded_String("Start equal stop: negative increment")),
       8 => (2, 2, 0, To_Unbounded_String("Start equal stop: zero increment")),
       9 => (0, 0, 0, To_Unbounded_String("Start equal stop equal zero: zero increment")));


begin
   for test of tests loop
      Put(Test.Comment); Put(" : ");
      print_range(test.start, test.stop, test.step);
      New_line;
   end loop;
end Main;
Task: Loops_Wrong ranges




Go: package main

import "fmt"

type S struct {
    start, stop, incr int
    comment          string
}

var examples = []S{
    {-2, 2, 1, "Normal"},
    {-2, 2, 0, "Zero increment"},
    {-2, 2, -1, "Increments away from stop value"},
    {-2, 2, 10, "First increment is beyond stop value"},
    {2, -2, 1, "Start more than stop: positive increment"},
    {2, 2, 1, "Start equal stop: positive increment"},
    {2, 2, -1, "Start equal stop: negative increment"},
    {2, 2, 0, "Start equal stop: zero increment"},
    {0, 0, 0, "Start equal stop equal zero: zero increment"},
}

func sequence(s S, limit int) []int {
    var seq []int
    for i, c := s.start, 0; i <= s.stop && c < limit; i, c = i+s.incr, c+1 {
        seq = append(seq, i)
    }
    return seq
}

func main() {
    const limit = 10
    for _, ex := range examples {
        fmt.Println(ex.comment)
        fmt.Printf("Range(%d, %d, %d) -> ", ex.start, ex.stop, ex.incr)
        fmt.Println(sequence(ex, limit))
        fmt.Println()
    }
}








Ada: with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;

procedure Main is
   procedure print_range(start : integer; stop : integer; step : integer) is
      Num : Integer := start;
   begin
      Put("Range(" & start'Image & ", " & stop'image &
            ", " & step'image & ") => ");
      if stop < start then
         Put_Line("Error: stop must be no less than start!");
      elsif step not in positive then
         Put_Line("Error: increment must be greater than 0!");
      elsif start = stop then
         Put_Line(start'image);
      else
         while num <= stop loop
            Put(num'Image);
            num := num + step;
         end loop;
         New_Line;
      end if;
   end print_range;

   type test_record is record
      start   : integer;
      stop    : integer;
      step    : integer;
      comment : unbounded_string := null_unbounded_string;
   end record;

   tests : array(1..9) of test_record :=
     ( 1 => (-2, 2, 1, To_Unbounded_String("Normal")),
       2 => (-2, 2, 0, To_Unbounded_String("Zero increment")),
       3 => (-2, 2, -1, To_Unbounded_String("Increments away from stop value")),
       4 => (-2, 2, 10, To_Unbounded_String("First increment is beyond stop value")),
       5 => (2, -1, 1, To_Unbounded_String("Start more than stop: positive increment")),
       6 => (2, 2, 1, To_Unbounded_String("Start equal stop: positive increment")),
       7 => (2, 2, -1, To_Unbounded_String("Start equal stop: negative increment")),
       8 => (2, 2, 0, To_Unbounded_String("Start equal stop: zero increment")),
       9 => (0, 0, 0, To_Unbounded_String("Start equal stop equal zero: zero increment")));


begin
   for test of tests loop
      Put(Test.Comment); Put(" : ");
      print_range(test.start, test.stop, test.step);
      New_line;
   end loop;
end Main;