Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Translate this program into Python but keep the logic exactly as in Julia. | ccall(:jl_exit_on_sigint, Cvoid, (Cint,), 0)
function timeit()
ticks = 0
try
while true
sleep(0.5)
ticks += 1
println(ticks)
end
catch
end
end
@time timeit()
println("Done.")
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Change the following Julia code into VB without altering its purpose. | ccall(:jl_exit_on_sigint, Cvoid, (Cint,), 0)
function timeit()
ticks = 0
try
while true
sleep(0.5)
ticks += 1
println(ticks)
end
catch
end
end
@time timeit()
println("Done.")
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Keep all operations the same but rewrite the snippet in Go. | ccall(:jl_exit_on_sigint, Cvoid, (Cint,), 0)
function timeit()
ticks = 0
try
while true
sleep(0.5)
ticks += 1
println(ticks)
end
catch
end
end
@time timeit()
println("Done.")
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Write the same code in C# as shown below in MATLAB. | function sigintHandle
k = 1;
tic
catchObj = onCleanup(@toc);
while true
pause(0.5)
fprintf('
k = k+1;
end
end
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Ensure the translated C++ code behaves exactly like the original MATLAB snippet. | function sigintHandle
k = 1;
tic
catchObj = onCleanup(@toc);
while true
pause(0.5)
fprintf('
k = k+1;
end
end
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Write the same code in Java as shown below in MATLAB. | function sigintHandle
k = 1;
tic
catchObj = onCleanup(@toc);
while true
pause(0.5)
fprintf('
k = k+1;
end
end
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Write a version of this MATLAB function in Python with identical behavior. | function sigintHandle
k = 1;
tic
catchObj = onCleanup(@toc);
while true
pause(0.5)
fprintf('
k = k+1;
end
end
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Convert this MATLAB block to VB, preserving its control flow and logic. | function sigintHandle
k = 1;
tic
catchObj = onCleanup(@toc);
while true
pause(0.5)
fprintf('
k = k+1;
end
end
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Convert this MATLAB block to Go, preserving its control flow and logic. | function sigintHandle
k = 1;
tic
catchObj = onCleanup(@toc);
while true
pause(0.5)
fprintf('
k = k+1;
end
end
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Keep all operations the same but rewrite the snippet in C. | import times, os, strutils
let t = epochTime()
proc handler() {.noconv.} =
echo "Program has run for ", formatFloat(epochTime() - t, precision = 0), " seconds."
quit 0
setControlCHook(handler)
for n in 1 ..< int64.high:
sleep 500
echo n
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Port the following code from Nim to C# with equivalent syntax and logic. | import times, os, strutils
let t = epochTime()
proc handler() {.noconv.} =
echo "Program has run for ", formatFloat(epochTime() - t, precision = 0), " seconds."
quit 0
setControlCHook(handler)
for n in 1 ..< int64.high:
sleep 500
echo n
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Ensure the translated C++ code behaves exactly like the original Nim snippet. | import times, os, strutils
let t = epochTime()
proc handler() {.noconv.} =
echo "Program has run for ", formatFloat(epochTime() - t, precision = 0), " seconds."
quit 0
setControlCHook(handler)
for n in 1 ..< int64.high:
sleep 500
echo n
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Ensure the translated Java code behaves exactly like the original Nim snippet. | import times, os, strutils
let t = epochTime()
proc handler() {.noconv.} =
echo "Program has run for ", formatFloat(epochTime() - t, precision = 0), " seconds."
quit 0
setControlCHook(handler)
for n in 1 ..< int64.high:
sleep 500
echo n
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Change the programming language of this snippet from Nim to Python without modifying what it does. | import times, os, strutils
let t = epochTime()
proc handler() {.noconv.} =
echo "Program has run for ", formatFloat(epochTime() - t, precision = 0), " seconds."
quit 0
setControlCHook(handler)
for n in 1 ..< int64.high:
sleep 500
echo n
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Keep all operations the same but rewrite the snippet in VB. | import times, os, strutils
let t = epochTime()
proc handler() {.noconv.} =
echo "Program has run for ", formatFloat(epochTime() - t, precision = 0), " seconds."
quit 0
setControlCHook(handler)
for n in 1 ..< int64.high:
sleep 500
echo n
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Translate the given Nim code snippet into Go without altering its behavior. | import times, os, strutils
let t = epochTime()
proc handler() {.noconv.} =
echo "Program has run for ", formatFloat(epochTime() - t, precision = 0), " seconds."
quit 0
setControlCHook(handler)
for n in 1 ..< int64.high:
sleep 500
echo n
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Port the following code from OCaml to C with equivalent syntax and logic. | #load "unix.cma";;
let start = Unix.gettimeofday ();;
Sys.set_signal Sys.sigint
(Sys.Signal_handle (fun _signum ->
Printf.printf "Ran for %f seconds.\n"
(Unix.gettimeofday () -. start);
exit 0));;
let rec loop n =
Printf.printf "%d\n%!" n;
Unix.sleep 1;
loop (n + 1)
in
loop 1;;
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the OCaml version. | #load "unix.cma";;
let start = Unix.gettimeofday ();;
Sys.set_signal Sys.sigint
(Sys.Signal_handle (fun _signum ->
Printf.printf "Ran for %f seconds.\n"
(Unix.gettimeofday () -. start);
exit 0));;
let rec loop n =
Printf.printf "%d\n%!" n;
Unix.sleep 1;
loop (n + 1)
in
loop 1;;
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Write the same algorithm in C++ as shown in this OCaml implementation. | #load "unix.cma";;
let start = Unix.gettimeofday ();;
Sys.set_signal Sys.sigint
(Sys.Signal_handle (fun _signum ->
Printf.printf "Ran for %f seconds.\n"
(Unix.gettimeofday () -. start);
exit 0));;
let rec loop n =
Printf.printf "%d\n%!" n;
Unix.sleep 1;
loop (n + 1)
in
loop 1;;
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Ensure the translated Java code behaves exactly like the original OCaml snippet. | #load "unix.cma";;
let start = Unix.gettimeofday ();;
Sys.set_signal Sys.sigint
(Sys.Signal_handle (fun _signum ->
Printf.printf "Ran for %f seconds.\n"
(Unix.gettimeofday () -. start);
exit 0));;
let rec loop n =
Printf.printf "%d\n%!" n;
Unix.sleep 1;
loop (n + 1)
in
loop 1;;
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Keep all operations the same but rewrite the snippet in Python. | #load "unix.cma";;
let start = Unix.gettimeofday ();;
Sys.set_signal Sys.sigint
(Sys.Signal_handle (fun _signum ->
Printf.printf "Ran for %f seconds.\n"
(Unix.gettimeofday () -. start);
exit 0));;
let rec loop n =
Printf.printf "%d\n%!" n;
Unix.sleep 1;
loop (n + 1)
in
loop 1;;
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Generate a VB translation of this OCaml snippet without changing its computational steps. | #load "unix.cma";;
let start = Unix.gettimeofday ();;
Sys.set_signal Sys.sigint
(Sys.Signal_handle (fun _signum ->
Printf.printf "Ran for %f seconds.\n"
(Unix.gettimeofday () -. start);
exit 0));;
let rec loop n =
Printf.printf "%d\n%!" n;
Unix.sleep 1;
loop (n + 1)
in
loop 1;;
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Preserve the algorithm and functionality while converting the code from OCaml to Go. | #load "unix.cma";;
let start = Unix.gettimeofday ();;
Sys.set_signal Sys.sigint
(Sys.Signal_handle (fun _signum ->
Printf.printf "Ran for %f seconds.\n"
(Unix.gettimeofday () -. start);
exit 0));;
let rec loop n =
Printf.printf "%d\n%!" n;
Unix.sleep 1;
loop (n + 1)
in
loop 1;;
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Preserve the algorithm and functionality while converting the code from Perl to C. | my $start = time;
my $arlm=5;
my $i;
$SIG{QUIT} = sub
{print " Ran for ", time - $start, " seconds.\n"; die; };
$SIG{INT} = sub
{print " Running for ", time - $start, " seconds.\n"; };
$SIG{ALRM} = sub
{print " After $arlm seconds i= $i. Executing for ", time - $start, " seconds.\n"; alarm $arlm };
alarm $arlm;
print " ^C to inerrupt, ^\\ to quit, takes a break at $arlm seconds \n";
while ( 1 ) {
for ( $w=11935000; $w--; $w>0 ){};
print ( ++$i," \n");
}
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Perl to C#. | my $start = time;
my $arlm=5;
my $i;
$SIG{QUIT} = sub
{print " Ran for ", time - $start, " seconds.\n"; die; };
$SIG{INT} = sub
{print " Running for ", time - $start, " seconds.\n"; };
$SIG{ALRM} = sub
{print " After $arlm seconds i= $i. Executing for ", time - $start, " seconds.\n"; alarm $arlm };
alarm $arlm;
print " ^C to inerrupt, ^\\ to quit, takes a break at $arlm seconds \n";
while ( 1 ) {
for ( $w=11935000; $w--; $w>0 ){};
print ( ++$i," \n");
}
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Transform the following Perl implementation into C++, maintaining the same output and logic. | my $start = time;
my $arlm=5;
my $i;
$SIG{QUIT} = sub
{print " Ran for ", time - $start, " seconds.\n"; die; };
$SIG{INT} = sub
{print " Running for ", time - $start, " seconds.\n"; };
$SIG{ALRM} = sub
{print " After $arlm seconds i= $i. Executing for ", time - $start, " seconds.\n"; alarm $arlm };
alarm $arlm;
print " ^C to inerrupt, ^\\ to quit, takes a break at $arlm seconds \n";
while ( 1 ) {
for ( $w=11935000; $w--; $w>0 ){};
print ( ++$i," \n");
}
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Produce a language-to-language conversion: from Perl to Java, same semantics. | my $start = time;
my $arlm=5;
my $i;
$SIG{QUIT} = sub
{print " Ran for ", time - $start, " seconds.\n"; die; };
$SIG{INT} = sub
{print " Running for ", time - $start, " seconds.\n"; };
$SIG{ALRM} = sub
{print " After $arlm seconds i= $i. Executing for ", time - $start, " seconds.\n"; alarm $arlm };
alarm $arlm;
print " ^C to inerrupt, ^\\ to quit, takes a break at $arlm seconds \n";
while ( 1 ) {
for ( $w=11935000; $w--; $w>0 ){};
print ( ++$i," \n");
}
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Convert this Perl block to Python, preserving its control flow and logic. | my $start = time;
my $arlm=5;
my $i;
$SIG{QUIT} = sub
{print " Ran for ", time - $start, " seconds.\n"; die; };
$SIG{INT} = sub
{print " Running for ", time - $start, " seconds.\n"; };
$SIG{ALRM} = sub
{print " After $arlm seconds i= $i. Executing for ", time - $start, " seconds.\n"; alarm $arlm };
alarm $arlm;
print " ^C to inerrupt, ^\\ to quit, takes a break at $arlm seconds \n";
while ( 1 ) {
for ( $w=11935000; $w--; $w>0 ){};
print ( ++$i," \n");
}
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Translate this program into VB but keep the logic exactly as in Perl. | my $start = time;
my $arlm=5;
my $i;
$SIG{QUIT} = sub
{print " Ran for ", time - $start, " seconds.\n"; die; };
$SIG{INT} = sub
{print " Running for ", time - $start, " seconds.\n"; };
$SIG{ALRM} = sub
{print " After $arlm seconds i= $i. Executing for ", time - $start, " seconds.\n"; alarm $arlm };
alarm $arlm;
print " ^C to inerrupt, ^\\ to quit, takes a break at $arlm seconds \n";
while ( 1 ) {
for ( $w=11935000; $w--; $w>0 ){};
print ( ++$i," \n");
}
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Generate an equivalent Go version of this Perl code. | my $start = time;
my $arlm=5;
my $i;
$SIG{QUIT} = sub
{print " Ran for ", time - $start, " seconds.\n"; die; };
$SIG{INT} = sub
{print " Running for ", time - $start, " seconds.\n"; };
$SIG{ALRM} = sub
{print " After $arlm seconds i= $i. Executing for ", time - $start, " seconds.\n"; alarm $arlm };
alarm $arlm;
print " ^C to inerrupt, ^\\ to quit, takes a break at $arlm seconds \n";
while ( 1 ) {
for ( $w=11935000; $w--; $w>0 ){};
print ( ++$i," \n");
}
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Transform the following PowerShell implementation into C, maintaining the same output and logic. | $Start_Time = (Get-date).second
Write-Host "Type CTRL-C to Terminate..."
$n = 1
Try
{
While($true)
{
Write-Host $n
$n ++
Start-Sleep -m 500
}
}
Finally
{
$End_Time = (Get-date).second
$Time_Diff = $End_Time - $Start_Time
Write-Host "Total time in seconds"$Time_Diff
}
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Transform the following PowerShell implementation into C#, maintaining the same output and logic. | $Start_Time = (Get-date).second
Write-Host "Type CTRL-C to Terminate..."
$n = 1
Try
{
While($true)
{
Write-Host $n
$n ++
Start-Sleep -m 500
}
}
Finally
{
$End_Time = (Get-date).second
$Time_Diff = $End_Time - $Start_Time
Write-Host "Total time in seconds"$Time_Diff
}
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Please provide an equivalent version of this PowerShell code in C++. | $Start_Time = (Get-date).second
Write-Host "Type CTRL-C to Terminate..."
$n = 1
Try
{
While($true)
{
Write-Host $n
$n ++
Start-Sleep -m 500
}
}
Finally
{
$End_Time = (Get-date).second
$Time_Diff = $End_Time - $Start_Time
Write-Host "Total time in seconds"$Time_Diff
}
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Produce a functionally identical Java code for the snippet given in PowerShell. | $Start_Time = (Get-date).second
Write-Host "Type CTRL-C to Terminate..."
$n = 1
Try
{
While($true)
{
Write-Host $n
$n ++
Start-Sleep -m 500
}
}
Finally
{
$End_Time = (Get-date).second
$Time_Diff = $End_Time - $Start_Time
Write-Host "Total time in seconds"$Time_Diff
}
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Generate a Python translation of this PowerShell snippet without changing its computational steps. | $Start_Time = (Get-date).second
Write-Host "Type CTRL-C to Terminate..."
$n = 1
Try
{
While($true)
{
Write-Host $n
$n ++
Start-Sleep -m 500
}
}
Finally
{
$End_Time = (Get-date).second
$Time_Diff = $End_Time - $Start_Time
Write-Host "Total time in seconds"$Time_Diff
}
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Generate a VB translation of this PowerShell snippet without changing its computational steps. | $Start_Time = (Get-date).second
Write-Host "Type CTRL-C to Terminate..."
$n = 1
Try
{
While($true)
{
Write-Host $n
$n ++
Start-Sleep -m 500
}
}
Finally
{
$End_Time = (Get-date).second
$Time_Diff = $End_Time - $Start_Time
Write-Host "Total time in seconds"$Time_Diff
}
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Keep all operations the same but rewrite the snippet in Go. | $Start_Time = (Get-date).second
Write-Host "Type CTRL-C to Terminate..."
$n = 1
Try
{
While($true)
{
Write-Host $n
$n ++
Start-Sleep -m 500
}
}
Finally
{
$End_Time = (Get-date).second
$Time_Diff = $End_Time - $Start_Time
Write-Host "Total time in seconds"$Time_Diff
}
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Translate this program into C but keep the logic exactly as in Racket. | #lang racket
(define now current-milliseconds)
(define start (now))
(with-handlers ([exn:break?
(λ(x)
(define elapsed (/ (- (now) start) 1000.))
(displayln (~a "Total time: " elapsed)))])
(for ([i (in-naturals)])
(displayln i)
(sleep 0.5)))
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Change the following Racket code into C# without altering its purpose. | #lang racket
(define now current-milliseconds)
(define start (now))
(with-handlers ([exn:break?
(λ(x)
(define elapsed (/ (- (now) start) 1000.))
(displayln (~a "Total time: " elapsed)))])
(for ([i (in-naturals)])
(displayln i)
(sleep 0.5)))
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Port the following code from Racket to C++ with equivalent syntax and logic. | #lang racket
(define now current-milliseconds)
(define start (now))
(with-handlers ([exn:break?
(λ(x)
(define elapsed (/ (- (now) start) 1000.))
(displayln (~a "Total time: " elapsed)))])
(for ([i (in-naturals)])
(displayln i)
(sleep 0.5)))
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Write the same code in Java as shown below in Racket. | #lang racket
(define now current-milliseconds)
(define start (now))
(with-handlers ([exn:break?
(λ(x)
(define elapsed (/ (- (now) start) 1000.))
(displayln (~a "Total time: " elapsed)))])
(for ([i (in-naturals)])
(displayln i)
(sleep 0.5)))
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Racket version. | #lang racket
(define now current-milliseconds)
(define start (now))
(with-handlers ([exn:break?
(λ(x)
(define elapsed (/ (- (now) start) 1000.))
(displayln (~a "Total time: " elapsed)))])
(for ([i (in-naturals)])
(displayln i)
(sleep 0.5)))
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Generate an equivalent VB version of this Racket code. | #lang racket
(define now current-milliseconds)
(define start (now))
(with-handlers ([exn:break?
(λ(x)
(define elapsed (/ (- (now) start) 1000.))
(displayln (~a "Total time: " elapsed)))])
(for ([i (in-naturals)])
(displayln i)
(sleep 0.5)))
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Please provide an equivalent version of this Racket code in Go. | #lang racket
(define now current-milliseconds)
(define start (now))
(with-handlers ([exn:break?
(λ(x)
(define elapsed (/ (- (now) start) 1000.))
(displayln (~a "Total time: " elapsed)))])
(for ([i (in-naturals)])
(displayln i)
(sleep 0.5)))
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Generate an equivalent C version of this COBOL code. | identification division.
program-id. signals.
data division.
working-storage section.
01 signal-flag pic 9 external.
88 signalled value 1.
01 half-seconds usage binary-long.
01 start-time usage binary-c-long.
01 end-time usage binary-c-long.
01 handler usage program-pointer.
01 SIGINT constant as 2.
procedure division.
call "gettimeofday" using start-time null
set handler to entry "handle-sigint"
call "signal" using by value SIGINT by value handler
perform until exit
if signalled then exit perform end-if
call "CBL_OC_NANOSLEEP" using 500000000
if signalled then exit perform end-if
add 1 to half-seconds
display half-seconds
end-perform
call "gettimeofday" using end-time null
subtract start-time from end-time
display "Program ran for " end-time " seconds"
goback.
end program signals.
identification division.
program-id. handle-sigint.
data division.
working-storage section.
01 signal-flag pic 9 external.
linkage section.
01 the-signal usage binary-long.
procedure division using by value the-signal returning omitted.
move 1 to signal-flag
goback.
end program handle-sigint.
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Port the following code from COBOL to C# with equivalent syntax and logic. | identification division.
program-id. signals.
data division.
working-storage section.
01 signal-flag pic 9 external.
88 signalled value 1.
01 half-seconds usage binary-long.
01 start-time usage binary-c-long.
01 end-time usage binary-c-long.
01 handler usage program-pointer.
01 SIGINT constant as 2.
procedure division.
call "gettimeofday" using start-time null
set handler to entry "handle-sigint"
call "signal" using by value SIGINT by value handler
perform until exit
if signalled then exit perform end-if
call "CBL_OC_NANOSLEEP" using 500000000
if signalled then exit perform end-if
add 1 to half-seconds
display half-seconds
end-perform
call "gettimeofday" using end-time null
subtract start-time from end-time
display "Program ran for " end-time " seconds"
goback.
end program signals.
identification division.
program-id. handle-sigint.
data division.
working-storage section.
01 signal-flag pic 9 external.
linkage section.
01 the-signal usage binary-long.
procedure division using by value the-signal returning omitted.
move 1 to signal-flag
goback.
end program handle-sigint.
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Translate the given COBOL code snippet into C++ without altering its behavior. | identification division.
program-id. signals.
data division.
working-storage section.
01 signal-flag pic 9 external.
88 signalled value 1.
01 half-seconds usage binary-long.
01 start-time usage binary-c-long.
01 end-time usage binary-c-long.
01 handler usage program-pointer.
01 SIGINT constant as 2.
procedure division.
call "gettimeofday" using start-time null
set handler to entry "handle-sigint"
call "signal" using by value SIGINT by value handler
perform until exit
if signalled then exit perform end-if
call "CBL_OC_NANOSLEEP" using 500000000
if signalled then exit perform end-if
add 1 to half-seconds
display half-seconds
end-perform
call "gettimeofday" using end-time null
subtract start-time from end-time
display "Program ran for " end-time " seconds"
goback.
end program signals.
identification division.
program-id. handle-sigint.
data division.
working-storage section.
01 signal-flag pic 9 external.
linkage section.
01 the-signal usage binary-long.
procedure division using by value the-signal returning omitted.
move 1 to signal-flag
goback.
end program handle-sigint.
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Produce a language-to-language conversion: from COBOL to Java, same semantics. | identification division.
program-id. signals.
data division.
working-storage section.
01 signal-flag pic 9 external.
88 signalled value 1.
01 half-seconds usage binary-long.
01 start-time usage binary-c-long.
01 end-time usage binary-c-long.
01 handler usage program-pointer.
01 SIGINT constant as 2.
procedure division.
call "gettimeofday" using start-time null
set handler to entry "handle-sigint"
call "signal" using by value SIGINT by value handler
perform until exit
if signalled then exit perform end-if
call "CBL_OC_NANOSLEEP" using 500000000
if signalled then exit perform end-if
add 1 to half-seconds
display half-seconds
end-perform
call "gettimeofday" using end-time null
subtract start-time from end-time
display "Program ran for " end-time " seconds"
goback.
end program signals.
identification division.
program-id. handle-sigint.
data division.
working-storage section.
01 signal-flag pic 9 external.
linkage section.
01 the-signal usage binary-long.
procedure division using by value the-signal returning omitted.
move 1 to signal-flag
goback.
end program handle-sigint.
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Port the following code from COBOL to Python with equivalent syntax and logic. | identification division.
program-id. signals.
data division.
working-storage section.
01 signal-flag pic 9 external.
88 signalled value 1.
01 half-seconds usage binary-long.
01 start-time usage binary-c-long.
01 end-time usage binary-c-long.
01 handler usage program-pointer.
01 SIGINT constant as 2.
procedure division.
call "gettimeofday" using start-time null
set handler to entry "handle-sigint"
call "signal" using by value SIGINT by value handler
perform until exit
if signalled then exit perform end-if
call "CBL_OC_NANOSLEEP" using 500000000
if signalled then exit perform end-if
add 1 to half-seconds
display half-seconds
end-perform
call "gettimeofday" using end-time null
subtract start-time from end-time
display "Program ran for " end-time " seconds"
goback.
end program signals.
identification division.
program-id. handle-sigint.
data division.
working-storage section.
01 signal-flag pic 9 external.
linkage section.
01 the-signal usage binary-long.
procedure division using by value the-signal returning omitted.
move 1 to signal-flag
goback.
end program handle-sigint.
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Produce a language-to-language conversion: from COBOL to VB, same semantics. | identification division.
program-id. signals.
data division.
working-storage section.
01 signal-flag pic 9 external.
88 signalled value 1.
01 half-seconds usage binary-long.
01 start-time usage binary-c-long.
01 end-time usage binary-c-long.
01 handler usage program-pointer.
01 SIGINT constant as 2.
procedure division.
call "gettimeofday" using start-time null
set handler to entry "handle-sigint"
call "signal" using by value SIGINT by value handler
perform until exit
if signalled then exit perform end-if
call "CBL_OC_NANOSLEEP" using 500000000
if signalled then exit perform end-if
add 1 to half-seconds
display half-seconds
end-perform
call "gettimeofday" using end-time null
subtract start-time from end-time
display "Program ran for " end-time " seconds"
goback.
end program signals.
identification division.
program-id. handle-sigint.
data division.
working-storage section.
01 signal-flag pic 9 external.
linkage section.
01 the-signal usage binary-long.
procedure division using by value the-signal returning omitted.
move 1 to signal-flag
goback.
end program handle-sigint.
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Change the following COBOL code into Go without altering its purpose. | identification division.
program-id. signals.
data division.
working-storage section.
01 signal-flag pic 9 external.
88 signalled value 1.
01 half-seconds usage binary-long.
01 start-time usage binary-c-long.
01 end-time usage binary-c-long.
01 handler usage program-pointer.
01 SIGINT constant as 2.
procedure division.
call "gettimeofday" using start-time null
set handler to entry "handle-sigint"
call "signal" using by value SIGINT by value handler
perform until exit
if signalled then exit perform end-if
call "CBL_OC_NANOSLEEP" using 500000000
if signalled then exit perform end-if
add 1 to half-seconds
display half-seconds
end-perform
call "gettimeofday" using end-time null
subtract start-time from end-time
display "Program ran for " end-time " seconds"
goback.
end program signals.
identification division.
program-id. handle-sigint.
data division.
working-storage section.
01 signal-flag pic 9 external.
linkage section.
01 the-signal usage binary-long.
procedure division using by value the-signal returning omitted.
move 1 to signal-flag
goback.
end program handle-sigint.
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Rewrite the snippet below in C so it works the same as the original REXX code. |
call time 'Reset'
signal on halt
do j=1
say right(j,20)
t=time('E')
do forever; u=time('Elapsed')
if u<t | u>t+.5 then iterate j
end
end
halt: say 'program HALTed, it ran for' format(time("ELapsed"),,2) 'seconds.'
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Ensure the translated C# code behaves exactly like the original REXX snippet. |
call time 'Reset'
signal on halt
do j=1
say right(j,20)
t=time('E')
do forever; u=time('Elapsed')
if u<t | u>t+.5 then iterate j
end
end
halt: say 'program HALTed, it ran for' format(time("ELapsed"),,2) 'seconds.'
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Write a version of this REXX function in C++ with identical behavior. |
call time 'Reset'
signal on halt
do j=1
say right(j,20)
t=time('E')
do forever; u=time('Elapsed')
if u<t | u>t+.5 then iterate j
end
end
halt: say 'program HALTed, it ran for' format(time("ELapsed"),,2) 'seconds.'
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Write the same algorithm in Java as shown in this REXX implementation. |
call time 'Reset'
signal on halt
do j=1
say right(j,20)
t=time('E')
do forever; u=time('Elapsed')
if u<t | u>t+.5 then iterate j
end
end
halt: say 'program HALTed, it ran for' format(time("ELapsed"),,2) 'seconds.'
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Can you help me rewrite this code in Python instead of REXX, keeping it the same logically? |
call time 'Reset'
signal on halt
do j=1
say right(j,20)
t=time('E')
do forever; u=time('Elapsed')
if u<t | u>t+.5 then iterate j
end
end
halt: say 'program HALTed, it ran for' format(time("ELapsed"),,2) 'seconds.'
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Translate the given REXX code snippet into VB without altering its behavior. |
call time 'Reset'
signal on halt
do j=1
say right(j,20)
t=time('E')
do forever; u=time('Elapsed')
if u<t | u>t+.5 then iterate j
end
end
halt: say 'program HALTed, it ran for' format(time("ELapsed"),,2) 'seconds.'
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Maintain the same structure and functionality when rewriting this code in Go. |
call time 'Reset'
signal on halt
do j=1
say right(j,20)
t=time('E')
do forever; u=time('Elapsed')
if u<t | u>t+.5 then iterate j
end
end
halt: say 'program HALTed, it ran for' format(time("ELapsed"),,2) 'seconds.'
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Change the following Ruby code into C without altering its purpose. | start = Time.utc
ch = Channel(Int32 | Symbol).new
spawn do
i = 0
loop do
sleep 1
ch.send(i += 1)
end
end
Signal::INT.trap do
Signal::INT.reset
ch.send(:kill)
end
loop do
x = ch.receive
break if x == :kill
puts x
end
elapsed = Time.utc - start
puts "Program has run for %5.3f seconds." % elapsed.total_seconds
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Convert this Ruby block to C#, preserving its control flow and logic. | start = Time.utc
ch = Channel(Int32 | Symbol).new
spawn do
i = 0
loop do
sleep 1
ch.send(i += 1)
end
end
Signal::INT.trap do
Signal::INT.reset
ch.send(:kill)
end
loop do
x = ch.receive
break if x == :kill
puts x
end
elapsed = Time.utc - start
puts "Program has run for %5.3f seconds." % elapsed.total_seconds
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Translate this program into C++ but keep the logic exactly as in Ruby. | start = Time.utc
ch = Channel(Int32 | Symbol).new
spawn do
i = 0
loop do
sleep 1
ch.send(i += 1)
end
end
Signal::INT.trap do
Signal::INT.reset
ch.send(:kill)
end
loop do
x = ch.receive
break if x == :kill
puts x
end
elapsed = Time.utc - start
puts "Program has run for %5.3f seconds." % elapsed.total_seconds
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Convert the following code from Ruby to Java, ensuring the logic remains intact. | start = Time.utc
ch = Channel(Int32 | Symbol).new
spawn do
i = 0
loop do
sleep 1
ch.send(i += 1)
end
end
Signal::INT.trap do
Signal::INT.reset
ch.send(:kill)
end
loop do
x = ch.receive
break if x == :kill
puts x
end
elapsed = Time.utc - start
puts "Program has run for %5.3f seconds." % elapsed.total_seconds
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Ruby version. | start = Time.utc
ch = Channel(Int32 | Symbol).new
spawn do
i = 0
loop do
sleep 1
ch.send(i += 1)
end
end
Signal::INT.trap do
Signal::INT.reset
ch.send(:kill)
end
loop do
x = ch.receive
break if x == :kill
puts x
end
elapsed = Time.utc - start
puts "Program has run for %5.3f seconds." % elapsed.total_seconds
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Maintain the same structure and functionality when rewriting this code in VB. | start = Time.utc
ch = Channel(Int32 | Symbol).new
spawn do
i = 0
loop do
sleep 1
ch.send(i += 1)
end
end
Signal::INT.trap do
Signal::INT.reset
ch.send(:kill)
end
loop do
x = ch.receive
break if x == :kill
puts x
end
elapsed = Time.utc - start
puts "Program has run for %5.3f seconds." % elapsed.total_seconds
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Change the programming language of this snippet from Ruby to Go without modifying what it does. | start = Time.utc
ch = Channel(Int32 | Symbol).new
spawn do
i = 0
loop do
sleep 1
ch.send(i += 1)
end
end
Signal::INT.trap do
Signal::INT.reset
ch.send(:kill)
end
loop do
x = ch.receive
break if x == :kill
puts x
end
elapsed = Time.utc - start
puts "Program has run for %5.3f seconds." % elapsed.total_seconds
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Transform the following Scala implementation into C, maintaining the same output and logic. |
import sun.misc.Signal
import sun.misc.SignalHandler
fun main(args: Array<String>) {
val startTime = System.currentTimeMillis()
Signal.handle(Signal("INT"), object : SignalHandler {
override fun handle(sig: Signal) {
val elapsedTime = (System.currentTimeMillis() - startTime) / 1000.0
println("\nThe program has run for $elapsedTime seconds")
System.exit(0)
}
})
var i = 0
while(true) {
println(i++)
Thread.sleep(500)
}
}
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C#. |
import sun.misc.Signal
import sun.misc.SignalHandler
fun main(args: Array<String>) {
val startTime = System.currentTimeMillis()
Signal.handle(Signal("INT"), object : SignalHandler {
override fun handle(sig: Signal) {
val elapsedTime = (System.currentTimeMillis() - startTime) / 1000.0
println("\nThe program has run for $elapsedTime seconds")
System.exit(0)
}
})
var i = 0
while(true) {
println(i++)
Thread.sleep(500)
}
}
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Convert the following code from Scala to C++, ensuring the logic remains intact. |
import sun.misc.Signal
import sun.misc.SignalHandler
fun main(args: Array<String>) {
val startTime = System.currentTimeMillis()
Signal.handle(Signal("INT"), object : SignalHandler {
override fun handle(sig: Signal) {
val elapsedTime = (System.currentTimeMillis() - startTime) / 1000.0
println("\nThe program has run for $elapsedTime seconds")
System.exit(0)
}
})
var i = 0
while(true) {
println(i++)
Thread.sleep(500)
}
}
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Keep all operations the same but rewrite the snippet in Java. |
import sun.misc.Signal
import sun.misc.SignalHandler
fun main(args: Array<String>) {
val startTime = System.currentTimeMillis()
Signal.handle(Signal("INT"), object : SignalHandler {
override fun handle(sig: Signal) {
val elapsedTime = (System.currentTimeMillis() - startTime) / 1000.0
println("\nThe program has run for $elapsedTime seconds")
System.exit(0)
}
})
var i = 0
while(true) {
println(i++)
Thread.sleep(500)
}
}
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Please provide an equivalent version of this Scala code in Python. |
import sun.misc.Signal
import sun.misc.SignalHandler
fun main(args: Array<String>) {
val startTime = System.currentTimeMillis()
Signal.handle(Signal("INT"), object : SignalHandler {
override fun handle(sig: Signal) {
val elapsedTime = (System.currentTimeMillis() - startTime) / 1000.0
println("\nThe program has run for $elapsedTime seconds")
System.exit(0)
}
})
var i = 0
while(true) {
println(i++)
Thread.sleep(500)
}
}
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Keep all operations the same but rewrite the snippet in VB. |
import sun.misc.Signal
import sun.misc.SignalHandler
fun main(args: Array<String>) {
val startTime = System.currentTimeMillis()
Signal.handle(Signal("INT"), object : SignalHandler {
override fun handle(sig: Signal) {
val elapsedTime = (System.currentTimeMillis() - startTime) / 1000.0
println("\nThe program has run for $elapsedTime seconds")
System.exit(0)
}
})
var i = 0
while(true) {
println(i++)
Thread.sleep(500)
}
}
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Maintain the same structure and functionality when rewriting this code in Go. |
import sun.misc.Signal
import sun.misc.SignalHandler
fun main(args: Array<String>) {
val startTime = System.currentTimeMillis()
Signal.handle(Signal("INT"), object : SignalHandler {
override fun handle(sig: Signal) {
val elapsedTime = (System.currentTimeMillis() - startTime) / 1000.0
println("\nThe program has run for $elapsedTime seconds")
System.exit(0)
}
})
var i = 0
while(true) {
println(i++)
Thread.sleep(500)
}
}
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Change the programming language of this snippet from Swift to C without modifying what it does. | import Foundation
let startTime = NSDate()
var signalReceived: sig_atomic_t = 0
signal(SIGINT) { signal in signalReceived = 1 }
for var i = 0;; {
if signalReceived == 1 { break }
usleep(500_000)
if signalReceived == 1 { break }
print(++i)
}
let endTime = NSDate()
print("Program has run for \(endTime.timeIntervalSinceDate(startTime)) seconds")
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C#. | import Foundation
let startTime = NSDate()
var signalReceived: sig_atomic_t = 0
signal(SIGINT) { signal in signalReceived = 1 }
for var i = 0;; {
if signalReceived == 1 { break }
usleep(500_000)
if signalReceived == 1 { break }
print(++i)
}
let endTime = NSDate()
print("Program has run for \(endTime.timeIntervalSinceDate(startTime)) seconds")
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Keep all operations the same but rewrite the snippet in C++. | import Foundation
let startTime = NSDate()
var signalReceived: sig_atomic_t = 0
signal(SIGINT) { signal in signalReceived = 1 }
for var i = 0;; {
if signalReceived == 1 { break }
usleep(500_000)
if signalReceived == 1 { break }
print(++i)
}
let endTime = NSDate()
print("Program has run for \(endTime.timeIntervalSinceDate(startTime)) seconds")
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Translate the given Swift code snippet into Java without altering its behavior. | import Foundation
let startTime = NSDate()
var signalReceived: sig_atomic_t = 0
signal(SIGINT) { signal in signalReceived = 1 }
for var i = 0;; {
if signalReceived == 1 { break }
usleep(500_000)
if signalReceived == 1 { break }
print(++i)
}
let endTime = NSDate()
print("Program has run for \(endTime.timeIntervalSinceDate(startTime)) seconds")
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Port the following code from Swift to Python with equivalent syntax and logic. | import Foundation
let startTime = NSDate()
var signalReceived: sig_atomic_t = 0
signal(SIGINT) { signal in signalReceived = 1 }
for var i = 0;; {
if signalReceived == 1 { break }
usleep(500_000)
if signalReceived == 1 { break }
print(++i)
}
let endTime = NSDate()
print("Program has run for \(endTime.timeIntervalSinceDate(startTime)) seconds")
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Rewrite this program in VB while keeping its functionality equivalent to the Swift version. | import Foundation
let startTime = NSDate()
var signalReceived: sig_atomic_t = 0
signal(SIGINT) { signal in signalReceived = 1 }
for var i = 0;; {
if signalReceived == 1 { break }
usleep(500_000)
if signalReceived == 1 { break }
print(++i)
}
let endTime = NSDate()
print("Program has run for \(endTime.timeIntervalSinceDate(startTime)) seconds")
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Convert this Swift snippet to Go and keep its semantics consistent. | import Foundation
let startTime = NSDate()
var signalReceived: sig_atomic_t = 0
signal(SIGINT) { signal in signalReceived = 1 }
for var i = 0;; {
if signalReceived == 1 { break }
usleep(500_000)
if signalReceived == 1 { break }
print(++i)
}
let endTime = NSDate()
print("Program has run for \(endTime.timeIntervalSinceDate(startTime)) seconds")
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Generate a C translation of this Tcl snippet without changing its computational steps. | package require Expect
proc sigint_handler {} {
puts "elapsed time: [expr {[clock seconds] - $::start_time}] seconds"
set ::looping false
}
trap sigint_handler SIGINT
set start_time [clock seconds]
set n 0
set looping true
while {$looping} {
puts [incr n]
after 500
}
| #include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
volatile sig_atomic_t gotint = 0;
void handleSigint() {
gotint = 1;
}
int main() {
clock_t startTime = clock();
signal(SIGINT, handleSigint);
int i=0;
for (;;) {
if (gotint)
break;
usleep(500000);
if (gotint)
break;
printf("%d\n", ++i);
}
clock_t endTime = clock();
double td = (endTime - startTime) / (double)CLOCKS_PER_SEC;
printf("Program has run for %5.3f seconds\n", td);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Tcl to C#. | package require Expect
proc sigint_handler {} {
puts "elapsed time: [expr {[clock seconds] - $::start_time}] seconds"
set ::looping false
}
trap sigint_handler SIGINT
set start_time [clock seconds]
set n 0
set looping true
while {$looping} {
puts [incr n]
after 500
}
| using System;
class Program
{
static DateTime start;
static void Main(string[] args)
{
start = DateTime.Now;
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
int counter = 0;
while (true)
{
Console.WriteLine(++counter);
System.Threading.Thread.Sleep(500);
}
}
static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
var end = DateTime.Now;
Console.WriteLine("This program ran for {0:000.000} seconds.", (end - start).TotalMilliseconds / 1000);
Environment.Exit(0);
}
}
|
Port the following code from Tcl to C++ with equivalent syntax and logic. | package require Expect
proc sigint_handler {} {
puts "elapsed time: [expr {[clock seconds] - $::start_time}] seconds"
set ::looping false
}
trap sigint_handler SIGINT
set start_time [clock seconds]
set n 0
set looping true
while {$looping} {
puts [incr n]
after 500
}
| #include <chrono>
#include <csignal>
#include <ctime>
#include <iostream>
#include <thread>
volatile sig_atomic_t gotint = 0;
void handler(int signum) {
gotint = 1;
}
int main() {
using namespace std;
signal(SIGINT, handler);
int i = 0;
clock_t startTime = clock();
while (true) {
if (gotint) break;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (gotint) break;
cout << ++i << endl;
}
clock_t endTime = clock();
double dt = (endTime - startTime) / (double)CLOCKS_PER_SEC;
cout << "Program has run for " << dt << " seconds" << endl;
return 0;
}
|
Convert this Tcl snippet to Java and keep its semantics consistent. | package require Expect
proc sigint_handler {} {
puts "elapsed time: [expr {[clock seconds] - $::start_time}] seconds"
set ::looping false
}
trap sigint_handler SIGINT
set start_time [clock seconds]
set n 0
set looping true
while {$looping} {
puts [incr n]
after 500
}
| import sun.misc.Signal;
import sun.misc.SignalHandler;
public class ExampleSignalHandler {
public static void main(String... args) throws InterruptedException {
final long start = System.nanoTime();
Signal.handle(new Signal("INT"), new SignalHandler() {
public void handle(Signal sig) {
System.out.format("\nProgram execution took %f seconds\n", (System.nanoTime() - start) / 1e9f);
System.exit(0);
}
});
int counter = 0;
while(true) {
System.out.println(counter++);
Thread.sleep(500);
}
}
}
|
Produce a language-to-language conversion: from Tcl to Python, same semantics. | package require Expect
proc sigint_handler {} {
puts "elapsed time: [expr {[clock seconds] - $::start_time}] seconds"
set ::looping false
}
trap sigint_handler SIGINT
set start_time [clock seconds]
set n 0
set looping true
while {$looping} {
puts [incr n]
after 500
}
| import time
def counter():
n = 0
t1 = time.time()
while True:
try:
time.sleep(0.5)
n += 1
print n
except KeyboardInterrupt, e:
print 'Program has run for %5.3f seconds.' % (time.time() - t1)
break
counter()
|
Generate a VB translation of this Tcl snippet without changing its computational steps. | package require Expect
proc sigint_handler {} {
puts "elapsed time: [expr {[clock seconds] - $::start_time}] seconds"
set ::looping false
}
trap sigint_handler SIGINT
set start_time [clock seconds]
set n 0
set looping true
while {$looping} {
puts [incr n]
after 500
}
| Module Module1
Dim startTime As Date
Sub Main()
startTime = Date.Now
AddHandler Console.CancelKeyPress, AddressOf Console_CancelKeyPress
Dim counter = 0
While True
counter += 1
Console.WriteLine(counter)
Threading.Thread.Sleep(500)
End While
End Sub
Sub Console_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs)
Dim stopTime = Date.Now
Console.WriteLine("This program ran for {0:000.000} seconds", (stopTime - startTime).TotalMilliseconds / 1000)
Environment.Exit(0)
End Sub
End Module
|
Translate the given Tcl code snippet into Go without altering its behavior. | package require Expect
proc sigint_handler {} {
puts "elapsed time: [expr {[clock seconds] - $::start_time}] seconds"
set ::looping false
}
trap sigint_handler SIGINT
set start_time [clock seconds]
set n 0
set looping true
while {$looping} {
puts [incr n]
after 500
}
| package main
import (
"fmt"
"os"
"os/signal"
"time"
)
func main() {
start := time.Now()
k := time.Tick(time.Second / 2)
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
for n := 1; ; {
select {
case <-k:
fmt.Println(n)
n++
case <-sc:
fmt.Printf("Ran for %f seconds.\n",
time.Now().Sub(start).Seconds())
return
}
}
}
|
Generate an equivalent PHP version of this Rust code. | #[cfg(unix)]
fn main() {
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::{Duration, Instant};
use libc::{sighandler_t, SIGINT};
let duration = Duration::from_secs(1) / 2;
static mut GOT_SIGINT: AtomicBool = AtomicBool::new(false);
unsafe {
GOT_SIGINT.store(false, Ordering::Release);
unsafe fn handle_sigint() {
GOT_SIGINT.store(true, Ordering::Release);
}
libc::signal(SIGINT, handle_sigint as sighandler_t);
}
let start = Instant::now();
let mut i = 0u32;
loop {
thread::sleep(duration);
if unsafe { GOT_SIGINT.load(Ordering::Acquire) } {
break;
}
i += 1;
println!("{}", i);
}
let elapsed = start.elapsed();
println!("Program has run for {} seconds", elapsed.as_secs());
}
#[cfg(not(unix))]
fn main() {
println!("Not supported on this platform");
}
| <?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>
|
Convert the following code from Ada to PHP, ensuring the logic remains intact. | with Ada.Interrupts; use Ada.Interrupts;
with Ada.Interrupts.Names; use Ada.Interrupts.Names;
package Sigint_Handler is
protected Handler is
entry Wait;
procedure Handle;
pragma Interrupt_Handler(Handle);
pragma Attach_Handler(Handle, Sigint);
private
Call_Count : Natural := 0;
end Handler;
end Sigint_Handler;
| <?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>
|
Generate an equivalent PHP version of this AutoHotKey code. | Start:=A_TickCount
counter=0
SetTimer, timer, 500
return
timer:
Send % ++Counter "`n"
return
^c::
SetTimer, timer, off
SetFormat, float, 0.3
Send, % "Task took " (A_TickCount-Start)/1000 " Seconds"
ExitApp
return
| <?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>
|
Rewrite the snippet below in PHP so it works the same as the original BBC_Basic code. |
INSTALL @lib$+"CALLBACK"
CTRL_C_EVENT = 0
SYS "GetStdHandle", -10 TO @hfile%(1)
SYS "GetStdHandle", -11 TO @hfile%(2)
*INPUT 13
*OUTPUT 14
ON ERROR PRINT REPORT$ : QUIT ERR
CtrlC% = FALSE
handler% = FN_callback(FNsigint(), 1)
SYS FN_syscalls("SetConsoleCtrlHandler"), handler%, 1 TO !FN_systo(res%)
IF res%=0 PRINT "Could not set SIGINT handler" : QUIT 1
PRINT "Press Ctrl+C to test...."
TIME = 0
Time% = 50
REPEAT
WAIT 1
IF TIME > Time% THEN
PRINT Time%
Time% += 50
ENDIF
UNTIL CtrlC%
PRINT "Ctrl+C was pressed after "; TIME/100 " seconds."
QUIT
DEF FNsigint(T%)
CASE T% OF
WHEN CTRL_C_EVENT: CtrlC% = TRUE : = 1
ENDCASE
= 0
| <?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>
|
Produce a language-to-language conversion: from Clojure to PHP, same semantics. | (require 'clojure.repl)
(def start (System/nanoTime))
(defn shutdown [_]
(println "Received INT after"
(/ (- (System/nanoTime) start) 1e9)
"seconds.")
(System/exit 0))
(clojure.repl/set-break-handler! shutdown)
(doseq [i (range)]
(prn i)
(Thread/sleep 500))
| <?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>
|
Generate a PHP translation of this Common_Lisp snippet without changing its computational steps. | (ql:quickload :cffi)
(defconstant +SIGINT+ 2)
(defmacro set-signal-handler (signo &body body)
(let ((handler (gensym "HANDLER")))
`(progn
(cffi:defcallback ,handler :void ((signo :int))
(declare (ignore signo))
,@body)
(cffi:foreign-funcall "signal" :int ,signo :pointer (cffi:callback ,handler)))))
(defvar *initial* (get-internal-real-time))
(set-signal-handler +SIGINT+
(format t "Ran for ~a seconds~&" (/ (- (get-internal-real-time) *initial*) internal-time-units-per-second))
(quit))
(let ((i 0))
(loop do
(format t "~a~&" (incf i))
(sleep 0.5)))
| <?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>
|
Port the provided D code into PHP while preserving the original functionality. | import core.stdc.signal;
import core.thread;
import std.concurrency;
import std.datetime.stopwatch;
import std.stdio;
__gshared int gotint = 0;
extern(C) void handleSigint(int sig) nothrow @nogc @system {
gotint = 1;
}
void main() {
auto sw = StopWatch(AutoStart.yes);
signal(SIGINT, &handleSigint);
for (int i=0; !gotint;) {
Thread.sleep(500_000.usecs);
if (gotint) {
break;
}
writeln(++i);
}
sw.stop();
auto td = sw.peek();
writeln("Program has run for ", td);
}
| <?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>
|
Convert the following code from Erlang to PHP, ensuring the logic remains intact. | #! /usr/bin/env escript
main([]) ->
erlang:unregister(erl_signal_server),
erlang:register(erl_signal_server, self()),
Start = seconds(),
os:set_signal(sigquit, handle),
Pid = spawn(fun() -> output_loop(1) end),
receive
{notify, sigquit} ->
erlang:exit(Pid, normal),
Seconds = seconds() - Start,
io:format("Program has run for ~b seconds~n", [Seconds])
end.
seconds() ->
calendar:datetime_to_gregorian_seconds({date(),time()}).
output_loop(N) ->
io:format("~b~n",[N]),
timer:sleep(500),
output_loop(N + 1).
| <?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>
|
Write the same algorithm in PHP as shown in this F# implementation. | open System
let rec loop n = Console.WriteLine( n:int )
Threading.Thread.Sleep( 500 )
loop (n + 1)
let main() =
let start = DateTime.Now
Console.CancelKeyPress.Add(
fun _ -> let span = DateTime.Now - start
printfn "Program has run for %.0f seconds" span.TotalSeconds
)
loop 1
main()
| <?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>
|
Convert the following code from Forth to PHP, ensuring the logic remains intact. | -28 constant SIGINT
: numbers
begin dup . cr 1+ 500 ms again ;
: main
utime
0 begin
['] numbers catch
SIGINT =
until drop
utime d- dnegate
<# # # # # # # [char] . hold #s #> type ." seconds" ;
main bye
| <?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>
|
Convert the following code from Fortran to PHP, ensuring the logic remains intact. | program signal_handling
use, intrinsic :: iso_fortran_env, only: atomic_logical_kind
implicit none
interface
integer(C_INT) function usleep(microseconds) bind(c)
use, intrinsic :: iso_c_binding, only: C_INT, C_INT32_T
integer(C_INT32_T), value :: microseconds
end function usleep
end interface
integer, parameter :: half_second = 500000
integer, parameter :: sigint = 2
integer, parameter :: sigquit = 3
logical(atomic_logical_kind) :: interrupt_received[*]
integer :: half_seconds
logical :: interrupt_received_ref
interrupt_received = .false.
half_seconds = 0
call signal(sigint, signal_handler)
call signal(sigquit, signal_handler)
do
if (usleep(half_second) == -1) &
print *, "Call to usleep interrupted."
call atomic_ref(interrupt_received_ref, interrupt_received)
if (interrupt_received_ref) then
print "(A,I0,A)", "Program ran for ", half_seconds / 2, " second(s)."
stop
end if
half_seconds = half_seconds + 1
print "(I0)", half_seconds
end do
contains
subroutine signal_handler(sig_num)
use, intrinsic :: iso_c_binding, only: C_INT
integer(C_INT), value, intent(in) :: sig_num
select case (sig_num)
case (sigint)
print *, "Received SIGINT."
case (sigquit)
print *, "Received SIGQUIT."
end select
call atomic_define(interrupt_received, .true.)
end subroutine signal_handler
end program signal_handling
| <?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>
|
Write the same code in PHP as shown below in Haskell. | import Prelude hiding (catch)
import Control.Exception (catch, throwIO, AsyncException(UserInterrupt))
import Data.Time.Clock (getCurrentTime, diffUTCTime)
import Control.Concurrent (threadDelay)
main = do t0 <- getCurrentTime
catch (loop 0)
(\e -> if e == UserInterrupt
then do t1 <- getCurrentTime
putStrLn ("\nTime: " ++ show (diffUTCTime t1 t0))
else throwIO e)
loop i = do print i
threadDelay 500000
loop (i + 1)
| <?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>
|
Translate this program into PHP but keep the logic exactly as in Julia. | ccall(:jl_exit_on_sigint, Cvoid, (Cint,), 0)
function timeit()
ticks = 0
try
while true
sleep(0.5)
ticks += 1
println(ticks)
end
catch
end
end
@time timeit()
println("Done.")
| <?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>
|
Change the programming language of this snippet from MATLAB to PHP without modifying what it does. | function sigintHandle
k = 1;
tic
catchObj = onCleanup(@toc);
while true
pause(0.5)
fprintf('
k = k+1;
end
end
| <?php
declare(ticks = 1);
$start = microtime(true);
function mySigHandler() {
global $start;
$elapsed = microtime(true) - $start;
echo "Ran for $elapsed seconds.\n";
exit();
}
pcntl_signal(SIGINT, 'mySigHandler');
for ($n = 0; ; usleep(500000)) // 0.5 seconds
echo ++$n, "\n";
?>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.