WeixiangYan/CodeTransOcean huggingface dataset:
Task: Kernighans large earthquake problem



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

public class Program
{
    static void Main() {
        foreach (var earthquake in LargeEarthquakes("data.txt", 6))
            Console.WriteLine(string.Join(" ", earthquake));
    }

    static IEnumerable<string[]> LargeEarthquakes(string filename, double limit) =>
        from line in File.ReadLines(filename)
        let parts = line.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries)
        where double.Parse(parts[2]) > limit
        select parts;

}



Java: import java.io.BufferedReader;
import java.io.FileReader;

public class KernighansLargeEarthquakeProblem {

    public static void main(String[] args) throws Exception {
        try (BufferedReader reader  = new BufferedReader(new FileReader("data.txt")); ) {
            String inLine = null;
            while ( (inLine = reader.readLine()) != null ) {
                String[] split = inLine.split("\\s+");
                double magnitude = Double.parseDouble(split[2]);
                if ( magnitude > 6 ) {
                    System.out.println(inLine);
                }
            }
        }

    }

}
Task: Kernighans large earthquake problem

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

int main() {
    FILE *fp;
    char *line = NULL;
    size_t len = 0;
    ssize_t read;
    char *lw, *lt;
    fp = fopen("data.txt", "r");
    if (fp == NULL) {
        printf("Unable to open file\n");
        exit(1);
    }
    printf("Those earthquakes with a magnitude > 6.0 are:\n\n");
    while ((read = getline(&line, &len, fp)) != EOF) {
        if (read < 2) continue;   
        lw = strrchr(line, ' ');  
        lt = strrchr(line, '\t'); 
        if (!lw && !lt) continue; 
        if (lt > lw) lw = lt;     
        if (atof(lw + 1) > 6.0) printf("%s", line);
    }
    fclose(fp);
    if (line) free(line);
    return 0;
}





Java: import java.io.BufferedReader;
import java.io.FileReader;

public class KernighansLargeEarthquakeProblem {

    public static void main(String[] args) throws Exception {
        try (BufferedReader reader  = new BufferedReader(new FileReader("data.txt")); ) {
            String inLine = null;
            while ( (inLine = reader.readLine()) != null ) {
                String[] split = inLine.split("\\s+");
                double magnitude = Double.parseDouble(split[2]);
                if ( magnitude > 6 ) {
                    System.out.println(inLine);
                }
            }
        }

    }

}
Task: Kernighans large earthquake problem



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

public class Program
{
    static void Main() {
        foreach (var earthquake in LargeEarthquakes("data.txt", 6))
            Console.WriteLine(string.Join(" ", earthquake));
    }

    static IEnumerable<string[]> LargeEarthquakes(string filename, double limit) =>
        from line in File.ReadLines(filename)
        let parts = line.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries)
        where double.Parse(parts[2]) > limit
        select parts;

}


Go: package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    f, err := os.Open("data.txt")
    if err != nil {
        fmt.Println("Unable to open the file")
        return
    }
    defer f.Close()
    fmt.Println("Those earthquakes with a magnitude > 6.0 are:\n")
    input := bufio.NewScanner(f)
    for input.Scan() {
        line := input.Text()
        fields := strings.Fields(line)
        mag, err := strconv.ParseFloat(fields[2], 64)
        if err != nil {
            fmt.Println("Unable to parse magnitude of an earthquake")
            return
        }
        if mag > 6.0 {
            fmt.Println(line)
        }
    }
}
Task: Kernighans large earthquake problem

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

int main() {
    FILE *fp;
    char *line = NULL;
    size_t len = 0;
    ssize_t read;
    char *lw, *lt;
    fp = fopen("data.txt", "r");
    if (fp == NULL) {
        printf("Unable to open file\n");
        exit(1);
    }
    printf("Those earthquakes with a magnitude > 6.0 are:\n\n");
    while ((read = getline(&line, &len, fp)) != EOF) {
        if (read < 2) continue;   
        lw = strrchr(line, ' ');  
        lt = strrchr(line, '\t'); 
        if (!lw && !lt) continue; 
        if (lt > lw) lw = lt;     
        if (atof(lw + 1) > 6.0) printf("%s", line);
    }
    fclose(fp);
    if (line) free(line);
    return 0;
}






