WeixiangYan/CodeTransOcean huggingface dataset:
Task: Synchronous concurrency




Go: package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    lines := make(chan string)
    count := make(chan int)
    go func() {
        c := 0
        for l := range lines {
            fmt.Println(l)
            c++
        }
        count <- c
    }()

    f, err := os.Open("input.txt")
    if err != nil {
        log.Fatal(err)
    }
    for s := bufio.NewScanner(f); s.Scan(); {
        lines <- s.Text()
    }
    f.Close()
    close(lines)
    fmt.Println("Number of lines:", <-count)
}





VB: Imports System.Threading

Module Module1

   Sub Main()
       Dim t1 As New Thread(AddressOf Reader)
       Dim t2 As New Thread(AddressOf Writer)
       t1.Start()
       t2.Start()
       t1.Join()
       t2.Join()
   End Sub

   Sub Reader()
       For Each line In IO.File.ReadAllLines("input.txt")
           m_WriterQueue.Enqueue(line)
       Next
       m_WriterQueue.Enqueue(Nothing)

       Dim result As Integer
       Do Until m_ReaderQueue.TryDequeue(result)
           Thread.Sleep(10)
       Loop

       Console.WriteLine(result)

   End Sub

   Sub Writer()
       Dim count = 0
       Dim line As String = Nothing
       Do
           Do Until m_WriterQueue.TryDequeue(line)
               Thread.Sleep(10)
           Loop
           If line IsNot Nothing Then
               Console.WriteLine(line)
               count += 1
           Else
               m_ReaderQueue.Enqueue(count)
               Exit Do
           End If
       Loop
   End Sub

   Private m_WriterQueue As New SafeQueue(Of String)
   Private m_ReaderQueue As New SafeQueue(Of Integer)

End Module

Class SafeQueue(Of T)
   Private m_list As New Queue(Of T)
   Public Function TryDequeue(ByRef result As T) As Boolean
       SyncLock m_list
           If m_list.Count = 0 Then Return False
           result = m_list.Dequeue
           Return True
       End SyncLock
   End Function
   Public Sub Enqueue(ByVal value As T)
       SyncLock m_list
           m_list.Enqueue(value)
       End SyncLock
   End Sub
End Class
Task: Synchronous concurrency







Python: import sys
from Queue import Queue
from threading import Thread

lines = Queue(1)
count = Queue(1)

def read(file):
    try:
        for line in file:
            lines.put(line)
    finally:
        lines.put(None)
    print count.get()

def write(file):
    n = 0
    while 1:
        line = lines.get()
        if line is None:
            break
        file.write(line)
        n += 1
    count.put(n)

reader = Thread(target=read, args=(open('input.txt'),))
writer = Thread(target=write, args=(sys.stdout,))
reader.start()
writer.start()
reader.join()
writer.join()


VB: Imports System.Threading

Module Module1

   Sub Main()
       Dim t1 As New Thread(AddressOf Reader)
       Dim t2 As New Thread(AddressOf Writer)
       t1.Start()
       t2.Start()
       t1.Join()
       t2.Join()
   End Sub

   Sub Reader()
       For Each line In IO.File.ReadAllLines("input.txt")
           m_WriterQueue.Enqueue(line)
       Next
       m_WriterQueue.Enqueue(Nothing)

       Dim result As Integer
       Do Until m_ReaderQueue.TryDequeue(result)
           Thread.Sleep(10)
       Loop

       Console.WriteLine(result)

   End Sub

   Sub Writer()
       Dim count = 0
       Dim line As String = Nothing
       Do
           Do Until m_WriterQueue.TryDequeue(line)
               Thread.Sleep(10)
           Loop
           If line IsNot Nothing Then
               Console.WriteLine(line)
               count += 1
           Else
               m_ReaderQueue.Enqueue(count)
               Exit Do
           End If
       Loop
   End Sub

   Private m_WriterQueue As New SafeQueue(Of String)
   Private m_ReaderQueue As New SafeQueue(Of Integer)

End Module

