Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Please provide an equivalent version of this Nim code in PHP. | import math
for i in 1..<5000:
var sum: int64 = 0
var number = i
while number > 0:
var digit = number mod 10
sum += digit ^ digit
number = number div 10
if sum == i:
echo i
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Produce a functionally identical PHP code for the snippet given in Nim. | import math
for i in 1..<5000:
var sum: int64 = 0
var number = i
while number > 0:
var digit = number mod 10
sum += digit ^ digit
number = number div 10
if sum == i:
echo i
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Change the following OCaml code into PHP without altering its purpose. | let is_munchausen n =
let pwr = [|1; 1; 4; 27; 256; 3125; 46656; 823543; 16777216; 387420489|] in
let rec aux x = if x < 10 then pwr.(x) else aux (x / 10) + pwr.(x mod 10) in
n = aux n
let () =
Seq.(ints 1 |> take 5000 |> filter is_munchausen |> iter (Printf.printf " %u"))
|> print_newline
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Produce a functionally identical PHP code for the snippet given in OCaml. | let is_munchausen n =
let pwr = [|1; 1; 4; 27; 256; 3125; 46656; 823543; 16777216; 387420489|] in
let rec aux x = if x < 10 then pwr.(x) else aux (x / 10) + pwr.(x mod 10) in
n = aux n
let () =
Seq.(ints 1 |> take 5000 |> filter is_munchausen |> iter (Printf.printf " %u"))
|> print_newline
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Rewrite the snippet below in PHP so it works the same as the original Pascal code. |
uses
sysutils;
type
tdigit = byte;
const
base = 10;
maxDigits = base-1;
var
DgtPotDgt : array[0..base-1] of NativeUint;
cnt: NativeUint;
function CheckSameDigits(n1,n2:NativeUInt):boolean;
var
dgtCnt : array[0..Base-1] of NativeInt;
i : NativeUInt;
Begin
fillchar(dgtCnt,SizeOf(dgtCnt),#0);
repeat
i := n1;n1 := n1 div base;i := i-n1*base;inc(dgtCnt[i]);
i := n2;n2 := n2 div base;i := i-n2*base;dec(dgtCnt[i]);
until (n1=0) AND (n2= 0 );
result := true;
For i := 0 to Base-1 do
result := result AND (dgtCnt[i]=0);
end;
procedure Munch(number,DgtPowSum,minDigit:NativeUInt;digits:NativeInt);
var
i: NativeUint;
begin
inc(cnt);
number := number*base;
IF digits > 1 then
Begin
For i := minDigit to base-1 do
Munch(number+i,DgtPowSum+DgtPotDgt[i],i,digits-1);
end
else
For i := minDigit to base-1 do
IF (number+i)<= (DgtPowSum+DgtPotDgt[i]) then
IF CheckSameDigits(number+i,DgtPowSum+DgtPotDgt[i]) then
iF number+i>0 then
writeln(Format('%*d %.*d',
[maxDigits,DgtPowSum+DgtPotDgt[i],maxDigits,number+i]));
end;
procedure InitDgtPotDgt;
var
i,k,dgtpow: NativeUint;
Begin
DgtPotDgt[0]:= 0;
For i := 1 to Base-1 do
Begin
dgtpow := i;
For k := 2 to i do
dgtpow := dgtpow*i;
DgtPotDgt[i] := dgtpow;
end;
end;
begin
cnt := 0;
InitDgtPotDgt;
Munch(0,0,0,maxDigits);
writeln('Check Count ',cnt);
end.
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Produce a functionally identical PHP code for the snippet given in Pascal. |
uses
sysutils;
type
tdigit = byte;
const
base = 10;
maxDigits = base-1;
var
DgtPotDgt : array[0..base-1] of NativeUint;
cnt: NativeUint;
function CheckSameDigits(n1,n2:NativeUInt):boolean;
var
dgtCnt : array[0..Base-1] of NativeInt;
i : NativeUInt;
Begin
fillchar(dgtCnt,SizeOf(dgtCnt),#0);
repeat
i := n1;n1 := n1 div base;i := i-n1*base;inc(dgtCnt[i]);
i := n2;n2 := n2 div base;i := i-n2*base;dec(dgtCnt[i]);
until (n1=0) AND (n2= 0 );
result := true;
For i := 0 to Base-1 do
result := result AND (dgtCnt[i]=0);
end;
procedure Munch(number,DgtPowSum,minDigit:NativeUInt;digits:NativeInt);
var
i: NativeUint;
begin
inc(cnt);
number := number*base;
IF digits > 1 then
Begin
For i := minDigit to base-1 do
Munch(number+i,DgtPowSum+DgtPotDgt[i],i,digits-1);
end
else
For i := minDigit to base-1 do
IF (number+i)<= (DgtPowSum+DgtPotDgt[i]) then
IF CheckSameDigits(number+i,DgtPowSum+DgtPotDgt[i]) then
iF number+i>0 then
writeln(Format('%*d %.*d',
[maxDigits,DgtPowSum+DgtPotDgt[i],maxDigits,number+i]));
end;
procedure InitDgtPotDgt;
var
i,k,dgtpow: NativeUint;
Begin
DgtPotDgt[0]:= 0;
For i := 1 to Base-1 do
Begin
dgtpow := i;
For k := 2 to i do
dgtpow := dgtpow*i;
DgtPotDgt[i] := dgtpow;
end;
end;
begin
cnt := 0;
InitDgtPotDgt;
Munch(0,0,0,maxDigits);
writeln('Check Count ',cnt);
end.
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Translate the given Perl code snippet into PHP without altering its behavior. | use List::Util "sum";
for my $n (1..5000) {
print "$n\n" if $n == sum( map { $_**$_ } split(//,$n) );
}
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Generate a PHP translation of this Perl snippet without changing its computational steps. | use List::Util "sum";
for my $n (1..5000) {
print "$n\n" if $n == sum( map { $_**$_ } split(//,$n) );
}
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Please provide an equivalent version of this COBOL code in PHP. | IDENTIFICATION DIVISION.
PROGRAM-ID. MUNCHAUSEN.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 VARIABLES.
03 CANDIDATE PIC 9(4).
03 DIGITS PIC 9 OCCURS 4 TIMES, REDEFINES CANDIDATE.
03 DIGIT PIC 9.
03 POWER-SUM PIC 9(5).
01 OUTPUT-LINE.
03 OUT-NUM PIC ZZZ9.
PROCEDURE DIVISION.
BEGIN.
PERFORM MUNCHAUSEN-TEST VARYING CANDIDATE FROM 1 BY 1
UNTIL CANDIDATE IS GREATER THAN 6000.
STOP RUN.
MUNCHAUSEN-TEST.
MOVE ZERO TO POWER-SUM.
MOVE 1 TO DIGIT.
INSPECT CANDIDATE TALLYING DIGIT FOR LEADING '0'.
PERFORM ADD-DIGIT-POWER VARYING DIGIT FROM DIGIT BY 1
UNTIL DIGIT IS GREATER THAN 4.
IF POWER-SUM IS EQUAL TO CANDIDATE,
MOVE CANDIDATE TO OUT-NUM,
DISPLAY OUTPUT-LINE.
ADD-DIGIT-POWER.
COMPUTE POWER-SUM =
POWER-SUM + DIGITS(DIGIT) ** DIGITS(DIGIT)
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Preserve the algorithm and functionality while converting the code from COBOL to PHP. | IDENTIFICATION DIVISION.
PROGRAM-ID. MUNCHAUSEN.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 VARIABLES.
03 CANDIDATE PIC 9(4).
03 DIGITS PIC 9 OCCURS 4 TIMES, REDEFINES CANDIDATE.
03 DIGIT PIC 9.
03 POWER-SUM PIC 9(5).
01 OUTPUT-LINE.
03 OUT-NUM PIC ZZZ9.
PROCEDURE DIVISION.
BEGIN.
PERFORM MUNCHAUSEN-TEST VARYING CANDIDATE FROM 1 BY 1
UNTIL CANDIDATE IS GREATER THAN 6000.
STOP RUN.
MUNCHAUSEN-TEST.
MOVE ZERO TO POWER-SUM.
MOVE 1 TO DIGIT.
INSPECT CANDIDATE TALLYING DIGIT FOR LEADING '0'.
PERFORM ADD-DIGIT-POWER VARYING DIGIT FROM DIGIT BY 1
UNTIL DIGIT IS GREATER THAN 4.
IF POWER-SUM IS EQUAL TO CANDIDATE,
MOVE CANDIDATE TO OUT-NUM,
DISPLAY OUTPUT-LINE.
ADD-DIGIT-POWER.
COMPUTE POWER-SUM =
POWER-SUM + DIGITS(DIGIT) ** DIGITS(DIGIT)
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Translate this program into PHP but keep the logic exactly as in REXX. | Do n=0 To 10000
If n=m(n) Then
Say n
End
Exit
m: Parse Arg z
res=0
Do While z>''
Parse Var z c +1 z
res=res+c**c
End
Return res
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Rewrite the snippet below in PHP so it works the same as the original REXX code. | Do n=0 To 10000
If n=m(n) Then
Say n
End
Exit
m: Parse Arg z
res=0
Do While z>''
Parse Var z c +1 z
res=res+c**c
End
Return res
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Generate a PHP translation of this Ruby snippet without changing its computational steps. | puts (1..5000).select{|n| n.digits.sum{|d| d**d} == n}
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Change the programming language of this snippet from Ruby to PHP without modifying what it does. | puts (1..5000).select{|n| n.digits.sum{|d| d**d} == n}
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Produce a language-to-language conversion: from Scala to PHP, same semantics. |
val powers = IntArray(10)
fun isMunchausen(n: Int): Boolean {
if (n < 0) return false
var sum = 0L
var nn = n
while (nn > 0) {
sum += powers[nn % 10]
if (sum > n.toLong()) return false
nn /= 10
}
return sum == n.toLong()
}
fun main(args: Array<String>) {
for (i in 1..9) powers[i] = Math.pow(i.toDouble(), i.toDouble()).toInt()
println("The Munchausen numbers between 0 and 500 million are:")
for (i in 0..500000000) if (isMunchausen(i))print ("$i ")
println()
}
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Convert the following code from Scala to PHP, ensuring the logic remains intact. |
val powers = IntArray(10)
fun isMunchausen(n: Int): Boolean {
if (n < 0) return false
var sum = 0L
var nn = n
while (nn > 0) {
sum += powers[nn % 10]
if (sum > n.toLong()) return false
nn /= 10
}
return sum == n.toLong()
}
fun main(args: Array<String>) {
for (i in 1..9) powers[i] = Math.pow(i.toDouble(), i.toDouble()).toInt()
println("The Munchausen numbers between 0 and 500 million are:")
for (i in 0..500000000) if (isMunchausen(i))print ("$i ")
println()
}
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Produce a language-to-language conversion: from Swift to PHP, same semantics. | import Foundation
func isMünchhausen(_ n: Int) -> Bool {
let nums = String(n).map(String.init).compactMap(Int.init)
return Int(nums.map({ pow(Double($0), Double($0)) }).reduce(0, +)) == n
}
for i in 1...5000 where isMünchhausen(i) {
print(i)
}
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Write a version of this Swift function in PHP with identical behavior. | import Foundation
func isMünchhausen(_ n: Int) -> Bool {
let nums = String(n).map(String.init).compactMap(Int.init)
return Int(nums.map({ pow(Double($0), Double($0)) }).reduce(0, +)) == n
}
for i in 1...5000 where isMünchhausen(i) {
print(i)
}
| <?php
$pwr = array_fill(0, 10, 0);
function isMunchhausen($n)
{
global $pwr;
$sm = 0;
$temp = $n;
while ($temp) {
$sm= $sm + $pwr[($temp % 10)];
$temp = (int)($temp / 10);
}
return $sm == $n;
}
for ($i = 0; $i < 10; $i++) {
$pwr[$i] = pow((float)($i), (float)($i));
}
for ($i = 1; $i < 5000 + 1; $i++) {
if (isMunchhausen($i)) {
echo $i . PHP_EOL;
}
}
|
Port the provided C++ code into Rust while preserving the original functionality. | #include <math.h>
#include <iostream>
unsigned pwr[10];
unsigned munch( unsigned i ) {
unsigned sum = 0;
while( i ) {
sum += pwr[(i % 10)];
i /= 10;
}
return sum;
}
int main( int argc, char* argv[] ) {
for( int i = 0; i < 10; i++ )
pwr[i] = (unsigned)pow( (float)i, (float)i );
std::cout << "Munchausen Numbers\n==================\n";
for( unsigned i = 1; i < 5000; i++ )
if( i == munch( i ) ) std::cout << i << "\n";
return 0;
}
| fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000 : {:?}", solutions);
}
|
Please provide an equivalent version of this C++ code in Rust. | #include <math.h>
#include <iostream>
unsigned pwr[10];
unsigned munch( unsigned i ) {
unsigned sum = 0;
while( i ) {
sum += pwr[(i % 10)];
i /= 10;
}
return sum;
}
int main( int argc, char* argv[] ) {
for( int i = 0; i < 10; i++ )
pwr[i] = (unsigned)pow( (float)i, (float)i );
std::cout << "Munchausen Numbers\n==================\n";
for( unsigned i = 1; i < 5000; i++ )
if( i == munch( i ) ) std::cout << i << "\n";
return 0;
}
| fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000 : {:?}", solutions);
}
|
Maintain the same structure and functionality when rewriting this code in Rust. | Func<char, int> toInt = c => c-'0';
foreach (var i in Enumerable.Range(1,5000)
.Where(n => n == n.ToString()
.Sum(x => Math.Pow(toInt(x), toInt(x)))))
Console.WriteLine(i);
| fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000 : {:?}", solutions);
}
|
Produce a language-to-language conversion: from C# to Rust, same semantics. | Func<char, int> toInt = c => c-'0';
foreach (var i in Enumerable.Range(1,5000)
.Where(n => n == n.ToString()
.Sum(x => Math.Pow(toInt(x), toInt(x)))))
Console.WriteLine(i);
| fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000 : {:?}", solutions);
}
|
Convert this Java block to Rust, preserving its control flow and logic. | public class Main {
public static void main(String[] args) {
for(int i = 0 ; i <= 5000 ; i++ ){
int val = String.valueOf(i).chars().map(x -> (int) Math.pow( x-48 ,x-48)).sum();
if( i == val){
System.out.println( i + " (munchausen)");
}
}
}
}
| fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000 : {:?}", solutions);
}
|
Produce a language-to-language conversion: from Java to Rust, same semantics. | public class Main {
public static void main(String[] args) {
for(int i = 0 ; i <= 5000 ; i++ ){
int val = String.valueOf(i).chars().map(x -> (int) Math.pow( x-48 ,x-48)).sum();
if( i == val){
System.out.println( i + " (munchausen)");
}
}
}
}
| fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000 : {:?}", solutions);
}
|
Port the following code from Go to Rust with equivalent syntax and logic. | package main
import(
"fmt"
"math"
)
var powers [10]int
func isMunchausen(n int) bool {
if n < 0 { return false }
n64 := int64(n)
nn := n64
var sum int64 = 0
for nn > 0 {
sum += int64(powers[nn % 10])
if sum > n64 { return false }
nn /= 10
}
return sum == n64
}
func main() {
for i := 1; i <= 9; i++ {
d := float64(i)
powers[i] = int(math.Pow(d, d))
}
fmt.Println("The Munchausen numbers between 0 and 500 million are:")
for i := 0; i <= 500000000; i++ {
if isMunchausen(i) { fmt.Printf("%d ", i) }
}
fmt.Println()
}
| fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000 : {:?}", solutions);
}
|
Please provide an equivalent version of this Go code in Rust. | package main
import(
"fmt"
"math"
)
var powers [10]int
func isMunchausen(n int) bool {
if n < 0 { return false }
n64 := int64(n)
nn := n64
var sum int64 = 0
for nn > 0 {
sum += int64(powers[nn % 10])
if sum > n64 { return false }
nn /= 10
}
return sum == n64
}
func main() {
for i := 1; i <= 9; i++ {
d := float64(i)
powers[i] = int(math.Pow(d, d))
}
fmt.Println("The Munchausen numbers between 0 and 500 million are:")
for i := 0; i <= 500000000; i++ {
if isMunchausen(i) { fmt.Printf("%d ", i) }
}
fmt.Println()
}
| fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000 : {:?}", solutions);
}
|
Can you help me rewrite this code in Python instead of Rust, keeping it the same logically? | fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000 : {:?}", solutions);
}
| for i in range(5000):
if i == sum(int(x) ** int(x) for x in str(i)):
print(i)
|
Write the same code in Python as shown below in Rust. | fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000 : {:?}", solutions);
}
| for i in range(5000):
if i == sum(int(x) ** int(x) for x in str(i)):
print(i)
|
Convert this Rust block to VB, preserving its control flow and logic. | fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000 : {:?}", solutions);
}
| Option Explicit
Sub Main_Munchausen_numbers()
Dim i&
For i = 1 To 5000
If IsMunchausen(i) Then Debug.Print i & " is a munchausen number."
Next i
End Sub
Function IsMunchausen(Number As Long) As Boolean
Dim Digits, i As Byte, Tot As Long
Digits = Split(StrConv(Number, vbUnicode), Chr(0))
For i = 0 To UBound(Digits) - 1
Tot = (Digits(i) ^ Digits(i)) + Tot
Next i
IsMunchausen = (Tot = Number)
End Function
|
Generate a VB translation of this Rust snippet without changing its computational steps. | fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000 : {:?}", solutions);
}
| Option Explicit
Sub Main_Munchausen_numbers()
Dim i&
For i = 1 To 5000
If IsMunchausen(i) Then Debug.Print i & " is a munchausen number."
Next i
End Sub
Function IsMunchausen(Number As Long) As Boolean
Dim Digits, i As Byte, Tot As Long
Digits = Split(StrConv(Number, vbUnicode), Chr(0))
For i = 0 To UBound(Digits) - 1
Tot = (Digits(i) ^ Digits(i)) + Tot
Next i
IsMunchausen = (Tot = Number)
End Function
|
Convert this C snippet to Rust and keep its semantics consistent. | #include <stdio.h>
#include <math.h>
int main() {
for (int i = 1; i < 5000; i++) {
int sum = 0;
for (int number = i; number > 0; number /= 10) {
int digit = number % 10;
sum += pow(digit, digit);
}
if (sum == i) {
printf("%i\n", i);
}
}
return 0;
}
| fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000 : {:?}", solutions);
}
|
Write the same algorithm in Rust as shown in this C implementation. | #include <stdio.h>
#include <math.h>
int main() {
for (int i = 1; i < 5000; i++) {
int sum = 0;
for (int number = i; number > 0; number /= 10) {
int digit = number % 10;
sum += pow(digit, digit);
}
if (sum == i) {
printf("%i\n", i);
}
}
return 0;
}
| fn main() {
let mut solutions = Vec::new();
for num in 1..5_000 {
let power_sum = num.to_string()
.chars()
.map(|c| {
let digit = c.to_digit(10).unwrap();
(digit as f64).powi(digit as i32) as usize
})
.sum::<usize>();
if power_sum == num {
solutions.push(num);
}
}
println!("Munchausen numbers below 5_000 : {:?}", solutions);
}
|
Produce a language-to-language conversion: from Ada to C#, same semantics. | with Ada.Strings.Fixed;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
procedure Strip is
use Ada.Strings.Unbounded;
procedure Print_Usage is
begin
Ada.Text_IO.Put_Line ("Usage:");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" strip <file> [<opening> [<closing>]]");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" file: file to strip");
Ada.Text_IO.Put_Line (" opening: string for opening comment");
Ada.Text_IO.Put_Line (" closing: string for closing comment");
Ada.Text_IO.New_Line;
end Print_Usage;
Opening_Pattern : Unbounded_String := To_Unbounded_String ("/*");
Closing_Pattern : Unbounded_String := To_Unbounded_String ("*/");
Inside_Comment : Boolean := False;
function Strip_Comments (From : String) return String is
use Ada.Strings.Fixed;
Opening_Index : Natural;
Closing_Index : Natural;
Start_Index : Natural := From'First;
begin
if Inside_Comment then
Start_Index :=
Index (Source => From, Pattern => To_String (Closing_Pattern));
if Start_Index < From'First then
return "";
end if;
Inside_Comment := False;
Start_Index := Start_Index + Length (Closing_Pattern);
end if;
Opening_Index :=
Index
(Source => From,
Pattern => To_String (Opening_Pattern),
From => Start_Index);
if Opening_Index < From'First then
return From (Start_Index .. From'Last);
else
Closing_Index :=
Index
(Source => From,
Pattern => To_String (Closing_Pattern),
From => Opening_Index + Length (Opening_Pattern));
if Closing_Index > 0 then
return From (Start_Index .. Opening_Index - 1) &
Strip_Comments
(From (
Closing_Index + Length (Closing_Pattern) .. From'Last));
else
Inside_Comment := True;
return From (Start_Index .. Opening_Index - 1);
end if;
end if;
end Strip_Comments;
File : Ada.Text_IO.File_Type;
begin
if Ada.Command_Line.Argument_Count < 1
or else Ada.Command_Line.Argument_Count > 3
then
Print_Usage;
return;
end if;
if Ada.Command_Line.Argument_Count > 1 then
Opening_Pattern := To_Unbounded_String (Ada.Command_Line.Argument (2));
if Ada.Command_Line.Argument_Count > 2 then
Closing_Pattern :=
To_Unbounded_String (Ada.Command_Line.Argument (3));
else
Closing_Pattern := Opening_Pattern;
end if;
end if;
Ada.Text_IO.Open
(File => File,
Mode => Ada.Text_IO.In_File,
Name => Ada.Command_Line.Argument (1));
while not Ada.Text_IO.End_Of_File (File => File) loop
declare
Line : constant String := Ada.Text_IO.Get_Line (File);
begin
Ada.Text_IO.Put_Line (Strip_Comments (Line));
end;
end loop;
Ada.Text_IO.Close (File => File);
end Strip;
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Translate this program into C but keep the logic exactly as in Ada. | with Ada.Strings.Fixed;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
procedure Strip is
use Ada.Strings.Unbounded;
procedure Print_Usage is
begin
Ada.Text_IO.Put_Line ("Usage:");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" strip <file> [<opening> [<closing>]]");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" file: file to strip");
Ada.Text_IO.Put_Line (" opening: string for opening comment");
Ada.Text_IO.Put_Line (" closing: string for closing comment");
Ada.Text_IO.New_Line;
end Print_Usage;
Opening_Pattern : Unbounded_String := To_Unbounded_String ("/*");
Closing_Pattern : Unbounded_String := To_Unbounded_String ("*/");
Inside_Comment : Boolean := False;
function Strip_Comments (From : String) return String is
use Ada.Strings.Fixed;
Opening_Index : Natural;
Closing_Index : Natural;
Start_Index : Natural := From'First;
begin
if Inside_Comment then
Start_Index :=
Index (Source => From, Pattern => To_String (Closing_Pattern));
if Start_Index < From'First then
return "";
end if;
Inside_Comment := False;
Start_Index := Start_Index + Length (Closing_Pattern);
end if;
Opening_Index :=
Index
(Source => From,
Pattern => To_String (Opening_Pattern),
From => Start_Index);
if Opening_Index < From'First then
return From (Start_Index .. From'Last);
else
Closing_Index :=
Index
(Source => From,
Pattern => To_String (Closing_Pattern),
From => Opening_Index + Length (Opening_Pattern));
if Closing_Index > 0 then
return From (Start_Index .. Opening_Index - 1) &
Strip_Comments
(From (
Closing_Index + Length (Closing_Pattern) .. From'Last));
else
Inside_Comment := True;
return From (Start_Index .. Opening_Index - 1);
end if;
end if;
end Strip_Comments;
File : Ada.Text_IO.File_Type;
begin
if Ada.Command_Line.Argument_Count < 1
or else Ada.Command_Line.Argument_Count > 3
then
Print_Usage;
return;
end if;
if Ada.Command_Line.Argument_Count > 1 then
Opening_Pattern := To_Unbounded_String (Ada.Command_Line.Argument (2));
if Ada.Command_Line.Argument_Count > 2 then
Closing_Pattern :=
To_Unbounded_String (Ada.Command_Line.Argument (3));
else
Closing_Pattern := Opening_Pattern;
end if;
end if;
Ada.Text_IO.Open
(File => File,
Mode => Ada.Text_IO.In_File,
Name => Ada.Command_Line.Argument (1));
while not Ada.Text_IO.End_Of_File (File => File) loop
declare
Line : constant String := Ada.Text_IO.Get_Line (File);
begin
Ada.Text_IO.Put_Line (Strip_Comments (Line));
end;
end loop;
Ada.Text_IO.Close (File => File);
end Strip;
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C++. | with Ada.Strings.Fixed;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
procedure Strip is
use Ada.Strings.Unbounded;
procedure Print_Usage is
begin
Ada.Text_IO.Put_Line ("Usage:");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" strip <file> [<opening> [<closing>]]");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" file: file to strip");
Ada.Text_IO.Put_Line (" opening: string for opening comment");
Ada.Text_IO.Put_Line (" closing: string for closing comment");
Ada.Text_IO.New_Line;
end Print_Usage;
Opening_Pattern : Unbounded_String := To_Unbounded_String ("/*");
Closing_Pattern : Unbounded_String := To_Unbounded_String ("*/");
Inside_Comment : Boolean := False;
function Strip_Comments (From : String) return String is
use Ada.Strings.Fixed;
Opening_Index : Natural;
Closing_Index : Natural;
Start_Index : Natural := From'First;
begin
if Inside_Comment then
Start_Index :=
Index (Source => From, Pattern => To_String (Closing_Pattern));
if Start_Index < From'First then
return "";
end if;
Inside_Comment := False;
Start_Index := Start_Index + Length (Closing_Pattern);
end if;
Opening_Index :=
Index
(Source => From,
Pattern => To_String (Opening_Pattern),
From => Start_Index);
if Opening_Index < From'First then
return From (Start_Index .. From'Last);
else
Closing_Index :=
Index
(Source => From,
Pattern => To_String (Closing_Pattern),
From => Opening_Index + Length (Opening_Pattern));
if Closing_Index > 0 then
return From (Start_Index .. Opening_Index - 1) &
Strip_Comments
(From (
Closing_Index + Length (Closing_Pattern) .. From'Last));
else
Inside_Comment := True;
return From (Start_Index .. Opening_Index - 1);
end if;
end if;
end Strip_Comments;
File : Ada.Text_IO.File_Type;
begin
if Ada.Command_Line.Argument_Count < 1
or else Ada.Command_Line.Argument_Count > 3
then
Print_Usage;
return;
end if;
if Ada.Command_Line.Argument_Count > 1 then
Opening_Pattern := To_Unbounded_String (Ada.Command_Line.Argument (2));
if Ada.Command_Line.Argument_Count > 2 then
Closing_Pattern :=
To_Unbounded_String (Ada.Command_Line.Argument (3));
else
Closing_Pattern := Opening_Pattern;
end if;
end if;
Ada.Text_IO.Open
(File => File,
Mode => Ada.Text_IO.In_File,
Name => Ada.Command_Line.Argument (1));
while not Ada.Text_IO.End_Of_File (File => File) loop
declare
Line : constant String := Ada.Text_IO.Get_Line (File);
begin
Ada.Text_IO.Put_Line (Strip_Comments (Line));
end;
end loop;
Ada.Text_IO.Close (File => File);
end Strip;
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Translate the given Ada code snippet into Go without altering its behavior. | with Ada.Strings.Fixed;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
procedure Strip is
use Ada.Strings.Unbounded;
procedure Print_Usage is
begin
Ada.Text_IO.Put_Line ("Usage:");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" strip <file> [<opening> [<closing>]]");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" file: file to strip");
Ada.Text_IO.Put_Line (" opening: string for opening comment");
Ada.Text_IO.Put_Line (" closing: string for closing comment");
Ada.Text_IO.New_Line;
end Print_Usage;
Opening_Pattern : Unbounded_String := To_Unbounded_String ("/*");
Closing_Pattern : Unbounded_String := To_Unbounded_String ("*/");
Inside_Comment : Boolean := False;
function Strip_Comments (From : String) return String is
use Ada.Strings.Fixed;
Opening_Index : Natural;
Closing_Index : Natural;
Start_Index : Natural := From'First;
begin
if Inside_Comment then
Start_Index :=
Index (Source => From, Pattern => To_String (Closing_Pattern));
if Start_Index < From'First then
return "";
end if;
Inside_Comment := False;
Start_Index := Start_Index + Length (Closing_Pattern);
end if;
Opening_Index :=
Index
(Source => From,
Pattern => To_String (Opening_Pattern),
From => Start_Index);
if Opening_Index < From'First then
return From (Start_Index .. From'Last);
else
Closing_Index :=
Index
(Source => From,
Pattern => To_String (Closing_Pattern),
From => Opening_Index + Length (Opening_Pattern));
if Closing_Index > 0 then
return From (Start_Index .. Opening_Index - 1) &
Strip_Comments
(From (
Closing_Index + Length (Closing_Pattern) .. From'Last));
else
Inside_Comment := True;
return From (Start_Index .. Opening_Index - 1);
end if;
end if;
end Strip_Comments;
File : Ada.Text_IO.File_Type;
begin
if Ada.Command_Line.Argument_Count < 1
or else Ada.Command_Line.Argument_Count > 3
then
Print_Usage;
return;
end if;
if Ada.Command_Line.Argument_Count > 1 then
Opening_Pattern := To_Unbounded_String (Ada.Command_Line.Argument (2));
if Ada.Command_Line.Argument_Count > 2 then
Closing_Pattern :=
To_Unbounded_String (Ada.Command_Line.Argument (3));
else
Closing_Pattern := Opening_Pattern;
end if;
end if;
Ada.Text_IO.Open
(File => File,
Mode => Ada.Text_IO.In_File,
Name => Ada.Command_Line.Argument (1));
while not Ada.Text_IO.End_Of_File (File => File) loop
declare
Line : constant String := Ada.Text_IO.Get_Line (File);
begin
Ada.Text_IO.Put_Line (Strip_Comments (Line));
end;
end loop;
Ada.Text_IO.Close (File => File);
end Strip;
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Please provide an equivalent version of this Ada code in Java. | with Ada.Strings.Fixed;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
procedure Strip is
use Ada.Strings.Unbounded;
procedure Print_Usage is
begin
Ada.Text_IO.Put_Line ("Usage:");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" strip <file> [<opening> [<closing>]]");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" file: file to strip");
Ada.Text_IO.Put_Line (" opening: string for opening comment");
Ada.Text_IO.Put_Line (" closing: string for closing comment");
Ada.Text_IO.New_Line;
end Print_Usage;
Opening_Pattern : Unbounded_String := To_Unbounded_String ("/*");
Closing_Pattern : Unbounded_String := To_Unbounded_String ("*/");
Inside_Comment : Boolean := False;
function Strip_Comments (From : String) return String is
use Ada.Strings.Fixed;
Opening_Index : Natural;
Closing_Index : Natural;
Start_Index : Natural := From'First;
begin
if Inside_Comment then
Start_Index :=
Index (Source => From, Pattern => To_String (Closing_Pattern));
if Start_Index < From'First then
return "";
end if;
Inside_Comment := False;
Start_Index := Start_Index + Length (Closing_Pattern);
end if;
Opening_Index :=
Index
(Source => From,
Pattern => To_String (Opening_Pattern),
From => Start_Index);
if Opening_Index < From'First then
return From (Start_Index .. From'Last);
else
Closing_Index :=
Index
(Source => From,
Pattern => To_String (Closing_Pattern),
From => Opening_Index + Length (Opening_Pattern));
if Closing_Index > 0 then
return From (Start_Index .. Opening_Index - 1) &
Strip_Comments
(From (
Closing_Index + Length (Closing_Pattern) .. From'Last));
else
Inside_Comment := True;
return From (Start_Index .. Opening_Index - 1);
end if;
end if;
end Strip_Comments;
File : Ada.Text_IO.File_Type;
begin
if Ada.Command_Line.Argument_Count < 1
or else Ada.Command_Line.Argument_Count > 3
then
Print_Usage;
return;
end if;
if Ada.Command_Line.Argument_Count > 1 then
Opening_Pattern := To_Unbounded_String (Ada.Command_Line.Argument (2));
if Ada.Command_Line.Argument_Count > 2 then
Closing_Pattern :=
To_Unbounded_String (Ada.Command_Line.Argument (3));
else
Closing_Pattern := Opening_Pattern;
end if;
end if;
Ada.Text_IO.Open
(File => File,
Mode => Ada.Text_IO.In_File,
Name => Ada.Command_Line.Argument (1));
while not Ada.Text_IO.End_Of_File (File => File) loop
declare
Line : constant String := Ada.Text_IO.Get_Line (File);
begin
Ada.Text_IO.Put_Line (Strip_Comments (Line));
end;
end loop;
Ada.Text_IO.Close (File => File);
end Strip;
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Please provide an equivalent version of this Ada code in Python. | with Ada.Strings.Fixed;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
procedure Strip is
use Ada.Strings.Unbounded;
procedure Print_Usage is
begin
Ada.Text_IO.Put_Line ("Usage:");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" strip <file> [<opening> [<closing>]]");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" file: file to strip");
Ada.Text_IO.Put_Line (" opening: string for opening comment");
Ada.Text_IO.Put_Line (" closing: string for closing comment");
Ada.Text_IO.New_Line;
end Print_Usage;
Opening_Pattern : Unbounded_String := To_Unbounded_String ("/*");
Closing_Pattern : Unbounded_String := To_Unbounded_String ("*/");
Inside_Comment : Boolean := False;
function Strip_Comments (From : String) return String is
use Ada.Strings.Fixed;
Opening_Index : Natural;
Closing_Index : Natural;
Start_Index : Natural := From'First;
begin
if Inside_Comment then
Start_Index :=
Index (Source => From, Pattern => To_String (Closing_Pattern));
if Start_Index < From'First then
return "";
end if;
Inside_Comment := False;
Start_Index := Start_Index + Length (Closing_Pattern);
end if;
Opening_Index :=
Index
(Source => From,
Pattern => To_String (Opening_Pattern),
From => Start_Index);
if Opening_Index < From'First then
return From (Start_Index .. From'Last);
else
Closing_Index :=
Index
(Source => From,
Pattern => To_String (Closing_Pattern),
From => Opening_Index + Length (Opening_Pattern));
if Closing_Index > 0 then
return From (Start_Index .. Opening_Index - 1) &
Strip_Comments
(From (
Closing_Index + Length (Closing_Pattern) .. From'Last));
else
Inside_Comment := True;
return From (Start_Index .. Opening_Index - 1);
end if;
end if;
end Strip_Comments;
File : Ada.Text_IO.File_Type;
begin
if Ada.Command_Line.Argument_Count < 1
or else Ada.Command_Line.Argument_Count > 3
then
Print_Usage;
return;
end if;
if Ada.Command_Line.Argument_Count > 1 then
Opening_Pattern := To_Unbounded_String (Ada.Command_Line.Argument (2));
if Ada.Command_Line.Argument_Count > 2 then
Closing_Pattern :=
To_Unbounded_String (Ada.Command_Line.Argument (3));
else
Closing_Pattern := Opening_Pattern;
end if;
end if;
Ada.Text_IO.Open
(File => File,
Mode => Ada.Text_IO.In_File,
Name => Ada.Command_Line.Argument (1));
while not Ada.Text_IO.End_Of_File (File => File) loop
declare
Line : constant String := Ada.Text_IO.Get_Line (File);
begin
Ada.Text_IO.Put_Line (Strip_Comments (Line));
end;
end loop;
Ada.Text_IO.Close (File => File);
end Strip;
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Ensure the translated VB code behaves exactly like the original Ada snippet. | with Ada.Strings.Fixed;
with Ada.Strings.Unbounded;
with Ada.Text_IO;
with Ada.Command_Line;
procedure Strip is
use Ada.Strings.Unbounded;
procedure Print_Usage is
begin
Ada.Text_IO.Put_Line ("Usage:");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" strip <file> [<opening> [<closing>]]");
Ada.Text_IO.New_Line;
Ada.Text_IO.Put_Line (" file: file to strip");
Ada.Text_IO.Put_Line (" opening: string for opening comment");
Ada.Text_IO.Put_Line (" closing: string for closing comment");
Ada.Text_IO.New_Line;
end Print_Usage;
Opening_Pattern : Unbounded_String := To_Unbounded_String ("/*");
Closing_Pattern : Unbounded_String := To_Unbounded_String ("*/");
Inside_Comment : Boolean := False;
function Strip_Comments (From : String) return String is
use Ada.Strings.Fixed;
Opening_Index : Natural;
Closing_Index : Natural;
Start_Index : Natural := From'First;
begin
if Inside_Comment then
Start_Index :=
Index (Source => From, Pattern => To_String (Closing_Pattern));
if Start_Index < From'First then
return "";
end if;
Inside_Comment := False;
Start_Index := Start_Index + Length (Closing_Pattern);
end if;
Opening_Index :=
Index
(Source => From,
Pattern => To_String (Opening_Pattern),
From => Start_Index);
if Opening_Index < From'First then
return From (Start_Index .. From'Last);
else
Closing_Index :=
Index
(Source => From,
Pattern => To_String (Closing_Pattern),
From => Opening_Index + Length (Opening_Pattern));
if Closing_Index > 0 then
return From (Start_Index .. Opening_Index - 1) &
Strip_Comments
(From (
Closing_Index + Length (Closing_Pattern) .. From'Last));
else
Inside_Comment := True;
return From (Start_Index .. Opening_Index - 1);
end if;
end if;
end Strip_Comments;
File : Ada.Text_IO.File_Type;
begin
if Ada.Command_Line.Argument_Count < 1
or else Ada.Command_Line.Argument_Count > 3
then
Print_Usage;
return;
end if;
if Ada.Command_Line.Argument_Count > 1 then
Opening_Pattern := To_Unbounded_String (Ada.Command_Line.Argument (2));
if Ada.Command_Line.Argument_Count > 2 then
Closing_Pattern :=
To_Unbounded_String (Ada.Command_Line.Argument (3));
else
Closing_Pattern := Opening_Pattern;
end if;
end if;
Ada.Text_IO.Open
(File => File,
Mode => Ada.Text_IO.In_File,
Name => Ada.Command_Line.Argument (1));
while not Ada.Text_IO.End_Of_File (File => File) loop
declare
Line : constant String := Ada.Text_IO.Get_Line (File);
begin
Ada.Text_IO.Put_Line (Strip_Comments (Line));
end;
end loop;
Ada.Text_IO.Close (File => File);
end Strip;
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Can you help me rewrite this code in C instead of AutoHotKey, keeping it the same logically? | code =
(
function subroutine() {
a = b + c
}
function something() {
}
)
openC:=""
openC:=RegExReplace(openC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
closeC:=RegExReplace(closeC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
MsgBox % sCode := RegExReplace(code,"s)(" . openC . ").*?(" . closeC . ")")
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Keep all operations the same but rewrite the snippet in C#. | code =
(
function subroutine() {
a = b + c
}
function something() {
}
)
openC:=""
openC:=RegExReplace(openC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
closeC:=RegExReplace(closeC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
MsgBox % sCode := RegExReplace(code,"s)(" . openC . ").*?(" . closeC . ")")
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Produce a language-to-language conversion: from AutoHotKey to C++, same semantics. | code =
(
function subroutine() {
a = b + c
}
function something() {
}
)
openC:=""
openC:=RegExReplace(openC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
closeC:=RegExReplace(closeC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
MsgBox % sCode := RegExReplace(code,"s)(" . openC . ").*?(" . closeC . ")")
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Write the same algorithm in Java as shown in this AutoHotKey implementation. | code =
(
function subroutine() {
a = b + c
}
function something() {
}
)
openC:=""
openC:=RegExReplace(openC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
closeC:=RegExReplace(closeC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
MsgBox % sCode := RegExReplace(code,"s)(" . openC . ").*?(" . closeC . ")")
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Produce a language-to-language conversion: from AutoHotKey to Python, same semantics. | code =
(
function subroutine() {
a = b + c
}
function something() {
}
)
openC:=""
openC:=RegExReplace(openC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
closeC:=RegExReplace(closeC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
MsgBox % sCode := RegExReplace(code,"s)(" . openC . ").*?(" . closeC . ")")
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Port the provided AutoHotKey code into VB while preserving the original functionality. | code =
(
function subroutine() {
a = b + c
}
function something() {
}
)
openC:=""
openC:=RegExReplace(openC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
closeC:=RegExReplace(closeC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
MsgBox % sCode := RegExReplace(code,"s)(" . openC . ").*?(" . closeC . ")")
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Port the provided AutoHotKey code into Go while preserving the original functionality. | code =
(
function subroutine() {
a = b + c
}
function something() {
}
)
openC:=""
openC:=RegExReplace(openC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
closeC:=RegExReplace(closeC,"(\*|\^|\?|\\|\+|\.|\!|\{|\}|\[|\]|\$|\|)","\$0")
MsgBox % sCode := RegExReplace(code,"s)(" . openC . ").*?(" . closeC . ")")
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Convert this AWK snippet to C and keep its semantics consistent. |
{ while ((start = index($0,"/*")) != 0) {
out = substr($0,1,start-1)
rest = substr($0,start+2)
while ((end = index(rest,"*/")) == 0) {
if (getline <= 0) {
printf("unexpected EOF or error: %s\n",ERRNO) >"/dev/stderr"
exit
}
rest = rest $0
}
rest = substr(rest,end+2)
$0 = out rest
}
printf("%s\n",$0)
}
END {
exit(0)
}
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Write the same algorithm in C# as shown in this AWK implementation. |
{ while ((start = index($0,"/*")) != 0) {
out = substr($0,1,start-1)
rest = substr($0,start+2)
while ((end = index(rest,"*/")) == 0) {
if (getline <= 0) {
printf("unexpected EOF or error: %s\n",ERRNO) >"/dev/stderr"
exit
}
rest = rest $0
}
rest = substr(rest,end+2)
$0 = out rest
}
printf("%s\n",$0)
}
END {
exit(0)
}
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Preserve the algorithm and functionality while converting the code from AWK to C++. |
{ while ((start = index($0,"/*")) != 0) {
out = substr($0,1,start-1)
rest = substr($0,start+2)
while ((end = index(rest,"*/")) == 0) {
if (getline <= 0) {
printf("unexpected EOF or error: %s\n",ERRNO) >"/dev/stderr"
exit
}
rest = rest $0
}
rest = substr(rest,end+2)
$0 = out rest
}
printf("%s\n",$0)
}
END {
exit(0)
}
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Generate an equivalent Java version of this AWK code. |
{ while ((start = index($0,"/*")) != 0) {
out = substr($0,1,start-1)
rest = substr($0,start+2)
while ((end = index(rest,"*/")) == 0) {
if (getline <= 0) {
printf("unexpected EOF or error: %s\n",ERRNO) >"/dev/stderr"
exit
}
rest = rest $0
}
rest = substr(rest,end+2)
$0 = out rest
}
printf("%s\n",$0)
}
END {
exit(0)
}
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Preserve the algorithm and functionality while converting the code from AWK to Python. |
{ while ((start = index($0,"/*")) != 0) {
out = substr($0,1,start-1)
rest = substr($0,start+2)
while ((end = index(rest,"*/")) == 0) {
if (getline <= 0) {
printf("unexpected EOF or error: %s\n",ERRNO) >"/dev/stderr"
exit
}
rest = rest $0
}
rest = substr(rest,end+2)
$0 = out rest
}
printf("%s\n",$0)
}
END {
exit(0)
}
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Transform the following AWK implementation into VB, maintaining the same output and logic. |
{ while ((start = index($0,"/*")) != 0) {
out = substr($0,1,start-1)
rest = substr($0,start+2)
while ((end = index(rest,"*/")) == 0) {
if (getline <= 0) {
printf("unexpected EOF or error: %s\n",ERRNO) >"/dev/stderr"
exit
}
rest = rest $0
}
rest = substr(rest,end+2)
$0 = out rest
}
printf("%s\n",$0)
}
END {
exit(0)
}
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Can you help me rewrite this code in Go instead of AWK, keeping it the same logically? |
{ while ((start = index($0,"/*")) != 0) {
out = substr($0,1,start-1)
rest = substr($0,start+2)
while ((end = index(rest,"*/")) == 0) {
if (getline <= 0) {
printf("unexpected EOF or error: %s\n",ERRNO) >"/dev/stderr"
exit
}
rest = rest $0
}
rest = substr(rest,end+2)
$0 = out rest
}
printf("%s\n",$0)
}
END {
exit(0)
}
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Rewrite this program in C while keeping its functionality equivalent to the BBC_Basic version. | infile$ = "C:\sample.c"
outfile$ = "C:\stripped.c"
PROCstripblockcomments(infile$, outfile$, "/*", "*/")
END
DEF PROCstripblockcomments(infile$, outfile$, start$, finish$)
LOCAL infile%, outfile%, comment%, test%, A$
infile% = OPENIN(infile$)
IF infile%=0 ERROR 100, "Could not open input file"
outfile% = OPENOUT(outfile$)
IF outfile%=0 ERROR 100, "Could not open output file"
WHILE NOT EOF#infile%
A$ = GET$#infile% TO 10
REPEAT
IF comment% THEN
test% = INSTR(A$, finish$)
IF test% THEN
A$ = MID$(A$, test% + LEN(finish$))
comment% = FALSE
ENDIF
ELSE
test% = INSTR(A$, start$)
IF test% THEN
BPUT#outfile%, LEFT$(A$, test%-1);
A$ = MID$(A$, test% + LEN(start$))
comment% = TRUE
ENDIF
ENDIF
UNTIL test%=0
IF NOT comment% BPUT#outfile%, A$
ENDWHILE
CLOSE #infile%
CLOSE #outfile%
ENDPROC
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Port the following code from BBC_Basic to C# with equivalent syntax and logic. | infile$ = "C:\sample.c"
outfile$ = "C:\stripped.c"
PROCstripblockcomments(infile$, outfile$, "/*", "*/")
END
DEF PROCstripblockcomments(infile$, outfile$, start$, finish$)
LOCAL infile%, outfile%, comment%, test%, A$
infile% = OPENIN(infile$)
IF infile%=0 ERROR 100, "Could not open input file"
outfile% = OPENOUT(outfile$)
IF outfile%=0 ERROR 100, "Could not open output file"
WHILE NOT EOF#infile%
A$ = GET$#infile% TO 10
REPEAT
IF comment% THEN
test% = INSTR(A$, finish$)
IF test% THEN
A$ = MID$(A$, test% + LEN(finish$))
comment% = FALSE
ENDIF
ELSE
test% = INSTR(A$, start$)
IF test% THEN
BPUT#outfile%, LEFT$(A$, test%-1);
A$ = MID$(A$, test% + LEN(start$))
comment% = TRUE
ENDIF
ENDIF
UNTIL test%=0
IF NOT comment% BPUT#outfile%, A$
ENDWHILE
CLOSE #infile%
CLOSE #outfile%
ENDPROC
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Convert this BBC_Basic snippet to C++ and keep its semantics consistent. | infile$ = "C:\sample.c"
outfile$ = "C:\stripped.c"
PROCstripblockcomments(infile$, outfile$, "/*", "*/")
END
DEF PROCstripblockcomments(infile$, outfile$, start$, finish$)
LOCAL infile%, outfile%, comment%, test%, A$
infile% = OPENIN(infile$)
IF infile%=0 ERROR 100, "Could not open input file"
outfile% = OPENOUT(outfile$)
IF outfile%=0 ERROR 100, "Could not open output file"
WHILE NOT EOF#infile%
A$ = GET$#infile% TO 10
REPEAT
IF comment% THEN
test% = INSTR(A$, finish$)
IF test% THEN
A$ = MID$(A$, test% + LEN(finish$))
comment% = FALSE
ENDIF
ELSE
test% = INSTR(A$, start$)
IF test% THEN
BPUT#outfile%, LEFT$(A$, test%-1);
A$ = MID$(A$, test% + LEN(start$))
comment% = TRUE
ENDIF
ENDIF
UNTIL test%=0
IF NOT comment% BPUT#outfile%, A$
ENDWHILE
CLOSE #infile%
CLOSE #outfile%
ENDPROC
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Rewrite the snippet below in Java so it works the same as the original BBC_Basic code. | infile$ = "C:\sample.c"
outfile$ = "C:\stripped.c"
PROCstripblockcomments(infile$, outfile$, "/*", "*/")
END
DEF PROCstripblockcomments(infile$, outfile$, start$, finish$)
LOCAL infile%, outfile%, comment%, test%, A$
infile% = OPENIN(infile$)
IF infile%=0 ERROR 100, "Could not open input file"
outfile% = OPENOUT(outfile$)
IF outfile%=0 ERROR 100, "Could not open output file"
WHILE NOT EOF#infile%
A$ = GET$#infile% TO 10
REPEAT
IF comment% THEN
test% = INSTR(A$, finish$)
IF test% THEN
A$ = MID$(A$, test% + LEN(finish$))
comment% = FALSE
ENDIF
ELSE
test% = INSTR(A$, start$)
IF test% THEN
BPUT#outfile%, LEFT$(A$, test%-1);
A$ = MID$(A$, test% + LEN(start$))
comment% = TRUE
ENDIF
ENDIF
UNTIL test%=0
IF NOT comment% BPUT#outfile%, A$
ENDWHILE
CLOSE #infile%
CLOSE #outfile%
ENDPROC
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Convert this BBC_Basic block to Python, preserving its control flow and logic. | infile$ = "C:\sample.c"
outfile$ = "C:\stripped.c"
PROCstripblockcomments(infile$, outfile$, "/*", "*/")
END
DEF PROCstripblockcomments(infile$, outfile$, start$, finish$)
LOCAL infile%, outfile%, comment%, test%, A$
infile% = OPENIN(infile$)
IF infile%=0 ERROR 100, "Could not open input file"
outfile% = OPENOUT(outfile$)
IF outfile%=0 ERROR 100, "Could not open output file"
WHILE NOT EOF#infile%
A$ = GET$#infile% TO 10
REPEAT
IF comment% THEN
test% = INSTR(A$, finish$)
IF test% THEN
A$ = MID$(A$, test% + LEN(finish$))
comment% = FALSE
ENDIF
ELSE
test% = INSTR(A$, start$)
IF test% THEN
BPUT#outfile%, LEFT$(A$, test%-1);
A$ = MID$(A$, test% + LEN(start$))
comment% = TRUE
ENDIF
ENDIF
UNTIL test%=0
IF NOT comment% BPUT#outfile%, A$
ENDWHILE
CLOSE #infile%
CLOSE #outfile%
ENDPROC
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Generate an equivalent VB version of this BBC_Basic code. | infile$ = "C:\sample.c"
outfile$ = "C:\stripped.c"
PROCstripblockcomments(infile$, outfile$, "/*", "*/")
END
DEF PROCstripblockcomments(infile$, outfile$, start$, finish$)
LOCAL infile%, outfile%, comment%, test%, A$
infile% = OPENIN(infile$)
IF infile%=0 ERROR 100, "Could not open input file"
outfile% = OPENOUT(outfile$)
IF outfile%=0 ERROR 100, "Could not open output file"
WHILE NOT EOF#infile%
A$ = GET$#infile% TO 10
REPEAT
IF comment% THEN
test% = INSTR(A$, finish$)
IF test% THEN
A$ = MID$(A$, test% + LEN(finish$))
comment% = FALSE
ENDIF
ELSE
test% = INSTR(A$, start$)
IF test% THEN
BPUT#outfile%, LEFT$(A$, test%-1);
A$ = MID$(A$, test% + LEN(start$))
comment% = TRUE
ENDIF
ENDIF
UNTIL test%=0
IF NOT comment% BPUT#outfile%, A$
ENDWHILE
CLOSE #infile%
CLOSE #outfile%
ENDPROC
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Change the following BBC_Basic code into Go without altering its purpose. | infile$ = "C:\sample.c"
outfile$ = "C:\stripped.c"
PROCstripblockcomments(infile$, outfile$, "/*", "*/")
END
DEF PROCstripblockcomments(infile$, outfile$, start$, finish$)
LOCAL infile%, outfile%, comment%, test%, A$
infile% = OPENIN(infile$)
IF infile%=0 ERROR 100, "Could not open input file"
outfile% = OPENOUT(outfile$)
IF outfile%=0 ERROR 100, "Could not open output file"
WHILE NOT EOF#infile%
A$ = GET$#infile% TO 10
REPEAT
IF comment% THEN
test% = INSTR(A$, finish$)
IF test% THEN
A$ = MID$(A$, test% + LEN(finish$))
comment% = FALSE
ENDIF
ELSE
test% = INSTR(A$, start$)
IF test% THEN
BPUT#outfile%, LEFT$(A$, test%-1);
A$ = MID$(A$, test% + LEN(start$))
comment% = TRUE
ENDIF
ENDIF
UNTIL test%=0
IF NOT comment% BPUT#outfile%, A$
ENDWHILE
CLOSE #infile%
CLOSE #outfile%
ENDPROC
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Convert this Clojure block to C, preserving its control flow and logic. | (defn comment-strip [txt & args]
(let [args (conj {:delim ["/*" "*/"]} (apply hash-map args))
[opener closer] (:delim args)]
(loop [out "", txt txt, delim-count 0]
(let [[hdtxt resttxt] (split-at (count opener) txt)]
(printf "hdtxt=%8s resttxt=%8s out=%8s txt=%16s delim-count=%s\n" (apply str hdtxt) (apply str resttxt) out (apply str txt) delim-count)
(cond
(empty? hdtxt) (str out (apply str txt))
(= (apply str hdtxt) opener) (recur out resttxt (inc delim-count))
(= (apply str hdtxt) closer) (recur out resttxt (dec delim-count))
(= delim-count 0)(recur (str out (first txt)) (rest txt) delim-count)
true (recur out (rest txt) delim-count))))))
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Produce a functionally identical C# code for the snippet given in Clojure. | (defn comment-strip [txt & args]
(let [args (conj {:delim ["/*" "*/"]} (apply hash-map args))
[opener closer] (:delim args)]
(loop [out "", txt txt, delim-count 0]
(let [[hdtxt resttxt] (split-at (count opener) txt)]
(printf "hdtxt=%8s resttxt=%8s out=%8s txt=%16s delim-count=%s\n" (apply str hdtxt) (apply str resttxt) out (apply str txt) delim-count)
(cond
(empty? hdtxt) (str out (apply str txt))
(= (apply str hdtxt) opener) (recur out resttxt (inc delim-count))
(= (apply str hdtxt) closer) (recur out resttxt (dec delim-count))
(= delim-count 0)(recur (str out (first txt)) (rest txt) delim-count)
true (recur out (rest txt) delim-count))))))
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Please provide an equivalent version of this Clojure code in C++. | (defn comment-strip [txt & args]
(let [args (conj {:delim ["/*" "*/"]} (apply hash-map args))
[opener closer] (:delim args)]
(loop [out "", txt txt, delim-count 0]
(let [[hdtxt resttxt] (split-at (count opener) txt)]
(printf "hdtxt=%8s resttxt=%8s out=%8s txt=%16s delim-count=%s\n" (apply str hdtxt) (apply str resttxt) out (apply str txt) delim-count)
(cond
(empty? hdtxt) (str out (apply str txt))
(= (apply str hdtxt) opener) (recur out resttxt (inc delim-count))
(= (apply str hdtxt) closer) (recur out resttxt (dec delim-count))
(= delim-count 0)(recur (str out (first txt)) (rest txt) delim-count)
true (recur out (rest txt) delim-count))))))
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Preserve the algorithm and functionality while converting the code from Clojure to Java. | (defn comment-strip [txt & args]
(let [args (conj {:delim ["/*" "*/"]} (apply hash-map args))
[opener closer] (:delim args)]
(loop [out "", txt txt, delim-count 0]
(let [[hdtxt resttxt] (split-at (count opener) txt)]
(printf "hdtxt=%8s resttxt=%8s out=%8s txt=%16s delim-count=%s\n" (apply str hdtxt) (apply str resttxt) out (apply str txt) delim-count)
(cond
(empty? hdtxt) (str out (apply str txt))
(= (apply str hdtxt) opener) (recur out resttxt (inc delim-count))
(= (apply str hdtxt) closer) (recur out resttxt (dec delim-count))
(= delim-count 0)(recur (str out (first txt)) (rest txt) delim-count)
true (recur out (rest txt) delim-count))))))
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Port the following code from Clojure to Python with equivalent syntax and logic. | (defn comment-strip [txt & args]
(let [args (conj {:delim ["/*" "*/"]} (apply hash-map args))
[opener closer] (:delim args)]
(loop [out "", txt txt, delim-count 0]
(let [[hdtxt resttxt] (split-at (count opener) txt)]
(printf "hdtxt=%8s resttxt=%8s out=%8s txt=%16s delim-count=%s\n" (apply str hdtxt) (apply str resttxt) out (apply str txt) delim-count)
(cond
(empty? hdtxt) (str out (apply str txt))
(= (apply str hdtxt) opener) (recur out resttxt (inc delim-count))
(= (apply str hdtxt) closer) (recur out resttxt (dec delim-count))
(= delim-count 0)(recur (str out (first txt)) (rest txt) delim-count)
true (recur out (rest txt) delim-count))))))
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Ensure the translated VB code behaves exactly like the original Clojure snippet. | (defn comment-strip [txt & args]
(let [args (conj {:delim ["/*" "*/"]} (apply hash-map args))
[opener closer] (:delim args)]
(loop [out "", txt txt, delim-count 0]
(let [[hdtxt resttxt] (split-at (count opener) txt)]
(printf "hdtxt=%8s resttxt=%8s out=%8s txt=%16s delim-count=%s\n" (apply str hdtxt) (apply str resttxt) out (apply str txt) delim-count)
(cond
(empty? hdtxt) (str out (apply str txt))
(= (apply str hdtxt) opener) (recur out resttxt (inc delim-count))
(= (apply str hdtxt) closer) (recur out resttxt (dec delim-count))
(= delim-count 0)(recur (str out (first txt)) (rest txt) delim-count)
true (recur out (rest txt) delim-count))))))
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Generate a Go translation of this Clojure snippet without changing its computational steps. | (defn comment-strip [txt & args]
(let [args (conj {:delim ["/*" "*/"]} (apply hash-map args))
[opener closer] (:delim args)]
(loop [out "", txt txt, delim-count 0]
(let [[hdtxt resttxt] (split-at (count opener) txt)]
(printf "hdtxt=%8s resttxt=%8s out=%8s txt=%16s delim-count=%s\n" (apply str hdtxt) (apply str resttxt) out (apply str txt) delim-count)
(cond
(empty? hdtxt) (str out (apply str txt))
(= (apply str hdtxt) opener) (recur out resttxt (inc delim-count))
(= (apply str hdtxt) closer) (recur out resttxt (dec delim-count))
(= delim-count 0)(recur (str out (first txt)) (rest txt) delim-count)
true (recur out (rest txt) delim-count))))))
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Preserve the algorithm and functionality while converting the code from D to C. | import std.algorithm, std.regex;
string[2] separateComments(in string txt,
in string cpat0, in string cpat1) {
int[2] plen;
int i, j;
bool inside;
bool advCursor() {
auto mo = match(txt[i .. $], inside ? cpat1 : cpat0);
if (mo.empty)
return false;
plen[inside] = max(0, plen[inside], mo.front[0].length);
j = i + mo.pre.length;
if (inside)
j += mo.front[0].length;
if (!match(mo.front[0], r"\n|\r").empty)
j--;
return true;
}
string[2] result;
while (true) {
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
if (inside && (j - i < plen[0] + plen[1])) {
i = j;
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
}
i = j;
inside = !inside;
}
if (inside)
throw new Exception("Mismatched Comment");
result[inside] ~= txt[i .. $];
return result;
}
void main() {
import std.stdio;
static void showResults(in string e, in string[2] pair) {
writeln("===Original text:\n", e);
writeln("\n\n===Text without comments:\n", pair[0]);
writeln("\n\n===The stripped comments:\n", pair[1]);
}
immutable ex1 = `
function subroutine() {
a = b + c ;
}
function something() {
}`;
showResults(ex1, separateComments(ex1, `/\*`, `\*/`));
writeln("\n");
immutable ex2 = "apples, pears # and bananas
apples, pears; and bananas ";
showResults(ex2, separateComments(ex2, `#|;`, `[\n\r]|$`));
}
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Convert the following code from D to C#, ensuring the logic remains intact. | import std.algorithm, std.regex;
string[2] separateComments(in string txt,
in string cpat0, in string cpat1) {
int[2] plen;
int i, j;
bool inside;
bool advCursor() {
auto mo = match(txt[i .. $], inside ? cpat1 : cpat0);
if (mo.empty)
return false;
plen[inside] = max(0, plen[inside], mo.front[0].length);
j = i + mo.pre.length;
if (inside)
j += mo.front[0].length;
if (!match(mo.front[0], r"\n|\r").empty)
j--;
return true;
}
string[2] result;
while (true) {
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
if (inside && (j - i < plen[0] + plen[1])) {
i = j;
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
}
i = j;
inside = !inside;
}
if (inside)
throw new Exception("Mismatched Comment");
result[inside] ~= txt[i .. $];
return result;
}
void main() {
import std.stdio;
static void showResults(in string e, in string[2] pair) {
writeln("===Original text:\n", e);
writeln("\n\n===Text without comments:\n", pair[0]);
writeln("\n\n===The stripped comments:\n", pair[1]);
}
immutable ex1 = `
function subroutine() {
a = b + c ;
}
function something() {
}`;
showResults(ex1, separateComments(ex1, `/\*`, `\*/`));
writeln("\n");
immutable ex2 = "apples, pears # and bananas
apples, pears; and bananas ";
showResults(ex2, separateComments(ex2, `#|;`, `[\n\r]|$`));
}
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Please provide an equivalent version of this D code in C++. | import std.algorithm, std.regex;
string[2] separateComments(in string txt,
in string cpat0, in string cpat1) {
int[2] plen;
int i, j;
bool inside;
bool advCursor() {
auto mo = match(txt[i .. $], inside ? cpat1 : cpat0);
if (mo.empty)
return false;
plen[inside] = max(0, plen[inside], mo.front[0].length);
j = i + mo.pre.length;
if (inside)
j += mo.front[0].length;
if (!match(mo.front[0], r"\n|\r").empty)
j--;
return true;
}
string[2] result;
while (true) {
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
if (inside && (j - i < plen[0] + plen[1])) {
i = j;
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
}
i = j;
inside = !inside;
}
if (inside)
throw new Exception("Mismatched Comment");
result[inside] ~= txt[i .. $];
return result;
}
void main() {
import std.stdio;
static void showResults(in string e, in string[2] pair) {
writeln("===Original text:\n", e);
writeln("\n\n===Text without comments:\n", pair[0]);
writeln("\n\n===The stripped comments:\n", pair[1]);
}
immutable ex1 = `
function subroutine() {
a = b + c ;
}
function something() {
}`;
showResults(ex1, separateComments(ex1, `/\*`, `\*/`));
writeln("\n");
immutable ex2 = "apples, pears # and bananas
apples, pears; and bananas ";
showResults(ex2, separateComments(ex2, `#|;`, `[\n\r]|$`));
}
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Rewrite this program in Java while keeping its functionality equivalent to the D version. | import std.algorithm, std.regex;
string[2] separateComments(in string txt,
in string cpat0, in string cpat1) {
int[2] plen;
int i, j;
bool inside;
bool advCursor() {
auto mo = match(txt[i .. $], inside ? cpat1 : cpat0);
if (mo.empty)
return false;
plen[inside] = max(0, plen[inside], mo.front[0].length);
j = i + mo.pre.length;
if (inside)
j += mo.front[0].length;
if (!match(mo.front[0], r"\n|\r").empty)
j--;
return true;
}
string[2] result;
while (true) {
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
if (inside && (j - i < plen[0] + plen[1])) {
i = j;
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
}
i = j;
inside = !inside;
}
if (inside)
throw new Exception("Mismatched Comment");
result[inside] ~= txt[i .. $];
return result;
}
void main() {
import std.stdio;
static void showResults(in string e, in string[2] pair) {
writeln("===Original text:\n", e);
writeln("\n\n===Text without comments:\n", pair[0]);
writeln("\n\n===The stripped comments:\n", pair[1]);
}
immutable ex1 = `
function subroutine() {
a = b + c ;
}
function something() {
}`;
showResults(ex1, separateComments(ex1, `/\*`, `\*/`));
writeln("\n");
immutable ex2 = "apples, pears # and bananas
apples, pears; and bananas ";
showResults(ex2, separateComments(ex2, `#|;`, `[\n\r]|$`));
}
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Write a version of this D function in Python with identical behavior. | import std.algorithm, std.regex;
string[2] separateComments(in string txt,
in string cpat0, in string cpat1) {
int[2] plen;
int i, j;
bool inside;
bool advCursor() {
auto mo = match(txt[i .. $], inside ? cpat1 : cpat0);
if (mo.empty)
return false;
plen[inside] = max(0, plen[inside], mo.front[0].length);
j = i + mo.pre.length;
if (inside)
j += mo.front[0].length;
if (!match(mo.front[0], r"\n|\r").empty)
j--;
return true;
}
string[2] result;
while (true) {
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
if (inside && (j - i < plen[0] + plen[1])) {
i = j;
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
}
i = j;
inside = !inside;
}
if (inside)
throw new Exception("Mismatched Comment");
result[inside] ~= txt[i .. $];
return result;
}
void main() {
import std.stdio;
static void showResults(in string e, in string[2] pair) {
writeln("===Original text:\n", e);
writeln("\n\n===Text without comments:\n", pair[0]);
writeln("\n\n===The stripped comments:\n", pair[1]);
}
immutable ex1 = `
function subroutine() {
a = b + c ;
}
function something() {
}`;
showResults(ex1, separateComments(ex1, `/\*`, `\*/`));
writeln("\n");
immutable ex2 = "apples, pears # and bananas
apples, pears; and bananas ";
showResults(ex2, separateComments(ex2, `#|;`, `[\n\r]|$`));
}
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Generate a VB translation of this D snippet without changing its computational steps. | import std.algorithm, std.regex;
string[2] separateComments(in string txt,
in string cpat0, in string cpat1) {
int[2] plen;
int i, j;
bool inside;
bool advCursor() {
auto mo = match(txt[i .. $], inside ? cpat1 : cpat0);
if (mo.empty)
return false;
plen[inside] = max(0, plen[inside], mo.front[0].length);
j = i + mo.pre.length;
if (inside)
j += mo.front[0].length;
if (!match(mo.front[0], r"\n|\r").empty)
j--;
return true;
}
string[2] result;
while (true) {
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
if (inside && (j - i < plen[0] + plen[1])) {
i = j;
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
}
i = j;
inside = !inside;
}
if (inside)
throw new Exception("Mismatched Comment");
result[inside] ~= txt[i .. $];
return result;
}
void main() {
import std.stdio;
static void showResults(in string e, in string[2] pair) {
writeln("===Original text:\n", e);
writeln("\n\n===Text without comments:\n", pair[0]);
writeln("\n\n===The stripped comments:\n", pair[1]);
}
immutable ex1 = `
function subroutine() {
a = b + c ;
}
function something() {
}`;
showResults(ex1, separateComments(ex1, `/\*`, `\*/`));
writeln("\n");
immutable ex2 = "apples, pears # and bananas
apples, pears; and bananas ";
showResults(ex2, separateComments(ex2, `#|;`, `[\n\r]|$`));
}
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Write the same algorithm in Go as shown in this D implementation. | import std.algorithm, std.regex;
string[2] separateComments(in string txt,
in string cpat0, in string cpat1) {
int[2] plen;
int i, j;
bool inside;
bool advCursor() {
auto mo = match(txt[i .. $], inside ? cpat1 : cpat0);
if (mo.empty)
return false;
plen[inside] = max(0, plen[inside], mo.front[0].length);
j = i + mo.pre.length;
if (inside)
j += mo.front[0].length;
if (!match(mo.front[0], r"\n|\r").empty)
j--;
return true;
}
string[2] result;
while (true) {
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
if (inside && (j - i < plen[0] + plen[1])) {
i = j;
if (!advCursor())
break;
result[inside] ~= txt[i .. j];
}
i = j;
inside = !inside;
}
if (inside)
throw new Exception("Mismatched Comment");
result[inside] ~= txt[i .. $];
return result;
}
void main() {
import std.stdio;
static void showResults(in string e, in string[2] pair) {
writeln("===Original text:\n", e);
writeln("\n\n===Text without comments:\n", pair[0]);
writeln("\n\n===The stripped comments:\n", pair[1]);
}
immutable ex1 = `
function subroutine() {
a = b + c ;
}
function something() {
}`;
showResults(ex1, separateComments(ex1, `/\*`, `\*/`));
writeln("\n");
immutable ex2 = "apples, pears # and bananas
apples, pears; and bananas ";
showResults(ex2, separateComments(ex2, `#|;`, `[\n\r]|$`));
}
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Preserve the algorithm and functionality while converting the code from Delphi to C. | program Strip_block_comments;
uses
System.SysUtils;
function BlockCommentStrip(commentStart, commentEnd, sampleText: string): string;
begin
while ((sampleText.IndexOf(commentStart) > -1) and (sampleText.IndexOf(commentEnd,
sampleText.IndexOf(commentStart) + commentStart.Length) > -1)) do
begin
var start := sampleText.IndexOf(commentStart);
var _end := sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText := sampleText.Remove(start, (_end + commentEnd.Length) - start);
end;
Result := sampleText;
end;
const
test = '/**' + #10 + '* Some comments' + #10 +
'* longer comments here that we can parse.' + #10 + '*' + #10 + '* Rahoo ' +
#10 + '*/' + #10 + 'function subroutine() ' + #10 +
'/*/ <-- tricky comments */' + #10 + '' + #10 + '/**' + #10 +
'* Another comment.' + #10 + '*/' + #10 + 'function something() ';
begin
writeln(BlockCommentStrip('/*', '*/', test));
readln;
end.
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Ensure the translated C# code behaves exactly like the original Delphi snippet. | program Strip_block_comments;
uses
System.SysUtils;
function BlockCommentStrip(commentStart, commentEnd, sampleText: string): string;
begin
while ((sampleText.IndexOf(commentStart) > -1) and (sampleText.IndexOf(commentEnd,
sampleText.IndexOf(commentStart) + commentStart.Length) > -1)) do
begin
var start := sampleText.IndexOf(commentStart);
var _end := sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText := sampleText.Remove(start, (_end + commentEnd.Length) - start);
end;
Result := sampleText;
end;
const
test = '/**' + #10 + '* Some comments' + #10 +
'* longer comments here that we can parse.' + #10 + '*' + #10 + '* Rahoo ' +
#10 + '*/' + #10 + 'function subroutine() ' + #10 +
'/*/ <-- tricky comments */' + #10 + '' + #10 + '/**' + #10 +
'* Another comment.' + #10 + '*/' + #10 + 'function something() ';
begin
writeln(BlockCommentStrip('/*', '*/', test));
readln;
end.
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Produce a language-to-language conversion: from Delphi to C++, same semantics. | program Strip_block_comments;
uses
System.SysUtils;
function BlockCommentStrip(commentStart, commentEnd, sampleText: string): string;
begin
while ((sampleText.IndexOf(commentStart) > -1) and (sampleText.IndexOf(commentEnd,
sampleText.IndexOf(commentStart) + commentStart.Length) > -1)) do
begin
var start := sampleText.IndexOf(commentStart);
var _end := sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText := sampleText.Remove(start, (_end + commentEnd.Length) - start);
end;
Result := sampleText;
end;
const
test = '/**' + #10 + '* Some comments' + #10 +
'* longer comments here that we can parse.' + #10 + '*' + #10 + '* Rahoo ' +
#10 + '*/' + #10 + 'function subroutine() ' + #10 +
'/*/ <-- tricky comments */' + #10 + '' + #10 + '/**' + #10 +
'* Another comment.' + #10 + '*/' + #10 + 'function something() ';
begin
writeln(BlockCommentStrip('/*', '*/', test));
readln;
end.
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Convert this Delphi snippet to Java and keep its semantics consistent. | program Strip_block_comments;
uses
System.SysUtils;
function BlockCommentStrip(commentStart, commentEnd, sampleText: string): string;
begin
while ((sampleText.IndexOf(commentStart) > -1) and (sampleText.IndexOf(commentEnd,
sampleText.IndexOf(commentStart) + commentStart.Length) > -1)) do
begin
var start := sampleText.IndexOf(commentStart);
var _end := sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText := sampleText.Remove(start, (_end + commentEnd.Length) - start);
end;
Result := sampleText;
end;
const
test = '/**' + #10 + '* Some comments' + #10 +
'* longer comments here that we can parse.' + #10 + '*' + #10 + '* Rahoo ' +
#10 + '*/' + #10 + 'function subroutine() ' + #10 +
'/*/ <-- tricky comments */' + #10 + '' + #10 + '/**' + #10 +
'* Another comment.' + #10 + '*/' + #10 + 'function something() ';
begin
writeln(BlockCommentStrip('/*', '*/', test));
readln;
end.
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Produce a language-to-language conversion: from Delphi to Python, same semantics. | program Strip_block_comments;
uses
System.SysUtils;
function BlockCommentStrip(commentStart, commentEnd, sampleText: string): string;
begin
while ((sampleText.IndexOf(commentStart) > -1) and (sampleText.IndexOf(commentEnd,
sampleText.IndexOf(commentStart) + commentStart.Length) > -1)) do
begin
var start := sampleText.IndexOf(commentStart);
var _end := sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText := sampleText.Remove(start, (_end + commentEnd.Length) - start);
end;
Result := sampleText;
end;
const
test = '/**' + #10 + '* Some comments' + #10 +
'* longer comments here that we can parse.' + #10 + '*' + #10 + '* Rahoo ' +
#10 + '*/' + #10 + 'function subroutine() ' + #10 +
'/*/ <-- tricky comments */' + #10 + '' + #10 + '/**' + #10 +
'* Another comment.' + #10 + '*/' + #10 + 'function something() ';
begin
writeln(BlockCommentStrip('/*', '*/', test));
readln;
end.
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Port the provided Delphi code into VB while preserving the original functionality. | program Strip_block_comments;
uses
System.SysUtils;
function BlockCommentStrip(commentStart, commentEnd, sampleText: string): string;
begin
while ((sampleText.IndexOf(commentStart) > -1) and (sampleText.IndexOf(commentEnd,
sampleText.IndexOf(commentStart) + commentStart.Length) > -1)) do
begin
var start := sampleText.IndexOf(commentStart);
var _end := sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText := sampleText.Remove(start, (_end + commentEnd.Length) - start);
end;
Result := sampleText;
end;
const
test = '/**' + #10 + '* Some comments' + #10 +
'* longer comments here that we can parse.' + #10 + '*' + #10 + '* Rahoo ' +
#10 + '*/' + #10 + 'function subroutine() ' + #10 +
'/*/ <-- tricky comments */' + #10 + '' + #10 + '/**' + #10 +
'* Another comment.' + #10 + '*/' + #10 + 'function something() ';
begin
writeln(BlockCommentStrip('/*', '*/', test));
readln;
end.
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Write the same algorithm in Go as shown in this Delphi implementation. | program Strip_block_comments;
uses
System.SysUtils;
function BlockCommentStrip(commentStart, commentEnd, sampleText: string): string;
begin
while ((sampleText.IndexOf(commentStart) > -1) and (sampleText.IndexOf(commentEnd,
sampleText.IndexOf(commentStart) + commentStart.Length) > -1)) do
begin
var start := sampleText.IndexOf(commentStart);
var _end := sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText := sampleText.Remove(start, (_end + commentEnd.Length) - start);
end;
Result := sampleText;
end;
const
test = '/**' + #10 + '* Some comments' + #10 +
'* longer comments here that we can parse.' + #10 + '*' + #10 + '* Rahoo ' +
#10 + '*/' + #10 + 'function subroutine() ' + #10 +
'/*/ <-- tricky comments */' + #10 + '' + #10 + '/**' + #10 +
'* Another comment.' + #10 + '*/' + #10 + 'function something() ';
begin
writeln(BlockCommentStrip('/*', '*/', test));
readln;
end.
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Transform the following F# implementation into C, maintaining the same output and logic. | open System
open System.Text.RegularExpressions
let balancedComments opening closing =
new Regex(
String.Format("""
{0} # An outer opening delimiter
(?> # efficiency: no backtracking here
{0} (?<LEVEL>) # An opening delimiter, one level down
|
{1} (?<-LEVEL>) # A closing delimiter, one level up
|
(?! {0} | {1} ) . # With negative lookahead: Anything but delimiters
)* # As many times as we see these
(?(LEVEL)(?!)) # Fail, unless on level 0 here
{1} # Outer closing delimiter
""", Regex.Escape(opening), Regex.Escape(closing)),
RegexOptions.IgnorePatternWhitespace ||| RegexOptions.Singleline)
[<EntryPoint>]
let main args =
let sample = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
* /* nested balanced
*/ */
function something() {
}
"""
let balancedC = balancedComments "/*" "*/"
printfn "%s" (balancedC.Replace(sample, ""))
0
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Generate an equivalent C# version of this F# code. | open System
open System.Text.RegularExpressions
let balancedComments opening closing =
new Regex(
String.Format("""
{0} # An outer opening delimiter
(?> # efficiency: no backtracking here
{0} (?<LEVEL>) # An opening delimiter, one level down
|
{1} (?<-LEVEL>) # A closing delimiter, one level up
|
(?! {0} | {1} ) . # With negative lookahead: Anything but delimiters
)* # As many times as we see these
(?(LEVEL)(?!)) # Fail, unless on level 0 here
{1} # Outer closing delimiter
""", Regex.Escape(opening), Regex.Escape(closing)),
RegexOptions.IgnorePatternWhitespace ||| RegexOptions.Singleline)
[<EntryPoint>]
let main args =
let sample = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
* /* nested balanced
*/ */
function something() {
}
"""
let balancedC = balancedComments "/*" "*/"
printfn "%s" (balancedC.Replace(sample, ""))
0
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Rewrite the snippet below in C++ so it works the same as the original F# code. | open System
open System.Text.RegularExpressions
let balancedComments opening closing =
new Regex(
String.Format("""
{0} # An outer opening delimiter
(?> # efficiency: no backtracking here
{0} (?<LEVEL>) # An opening delimiter, one level down
|
{1} (?<-LEVEL>) # A closing delimiter, one level up
|
(?! {0} | {1} ) . # With negative lookahead: Anything but delimiters
)* # As many times as we see these
(?(LEVEL)(?!)) # Fail, unless on level 0 here
{1} # Outer closing delimiter
""", Regex.Escape(opening), Regex.Escape(closing)),
RegexOptions.IgnorePatternWhitespace ||| RegexOptions.Singleline)
[<EntryPoint>]
let main args =
let sample = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
* /* nested balanced
*/ */
function something() {
}
"""
let balancedC = balancedComments "/*" "*/"
printfn "%s" (balancedC.Replace(sample, ""))
0
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Preserve the algorithm and functionality while converting the code from F# to Java. | open System
open System.Text.RegularExpressions
let balancedComments opening closing =
new Regex(
String.Format("""
{0} # An outer opening delimiter
(?> # efficiency: no backtracking here
{0} (?<LEVEL>) # An opening delimiter, one level down
|
{1} (?<-LEVEL>) # A closing delimiter, one level up
|
(?! {0} | {1} ) . # With negative lookahead: Anything but delimiters
)* # As many times as we see these
(?(LEVEL)(?!)) # Fail, unless on level 0 here
{1} # Outer closing delimiter
""", Regex.Escape(opening), Regex.Escape(closing)),
RegexOptions.IgnorePatternWhitespace ||| RegexOptions.Singleline)
[<EntryPoint>]
let main args =
let sample = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
* /* nested balanced
*/ */
function something() {
}
"""
let balancedC = balancedComments "/*" "*/"
printfn "%s" (balancedC.Replace(sample, ""))
0
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Ensure the translated Python code behaves exactly like the original F# snippet. | open System
open System.Text.RegularExpressions
let balancedComments opening closing =
new Regex(
String.Format("""
{0} # An outer opening delimiter
(?> # efficiency: no backtracking here
{0} (?<LEVEL>) # An opening delimiter, one level down
|
{1} (?<-LEVEL>) # A closing delimiter, one level up
|
(?! {0} | {1} ) . # With negative lookahead: Anything but delimiters
)* # As many times as we see these
(?(LEVEL)(?!)) # Fail, unless on level 0 here
{1} # Outer closing delimiter
""", Regex.Escape(opening), Regex.Escape(closing)),
RegexOptions.IgnorePatternWhitespace ||| RegexOptions.Singleline)
[<EntryPoint>]
let main args =
let sample = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
* /* nested balanced
*/ */
function something() {
}
"""
let balancedC = balancedComments "/*" "*/"
printfn "%s" (balancedC.Replace(sample, ""))
0
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Can you help me rewrite this code in VB instead of F#, keeping it the same logically? | open System
open System.Text.RegularExpressions
let balancedComments opening closing =
new Regex(
String.Format("""
{0} # An outer opening delimiter
(?> # efficiency: no backtracking here
{0} (?<LEVEL>) # An opening delimiter, one level down
|
{1} (?<-LEVEL>) # A closing delimiter, one level up
|
(?! {0} | {1} ) . # With negative lookahead: Anything but delimiters
)* # As many times as we see these
(?(LEVEL)(?!)) # Fail, unless on level 0 here
{1} # Outer closing delimiter
""", Regex.Escape(opening), Regex.Escape(closing)),
RegexOptions.IgnorePatternWhitespace ||| RegexOptions.Singleline)
[<EntryPoint>]
let main args =
let sample = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
* /* nested balanced
*/ */
function something() {
}
"""
let balancedC = balancedComments "/*" "*/"
printfn "%s" (balancedC.Replace(sample, ""))
0
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Produce a language-to-language conversion: from F# to Go, same semantics. | open System
open System.Text.RegularExpressions
let balancedComments opening closing =
new Regex(
String.Format("""
{0} # An outer opening delimiter
(?> # efficiency: no backtracking here
{0} (?<LEVEL>) # An opening delimiter, one level down
|
{1} (?<-LEVEL>) # A closing delimiter, one level up
|
(?! {0} | {1} ) . # With negative lookahead: Anything but delimiters
)* # As many times as we see these
(?(LEVEL)(?!)) # Fail, unless on level 0 here
{1} # Outer closing delimiter
""", Regex.Escape(opening), Regex.Escape(closing)),
RegexOptions.IgnorePatternWhitespace ||| RegexOptions.Singleline)
[<EntryPoint>]
let main args =
let sample = """
/**
* Some comments
* longer comments here that we can parse.
*
* Rahoo
*/
function subroutine() {
a = /* inline comment */ b + c ;
}
/*/ <-- tricky comments */
/**
* Another comment.
* /* nested balanced
*/ */
function something() {
}
"""
let balancedC = balancedComments "/*" "*/"
printfn "%s" (balancedC.Replace(sample, ""))
0
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Maintain the same structure and functionality when rewriting this code in C. | : strip-block-comments ( string -- string )
R/ /\*.*?\*\// "" re-replace ;
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Change the programming language of this snippet from Factor to C# without modifying what it does. | : strip-block-comments ( string -- string )
R/ /\*.*?\*\// "" re-replace ;
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Port the following code from Factor to C++ with equivalent syntax and logic. | : strip-block-comments ( string -- string )
R/ /\*.*?\*\// "" re-replace ;
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Generate an equivalent Java version of this Factor code. | : strip-block-comments ( string -- string )
R/ /\*.*?\*\// "" re-replace ;
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Factor version. | : strip-block-comments ( string -- string )
R/ /\*.*?\*\// "" re-replace ;
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Generate a VB translation of this Factor snippet without changing its computational steps. | : strip-block-comments ( string -- string )
R/ /\*.*?\*\// "" re-replace ;
|
Dim t As String
Dim s() As Byte
Dim j As Integer
Dim SourceLength As Integer
Dim flag As Boolean
Private Sub Block_Comment(sOpBC As String, sClBC As String)
flag = False
Do While j < SourceLength - 2
Select Case s(j)
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
End If
Case Asc(Left(sClBC, 1))
If s(j + 1) = Asc(Right(sClBC, 1)) Then
flag = True
j = j + 2
Exit Do
End If
Case Else
End Select
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing close block comment delimeter"
End Sub
Private Sub String_Literal()
flag = False
Do While j < SourceLength - 2
If s(j) = Asc("""") Then
If s(j + 1) = Asc("""") Then
t = t + Chr(s(j))
j = j + 1
Else
flag = True
t = t + Chr(s(j))
j = j + 1
Exit Do
End If
End If
t = t + Chr(s(j))
j = j + 1
Loop
If Not flag Then MsgBox "Error, missing closing string delimeter"
End Sub
Private Sub Other_Text(Optional sOpBC As String = "/*", Optional sClBC As String = "*/")
If Len(sOpBC) <> 2 Then
MsgBox "Error, open block comment delimeter must be 2" & _
" characters long, got " & Len(sOpBC) & " characters"
Exit Sub
End If
If Len(sClBC) <> 2 Then
MsgBox "Error, close block comment delimeter must be 2" & _
" characters long, got " & Len(sClBC) & " characters"
Exit Sub
End If
Do While j < SourceLength - 1
Select Case s(j)
Case Asc(""""):
t = t + Chr(s(j))
j = j + 1
String_Literal
Case Asc(Left(sOpBC, 1))
If s(j + 1) = Asc(Right(sOpBC, 1)) Then
j = j + 2
Block_Comment sOpBC, sClBC
Else
t = t + Chr(s(j))
j = j + 1
End If
Case Else
t = t + Chr(s(j))
j = j + 1
End Select
Loop
If j = SourceLength - 1 Then t = t + Chr(s(j))
End Sub
Public Sub strip_block_comment()
Dim n As String
n = n & "/**" & vbCrLf
n = n & "* Some comments /*NESTED COMMENT*/" & vbCrLf
n = n & "* longer comments here that we can parse." & vbCrLf
n = n & "*" & vbCrLf
n = n & "* Rahoo" & vbCrLf
n = n & "*/" & vbCrLf
n = n & "mystring = ""This is the """"/*"""" open comment block mark.""" & vbCrLf
n = n & "function subroutine() {" & vbCrLf
n = n & "a = /* inline comment */ b + c ;" & vbCrLf
n = n & "}" & vbCrLf
n = n & "/*/ <-- tricky /*NESTED*/ comments */" & vbCrLf
n = n & "" & vbCrLf
n = n & "/**" & vbCrLf
n = n & "* Another comment." & vbCrLf
n = n & "*/" & vbCrLf
n = n & "function something() {" & vbCrLf
n = n & "}"
s = StrConv(n, vbFromUnicode)
j = 0
t = ""
SourceLength = Len(n)
Other_Text
Debug.Print "Original text:"
Debug.Print String$(60, "-")
Debug.Print n & vbCrLf
Debug.Print "Text after deleting comment blocks, preserving string literals:"
Debug.Print String$(60, "-")
Debug.Print t
End Sub
|
Generate a Go translation of this Factor snippet without changing its computational steps. | : strip-block-comments ( string -- string )
R/ /\*.*?\*\// "" re-replace ;
| package main
import (
"fmt"
"strings"
)
func newStripper(start, end string) func(string) string {
if start == "" || end == "" {
start, end = ""
}
return func(source string) string {
for {
cs := strings.Index(source, start)
if cs < 0 {
break
}
ce := strings.Index(source[cs+2:], end)
if ce < 0 {
break
}
source = source[:cs] + source[cs+ce+4:]
}
return source
}
}
func main() {
stripC := newStripper("", "")
fmt.Println(stripC(`
function subroutine() {
a = b + c ;
}
function something() {
}`))
}
|
Convert this Fortran block to C#, preserving its control flow and logic. | SUBROUTINE UNBLOCK(THIS,THAT)
Copies from file INF to file OUT, record by record, except skipping null output records.
CHARACTER*(*) THIS,THAT
INTEGER LOTS
PARAMETER (LOTS = 6666)
CHARACTER*(LOTS) ACARD,ALINE
INTEGER LC,LL,L
INTEGER L1,L2
INTEGER NC,NL
LOGICAL BLAH
INTEGER MSG,KBD,INF,OUT
COMMON /IODEV/MSG,KBD,INF,OUT
NC = 0
NL = 0
BLAH = .FALSE.
Chug through the input.
10 READ(INF,11,END = 100) LC,ACARD(1:MIN(LC,LOTS))
11 FORMAT (Q,A)
NC = NC + 1
IF (LC.GT.LOTS) THEN
WRITE (MSG,12) NC,LC,LOTS
12 FORMAT ("Record ",I0," has length ",I0,"
LC = LOTS
END IF
Chew through ACARD according to mood.
LL = 0
L2 = 0
20 L1 = L2 + 1
IF (L1.LE.LC) THEN
L2 = L1
IF (BLAH) THEN
21 IF (L2 + LEN(THAT) - 1 .LE. LC) THEN
IF (ACARD(L2:L2 + LEN(THAT) - 1).EQ.THAT) THEN
BLAH = .FALSE.
L2 = L2 + LEN(THAT) - 1
GO TO 20
END IF
L2 = L2 + 1
GO TO 21
END IF
ELSE
22 IF (L2 + LEN(THIS) - 1 .LE. LC) THEN
IF (ACARD(L2:L2 + LEN(THIS) - 1).EQ.THIS) THEN
BLAH = .TRUE.
L = L2 - L1
ALINE(LL + 1:LL + L) = ACARD(L1:L2 - 1)
LL = LL + L
L2 = L2 + LEN(THIS) - 1
GO TO 20
END IF
L2 = L2 + 1
GO TO 22
END IF
L = LC - L1 + 1
ALINE(LL + 1:LL + L) = ACARD(L1:LC)
LL = LL + L
END IF
END IF
Cast forth some output.
IF (LL.GT.0) THEN
WRITE (OUT,23) ALINE(1:LL)
23 FORMAT (">",A,"<")
NL = NL + 1
END IF
GO TO 10
Completed.
100 WRITE (MSG,101) NC,NL
101 FORMAT (I0," read, ",I0," written.")
END
PROGRAM TEST
INTEGER MSG,KBD,INF,OUT
COMMON /IODEV/MSG,KBD,INF,OUT
KBD = 5
MSG = 6
INF = 10
OUT = 11
OPEN (INF,FILE="Source.txt",STATUS="OLD",ACTION="READ")
OPEN (OUT,FILE="Src.txt",STATUS="REPLACE",ACTION="WRITE")
CALL UNBLOCK("/*","*/")
END
| using System;
class Program
{
private static string BlockCommentStrip(string commentStart, string commentEnd, string sampleText)
{
while (sampleText.IndexOf(commentStart) > -1 && sampleText.IndexOf(commentEnd, sampleText.IndexOf(commentStart) + commentStart.Length) > -1)
{
int start = sampleText.IndexOf(commentStart);
int end = sampleText.IndexOf(commentEnd, start + commentStart.Length);
sampleText = sampleText.Remove(
start,
(end + commentEnd.Length) - start
);
}
return sampleText;
}
}
|
Convert this Fortran block to C++, preserving its control flow and logic. | SUBROUTINE UNBLOCK(THIS,THAT)
Copies from file INF to file OUT, record by record, except skipping null output records.
CHARACTER*(*) THIS,THAT
INTEGER LOTS
PARAMETER (LOTS = 6666)
CHARACTER*(LOTS) ACARD,ALINE
INTEGER LC,LL,L
INTEGER L1,L2
INTEGER NC,NL
LOGICAL BLAH
INTEGER MSG,KBD,INF,OUT
COMMON /IODEV/MSG,KBD,INF,OUT
NC = 0
NL = 0
BLAH = .FALSE.
Chug through the input.
10 READ(INF,11,END = 100) LC,ACARD(1:MIN(LC,LOTS))
11 FORMAT (Q,A)
NC = NC + 1
IF (LC.GT.LOTS) THEN
WRITE (MSG,12) NC,LC,LOTS
12 FORMAT ("Record ",I0," has length ",I0,"
LC = LOTS
END IF
Chew through ACARD according to mood.
LL = 0
L2 = 0
20 L1 = L2 + 1
IF (L1.LE.LC) THEN
L2 = L1
IF (BLAH) THEN
21 IF (L2 + LEN(THAT) - 1 .LE. LC) THEN
IF (ACARD(L2:L2 + LEN(THAT) - 1).EQ.THAT) THEN
BLAH = .FALSE.
L2 = L2 + LEN(THAT) - 1
GO TO 20
END IF
L2 = L2 + 1
GO TO 21
END IF
ELSE
22 IF (L2 + LEN(THIS) - 1 .LE. LC) THEN
IF (ACARD(L2:L2 + LEN(THIS) - 1).EQ.THIS) THEN
BLAH = .TRUE.
L = L2 - L1
ALINE(LL + 1:LL + L) = ACARD(L1:L2 - 1)
LL = LL + L
L2 = L2 + LEN(THIS) - 1
GO TO 20
END IF
L2 = L2 + 1
GO TO 22
END IF
L = LC - L1 + 1
ALINE(LL + 1:LL + L) = ACARD(L1:LC)
LL = LL + L
END IF
END IF
Cast forth some output.
IF (LL.GT.0) THEN
WRITE (OUT,23) ALINE(1:LL)
23 FORMAT (">",A,"<")
NL = NL + 1
END IF
GO TO 10
Completed.
100 WRITE (MSG,101) NC,NL
101 FORMAT (I0," read, ",I0," written.")
END
PROGRAM TEST
INTEGER MSG,KBD,INF,OUT
COMMON /IODEV/MSG,KBD,INF,OUT
KBD = 5
MSG = 6
INF = 10
OUT = 11
OPEN (INF,FILE="Source.txt",STATUS="OLD",ACTION="READ")
OPEN (OUT,FILE="Src.txt",STATUS="REPLACE",ACTION="WRITE")
CALL UNBLOCK("/*","*/")
END
| #include <string>
#include <iostream>
#include <iterator>
#include <fstream>
#include <boost/regex.hpp>
int main( ) {
std::ifstream codeFile( "samplecode.txt" ) ;
if ( codeFile ) {
boost::regex commentre( "/\\*.*?\\*/" ) ;
std::string my_erase( "" ) ;
std::string stripped ;
std::string code( (std::istreambuf_iterator<char>( codeFile ) ) ,
std::istreambuf_iterator<char>( ) ) ;
codeFile.close( ) ;
stripped = boost::regex_replace( code , commentre , my_erase ) ;
std::cout << "Code unstripped:\n" << stripped << std::endl ;
return 0 ;
}
else {
std::cout << "Could not find code file!" << std::endl ;
return 1 ;
}
}
|
Translate this program into C but keep the logic exactly as in Fortran. | SUBROUTINE UNBLOCK(THIS,THAT)
Copies from file INF to file OUT, record by record, except skipping null output records.
CHARACTER*(*) THIS,THAT
INTEGER LOTS
PARAMETER (LOTS = 6666)
CHARACTER*(LOTS) ACARD,ALINE
INTEGER LC,LL,L
INTEGER L1,L2
INTEGER NC,NL
LOGICAL BLAH
INTEGER MSG,KBD,INF,OUT
COMMON /IODEV/MSG,KBD,INF,OUT
NC = 0
NL = 0
BLAH = .FALSE.
Chug through the input.
10 READ(INF,11,END = 100) LC,ACARD(1:MIN(LC,LOTS))
11 FORMAT (Q,A)
NC = NC + 1
IF (LC.GT.LOTS) THEN
WRITE (MSG,12) NC,LC,LOTS
12 FORMAT ("Record ",I0," has length ",I0,"
LC = LOTS
END IF
Chew through ACARD according to mood.
LL = 0
L2 = 0
20 L1 = L2 + 1
IF (L1.LE.LC) THEN
L2 = L1
IF (BLAH) THEN
21 IF (L2 + LEN(THAT) - 1 .LE. LC) THEN
IF (ACARD(L2:L2 + LEN(THAT) - 1).EQ.THAT) THEN
BLAH = .FALSE.
L2 = L2 + LEN(THAT) - 1
GO TO 20
END IF
L2 = L2 + 1
GO TO 21
END IF
ELSE
22 IF (L2 + LEN(THIS) - 1 .LE. LC) THEN
IF (ACARD(L2:L2 + LEN(THIS) - 1).EQ.THIS) THEN
BLAH = .TRUE.
L = L2 - L1
ALINE(LL + 1:LL + L) = ACARD(L1:L2 - 1)
LL = LL + L
L2 = L2 + LEN(THIS) - 1
GO TO 20
END IF
L2 = L2 + 1
GO TO 22
END IF
L = LC - L1 + 1
ALINE(LL + 1:LL + L) = ACARD(L1:LC)
LL = LL + L
END IF
END IF
Cast forth some output.
IF (LL.GT.0) THEN
WRITE (OUT,23) ALINE(1:LL)
23 FORMAT (">",A,"<")
NL = NL + 1
END IF
GO TO 10
Completed.
100 WRITE (MSG,101) NC,NL
101 FORMAT (I0," read, ",I0," written.")
END
PROGRAM TEST
INTEGER MSG,KBD,INF,OUT
COMMON /IODEV/MSG,KBD,INF,OUT
KBD = 5
MSG = 6
INF = 10
OUT = 11
OPEN (INF,FILE="Source.txt",STATUS="OLD",ACTION="READ")
OPEN (OUT,FILE="Src.txt",STATUS="REPLACE",ACTION="WRITE")
CALL UNBLOCK("/*","*/")
END
| #include <stdio.h>
#include <string.h>
#include <stdlib.h>
const char *ca = "";
int al = 2, bl = 2;
char *loadfile(const char *fn) {
FILE *f = fopen(fn, "rb");
int l;
char *s;
if (f != NULL) {
fseek(f, 0, SEEK_END);
l = ftell(f);
s = malloc(l+1);
rewind(f);
if (s)
fread(s, 1, l, f);
fclose(f);
}
return s;
}
void stripcomments(char *s) {
char *a, *b;
int len = strlen(s) + 1;
while ((a = strstr(s, ca)) != NULL) {
b = strstr(a+al, cb);
if (b == NULL)
break;
b += bl;
memmove(a, b, len-(b-a));
}
}
int main(int argc, char **argv) {
const char *fn = "input.txt";
char *s;
if (argc >= 2)
fn = argv[1];
s = loadfile(fn);
if (argc == 4) {
al = strlen(ca = argv[2]);
bl = strlen(cb = argv[3]);
}
stripcomments(s);
puts(s);
free(s);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Fortran to Java. | SUBROUTINE UNBLOCK(THIS,THAT)
Copies from file INF to file OUT, record by record, except skipping null output records.
CHARACTER*(*) THIS,THAT
INTEGER LOTS
PARAMETER (LOTS = 6666)
CHARACTER*(LOTS) ACARD,ALINE
INTEGER LC,LL,L
INTEGER L1,L2
INTEGER NC,NL
LOGICAL BLAH
INTEGER MSG,KBD,INF,OUT
COMMON /IODEV/MSG,KBD,INF,OUT
NC = 0
NL = 0
BLAH = .FALSE.
Chug through the input.
10 READ(INF,11,END = 100) LC,ACARD(1:MIN(LC,LOTS))
11 FORMAT (Q,A)
NC = NC + 1
IF (LC.GT.LOTS) THEN
WRITE (MSG,12) NC,LC,LOTS
12 FORMAT ("Record ",I0," has length ",I0,"
LC = LOTS
END IF
Chew through ACARD according to mood.
LL = 0
L2 = 0
20 L1 = L2 + 1
IF (L1.LE.LC) THEN
L2 = L1
IF (BLAH) THEN
21 IF (L2 + LEN(THAT) - 1 .LE. LC) THEN
IF (ACARD(L2:L2 + LEN(THAT) - 1).EQ.THAT) THEN
BLAH = .FALSE.
L2 = L2 + LEN(THAT) - 1
GO TO 20
END IF
L2 = L2 + 1
GO TO 21
END IF
ELSE
22 IF (L2 + LEN(THIS) - 1 .LE. LC) THEN
IF (ACARD(L2:L2 + LEN(THIS) - 1).EQ.THIS) THEN
BLAH = .TRUE.
L = L2 - L1
ALINE(LL + 1:LL + L) = ACARD(L1:L2 - 1)
LL = LL + L
L2 = L2 + LEN(THIS) - 1
GO TO 20
END IF
L2 = L2 + 1
GO TO 22
END IF
L = LC - L1 + 1
ALINE(LL + 1:LL + L) = ACARD(L1:LC)
LL = LL + L
END IF
END IF
Cast forth some output.
IF (LL.GT.0) THEN
WRITE (OUT,23) ALINE(1:LL)
23 FORMAT (">",A,"<")
NL = NL + 1
END IF
GO TO 10
Completed.
100 WRITE (MSG,101) NC,NL
101 FORMAT (I0," read, ",I0," written.")
END
PROGRAM TEST
INTEGER MSG,KBD,INF,OUT
COMMON /IODEV/MSG,KBD,INF,OUT
KBD = 5
MSG = 6
INF = 10
OUT = 11
OPEN (INF,FILE="Source.txt",STATUS="OLD",ACTION="READ")
OPEN (OUT,FILE="Src.txt",STATUS="REPLACE",ACTION="WRITE")
CALL UNBLOCK("/*","*/")
END
| import java.io.*;
public class StripBlockComments{
public static String readFile(String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
try {
StringBuilder fileContents = new StringBuilder();
char[] buffer = new char[4096];
while (reader.read(buffer, 0, 4096) > 0) {
fileContents.append(buffer);
}
return fileContents.toString();
} finally {
reader.close();
}
}
public static String stripComments(String beginToken, String endToken,
String input) {
StringBuilder output = new StringBuilder();
while (true) {
int begin = input.indexOf(beginToken);
int end = input.indexOf(endToken, begin+beginToken.length());
if (begin == -1 || end == -1) {
output.append(input);
return output.toString();
}
output.append(input.substring(0, begin));
input = input.substring(end + endToken.length());
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.out.println("Usage: BeginToken EndToken FileToProcess");
System.exit(1);
}
String begin = args[0];
String end = args[1];
String input = args[2];
try {
System.out.println(stripComments(begin, end, readFile(input)));
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
|
Change the programming language of this snippet from Fortran to Python without modifying what it does. | SUBROUTINE UNBLOCK(THIS,THAT)
Copies from file INF to file OUT, record by record, except skipping null output records.
CHARACTER*(*) THIS,THAT
INTEGER LOTS
PARAMETER (LOTS = 6666)
CHARACTER*(LOTS) ACARD,ALINE
INTEGER LC,LL,L
INTEGER L1,L2
INTEGER NC,NL
LOGICAL BLAH
INTEGER MSG,KBD,INF,OUT
COMMON /IODEV/MSG,KBD,INF,OUT
NC = 0
NL = 0
BLAH = .FALSE.
Chug through the input.
10 READ(INF,11,END = 100) LC,ACARD(1:MIN(LC,LOTS))
11 FORMAT (Q,A)
NC = NC + 1
IF (LC.GT.LOTS) THEN
WRITE (MSG,12) NC,LC,LOTS
12 FORMAT ("Record ",I0," has length ",I0,"
LC = LOTS
END IF
Chew through ACARD according to mood.
LL = 0
L2 = 0
20 L1 = L2 + 1
IF (L1.LE.LC) THEN
L2 = L1
IF (BLAH) THEN
21 IF (L2 + LEN(THAT) - 1 .LE. LC) THEN
IF (ACARD(L2:L2 + LEN(THAT) - 1).EQ.THAT) THEN
BLAH = .FALSE.
L2 = L2 + LEN(THAT) - 1
GO TO 20
END IF
L2 = L2 + 1
GO TO 21
END IF
ELSE
22 IF (L2 + LEN(THIS) - 1 .LE. LC) THEN
IF (ACARD(L2:L2 + LEN(THIS) - 1).EQ.THIS) THEN
BLAH = .TRUE.
L = L2 - L1
ALINE(LL + 1:LL + L) = ACARD(L1:L2 - 1)
LL = LL + L
L2 = L2 + LEN(THIS) - 1
GO TO 20
END IF
L2 = L2 + 1
GO TO 22
END IF
L = LC - L1 + 1
ALINE(LL + 1:LL + L) = ACARD(L1:LC)
LL = LL + L
END IF
END IF
Cast forth some output.
IF (LL.GT.0) THEN
WRITE (OUT,23) ALINE(1:LL)
23 FORMAT (">",A,"<")
NL = NL + 1
END IF
GO TO 10
Completed.
100 WRITE (MSG,101) NC,NL
101 FORMAT (I0," read, ",I0," written.")
END
PROGRAM TEST
INTEGER MSG,KBD,INF,OUT
COMMON /IODEV/MSG,KBD,INF,OUT
KBD = 5
MSG = 6
INF = 10
OUT = 11
OPEN (INF,FILE="Source.txt",STATUS="OLD",ACTION="READ")
OPEN (OUT,FILE="Src.txt",STATUS="REPLACE",ACTION="WRITE")
CALL UNBLOCK("/*","*/")
END
| def _commentstripper(txt, delim):
'Strips first nest of block comments'
deliml, delimr = delim
out = ''
if deliml in txt:
indx = txt.index(deliml)
out += txt[:indx]
txt = txt[indx+len(deliml):]
txt = _commentstripper(txt, delim)
assert delimr in txt, 'Cannot find closing comment delimiter in ' + txt
indx = txt.index(delimr)
out += txt[(indx+len(delimr)):]
else:
out = txt
return out
def commentstripper(txt, delim=('/*', '*/')):
'Strips nests of block comments'
deliml, delimr = delim
while deliml in txt:
txt = _commentstripper(txt, delim)
return txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.