PHP: <?php

if ( ! isset( $argv[1] ) )
    die( 'Data file name required' );

if ( ! $fh = fopen( $argv[1], 'r' ) )
    die ( 'Cannot open file: ' . $argv[1] );

while ( list( $date, $loc, $mag ) = fscanf( $fh, "%s %s %f" ) ) {
    if ( $mag > 6 ) {
        printf( "% -12s % -19s %.1f\n", $date, $loc, $mag );
    }
}

fclose( $fh );
Task: Kernighans large earthquake problem



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

public class Program
{
    static void Main() {
        foreach (var earthquake in LargeEarthquakes("data.txt", 6))
            Console.WriteLine(string.Join(" ", earthquake));
    }

    static IEnumerable<string[]> LargeEarthquakes(string filename, double limit) =>
        from line in File.ReadLines(filename)
        let parts = line.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries)
        where double.Parse(parts[2]) > limit
        select parts;

}




PHP: <?php

if ( ! isset( $argv[1] ) )
    die( 'Data file name required' );

if ( ! $fh = fopen( $argv[1], 'r' ) )
    die ( 'Cannot open file: ' . $argv[1] );

while ( list( $date, $loc, $mag ) = fscanf( $fh, "%s %s %f" ) ) {
    if ( $mag > 6 ) {
        printf( "% -12s % -19s %.1f\n", $date, $loc, $mag );
    }
}

fclose( $fh );
Task: Kernighans large earthquake problem


C++: 
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ifstream file("../include/earthquake.txt");

    int count_quake = 0;
    int column = 1;
    string value;
    double size_quake;
    string row = "";


    while(file >> value)
    {
        if(column == 3)
        {
            size_quake = stod(value);

            if(size_quake>6.0)
            {
                count_quake++;
                row += value + "\t";
                cout << row << endl;
            }

            column = 1;
            row = "";
        }
        else
        {
            column++;
            row+=value + "\t";
        }
    }

    cout << "\nNumber of quakes greater than 6 is " << count_quake << endl;

    return 0;
}





PHP: <?php

if ( ! isset( $argv[1] ) )
    die( 'Data file name required' );

if ( ! $fh = fopen( $argv[1], 'r' ) )
    die ( 'Cannot open file: ' . $argv[1] );

while ( list( $date, $loc, $mag ) = fscanf( $fh, "%s %s %f" ) ) {
    if ( $mag > 6 ) {
        printf( "% -12s % -19s %.1f\n", $date, $loc, $mag );
    }
}

fclose( $fh );
Task: Kernighans large earthquake problem




Go: package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    f, err := os.Open("data.txt")
    if err != nil {
        fmt.Println("Unable to open the file")
        return
    }
    defer f.Close()
    fmt.Println("Those earthquakes with a magnitude > 6.0 are:\n")
    input := bufio.NewScanner(f)
    for input.Scan() {
        line := input.Text()
        fields := strings.Fields(line)
        mag, err := strconv.ParseFloat(fields[2], 64)
        if err != nil {
            fmt.Println("Unable to parse magnitude of an earthquake")
            return
        }
        if mag > 6.0 {
            fmt.Println(line)
        }
    }
}



PHP: <?php

if ( ! isset( $argv[1] ) )
    die( 'Data file name required' );

if ( ! $fh = fopen( $argv[1], 'r' ) )
    die ( 'Cannot open file: ' . $argv[1] );

while ( list( $date, $loc, $mag ) = fscanf( $fh, "%s %s %f" ) ) {
    if ( $mag > 6 ) {
        printf( "% -12s % -19s %.1f\n", $date, $loc, $mag );
    }
}

fclose( $fh );
Task: Kernighans large earthquake problem





Java: import java.io.BufferedReader;
import java.io.FileReader;