Class SafeQueue(Of T)
   Private m_list As New Queue(Of T)
   Public Function TryDequeue(ByRef result As T) As Boolean
       SyncLock m_list
           If m_list.Count = 0 Then Return False
           result = m_list.Dequeue
           Return True
       End SyncLock
   End Function
   Public Sub Enqueue(ByVal value As T)
       SyncLock m_list
           m_list.Enqueue(value)
       End SyncLock
   End Sub
End Class
Task: Synchronous concurrency


C++: #include <future>
#include <iostream>
#include <fstream>
#include <mutex>
#include <queue>
#include <string>
#include <thread>

struct lock_queue
{
    std::queue<std::string> q;
    std::mutex mutex;
};

void reader(std::string filename, std::future<size_t> lines, lock_queue& out)
{
    std::string line;
    std::ifstream in(filename);
    while(std::getline(in, line)) {
        line += '\n';
        std::lock_guard<std::mutex> lock(out.mutex);
        out.q.push(line);
    } {
        std::lock_guard<std::mutex> lock(out.mutex);
        out.q.push("");
    }
    lines.wait();
    std::cout << "\nPrinted " << lines.get() << " lines\n";
}

void printer(std::promise<size_t> lines, lock_queue& in)
{
    std::string s;
    size_t line_n = 0;
    bool print = false;
    while(true) {
        {
            std::lock_guard<std::mutex> lock(in.mutex);
            if(( print = not in.q.empty() )) { 
                s = in.q.front();
                in.q.pop();
            }
        }
        if(print) {
            if(s == "") break;
            std::cout << s;
            ++line_n;
            print = false;
        }
    }
    lines.set_value(line_n);
}

int main()
{
    lock_queue queue;
    std::promise<size_t> promise;
    std::thread t1(reader, "input.txt", promise.get_future(), std::ref(queue));
    std::thread t2(printer, std::move(promise), std::ref(queue));
    t1.join(); t2.join();
}


C#: using System;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.IO;

namespace SynchronousConcurrency
{
    class Program
    {
        static void Main(string[] args)
        {
            BlockingCollection<string> toWriterTask = new BlockingCollection<string>();
            BlockingCollection<int> fromWriterTask = new BlockingCollection<int>();
            Task writer = Task.Factory.StartNew(() => ConsoleWriter(toWriterTask, fromWriterTask));
            Task reader = Task.Factory.StartNew(() => FileReader(fromWriterTask, toWriterTask));
            Task.WaitAll(writer, reader);
        }
        static void ConsoleWriter(BlockingCollection<string> input, BlockingCollection<int> output)
        {
            int nLines = 0;
            string line;
            while ((line = input.Take()) != null)
            {
                Console.WriteLine(line);
                ++nLines;
            }
            output.Add(nLines);
        }
        static void FileReader(BlockingCollection<int> input, BlockingCollection<string> output)
        {
            StreamReader file = new StreamReader("input.txt"); 
            string line;
            while ((line = file.ReadLine()) != null)
            {
                output.Add(line);

            }
            output.Add(null); 
            Console.WriteLine("line count: " + input.Take());
        }
    }
}
Task: Synchronous concurrency





Java: import java.io.BufferedReader;
import java.io.FileReader;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

class SynchronousConcurrency
{
  public static void main(String[] args) throws Exception
  {
    final AtomicLong lineCount = new AtomicLong(0);
    final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
    final String EOF = new String();
    
    final Thread writerThread = new Thread(new Runnable() {
        public void run()
        {
          long linesWrote = 0;
          while (true)
          {
            try
            {
              String line = queue.take();
              
              if (line == EOF)
                break;
              System.out.println(line);
              linesWrote++;
            }
            catch (InterruptedException ie)
            {  }
          }
          lineCount.set(linesWrote);
        }
      }
    );
    writerThread.start();
    
    
    BufferedReader br = new BufferedReader(new FileReader("input.txt"));
    String line;
    while ((line = br.readLine()) != null)
      queue.put(line);
    br.close();
    queue.put(EOF);
    writerThread.join();
    
    System.out.println("Line count: " + lineCount.get());
    return;
  }
}



Python: import sys
from Queue import Queue
from threading import Thread

