Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Please provide an equivalent version of this PHP code in Go. | <?php
$code = 'echo "hello world"';
eval($code);
$code = 'return "hello world"';
print eval($code);
| package main
import (
"fmt"
"bitbucket.org/binet/go-eval/pkg/eval"
"go/token"
)
func main() {
w := eval.NewWorld();
fset := token.NewFileSet();
code, err := w.Compile(fset, "1 + 2")
if err != nil {
fmt.Println("Compile error");
return
}
val, err := code.Run();
if err != nil {
fmt.Println("Run time error");
return;
}
fmt.Println("Return value:", val)
}
|
Can you help me rewrite this code in Go instead of PHP, keeping it the same logically? | <?php
function permutate($values, $size, $offset) {
$count = count($values);
$array = array();
for ($i = 0; $i < $size; $i++) {
$selector = ($offset / pow($count,$i)) % $count;
$array[$i] = $values[$selector];
}
return $array;
}
function permutations($values, $size) {
$a = array();
$c = pow(count($values), $size);
for ($i = 0; $i<$c; $i++) {
$a[$i] = permutate($values, $size, $i);
}
return $a;
}
$permutations = permutations(['bat','fox','cow'], 2);
foreach ($permutations as $permutation) {
echo join(',', $permutation)."\n";
}
| package main
import "fmt"
var (
n = 3
values = []string{"A", "B", "C", "D"}
k = len(values)
decide = func(p []string) bool {
return p[0] == "B" && p[1] == "C"
}
)
func main() {
pn := make([]int, n)
p := make([]string, n)
for {
for i, x := range pn {
p[i] = values[x]
}
fmt.Println(p)
if decide(p) {
return
}
for i := 0; ; {
pn[i]++
if pn[i] < k {
break
}
pn[i] = 0
i++
if i == n {
return
}
}
}
}
|
Write the same algorithm in Go as shown in this PHP implementation. | <?php
function permutate($values, $size, $offset) {
$count = count($values);
$array = array();
for ($i = 0; $i < $size; $i++) {
$selector = ($offset / pow($count,$i)) % $count;
$array[$i] = $values[$selector];
}
return $array;
}
function permutations($values, $size) {
$a = array();
$c = pow(count($values), $size);
for ($i = 0; $i<$c; $i++) {
$a[$i] = permutate($values, $size, $i);
}
return $a;
}
$permutations = permutations(['bat','fox','cow'], 2);
foreach ($permutations as $permutation) {
echo join(',', $permutation)."\n";
}
| package main
import "fmt"
var (
n = 3
values = []string{"A", "B", "C", "D"}
k = len(values)
decide = func(p []string) bool {
return p[0] == "B" && p[1] == "C"
}
)
func main() {
pn := make([]int, n)
p := make([]string, n)
for {
for i, x := range pn {
p[i] = values[x]
}
fmt.Println(p)
if decide(p) {
return
}
for i := 0; ; {
pn[i]++
if pn[i] < k {
break
}
pn[i] = 0
i++
if i == n {
return
}
}
}
}
|
Change the following PHP code into Go without altering its purpose. | <?php
function permutate($values, $size, $offset) {
$count = count($values);
$array = array();
for ($i = 0; $i < $size; $i++) {
$selector = ($offset / pow($count,$i)) % $count;
$array[$i] = $values[$selector];
}
return $array;
}
function permutations($values, $size) {
$a = array();
$c = pow(count($values), $size);
for ($i = 0; $i<$c; $i++) {
$a[$i] = permutate($values, $size, $i);
}
return $a;
}
$permutations = permutations(['bat','fox','cow'], 2);
foreach ($permutations as $permutation) {
echo join(',', $permutation)."\n";
}
| package main
import "fmt"
var (
n = 3
values = []string{"A", "B", "C", "D"}
k = len(values)
decide = func(p []string) bool {
return p[0] == "B" && p[1] == "C"
}
)
func main() {
pn := make([]int, n)
p := make([]string, n)
for {
for i, x := range pn {
p[i] = values[x]
}
fmt.Println(p)
if decide(p) {
return
}
for i := 0; ; {
pn[i]++
if pn[i] < k {
break
}
pn[i] = 0
i++
if i == n {
return
}
}
}
}
|
Generate an equivalent Go version of this PHP code. | <?php
function permutate($values, $size, $offset) {
$count = count($values);
$array = array();
for ($i = 0; $i < $size; $i++) {
$selector = ($offset / pow($count,$i)) % $count;
$array[$i] = $values[$selector];
}
return $array;
}
function permutations($values, $size) {
$a = array();
$c = pow(count($values), $size);
for ($i = 0; $i<$c; $i++) {
$a[$i] = permutate($values, $size, $i);
}
return $a;
}
$permutations = permutations(['bat','fox','cow'], 2);
foreach ($permutations as $permutation) {
echo join(',', $permutation)."\n";
}
| package main
import "fmt"
var (
n = 3
values = []string{"A", "B", "C", "D"}
k = len(values)
decide = func(p []string) bool {
return p[0] == "B" && p[1] == "C"
}
)
func main() {
pn := make([]int, n)
p := make([]string, n)
for {
for i, x := range pn {
p[i] = values[x]
}
fmt.Println(p)
if decide(p) {
return
}
for i := 0; ; {
pn[i]++
if pn[i] < k {
break
}
pn[i] = 0
i++
if i == n {
return
}
}
}
}
|
Produce a language-to-language conversion: from PHP to Go, same semantics. | function ownCalcPass($password, $nonce) {
$msr = 0x7FFFFFFF;
$m_1 = (int)0xFFFFFFFF;
$m_8 = (int)0xFFFFFFF8;
$m_16 = (int)0xFFFFFFF0;
$m_128 = (int)0xFFFFFF80;
$m_16777216 = (int)0xFF000000;
$flag = True;
$num1 = 0;
$num2 = 0;
foreach (str_split($nonce) as $c) {
$num1 = $num1 & $m_1;
$num2 = $num2 & $m_1;
if ($c == '1') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & $m_128;
$num1 = $num1 >> 1;
$num1 = $num1 & $msr;
$num1 = $num1 >> 6;
$num2 = $num2 << 25;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '2') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & $m_16;
$num1 = $num1 >> 1;
$num1 = $num1 & $msr;
$num1 = $num1 >> 3;
$num2 = $num2 << 28;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '3') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & $m_8;
$num1 = $num1 >> 1;
$num1 = $num1 & $msr;
$num1 = $num1 >> 2;
$num2 = $num2 << 29;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '4') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 << 1;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 30;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '5') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 << 5;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 26;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '6') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 << 12;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 19;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '7') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & 0xFF00;
$num1 = $num1 + (( $num2 & 0xFF ) << 24 );
$num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 );
$num2 = $num2 & $m_16777216;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 7;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '8') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & 0xFFFF;
$num1 = $num1 << 16;
$numx = $num2 >> 1;
$numx = $numx & $msr;
$numx = $numx >> 23;
$num1 = $num1 + $numx;
$num2 = $num2 & 0xFF0000;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 7;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '9') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = ~(int)$num2;
$flag = False;
} else {
$num1 = $num2;
}
$num2 = $num1;
}
return sprintf('%u', $num1 & $m_1);
}
| package main
import (
"fmt"
"strconv"
)
func ownCalcPass(password, nonce string) uint32 {
start := true
num1 := uint32(0)
num2 := num1
i, _ := strconv.Atoi(password)
pwd := uint32(i)
for _, c := range nonce {
if c != '0' {
if start {
num2 = pwd
}
start = false
}
switch c {
case '1':
num1 = (num2 & 0xFFFFFF80) >> 7
num2 = num2 << 25
case '2':
num1 = (num2 & 0xFFFFFFF0) >> 4
num2 = num2 << 28
case '3':
num1 = (num2 & 0xFFFFFFF8) >> 3
num2 = num2 << 29
case '4':
num1 = num2 << 1
num2 = num2 >> 31
case '5':
num1 = num2 << 5
num2 = num2 >> 27
case '6':
num1 = num2 << 12
num2 = num2 >> 20
case '7':
num3 := num2 & 0x0000FF00
num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16)
num1 = num3 | num4
num2 = (num2 & 0xFF000000) >> 8
case '8':
num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24)
num2 = (num2 & 0x00FF0000) >> 8
case '9':
num1 = ^num2
default:
num1 = num2
}
num1 &= 0xFFFFFFFF
num2 &= 0xFFFFFFFF
if c != '0' && c != '9' {
num1 |= num2
}
num2 = num1
}
return num1
}
func testPasswordCalc(password, nonce string, expected uint32) {
res := ownCalcPass(password, nonce)
m := fmt.Sprintf("%s %s %-10d %-10d", password, nonce, res, expected)
if res == expected {
fmt.Println("PASS", m)
} else {
fmt.Println("FAIL", m)
}
}
func main() {
testPasswordCalc("12345", "603356072", 25280520)
testPasswordCalc("12345", "410501656", 119537670)
testPasswordCalc("12345", "630292165", 4269684735)
}
|
Please provide an equivalent version of this PHP code in Go. | function ownCalcPass($password, $nonce) {
$msr = 0x7FFFFFFF;
$m_1 = (int)0xFFFFFFFF;
$m_8 = (int)0xFFFFFFF8;
$m_16 = (int)0xFFFFFFF0;
$m_128 = (int)0xFFFFFF80;
$m_16777216 = (int)0xFF000000;
$flag = True;
$num1 = 0;
$num2 = 0;
foreach (str_split($nonce) as $c) {
$num1 = $num1 & $m_1;
$num2 = $num2 & $m_1;
if ($c == '1') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & $m_128;
$num1 = $num1 >> 1;
$num1 = $num1 & $msr;
$num1 = $num1 >> 6;
$num2 = $num2 << 25;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '2') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & $m_16;
$num1 = $num1 >> 1;
$num1 = $num1 & $msr;
$num1 = $num1 >> 3;
$num2 = $num2 << 28;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '3') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & $m_8;
$num1 = $num1 >> 1;
$num1 = $num1 & $msr;
$num1 = $num1 >> 2;
$num2 = $num2 << 29;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '4') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 << 1;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 30;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '5') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 << 5;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 26;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '6') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 << 12;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 19;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '7') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & 0xFF00;
$num1 = $num1 + (( $num2 & 0xFF ) << 24 );
$num1 = $num1 + (( $num2 & 0xFF0000 ) >> 16 );
$num2 = $num2 & $m_16777216;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 7;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '8') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = $num2 & 0xFFFF;
$num1 = $num1 << 16;
$numx = $num2 >> 1;
$numx = $numx & $msr;
$numx = $numx >> 23;
$num1 = $num1 + $numx;
$num2 = $num2 & 0xFF0000;
$num2 = $num2 >> 1;
$num2 = $num2 & $msr;
$num2 = $num2 >> 7;
$num1 = $num1 + $num2;
$flag = False;
} elseif ($c == '9') {
$length = !$flag;
if (!$length) {
$num2 = $password;
}
$num1 = ~(int)$num2;
$flag = False;
} else {
$num1 = $num2;
}
$num2 = $num1;
}
return sprintf('%u', $num1 & $m_1);
}
| package main
import (
"fmt"
"strconv"
)
func ownCalcPass(password, nonce string) uint32 {
start := true
num1 := uint32(0)
num2 := num1
i, _ := strconv.Atoi(password)
pwd := uint32(i)
for _, c := range nonce {
if c != '0' {
if start {
num2 = pwd
}
start = false
}
switch c {
case '1':
num1 = (num2 & 0xFFFFFF80) >> 7
num2 = num2 << 25
case '2':
num1 = (num2 & 0xFFFFFFF0) >> 4
num2 = num2 << 28
case '3':
num1 = (num2 & 0xFFFFFFF8) >> 3
num2 = num2 << 29
case '4':
num1 = num2 << 1
num2 = num2 >> 31
case '5':
num1 = num2 << 5
num2 = num2 >> 27
case '6':
num1 = num2 << 12
num2 = num2 >> 20
case '7':
num3 := num2 & 0x0000FF00
num4 := ((num2 & 0x000000FF) << 24) | ((num2 & 0x00FF0000) >> 16)
num1 = num3 | num4
num2 = (num2 & 0xFF000000) >> 8
case '8':
num1 = (num2&0x0000FFFF)<<16 | (num2 >> 24)
num2 = (num2 & 0x00FF0000) >> 8
case '9':
num1 = ^num2
default:
num1 = num2
}
num1 &= 0xFFFFFFFF
num2 &= 0xFFFFFFFF
if c != '0' && c != '9' {
num1 |= num2
}
num2 = num1
}
return num1
}
func testPasswordCalc(password, nonce string, expected uint32) {
res := ownCalcPass(password, nonce)
m := fmt.Sprintf("%s %s %-10d %-10d", password, nonce, res, expected)
if res == expected {
fmt.Println("PASS", m)
} else {
fmt.Println("FAIL", m)
}
}
func main() {
testPasswordCalc("12345", "603356072", 25280520)
testPasswordCalc("12345", "410501656", 119537670)
testPasswordCalc("12345", "630292165", 4269684735)
}
|
Transform the following PHP implementation into Go, maintaining the same output and logic. | class WriterMonad {
private $value;
private $logs;
private function __construct($value, array $logs = []) {
$this->value = $value;
$this->logs = $logs;
}
public static function unit($value, string $log): WriterMonad {
return new WriterMonad($value, ["{$log}: {$value}"]);
}
public function bind(callable $mapper): WriterMonad {
$mapped = $mapper($this->value);
assert($mapped instanceof WriterMonad);
return new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);
}
public function value() {
return $this->value;
}
public function logs(): array {
return $this->logs;
}
}
$root = fn(float $i): float => sqrt($i);
$addOne = fn(float $i): float => $i + 1;
$half = fn(float $i): float => $i / 2;
$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);
$result = WriterMonad::unit(5, "Initial value")
->bind($m($root, "square root"))
->bind($m($addOne, "add one"))
->bind($m($half, "half"));
print "The Golden Ratio is: {$result->value()}\n";
print join("\n", $result->logs());
| package main
import (
"fmt"
"math"
)
type mwriter struct {
value float64
log string
}
func (m mwriter) bind(f func(v float64) mwriter) mwriter {
n := f(m.value)
n.log = m.log + n.log
return n
}
func unit(v float64, s string) mwriter {
return mwriter{v, fmt.Sprintf(" %-17s: %g\n", s, v)}
}
func root(v float64) mwriter {
return unit(math.Sqrt(v), "Took square root")
}
func addOne(v float64) mwriter {
return unit(v+1, "Added one")
}
func half(v float64) mwriter {
return unit(v/2, "Divided by two")
}
func main() {
mw1 := unit(5, "Initial value")
mw2 := mw1.bind(root).bind(addOne).bind(half)
fmt.Println("The Golden Ratio is", mw2.value)
fmt.Println("\nThis was derived as follows:-")
fmt.Println(mw2.log)
}
|
Translate the given PHP code snippet into Go without altering its behavior. | class WriterMonad {
private $value;
private $logs;
private function __construct($value, array $logs = []) {
$this->value = $value;
$this->logs = $logs;
}
public static function unit($value, string $log): WriterMonad {
return new WriterMonad($value, ["{$log}: {$value}"]);
}
public function bind(callable $mapper): WriterMonad {
$mapped = $mapper($this->value);
assert($mapped instanceof WriterMonad);
return new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);
}
public function value() {
return $this->value;
}
public function logs(): array {
return $this->logs;
}
}
$root = fn(float $i): float => sqrt($i);
$addOne = fn(float $i): float => $i + 1;
$half = fn(float $i): float => $i / 2;
$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);
$result = WriterMonad::unit(5, "Initial value")
->bind($m($root, "square root"))
->bind($m($addOne, "add one"))
->bind($m($half, "half"));
print "The Golden Ratio is: {$result->value()}\n";
print join("\n", $result->logs());
| package main
import (
"fmt"
"math"
)
type mwriter struct {
value float64
log string
}
func (m mwriter) bind(f func(v float64) mwriter) mwriter {
n := f(m.value)
n.log = m.log + n.log
return n
}
func unit(v float64, s string) mwriter {
return mwriter{v, fmt.Sprintf(" %-17s: %g\n", s, v)}
}
func root(v float64) mwriter {
return unit(math.Sqrt(v), "Took square root")
}
func addOne(v float64) mwriter {
return unit(v+1, "Added one")
}
func half(v float64) mwriter {
return unit(v/2, "Divided by two")
}
func main() {
mw1 := unit(5, "Initial value")
mw2 := mw1.bind(root).bind(addOne).bind(half)
fmt.Println("The Golden Ratio is", mw2.value)
fmt.Println("\nThis was derived as follows:-")
fmt.Println(mw2.log)
}
|
Transform the following PHP implementation into Go, maintaining the same output and logic. |
function RGBtoHSV($r, $g, $b) {
$r = $r/255.; // convert to range 0..1
$g = $g/255.;
$b = $b/255.;
$cols = array("r" => $r, "g" => $g, "b" => $b);
asort($cols, SORT_NUMERIC);
$min = key(array_slice($cols, 1)); // "r", "g" or "b"
$max = key(array_slice($cols, -1)); // "r", "g" or "b"
if($cols[$min] == $cols[$max]) {
$h = 0;
} else {
if($max == "r") {
$h = 60. * ( 0 + ( ($cols["g"]-$cols["b"]) / ($cols[$max]-$cols[$min]) ) );
} elseif ($max == "g") {
$h = 60. * ( 2 + ( ($cols["b"]-$cols["r"]) / ($cols[$max]-$cols[$min]) ) );
} elseif ($max == "b") {
$h = 60. * ( 4 + ( ($cols["r"]-$cols["g"]) / ($cols[$max]-$cols[$min]) ) );
}
if($h < 0) {
$h += 360;
}
}
if($cols[$max] == 0) {
$s = 0;
} else {
$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );
$s = $s * 255;
}
$v = $cols[$max];
$v = $v * 255;
return(array($h, $s, $v));
}
$filename = "image.png";
$dimensions = getimagesize($filename);
$w = $dimensions[0]; // width
$h = $dimensions[1]; // height
$im = imagecreatefrompng($filename);
for($hi=0; $hi < $h; $hi++) {
for($wi=0; $wi < $w; $wi++) {
$rgb = imagecolorat($im, $wi, $hi);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$hsv = RGBtoHSV($r, $g, $b);
$brgb = imagecolorat($im, $wi, $hi+1);
$br = ($brgb >> 16) & 0xFF;
$bg = ($brgb >> 8) & 0xFF;
$bb = $brgb & 0xFF;
$bhsv = RGBtoHSV($br, $bg, $bb);
if($hsv[2]-$bhsv[2] > 20) {
imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));
}
else {
imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));
}
}
}
header('Content-Type: image/jpeg');
imagepng($im);
imagedestroy($im);
| package main
import (
ed "github.com/Ernyoke/Imger/edgedetection"
"github.com/Ernyoke/Imger/imgio"
"log"
)
func main() {
img, err := imgio.ImreadRGBA("Valve_original_(1).png")
if err != nil {
log.Fatal("Could not read image", err)
}
cny, err := ed.CannyRGBA(img, 15, 45, 5)
if err != nil {
log.Fatal("Could not perform Canny Edge detection")
}
err = imgio.Imwrite(cny, "Valve_canny_(1).png")
if err != nil {
log.Fatal("Could not write Canny image to disk")
}
}
|
Generate an equivalent Go version of this PHP code. |
function RGBtoHSV($r, $g, $b) {
$r = $r/255.; // convert to range 0..1
$g = $g/255.;
$b = $b/255.;
$cols = array("r" => $r, "g" => $g, "b" => $b);
asort($cols, SORT_NUMERIC);
$min = key(array_slice($cols, 1)); // "r", "g" or "b"
$max = key(array_slice($cols, -1)); // "r", "g" or "b"
if($cols[$min] == $cols[$max]) {
$h = 0;
} else {
if($max == "r") {
$h = 60. * ( 0 + ( ($cols["g"]-$cols["b"]) / ($cols[$max]-$cols[$min]) ) );
} elseif ($max == "g") {
$h = 60. * ( 2 + ( ($cols["b"]-$cols["r"]) / ($cols[$max]-$cols[$min]) ) );
} elseif ($max == "b") {
$h = 60. * ( 4 + ( ($cols["r"]-$cols["g"]) / ($cols[$max]-$cols[$min]) ) );
}
if($h < 0) {
$h += 360;
}
}
if($cols[$max] == 0) {
$s = 0;
} else {
$s = ( ($cols[$max]-$cols[$min])/$cols[$max] );
$s = $s * 255;
}
$v = $cols[$max];
$v = $v * 255;
return(array($h, $s, $v));
}
$filename = "image.png";
$dimensions = getimagesize($filename);
$w = $dimensions[0]; // width
$h = $dimensions[1]; // height
$im = imagecreatefrompng($filename);
for($hi=0; $hi < $h; $hi++) {
for($wi=0; $wi < $w; $wi++) {
$rgb = imagecolorat($im, $wi, $hi);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$hsv = RGBtoHSV($r, $g, $b);
$brgb = imagecolorat($im, $wi, $hi+1);
$br = ($brgb >> 16) & 0xFF;
$bg = ($brgb >> 8) & 0xFF;
$bb = $brgb & 0xFF;
$bhsv = RGBtoHSV($br, $bg, $bb);
if($hsv[2]-$bhsv[2] > 20) {
imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 255, 0, 0));
}
else {
imagesetpixel($im, $wi, $hi, imagecolorallocate($im, 0, 0, 0));
}
}
}
header('Content-Type: image/jpeg');
imagepng($im);
imagedestroy($im);
| package main
import (
ed "github.com/Ernyoke/Imger/edgedetection"
"github.com/Ernyoke/Imger/imgio"
"log"
)
func main() {
img, err := imgio.ImreadRGBA("Valve_original_(1).png")
if err != nil {
log.Fatal("Could not read image", err)
}
cny, err := ed.CannyRGBA(img, 15, 45, 5)
if err != nil {
log.Fatal("Could not perform Canny Edge detection")
}
err = imgio.Imwrite(cny, "Valve_canny_(1).png")
if err != nil {
log.Fatal("Could not write Canny image to disk")
}
}
|
Port the provided PHP code into Go while preserving the original functionality. | class E {};
$e=new E();
$e->foo=1;
$e->{"foo"} = 1; // using a runtime name
$x = "foo";
$e->$x = 1; // using a runtime name in a variable
| package main
import (
"bufio"
"fmt"
"log"
"os"
)
type SomeStruct struct {
runtimeFields map[string]string
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
ss := SomeStruct{make(map[string]string)}
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Create two fields at runtime: ")
for i := 1; i <= 2; i++ {
fmt.Printf(" Field #%d:\n", i)
fmt.Print(" Enter name : ")
scanner.Scan()
name := scanner.Text()
fmt.Print(" Enter value : ")
scanner.Scan()
value := scanner.Text()
check(scanner.Err())
ss.runtimeFields[name] = value
fmt.Println()
}
for {
fmt.Print("Which field do you want to inspect ? ")
scanner.Scan()
name := scanner.Text()
check(scanner.Err())
value, ok := ss.runtimeFields[name]
if !ok {
fmt.Println("There is no field of that name, try again")
} else {
fmt.Printf("Its value is '%s'\n", value)
return
}
}
}
|
Change the following PHP code into Go without altering its purpose. | class E {};
$e=new E();
$e->foo=1;
$e->{"foo"} = 1; // using a runtime name
$x = "foo";
$e->$x = 1; // using a runtime name in a variable
| package main
import (
"bufio"
"fmt"
"log"
"os"
)
type SomeStruct struct {
runtimeFields map[string]string
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
ss := SomeStruct{make(map[string]string)}
scanner := bufio.NewScanner(os.Stdin)
fmt.Println("Create two fields at runtime: ")
for i := 1; i <= 2; i++ {
fmt.Printf(" Field #%d:\n", i)
fmt.Print(" Enter name : ")
scanner.Scan()
name := scanner.Text()
fmt.Print(" Enter value : ")
scanner.Scan()
value := scanner.Text()
check(scanner.Err())
ss.runtimeFields[name] = value
fmt.Println()
}
for {
fmt.Print("Which field do you want to inspect ? ")
scanner.Scan()
name := scanner.Text()
check(scanner.Err())
value, ok := ss.runtimeFields[name]
if !ok {
fmt.Println("There is no field of that name, try again")
} else {
fmt.Printf("Its value is '%s'\n", value)
return
}
}
}
|
Write the same code in Go as shown below in PHP. | $tests = array(
'this URI contains an illegal character, parentheses and a misplaced full stop:',
'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).',
'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)',
'")" is handled the wrong way by the mediawiki parser.',
'ftp://domain.name/path(balanced_brackets)/foo.html',
'ftp://domain.name/path(balanced_brackets)/ending.in.dot.',
'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.',
'leading junk ftp://domain.name/path/embedded?punct/uation.',
'leading junk ftp://domain.name/dangling_close_paren)',
'if you have other interesting URIs for testing, please add them here:',
'http://www.example.org/foo.html#includes_fragment',
'http://www.example.org/foo.html#enthält_Unicode-Fragment',
' http://192.168.0.1/admin/?hackme=%%%%%%%%%true',
'blah (foo://domain.hld/))))',
'https://haxor.ur:4592/~mama/####&?foo'
);
foreach ( $tests as $test ) {
foreach( explode( ' ', $test ) as $uri ) {
if ( filter_var( $uri, FILTER_VALIDATE_URL ) )
echo $uri, PHP_EOL;
}
}
| package main
import (
"fmt"
"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre"
)
var pattern =
"(*UTF)(*UCP)" +
"[a-z][-a-z0-9+.]*:" +
"(?=[/\\w])" +
"(?:
"[-\\w.~/%!$&'()*+,;=]*" +
"(?:\\?[-\\w.~%!$&'()*+,;=/?]*)?" +
"(?:\\#[-\\w.~%!$&'()*+,;=/?]*)?"
func main() {
text := `
this URI contains an illegal character, parentheses and a misplaced full stop:
http:
and another one just to confuse the parser: http:
")" is handled the wrong way by the mediawiki parser.
ftp:
ftp:
ftp:
leading junk ftp:
leading junk ftp:
if you have other interesting URIs for testing, please add them here:
http:
http:
`
descs := []string{"URIs:-", "IRIs:-"}
patterns := []string{pattern[12:], pattern}
for i := 0; i <= 1; i++ {
fmt.Println(descs[i])
re := pcre.MustCompile(patterns[i], 0)
t := text
for {
se := re.FindIndex([]byte(t), 0)
if se == nil {
break
}
fmt.Println(t[se[0]:se[1]])
t = t[se[1]:]
}
fmt.Println()
}
}
|
Port the following code from PHP to Go with equivalent syntax and logic. | $tests = array(
'this URI contains an illegal character, parentheses and a misplaced full stop:',
'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).',
'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)',
'")" is handled the wrong way by the mediawiki parser.',
'ftp://domain.name/path(balanced_brackets)/foo.html',
'ftp://domain.name/path(balanced_brackets)/ending.in.dot.',
'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.',
'leading junk ftp://domain.name/path/embedded?punct/uation.',
'leading junk ftp://domain.name/dangling_close_paren)',
'if you have other interesting URIs for testing, please add them here:',
'http://www.example.org/foo.html#includes_fragment',
'http://www.example.org/foo.html#enthält_Unicode-Fragment',
' http://192.168.0.1/admin/?hackme=%%%%%%%%%true',
'blah (foo://domain.hld/))))',
'https://haxor.ur:4592/~mama/####&?foo'
);
foreach ( $tests as $test ) {
foreach( explode( ' ', $test ) as $uri ) {
if ( filter_var( $uri, FILTER_VALIDATE_URL ) )
echo $uri, PHP_EOL;
}
}
| package main
import (
"fmt"
"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre"
)
var pattern =
"(*UTF)(*UCP)" +
"[a-z][-a-z0-9+.]*:" +
"(?=[/\\w])" +
"(?:
"[-\\w.~/%!$&'()*+,;=]*" +
"(?:\\?[-\\w.~%!$&'()*+,;=/?]*)?" +
"(?:\\#[-\\w.~%!$&'()*+,;=/?]*)?"
func main() {
text := `
this URI contains an illegal character, parentheses and a misplaced full stop:
http:
and another one just to confuse the parser: http:
")" is handled the wrong way by the mediawiki parser.
ftp:
ftp:
ftp:
leading junk ftp:
leading junk ftp:
if you have other interesting URIs for testing, please add them here:
http:
http:
`
descs := []string{"URIs:-", "IRIs:-"}
patterns := []string{pattern[12:], pattern}
for i := 0; i <= 1; i++ {
fmt.Println(descs[i])
re := pcre.MustCompile(patterns[i], 0)
t := text
for {
se := re.FindIndex([]byte(t), 0)
if se == nil {
break
}
fmt.Println(t[se[0]:se[1]])
t = t[se[1]:]
}
fmt.Println()
}
}
|
Port the following code from PHP to Go with equivalent syntax and logic. | $tests = array(
'this URI contains an illegal character, parentheses and a misplaced full stop:',
'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).',
'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)',
'")" is handled the wrong way by the mediawiki parser.',
'ftp://domain.name/path(balanced_brackets)/foo.html',
'ftp://domain.name/path(balanced_brackets)/ending.in.dot.',
'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.',
'leading junk ftp://domain.name/path/embedded?punct/uation.',
'leading junk ftp://domain.name/dangling_close_paren)',
'if you have other interesting URIs for testing, please add them here:',
'http://www.example.org/foo.html#includes_fragment',
'http://www.example.org/foo.html#enthält_Unicode-Fragment',
' http://192.168.0.1/admin/?hackme=%%%%%%%%%true',
'blah (foo://domain.hld/))))',
'https://haxor.ur:4592/~mama/####&?foo'
);
foreach ( $tests as $test ) {
foreach( explode( ' ', $test ) as $uri ) {
if ( filter_var( $uri, FILTER_VALIDATE_URL ) )
echo $uri, PHP_EOL;
}
}
| package main
import (
"fmt"
"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre"
)
var pattern =
"(*UTF)(*UCP)" +
"[a-z][-a-z0-9+.]*:" +
"(?=[/\\w])" +
"(?:
"[-\\w.~/%!$&'()*+,;=]*" +
"(?:\\?[-\\w.~%!$&'()*+,;=/?]*)?" +
"(?:\\#[-\\w.~%!$&'()*+,;=/?]*)?"
func main() {
text := `
this URI contains an illegal character, parentheses and a misplaced full stop:
http:
and another one just to confuse the parser: http:
")" is handled the wrong way by the mediawiki parser.
ftp:
ftp:
ftp:
leading junk ftp:
leading junk ftp:
if you have other interesting URIs for testing, please add them here:
http:
http:
`
descs := []string{"URIs:-", "IRIs:-"}
patterns := []string{pattern[12:], pattern}
for i := 0; i <= 1; i++ {
fmt.Println(descs[i])
re := pcre.MustCompile(patterns[i], 0)
t := text
for {
se := re.FindIndex([]byte(t), 0)
if se == nil {
break
}
fmt.Println(t[se[0]:se[1]])
t = t[se[1]:]
}
fmt.Println()
}
}
|
Rewrite this program in Go while keeping its functionality equivalent to the PHP version. | $tests = array(
'this URI contains an illegal character, parentheses and a misplaced full stop:',
'http://en.wikipedia.org/wiki/Erich_Kästner_(camera_designer). (which is handled by http://mediawiki.org/).',
'and another one just to confuse the parser: http://en.wikipedia.org/wiki/-)',
'")" is handled the wrong way by the mediawiki parser.',
'ftp://domain.name/path(balanced_brackets)/foo.html',
'ftp://domain.name/path(balanced_brackets)/ending.in.dot.',
'ftp://domain.name/path(unbalanced_brackets/ending.in.dot.',
'leading junk ftp://domain.name/path/embedded?punct/uation.',
'leading junk ftp://domain.name/dangling_close_paren)',
'if you have other interesting URIs for testing, please add them here:',
'http://www.example.org/foo.html#includes_fragment',
'http://www.example.org/foo.html#enthält_Unicode-Fragment',
' http://192.168.0.1/admin/?hackme=%%%%%%%%%true',
'blah (foo://domain.hld/))))',
'https://haxor.ur:4592/~mama/####&?foo'
);
foreach ( $tests as $test ) {
foreach( explode( ' ', $test ) as $uri ) {
if ( filter_var( $uri, FILTER_VALIDATE_URL ) )
echo $uri, PHP_EOL;
}
}
| package main
import (
"fmt"
"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre"
)
var pattern =
"(*UTF)(*UCP)" +
"[a-z][-a-z0-9+.]*:" +
"(?=[/\\w])" +
"(?:
"[-\\w.~/%!$&'()*+,;=]*" +
"(?:\\?[-\\w.~%!$&'()*+,;=/?]*)?" +
"(?:\\#[-\\w.~%!$&'()*+,;=/?]*)?"
func main() {
text := `
this URI contains an illegal character, parentheses and a misplaced full stop:
http:
and another one just to confuse the parser: http:
")" is handled the wrong way by the mediawiki parser.
ftp:
ftp:
ftp:
leading junk ftp:
leading junk ftp:
if you have other interesting URIs for testing, please add them here:
http:
http:
`
descs := []string{"URIs:-", "IRIs:-"}
patterns := []string{pattern[12:], pattern}
for i := 0; i <= 1; i++ {
fmt.Println(descs[i])
re := pcre.MustCompile(patterns[i], 0)
t := text
for {
se := re.FindIndex([]byte(t), 0)
if se == nil {
break
}
fmt.Println(t[se[0]:se[1]])
t = t[se[1]:]
}
fmt.Println()
}
}
|
Write a version of this Python function in VB with identical behavior. | from collections import Counter
from pprint import pprint as pp
def distcheck(fn, repeats, delta):
bin = Counter(fn() for i in range(repeats))
target = repeats // len(bin)
deltacount = int(delta / 100. * target)
assert all( abs(target - count) < deltacount
for count in bin.values() ), "Bin distribution skewed from %i +/- %i: %s" % (
target, deltacount, [ (key, target - count)
for key, count in sorted(bin.items()) ]
)
pp(dict(bin))
| Option Explicit
sub verifydistribution(calledfunction, samples, delta)
Dim i, n, maxdiff
Dim d : Set d = CreateObject("Scripting.Dictionary")
wscript.echo "Running """ & calledfunction & """ " & samples & " times..."
for i = 1 to samples
Execute "n = " & calledfunction
d(n) = d(n) + 1
next
n = d.Count
maxdiff = 0
wscript.echo "Expected average count is " & Int(samples/n) & " across " & n & " buckets."
for each i in d.Keys
dim diff : diff = abs(1 - d(i) / (samples/n))
if diff > maxdiff then maxdiff = diff
wscript.echo "Bucket " & i & " had " & d(i) & " occurences" _
& vbTab & " difference from expected=" & FormatPercent(diff, 2)
next
wscript.echo "Maximum found variation is " & FormatPercent(maxdiff, 2) _
& ", desired limit is " & FormatPercent(delta, 2) & "."
if maxdiff > delta then wscript.echo "Skewed!" else wscript.echo "Smooth!"
end sub
|
Transform the following Python implementation into VB, maintaining the same output and logic. | computed = {}
def sterling2(n, k):
key = str(n) + "," + str(k)
if key in computed.keys():
return computed[key]
if n == k == 0:
return 1
if (n > 0 and k == 0) or (n == 0 and k > 0):
return 0
if n == k:
return 1
if k > n:
return 0
result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
computed[key] = result
return result
print("Stirling numbers of the second kind:")
MAX = 12
print("n/k".ljust(10), end="")
for n in range(MAX + 1):
print(str(n).rjust(10), end="")
print()
for n in range(MAX + 1):
print(str(n).ljust(10), end="")
for k in range(n + 1):
print(str(sterling2(n, k)).rjust(10), end="")
print()
print("The maximum value of S2(100, k) = ")
previous = 0
for k in range(1, 100 + 1):
current = sterling2(100, k)
if current > previous:
previous = current
else:
print("{0}\n({1} digits, k = {2})\n".format(previous, len(str(previous)), k - 1))
break
| Imports System.Numerics
Module Module1
Class Sterling
Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger)
Private Shared Function CacheKey(n As Integer, k As Integer) As String
Return String.Format("{0}:{1}", n, k)
End Function
Private Shared Function Impl(n As Integer, k As Integer) As BigInteger
If n = 0 AndAlso k = 0 Then
Return 1
End If
If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then
Return 0
End If
If n = k Then
Return 1
End If
If k > n Then
Return 0
End If
Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1)
End Function
Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger
Dim key = CacheKey(n, k)
If COMPUTED.ContainsKey(key) Then
Return COMPUTED(key)
End If
Dim result = Impl(n, k)
COMPUTED.Add(key, result)
Return result
End Function
End Class
Sub Main()
Console.WriteLine("Stirling numbers of the second kind:")
Dim max = 12
Console.Write("n/k")
For n = 0 To max
Console.Write("{0,10}", n)
Next
Console.WriteLine()
For n = 0 To max
Console.Write("{0,3}", n)
For k = 0 To n
Console.Write("{0,10}", Sterling.Sterling2(n, k))
Next
Console.WriteLine()
Next
Console.WriteLine("The maximum value of S2(100, k) = ")
Dim previous = BigInteger.Zero
For k = 1 To 100
Dim current = Sterling.Sterling2(100, k)
If current > previous Then
previous = current
Else
Console.WriteLine(previous)
Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1)
Exit For
End If
Next
End Sub
End Module
|
Port the provided Python code into VB while preserving the original functionality. | computed = {}
def sterling2(n, k):
key = str(n) + "," + str(k)
if key in computed.keys():
return computed[key]
if n == k == 0:
return 1
if (n > 0 and k == 0) or (n == 0 and k > 0):
return 0
if n == k:
return 1
if k > n:
return 0
result = k * sterling2(n - 1, k) + sterling2(n - 1, k - 1)
computed[key] = result
return result
print("Stirling numbers of the second kind:")
MAX = 12
print("n/k".ljust(10), end="")
for n in range(MAX + 1):
print(str(n).rjust(10), end="")
print()
for n in range(MAX + 1):
print(str(n).ljust(10), end="")
for k in range(n + 1):
print(str(sterling2(n, k)).rjust(10), end="")
print()
print("The maximum value of S2(100, k) = ")
previous = 0
for k in range(1, 100 + 1):
current = sterling2(100, k)
if current > previous:
previous = current
else:
print("{0}\n({1} digits, k = {2})\n".format(previous, len(str(previous)), k - 1))
break
| Imports System.Numerics
Module Module1
Class Sterling
Private Shared ReadOnly COMPUTED As New Dictionary(Of String, BigInteger)
Private Shared Function CacheKey(n As Integer, k As Integer) As String
Return String.Format("{0}:{1}", n, k)
End Function
Private Shared Function Impl(n As Integer, k As Integer) As BigInteger
If n = 0 AndAlso k = 0 Then
Return 1
End If
If (n > 0 AndAlso k = 0) OrElse (n = 0 AndAlso k > 0) Then
Return 0
End If
If n = k Then
Return 1
End If
If k > n Then
Return 0
End If
Return k * Sterling2(n - 1, k) + Sterling2(n - 1, k - 1)
End Function
Public Shared Function Sterling2(n As Integer, k As Integer) As BigInteger
Dim key = CacheKey(n, k)
If COMPUTED.ContainsKey(key) Then
Return COMPUTED(key)
End If
Dim result = Impl(n, k)
COMPUTED.Add(key, result)
Return result
End Function
End Class
Sub Main()
Console.WriteLine("Stirling numbers of the second kind:")
Dim max = 12
Console.Write("n/k")
For n = 0 To max
Console.Write("{0,10}", n)
Next
Console.WriteLine()
For n = 0 To max
Console.Write("{0,3}", n)
For k = 0 To n
Console.Write("{0,10}", Sterling.Sterling2(n, k))
Next
Console.WriteLine()
Next
Console.WriteLine("The maximum value of S2(100, k) = ")
Dim previous = BigInteger.Zero
For k = 1 To 100
Dim current = Sterling.Sterling2(100, k)
If current > previous Then
previous = current
Else
Console.WriteLine(previous)
Console.WriteLine("({0} digits, k = {1})", previous.ToString().Length, k - 1)
Exit For
End If
Next
End Sub
End Module
|
Port the following code from Python to VB with equivalent syntax and logic. | from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
yield nxt
while True:
an1, n = nxt, n + 1
nxt = an1 - n
if nxt < 0 or nxt in a:
nxt = an1 + n
a.add(nxt)
self.n = n
yield nxt
if __name__ == '__main__':
recamans = Recamans()
print("First fifteen members of Recamans sequence:",
list(islice(recamans(), 15)))
so_far = set()
for term in recamans():
if term in so_far:
print(f"First duplicate number in series is: a({recamans.n}) = {term}")
break
so_far.add(term)
n = 1_000
setn = set(range(n + 1))
for _ in recamans():
if setn.issubset(recamans.a):
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
break
|
nx=15
h=1000
Wscript.StdOut.WriteLine "Recaman
Wscript.StdOut.WriteLine recaman("seq",nx)
Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0)
Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h)
Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine()
function recaman(op,nn)
Dim b,d,h
Set b = CreateObject("Scripting.Dictionary")
Set d = CreateObject("Scripting.Dictionary")
list="0" : firstdup=0
if op="firstdup" then
nn=1000 : firstdup=1
end if
if op="numterm" then
h=nn : nn=10000000 : numterm=1
end if
ax=0
b.Add 0,1
s=0
for n=1 to nn-1
an=ax-n
if an<=0 then
an=ax+n
elseif b.Exists(an) then
an=ax+n
end if
ax=an
if not b.Exists(an) then b.Add an,1
if op="seq" then
list=list&" "&an
end if
if firstdup then
if d.Exists(an) then
recaman="a("&n&")="&an
exit function
else
d.Add an,1
end if
end if
if numterm then
if an<=h then
if not d.Exists(an) then
s=s+1
d.Add an,1
end if
if s>=h then
recaman=n
exit function
end if
end if
end if
next
recaman=list
end function
|
Keep all operations the same but rewrite the snippet in VB. | from itertools import islice
class Recamans():
"Recamán's sequence generator callable class"
def __init__(self):
self.a = None
self.n = None
def __call__(self):
"Recamán's sequence generator"
nxt = 0
a, n = {nxt}, 0
self.a = a
self.n = n
yield nxt
while True:
an1, n = nxt, n + 1
nxt = an1 - n
if nxt < 0 or nxt in a:
nxt = an1 + n
a.add(nxt)
self.n = n
yield nxt
if __name__ == '__main__':
recamans = Recamans()
print("First fifteen members of Recamans sequence:",
list(islice(recamans(), 15)))
so_far = set()
for term in recamans():
if term in so_far:
print(f"First duplicate number in series is: a({recamans.n}) = {term}")
break
so_far.add(term)
n = 1_000
setn = set(range(n + 1))
for _ in recamans():
if setn.issubset(recamans.a):
print(f"Range 0 ..{n} is covered by terms up to a({recamans.n})")
break
|
nx=15
h=1000
Wscript.StdOut.WriteLine "Recaman
Wscript.StdOut.WriteLine recaman("seq",nx)
Wscript.StdOut.WriteLine "The first duplicate number is: " & recaman("firstdup",0)
Wscript.StdOut.WriteLine "The number of terms to complete the range 0--->"& h &" is: "& recaman("numterm",h)
Wscript.StdOut.Write vbCrlf&".../...": zz=Wscript.StdIn.ReadLine()
function recaman(op,nn)
Dim b,d,h
Set b = CreateObject("Scripting.Dictionary")
Set d = CreateObject("Scripting.Dictionary")
list="0" : firstdup=0
if op="firstdup" then
nn=1000 : firstdup=1
end if
if op="numterm" then
h=nn : nn=10000000 : numterm=1
end if
ax=0
b.Add 0,1
s=0
for n=1 to nn-1
an=ax-n
if an<=0 then
an=ax+n
elseif b.Exists(an) then
an=ax+n
end if
ax=an
if not b.Exists(an) then b.Add an,1
if op="seq" then
list=list&" "&an
end if
if firstdup then
if d.Exists(an) then
recaman="a("&n&")="&an
exit function
else
d.Add an,1
end if
end if
if numterm then
if an<=h then
if not d.Exists(an) then
s=s+1
d.Add an,1
end if
if s>=h then
recaman=n
exit function
end if
end if
end if
next
recaman=list
end function
|
Preserve the algorithm and functionality while converting the code from Python to VB. |
import random
board = list('123456789')
wins = ((0,1,2), (3,4,5), (6,7,8),
(0,3,6), (1,4,7), (2,5,8),
(0,4,8), (2,4,6))
def printboard():
print('\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))
def score():
for w in wins:
b = board[w[0]]
if b in 'XO' and all (board[i] == b for i in w):
return b, [i+1 for i in w]
return None, None
def finished():
return all (b in 'XO' for b in board)
def space():
return [ b for b in board if b not in 'XO']
def my_turn(xo):
options = space()
choice = random.choice(options)
board[int(choice)-1] = xo
return choice
def your_turn(xo):
options = space()
while True:
choice = input(" Put your %s in any of these positions: %s "
% (xo, ''.join(options))).strip()
if choice in options:
break
print( "Whoops I don't understand the input" )
board[int(choice)-1] = xo
return choice
def me(xo='X'):
printboard()
print('I go at', my_turn(xo))
return score()
assert not s[0], "\n%s wins across %s" % s
def you(xo='O'):
printboard()
print('You went at', your_turn(xo))
return score()
assert not s[0], "\n%s wins across %s" % s
print(__doc__)
while not finished():
s = me('X')
if s[0]:
printboard()
print("\n%s wins across %s" % s)
break
if not finished():
s = you('O')
if s[0]:
printboard()
print("\n%s wins across %s" % s)
break
else:
print('\nA draw')
| Option Explicit
Private Lines(1 To 3, 1 To 3) As String
Private Nb As Byte, player As Byte
Private GameWin As Boolean, GameOver As Boolean
Sub Main_TicTacToe()
Dim p As String
InitLines
printLines Nb
Do
p = WhoPlay
Debug.Print p & " play"
If p = "Human" Then
Call HumanPlay
GameWin = IsWinner("X")
Else
Call ComputerPlay
GameWin = IsWinner("O")
End If
If Not GameWin Then GameOver = IsEnd
Loop Until GameWin Or GameOver
If Not GameOver Then
Debug.Print p & " Win !"
Else
Debug.Print "Game Over!"
End If
End Sub
Sub InitLines(Optional S As String)
Dim i As Byte, j As Byte
Nb = 0: player = 0
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
Lines(i, j) = "#"
Next j
Next i
End Sub
Sub printLines(Nb As Byte)
Dim i As Byte, j As Byte, strT As String
Debug.Print "Loop " & Nb
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
strT = strT & Lines(i, j)
Next j
Debug.Print strT
strT = vbNullString
Next i
End Sub
Function WhoPlay(Optional S As String) As String
If player = 0 Then
player = 1
WhoPlay = "Human"
Else
player = 0
WhoPlay = "Computer"
End If
End Function
Sub HumanPlay(Optional S As String)
Dim L As Byte, C As Byte, GoodPlay As Boolean
Do
L = Application.InputBox("Choose the row", "Numeric only", Type:=1)
If L > 0 And L < 4 Then
C = Application.InputBox("Choose the column", "Numeric only", Type:=1)
If C > 0 And C < 4 Then
If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then
Lines(L, C) = "X"
Nb = Nb + 1
printLines Nb
GoodPlay = True
End If
End If
End If
Loop Until GoodPlay
End Sub
Sub ComputerPlay(Optional S As String)
Dim L As Byte, C As Byte, GoodPlay As Boolean
Randomize Timer
Do
L = Int((Rnd * 3) + 1)
C = Int((Rnd * 3) + 1)
If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then
Lines(L, C) = "O"
Nb = Nb + 1
printLines Nb
GoodPlay = True
End If
Loop Until GoodPlay
End Sub
Function IsWinner(S As String) As Boolean
Dim i As Byte, j As Byte, Ch As String, strTL As String, strTC As String
Ch = String(UBound(Lines, 1), S)
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
strTL = strTL & Lines(i, j)
strTC = strTC & Lines(j, i)
Next j
If strTL = Ch Or strTC = Ch Then IsWinner = True: Exit For
strTL = vbNullString: strTC = vbNullString
Next i
strTL = Lines(1, 1) & Lines(2, 2) & Lines(3, 3)
strTC = Lines(1, 3) & Lines(2, 2) & Lines(3, 1)
If strTL = Ch Or strTC = Ch Then IsWinner = True
End Function
Function IsEnd() As Boolean
Dim i As Byte, j As Byte
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
If Lines(i, j) = "#" Then Exit Function
Next j
Next i
IsEnd = True
End Function
|
Generate a VB translation of this Python snippet without changing its computational steps. | i=1
while i:
print(i)
i += 1
| For i As Integer = 0 To Integer.MaxValue
Console.WriteLine(i)
Next
|
Produce a language-to-language conversion: from Python to VB, same semantics. | i=1
while i:
print(i)
i += 1
| For i As Integer = 0 To Integer.MaxValue
Console.WriteLine(i)
Next
|
Change the following Python code into VB without altering its purpose. | >>> import socket
>>> ips = set(i[4][0] for i in socket.getaddrinfo('www.kame.net', 80))
>>> for ip in ips: print ip
...
2001:200:dff:fff1:216:3eff:feb1:44d7
203.178.141.194
| Function dns_query(url,ver)
Set r = New RegExp
r.Pattern = "Pinging.+?\[(.+?)\].+"
Set objshell = CreateObject("WScript.Shell")
Set objexec = objshell.Exec("%comspec% /c " & "ping -" & ver & " " & url)
WScript.StdOut.WriteLine "URL: " & url
Do Until objexec.StdOut.AtEndOfStream
line = objexec.StdOut.ReadLine
If r.Test(line) Then
WScript.StdOut.WriteLine "IP Version " &_
ver & ": " & r.Replace(line,"$1")
End If
Loop
End Function
Call dns_query(WScript.Arguments(0),WScript.Arguments(1))
|
Translate the given Python code snippet into VB without altering its behavior. | import turtle as tt
import inspect
stack = []
def peano(iterations=1):
global stack
ivan = tt.Turtle(shape = "classic", visible = True)
screen = tt.Screen()
screen.title("Desenhin do Peano")
screen.bgcolor("
screen.delay(0)
screen.setup(width=0.95, height=0.9)
walk = 1
def screenlength(k):
if k != 0:
length = screenlength(k-1)
return 2*length + 1
else: return 0
kkkj = screenlength(iterations)
screen.setworldcoordinates(-1, -1, kkkj + 1, kkkj + 1)
ivan.color("
def step1(k):
global stack
stack.append(len(inspect.stack()))
if k != 0:
ivan.left(90)
step2(k - 1)
ivan.forward(walk)
ivan.right(90)
step1(k - 1)
ivan.forward(walk)
step1(k - 1)
ivan.right(90)
ivan.forward(walk)
step2(k - 1)
ivan.left(90)
def step2(k):
global stack
stack.append(len(inspect.stack()))
if k != 0:
ivan.right(90)
step1(k - 1)
ivan.forward(walk)
ivan.left(90)
step2(k - 1)
ivan.forward(walk)
step2(k - 1)
ivan.left(90)
ivan.forward(walk)
step1(k - 1)
ivan.right(90)
ivan.left(90)
step2(iterations)
tt.done()
if __name__ == "__main__":
peano(4)
import pylab as P
P.plot(stack)
P.show()
| Const WIDTH = 243
Dim n As Long
Dim points() As Single
Dim flag As Boolean
Private Sub lineto(x As Integer, y As Integer)
If flag Then
points(n, 1) = x
points(n, 2) = y
End If
n = n + 1
End Sub
Private Sub Peano(ByVal x As Integer, ByVal y As Integer, ByVal lg As Integer, _
ByVal i1 As Integer, ByVal i2 As Integer)
If (lg = 1) Then
Call lineto(x * 3, y * 3)
Exit Sub
End If
lg = lg / 3
Call Peano(x + (2 * i1 * lg), y + (2 * i1 * lg), lg, i1, i2)
Call Peano(x + ((i1 - i2 + 1) * lg), y + ((i1 + i2) * lg), lg, i1, 1 - i2)
Call Peano(x + lg, y + lg, lg, i1, 1 - i2)
Call Peano(x + ((i1 + i2) * lg), y + ((i1 - i2 + 1) * lg), lg, 1 - i1, 1 - i2)
Call Peano(x + (2 * i2 * lg), y + (2 * (1 - i2) * lg), lg, i1, i2)
Call Peano(x + ((1 + i2 - i1) * lg), y + ((2 - i1 - i2) * lg), lg, i1, i2)
Call Peano(x + (2 * (1 - i1) * lg), y + (2 * (1 - i1) * lg), lg, i1, i2)
Call Peano(x + ((2 - i1 - i2) * lg), y + ((1 + i2 - i1) * lg), lg, 1 - i1, i2)
Call Peano(x + (2 * (1 - i2) * lg), y + (2 * i2 * lg), lg, 1 - i1, i2)
End Sub
Sub main()
n = 1: flag = False
Call Peano(0, 0, WIDTH, 0, 0)
ReDim points(1 To n - 1, 1 To 2)
n = 1: flag = True
Call Peano(0, 0, WIDTH, 0, 0)
ActiveSheet.Shapes.AddPolyline points
End Sub
|
Rewrite the snippet below in VB so it works the same as the original Python code. | from random import randint
def dice5():
return randint(1, 5)
def dice7():
r = dice5() + dice5() * 5 - 6
return (r % 7) + 1 if r < 21 else dice7()
| Private Function Test4DiscreteUniformDistribution(ObservationFrequencies() As Variant, Significance As Single) As Boolean
Dim Total As Long, Ei As Long, i As Integer
Dim ChiSquared As Double, DegreesOfFreedom As Integer, p_value As Double
Debug.Print "[1] ""Data set:"" ";
For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
Total = Total + ObservationFrequencies(i)
Debug.Print ObservationFrequencies(i); " ";
Next i
DegreesOfFreedom = UBound(ObservationFrequencies) - LBound(ObservationFrequencies)
Ei = Total / (DegreesOfFreedom + 1)
For i = LBound(ObservationFrequencies) To UBound(ObservationFrequencies)
ChiSquared = ChiSquared + (ObservationFrequencies(i) - Ei) ^ 2 / Ei
Next i
p_value = 1 - WorksheetFunction.ChiSq_Dist(ChiSquared, DegreesOfFreedom, True)
Debug.Print
Debug.Print "Chi-squared test for given frequencies"
Debug.Print "X-squared ="; Format(ChiSquared, "0.0000"); ", ";
Debug.Print "df ="; DegreesOfFreedom; ", ";
Debug.Print "p-value = "; Format(p_value, "0.0000")
Test4DiscreteUniformDistribution = p_value > Significance
End Function
Private Function Dice5() As Integer
Dice5 = Int(5 * Rnd + 1)
End Function
Private Function Dice7() As Integer
Dim i As Integer
Do
i = 5 * (Dice5 - 1) + Dice5
Loop While i > 21
Dice7 = i Mod 7 + 1
End Function
Sub TestDice7()
Dim i As Long, roll As Integer
Dim Bins(1 To 7) As Variant
For i = 1 To 1000000
roll = Dice7
Bins(roll) = Bins(roll) + 1
Next i
Debug.Print "[1] ""Uniform? "; Test4DiscreteUniformDistribution(Bins, 0.05); """"
End Sub
|
Generate a VB translation of this Python snippet without changing its computational steps. | islice(count(7), 0, None, 2)
| Option Explicit
Sub Main()
Dim Primes() As Long, n As Long, temp$
Dim t As Single
t = Timer
n = 133218295
Primes = ListPrimes(n)
Debug.Print "For N = " & Format(n, "#,##0") & ", execution time : " & _
Format(Timer - t, "0.000 s") & ", " & _
Format(UBound(Primes) + 1, "#,##0") & " primes numbers."
For n = 0 To 19
temp = temp & ", " & Primes(n)
Next
Debug.Print "First twenty primes : "; Mid(temp, 3)
n = 0: temp = vbNullString
Do While Primes(n) < 100
n = n + 1
Loop
Do While Primes(n) < 150
temp = temp & ", " & Primes(n)
n = n + 1
Loop
Debug.Print "Primes between 100 and 150 : " & Mid(temp, 3)
Dim ccount As Long
n = 0
Do While Primes(n) < 7700
n = n + 1
Loop
Do While Primes(n) < 8000
ccount = ccount + 1
n = n + 1
Loop
Debug.Print "Number of primes between 7,700 and 8,000 : " & ccount
n = 1
Do While n <= 100000
n = n * 10
Debug.Print "The " & n & "th prime: "; Format(Primes(n - 1), "#,##0")
Loop
Debug.Print "VBA has a limit in array
Debug.Print "With my computer, the limit for an array of Long is : 133 218 295"
Debug.Print "The last prime I could find is the : " & _
Format(UBound(Primes), "#,##0") & "th, Value : " & _
Format(Primes(UBound(Primes)), "#,##0")
End Sub
Function ListPrimes(MAX As Long) As Long()
Dim t() As Boolean, L() As Long, c As Long, s As Long, i As Long, j As Long
ReDim t(2 To MAX)
ReDim L(MAX \ 2)
s = Sqr(MAX)
For i = 3 To s Step 2
If t(i) = False Then
For j = i * i To MAX Step i
t(j) = True
Next
End If
Next i
L(0) = 2
For i = 3 To MAX Step 2
If t(i) = False Then
c = c + 1
L(c) = i
End If
Next i
ReDim Preserve L(c)
ListPrimes = L
End Function
|
Rewrite this program in VB while keeping its functionality equivalent to the Python version. | width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
myarray = [[0] * width for i in range(height)]
myarray[0][0] = 3.5
print (myarray[0][0])
| Module Program
Sub Main()
Console.WriteLine("Enter two space-delimited integers:")
Dim input = Console.ReadLine().Split()
Dim rows = Integer.Parse(input(0))
Dim cols = Integer.Parse(input(1))
Dim arr(rows - 1, cols - 1) As Integer
arr(0, 0) = 2
Console.WriteLine(arr(0, 0))
End Sub
End Module
|
Change the programming language of this snippet from Python to VB without modifying what it does. |
def chinese_remainder(n, a):
sum = 0
prod = reduce(lambda a, b: a*b, n)
for n_i, a_i in zip(n, a):
p = prod / n_i
sum += a_i * mul_inv(p, n_i) * p
return sum % prod
def mul_inv(a, b):
b0 = b
x0, x1 = 0, 1
if b == 1: return 1
while a > 1:
q = a / b
a, b = b, a%b
x0, x1 = x1 - q * x0, x0
if x1 < 0: x1 += b0
return x1
if __name__ == '__main__':
n = [3, 5, 7]
a = [2, 3, 2]
print chinese_remainder(n, a)
| Private Function chinese_remainder(n As Variant, a As Variant) As Variant
Dim p As Long, prod As Long, tot As Long
prod = 1: tot = 0
For i = 1 To UBound(n)
prod = prod * n(i)
Next i
Dim m As Variant
For i = 1 To UBound(n)
p = prod / n(i)
m = mul_inv(p, n(i))
If WorksheetFunction.IsText(m) Then
chinese_remainder = "fail"
Exit Function
End If
tot = tot + a(i) * m * p
Next i
chinese_remainder = tot Mod prod
End Function
Public Sub re()
Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])
Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])
Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])
Debug.Print chinese_remainder([{100,23}], [{19,0}])
End Sub
|
Maintain the same structure and functionality when rewriting this code in VB. |
def chinese_remainder(n, a):
sum = 0
prod = reduce(lambda a, b: a*b, n)
for n_i, a_i in zip(n, a):
p = prod / n_i
sum += a_i * mul_inv(p, n_i) * p
return sum % prod
def mul_inv(a, b):
b0 = b
x0, x1 = 0, 1
if b == 1: return 1
while a > 1:
q = a / b
a, b = b, a%b
x0, x1 = x1 - q * x0, x0
if x1 < 0: x1 += b0
return x1
if __name__ == '__main__':
n = [3, 5, 7]
a = [2, 3, 2]
print chinese_remainder(n, a)
| Private Function chinese_remainder(n As Variant, a As Variant) As Variant
Dim p As Long, prod As Long, tot As Long
prod = 1: tot = 0
For i = 1 To UBound(n)
prod = prod * n(i)
Next i
Dim m As Variant
For i = 1 To UBound(n)
p = prod / n(i)
m = mul_inv(p, n(i))
If WorksheetFunction.IsText(m) Then
chinese_remainder = "fail"
Exit Function
End If
tot = tot + a(i) * m * p
Next i
chinese_remainder = tot Mod prod
End Function
Public Sub re()
Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}])
Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}])
Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}])
Debug.Print chinese_remainder([{100,23}], [{19,0}])
End Sub
|
Please provide an equivalent version of this Python code in VB. | def calcPi():
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
while True:
if 4*q+r-t < n*t:
yield n
nr = 10*(r-n*t)
n = ((10*(3*q+r))//t)-10*n
q *= 10
r = nr
else:
nr = (2*q+r)*l
nn = (q*(7*k)+2+(r*l))//(t*l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
import sys
pi_digits = calcPi()
i = 0
for d in pi_digits:
sys.stdout.write(str(d))
i += 1
if i == 40: print(""); i = 0
| Option Explicit
Sub Main()
Const VECSIZE As Long = 3350
Const BUFSIZE As Long = 201
Dim buffer(1 To BUFSIZE) As Long
Dim vect(1 To VECSIZE) As Long
Dim more As Long, karray As Long, num As Long, k As Long, l As Long, n As Long
For n = 1 To VECSIZE
vect(n) = 2
Next n
For n = 1 To BUFSIZE
karray = 0
For l = VECSIZE To 1 Step -1
num = 100000 * vect(l) + karray * l
karray = num \ (2 * l - 1)
vect(l) = num - karray * (2 * l - 1)
Next l
k = karray \ 100000
buffer(n) = more + k
more = karray - k * 100000
Next n
Debug.Print CStr(buffer(1));
Debug.Print "."
l = 0
For n = 2 To BUFSIZE
Debug.Print Format$(buffer(n), "00000");
l = l + 1
If l = 10 Then
l = 0
Debug.Print
End If
Next n
End Sub
|
Convert this Python snippet to VB and keep its semantics consistent. | def q(n):
if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
try:
return q.seq[n]
except IndexError:
ans = q(n - q(n - 1)) + q(n - q(n - 2))
q.seq.append(ans)
return ans
q.seq = [None, 1, 1]
if __name__ == '__main__':
first10 = [q(i) for i in range(1,11)]
assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], "Q() value error(s)"
print("Q(n) for n = [1..10] is:", ', '.join(str(i) for i in first10))
assert q(1000) == 502, "Q(1000) value error"
print("Q(1000) =", q(1000))
| Public Q(100000) As Long
Public Sub HofstadterQ()
Dim n As Long, smaller As Long
Q(1) = 1
Q(2) = 1
For n = 3 To 100000
Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))
If Q(n) < Q(n - 1) Then smaller = smaller + 1
Next n
Debug.Print "First ten terms:"
For i = 1 To 10
Debug.Print Q(i);
Next i
Debug.print
Debug.Print "The 1000th term is:"; Q(1000)
Debug.Print "Number of times smaller:"; smaller
End Sub
|
Generate an equivalent VB version of this Python code. | def q(n):
if n < 1 or type(n) != int: raise ValueError("n must be an int >= 1")
try:
return q.seq[n]
except IndexError:
ans = q(n - q(n - 1)) + q(n - q(n - 2))
q.seq.append(ans)
return ans
q.seq = [None, 1, 1]
if __name__ == '__main__':
first10 = [q(i) for i in range(1,11)]
assert first10 == [1, 1, 2, 3, 3, 4, 5, 5, 6, 6], "Q() value error(s)"
print("Q(n) for n = [1..10] is:", ', '.join(str(i) for i in first10))
assert q(1000) == 502, "Q(1000) value error"
print("Q(1000) =", q(1000))
| Public Q(100000) As Long
Public Sub HofstadterQ()
Dim n As Long, smaller As Long
Q(1) = 1
Q(2) = 1
For n = 3 To 100000
Q(n) = Q(n - Q(n - 1)) + Q(n - Q(n - 2))
If Q(n) < Q(n - 1) Then smaller = smaller + 1
Next n
Debug.Print "First ten terms:"
For i = 1 To 10
Debug.Print Q(i);
Next i
Debug.print
Debug.Print "The 1000th term is:"; Q(1000)
Debug.Print "Number of times smaller:"; smaller
End Sub
|
Keep all operations the same but rewrite the snippet in VB. | >>> Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
>>> fac = lambda f: lambda n: (1 if n<2 else n*f(n-1))
>>> [ Y(fac)(i) for i in range(10) ]
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
>>> fib = lambda f: lambda n: 0 if n == 0 else (1 if n == 1 else f(n-1) + f(n-2))
>>> [ Y(fib)(i) for i in range(10) ]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
| Private Function call_fn(f As String, n As Long) As Long
call_fn = Application.Run(f, f, n)
End Function
Private Function Y(f As String) As String
Y = f
End Function
Private Function fac(self As String, n As Long) As Long
If n > 1 Then
fac = n * call_fn(self, n - 1)
Else
fac = 1
End If
End Function
Private Function fib(self As String, n As Long) As Long
If n > 1 Then
fib = call_fn(self, n - 1) + call_fn(self, n - 2)
Else
fib = n
End If
End Function
Private Sub test(name As String)
Dim f As String: f = Y(name)
Dim i As Long
Debug.Print name
For i = 1 To 10
Debug.Print call_fn(f, i);
Next i
Debug.Print
End Sub
Public Sub main()
test "fac"
test "fib"
End Sub
|
Rewrite this program in VB while keeping its functionality equivalent to the Python version. | def addsub(x, y):
return x + y, x - y
| Type Contact
Name As String
firstname As String
Age As Byte
End Type
Function SetContact(N As String, Fn As String, A As Byte) As Contact
SetContact.Name = N
SetContact.firstname = Fn
SetContact.Age = A
End Function
Sub Test_SetContact()
Dim Cont As Contact
Cont = SetContact("SMITH", "John", 23)
Debug.Print Cont.Name & " " & Cont.firstname & ", " & Cont.Age & " years old."
End Sub
|
Maintain the same structure and functionality when rewriting this code in VB. | def van_eck():
n, seen, val = 0, {}, 0
while True:
yield val
last = {val: n}
val = n - seen.get(val, n)
seen.update(last)
n += 1
if __name__ == '__main__':
print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10)))
print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
| Imports System.Linq
Module Module1
Dim h() As Integer
Sub sho(i As Integer)
Console.WriteLine(String.Join(" ", h.Skip(i).Take(10)))
End Sub
Sub Main()
Dim a, b, c, d, f, g As Integer : g = 1000
h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g
f = h(b) : For d = a To 0 Step -1
If f = h(d) Then h(c) = b - d: Exit For
Next : a = b : b = c : Next : sho(0) : sho(990)
End Sub
End Module
|
Rewrite this program in VB while keeping its functionality equivalent to the Python version. | def van_eck():
n, seen, val = 0, {}, 0
while True:
yield val
last = {val: n}
val = n - seen.get(val, n)
seen.update(last)
n += 1
if __name__ == '__main__':
print("Van Eck: first 10 terms: ", list(islice(van_eck(), 10)))
print("Van Eck: terms 991 - 1000:", list(islice(van_eck(), 1000))[-10:])
| Imports System.Linq
Module Module1
Dim h() As Integer
Sub sho(i As Integer)
Console.WriteLine(String.Join(" ", h.Skip(i).Take(10)))
End Sub
Sub Main()
Dim a, b, c, d, f, g As Integer : g = 1000
h = new Integer(g){} : a = 0 : b = 1 : For c = 2 To g
f = h(b) : For d = a To 0 Step -1
If f = h(d) Then h(c) = b - d: Exit For
Next : a = b : b = c : Next : sho(0) : sho(990)
End Sub
End Module
|
Convert this Python snippet to VB and keep its semantics consistent. |
from __future__ import division, print_function
import random, ast, re
import sys
if sys.version_info[0] < 3: input = raw_input
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
print ("New digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
if __name__ == '__main__': main()
| Sub Rosetta_24game()
Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer
Dim stUserExpression As String
Dim stFailMessage As String, stFailDigits As String
Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean
Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant
GenerateNewDigits:
For i = 1 To 4
Digit(i) = [randbetween(1,9)]
Next i
GetUserExpression:
bValidExpression = True
stFailMessage = ""
stFailDigits = ""
stUserExpression = InputBox("Enter a mathematical expression which results in 24, using the following digits: " & _
Digit(1) & ", " & Digit(2) & ", " & Digit(3) & " and " & Digit(4), "Rosetta Code | 24 Game")
bValidDigits = True
stFailDigits = ""
For i = 1 To 4
If InStr(stUserExpression, Digit(i)) = 0 Then
bValidDigits = False
stFailDigits = stFailDigits & " " & Digit(i)
End If
Next i
If bValidDigits = False Then
bValidExpression = False
stFailMessage = "Your expression excluded the following required digits: " & stFailDigits & vbCr & vbCr
End If
bValidDigits = True
stFailDigits = ""
For i = 1 To Len(stUserExpression)
If InStr("0123456789+-*/()", Mid(stUserExpression, i, 1)) = 0 Then
bValidDigits = False
stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1)
End If
Next i
If bValidDigits = False Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained invalid characters:" & stFailDigits & vbCr & vbCr
End If
bValidDigits = True
stFailDigits = ""
iDigitCount = 0
For i = 1 To Len(stUserExpression)
If Not InStr("0123456789", Mid(stUserExpression, i, 1)) = 0 Then
iDigitCount = iDigitCount + 1
If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then
bValidDigits = False
stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1)
End If
End If
Next i
If iDigitCount > 4 Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained more than 4 digits" & vbCr & vbCr
End If
If iDigitCount < 4 Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained less than 4 digits" & vbCr & vbCr
End If
If bValidDigits = False Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained invalid digits:" & stFailDigits & vbCr & vbCr
End If
bValidDigits = True
stFailDigits = ""
For i = 11 To 99
If Not InStr(stUserExpression, i) = 0 Then
bValidDigits = False
stFailDigits = stFailDigits & " " & i
End If
Next i
If bValidDigits = False Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained invalid numbers:" & stFailDigits & vbCr & vbCr
End If
On Error GoTo EvalFail
vResult = Evaluate(stUserExpression)
If Not vResult = 24 Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression did not result in 24. It returned: " & vResult
End If
If bValidExpression = False Then
vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & "Would you like to try again?", vbCritical + vbRetryCancel, "Rosetta Code | 24 Game | FAILED")
If vTryAgain = vbRetry Then
vSameDigits = MsgBox("Do you want to use the same numbers?", vbQuestion + vbYesNo, "Rosetta Code | 24 Game | RETRY")
If vSameDigits = vbYes Then
GoTo GetUserExpression
Else
GoTo GenerateNewDigits
End If
End If
Else
vTryAgain = MsgBox("You entered: " & stUserExpression & vbCr & vbCr & "which resulted in: " & vResult, _
vbInformation + vbRetryCancel, "Rosetta Code | 24 Game | SUCCESS")
If vTryAgain = vbRetry Then
GoTo GenerateNewDigits
End If
End If
Exit Sub
EvalFail:
bValidExpression = False
vResult = Err.Description
Resume
End Sub
|
Change the following Python code into VB without altering its purpose. |
from __future__ import division, print_function
import random, ast, re
import sys
if sys.version_info[0] < 3: input = raw_input
def choose4():
'four random digits >0 as characters'
return [str(random.randint(1,9)) for i in range(4)]
def welcome(digits):
print (__doc__)
print ("Your four digits: " + ' '.join(digits))
def check(answer, digits):
allowed = set('() +-*/\t'+''.join(digits))
ok = all(ch in allowed for ch in answer) and \
all(digits.count(dig) == answer.count(dig) for dig in set(digits)) \
and not re.search('\d\d', answer)
if ok:
try:
ast.parse(answer)
except:
ok = False
return ok
def main():
digits = choose4()
welcome(digits)
trial = 0
answer = ''
chk = ans = False
while not (chk and ans == 24):
trial +=1
answer = input("Expression %i: " % trial)
chk = check(answer, digits)
if answer.lower() == 'q':
break
if answer == '!':
digits = choose4()
print ("New digits:", ' '.join(digits))
continue
if not chk:
print ("The input '%s' was wonky!" % answer)
else:
ans = eval(answer)
print (" = ", ans)
if ans == 24:
print ("Thats right!")
print ("Thank you and goodbye")
if __name__ == '__main__': main()
| Sub Rosetta_24game()
Dim Digit(4) As Integer, i As Integer, iDigitCount As Integer
Dim stUserExpression As String
Dim stFailMessage As String, stFailDigits As String
Dim bValidExpression As Boolean, bValidDigits As Boolean, bValidChars As Boolean
Dim vResult As Variant, vTryAgain As Variant, vSameDigits As Variant
GenerateNewDigits:
For i = 1 To 4
Digit(i) = [randbetween(1,9)]
Next i
GetUserExpression:
bValidExpression = True
stFailMessage = ""
stFailDigits = ""
stUserExpression = InputBox("Enter a mathematical expression which results in 24, using the following digits: " & _
Digit(1) & ", " & Digit(2) & ", " & Digit(3) & " and " & Digit(4), "Rosetta Code | 24 Game")
bValidDigits = True
stFailDigits = ""
For i = 1 To 4
If InStr(stUserExpression, Digit(i)) = 0 Then
bValidDigits = False
stFailDigits = stFailDigits & " " & Digit(i)
End If
Next i
If bValidDigits = False Then
bValidExpression = False
stFailMessage = "Your expression excluded the following required digits: " & stFailDigits & vbCr & vbCr
End If
bValidDigits = True
stFailDigits = ""
For i = 1 To Len(stUserExpression)
If InStr("0123456789+-*/()", Mid(stUserExpression, i, 1)) = 0 Then
bValidDigits = False
stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1)
End If
Next i
If bValidDigits = False Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained invalid characters:" & stFailDigits & vbCr & vbCr
End If
bValidDigits = True
stFailDigits = ""
iDigitCount = 0
For i = 1 To Len(stUserExpression)
If Not InStr("0123456789", Mid(stUserExpression, i, 1)) = 0 Then
iDigitCount = iDigitCount + 1
If IsError(Application.Match(--(Mid(stUserExpression, i, 1)), Digit, False)) Then
bValidDigits = False
stFailDigits = stFailDigits & " " & Mid(stUserExpression, i, 1)
End If
End If
Next i
If iDigitCount > 4 Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained more than 4 digits" & vbCr & vbCr
End If
If iDigitCount < 4 Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained less than 4 digits" & vbCr & vbCr
End If
If bValidDigits = False Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained invalid digits:" & stFailDigits & vbCr & vbCr
End If
bValidDigits = True
stFailDigits = ""
For i = 11 To 99
If Not InStr(stUserExpression, i) = 0 Then
bValidDigits = False
stFailDigits = stFailDigits & " " & i
End If
Next i
If bValidDigits = False Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression contained invalid numbers:" & stFailDigits & vbCr & vbCr
End If
On Error GoTo EvalFail
vResult = Evaluate(stUserExpression)
If Not vResult = 24 Then
bValidExpression = False
stFailMessage = stFailMessage & "Your expression did not result in 24. It returned: " & vResult
End If
If bValidExpression = False Then
vTryAgain = MsgBox(stFailMessage & vbCr & vbCr & "Would you like to try again?", vbCritical + vbRetryCancel, "Rosetta Code | 24 Game | FAILED")
If vTryAgain = vbRetry Then
vSameDigits = MsgBox("Do you want to use the same numbers?", vbQuestion + vbYesNo, "Rosetta Code | 24 Game | RETRY")
If vSameDigits = vbYes Then
GoTo GetUserExpression
Else
GoTo GenerateNewDigits
End If
End If
Else
vTryAgain = MsgBox("You entered: " & stUserExpression & vbCr & vbCr & "which resulted in: " & vResult, _
vbInformation + vbRetryCancel, "Rosetta Code | 24 Game | SUCCESS")
If vTryAgain = vbRetry Then
GoTo GenerateNewDigits
End If
End If
Exit Sub
EvalFail:
bValidExpression = False
vResult = Err.Description
Resume
End Sub
|
Transform the following Python implementation into VB, maintaining the same output and logic. | for i in range(1, 11):
if i % 5 == 0:
print(i)
continue
print(i, end=', ')
| For i = 1 To 10
Console.Write(i)
If i Mod 5 = 0 Then
Console.WriteLine()
Else
Console.Write(", ")
End If
Next
|
Convert the following code from Python to VB, ensuring the logic remains intact. | from pprint import pprint
def matrixMul(A, B):
TB = zip(*B)
return [[sum(ea*eb for ea,eb in zip(a,b)) for b in TB] for a in A]
def pivotize(m):
n = len(m)
ID = [[float(i == j) for i in xrange(n)] for j in xrange(n)]
for j in xrange(n):
row = max(xrange(j, n), key=lambda i: abs(m[i][j]))
if j != row:
ID[j], ID[row] = ID[row], ID[j]
return ID
def lu(A):
n = len(A)
L = [[0.0] * n for i in xrange(n)]
U = [[0.0] * n for i in xrange(n)]
P = pivotize(A)
A2 = matrixMul(P, A)
for j in xrange(n):
L[j][j] = 1.0
for i in xrange(j+1):
s1 = sum(U[k][j] * L[i][k] for k in xrange(i))
U[i][j] = A2[i][j] - s1
for i in xrange(j, n):
s2 = sum(U[k][j] * L[i][k] for k in xrange(j))
L[i][j] = (A2[i][j] - s2) / U[j][j]
return (L, U, P)
a = [[1, 3, 5], [2, 4, 7], [1, 1, 0]]
for part in lu(a):
pprint(part, width=19)
print
print
b = [[11,9,24,2],[1,5,2,6],[3,17,18,1],[2,5,7,1]]
for part in lu(b):
pprint(part)
print
| Option Base 1
Private Function pivotize(m As Variant) As Variant
Dim n As Integer: n = UBound(m)
Dim im() As Double
ReDim im(n, n)
For i = 1 To n
For j = 1 To n
im(i, j) = 0
Next j
im(i, i) = 1
Next i
For i = 1 To n
mx = Abs(m(i, i))
row_ = i
For j = i To n
If Abs(m(j, i)) > mx Then
mx = Abs(m(j, i))
row_ = j
End If
Next j
If i <> Row Then
For j = 1 To n
tmp = im(i, j)
im(i, j) = im(row_, j)
im(row_, j) = tmp
Next j
End If
Next i
pivotize = im
End Function
Private Function lu(a As Variant) As Variant
Dim n As Integer: n = UBound(a)
Dim l() As Double
ReDim l(n, n)
For i = 1 To n
For j = 1 To n
l(i, j) = 0
Next j
Next i
u = l
p = pivotize(a)
a2 = WorksheetFunction.MMult(p, a)
For j = 1 To n
l(j, j) = 1#
For i = 1 To j
sum1 = 0#
For k = 1 To i
sum1 = sum1 + u(k, j) * l(i, k)
Next k
u(i, j) = a2(i, j) - sum1
Next i
For i = j + 1 To n
sum2 = 0#
For k = 1 To j
sum2 = sum2 + u(k, j) * l(i, k)
Next k
l(i, j) = (a2(i, j) - sum2) / u(j, j)
Next i
Next j
Dim res(4) As Variant
res(1) = a
res(2) = l
res(3) = u
res(4) = p
lu = res
End Function
Public Sub main()
a = [{1, 3, 5; 2, 4, 7; 1, 1, 0}]
Debug.Print "== a,l,u,p: =="
result = lu(a)
For i = 1 To 4
For j = 1 To UBound(result(1))
For k = 1 To UBound(result(1), 2)
Debug.Print result(i)(j, k),
Next k
Debug.Print
Next j
Debug.Print
Next i
a = [{11, 9,24, 2; 1, 5, 2, 6; 3,17,18, 1; 2, 5, 7, 1}]
Debug.Print "== a,l,u,p: =="
result = lu(a)
For i = 1 To 4
For j = 1 To UBound(result(1))
For k = 1 To UBound(result(1), 2)
Debug.Print Format(result(i)(j, k), "0.#####"),
Next k
Debug.Print
Next j
Debug.Print
Next i
End Sub
|
Produce a language-to-language conversion: from Python to VB, same semantics. | def genfizzbuzz(factorwords, numbers):
factorwords.sort(key=lambda factor_and_word: factor_and_word[0])
lines = []
for num in numbers:
words = ''.join(word for factor, word in factorwords if (num % factor) == 0)
lines.append(words if words else str(num))
return '\n'.join(lines)
if __name__ == '__main__':
print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
| Option Explicit
Private Type Choice
Number As Integer
Name As String
End Type
Private MaxNumber As Integer
Sub Main()
Dim U(1 To 3) As Choice, i As Integer, j As Integer, t$
MaxNumber = Application.InputBox("Enter the max number : ", "Integer please", Type:=1)
For i = 1 To 3
U(i) = UserChoice
Next
For i = 1 To MaxNumber
t = vbNullString
For j = 1 To 3
If i Mod U(j).Number = 0 Then t = t & U(j).Name
Next
Debug.Print IIf(t = vbNullString, i, t)
Next i
End Sub
Private Function UserChoice() As Choice
Dim ok As Boolean
Do While Not ok
UserChoice.Number = Application.InputBox("Enter the factors to be calculated : ", "Integer please", Type:=1)
UserChoice.Name = InputBox("Enter the corresponding word : ")
If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True
Loop
End Function
|
Translate this program into VB but keep the logic exactly as in Python. | def genfizzbuzz(factorwords, numbers):
factorwords.sort(key=lambda factor_and_word: factor_and_word[0])
lines = []
for num in numbers:
words = ''.join(word for factor, word in factorwords if (num % factor) == 0)
lines.append(words if words else str(num))
return '\n'.join(lines)
if __name__ == '__main__':
print(genfizzbuzz([(5, 'Buzz'), (3, 'Fizz'), (7, 'Baxx')], range(1, 21)))
| Option Explicit
Private Type Choice
Number As Integer
Name As String
End Type
Private MaxNumber As Integer
Sub Main()
Dim U(1 To 3) As Choice, i As Integer, j As Integer, t$
MaxNumber = Application.InputBox("Enter the max number : ", "Integer please", Type:=1)
For i = 1 To 3
U(i) = UserChoice
Next
For i = 1 To MaxNumber
t = vbNullString
For j = 1 To 3
If i Mod U(j).Number = 0 Then t = t & U(j).Name
Next
Debug.Print IIf(t = vbNullString, i, t)
Next i
End Sub
Private Function UserChoice() As Choice
Dim ok As Boolean
Do While Not ok
UserChoice.Number = Application.InputBox("Enter the factors to be calculated : ", "Integer please", Type:=1)
UserChoice.Name = InputBox("Enter the corresponding word : ")
If StrPtr(UserChoice.Name) <> 0 And UserChoice.Number < MaxNumber Then ok = True
Loop
End Function
|
Transform the following Python implementation into VB, maintaining the same output and logic. | with open('xxx.txt') as f:
for i, line in enumerate(f):
if i == 6:
break
else:
print('Not 7 lines in file')
line = None
| Function read_line(filepath,n)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(filepath,1)
arrLines = Split(objFile.ReadAll,vbCrLf)
If UBound(arrLines) >= n-1 Then
If arrLines(n-1) <> "" Then
read_line = arrLines(n-1)
Else
read_line = "Line " & n & " is null."
End If
Else
read_line = "Line " & n & " does not exist."
End If
objFile.Close
Set objFSO = Nothing
End Function
WScript.Echo read_line("c:\temp\input.txt",7)
|
Can you help me rewrite this code in VB instead of Python, keeping it the same logically? | with open('xxx.txt') as f:
for i, line in enumerate(f):
if i == 6:
break
else:
print('Not 7 lines in file')
line = None
| Function read_line(filepath,n)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(filepath,1)
arrLines = Split(objFile.ReadAll,vbCrLf)
If UBound(arrLines) >= n-1 Then
If arrLines(n-1) <> "" Then
read_line = arrLines(n-1)
Else
read_line = "Line " & n & " is null."
End If
Else
read_line = "Line " & n & " does not exist."
End If
objFile.Close
Set objFSO = Nothing
End Function
WScript.Echo read_line("c:\temp\input.txt",7)
|
Convert the following code from Python to VB, ensuring the logic remains intact. | def tobits(n, _group=8, _sep='_', _pad=False):
'Express n as binary bits with separator'
bits = '{0:b}'.format(n)[::-1]
if _pad:
bits = '{0:0{1}b}'.format(n,
((_group+len(bits)-1)//_group)*_group)[::-1]
answer = _sep.join(bits[i:i+_group]
for i in range(0, len(bits), _group))[::-1]
answer = '0'*(len(_sep)-1) + answer
else:
answer = _sep.join(bits[i:i+_group]
for i in range(0, len(bits), _group))[::-1]
return answer
def tovlq(n):
return tobits(n, _group=7, _sep='1_', _pad=True)
def toint(vlq):
return int(''.join(vlq.split('_1')), 2)
def vlqsend(vlq):
for i, byte in enumerate(vlq.split('_')[::-1]):
print('Sent byte {0:3}: {1:
| Module Module1
Function ToVlq(v As ULong) As ULong
Dim array(8) As Byte
Dim buffer = ToVlqCollection(v).SkipWhile(Function(b) b = 0).Reverse().ToArray
buffer.CopyTo(array, 0)
Return BitConverter.ToUInt64(array, 0)
End Function
Function FromVlq(v As ULong) As ULong
Dim collection = BitConverter.GetBytes(v).Reverse()
Return FromVlqCollection(collection)
End Function
Iterator Function ToVlqCollection(v As ULong) As IEnumerable(Of Byte)
If v > Math.Pow(2, 56) Then
Throw New OverflowException("Integer exceeds max value.")
End If
Dim index = 7
Dim significantBitReached = False
Dim mask = &H7FUL << (index * 7)
While index >= 0
Dim buffer = mask And v
If buffer > 0 OrElse significantBitReached Then
significantBitReached = True
buffer >>= index * 7
If index > 0 Then
buffer = buffer Or &H80
End If
Yield buffer
End If
mask >>= 7
index -= 1
End While
End Function
Function FromVlqCollection(vlq As IEnumerable(Of Byte)) As ULong
Dim v = 0UL
Dim significantBitReached = False
Using enumerator = vlq.GetEnumerator
Dim index = 0
While enumerator.MoveNext
Dim buffer = enumerator.Current
If buffer > 0 OrElse significantBitReached Then
significantBitReached = True
v <<= 7
v = v Or (buffer And &H7FUL)
End If
index += 1
If index = 8 OrElse (significantBitReached AndAlso (buffer And &H80) <> &H80) Then
Exit While
End If
End While
End Using
Return v
End Function
Sub Main()
Dim values = {&H7FUL << 7 * 7, &H80, &H2000, &H3FFF, &H4000, &H200000, &H1FFFFF}
For Each original In values
Console.WriteLine("Original: 0x{0:X}", original)
REM collection
Dim seq = ToVlqCollection(original)
Console.WriteLine("Sequence: 0x{0}", seq.Select(Function(b) b.ToString("X2")).Aggregate(Function(a, b) String.Concat(a, b)))
Dim decoded = FromVlqCollection(seq)
Console.WriteLine("Decoded: 0x{0:X}", decoded)
REM ints
Dim encoded = ToVlq(original)
Console.WriteLine("Encoded: 0x{0:X}", encoded)
decoded = FromVlq(encoded)
Console.WriteLine("Decoded: 0x{0:X}", decoded)
Console.WriteLine()
Next
End Sub
End Module
|
Write a version of this Python function in VB with identical behavior. | s = "alphaBETA"
print s.upper()
print s.lower()
print s.swapcase()
print "fOo bAR".capitalize()
print "fOo bAR".title()
import string
print string.capwords("fOo bAR")
| Sub Main()
Const TESTSTRING As String = "alphaBETA"
Debug.Print "initial = " _
& TESTSTRING
Debug.Print "uppercase = " _
& UCase(TESTSTRING)
Debug.Print "lowercase = " _
& LCase(TESTSTRING)
Debug.Print "first letter capitalized = " _
& StrConv(TESTSTRING, vbProperCase)
Debug.Print "length (in characters) = " _
& CStr(Len(TESTSTRING))
Debug.Print "length (in bytes) = " _
& CStr(LenB(TESTSTRING))
Debug.Print "reversed = " _
& StrReverse(TESTSTRING)
Debug.Print "first position of letter A (case-sensitive) = " _
& InStr(1, TESTSTRING, "A", vbBinaryCompare)
Debug.Print "first position of letter A (case-insensitive) = " _
& InStr(1, TESTSTRING, "A", vbTextCompare)
Debug.Print "concatenated with
& TESTSTRING & "123"
End Sub
|
Port the provided Python code into VB while preserving the original functionality. | import fileinput
import sys
nodata = 0;
nodata_max=-1;
nodata_maxline=[];
tot_file = 0
num_file = 0
infiles = sys.argv[1:]
for line in fileinput.input():
tot_line=0;
num_line=0;
field = line.split()
date = field[0]
data = [float(f) for f in field[1::2]]
flags = [int(f) for f in field[2::2]]
for datum, flag in zip(data, flags):
if flag<1:
nodata += 1
else:
if nodata_max==nodata and nodata>0:
nodata_maxline.append(date)
if nodata_max<nodata and nodata>0:
nodata_max=nodata
nodata_maxline=[date]
nodata=0;
tot_line += datum
num_line += 1
tot_file += tot_line
num_file += num_line
print "Line: %11s Reject: %2i Accept: %2i Line_tot: %10.3f Line_avg: %10.3f" % (
date,
len(data) -num_line,
num_line, tot_line,
tot_line/num_line if (num_line>0) else 0)
print ""
print "File(s) = %s" % (", ".join(infiles),)
print "Total = %10.3f" % (tot_file,)
print "Readings = %6i" % (num_file,)
print "Average = %10.3f" % (tot_file / num_file,)
print "\nMaximum run(s) of %i consecutive false readings ends at line starting with date(s): %s" % (
nodata_max, ", ".join(nodata_maxline))
| Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(objFSO.GetParentFolderName(WScript.ScriptFullName) &_
"\data.txt",1)
bad_readings_total = 0
good_readings_total = 0
data_gap = 0
start_date = ""
end_date = ""
tmp_datax_gap = 0
tmp_start_date = ""
Do Until objFile.AtEndOfStream
bad_readings = 0
good_readings = 0
line_total = 0
line = objFile.ReadLine
token = Split(line,vbTab)
n = 1
Do While n <= UBound(token)
If n + 1 <= UBound(token) Then
If CInt(token(n+1)) < 1 Then
bad_readings = bad_readings + 1
bad_readings_total = bad_readings_total + 1
If tmp_start_date = "" Then
tmp_start_date = token(0)
End If
tmp_data_gap = tmp_data_gap + 1
Else
good_readings = good_readings + 1
line_total = line_total + CInt(token(n))
good_readings_total = good_readings_total + 1
If (tmp_start_date <> "") And (tmp_data_gap > data_gap) Then
start_date = tmp_start_date
end_date = token(0)
data_gap = tmp_data_gap
tmp_start_date = ""
tmp_data_gap = 0
Else
tmp_start_date = ""
tmp_data_gap = 0
End If
End If
End If
n = n + 2
Loop
line_avg = line_total/good_readings
WScript.StdOut.Write "Date: " & token(0) & vbTab &_
"Bad Reads: " & bad_readings & vbTab &_
"Good Reads: " & good_readings & vbTab &_
"Line Total: " & FormatNumber(line_total,3) & vbTab &_
"Line Avg: " & FormatNumber(line_avg,3)
WScript.StdOut.WriteLine
Loop
WScript.StdOut.WriteLine
WScript.StdOut.Write "Maximum run of " & data_gap &_
" consecutive bad readings from " & start_date & " to " &_
end_date & "."
WScript.StdOut.WriteLine
objFile.Close
Set objFSO = Nothing
|
Maintain the same structure and functionality when rewriting this code in VB. | >>> import hashlib
>>>
>>> tests = (
(b"", 'd41d8cd98f00b204e9800998ecf8427e'),
(b"a", '0cc175b9c0f1b6a831c399e269772661'),
(b"abc", '900150983cd24fb0d6963f7d28e17f72'),
(b"message digest", 'f96b697d7cb7938d525a2f31aaf161d0'),
(b"abcdefghijklmnopqrstuvwxyz", 'c3fcd3d76192e4007dfb496cca67e13b'),
(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", 'd174ab98d277d9f5a5611c2c9f419d9f'),
(b"12345678901234567890123456789012345678901234567890123456789012345678901234567890", '57edf4a22be3c955ac49da2e2107b67a') )
>>> for text, golden in tests: assert hashlib.md5(text).hexdigest() == golden
>>>
| Imports System.Security.Cryptography
Imports System.Text
Module MD5hash
Sub Main(args As String())
Console.WriteLine(GetMD5("Visual Basic .Net"))
End Sub
Private Function GetMD5(plainText As String) As String
Dim hash As String = ""
Using hashObject As MD5 = MD5.Create()
Dim ptBytes As Byte() = hashObject.ComputeHash(Encoding.UTF8.GetBytes(plainText))
Dim hashBuilder As New StringBuilder
For i As Integer = 0 To ptBytes.Length - 1
hashBuilder.Append(ptBytes(i).ToString("X2"))
Next
hash = hashBuilder.ToString
End Using
Return hash
End Function
End Module
|
Generate an equivalent VB version of this Python code. | from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new = pdsum(s[-1])
if new in s:
if s[0] == new:
if slen == 1:
return 'perfect', s
elif slen == 2:
return 'amicable', s
else:
return 'sociable of length %i' % slen, s
elif s[-1] == new:
return 'aspiring', s
else:
return 'cyclic back to %i' % new, s
elif new == 0:
return 'terminating', s + [0]
else:
s.append(new)
slen += 1
else:
return 'non-terminating', s
if __name__ == '__main__':
for n in range(1, 11):
print('%s: %r' % aliquot(n))
print()
for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]:
print('%s: %r' % aliquot(n))
| Option Explicit
Private Type Aliquot
Sequence() As Double
Classification As String
End Type
Sub Main()
Dim result As Aliquot, i As Long, j As Double, temp As String
For j = 1 To 10
result = Aliq(j)
temp = vbNullString
For i = 0 To UBound(result.Sequence)
temp = temp & result.Sequence(i) & ", "
Next i
Debug.Print "Aliquot seq of " & j & " : " & result.Classification & " " & Left(temp, Len(temp) - 2)
Next j
Dim a
a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)
For j = LBound(a) To UBound(a)
result = Aliq(CDbl(a(j)))
temp = vbNullString
For i = 0 To UBound(result.Sequence)
temp = temp & result.Sequence(i) & ", "
Next i
Debug.Print "Aliquot seq of " & a(j) & " : " & result.Classification & " " & Left(temp, Len(temp) - 2)
Next
End Sub
Private Function Aliq(Nb As Double) As Aliquot
Dim s() As Double, i As Long, temp, j As Long, cpt As Long
temp = Array("non-terminating", "Terminate", "Perfect", "Amicable", "Sociable", "Aspiring", "Cyclic")
ReDim s(0)
s(0) = Nb
For i = 1 To 15
cpt = cpt + 1
ReDim Preserve s(cpt)
s(i) = SumPDiv(s(i - 1))
If s(i) > 140737488355328# Then Exit For
If s(i) = 0 Then j = 1
If s(1) = s(0) Then j = 2
If s(i) = s(0) And i > 1 And i <> 2 Then j = 4
If s(i) = s(i - 1) And i > 1 Then j = 5
If i >= 2 Then
If s(2) = s(0) Then j = 3
If s(i) = s(i - 2) And i <> 2 Then j = 6
End If
If j > 0 Then Exit For
Next
Aliq.Classification = temp(j)
Aliq.Sequence = s
End Function
Private Function SumPDiv(n As Double) As Double
Dim j As Long, t As Long
If n > 1 Then
For j = 1 To n \ 2
If n Mod j = 0 Then t = t + j
Next
End If
SumPDiv = t
End Function
|
Convert this Python snippet to VB and keep its semantics consistent. | from proper_divisors import proper_divs
from functools import lru_cache
@lru_cache()
def pdsum(n):
return sum(proper_divs(n))
def aliquot(n, maxlen=16, maxterm=2**47):
if n == 0:
return 'terminating', [0]
s, slen, new = [n], 1, n
while slen <= maxlen and new < maxterm:
new = pdsum(s[-1])
if new in s:
if s[0] == new:
if slen == 1:
return 'perfect', s
elif slen == 2:
return 'amicable', s
else:
return 'sociable of length %i' % slen, s
elif s[-1] == new:
return 'aspiring', s
else:
return 'cyclic back to %i' % new, s
elif new == 0:
return 'terminating', s + [0]
else:
s.append(new)
slen += 1
else:
return 'non-terminating', s
if __name__ == '__main__':
for n in range(1, 11):
print('%s: %r' % aliquot(n))
print()
for n in [11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, 15355717786080]:
print('%s: %r' % aliquot(n))
| Option Explicit
Private Type Aliquot
Sequence() As Double
Classification As String
End Type
Sub Main()
Dim result As Aliquot, i As Long, j As Double, temp As String
For j = 1 To 10
result = Aliq(j)
temp = vbNullString
For i = 0 To UBound(result.Sequence)
temp = temp & result.Sequence(i) & ", "
Next i
Debug.Print "Aliquot seq of " & j & " : " & result.Classification & " " & Left(temp, Len(temp) - 2)
Next j
Dim a
a = Array(11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488)
For j = LBound(a) To UBound(a)
result = Aliq(CDbl(a(j)))
temp = vbNullString
For i = 0 To UBound(result.Sequence)
temp = temp & result.Sequence(i) & ", "
Next i
Debug.Print "Aliquot seq of " & a(j) & " : " & result.Classification & " " & Left(temp, Len(temp) - 2)
Next
End Sub
Private Function Aliq(Nb As Double) As Aliquot
Dim s() As Double, i As Long, temp, j As Long, cpt As Long
temp = Array("non-terminating", "Terminate", "Perfect", "Amicable", "Sociable", "Aspiring", "Cyclic")
ReDim s(0)
s(0) = Nb
For i = 1 To 15
cpt = cpt + 1
ReDim Preserve s(cpt)
s(i) = SumPDiv(s(i - 1))
If s(i) > 140737488355328# Then Exit For
If s(i) = 0 Then j = 1
If s(1) = s(0) Then j = 2
If s(i) = s(0) And i > 1 And i <> 2 Then j = 4
If s(i) = s(i - 1) And i > 1 Then j = 5
If i >= 2 Then
If s(2) = s(0) Then j = 3
If s(i) = s(i - 2) And i <> 2 Then j = 6
End If
If j > 0 Then Exit For
Next
Aliq.Classification = temp(j)
Aliq.Sequence = s
End Function
Private Function SumPDiv(n As Double) As Double
Dim j As Long, t As Long
If n > 1 Then
For j = 1 To n \ 2
If n Mod j = 0 Then t = t + j
Next
End If
SumPDiv = t
End Function
|
Write a version of this Python function in VB with identical behavior. | from time import sleep
from threading import Timer
def sleepsort(values):
sleepsort.result = []
def add1(x):
sleepsort.result.append(x)
mx = values[0]
for v in values:
if mx < v: mx = v
Timer(v, add1, [v]).start()
sleep(mx+1)
return sleepsort.result
if __name__ == '__main__':
x = [3,2,4,7,3,6,9,1]
if sleepsort(x) == sorted(x):
print('sleep sort worked for:',x)
else:
print('sleep sort FAILED for:',x)
| Imports System.Threading
Module Module1
Sub SleepSort(items As IEnumerable(Of Integer))
For Each item In items
Task.Factory.StartNew(Sub()
Thread.Sleep(1000 * item)
Console.WriteLine(item)
End Sub)
Next
End Sub
Sub Main()
SleepSort({1, 5, 2, 1, 8, 10, 3})
Console.ReadKey()
End Sub
End Module
|
Produce a language-to-language conversion: from Python to VB, same semantics. | from random import randint
def do_scan(mat):
for row in mat:
for item in row:
print item,
if item == 20:
print
return
print
print
mat = [[randint(1, 20) for x in xrange(10)] for y in xrange(10)]
do_scan(mat)
| Public Sub LoopsNested()
Dim a(1 To 10, 1 To 10) As Integer
Randomize
For i = 1 To 10
For j = 1 To 10
a(i, j) = Int(20 * Rnd) + 1
Next j
Next i
For i = 1 To 10
For j = 1 To 10
If a(i, j) <> 20 Then
Debug.Print a(i, j),
Else
i = 10
Exit For
End If
Next j
Debug.Print
Next i
End Sub
|
Convert this Python block to VB, preserving its control flow and logic. | from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
| Dim total As Variant, prim As Variant, maxPeri As Variant
Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)
Dim p As Variant
p = CDec(s0) + CDec(s1) + CDec(s2)
If p <= maxPeri Then
prim = prim + 1
total = total + maxPeri \ p
newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2
newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2
newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2
End If
End Sub
Public Sub Program_PythagoreanTriples()
maxPeri = CDec(100)
Do While maxPeri <= 10000000#
prim = CDec(0)
total = CDec(0)
newTri 3, 4, 5
Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives."
maxPeri = maxPeri * 10
Loop
End Sub
|
Ensure the translated VB code behaves exactly like the original Python snippet. | from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
| Dim total As Variant, prim As Variant, maxPeri As Variant
Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)
Dim p As Variant
p = CDec(s0) + CDec(s1) + CDec(s2)
If p <= maxPeri Then
prim = prim + 1
total = total + maxPeri \ p
newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2
newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2
newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2
End If
End Sub
Public Sub Program_PythagoreanTriples()
maxPeri = CDec(100)
Do While maxPeri <= 10000000#
prim = CDec(0)
total = CDec(0)
newTri 3, 4, 5
Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives."
maxPeri = maxPeri * 10
Loop
End Sub
|
Ensure the translated VB code behaves exactly like the original Python snippet. | from fractions import gcd
def pt1(maxperimeter=100):
trips = []
for a in range(1, maxperimeter):
aa = a*a
for b in range(a, maxperimeter-a+1):
bb = b*b
for c in range(b, maxperimeter-b-a+1):
cc = c*c
if a+b+c > maxperimeter or cc > aa + bb: break
if aa + bb == cc:
trips.append((a,b,c, gcd(a, b) == 1))
return trips
def pytrip(trip=(3,4,5),perim=100, prim=1):
a0, b0, c0 = a, b, c = sorted(trip)
t, firstprim = set(), prim>0
while a + b + c <= perim:
t.add((a, b, c, firstprim>0))
a, b, c, firstprim = a+a0, b+b0, c+c0, False
t2 = set()
for a, b, c, firstprim in t:
a2, a5, b2, b5, c2, c3, c7 = a*2, a*5, b*2, b*5, c*2, c*3, c*7
if a5 - b5 + c7 <= perim:
t2 |= pytrip(( a - b2 + c2, a2 - b + c2, a2 - b2 + c3), perim, firstprim)
if a5 + b5 + c7 <= perim:
t2 |= pytrip(( a + b2 + c2, a2 + b + c2, a2 + b2 + c3), perim, firstprim)
if -a5 + b5 + c7 <= perim:
t2 |= pytrip((-a + b2 + c2, -a2 + b + c2, -a2 + b2 + c3), perim, firstprim)
return t | t2
def pt2(maxperimeter=100):
trips = pytrip((3,4,5), maxperimeter, 1)
return trips
def printit(maxperimeter=100, pt=pt1):
trips = pt(maxperimeter)
print(" Up to a perimeter of %i there are %i triples, of which %i are primitive"
% (maxperimeter,
len(trips),
len([prim for a,b,c,prim in trips if prim])))
for algo, mn, mx in ((pt1, 250, 2500), (pt2, 500, 20000)):
print(algo.__doc__)
for maxperimeter in range(mn, mx+1, mn):
printit(maxperimeter, algo)
| Dim total As Variant, prim As Variant, maxPeri As Variant
Private Sub newTri(s0 As Variant, s1 As Variant, s2 As Variant)
Dim p As Variant
p = CDec(s0) + CDec(s1) + CDec(s2)
If p <= maxPeri Then
prim = prim + 1
total = total + maxPeri \ p
newTri s0 + 2 * (-s1 + s2), 2 * (s0 + s2) - s1, 2 * (s0 - s1 + s2) + s2
newTri s0 + 2 * (s1 + s2), 2 * (s0 + s2) + s1, 2 * (s0 + s1 + s2) + s2
newTri -s0 + 2 * (s1 + s2), 2 * (-s0 + s2) + s1, 2 * (-s0 + s1 + s2) + s2
End If
End Sub
Public Sub Program_PythagoreanTriples()
maxPeri = CDec(100)
Do While maxPeri <= 10000000#
prim = CDec(0)
total = CDec(0)
newTri 3, 4, 5
Debug.Print "Up to "; maxPeri; ": "; total; " triples, "; prim; " primitives."
maxPeri = maxPeri * 10
Loop
End Sub
|
Port the provided Python code into VB while preserving the original functionality. | items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = list(set(items))
| Option Explicit
Sub Main()
Dim myArr() As Variant, i As Long
myArr = Remove_Duplicate(Array(1.23456789101112E+16, True, False, True, "Alpha", 1, 235, 4, 1.25, 1.25, "Beta", 1.23456789101112E+16, "Delta", "Alpha", "Charlie", 1, 2, "Foxtrot", "Foxtrot", "Alpha", 235))
For i = LBound(myArr) To UBound(myArr)
Debug.Print myArr(i)
Next
End Sub
Private Function Remove_Duplicate(Arr As Variant) As Variant()
Dim myColl As New Collection, Temp() As Variant, i As Long, cpt As Long
ReDim Temp(UBound(Arr))
For i = LBound(Arr) To UBound(Arr)
On Error Resume Next
myColl.Add CStr(Arr(i)), CStr(Arr(i))
If Err.Number > 0 Then
On Error GoTo 0
Else
Temp(cpt) = Arr(i)
cpt = cpt + 1
End If
Next i
ReDim Preserve Temp(cpt - 1)
Remove_Duplicate = Temp
End Function
|
Write the same code in VB as shown below in Python. | def lookandsay(number):
result = ""
repeat = number[0]
number = number[1:]+" "
times = 1
for actual in number:
if actual != repeat:
result += str(times)+repeat
times = 1
repeat = actual
else:
times += 1
return result
num = "1"
for i in range(10):
print num
num = lookandsay(num)
| function looksay( n )
dim i
dim accum
dim res
dim c
res = vbnullstring
do
if n = vbnullstring then exit do
accum = 0
c = left( n,1 )
do while left( n, 1 ) = c
accum = accum + 1
n = mid(n,2)
loop
if accum > 0 then
res = res & accum & c
end if
loop
looksay = res
end function
|
Change the following Python code into VB without altering its purpose. | from collections import deque
stack = deque()
stack.append(value)
value = stack.pop()
not stack
|
Private myStack()
Private myStackHeight As Integer
Public Function Push(aValue)
myStackHeight = myStackHeight + 1
ReDim Preserve myStack(myStackHeight)
myStack(myStackHeight) = aValue
End Function
Public Function Pop()
If myStackHeight > 0 Then
Pop = myStack(myStackHeight)
myStackHeight = myStackHeight - 1
Else
MsgBox "Pop: stack is empty!"
End If
End Function
Public Function IsEmpty() As Boolean
IsEmpty = (myStackHeight = 0)
End Function
Property Get Size() As Integer
Size = myStackHeight
End Property
|
Convert the following code from Python to VB, ensuring the logic remains intact. | from math import gcd
def φ(n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
if __name__ == '__main__':
def is_prime(n):
return φ(n) == n - 1
for n in range(1, 26):
print(f" φ({n}) == {φ(n)}{', is prime' if is_prime(n) else ''}")
count = 0
for n in range(1, 10_000 + 1):
count += is_prime(n)
if n in {100, 1000, 10_000}:
print(f"Primes up to {n}: {count}")
| Private Function totient(ByVal n As Long) As Long
Dim tot As Long: tot = n
Dim i As Long: i = 2
Do While i * i <= n
If n Mod i = 0 Then
Do While True
n = n \ i
If n Mod i <> 0 Then Exit Do
Loop
tot = tot - tot \ i
End If
i = i + IIf(i = 2, 1, 2)
Loop
If n > 1 Then
tot = tot - tot \ n
End If
totient = tot
End Function
Public Sub main()
Debug.Print " n phi prime"
Debug.Print " --------------"
Dim count As Long
Dim tot As Integer, n As Long
For n = 1 To 25
tot = totient(n)
prime = (n - 1 = tot)
count = count - prime
Debug.Print Format(n, "@@"); Format(tot, "@@@@@"); Format(prime, "@@@@@@@@")
Next n
Debug.Print
Debug.Print "Number of primes up to 25 = "; Format(count, "@@@@")
For n = 26 To 100000
count = count - (totient(n) = n - 1)
Select Case n
Case 100, 1000, 10000, 100000
Debug.Print "Number of primes up to"; n; String$(6 - Len(CStr(n)), " "); "="; Format(count, "@@@@@")
Case Else
End Select
Next n
End Sub
|
Maintain the same structure and functionality when rewriting this code in VB. | if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
qux()
match x:
0 => foo()
1 => bar()
2 => baz()
_ => qux()
(a) ? b : c
| Sub C_S_If()
Dim A$, B$
A = "Hello"
B = "World"
If A = B Then Debug.Print A & " = " & B
If A = B Then
Debug.Print A & " = " & B
Else
Debug.Print A & " and " & B & " are differents."
End If
If A = B Then
Debug.Print A & " = " & B
Else: Debug.Print A & " and " & B & " are differents."
End If
If A = B Then Debug.Print A & " = " & B _
Else Debug.Print A & " and " & B & " are differents."
If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents."
If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents."
End Sub
|
Keep all operations the same but rewrite the snippet in VB. | if x == 0:
foo()
elif x == 1:
bar()
elif x == 2:
baz()
else:
qux()
match x:
0 => foo()
1 => bar()
2 => baz()
_ => qux()
(a) ? b : c
| Sub C_S_If()
Dim A$, B$
A = "Hello"
B = "World"
If A = B Then Debug.Print A & " = " & B
If A = B Then
Debug.Print A & " = " & B
Else
Debug.Print A & " and " & B & " are differents."
End If
If A = B Then
Debug.Print A & " = " & B
Else: Debug.Print A & " and " & B & " are differents."
End If
If A = B Then Debug.Print A & " = " & B _
Else Debug.Print A & " and " & B & " are differents."
If A = B Then Debug.Print A & " = " & B Else Debug.Print A & " and " & B & " are differents."
If A = B Then Debug.Print A & " = " & B Else: Debug.Print A & " and " & B & " are differents."
End Sub
|
Change the programming language of this snippet from Python to VB without modifying what it does. | from fractions import Fraction
def fractran(n, fstring='17 / 91, 78 / 85, 19 / 51, 23 / 38, 29 / 33,'
'77 / 29, 95 / 23, 77 / 19, 1 / 17, 11 / 13,'
'13 / 11, 15 / 14, 15 / 2, 55 / 1'):
flist = [Fraction(f) for f in fstring.replace(' ', '').split(',')]
n = Fraction(n)
while True:
yield n.numerator
for f in flist:
if (n * f).denominator == 1:
break
else:
break
n *= f
if __name__ == '__main__':
n, m = 2, 15
print('First %i members of fractran(%i):\n ' % (m, n) +
', '.join(str(f) for f,i in zip(fractran(n), range(m))))
| Option Base 1
Public prime As Variant
Public nf As New Collection
Public df As New Collection
Const halt = 20
Private Sub init()
prime = [{2,3,5,7,11,13,17,19,23,29,31}]
End Sub
Private Function factor(f As Long) As Variant
Dim result(10) As Integer
Dim i As Integer: i = 1
Do While f > 1
Do While f Mod prime(i) = 0
f = f \ prime(i)
result(i) = result(i) + 1
Loop
i = i + 1
Loop
factor = result
End Function
Private Function decrement(ByVal a As Variant, b As Variant) As Variant
For i = LBound(a) To UBound(a)
a(i) = a(i) - b(i)
Next i
decrement = a
End Function
Private Function increment(ByVal a As Variant, b As Variant) As Variant
For i = LBound(a) To UBound(a)
a(i) = a(i) + b(i)
Next i
increment = a
End Function
Private Function test(a As Variant, b As Variant)
flag = True
For i = LBound(a) To UBound(a)
If a(i) < b(i) Then
flag = False
Exit For
End If
Next i
test = flag
End Function
Private Function unfactor(x As Variant) As Long
result = 1
For i = LBound(x) To UBound(x)
result = result * prime(i) ^ x(i)
Next i
unfactor = result
End Function
Private Sub compile(program As String)
program = Replace(program, " ", "")
programlist = Split(program, ",")
For Each instruction In programlist
parts = Split(instruction, "/")
nf.Add factor(Val(parts(0)))
df.Add factor(Val(parts(1)))
Next instruction
End Sub
Private Function run(x As Long) As Variant
n = factor(x)
counter = 0
Do While True
For i = 1 To df.Count
If test(n, df(i)) Then
n = increment(decrement(n, df(i)), nf(i))
Exit For
End If
Next i
Debug.Print unfactor(n);
counter = counter + 1
If num = 31 Or counter >= halt Then Exit Do
Loop
Debug.Print
run = n
End Function
Private Function steps(x As Variant) As Variant
For i = 1 To df.Count
If test(x, df(i)) Then
x = increment(decrement(x, df(i)), nf(i))
Exit For
End If
Next i
steps = x
End Function
Private Function is_power_of_2(x As Variant) As Boolean
flag = True
For i = LBound(x) + 1 To UBound(x)
If x(i) > 0 Then
flag = False
Exit For
End If
Next i
is_power_of_2 = flag
End Function
Private Function filter_primes(x As Long, max As Integer) As Long
n = factor(x)
i = 0: iterations = 0
Do While i < max
If is_power_of_2(steps(n)) Then
Debug.Print n(1);
i = i + 1
End If
iterations = iterations + 1
Loop
Debug.Print
filter_primes = iterations
End Function
Public Sub main()
init
compile ("17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1")
Debug.Print "First 20 results:"
output = run(2)
Debug.Print "First 30 primes:"
Debug.Print "after"; filter_primes(2, 30); "iterations."
End Sub
|
Convert this Python snippet to VB and keep its semantics consistent. | def readconf(fn):
ret = {}
with file(fn) as fp:
for line in fp:
line = line.strip()
if not line or line.startswith('
boolval = True
if line.startswith(';'):
line = line.lstrip(';')
if len(line.split()) != 1: continue
boolval = False
bits = line.split(None, 1)
if len(bits) == 1:
k = bits[0]
v = boolval
else:
k, v = bits
ret[k.lower()] = v
return ret
if __name__ == '__main__':
import sys
conf = readconf(sys.argv[1])
for k, v in sorted(conf.items()):
print k, '=', v
| type TSettings extends QObject
FullName as string
FavouriteFruit as string
NeedSpelling as integer
SeedsRemoved as integer
OtherFamily as QStringlist
Constructor
FullName = ""
FavouriteFruit = ""
NeedSpelling = 0
SeedsRemoved = 0
OtherFamily.clear
end constructor
end type
Dim Settings as TSettings
dim ConfigList as QStringList
dim x as integer
dim StrLine as string
dim StrPara as string
dim StrData as string
function Trim$(Expr as string) as string
Result = Rtrim$(Ltrim$(Expr))
end function
Sub ConfigOption(PData as string)
dim x as integer
for x = 1 to tally(PData, ",") +1
Settings.OtherFamily.AddItems Trim$(field$(PData, "," ,x))
next
end sub
Function ConfigBoolean(PData as string) as integer
PData = Trim$(PData)
Result = iif(lcase$(PData)="true" or PData="1" or PData="", 1, 0)
end function
sub ReadSettings
ConfigList.LoadFromFile("Rosetta.cfg")
ConfigList.text = REPLACESUBSTR$(ConfigList.text,"="," ")
for x = 0 to ConfigList.ItemCount -1
StrLine = Trim$(ConfigList.item(x))
StrPara = Trim$(field$(StrLine," ",1))
StrData = Trim$(lTrim$(StrLine - StrPara))
Select case UCase$(StrPara)
case "FULLNAME" : Settings.FullName = StrData
case "FAVOURITEFRUIT" : Settings.FavouriteFruit = StrData
case "NEEDSPEELING" : Settings.NeedSpelling = ConfigBoolean(StrData)
case "SEEDSREMOVED" : Settings.SeedsRemoved = ConfigBoolean(StrData)
case "OTHERFAMILY" : Call ConfigOption(StrData)
end select
next
end sub
Call ReadSettings
|
Write a version of this Python function in VB with identical behavior. | strings = "here are Some sample strings to be sorted".split()
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey)
| Imports System
Module Sorting_Using_a_Custom_Comparator
Function CustomComparator(ByVal x As String, ByVal y As String) As Integer
Dim result As Integer
result = y.Length - x.Length
If result = 0 Then
result = String.Compare(x, y, True)
End If
Return result
End Function
Sub Main()
Dim strings As String() = {"test", "Zoom", "strings", "a"}
Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))
End Sub
End Module
|
Maintain the same structure and functionality when rewriting this code in VB. | txt = "Hello, world! "
left = True
def draw():
global txt
background(128)
text(txt, 10, height / 2)
if frameCount % 10 == 0:
if (left):
txt = rotate(txt, 1)
else:
txt = rotate(txt, -1)
println(txt)
def mouseReleased():
global left
left = not left
def rotate(text, startIdx):
rotated = text[startIdx:] + text[:startIdx]
return rotated
| VERSION 5.00
Begin VB.Form Form1
Begin VB.Timer Timer1
Interval = 250
End
Begin VB.Label Label1
AutoSize = -1
Caption = "Hello World! "
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Private goRight As Boolean
Private Sub Label1_Click()
goRight = Not goRight
End Sub
Private Sub Timer1_Timer()
If goRight Then
x = Mid(Label1.Caption, 2) & Left(Label1.Caption, 1)
Else
x = Right(Label1.Caption, 1) & Left(Label1.Caption, Len(Label1.Caption) - 1)
End If
Label1.Caption = x
End Sub
|
Transform the following Python implementation into VB, maintaining the same output and logic. | [(x,y,z) for x in xrange(1,n+1) for y in xrange(x,n+1) for z in xrange(y,n+1) if x**2 + y**2 == z**2]
| Module ListComp
Sub Main()
Dim ts = From a In Enumerable.Range(1, 20) _
From b In Enumerable.Range(a, 21 - a) _
From c In Enumerable.Range(b, 21 - b) _
Where a * a + b * b = c * c _
Select New With { a, b, c }
For Each t In ts
System.Console.WriteLine("{0}, {1}, {2}", t.a, t.b, t.c)
Next
End Sub
End Module
|
Rewrite this program in VB while keeping its functionality equivalent to the Python version. | def selection_sort(lst):
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst
| Function Selection_Sort(s)
arr = Split(s,",")
For i = 0 To UBound(arr)
For j = i To UBound(arr)
temp = arr(i)
If arr(j) < arr(i) Then
arr(i) = arr(j)
arr(j) = temp
End If
Next
Next
Selection_Sort = (Join(arr,","))
End Function
WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted"
WScript.StdOut.WriteLine
WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1")
WScript.StdOut.WriteLine
WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d")
|
Can you help me rewrite this code in VB instead of Python, keeping it the same logically? | def selection_sort(lst):
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst
| Function Selection_Sort(s)
arr = Split(s,",")
For i = 0 To UBound(arr)
For j = i To UBound(arr)
temp = arr(i)
If arr(j) < arr(i) Then
arr(i) = arr(j)
arr(j) = temp
End If
Next
Next
Selection_Sort = (Join(arr,","))
End Function
WScript.StdOut.Write "Pre-Sort" & vbTab & "Sorted"
WScript.StdOut.WriteLine
WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1")
WScript.StdOut.WriteLine
WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d")
|
Can you help me rewrite this code in VB instead of Python, keeping it the same logically? | def square(n):
return n * n
numbers = [1, 3, 5, 7]
squares1 = [square(n) for n in numbers]
squares2a = map(square, numbers)
squares2b = map(lambda x: x*x, numbers)
squares3 = [n * n for n in numbers]
isquares1 = (n * n for n in numbers)
import itertools
isquares2 = itertools.imap(square, numbers)
| Option Explicit
Sub Main()
Dim arr, i
arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next
Debug.Print Join(arr, ", ")
End Sub
Private Function Fibonacci(N) As Variant
If N <= 1 Then
Fibonacci = N
Else
Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)
End If
End Function
|
Please provide an equivalent version of this Python code in VB. | def square(n):
return n * n
numbers = [1, 3, 5, 7]
squares1 = [square(n) for n in numbers]
squares2a = map(square, numbers)
squares2b = map(lambda x: x*x, numbers)
squares3 = [n * n for n in numbers]
isquares1 = (n * n for n in numbers)
import itertools
isquares2 = itertools.imap(square, numbers)
| Option Explicit
Sub Main()
Dim arr, i
arr = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
For i = LBound(arr) To UBound(arr): arr(i) = Fibonacci(arr(i)): Next
Debug.Print Join(arr, ", ")
End Sub
Private Function Fibonacci(N) As Variant
If N <= 1 Then
Fibonacci = N
Else
Fibonacci = Fibonacci(N - 1) + Fibonacci(N - 2)
End If
End Function
|
Change the following Python code into VB without altering its purpose. | >>> dog = 'Benjamin'; Dog = 'Samba'; DOG = 'Bernie'
>>> print ('The three dogs are named ',dog,', ',Dog,', and ',DOG)
The three dogs are named Benjamin , Samba , and Bernie
>>>
| Public Sub case_sensitivity()
Dim DOG As String
DOG = "Benjamin"
DOG = "Samba"
DOG = "Bernie"
Debug.Print "There is just one dog named " & DOG
End Sub
|
Rewrite this program in VB while keeping its functionality equivalent to the Python version. | with open(filename, 'w') as f:
f.write(data)
| Option Explicit
Const strName As String = "MyFileText.txt"
Const Text As String = "(Over)write a file so that it contains a string. " & vbCrLf & _
"The reverse of Read entire file—for when you want to update or " & vbCrLf & _
"create a file which you would read in its entirety all at once."
Sub Main()
Dim Nb As Integer
Nb = FreeFile
Open "C:\Users\" & Environ("username") & "\Desktop\" & strName For Output As #Nb
Print #1, Text
Close #Nb
End Sub
|
Can you help me rewrite this code in VB instead of Python, keeping it the same logically? | for i in 1..5:
for j in 1..i:
stdout.write("*")
echo("")
| Public OutConsole As Scripting.TextStream
For i = 0 To 4
For j = 0 To i
OutConsole.Write "*"
Next j
OutConsole.WriteLine
Next i
|
Generate an equivalent VB version of this Python code. | for i in 1..5:
for j in 1..i:
stdout.write("*")
echo("")
| Public OutConsole As Scripting.TextStream
For i = 0 To 4
For j = 0 To i
OutConsole.Write "*"
Next j
OutConsole.WriteLine
Next i
|
Convert this Python block to VB, preserving its control flow and logic. |
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
| option explicit
const pi180= 0.01745329251994329576923690768489
const pi=3.1415926535897932384626433832795
class turtle
dim fso
dim fn
dim svg
dim iang
dim ori
dim incr
dim pdown
dim clr
dim x
dim y
public property let orient(n):ori = n*pi180 :end property
public property let iangle(n):iang= n*pi180 :end property
public sub pd() : pdown=true: end sub
public sub pu() :pdown=FALSE :end sub
public sub rt(i)
ori=ori - i*iang:
end sub
public sub lt(i):
ori=(ori + i*iang)
end sub
public sub bw(l)
x= x+ cos(ori+pi)*l*incr
y= y+ sin(ori+pi)*l*incr
end sub
public sub fw(l)
dim x1,y1
x1=x + cos(ori)*l*incr
y1=y + sin(ori)*l*incr
if pdown then line x,y,x1,y1
x=x1:y=y1
end sub
Private Sub Class_Initialize()
setlocale "us"
initsvg
x=400:y=400:incr=100
ori=90*pi180
iang=90*pi180
clr=0
pdown=true
end sub
Private Sub Class_Terminate()
disply
end sub
private sub line (x,y,x1,y1)
svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>"
end sub
private sub disply()
dim shell
svg.WriteLine "</svg></body></html>"
svg.close
Set shell = CreateObject("Shell.Application")
shell.ShellExecute fn,1,False
end sub
private sub initsvg()
dim scriptpath
Set fso = CreateObject ("Scripting.Filesystemobject")
ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))
fn=Scriptpath & "SIERP.HTML"
Set svg = fso.CreateTextFile(fn,True)
if SVG IS nothing then wscript.echo "Can
svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>"
svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>"
svg.writeline "</head>"&vbcrlf & "<body>"
svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">"
end sub
end class
sub sier(lev,lgth)
dim i
if lev=1 then
for i=1 to 3
x.fw lgth
x.lt 2
next
else
sier lev-1,lgth\2
x.fw lgth\2
sier lev-1,lgth\2
x.bw lgth\2
x.lt 1
x.fw lgth\2
x.rt 1
sier lev-1,lgth\2
x.lt 1
x.bw lgth\2
x.rt 1
end if
end sub
dim x
set x=new turtle
x.iangle=60
x.orient=0
x.incr=10
x.x=100:x.y=100
sier 7,64
set x=nothing
|
Write the same algorithm in VB as shown in this Python implementation. |
import turtle as t
def sier(n,length):
if n == 0:
return
for i in range(3):
sier(n - 1, length / 2)
t.fd(length)
t.rt(120)
| option explicit
const pi180= 0.01745329251994329576923690768489
const pi=3.1415926535897932384626433832795
class turtle
dim fso
dim fn
dim svg
dim iang
dim ori
dim incr
dim pdown
dim clr
dim x
dim y
public property let orient(n):ori = n*pi180 :end property
public property let iangle(n):iang= n*pi180 :end property
public sub pd() : pdown=true: end sub
public sub pu() :pdown=FALSE :end sub
public sub rt(i)
ori=ori - i*iang:
end sub
public sub lt(i):
ori=(ori + i*iang)
end sub
public sub bw(l)
x= x+ cos(ori+pi)*l*incr
y= y+ sin(ori+pi)*l*incr
end sub
public sub fw(l)
dim x1,y1
x1=x + cos(ori)*l*incr
y1=y + sin(ori)*l*incr
if pdown then line x,y,x1,y1
x=x1:y=y1
end sub
Private Sub Class_Initialize()
setlocale "us"
initsvg
x=400:y=400:incr=100
ori=90*pi180
iang=90*pi180
clr=0
pdown=true
end sub
Private Sub Class_Terminate()
disply
end sub
private sub line (x,y,x1,y1)
svg.WriteLine "<line x1=""" & x & """ y1= """& y & """ x2=""" & x1& """ y2=""" & y1 & """/>"
end sub
private sub disply()
dim shell
svg.WriteLine "</svg></body></html>"
svg.close
Set shell = CreateObject("Shell.Application")
shell.ShellExecute fn,1,False
end sub
private sub initsvg()
dim scriptpath
Set fso = CreateObject ("Scripting.Filesystemobject")
ScriptPath= Left(WScript.ScriptFullName, InStrRev(WScript.ScriptFullName, "\"))
fn=Scriptpath & "SIERP.HTML"
Set svg = fso.CreateTextFile(fn,True)
if SVG IS nothing then wscript.echo "Can
svg.WriteLine "<!DOCTYPE html>" &vbcrlf & "<html>" &vbcrlf & "<head>"
svg.writeline "<style>" & vbcrlf & "line {stroke:rgb(255,0,0);stroke-width:.5}" &vbcrlf &"</style>"
svg.writeline "</head>"&vbcrlf & "<body>"
svg.WriteLine "<svg xmlns=""http://www.w3.org/2000/svg"" width=""800"" height=""800"" viewBox=""0 0 800 800"">"
end sub
end class
sub sier(lev,lgth)
dim i
if lev=1 then
for i=1 to 3
x.fw lgth
x.lt 2
next
else
sier lev-1,lgth\2
x.fw lgth\2
sier lev-1,lgth\2
x.bw lgth\2
x.lt 1
x.fw lgth\2
x.rt 1
sier lev-1,lgth\2
x.lt 1
x.bw lgth\2
x.rt 1
end if
end sub
dim x
set x=new turtle
x.iangle=60
x.orient=0
x.incr=10
x.x=100:x.y=100
sier 7,64
set x=nothing
|
Translate the given Python code snippet into VB without altering its behavior. | def ncsub(seq, s=0):
if seq:
x = seq[:1]
xs = seq[1:]
p2 = s % 2
p1 = not p2
return [x + ys for ys in ncsub(xs, s + p1)] + ncsub(xs, s + p2)
else:
return [[]] if s >= 3 else []
|
Function noncontsubseq(l)
Dim i, j, g, n, r, s, w, m
Dim a, b, c
n = Ubound(l)
For s = 0 To n-2
For g = s+1 To n-1
a = "["
For i = s To g-1
a = a & l(i) & ", "
Next
For w = 1 To n-g
r = n+1-g-w
For i = 1 To 2^r-1 Step 2
b = a
For j = 0 To r-1
If i And 2^j Then b=b & l(g+w+j) & ", "
Next
c = (Left(b, Len(b)-1))
WScript.Echo Left(c, Len(c)-1) & "]"
m = m+1
Next
Next
Next
Next
noncontsubseq = m
End Function
list = Array("1", "2", "3", "4")
WScript.Echo "List: [" & Join(list, ", ") & "]"
nn = noncontsubseq(list)
WScript.Echo nn & " non-continuous subsequences"
|
Produce a functionally identical VB code for the snippet given in Python. | primes = [2, 3, 5, 7, 11, 13, 17, 19]
def count_twin_primes(limit: int) -> int:
global primes
if limit > primes[-1]:
ram_limit = primes[-1] + 90000000 - len(primes)
reasonable_limit = min(limit, primes[-1] ** 2, ram_limit) - 1
while reasonable_limit < limit:
ram_limit = primes[-1] + 90000000 - len(primes)
if ram_limit > primes[-1]:
reasonable_limit = min(limit, primes[-1] ** 2, ram_limit)
else:
reasonable_limit = min(limit, primes[-1] ** 2)
sieve = list({x for prime in primes for x in
range(primes[-1] + prime - (primes[-1] % prime), reasonable_limit, prime)})
primes += [x - 1 for i, x in enumerate(sieve) if i and x - 1 != sieve[i - 1] and x - 1 < limit]
count = len([(x, y) for (x, y) in zip(primes, primes[1:]) if x + 2 == y])
return count
def test(limit: int):
count = count_twin_primes(limit)
print(f"Number of twin prime pairs less than {limit} is {count}\n")
test(10)
test(100)
test(1000)
test(10000)
test(100000)
test(1000000)
test(10000000)
test(100000000)
| Function IsPrime(x As Long) As Boolean
Dim i As Long
If x Mod 2 = 0 Then
Exit Function
Else
For i = 3 To Int(Sqr(x)) Step 2
If x Mod i = 0 Then Exit Function
Next i
End If
IsPrime = True
End Function
Function TwinPrimePairs(max As Long) As Long
Dim p1 As Boolean, p2 As Boolean, count As Long, i As Long
p2 = True
For i = 5 To max Step 2
p1 = p2
p2 = IsPrime(i)
If p1 And p2 Then count = count + 1
Next i
TwinPrimePairs = count
End Function
Sub Test(x As Long)
Debug.Print "Twin prime pairs below" + Str(x) + ":" + Str(TwinPrimePairs(x))
End Sub
Sub Main()
Test 10
Test 100
Test 1000
Test 10000
Test 100000
Test 1000000
Test 10000000
End Sub
|
Ensure the translated VB code behaves exactly like the original Python snippet. | import cmath
class Complex(complex):
def __repr__(self):
rp = '%7.5f' % self.real if not self.pureImag() else ''
ip = '%7.5fj' % self.imag if not self.pureReal() else ''
conj = '' if (
self.pureImag() or self.pureReal() or self.imag < 0.0
) else '+'
return '0.0' if (
self.pureImag() and self.pureReal()
) else rp + conj + ip
def pureImag(self):
return abs(self.real) < 0.000005
def pureReal(self):
return abs(self.imag) < 0.000005
def croots(n):
if n <= 0:
return None
return (Complex(cmath.rect(1, 2 * k * cmath.pi / n)) for k in range(n))
for nr in range(2, 11):
print(nr, list(croots(nr)))
| Public Sub roots_of_unity()
For n = 2 To 9
Debug.Print n; "th roots of 1:"
For r00t = 0 To n - 1
Debug.Print " Root "; r00t & ": "; WorksheetFunction.Complex(Cos(2 * WorksheetFunction.Pi() * r00t / n), _
Sin(2 * WorksheetFunction.Pi() * r00t / n))
Next r00t
Debug.Print
Next n
End Sub
|
Rewrite the snippet below in VB so it works the same as the original Python code. |
print 2**64*2**64
| Imports System
Imports System.Console
Imports BI = System.Numerics.BigInteger
Module Module1
Dim a As Decimal, mx As Decimal = 1E28D, hm As Decimal = 1E14D
Structure bd
Public hi, lo As Decimal
End Structure
Function toStr(ByVal a As bd, ByVal Optional comma As Boolean = False) As String
Dim r As String = If(a.hi = 0, String.Format("{0:0}", a.lo),
String.Format("{0:0}{1:" & New String("0"c, 28) & "}", a.hi, a.lo))
If Not comma Then Return r
Dim rc As String = ""
For i As Integer = r.Length - 3 To 0 Step -3
rc = "," & r.Substring(i, 3) & rc : Next
toStr = r.Substring(0, r.Length Mod 3) & rc
toStr = toStr.Substring(If(toStr.Chars(0) = "," , 1, 0))
End Function
Function Pow_dec(ByVal bas As Decimal, ByVal exp As UInteger) As Decimal
If exp = 0 Then Pow_dec = 1D else Pow_dec = Pow_dec(bas, exp >> 1) : _
Pow_dec *= Pow_dec : If (exp And 1) <> 0 Then Pow_dec *= bas
End Function
Sub Main(ByVal args As String())
For p As UInteger = 64 To 95 - 1 Step 30
Dim y As bd, x As bd : a = Pow_dec(2D, p)
WriteLine("The square of (2^{0}): {1,38:n0}", p, a)
x.hi = Math.Floor(a / hm) : x.lo = a Mod hm
Dim BS As BI = BI.Pow(CType(a, BI), 2)
y.lo = x.lo * x.lo : y.hi = x.hi * x.hi
a = x.hi * x.lo * 2D
y.hi += Math.Floor(a / hm) : y.lo += (a Mod hm) * hm
While y.lo > mx : y.lo -= mx : y.hi += 1 : End While
WriteLine(" is {0,75} (which {1} match the BigInteger computation)" & vbLf,
toStr(y, True), If(BS.ToString() = toStr(y), "does", "fails to"))
Next
End Sub
End Module
|
Port the following code from Python to VB with equivalent syntax and logic. | import math
def solvePell(n):
x = int(math.sqrt(n))
y, z, r = x, 1, x << 1
e1, e2 = 1, 0
f1, f2 = 0, 1
while True:
y = r * z - y
z = (n - y * y) // z
r = (x + y) // z
e1, e2 = e2, e1 + e2 * r
f1, f2 = f2, f1 + f2 * r
a, b = f2 * x + e2, f2
if a * a - n * b * b == 1:
return a, b
for n in [61, 109, 181, 277]:
x, y = solvePell(n)
print("x^2 - %3d * y^2 = 1 for x = %27d and y = %25d" % (n, x, y))
| Imports System.Numerics
Module Module1
Sub Fun(ByRef a As BigInteger, ByRef b As BigInteger, c As Integer)
Dim t As BigInteger = a : a = b : b = b * c + t
End Sub
Sub SolvePell(n As Integer, ByRef a As BigInteger, ByRef b As BigInteger)
Dim x As Integer = Math.Sqrt(n), y As Integer = x, z As Integer = 1, r As Integer = x << 1,
e1 As BigInteger = 1, e2 As BigInteger = 0, f1 As BigInteger = 0, f2 As BigInteger = 1
While True
y = r * z - y : z = (n - y * y) / z : r = (x + y) / z
Fun(e1, e2, r) : Fun(f1, f2, r) : a = f2 : b = e2 : Fun(b, a, x)
If a * a - n * b * b = 1 Then Exit Sub
End While
End Sub
Sub Main()
Dim x As BigInteger, y As BigInteger
For Each n As Integer In {61, 109, 181, 277}
SolvePell(n, x, y)
Console.WriteLine("x^2 - {0,3} * y^2 = 1 for x = {1,27:n0} and y = {2,25:n0}", n, x, y)
Next
End Sub
End Module
|
Rewrite this program in VB while keeping its functionality equivalent to the Python version. |
import random
digits = '123456789'
size = 4
chosen = ''.join(random.sample(digits,size))
print % (size, size)
guesses = 0
while True:
guesses += 1
while True:
guess = raw_input('\nNext guess [%i]: ' % guesses).strip()
if len(guess) == size and \
all(char in digits for char in guess) \
and len(set(guess)) == size:
break
print "Problem, try again. You need to enter %i unique digits from 1 to 9" % size
if guess == chosen:
print '\nCongratulations you guessed correctly in',guesses,'attempts'
break
bulls = cows = 0
for i in range(size):
if guess[i] == chosen[i]:
bulls += 1
elif guess[i] in chosen:
cows += 1
print ' %i Bulls\n %i Cows' % (bulls, cows)
| Option Explicit
Sub Main_Bulls_and_cows()
Dim strNumber As String, strInput As String, strMsg As String, strTemp As String
Dim boolEnd As Boolean
Dim lngCpt As Long
Dim i As Byte, bytCow As Byte, bytBull As Byte
Const NUMBER_OF_DIGITS As Byte = 4
Const MAX_LOOPS As Byte = 25
strNumber = Create_Number(NUMBER_OF_DIGITS)
Do
bytBull = 0: bytCow = 0: lngCpt = lngCpt + 1
If lngCpt > MAX_LOOPS Then strMsg = "Max of loops... Sorry you loose!": Exit Do
strInput = AskToUser(NUMBER_OF_DIGITS)
If strInput = "Exit Game" Then strMsg = "User abort": Exit Do
For i = 1 To Len(strNumber)
If Mid(strNumber, i, 1) = Mid(strInput, i, 1) Then
bytBull = bytBull + 1
ElseIf InStr(strNumber, Mid(strInput, i, 1)) > 0 Then
bytCow = bytCow + 1
End If
Next i
If bytBull = Len(strNumber) Then
boolEnd = True: strMsg = "You win in " & lngCpt & " loops!"
Else
strTemp = strTemp & vbCrLf & "With : " & strInput & " ,you have : " & bytBull & " bulls," & bytCow & " cows."
MsgBox strTemp
End If
Loop While Not boolEnd
MsgBox strMsg
End Sub
Function Create_Number(NbDigits As Byte) As String
Dim myColl As New Collection
Dim strTemp As String
Dim bytAlea As Byte
Randomize
Do
bytAlea = Int((Rnd * 9) + 1)
On Error Resume Next
myColl.Add CStr(bytAlea), CStr(bytAlea)
If Err <> 0 Then
On Error GoTo 0
Else
strTemp = strTemp & CStr(bytAlea)
End If
Loop While Len(strTemp) < NbDigits
Create_Number = strTemp
End Function
Function AskToUser(NbDigits As Byte) As String
Dim boolGood As Boolean, strIn As String, i As Byte, NbDiff As Byte
Do While Not boolGood
strIn = InputBox("Enter your number (" & NbDigits & " digits)", "Number")
If StrPtr(strIn) = 0 Then strIn = "Exit Game": Exit Do
If strIn <> "" Then
If Len(strIn) = NbDigits Then
NbDiff = 0
For i = 1 To Len(strIn)
If Len(Replace(strIn, Mid(strIn, i, 1), "")) < NbDigits - 1 Then
NbDiff = 1
Exit For
End If
Next i
If NbDiff = 0 Then boolGood = True
End If
End If
Loop
AskToUser = strIn
End Function
|
Generate an equivalent VB version of this Python code. | def bubble_sort(seq):
changed = True
while changed:
changed = False
for i in range(len(seq) - 1):
if seq[i] > seq[i+1]:
seq[i], seq[i+1] = seq[i+1], seq[i]
changed = True
return seq
if __name__ == "__main__":
from random import shuffle
testset = [_ for _ in range(100)]
testcase = testset.copy()
shuffle(testcase)
assert testcase != testset
bubble_sort(testcase)
assert testcase == testset
| Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sortable.Shuffle()
Dim swapped As Boolean
Do
Dim index, bound As Integer
bound = sortable.Ubound
While index < bound
If sortable(index) > sortable(index + 1) Then
Dim s As Integer = sortable(index)
sortable.Remove(index)
sortable.Insert(index + 1, s)
swapped = True
End If
index = index + 1
Wend
Loop Until Not swapped
|
Rewrite this program in VB while keeping its functionality equivalent to the Python version. | def bubble_sort(seq):
changed = True
while changed:
changed = False
for i in range(len(seq) - 1):
if seq[i] > seq[i+1]:
seq[i], seq[i+1] = seq[i+1], seq[i]
changed = True
return seq
if __name__ == "__main__":
from random import shuffle
testset = [_ for _ in range(100)]
testcase = testset.copy()
shuffle(testcase)
assert testcase != testset
bubble_sort(testcase)
assert testcase == testset
| Dim sortable() As Integer = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
sortable.Shuffle()
Dim swapped As Boolean
Do
Dim index, bound As Integer
bound = sortable.Ubound
While index < bound
If sortable(index) > sortable(index + 1) Then
Dim s As Integer = sortable(index)
sortable.Remove(index)
sortable.Insert(index + 1, s)
swapped = True
End If
index = index + 1
Wend
Loop Until Not swapped
|
Keep all operations the same but rewrite the snippet in VB. | import shutil
shutil.copyfile('input.txt', 'output.txt')
| Sub WriteToFile(input As FolderItem, output As FolderItem)
Dim tis As TextInputStream
Dim tos As TextOutputStream
tis = tis.Open(input)
tos = tos.Create(output)
While Not tis.EOF
tos.WriteLine(tis.ReadLine)
Wend
tis.Close
tos.Close
End Sub
|
Preserve the algorithm and functionality while converting the code from Python to VB. | import shutil
shutil.copyfile('input.txt', 'output.txt')
| Sub WriteToFile(input As FolderItem, output As FolderItem)
Dim tis As TextInputStream
Dim tos As TextOutputStream
tis = tis.Open(input)
tos = tos.Create(output)
While Not tis.EOF
tos.WriteLine(tis.ReadLine)
Wend
tis.Close
tos.Close
End Sub
|
Ensure the translated VB code behaves exactly like the original Python snippet. | x = int(raw_input("Number 1: "))
y = int(raw_input("Number 2: "))
print "Sum: %d" % (x + y)
print "Difference: %d" % (x - y)
print "Product: %d" % (x * y)
print "Quotient: %d" % (x / y)
print "Remainder: %d" % (x % y)
print "Quotient: %d with Remainder: %d" % divmod(x, y)
print "Power: %d" % x**y
raw_input( )
| START:
INPUT "Enter two integers (a,b):"; a!, b!
IF a = 0 THEN END
IF b = 0 THEN
PRINT "Second integer is zero. Zero not allowed for Quotient or Remainder."
GOTO START
END IF
PRINT
PRINT " Sum = "; a + b
PRINT " Difference = "; a - b
PRINT " Product = "; a * b
PRINT "Integer Quotient = "; a \ b, , "* Rounds toward 0."
PRINT " Remainder = "; a MOD b, , "* Sign matches first operand."
PRINT " Exponentiation = "; a ^ b
PRINT
INPUT "Again? (y/N)"; a$
IF UCASE$(a$) = "Y" THEN CLS: GOTO START
CLS
END
|
Preserve the algorithm and functionality while converting the code from Python to VB. | m=((1, 1, 1, 1),
(2, 4, 8, 16),
(3, 9, 27, 81),
(4, 16, 64, 256),
(5, 25,125, 625))
print(zip(*m))
| Function transpose(m As Variant) As Variant
transpose = WorksheetFunction.transpose(m)
End Function
|
Convert the following code from Python to VB, ensuring the logic remains intact. | >>> def a(answer):
print("
return answer
>>> def b(answer):
print("
return answer
>>> for i in (False, True):
for j in (False, True):
print ("\nCalculating: x = a(i) and b(j)")
x = a(i) and b(j)
print ("Calculating: y = a(i) or b(j)")
y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
Calculating: x = a(i) and b(j)
Calculating: y = a(i) or b(j)
| Private Function a(i As Variant) As Boolean
Debug.Print "a: "; i = 1,
a = i
End Function
Private Function b(j As Variant) As Boolean
Debug.Print "b: "; j = 1;
b = j
End Function
Public Sub short_circuit()
Dim x As Boolean, y As Boolean
Debug.Print "=====AND=====" & vbCrLf
For p = 0 To 1
For q = 0 To 1
If a(p) Then
x = b(q)
End If
Debug.Print " = x"
Next q
Debug.Print
Next p
Debug.Print "======OR=====" & vbCrLf
For p = 0 To 1
For q = 0 To 1
If Not a(p) Then
x = b(q)
End If
Debug.Print " = x"
Next q
Debug.Print
Next p
Debug.Print
End Sub
|
Convert this Python block to VB, preserving its control flow and logic. | import sys
print(sys.getrecursionlimit())
| Option Explicit
Sub Main()
Debug.Print "The limit is : " & Limite_Recursivite(0)
End Sub
Function Limite_Recursivite(Cpt As Long) As Long
Cpt = Cpt + 1
On Error Resume Next
Limite_Recursivite Cpt
On Error GoTo 0
Limite_Recursivite = Cpt
End Function
|
Transform the following Python implementation into VB, maintaining the same output and logic. | import sys
print(sys.getrecursionlimit())
| Option Explicit
Sub Main()
Debug.Print "The limit is : " & Limite_Recursivite(0)
End Sub
Function Limite_Recursivite(Cpt As Long) As Long
Cpt = Cpt + 1
On Error Resume Next
Limite_Recursivite Cpt
On Error GoTo 0
Limite_Recursivite = Cpt
End Function
|
Write the same algorithm in VB as shown in this Python implementation. | black = color(0)
white = color(255)
def setup():
size(320, 240)
def draw():
loadPixels()
for i in range(len(pixels)):
if random(1) < 0.5:
pixels[i] = black
else:
pixels[i] = white
updatePixels()
fill(0, 128)
rect(0, 0, 60, 20)
fill(255)
text(frameRate, 5, 15)
| Imports System.Drawing.Imaging
Public Class frmSnowExercise
Dim bRunning As Boolean = True
Private Sub Form1_Load(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles MyBase.Load
SetStyle(ControlStyles.AllPaintingInWmPaint Or ControlStyles.UserPaint _
Or ControlStyles.OptimizedDoubleBuffer, True)
UpdateStyles()
FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
MaximizeBox = False
Width = 320 + Size.Width - ClientSize.Width
Height = 240 + Size.Height - ClientSize.Height
Show()
Activate()
Application.DoEvents()
RenderLoop()
Close()
End Sub
Private Sub Form1_KeyPress(ByVal sender As Object, ByVal e As _
System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
If e.KeyChar = ChrW(Keys.Escape) Then bRunning = False
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As _
System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
e.Cancel = bRunning
bRunning = False
End Sub
Private Sub RenderLoop()
Const cfPadding As Single = 5.0F
Dim b As New Bitmap(ClientSize.Width, ClientSize.Width,
PixelFormat.Format32bppArgb)
Dim g As Graphics = Graphics.FromImage(b)
Dim r As New Random(Now.Millisecond)
Dim oBMPData As BitmapData = Nothing
Dim oPixels() As Integer = Nothing
Dim oBlackWhite() As Integer = {Color.White.ToArgb, Color.Black.ToArgb}
Dim oStopwatch As New Stopwatch
Dim fElapsed As Single = 0.0F
Dim iLoops As Integer = 0
Dim sFPS As String = "0.0 FPS"
Dim oFPSSize As SizeF = g.MeasureString(sFPS, Font)
Dim oFPSBG As RectangleF = New RectangleF(ClientSize.Width - cfPadding -
oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
g.Clear(Color.Black)
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb)
Array.Resize(oPixels, b.Width * b.Height)
Runtime.InteropServices.Marshal.Copy(oBMPData.Scan0,
oPixels, 0, oPixels.Length)
b.UnlockBits(oBMPData)
Do
fElapsed += oStopwatch.ElapsedMilliseconds / 1000.0F
oStopwatch.Reset() : oStopwatch.Start()
iLoops += 1
If fElapsed >= 1.0F Then
sFPS = (iLoops / fElapsed).ToString("0.0") & " FPS"
oFPSSize = g.MeasureString(sFPS, Font)
oFPSBG = New RectangleF(ClientSize.Width - cfPadding -
oFPSSize.Width, cfPadding, oFPSSize.Width, oFPSSize.Height)
fElapsed -= 1.0F
iLoops = 0
End If
For i As Integer = 0 To oPixels.GetUpperBound(0)
oPixels(i) = oBlackWhite(r.Next(oBlackWhite.Length))
Next
oBMPData = b.LockBits(New Rectangle(0, 0, b.Width, b.Height),
ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)
Runtime.InteropServices.Marshal.Copy(oPixels, 0, oBMPData.Scan0,
oPixels.Length)
b.UnlockBits(oBMPData)
g.FillRectangle(Brushes.Black, oFPSBG)
g.DrawString(sFPS, Font, Brushes.Yellow, oFPSBG.Left, oFPSBG.Top)
BackgroundImage = b
Invalidate(ClientRectangle)
Application.DoEvents()
Loop While bRunning
End Sub
End Class
|
Write the same code in VB as shown below in Python. |
try:
from msvcrt import getch
except ImportError:
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
print "Press Y or N to continue"
while True:
char = getch()
if char.lower() in ("y", "n"):
print char
break
|
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.")
GraphicsWindow.KeyDown = OnKeyDown
Sub OnKeyDown
TextWindow.WriteLine(GraphicsWindow.LastKey)
EndSub
|
Translate the given Python code snippet into VB without altering its behavior. |
try:
from msvcrt import getch
except ImportError:
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
print "Press Y or N to continue"
while True:
char = getch()
if char.lower() in ("y", "n"):
print char
break
|
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.")
GraphicsWindow.KeyDown = OnKeyDown
Sub OnKeyDown
TextWindow.WriteLine(GraphicsWindow.LastKey)
EndSub
|
Produce a language-to-language conversion: from Python to VB, same semantics. |
try:
from msvcrt import getch
except ImportError:
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
print "Press Y or N to continue"
while True:
char = getch()
if char.lower() in ("y", "n"):
print char
break
|
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.")
GraphicsWindow.KeyDown = OnKeyDown
Sub OnKeyDown
TextWindow.WriteLine(GraphicsWindow.LastKey)
EndSub
|
Write the same code in VB as shown below in Python. | def perf1(n):
sum = 0
for i in range(1, n):
if n % i == 0:
sum += i
return sum == n
| Private Function Factors(x As Long) As String
Application.Volatile
Dim i As Long
Dim cooresponding_factors As String
Factors = 1
corresponding_factors = x
For i = 2 To Sqr(x)
If x Mod i = 0 Then
Factors = Factors & ", " & i
If i <> x / i Then corresponding_factors = x / i & ", " & corresponding_factors
End If
Next i
If x <> 1 Then Factors = Factors & ", " & corresponding_factors
End Function
Private Function is_perfect(n As Long)
fs = Split(Factors(n), ", ")
Dim f() As Long
ReDim f(UBound(fs))
For i = 0 To UBound(fs)
f(i) = Val(fs(i))
Next i
is_perfect = WorksheetFunction.Sum(f) - n = n
End Function
Public Sub main()
Dim i As Long
For i = 2 To 100000
If is_perfect(i) Then Debug.Print i
Next i
End Sub
|
Write the same code in VB as shown below in Python. |
from itertools import zip_longest
def beadsort(l):
return list(map(sum, zip_longest(*[[1] * e for e in l], fillvalue=0)))
print(beadsort([5,3,1,7,4,1,1]))
| Option Base 1
Private Function sq_add(arr As Variant, x As Double) As Variant
Dim res() As Variant
ReDim res(UBound(arr))
For i = 1 To UBound(arr)
res(i) = arr(i) + x
Next i
sq_add = res
End Function
Private Function beadsort(ByVal a As Variant) As Variant
Dim poles() As Variant
ReDim poles(WorksheetFunction.Max(a))
For i = 1 To UBound(a)
For j = 1 To a(i)
poles(j) = poles(j) + 1
Next j
Next i
For j = 1 To UBound(a)
a(j) = 0
Next j
For i = 1 To UBound(poles)
For j = 1 To poles(i)
a(j) = a(j) + 1
Next j
Next i
beadsort = a
End Function
Public Sub main()
Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), ", ")
End Sub
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.