public class KernighansLargeEarthquakeProblem {

    public static void main(String[] args) throws Exception {
        try (BufferedReader reader  = new BufferedReader(new FileReader("data.txt")); ) {
            String inLine = null;
            while ( (inLine = reader.readLine()) != null ) {
                String[] split = inLine.split("\\s+");
                double magnitude = Double.parseDouble(split[2]);
                if ( magnitude > 6 ) {
                    System.out.println(inLine);
                }
            }
        }

    }

}


PHP: <?php

if ( ! isset( $argv[1] ) )
    die( 'Data file name required' );

if ( ! $fh = fopen( $argv[1], 'r' ) )
    die ( 'Cannot open file: ' . $argv[1] );

while ( list( $date, $loc, $mag ) = fscanf( $fh, "%s %s %f" ) ) {
    if ( $mag > 6 ) {
        printf( "% -12s % -19s %.1f\n", $date, $loc, $mag );
    }
}

fclose( $fh );
Task: Kernighans large earthquake problem






PHP: <?php

if ( ! isset( $argv[1] ) )
    die( 'Data file name required' );

if ( ! $fh = fopen( $argv[1], 'r' ) )
    die ( 'Cannot open file: ' . $argv[1] );

while ( list( $date, $loc, $mag ) = fscanf( $fh, "%s %s %f" ) ) {
    if ( $mag > 6 ) {
        printf( "% -12s % -19s %.1f\n", $date, $loc, $mag );
    }
}

fclose( $fh );


Python: python -c '
with open("data.txt") as f:
    for ln in f:
        if float(ln.strip().split()[2]) > 6:
            print(ln.strip())'
Task: Kernighans large earthquake problem






PHP: <?php

if ( ! isset( $argv[1] ) )
    die( 'Data file name required' );

if ( ! $fh = fopen( $argv[1], 'r' ) )
    die ( 'Cannot open file: ' . $argv[1] );

while ( list( $date, $loc, $mag ) = fscanf( $fh, "%s %s %f" ) ) {
    if ( $mag > 6 ) {
        printf( "% -12s % -19s %.1f\n", $date, $loc, $mag );
    }
}

fclose( $fh );



VB: Imports System.IO

Module Module1

    Function LargeEarthquakes(filename As String, limit As Double) As IEnumerable(Of String())
        Return From line In File.ReadLines(filename)
               Let parts = line.Split(CType(Nothing, Char()), StringSplitOptions.RemoveEmptyEntries)
               Where Double.Parse(parts(2)) > limit
               Select parts
    End Function

    Sub Main()
        For Each earthquake In LargeEarthquakes("data.txt", 6)
            Console.WriteLine(String.Join(" ", earthquake))
        Next
    End Sub

End Module
Task: Tarjan



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

class Node
{
    public int LowLink { get; set; }
    public int Index { get; set; }
    public int N { get; }

    public Node(int n)
    {
        N = n;
        Index = -1;
        LowLink = 0;
    }
}

class Graph
{
    public HashSet<Node> V { get; }
    public Dictionary<Node, HashSet<Node>> Adj { get; }

    
    
    
    public void Tarjan()
    {
        var index = 0; 
        var S = new Stack<Node>();

        Action<Node> StrongConnect = null;
        StrongConnect = (v) =>
        {
            
            v.Index = index;
            v.LowLink = index;

            index++;
            S.Push(v);

            
            foreach (var w in Adj[v])
                if (w.Index < 0)
                {
                    
                    StrongConnect(w);
                    v.LowLink = Math.Min(v.LowLink, w.LowLink);
                }
                else if (S.Contains(w))
                    
                    v.LowLink = Math.Min(v.LowLink, w.Index);

            
            if (v.LowLink == v.Index)
            {
                Console.Write("SCC: ");

                Node w;
                do
                {
                    w = S.Pop();
                    Console.Write(w.N + " ");
                } while (w != v);

                Console.WriteLine();
            }
        };

        foreach (var v in V)
            if (v.Index < 0)
                StrongConnect(v);
    }
}