lines = Queue(1)
count = Queue(1)

def read(file):
    try:
        for line in file:
            lines.put(line)
    finally:
        lines.put(None)
    print count.get()

def write(file):
    n = 0
    while 1:
        line = lines.get()
        if line is None:
            break
        file.write(line)
        n += 1
    count.put(n)

reader = Thread(target=read, args=(open('input.txt'),))
writer = Thread(target=write, args=(sys.stdout,))
reader.start()
writer.start()
reader.join()
writer.join()
Task: Synchronous concurrency



C#: using System;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.IO;

namespace SynchronousConcurrency
{
    class Program
    {
        static void Main(string[] args)
        {
            BlockingCollection<string> toWriterTask = new BlockingCollection<string>();
            BlockingCollection<int> fromWriterTask = new BlockingCollection<int>();
            Task writer = Task.Factory.StartNew(() => ConsoleWriter(toWriterTask, fromWriterTask));
            Task reader = Task.Factory.StartNew(() => FileReader(fromWriterTask, toWriterTask));
            Task.WaitAll(writer, reader);
        }
        static void ConsoleWriter(BlockingCollection<string> input, BlockingCollection<int> output)
        {
            int nLines = 0;
            string line;
            while ((line = input.Take()) != null)
            {
                Console.WriteLine(line);
                ++nLines;
            }
            output.Add(nLines);
        }
        static void FileReader(BlockingCollection<int> input, BlockingCollection<string> output)
        {
            StreamReader file = new StreamReader("input.txt"); 
            string line;
            while ((line = file.ReadLine()) != null)
            {
                output.Add(line);

            }
            output.Add(null); 
            Console.WriteLine("line count: " + input.Take());
        }
    }
}


Go: package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    lines := make(chan string)
    count := make(chan int)
    go func() {
        c := 0
        for l := range lines {
            fmt.Println(l)
            c++
        }
        count <- c
    }()

    f, err := os.Open("input.txt")
    if err != nil {
        log.Fatal(err)
    }
    for s := bufio.NewScanner(f); s.Scan(); {
        lines <- s.Text()
    }
    f.Close()
    close(lines)
    fmt.Println("Number of lines:", <-count)
}
Task: Synchronous concurrency



C#: using System;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.IO;

namespace SynchronousConcurrency
{
    class Program
    {
        static void Main(string[] args)
        {
            BlockingCollection<string> toWriterTask = new BlockingCollection<string>();
            BlockingCollection<int> fromWriterTask = new BlockingCollection<int>();
            Task writer = Task.Factory.StartNew(() => ConsoleWriter(toWriterTask, fromWriterTask));
            Task reader = Task.Factory.StartNew(() => FileReader(fromWriterTask, toWriterTask));
            Task.WaitAll(writer, reader);
        }
        static void ConsoleWriter(BlockingCollection<string> input, BlockingCollection<int> output)
        {
            int nLines = 0;
            string line;
            while ((line = input.Take()) != null)
            {
                Console.WriteLine(line);
                ++nLines;
            }
            output.Add(nLines);
        }
        static void FileReader(BlockingCollection<int> input, BlockingCollection<string> output)
        {
            StreamReader file = new StreamReader("input.txt"); 
            string line;
            while ((line = file.ReadLine()) != null)
            {
                output.Add(line);

            }
            output.Add(null); 
            Console.WriteLine("line count: " + input.Take());
        }
    }
}



Java: import java.io.BufferedReader;
import java.io.FileReader;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

class SynchronousConcurrency
{
  public static void main(String[] args) throws Exception
  {
    final AtomicLong lineCount = new AtomicLong(0);
    final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
    final String EOF = new String();
    
    final Thread writerThread = new Thread(new Runnable() {
        public void run()
        {
          long linesWrote = 0;
          while (true)
          {
            try
            {
              String line = queue.take();
              
              if (line == EOF)
                break;
              System.out.println(line);
              linesWrote++;
            }
            catch (InterruptedException ie)
            {  }
          }
          lineCount.set(linesWrote);
        }
      }
    );
    writerThread.start();
    
    
    BufferedReader br = new BufferedReader(new FileReader("input.txt"));
    String line;
    while ((line = br.readLine()) != null)
      queue.put(line);
    br.close();
    queue.put(EOF);
    writerThread.join();
    
    System.out.println("Line count: " + lineCount.get());
    return;
  }
}
Task: Pascal matrix generation

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