Go: package main

import (
    "fmt"
    "math/big"
)


var g = [][]int{
    0: {1},
    2: {0},
    5: {2, 6},
    6: {5},
    1: {2},
    3: {1, 2, 4},
    4: {5, 3},
    7: {4, 7, 6},
}

func main() {
    tarjan(g, func(c []int) { fmt.Println(c) })
}



func tarjan(g [][]int, emit func([]int)) {
    var indexed, stacked big.Int
    index := make([]int, len(g))
    lowlink := make([]int, len(g))
    x := 0
    var S []int
    var sc func(int) bool
    sc = func(n int) bool {
        index[n] = x
        indexed.SetBit(&indexed, n, 1)
        lowlink[n] = x
        x++
        S = append(S, n)
        stacked.SetBit(&stacked, n, 1)
        for _, nb := range g[n] {
            if indexed.Bit(nb) == 0 {
                if !sc(nb) {
                    return false
                }
                if lowlink[nb] < lowlink[n] {
                    lowlink[n] = lowlink[nb]
                }
            } else if stacked.Bit(nb) == 1 {
                if index[nb] < lowlink[n] {
                    lowlink[n] = index[nb]
                }
            }
        }
        if lowlink[n] == index[n] {
            var c []int
            for {
                last := len(S) - 1
                w := S[last]
                S = S[:last]
                stacked.SetBit(&stacked, w, 0)
                c = append(c, w)
                if w == n {
                    emit(c)
                    break
                }
            }
        }
        return true
    }
    for n := range g {
        if indexed.Bit(n) == 0 && !sc(n) {
            return
        }
    }
}
Task: Tarjan



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

class Node
{
    public int LowLink { get; set; }
    public int Index { get; set; }
    public int N { get; }

    public Node(int n)
    {
        N = n;
        Index = -1;
        LowLink = 0;
    }
}

class Graph
{
    public HashSet<Node> V { get; }
    public Dictionary<Node, HashSet<Node>> Adj { get; }

    
    
    
    public void Tarjan()
    {
        var index = 0; 
        var S = new Stack<Node>();

        Action<Node> StrongConnect = null;
        StrongConnect = (v) =>
        {
            
            v.Index = index;
            v.LowLink = index;

            index++;
            S.Push(v);

            
            foreach (var w in Adj[v])
                if (w.Index < 0)
                {
                    
                    StrongConnect(w);
                    v.LowLink = Math.Min(v.LowLink, w.LowLink);
                }
                else if (S.Contains(w))
                    
                    v.LowLink = Math.Min(v.LowLink, w.Index);

            
            if (v.LowLink == v.Index)
            {
                Console.Write("SCC: ");

                Node w;
                do
                {
                    w = S.Pop();
                    Console.Write(w.N + " ");
                } while (w != v);

                Console.WriteLine();
            }
        };

        foreach (var v in V)
            if (v.Index < 0)
                StrongConnect(v);
    }
}





Python: from collections import defaultdict

def from_edges(edges):
    

    class Node:
        def __init__(self):
            
            
            
            
            self.root = None
            self.succ = []

    nodes = defaultdict(Node)
    for v,w in edges:
        nodes[v].succ.append(nodes[w])

    for i,v in nodes.items(): 
        v.id = i

    return nodes.values()

def trajan(V):
    def strongconnect(v, S):
        v.root = pos = len(S)
        S.append(v)

        for w in v.succ:
            if w.root is None:  
                yield from strongconnect(w, S)

            if w.root >= 0:  
                v.root = min(v.root, w.root)

        if v.root == pos:  
            res, S[pos:] = S[pos:], []
            for w in res:
                w.root = -1
            yield [r.id for r in res]

    for v in V:
        if v.root is None:
            yield from strongconnect(v, [])


tables = [  
            [(1,2), (3,1), (3,6), (6,7), (7,6), (2,3), (4,2),
             (4,3), (4,5), (5,6), (5,4), (8,5), (8,7), (8,6)],

            
            [('A', 'B'), ('B', 'C'), ('C', 'A'), ('A', 'Other')]]