void pascal_low(int **mat, int n) {
    int i, j;

    for (i = 0; i < n; ++i)
        for (j = 0; j < n; ++j)
            if (i < j)
                mat[i][j] = 0;
            else if (i == j || j == 0)
                mat[i][j] = 1;
            else
                mat[i][j] = mat[i - 1][j - 1] + mat[i - 1][j];
}

void pascal_upp(int **mat, int n) {
    int i, j;

    for (i = 0; i < n; ++i)
        for (j = 0; j < n; ++j)
            if (i > j)
                mat[i][j] = 0;
            else if (i == j || i == 0)
                mat[i][j] = 1;
            else
                mat[i][j] = mat[i - 1][j - 1] + mat[i][j - 1];
}

void pascal_sym(int **mat, int n) {
    int i, j;

    for (i = 0; i < n; ++i)
        for (j = 0; j < n; ++j)
            if (i == 0 || j == 0)
                mat[i][j] = 1;
            else
                mat[i][j] = mat[i - 1][j] + mat[i][j - 1];
}

int main(int argc, char * argv[]) {
    int **mat;
    int i, j, n;

    
    n = 5;

    
    mat = calloc(n, sizeof(int *));
    for (i = 0; i < n; ++i)
        mat[i] = calloc(n, sizeof(int));

    
    printf("=== Pascal upper matrix ===\n");
    pascal_upp(mat, n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            printf("%4d%c", mat[i][j], j < n - 1 ? ' ' : '\n');

    printf("=== Pascal lower matrix ===\n");
    pascal_low(mat, n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            printf("%4d%c", mat[i][j], j < n - 1 ? ' ' : '\n');

    printf("=== Pascal symmetric matrix ===\n");
    pascal_sym(mat, n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            printf("%4d%c", mat[i][j], j < n - 1 ? ' ' : '\n');

    return 0;
}





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));
    }
}
Task: Pascal matrix generation

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

void pascal_low(int **mat, int n) {
    int i, j;

    for (i = 0; i < n; ++i)
        for (j = 0; j < n; ++j)
            if (i < j)
                mat[i][j] = 0;
            else if (i == j || j == 0)
                mat[i][j] = 1;
            else
                mat[i][j] = mat[i - 1][j - 1] + mat[i - 1][j];
}

void pascal_upp(int **mat, int n) {
    int i, j;

    for (i = 0; i < n; ++i)
        for (j = 0; j < n; ++j)
            if (i > j)
                mat[i][j] = 0;
            else if (i == j || i == 0)
                mat[i][j] = 1;
            else
                mat[i][j] = mat[i - 1][j - 1] + mat[i][j - 1];
}

void pascal_sym(int **mat, int n) {
    int i, j;

    for (i = 0; i < n; ++i)
        for (j = 0; j < n; ++j)
            if (i == 0 || j == 0)
                mat[i][j] = 1;
            else
                mat[i][j] = mat[i - 1][j] + mat[i][j - 1];
}