for table in (tables):
    for g in trajan(from_edges(table)):
        print(g)
    print()
Task: Tarjan




Go: package main

import (
    "fmt"
    "math/big"
)


var g = [][]int{
    0: {1},
    2: {0},
    5: {2, 6},
    6: {5},
    1: {2},
    3: {1, 2, 4},
    4: {5, 3},
    7: {4, 7, 6},
}

func main() {
    tarjan(g, func(c []int) { fmt.Println(c) })
}



func tarjan(g [][]int, emit func([]int)) {
    var indexed, stacked big.Int
    index := make([]int, len(g))
    lowlink := make([]int, len(g))
    x := 0
    var S []int
    var sc func(int) bool
    sc = func(n int) bool {
        index[n] = x
        indexed.SetBit(&indexed, n, 1)
        lowlink[n] = x
        x++
        S = append(S, n)
        stacked.SetBit(&stacked, n, 1)
        for _, nb := range g[n] {
            if indexed.Bit(nb) == 0 {
                if !sc(nb) {
                    return false
                }
                if lowlink[nb] < lowlink[n] {
                    lowlink[n] = lowlink[nb]
                }
            } else if stacked.Bit(nb) == 1 {
                if index[nb] < lowlink[n] {
                    lowlink[n] = index[nb]
                }
            }
        }
        if lowlink[n] == index[n] {
            var c []int
            for {
                last := len(S) - 1
                w := S[last]
                S = S[:last]
                stacked.SetBit(&stacked, w, 0)
                c = append(c, w)
                if w == n {
                    emit(c)
                    break
                }
            }
        }
        return true
    }
    for n := range g {
        if indexed.Bit(n) == 0 && !sc(n) {
            return
        }
    }
}




Python: from collections import defaultdict

def from_edges(edges):
    

    class Node:
        def __init__(self):
            
            
            
            
            self.root = None
            self.succ = []

    nodes = defaultdict(Node)
    for v,w in edges:
        nodes[v].succ.append(nodes[w])

    for i,v in nodes.items(): 
        v.id = i

    return nodes.values()

def trajan(V):
    def strongconnect(v, S):
        v.root = pos = len(S)
        S.append(v)

        for w in v.succ:
            if w.root is None:  
                yield from strongconnect(w, S)

            if w.root >= 0:  
                v.root = min(v.root, w.root)

        if v.root == pos:  
            res, S[pos:] = S[pos:], []
            for w in res:
                w.root = -1
            yield [r.id for r in res]

    for v in V:
        if v.root is None:
            yield from strongconnect(v, [])


tables = [  
            [(1,2), (3,1), (3,6), (6,7), (7,6), (2,3), (4,2),
             (4,3), (4,5), (5,6), (5,4), (8,5), (8,7), (8,6)],

            
            [('A', 'B'), ('B', 'C'), ('C', 'A'), ('A', 'Other')]]

for table in (tables):
    for g in trajan(from_edges(table)):
        print(g)
    print()
Task: Calculating the value of e

C: #include <stdio.h>
#include <math.h>

int main(void)
{
    double e;

    puts("The double precision in C give about 15 significant digits.\n"
         "Values below are presented with 16 digits after the decimal point.\n");

    
    
    e = exp(1);
    printf("Euler constant e = %.16lf\n", e);

    
    
    e = 1.0 + 0x1p-26;
    for (int i = 0; i < 26; i++)
        e *= e;
    printf("Euler constant e = %.16lf\n", e);

    
    
    
    const int N = 1000;
    double a[1000];
    a[0] = 1.0;
    for (int i = 1; i < N; i++)
    {
        a[i] = a[i-1] / i;
    }
    e = 1.;
    for (int i = N - 1; i > 0; i--)
        e += a[i];
    printf("Euler constant e = %.16lf\n", e);

    return 0;
}



C#: using System;

namespace CalculateE {
    class Program {
        public const double EPSILON = 1.0e-15;

        static void Main(string[] args) {
            ulong fact = 1;
            double e = 2.0;
            double e0;
            uint n = 2;
            do {
                e0 = e;
                fact *= n++;
                e += 1.0 / fact;
            } while (Math.Abs(e - e0) >= EPSILON);
            Console.WriteLine("e = {0:F15}", e);
        }
    }
}
Task: Calculating the value of e

C: #include <stdio.h>
#include <math.h>

int main(void)
{
    double e;

    puts("The double precision in C give about 15 significant digits.\n"
         "Values below are presented with 16 digits after the decimal point.\n");

    
    
    e = exp(1);
    printf("Euler constant e = %.16lf\n", e);

    
    
    e = 1.0 + 0x1p-26;
    for (int i = 0; i < 26; i++)
        e *= e;
    printf("Euler constant e = %.16lf\n", e);

    
    
    
    const int N = 1000;
    double a[1000];
    a[0] = 1.0;
    for (int i = 1; i < N; i++)
    {
        a[i] = a[i-1] / i;
    }
    e = 1.;
    for (int i = N - 1; i > 0; i--)
        e += a[i];
    printf("Euler constant e = %.16lf\n", e);

    return 0;
}


C++: #include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main() {
    const double EPSILON = 1.0e-15;
    unsigned long long fact = 1;
    double e = 2.0, e0;
    int n = 2;
    do {
        e0 = e;
        fact *= n++;
        e += 1.0 / fact;
    }
    while (fabs(e - e0) >= EPSILON);
    cout << "e = " << setprecision(16) << e << endl;
    return 0;
}
Task: Calculating the value of e

C: #include <stdio.h>
#include <math.h>

int main(void)
{
    double e;

    puts("The double precision in C give about 15 significant digits.\n"
         "Values below are presented with 16 digits after the decimal point.\n");

    
    
    e = exp(1);
    printf("Euler constant e = %.16lf\n", e);

    
    
    e = 1.0 + 0x1p-26;
    for (int i = 0; i < 26; i++)
        e *= e;
    printf("Euler constant e = %.16lf\n", e);

    
    
    
    const int N = 1000;
    double a[1000];
    a[0] = 1.0;
    for (int i = 1; i < N; i++)
    {
        a[i] = a[i-1] / i;
    }
    e = 1.;
    for (int i = N - 1; i > 0; i--)
        e += a[i];
    printf("Euler constant e = %.16lf\n", e);

    return 0;
}





Java: public class CalculateE {
    public static final double EPSILON = 1.0e-15;

    public static void main(String[] args) {
        long fact = 1;
        double e = 2.0;
        int n = 2;
        double e0;
        do {
            e0 = e;
            fact *= n++;
            e += 1.0 / fact;
        } while (Math.abs(e - e0) >= EPSILON);
        System.out.printf("e = %.15f\n", e);
    }
}
Task: Calculating the value of e

C: #include <stdio.h>
#include <math.h>

int main(void)
{
    double e;

    puts("The double precision in C give about 15 significant digits.\n"
         "Values below are presented with 16 digits after the decimal point.\n");

    
    
    e = exp(1);
    printf("Euler constant e = %.16lf\n", e);

    
    
    e = 1.0 + 0x1p-26;
    for (int i = 0; i < 26; i++)
        e *= e;
    printf("Euler constant e = %.16lf\n", e);

    
    
    
    const int N = 1000;
    double a[1000];
    a[0] = 1.0;
    for (int i = 1; i < N; i++)
    {
        a[i] = a[i-1] / i;
    }
    e = 1.;
    for (int i = N - 1; i > 0; i--)
        e += a[i];
    printf("Euler constant e = %.16lf\n", e);

    return 0;
}







Python: import math

e0 = 0
e = 2
n = 0
fact = 1
while(e-e0 > 1e-15):
	e0 = e
	n += 1
	fact *= 2*n*(2*n+1)
	e += (2.*n+2)/fact

print "Computed e = "+str(e)
print "Real e = "+str(math.e)
print "Error = "+str(math.e-e)
print "Number of iterations = "+str(n)