int main(int argc, char * argv[]) {
    int **mat;
    int i, j, n;

    
    n = 5;

    
    mat = calloc(n, sizeof(int *));
    for (i = 0; i < n; ++i)
        mat[i] = calloc(n, sizeof(int));

    
    printf("=== Pascal upper matrix ===\n");
    pascal_upp(mat, n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            printf("%4d%c", mat[i][j], j < n - 1 ? ' ' : '\n');

    printf("=== Pascal lower matrix ===\n");
    pascal_low(mat, n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            printf("%4d%c", mat[i][j], j < n - 1 ? ' ' : '\n');

    printf("=== Pascal symmetric matrix ===\n");
    pascal_sym(mat, n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            printf("%4d%c", mat[i][j], j < n - 1 ? ' ' : '\n');

    return 0;
}







Python: from pprint import pprint as pp

def pascal_upp(n):
    s = [[0] * n for _ in range(n)]
    s[0] = [1] * n
    for i in range(1, n):
        for j in range(i, n):
            s[i][j] = s[i-1][j-1] + s[i][j-1]
    return s

def pascal_low(n):
    
    return [list(x) for x in zip(*pascal_upp(n))]

def pascal_sym(n):
    s = [[1] * n for _ in range(n)]
    for i in range(1, n):
        for j in range(1, n):
            s[i][j] = s[i-1][j] + s[i][j-1]
    return s
    

if __name__ == "__main__":
    n = 5
    print("\nUpper:")
    pp(pascal_upp(n))
    print("\nLower:")
    pp(pascal_low(n))
    print("\nSymmetric:")
    pp(pascal_sym(n))
Task: Pascal matrix generation

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

void pascal_low(int **mat, int n) {
    int i, j;

    for (i = 0; i < n; ++i)
        for (j = 0; j < n; ++j)
            if (i < j)
                mat[i][j] = 0;
            else if (i == j || j == 0)
                mat[i][j] = 1;
            else
                mat[i][j] = mat[i - 1][j - 1] + mat[i - 1][j];
}

void pascal_upp(int **mat, int n) {
    int i, j;

    for (i = 0; i < n; ++i)
        for (j = 0; j < n; ++j)
            if (i > j)
                mat[i][j] = 0;
            else if (i == j || i == 0)
                mat[i][j] = 1;
            else
                mat[i][j] = mat[i - 1][j - 1] + mat[i][j - 1];
}

void pascal_sym(int **mat, int n) {
    int i, j;

    for (i = 0; i < n; ++i)
        for (j = 0; j < n; ++j)
            if (i == 0 || j == 0)
                mat[i][j] = 1;
            else
                mat[i][j] = mat[i - 1][j] + mat[i][j - 1];
}

int main(int argc, char * argv[]) {
    int **mat;
    int i, j, n;

    
    n = 5;

    
    mat = calloc(n, sizeof(int *));
    for (i = 0; i < n; ++i)
        mat[i] = calloc(n, sizeof(int));

    
    printf("=== Pascal upper matrix ===\n");
    pascal_upp(mat, n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            printf("%4d%c", mat[i][j], j < n - 1 ? ' ' : '\n');

    printf("=== Pascal lower matrix ===\n");
    pascal_low(mat, n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            printf("%4d%c", mat[i][j], j < n - 1 ? ' ' : '\n');

    printf("=== Pascal symmetric matrix ===\n");
    pascal_sym(mat, n);
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            printf("%4d%c", mat[i][j], j < n - 1 ? ' ' : '\n');

    return 0;
}








VB: Option Base 1
Private Function pascal_upper(n As Integer)
    Dim res As Variant: ReDim res(n, n)
    For j = 1 To n
        res(1, j) = 1
    Next j
    For i = 2 To n
        res(i, 1) = 0
        For j = 2 To i
            res(j, i) = res(j, i - 1) + res(j - 1, i - 1)
        Next j
        For j = i + 1 To n
            res(j, i) = 0
        Next j
    Next i
    pascal_upper = res
End Function
 
Private Function pascal_symmetric(n As Integer)
    Dim res As Variant: ReDim res(n, n)
    For i = 1 To n
        res(i, 1) = 1
        res(1, i) = 1
    Next i
    For i = 2 To n
        For j = 2 To n
            res(i, j) = res(i - 1, j) + res(i, j - 1)
        Next j
    Next i
    pascal_symmetric = res
End Function

Private Sub pp(m As Variant)
    For i = 1 To UBound(m)
        For j = 1 To UBound(m, 2)
            Debug.Print Format(m(i, j), "@@@");
        Next j
        Debug.Print
    Next i
End Sub

Public Sub main()
    Debug.Print "=== Pascal upper matrix ==="
    pp pascal_upper(5)
    Debug.Print "=== Pascal lower matrix ==="
    pp WorksheetFunction.Transpose(pascal_upper(5))
    Debug.Print "=== Pascal symmetrical matrix ==="
    pp pascal_symmetric(5)
End Sub