Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Keep all operations the same but rewrite the snippet in Scala. | import logging, logging.handlers
LOG_FILENAME = "logdemo.log"
FORMAT_STRING = "%(levelname)s:%(asctime)s:%(name)s:%(funcName)s:line-%(lineno)d: %(message)s"
LOGLEVEL = logging.DEBUG
def print_squares(number):
logger.info("In print_squares")
for i in range(number):
print("square of {0} is {1}".format(... | fun printDebug(message: String) {
val exception = RuntimeException()
val stackTrace = exception.stackTrace
val stackTraceElement = stackTrace[1]
val fileName = stackTraceElement.fileName
val className = stackTraceElement.className
val methodName = stackTraceElement.methodName
val lineNumber ... |
Maintain the same structure and functionality when rewriting this code in Scala. | class Montgomery:
BASE = 2
def __init__(self, m):
self.m = m
self.n = m.bit_length()
self.rrm = (1 << (self.n * 2)) % m
def reduce(self, t):
a = t
for i in xrange(self.n):
if (a & 1) == 1:
a = a + self.m
a = a >> 1
if ... |
import java.math.BigInteger
val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
val bigTwo = BigInteger.valueOf(2L)
class Montgomery(val m: BigInteger) {
val n: Int
val rrm: BigInteger
init {
require(m > bigZero && m.testBit(0))
n = m.bitLength()
rrm = bigOne.s... |
Generate a Scala translation of this Python snippet without changing its computational steps. |
states = { 'ready':{
'prompt' : 'Machine ready: (d)eposit, or (q)uit?',
'responses' : ['d','q']},
'waiting':{
'prompt' : 'Machine waiting: (s)elect, or (r)efund?',
'responses' : ['s','r']},
'dispense' : {
'prompt'... |
enum class State { READY, WAITING, EXIT, DISPENSE, REFUNDING }
fun fsm() {
println("Please enter your option when prompted")
println("(any characters after the first will be ignored)")
var state = State.READY
var trans: String
while (true) {
when (state) {
State.READY -> {
... |
Transform the following Python implementation into Scala, maintaining the same output and logic. | from array import array
from collections import deque
import psyco
data = []
nrows = 0
px = py = 0
sdata = ""
ddata = ""
def init(board):
global data, nrows, sdata, ddata, px, py
data = filter(None, board.splitlines())
nrows = max(len(r) for r in data)
maps = {' ':' ', '.': '.', '@':' ', '
mapd =... |
import java.util.LinkedList
class Sokoban(board: List<String>) {
val destBoard: String
val currBoard: String
val nCols = board[0].length
var playerX = 0
var playerY = 0
init {
val destBuf = StringBuilder()
val currBuf = StringBuilder()
for (r in 0 until board.size) {
... |
Write a version of this Python function in Scala with identical behavior. | from sympy import divisors
from sympy.combinatorics.subsets import Subset
def isZumkeller(n):
d = divisors(n)
s = sum(d)
if not s % 2 and max(d) <= s/2:
for x in range(1, 2**len(d)):
if sum(Subset.unrank_binary(x, d).subset) == s/2:
return True
return False
def ... | import java.util.ArrayList
import kotlin.math.sqrt
object ZumkellerNumbers {
@JvmStatic
fun main(args: Array<String>) {
var n = 1
println("First 220 Zumkeller numbers:")
run {
var count = 1
while (count <= 220) {
if (isZumkeller(n)) {
... |
Write the same code in Scala as shown below in Python. | import re as RegEx
def Commatize( _string, _startPos=0, _periodLen=3, _separator="," ):
outString = ""
strPos = 0
matches = RegEx.findall( "[0-9]*", _string )
for match in matches[:-1]:
if not match:
outString += _string[ strPos ]
strPos += 1
else:
if len(match) > _periodLen:
leadIn = match[:_st... |
val r = Regex("""(\.[0-9]+|[1-9]([0-9]+)?(\.[0-9]+)?)""")
fun String.commatize(startIndex: Int = 0, period: Int = 3, sep: String = ","): String {
if ((startIndex !in 0 until this.length) || period < 1 || sep == "") return this
val m = r.find(this, startIndex)
if (m == null) return this
val splits = m... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. |
from math import floor, sqrt
from datetime import datetime
def main():
start = datetime.now()
for i in xrange(1, 10 ** 11):
if rare(i):
print "found a rare:", i
end = datetime.now()
print "time elapsed:", end - start
def is_square(n):
s = floor(sqrt(n + 0.5))
return s * s == n
def reverse(n):
return ... | import java.time.Duration
import java.time.LocalDateTime
import kotlin.math.sqrt
class Term(var coeff: Long, var ix1: Byte, var ix2: Byte)
const val maxDigits = 16
fun toLong(digits: List<Byte>, reverse: Boolean): Long {
var sum: Long = 0
if (reverse) {
var i = digits.size - 1
while (i >= 0) ... |
Write a version of this Python function in Scala with identical behavior. | class Node:
def __init__(self, sub="", children=None):
self.sub = sub
self.ch = children or []
class SuffixTree:
def __init__(self, str):
self.nodes = [Node()]
for i in range(len(str)):
self.addSuffix(str[i:])
def addSuffix(self, suf):
n = 0
i = ... |
class Node {
var sub = ""
var ch = mutableListOf<Int>()
}
class SuffixTree(val str: String) {
val nodes = mutableListOf<Node>(Node())
init {
for (i in 0 until str.length) addSuffix(str.substring(i))
}
private fun addSuffix(suf: String) {
var n = 0
... |
Convert the following code from Python to Scala, ensuring the logic remains intact. | class Node:
def __init__(self, sub="", children=None):
self.sub = sub
self.ch = children or []
class SuffixTree:
def __init__(self, str):
self.nodes = [Node()]
for i in range(len(str)):
self.addSuffix(str[i:])
def addSuffix(self, suf):
n = 0
i = ... |
class Node {
var sub = ""
var ch = mutableListOf<Int>()
}
class SuffixTree(val str: String) {
val nodes = mutableListOf<Node>(Node())
init {
for (i in 0 until str.length) addSuffix(str.substring(i))
}
private fun addSuffix(suf: String) {
var n = 0
... |
Convert this Python block to Scala, preserving its control flow and logic. | class Parent(object):
__priv = 'private'
def __init__(self, name):
self.name = name
def __repr__(self):
return '%s(%s)' % (type(self).__name__, self.name)
def doNothing(self):
pass
import re
class Child(Parent):
__rePrivate = re.compile('^_(Child|Parent)... |
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.isAccessible
open class BaseExample(val baseProp: String) {
protected val protectedProp: String = "inherited protected value"
}
class Example(val prop1: String, val prop2: Int, baseProp: String) : BaseExample(baseProp) {
private val priva... |
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically? |
from __future__ import print_function
class Node(object):
def __init__(self):
self.edges = {}
self.link = None
self.len = 0
class Eertree(object):
def __init__(self):
self.nodes = []
self.rto = Node()
self.rte = Node()
self.rto.link = self.rte.link = self.rto;
self.rto.len = -1
self.r... |
class Node {
val edges = mutableMapOf<Char, Node>()
var link: Node? = null
var len = 0
}
class Eertree(str: String) {
val nodes = mutableListOf<Node>()
private val rto = Node()
private val rte = Node()
priva... |
Write the same code in Scala as shown below in Python. |
from __future__ import print_function
class Node(object):
def __init__(self):
self.edges = {}
self.link = None
self.len = 0
class Eertree(object):
def __init__(self):
self.nodes = []
self.rto = Node()
self.rte = Node()
self.rto.link = self.rte.link = self.rto;
self.rto.len = -1
self.r... |
class Node {
val edges = mutableMapOf<Char, Node>()
var link: Node? = null
var len = 0
}
class Eertree(str: String) {
val nodes = mutableListOf<Node>()
private val rto = Node()
private val rte = Node()
priva... |
Translate the given Python code snippet into Scala without altering its behavior. | ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
def convertToBase58(num):
sb = ''
while (num > 0):
r = num % 58
sb = sb + ALPHABET[r]
num = num // 58;
return sb[::-1]
s = 25420294593250030202636073700053352635053786165627414518
b = convertToBase58(s)
print("... |
import java.math.BigInteger
const val ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
val big0 = BigInteger.ZERO
val big58 = BigInteger.valueOf(58L)
fun convertToBase58(hash: String, base: Int = 16): String {
var x = if (base == 16 && hash.take(2) == "0x") BigInteger(hash.drop(2), 16)
... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
def convertToBase58(num):
sb = ''
while (num > 0):
r = num % 58
sb = sb + ALPHABET[r]
num = num // 58;
return sb[::-1]
s = 25420294593250030202636073700053352635053786165627414518
b = convertToBase58(s)
print("... |
import java.math.BigInteger
const val ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
val big0 = BigInteger.ZERO
val big58 = BigInteger.valueOf(58L)
fun convertToBase58(hash: String, base: Int = 16): String {
var x = if (base == 16 && hash.take(2) == "0x") BigInteger(hash.drop(2), 16)
... |
Convert the following code from Python to Scala, ensuring the logic remains intact. | def dList(n, start):
start -= 1
a = range(n)
a[start] = a[0]
a[0] = start
a[1:] = sorted(a[1:])
first = a[1]
r = []
def recurse(last):
if (last == first):
for j,v in enumerate(a[1:]):
if j + 1 == v:
... | typealias Matrix = MutableList<MutableList<Int>>
fun dList(n: Int, sp: Int): Matrix {
val start = sp - 1
val a = generateSequence(0) { it + 1 }.take(n).toMutableList()
a[start] = a[0].also { a[0] = a[start] }
a.subList(1, a.size).sort()
val first = a[1]
val r = mutableListOf<MutableList... |
Keep all operations the same but rewrite the snippet in Scala. | def kosaraju(g):
class nonlocal: pass
size = len(g)
vis = [False]*size
l = [0]*size
nonlocal.x = size
t = [[]]*size
def visit(u):
if not vis[u]:
vis[u] = True
for v in g[u]:
visit(v)
t[v] = t[v] + [u]
non... |
val g = listOf(
intArrayOf(1),
intArrayOf(2),
intArrayOf(0),
intArrayOf(1, 2, 4),
intArrayOf(3, 5),
intArrayOf(2, 6),
intArrayOf(5),
intArrayOf(4, 6, 7)
)
fun kosaraju(g: List<IntArray>): List<List<Int>> {
val size = g.size
... |
Convert this Python block to Scala, preserving its control flow and logic. | import re
from random import shuffle, randint
dirs = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]]
n_rows = 10
n_cols = 10
grid_size = n_rows * n_cols
min_words = 25
class Grid:
def __init__(self):
self.num_attempts = 0
self.cells = [['' for _ in range(n_cols)] for _ in r... |
import java.util.Random
import java.io.File
val dirs = listOf(
intArrayOf( 1, 0), intArrayOf(0, 1), intArrayOf( 1, 1), intArrayOf( 1, -1),
intArrayOf(-1, 0), intArrayOf(0, -1), intArrayOf(-1, -1), intArrayOf(-1, 1)
)
val nRows = 10
val nCols = 10
val gridSize = nRows * nCols
val minWords = 25
val rand = ... |
Convert this Python snippet to Scala and keep its semantics consistent. | import random, sys
def makerule(data, context):
rule = {}
words = data.split(' ')
index = context
for word in words[index:]:
key = ' '.join(words[index-context:index])
if key in rule:
rule[key].append(word)
else:
rule[key] = [word]
index... |
import java.io.File
fun markov(filePath: String, keySize: Int, outputSize: Int): String {
require(keySize >= 1) { "Key size can't be less than 1" }
val words = File(filePath).readText().trimEnd().split(' ')
require(outputSize in keySize..words.size) { "Output size is out of range" }
val dict = muta... |
Translate the given Python code snippet into Scala without altering its behavior. | from collections import Counter
def cumulative_freq(freq):
cf = {}
total = 0
for b in range(256):
if b in freq:
cf[b] = total
total += freq[b]
return cf
def arithmethic_coding(bytes, radix):
freq = Counter(bytes)
cf = cumulative_freq(freq)
... |
import java.math.BigInteger
typealias Freq = Map<Char, Long>
val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
fun cumulativeFreq(freq: Freq): Freq {
var total = 0L
val cf = mutableMapOf<Char, Long>()
for (i in 0..255) {
val c = i.toChar()
val v = freq[c]
if (v != null)... |
Rewrite the snippet below in Scala so it works the same as the original Python code. | import copy, random
def bitcount(n):
return bin(n).count("1")
def reoderingSign(i, j):
k = i >> 1
sum = 0
while k != 0:
sum += bitcount(k & j)
k = k >> 1
return 1.0 if ((sum & 1) == 0) else -1.0
class Vector:
def __init__(self, da):
self.dims = da
def dot(self, ot... | fun bitCount(i: Int): Int {
var j = i
j -= ((j shr 1) and 0x55555555)
j = (j and 0x33333333) + ((j shr 2) and 0x33333333)
j = (j + (j shr 4)) and 0x0F0F0F0F
j += (j shr 8)
j += (j shr 16)
return j and 0x0000003F
}
fun reorderingSign(i: Int, j: Int): Double {
var k = i shr 1
var sum ... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | from string import ascii_uppercase
from itertools import product
from re import findall
def uniq(seq):
seen = {}
return [seen.setdefault(x, x) for x in seq if x not in seen]
def partition(seq, n):
return [seq[i : i + n] for i in xrange(0, len(seq), n)]
def playfair(key, from_ = 'J', to = None):
if ... |
enum class PlayfairOption {
NO_Q,
I_EQUALS_J
}
class Playfair(keyword: String, val pfo: PlayfairOption) {
private val table: Array<CharArray> = Array(5, { CharArray(5) })
init {
val used = BooleanArray(26)
if (pfo == PlayfairOption.NO_Q)
used[16] = true
... |
Preserve the algorithm and functionality while converting the code from Python to Scala. | from string import ascii_uppercase
from itertools import product
from re import findall
def uniq(seq):
seen = {}
return [seen.setdefault(x, x) for x in seq if x not in seen]
def partition(seq, n):
return [seq[i : i + n] for i in xrange(0, len(seq), n)]
def playfair(key, from_ = 'J', to = None):
if ... |
enum class PlayfairOption {
NO_Q,
I_EQUALS_J
}
class Playfair(keyword: String, val pfo: PlayfairOption) {
private val table: Array<CharArray> = Array(5, { CharArray(5) })
init {
val used = BooleanArray(26)
if (pfo == PlayfairOption.NO_Q)
used[16] = true
... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | def _notcell(c):
return '0' if c == '1' else '1'
def eca_infinite(cells, rule):
lencells = len(cells)
rulebits = '{0:08b}'.format(rule)
neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)}
c = cells
while True:
yield c
c = _notcell(c[0])*2 + c + _notcell(c... |
fun evolve(l: Int, rule: Int) {
println(" Rule #$rule:")
var cells = StringBuilder("*")
for (x in 0 until l) {
addNoCells(cells)
val width = 40 + (cells.length shr 1)
println(cells.padStart(width))
cells = step(cells, rule)
}
}
fun step(cells: StringBuilder, rule: Int)... |
Translate the given Python code snippet into Scala without altering its behavior. |
from itertools import (chain)
def stringParse(lexicon):
return lambda s: Node(s)(
tokenTrees(lexicon)(s)
)
def tokenTrees(wds):
def go(s):
return [Node(s)([])] if s in wds else (
concatMap(nxt(s))(wds)
)
def nxt(s):
return lambda w: parse(
... |
import java.io.File
val partitions = mutableListOf<List<String>>()
fun partitionString(s: String, ml: MutableList<String>, level: Int) {
for (i in s.length - 1 downTo 1) {
val part1 = s.substring(0, i)
val part2 = s.substring(i)
ml.add(part1)
ml.add(part2)
partitions.add(... |
Convert the following code from Python to Scala, ensuring the logic remains intact. | from collections import UserDict
import copy
class Dict(UserDict):
def __init__(self, dict=None, **kwargs):
self.__init = True
super().__init__(dict, **kwargs)
self.default = copy.deepcopy(self.data)
self.__init = False
def __delitem__(self, key):
if key in sel... |
fun main(args: Array<String>) {
val map = mapOf('A' to 65, 'B' to 66, 'C' to 67)
println(map)
}
|
Produce a functionally identical Scala code for the snippet given in Python. | from math import pi, sin, cos
from collections import namedtuple
from random import random, choice
from copy import copy
try:
import psyco
psyco.full()
except ImportError:
pass
FLOAT_MAX = 1e100
class Point:
__slots__ = ["x", "y", "group"]
def __init__(self, x=0.0, y=0.0, group=0):
self... |
import java.util.Random
import kotlin.math.*
data class Point(var x: Double, var y: Double, var group: Int)
typealias LPoint = List<Point>
typealias MLPoint = MutableList<Point>
val origin get() = Point(0.0, 0.0, 0)
val r = Random()
val hugeVal = Double.POSITIVE_INFINITY
const val RAND_MAX = Int.MAX_VALUE
const v... |
Transform the following Python implementation into Scala, maintaining the same output and logic. | hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))
bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))
def float_dec2bin(d):
neg = False
if d < 0:
d = -d
neg = True
hx = float(d).hex()
p = hx.index('p')
bn = ''.join(hex2bin.get(char, char) for char i... |
fun decToBin(d: Double): String {
val whole = Math.floor(d).toLong()
var binary = whole.toString(2) + "."
var dd = d - whole
while (dd > 0.0) {
val r = dd * 2.0
if (r >= 1.0) {
binary += "1"
dd = r - 1
}
else {
binary += "0"
... |
Generate a Scala translation of this Python snippet without changing its computational steps. | hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))
bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))
def float_dec2bin(d):
neg = False
if d < 0:
d = -d
neg = True
hx = float(d).hex()
p = hx.index('p')
bn = ''.join(hex2bin.get(char, char) for char i... |
fun decToBin(d: Double): String {
val whole = Math.floor(d).toLong()
var binary = whole.toString(2) + "."
var dd = d - whole
while (dd > 0.0) {
val r = dd * 2.0
if (r >= 1.0) {
binary += "1"
dd = r - 1
}
else {
binary += "0"
... |
Write a version of this Python function in Scala with identical behavior. | from itertools import imap, imap, groupby, chain, imap
from operator import itemgetter
from sys import argv
from array import array
def concat_map(func, it):
return list(chain.from_iterable(imap(func, it)))
def minima(poly):
return (min(pt[0] for pt in poly), min(pt[1] for pt in poly))
def translate_to_... |
class Point(val x: Int, val y: Int) : Comparable<Point> {
fun rotate90() = Point( this.y, -this.x)
fun rotate180() = Point(-this.x, -this.y)
fun rotate270() = Point(-this.y, this.x)
fun reflect() = Point(-this.x, this.y)
override fun equals(other: Any?): Boolean {
if (other == null |... |
Port the following code from Python to Scala with equivalent syntax and logic. |
from itertools import groupby
from unicodedata import decomposition, name
from pprint import pprint as pp
commonleaders = ['the']
replacements = {u'ß': 'ss',
u'ſ': 's',
u'ʒ': 's',
}
hexdigits = set('0123456789abcdef')
decdigits = set('0123456789')
def splitch... |
val r2 = Regex("""[ ]{2,}""")
val r3 = Regex("""\s""")
val r5 = Regex("""\d+""")
val ucAccented = arrayOf("ÀÁÂÃÄÅ", "Ç", "ÈÉÊË", "ÌÍÎÏ", "Ñ", "ÒÓÔÕÖØ", "ÙÚÛÜ", "ÝŸ")
val lcAccented = arrayOf("àáâãäå", "ç", "èéêë", "ìíîï", "ñ", "òóôõöø", "ùúûü", "ýÿ")
val ucNormal = "ACEINOUY"
val lcNormal = "aceinouy"
val ucL... |
Convert this Python snippet to Scala and keep its semantics consistent. | def ownCalcPass (password, nonce, test=False) :
start = True
num1 = 0
num2 = 0
password = int(password)
if test:
print("password: %08x" % (password))
for c in nonce :
if c != "0":
if start:
num2 = password
start = False
if test:... |
fun ownCalcPass(password: Long, nonce: String): Long {
val m1 = 0xFFFF_FFFFL
val m8 = 0xFFFF_FFF8L
val m16 = 0xFFFF_FFF0L
val m128 = 0xFFFF_FF80L
val m16777216 = 0xFF00_0000L
var flag = true
var num1 = 0L
var num2 = 0L
for (c in nonce) {
num2 = nu... |
Write the same code in Scala as shown below in Python. | import math
import random
INFINITY = 1 << 127
MAX_INT = 1 << 31
class Parameters:
def __init__(self, omega, phip, phig):
self.omega = omega
self.phip = phip
self.phig = phig
class State:
def __init__(self, iter, gbpos, gbval, min, max, parameters, pos, vel, bpos, bval, nParticles, nDi... |
import java.util.Random
typealias Func = (DoubleArray) -> Double
class Parameters(val omega: Double, val phip: Double, val phig: Double)
class State(
val iter: Int,
val gbpos: DoubleArray,
val gbval: Double,
val min: DoubleArray,
val max: DoubleArray,
val parameters: Parameters,
val pos... |
Produce a language-to-language conversion: from Python to Scala, same semantics. |
def DrawBoard(board):
peg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
for n in xrange(1,16):
peg[n] = '.'
if n in board:
peg[n] = "%X" % n
print " %s" % peg[1]
print " %s %s" % (peg[2],peg[3])
print " %s %s %s" % (peg[4],peg[5],peg[6])
print " %s %s %s %s" % (peg[7],peg[8],peg[9],peg[10])... |
data class Solution(val peg: Int, val over: Int, val land: Int)
var board = BooleanArray(16) { if (it == 0) false else true }
val jumpMoves = listOf(
listOf(),
listOf( 2 to 4, 3 to 6),
listOf( 4 to 7, 5 to 9),
listOf( 5 to 8, 6 to 10),
listOf( 2 to 1, 5 to 6, 7 to 11, 8 to 13),
... |
Convert this Python block to Scala, preserving its control flow and logic. | from __future__ import print_function
from __future__ import division
def extended_synthetic_division(dividend, divisor):
out = list(dividend)
normalizer = divisor[0]
for i in xrange(len(dividend)-(len(divisor)-1)):
out[i] /= normalizer
coef... |
fun extendedSyntheticDivision(dividend: IntArray, divisor: IntArray): Pair<IntArray, IntArray> {
val out = dividend.copyOf()
val normalizer = divisor[0]
val separator = dividend.size - divisor.size + 1
for (i in 0 until separator) {
out[i] /= normalizer
val coef = out[i]
if (co... |
Preserve the algorithm and functionality while converting the code from Python to Scala. | from __future__ import print_function
from __future__ import division
def extended_synthetic_division(dividend, divisor):
out = list(dividend)
normalizer = divisor[0]
for i in xrange(len(dividend)-(len(divisor)-1)):
out[i] /= normalizer
coef... |
fun extendedSyntheticDivision(dividend: IntArray, divisor: IntArray): Pair<IntArray, IntArray> {
val out = dividend.copyOf()
val normalizer = divisor[0]
val separator = dividend.size - divisor.size + 1
for (i in 0 until separator) {
out[i] /= normalizer
val coef = out[i]
if (co... |
Write the same algorithm in Scala as shown in this Python implementation. | size(300, 300)
background(0)
radius = min(width, height) / 2.0
cx, cy = width / 2, width / 2
for x in range(width):
for y in range(height):
rx = x - cx
ry = y - cy
s = sqrt(rx ** 2 + ry ** 2) / radius
if s <= 1.0:
h = ((atan2(ry, rx) / PI) + 1.0) /... |
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
import kotlin.math.*
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val... |
Produce a language-to-language conversion: from Python to Scala, same semantics. | import random
TRAINING_LENGTH = 2000
class Perceptron:
def __init__(self,n):
self.c = .01
self.weights = [random.uniform(-1.0, 1.0) for _ in range(n)]
def feed_forward(self, inputs):
weighted_inputs = []
for i in range(len(inputs)):
weighted_inputs.append(inpu... |
import java.awt.*
import java.awt.event.ActionEvent
import java.util.Random
import javax.swing.JPanel
import javax.swing.JFrame
import javax.swing.Timer
import javax.swing.SwingUtilities
class Perceptron(n: Int) : JPanel() {
class Trainer(x: Double, y: Double, val answer: Int) {
val inputs = doubleArray... |
Please provide an equivalent version of this Python code in Scala. |
import datetime
import re
import urllib.request
import sys
def get(url):
with urllib.request.urlopen(url) as response:
html = response.read().decode('utf-8')
if re.match(r'<!Doctype HTML[\s\S]*<Title>URL Not Found</Title>', html):
return None
return html
def main():
template = 'http://... | import java.net.Socket
import java.net.URL
import java.time
import java.time.format
import java.time.ZoneId
import java.util.Scanner
import scala.collection.JavaConverters._
def get(rawUrl: String): List[String] = {
val url = new URL(rawUrl)
val port = if (url.getPort > -1) url.getPort else 80
val sock = n... |
Maintain the same structure and functionality when rewriting this code in Scala. |
from __future__ import annotations
import functools
import gzip
import json
import logging
import platform
import re
from collections import Counter
from collections import defaultdict
from typing import Any
from typing import Iterator
from typing import Iterable
from typing import List
from typing import Mapping
... | import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.util.regex.Pattern
import java.util.stream.Collectors
const val BASE = "http:
fun main() {
val client = HttpClient.newBuilder().build()
val titleUri = URI.create("$BASE/mw/api.ph... |
Ensure the translated Scala code behaves exactly like the original Python snippet. |
from __future__ import print_function
import lxml
from lxml import etree
if __name__=="__main__":
parser = etree.XMLParser(dtd_validation=True)
schema_root = etree.XML()
schema = etree.XMLSchema(schema_root)
parser = etree.XMLParser(schema = schema)
try:
root = etree.fromstring("<a>5</a>", parser)
print ... |
import kotlinx.cinterop.*
import platform.posix.*
import libxml_schemas.*
fun err(ctx: COpaquePointer?, msg: CPointer<ByteVar>?, extra: CPointer<ByteVar>?) {
val fp = ctx?.reinterpret<FILE>()
fprintf(fp, msg?.toKString(), extra?.toKString())
}
fun warn(ctx: COpaquePointer?, msg: CPointer<ByteVar>?, extra: C... |
Port the following code from Python to Scala with equivalent syntax and logic. | from itertools import count, islice
from _pydecimal import getcontext, Decimal
def metallic_ratio(b):
m, n = 1, 1
while True:
yield m, n
m, n = m*b + n, m
def stable(b, prec):
def to_decimal(b):
for m,n in metallic_ratio(b):
yield Decimal(m)/Decimal(n)
getcontext()... | import java.math.BigDecimal
import java.math.BigInteger
val names = listOf("Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead")
fun lucas(b: Long) {
println("Lucas sequence for ${names[b.toInt()]} ratio, where b = $b:")
print("First 15 elements: ")
var x0 = 1L
... |
Maintain the same structure and functionality when rewriting this code in Scala. | from itertools import count, islice
from _pydecimal import getcontext, Decimal
def metallic_ratio(b):
m, n = 1, 1
while True:
yield m, n
m, n = m*b + n, m
def stable(b, prec):
def to_decimal(b):
for m,n in metallic_ratio(b):
yield Decimal(m)/Decimal(n)
getcontext()... | import java.math.BigDecimal
import java.math.BigInteger
val names = listOf("Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead")
fun lucas(b: Long) {
println("Lucas sequence for ${names[b.toInt()]} ratio, where b = $b:")
print("First 15 elements: ")
var x0 = 1L
... |
Write a version of this Python function in Scala with identical behavior. | class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class SLinkedList:
def __init__(self):
self.head = None
def insert_first(self, insert_this):
new_node = Node(insert_this)
new_node.next = self.head
self.head = new_node
def re... |
class Node<T: Number>(var data: T, var next: Node<T>? = null) {
override fun toString(): String {
val sb = StringBuilder(this.data.toString())
var node = this.next
while (node != null) {
sb.append(" -> ", node.data.toString())
node = node.next
}
retu... |
Port the provided Python code into Scala while preserving the original functionality. |
IP = (
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7
)
IP_INV = (
40, 8, 48, 1... |
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
fun String.toHexByteArray(): ByteArray {
val bytes = ByteArray(this.length / 2)
for (i in 0 until bytes.size) {
bytes[i] = this.substring(i * 2, i * 2 + 2).toInt(16).toByte()
}
return bytes
}
fun ByteArray.printHexBytes... |
Rewrite the snippet below in Scala so it works the same as the original Python code. |
from __future__ import annotations
import functools
import math
import os
from typing import Any
from typing import Callable
from typing import Generic
from typing import List
from typing import TypeVar
from typing import Union
T = TypeVar("T")
class Writer(Generic[T]):
def __init__(self, value: Union[T, Wri... |
import kotlin.math.sqrt
class Writer<T : Any> private constructor(val value: T, s: String) {
var log = " ${s.padEnd(17)}: $value\n"
private set
fun bind(f: (T) -> Writer<T>): Writer<T> {
val new = f(this.value)
new.log = this.log + new.log
return new
}
companion obj... |
Generate an equivalent Scala version of this Python code. | from itertools import combinations_with_replacement as cmbr
from time import time
def dice_gen(n, faces, m):
dice = list(cmbr(faces, n))
succ = [set(j for j, b in enumerate(dice)
if sum((x>y) - (x<y) for x in a for y in b) > 0)
for a in dice]
def loops(seq):
... | fun fourFaceCombos(): List<Array<Int>> {
val res = mutableListOf<Array<Int>>()
val found = mutableSetOf<Int>()
for (i in 1..4) {
for (j in 1..4) {
for (k in 1..4) {
for (l in 1..4) {
val c = arrayOf(i, j, k, l)
c.sort()
... |
Generate an equivalent Scala version of this Python code. | Plataanstraat 5 split as (Plataanstraat, 5)
Straat 12 split as (Straat, 12)
Straat 12 II split as (Straat, 12 II)
Dr. J. Straat 12 split as (Dr. J. Straat , 12)
Dr. J. Straat 12 a split as (Dr. J. Straat, 12 a)
Dr. J. Straat 12-14 split as (Dr. J. Straat, 12... |
val r = Regex("""\s+""")
fun separateHouseNumber(address: String): Pair<String, String> {
val street: String
val house: String
val len = address.length
val splits = address.split(r)
val size = splits.size
val last = splits[size - 1]
val penult = splits[size - 2]
if (last[0] in... |
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically? | import numpy as np
from numpy.linalg import inv
a = np.array([[1., 2., 3.], [4., 1., 6.],[ 7., 8., 9.]])
ainv = inv(a)
print(a)
print(ainv)
|
typealias Matrix = Array<DoubleArray>
fun Matrix.inverse(): Matrix {
val len = this.size
require(this.all { it.size == len }) { "Not a square matrix" }
val aug = Array(len) { DoubleArray(2 * len) }
for (i in 0 until len) {
for (j in 0 until len) aug[i][j] = this[i][j]
aug[i][... |
Convert this Python block to Scala, preserving its control flow and logic. | import numpy as np
from numpy.linalg import inv
a = np.array([[1., 2., 3.], [4., 1., 6.],[ 7., 8., 9.]])
ainv = inv(a)
print(a)
print(ainv)
|
typealias Matrix = Array<DoubleArray>
fun Matrix.inverse(): Matrix {
val len = this.size
require(this.all { it.size == len }) { "Not a square matrix" }
val aug = Array(len) { DoubleArray(2 * len) }
for (i in 0 until len) {
for (j in 0 until len) aug[i][j] = this[i][j]
aug[i][... |
Convert the following code from Python to Scala, ensuring the logic remains intact. |
import math
import collections
triple = collections.namedtuple('triple', 'm fm simp')
def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:
m = a + (b - a) / 2
fm = f(m)
simp = abs(b - a) / 6 * (fa + 4*fm + fb)
return triple(m, fm, simp,)
def _quad_asr(f: ca... |
import kotlin.math.abs
import kotlin.math.sin
typealias F = (Double) -> Double
typealias T = Triple<Double, Double, Double>
fun quadSimpsonsMem(f: F, a: Double, fa: Double, b: Double, fb: Double): T {
val m = (a + b) / 2
val fm = f(m)
val simp = abs(b - a) / 6 * (fa + 4 * fm + fb)
return T(m, ... |
Transform the following Python implementation into Scala, maintaining the same output and logic. |
import math
import collections
triple = collections.namedtuple('triple', 'm fm simp')
def _quad_simpsons_mem(f: callable, a: float , fa: float, b: float, fb: float)->tuple:
m = a + (b - a) / 2
fm = f(m)
simp = abs(b - a) / 6 * (fa + 4*fm + fb)
return triple(m, fm, simp,)
def _quad_asr(f: ca... |
import kotlin.math.abs
import kotlin.math.sin
typealias F = (Double) -> Double
typealias T = Triple<Double, Double, Double>
fun quadSimpsonsMem(f: F, a: Double, fa: Double, b: Double, fb: Double): T {
val m = (a + b) / 2
val fm = f(m)
val simp = abs(b - a) / 6 * (fa + 4 * fm + fb)
return T(m, ... |
Maintain the same structure and functionality when rewriting this code in Scala. | import random
board = [[" " for x in range(8)] for y in range(8)]
piece_list = ["R", "N", "B", "Q", "P"]
def place_kings(brd):
while True:
rank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)
diff_list = [abs(rank_white - rank_black)... |
import java.util.Random
import kotlin.math.abs
val rand = Random()
val grid = List(8) { CharArray(8) }
const val NUL = '\u0000'
fun createFen(): String {
placeKings()
placePieces("PPPPPPPP", true)
placePieces("pppppppp", true)
placePieces("RNBQBNR", false)
placePieces("rnbqbnr", false)
ret... |
Transform the following Python implementation into Scala, maintaining the same output and logic. |
from math import prod
def superFactorial(n):
return prod([prod(range(1,i+1)) for i in range(1,n+1)])
def hyperFactorial(n):
return prod([i**i for i in range(1,n+1)])
def alternatingFactorial(n):
return sum([(-1)**(n-i)*prod(range(1,i+1)) for i in range(1,n+1)])
def exponentialFactorial(n):
if n in... | import java.math.BigInteger
import java.util.function.Function
fun factorial(n: Int): BigInteger {
val bn = BigInteger.valueOf(n.toLong())
var result = BigInteger.ONE
var i = BigInteger.TWO
while (i <= bn) {
result *= i++
}
return result
}
fun inverseFactorial(f: BigInteger): Int {
... |
Convert this Python block to Scala, preserving its control flow and logic. | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return NULL
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right =... | package xyz.hyperreal.rosettacodeCompiler
import scala.collection.mutable
import scala.io.Source
object ASTInterpreter {
def fromStdin = fromSource(Source.stdin)
def fromString(src: String) = fromSource(Source.fromString(src))
def fromSource(s: Source) = {
val lines = s.getLines
def load: Node =
... |
Ensure the translated Scala code behaves exactly like the original Python snippet. | def load_ast()
line = readline()
line_list = tokenize the line, respecting double quotes
text = line_list[0]
if text == ";"
return NULL
node_type = text
if len(line_list) > 1
return make_leaf(node_type, line_list[1])
left = load_ast()
right =... | package xyz.hyperreal.rosettacodeCompiler
import scala.collection.mutable
import scala.io.Source
object ASTInterpreter {
def fromStdin = fromSource(Source.stdin)
def fromString(src: String) = fromSource(Source.fromString(src))
def fromSource(s: Source) = {
val lines = s.getLines
def load: Node =
... |
Generate a Scala translation of this Python snippet without changing its computational steps. | import numpy as np
import scipy as sp
import scipy.stats
def welch_ttest(x1, x2):
n1 = x1.size
n2 = x2.size
m1 = np.mean(x1)
m2 = np.mean(x2)
v1 = np.var(x1, ddof=1)
v2 = np.var(x2, ddof=1)
t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)
df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - ... |
typealias Func = (Double) -> Double
fun square(d: Double) = d * d
fun sampleVar(da: DoubleArray): Double {
if (da.size < 2) throw IllegalArgumentException("Array must have at least 2 elements")
val m = da.average()
return da.map { square(it - m) }.sum() / (da.size - 1)
}
fun welch(da1: DoubleArray, da2... |
Change the following Python code into Scala without altering its purpose. | import numpy as np
import scipy as sp
import scipy.stats
def welch_ttest(x1, x2):
n1 = x1.size
n2 = x2.size
m1 = np.mean(x1)
m2 = np.mean(x2)
v1 = np.var(x1, ddof=1)
v2 = np.var(x2, ddof=1)
t = (m1 - m2) / np.sqrt(v1 / n1 + v2 / n2)
df = (v1 / n1 + v2 / n2)**2 / (v1**2 / (n1**2 * (n1 - ... |
typealias Func = (Double) -> Double
fun square(d: Double) = d * d
fun sampleVar(da: DoubleArray): Double {
if (da.size < 2) throw IllegalArgumentException("Array must have at least 2 elements")
val m = da.average()
return da.map { square(it - m) }.sum() / (da.size - 1)
}
fun welch(da1: DoubleArray, da2... |
Translate the given Python code snippet into Scala without altering its behavior. |
import inflect
def count_letters(word):
count = 0
for letter in word:
if letter != ',' and letter !='-' and letter !=' ':
count += 1
return count
def split_with_spaces(sentence):
sentence_list = []
curr_word = ""
for c in sentence:
if... |
val names = mapOf(
1 to "one",
2 to "two",
3 to "three",
4 to "four",
5 to "five",
6 to "six",
7 to "seven",
8 to "eight",
9 to "nine",
10 to "ten",
11 to "eleven",
12 to "twelve",
13 to "thirteen",
14 to "fourteen",
15 to "fifteen",
16 to "sixteen",
... |
Write the same algorithm in Scala as shown in this Python implementation. | import collections
def MostFreqKHashing(inputString, K):
occuDict = collections.defaultdict(int)
for c in inputString:
occuDict[c] += 1
occuList = sorted(occuDict.items(), key = lambda x: x[1], reverse = True)
outputStr = ''.join(c + str(cnt) for c, cnt in occuList[:K])
return outputStr
d... |
fun mostFreqKHashing(input: String, k: Int): String =
input.groupBy { it }.map { Pair(it.key, it.value.size) }
.sortedByDescending { it.second }
.take(k)
.fold("") { acc, v -> acc + "${v.first}${v.second.toChar()}" }
fun mostFreqKSimilarit... |
Translate this program into Scala but keep the logic exactly as in Python. |
import argparse
import itertools
import pathlib
import re
import secrets
import sys
MAGIC = "
def make_keys(n, size):
return (secrets.token_hex(size) for _ in range(n))
def make_pad(name, pad_size, key_size):
pad = [
MAGIC,
f"
f"
*make_keys(pad_s... |
import java.io.File
import java.security.SecureRandom
const val CHARS_PER_LINE = 48
const val CHUNK_SIZE = 6
const val COLS = 8
const val DEMO = true
enum class FileType { OTP, ENC, DEC }
fun Char.isAlpha() = this in 'A'..'Z'
fun String.toAlpha() = this.filter { it.isAlpha() }
fun String.isOtpRelated() = endsW... |
Produce a functionally identical Scala code for the snippet given in Python. |
import argparse
import itertools
import pathlib
import re
import secrets
import sys
MAGIC = "
def make_keys(n, size):
return (secrets.token_hex(size) for _ in range(n))
def make_pad(name, pad_size, key_size):
pad = [
MAGIC,
f"
f"
*make_keys(pad_s... |
import java.io.File
import java.security.SecureRandom
const val CHARS_PER_LINE = 48
const val CHUNK_SIZE = 6
const val COLS = 8
const val DEMO = true
enum class FileType { OTP, ENC, DEC }
fun Char.isAlpha() = this in 'A'..'Z'
fun String.toAlpha() = this.filter { it.isAlpha() }
fun String.isOtpRelated() = endsW... |
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically? | from itertools import zip_longest
fc2 =
NAME, WT, COV = 0, 1, 2
def right_type(txt):
try:
return float(txt)
except ValueError:
return txt
def commas_to_list(the_list, lines, start_indent=0):
for n, line in lines:
indent = 0
while line.startswith(' ' * (4 * indent))... |
class FCNode(val name: String, val weight: Int = 1, coverage: Double = 0.0) {
var coverage = coverage
set(value) {
if (field != value) {
field = value
if (parent != null) parent!!.updateCoverage()
}
}
val children = mutabl... |
Can you help me rewrite this code in Scala instead of Python, keeping it the same logically? | Python 3.2 (r32:88445, Feb 20 2011, 21:30:00) [MSC v.1500 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import __future__
>>> __future__.all_feature_names
['nested_scopes', 'generators', 'division', 'absolute_import', 'with_statement', 'print_function', 'unicode_literals'... |
@Suppress("UNUSED_VARIABLE")
fun main(args: Array<String>) {
val s = "To be suppressed"
}
|
Please provide an equivalent version of this Python code in Scala. |
HW = r
def snusp(store, code):
ds = bytearray(store)
dp = 0
cs = code.splitlines()
ipr, ipc = 0, 0
for r, row in enumerate(cs):
try:
ipc = row.index('$')
ipr = r
break
except ValueError:
pass
rt, dn, l... |
const val hw = """
/++++!/===========?\>++.>+.+++++++..+++\
\+++\ | /+>+++++++>/ /++++++++++<<.++>./
$+++/ | \+++++++++>\ \+++++.>.+++.-----\
\==-<<<<+>+++/ /=.>.+>.--------.-/"""
fun snusp(dlen: Int, raw: String) {
val ds = CharArray(dlen)
var dp = 0
var s = raw
s = s... |
Generate an equivalent Scala version of this Python code. | try:
from functools import reduce
except: pass
def topx(data, tops=None):
'Extract the set of top-level(s) in topological order'
for k, v in data.items():
v.discard(k)
if tops is None:
tops = toplevels(data)
return _topx(data, tops, [], set())
def _topx(data, tops, _sofar, _sofar... |
import java.util.LinkedList
val s = "top1, top2, ip1, ip2, ip3, ip1a, ip2a, ip2b, ip2c, ipcommon, des1, " +
"des1a, des1b, des1c, des1a1, des1a2, des1c1, extra1"
val deps = mutableListOf(
0 to 10, 0 to 2, 0 to 3,
1 to 10, 1 to 3, 1 to 4,
2 to 17, 2 to 5, 2 to 9,
3 to 6, 3 to 7, 3 to 8, 3 to ... |
Maintain the same structure and functionality when rewriting this code in Scala. | try:
from functools import reduce
except: pass
def topx(data, tops=None):
'Extract the set of top-level(s) in topological order'
for k, v in data.items():
v.discard(k)
if tops is None:
tops = toplevels(data)
return _topx(data, tops, [], set())
def _topx(data, tops, _sofar, _sofar... |
import java.util.LinkedList
val s = "top1, top2, ip1, ip2, ip3, ip1a, ip2a, ip2b, ip2c, ipcommon, des1, " +
"des1a, des1b, des1c, des1a1, des1a2, des1c1, extra1"
val deps = mutableListOf(
0 to 10, 0 to 2, 0 to 3,
1 to 10, 1 to 3, 1 to 4,
2 to 17, 2 to 5, 2 to 9,
3 to 6, 3 to 7, 3 to 8, 3 to ... |
Rewrite this program in Scala while keeping its functionality equivalent to the Python version. | def main():
resources = int(input("Cantidad de recursos: "))
processes = int(input("Cantidad de procesos: "))
max_resources = [int(i) for i in input("Recursos máximos: ").split()]
print("\n-- recursos asignados para cada proceso --")
currently_allocated = [[int(i) for i in input(f"proceso {j + 1}:... |
fun main(args: Array<String>) {
print("Enter the number of resources: ")
val r = readLine()!!.toInt()
print("\nEnter the number of processes: ")
val p = readLine()!!.toInt()
print("\nEnter Claim Vector: ")
val maxRes = readLine()!!.split(' ').map { it.toInt() } .toIntArray()
println("\n... |
Transform the following Python implementation into Scala, maintaining the same output and logic. | def penrose(depth):
print( <g id="A{d+1}" transform="translate(100, 0) scale(0.6180339887498949)">
<use href="
<use href="
</g>
<g id="B{d+1}">
<use href="
<use href="
</g> <g id="G">
<use href="
<use href="
</g>
</defs>
<g transform="scale(2, 2)">
<use href="
<use href="
<use href="
<use hr... |
import java.awt.*
import java.awt.geom.Path2D
import javax.swing.*
class PenroseTiling(w: Int, h: Int) : JPanel() {
private enum class Type {
KITE, DART
}
private class Tile(
val type: Type,
val x: Double,
val y: Double,
val angle: Double,
val size: Do... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | from itertools import count, islice
import numpy as np
from numpy import sin, cos, pi
ANGDIV = 12
ANG = 2*pi/ANGDIV
def draw_all(sols):
import matplotlib.pyplot as plt
def draw_track(ax, s):
turn, xend, yend = 0, [0], [0]
for d in s:
x0, y0 = xend[-1], yend[-1]
a = t... |
const val RIGHT = 1
const val LEFT = -1
const val STRAIGHT = 0
fun normalize(tracks: IntArray): String {
val size = tracks.size
val a = CharArray(size) { "abc"[tracks[it] + 1] }
var norm = String(a)
repeat(size) {
val s = String(a)
if (s < norm) norm = s
val tmp = a[0]
... |
Write the same algorithm in Scala as shown in this Python implementation. | import httplib
connection = httplib.HTTPSConnection('www.example.com',cert_file='myCert.PEM')
connection.request('GET','/index.html')
response = connection.getresponse()
data = response.read()
|
import java.security.KeyStore
import javax.net.ssl.KeyManagerFactory
import javax.net.ssl.SSLContext
import javax.net.ssl.HttpsURLConnection
import java.net.URL
import java.io.FileInputStream
import java.io.InputStreamReader
import java.io.BufferedReader
fun getSSLContext(p12Path: String, password: String): SSLConte... |
Rewrite the snippet below in Scala so it works the same as the original Python code. | import mysql.connector
import hashlib
import sys
import random
DB_HOST = "localhost"
DB_USER = "devel"
DB_PASS = "devel"
DB_NAME = "test"
def connect_db():
try:
return mysql.connector.connect(host=DB_HOST, user=DB_USER, passwd=DB_PASS, db=DB_NAME)
except:
return ... |
import java.sql.Connection
import java.sql.DriverManager
import java.sql.ResultSet
import java.security.MessageDigest
import java.security.SecureRandom
import java.math.BigInteger
class UserManager {
private lateinit var dbConnection: Connection
private fun md5(message: String): String {
val hexStri... |
Convert the following code from Python to Scala, ensuring the logic remains intact. |
from PIL import Image
im = Image.open("boxes_1.ppm")
im.save("boxes_1.jpg")
|
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image... |
Translate this program into Scala but keep the logic exactly as in Python. | from collections import defaultdict
def from_edges(edges):
class Node:
def __init__(self):
self.root = None
self.succ = []
nodes = defaultdict(Node)
for v,w in edges:
nodes[v].succ.append(nodes[w])
for i... |
import java.util.Stack
typealias Nodes = List<Node>
class Node(val n: Int) {
var index = -1
var lowLink = -1
var onStack = false
override fun toString() = n.toString()
}
class DirectedGraph(val vs: Nodes, val es: Map<Node, Nodes>)
fun tarjan(g: DirectedGraph): List<Nodes> {
val sccs = mu... |
Keep all operations the same but rewrite the snippet in Scala. | from itertools import product
minos = (((197123, 7, 6), (1797, 6, 7), (1287, 6, 7), (196867, 7, 6)),
((263937, 6, 6), (197126, 6, 6), (393731, 6, 6), (67332, 6, 6)),
((16843011, 7, 5), (2063, 5, 7), (3841, 5, 7), (271, 5, 7), (3848, 5, 7), (50463234, 7, 5), (50397441, 7, 5), (33686019, 7, 5)),
... |
import java.util.Random
val F = arrayOf(
intArrayOf(1, -1, 1, 0, 1, 1, 2, 1), intArrayOf(0, 1, 1, -1, 1, 0, 2, 0),
intArrayOf(1, 0, 1, 1, 1, 2, 2, 1), intArrayOf(1, 0, 1, 1, 2, -1, 2, 0),
intArrayOf(1, -2, 1, -1, 1, 0, 2, -1), intArrayOf(0, 1, 1, 1, 1, 2, 2, 1),
intArrayOf(1, -1, 1, 0, 1, 1, 2, -1),... |
Change the programming language of this snippet from Python to Scala without modifying what it does. | class FibonacciHeap:
class Node:
def __init__(self, data):
self.data = data
self.parent = self.child = self.left = self.right = None
self.degree = 0
self.mark = False
def iterate(self, head):
node = stop = head
f... |
class Node<V : Comparable<V>>(var value: V) {
var parent: Node<V>? = null
var child: Node<V>? = null
var prev: Node<V>? = null
var next: Node<V>? = null
var rank = 0
var mark = false
fun meld1(node: Node<V>) {
this.prev?.next = node
node.prev = this.prev
node.... |
Convert the following code from C++ to Haskell, ensuring the logic remains intact. | #include <concepts>
#include <iostream>
void PrintMatrix(std::predicate<int, int, int> auto f, int size)
{
for(int y = 0; y < size; y++)
{
for(int x = 0; x < size; x++)
{
std::cout << " " << f(x, y, size);
}
std::cout << "\n";
}
std::cout << "\n";
}
int main()
{
auto diagonals = [... |
twoDiagonalMatrix :: Int -> [[Int]]
twoDiagonalMatrix n = flip (fmap . go) xs <$> xs
where
xs = [1 .. n]
go x y
| y == x = 1
| y == succ (subtract x n) = 1
| otherwise = 0
main :: IO ()
main =
mapM_ putStrLn $
unlines . fmap (((' ' :) . show) =<<)
. twoDiagonalMatrix
<$... |
Rewrite this program in Haskell while keeping its functionality equivalent to the C++ version. | #include <iostream>
#include <fstream>
int main() {
std::string word;
std::ifstream file("unixdict.txt");
if (!file) {
std::cerr << "Cannot open unixdict.txt" << std::endl;
return -1;
}
while (file >> word) {
if (word.length() > 11 && word.find("the") != std::string::npos)... | import System.IO (readFile)
import Data.List (isInfixOf)
main = do
txt <- readFile "unixdict.txt"
let res = [ w | w <- lines txt, isInfixOf "the" w, length w > 11 ]
putStrLn $ show (length res) ++ " words were found:"
mapM_ putStrLn res
|
Convert this C++ snippet to Haskell and keep its semantics consistent. | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
std::string lcs(const std::vector<std::string>& strs) {
std::vector<std::string::const_reverse_iterator> backs;
std::string s;
if (strs.size() == 0) return "";
if (strs.size() == 1) return strs[0];
for (auto& str... | import Data.List (transpose)
longestCommonSuffix :: [String] -> String
longestCommonSuffix =
foldr (flip (<>) . return . head) [] .
takeWhile (all =<< (==) . head) . transpose . fmap reverse
main :: IO ()
main =
mapM_
(putStrLn . longestCommonSuffix)
[ [ "Sunday"
, "Monday"
, "Tuesday"
... |
Convert this C++ block to Haskell, preserving its control flow and logic. | #include <iostream>
#include <set>
#include <cmath>
int main() {
std::set<int> values;
for (int a=2; a<=5; a++)
for (int b=2; b<=5; b++)
values.insert(std::pow(a, b));
for (int i : values)
std::cout << i << " ";
std::cout << std::endl;
return 0;
}
| import qualified Data.Set as S
distinctPowerNumbers :: Int -> Int -> [Int]
distinctPowerNumbers a b =
(S.elems . S.fromList) $
(fmap (^) >>= (<*>)) [a .. b]
main :: IO ()
main =
print $
distinctPowerNumbers 2 5
|
Maintain the same structure and functionality when rewriting this code in Haskell. | #include <iostream>
#include <map>
int main() {
const char* strings[] = {"133252abcdeeffd", "a6789798st", "yxcdfgxcyz"};
std::map<char, int> count;
for (const char* str : strings) {
for (; *str; ++str)
++count[*str];
}
for (const auto& p : count) {
if (p.second == 1)
... | import Data.List (group, sort)
uniques :: [String] -> String
uniques ks =
[c | (c : cs) <- (group . sort . concat) ks, null cs]
main :: IO ()
main =
putStrLn $
uniques
[ "133252abcdeeffd",
"a6789798st",
"yxcdfgxcyz"
]
|
Port the following code from C++ to Haskell with equivalent syntax and logic. | #include <algorithm>
#include <iostream>
template <class T>
class AVLnode {
public:
T key;
int balance;
AVLnode *left, *right, *parent;
AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),
left(NULL), right(NULL) {}
~AVLnode() {
delete left;
delete ri... | data Tree a
= Leaf
| Node
Int
(Tree a)
a
(Tree a)
deriving (Show, Eq)
foldTree :: Ord a => [a] -> Tree a
foldTree = foldr insert Leaf
height :: Tree a -> Int
height Leaf = -1
height (Node h _ _ _) = h
depth :: Tree a -> Tree a -> Int
depth a b = succ (max (height a) (height b))
ins... |
Port the provided C++ code into Haskell while preserving the original functionality. | #include <algorithm>
#include <iostream>
template <class T>
class AVLnode {
public:
T key;
int balance;
AVLnode *left, *right, *parent;
AVLnode(T k, AVLnode *p) : key(k), balance(0), parent(p),
left(NULL), right(NULL) {}
~AVLnode() {
delete left;
delete ri... | data Tree a
= Leaf
| Node
Int
(Tree a)
a
(Tree a)
deriving (Show, Eq)
foldTree :: Ord a => [a] -> Tree a
foldTree = foldr insert Leaf
height :: Tree a -> Int
height Leaf = -1
height (Node h _ _ _) = h
depth :: Tree a -> Tree a -> Int
depth a b = succ (max (height a) (height b))
ins... |
Generate a Haskell translation of this C++ snippet without changing its computational steps. |
class matrixNG {
private:
virtual void consumeTerm(){}
virtual void consumeTerm(int n){}
virtual const bool needTerm(){}
protected: int cfn = 0, thisTerm;
bool haveTerm = false;
friend class NG;
};
class NG_4 : public matrixNG {
private: int a1, a, b1, b, t;
const bool needTerm() {
if... |
import Data.Ratio ((%))
real2cf frac =
let (quotient, remainder) = properFraction frac
in (quotient : (if remainder == 0
then []
else real2cf (1 / remainder)))
apply_hfunc (a1, a, b1, b) cf =
recurs (a1, a, b1, b, cf)
where recurs (a1, a, b1, b, cf) =
if b1 ... |
Port the following code from C++ to Haskell with equivalent syntax and logic. |
class matrixNG {
private:
virtual void consumeTerm(){}
virtual void consumeTerm(int n){}
virtual const bool needTerm(){}
protected: int cfn = 0, thisTerm;
bool haveTerm = false;
friend class NG;
};
class NG_4 : public matrixNG {
private: int a1, a, b1, b, t;
const bool needTerm() {
if... |
import Data.Ratio ((%))
real2cf frac =
let (quotient, remainder) = properFraction frac
in (quotient : (if remainder == 0
then []
else real2cf (1 / remainder)))
apply_hfunc (a1, a, b1, b) cf =
recurs (a1, a, b1, b, cf)
where recurs (a1, a, b1, b, cf) =
if b1 ... |
Please provide an equivalent version of this C++ code in Haskell. | #include <iostream>
int main()
{
std::cout <<
R"EOF( A raw string begins with R, then a double-quote ("), then an optional
identifier (here I've used "EOF"), then an opening parenthesis ('('). If you
use an identifier, it cannot be longer than 16 characters, and it cannot
contain a space, either op... | main :: IO ()
main = do
putStrLn "Hello\
\ World!\n"
putStrLn $ unwords ["This", "is", "an", "example", "text!\n"]
putStrLn $ unlines [
unwords ["This", "is", "the", "first" , "line."]
, unwords ["This", "is", "the", "second", "line."]
, unwords ["This", "is", ... |
Change the following C++ code into Haskell without altering its purpose. | #include <iostream>
int main()
{
std::cout <<
R"EOF( A raw string begins with R, then a double-quote ("), then an optional
identifier (here I've used "EOF"), then an opening parenthesis ('('). If you
use an identifier, it cannot be longer than 16 characters, and it cannot
contain a space, either op... | main :: IO ()
main = do
putStrLn "Hello\
\ World!\n"
putStrLn $ unwords ["This", "is", "an", "example", "text!\n"]
putStrLn $ unlines [
unwords ["This", "is", "the", "first" , "line."]
, unwords ["This", "is", "the", "second", "line."]
, unwords ["This", "is", ... |
Write a version of this C++ function in Haskell with identical behavior. | #include <algorithm>
#include <array>
#include <cassert>
#include <initializer_list>
#include <iostream>
constexpr size_t sp_rows = 3;
constexpr size_t sp_columns = 3;
constexpr size_t sp_cells = sp_rows * sp_columns;
constexpr int sp_limit = 4;
class abelian_sandpile {
friend std::ostream& operator<<(std::ostrea... |
import Data.List (findIndex, transpose)
import Data.List.Split (chunksOf)
main :: IO ()
main = do
let s0 = [[4, 3, 3], [3, 1, 2], [0, 2, 3]]
s1 = [[1, 2, 0], [2, 1, 1], [0, 1, 3]]
s2 = [[2, 1, 3], [1, 0, 1], [0, 1, 0]]
s3_id = [[2, 1, 2], [1, 0, 1], [2, 1, 2]]
s3 = replicate 3 (replicate 3... |
Transform the following C++ implementation into Haskell, maintaining the same output and logic. | #include <algorithm>
#include <array>
#include <cassert>
#include <initializer_list>
#include <iostream>
constexpr size_t sp_rows = 3;
constexpr size_t sp_columns = 3;
constexpr size_t sp_cells = sp_rows * sp_columns;
constexpr int sp_limit = 4;
class abelian_sandpile {
friend std::ostream& operator<<(std::ostrea... |
import Data.List (findIndex, transpose)
import Data.List.Split (chunksOf)
main :: IO ()
main = do
let s0 = [[4, 3, 3], [3, 1, 2], [0, 2, 3]]
s1 = [[1, 2, 0], [2, 1, 1], [0, 1, 3]]
s2 = [[2, 1, 3], [1, 0, 1], [0, 1, 0]]
s3_id = [[2, 1, 2], [1, 0, 1], [2, 1, 2]]
s3 = replicate 3 (replicate 3... |
Ensure the translated Haskell code behaves exactly like the original C++ snippet. | #include <iomanip>
#include <iostream>
bool nondecimal(unsigned int n) {
for (; n > 0; n >>= 4) {
if ((n & 0xF) > 9)
return true;
}
return false;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 0; n < 501; ++n) {
if (nondecimal(n)) {
++count;
... | import Data.List (intercalate, transpose)
import Data.List.Split (chunksOf)
import Text.Printf (printf)
p :: Int -> Bool
p n =
9 < n
&& ( 9 < rem n 16
|| p (quot n 16)
)
main :: IO ()
main =
let upperLimit = 500
xs = [show x | x <- [0 .. upperLimit], p x]
in mapM_
putStrL... |
Port the provided C++ code into Haskell while preserving the original functionality. | #include <iomanip>
#include <iostream>
bool nondecimal(unsigned int n) {
for (; n > 0; n >>= 4) {
if ((n & 0xF) > 9)
return true;
}
return false;
}
int main() {
unsigned int count = 0;
for (unsigned int n = 0; n < 501; ++n) {
if (nondecimal(n)) {
++count;
... | import Data.List (intercalate, transpose)
import Data.List.Split (chunksOf)
import Text.Printf (printf)
p :: Int -> Bool
p n =
9 < n
&& ( 9 < rem n 16
|| p (quot n 16)
)
main :: IO ()
main =
let upperLimit = 500
xs = [show x | x <- [0 .. upperLimit], p x]
in mapM_
putStrL... |
Transform the following C++ implementation into Haskell, maintaining the same output and logic. | #include <cassert>
#include <iomanip>
#include <iostream>
#include <string>
#include <gmpxx.h>
using big_int = mpz_class;
auto juggler(int n) {
assert(n >= 1);
int count = 0, max_count = 0;
big_int a = n, max = n;
while (a != 1) {
if (a % 2 == 0)
a = sqrt(a);
else
... | import Text.Printf
import Data.List
juggler :: Integer -> [Integer]
juggler = takeWhile (> 1) . iterate (\x -> if odd x
then isqrt (x*x*x)
else isqrt x)
task :: Integer -> IO ()
task n = printf s n (length ns + 1) (i :: Int) (showMa... |
Port the provided C++ code into Haskell while preserving the original functionality. | #include <cassert>
#include <iomanip>
#include <iostream>
#include <string>
#include <gmpxx.h>
using big_int = mpz_class;
auto juggler(int n) {
assert(n >= 1);
int count = 0, max_count = 0;
big_int a = n, max = n;
while (a != 1) {
if (a % 2 == 0)
a = sqrt(a);
else
... | import Text.Printf
import Data.List
juggler :: Integer -> [Integer]
juggler = takeWhile (> 1) . iterate (\x -> if odd x
then isqrt (x*x*x)
else isqrt x)
task :: Integer -> IO ()
task n = printf s n (length ns + 1) (i :: Int) (showMa... |
Rewrite the snippet below in Haskell so it works the same as the original C++ code. | #include <time.h>
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
typedef unsigned int uint;
using namespace std;
enum movDir { UP, DOWN, LEFT, RIGHT };
class tile
{
public:
tile() : val( 0 ), blocked( false ) {}
uint val;
bool blocked;
};
class g2048
{
public:
g2048() : d... | import System.IO
import Data.List
import Data.Maybe
import Control.Monad
import Data.Random
import Data.Random.Distribution.Categorical
import System.Console.ANSI
import Control.Lens
prob4 :: Double
prob4 = 0.1
type Position = [[Int]]
combine, shift :: [Int]->[Int]
combine (x:y:l) | x==y = (2*x) : combine l
combi... |
Keep all operations the same but rewrite the snippet in Haskell. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
const int PLAYERS = 4, MAX_POINTS = 100;
enum Moves { ROLL, HOLD };
class player
{
public:
player() { current_score = round_score = 0; }
void addCurrScore() { current_score += round_score; }
... |
module Main where
import System.Random (randomRIO)
import Text.Printf (printf)
data PInfo = PInfo { stack :: Int
, score :: Int
, rolls :: Int
, next :: Bool
, won :: Bool
, name :: String
}
type... |
Rewrite this program in Haskell while keeping its functionality equivalent to the C++ version. | #include <windows.h>
#include <iostream>
#include <string>
using namespace std;
const int PLAYERS = 4, MAX_POINTS = 100;
enum Moves { ROLL, HOLD };
class player
{
public:
player() { current_score = round_score = 0; }
void addCurrScore() { current_score += round_score; }
... |
module Main where
import System.Random (randomRIO)
import Text.Printf (printf)
data PInfo = PInfo { stack :: Int
, score :: Int
, rolls :: Int
, next :: Bool
, won :: Bool
, name :: String
}
type... |
Convert the following code from C++ to Haskell, ensuring the logic remains intact. | #include <bitset>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>
size_t consonants(const std::string& word) {
std::bitset<26> bits;
size_t bit = 0;
for (char ch : word) {
ch = std::tolower(static_ca... |
import Data.Bifunctor (first)
import Data.Char (toUpper)
import Data.Function (on)
import Data.List ((\\), groupBy, intersect, nub, sortOn)
import Data.Ord (Down(..))
consonants :: String
consonants = cons ++ map toUpper cons
where cons = ['a'..'z'] \\ "aeiou"
onlyConsonants :: String -> String
onlyConsonan... |
Keep all operations the same but rewrite the snippet in Haskell. | #include <gmpxx.h>
#include <iomanip>
#include <iostream>
using big_int = mpz_class;
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;
}
big_int jacobsthal_number(unsigned int n) {
return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;
}
big_int jacobsthal_lucas... | jacobsthal :: [Integer]
jacobsthal = 0 : 1 : zipWith (\x y -> 2 * x + y) jacobsthal (tail jacobsthal)
jacobsthalLucas :: [Integer]
jacobsthalLucas = 2 : 1 : zipWith (\x y -> 2 * x + y) jacobsthalLucas (tail jacobsthalLucas)
jacobsthalOblong :: [Integer]
jacobsthalOblong = zipWith (*) jacobsthal (tail jacobsthal)
isP... |
Preserve the algorithm and functionality while converting the code from C++ to Haskell. | #include <gmpxx.h>
#include <iomanip>
#include <iostream>
using big_int = mpz_class;
bool is_probably_prime(const big_int& n) {
return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0;
}
big_int jacobsthal_number(unsigned int n) {
return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3;
}
big_int jacobsthal_lucas... | jacobsthal :: [Integer]
jacobsthal = 0 : 1 : zipWith (\x y -> 2 * x + y) jacobsthal (tail jacobsthal)
jacobsthalLucas :: [Integer]
jacobsthalLucas = 2 : 1 : zipWith (\x y -> 2 * x + y) jacobsthalLucas (tail jacobsthalLucas)
jacobsthalOblong :: [Integer]
jacobsthalOblong = zipWith (*) jacobsthal (tail jacobsthal)
isP... |
Rewrite this program in Haskell while keeping its functionality equivalent to the C++ version. | #include <iostream>
bool is_prime(int n) {
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
if (n % 3 == 0) {
return n == 3;
}
int i = 5;
while (i * i <= n) {
if (n % i == 0) {
return false;
}
i += 2;
... | import Data.List (scanl)
import Data.Numbers.Primes (isPrime, primes)
indexedPrimeSums :: [(Integer, Integer, Integer)]
indexedPrimeSums =
filter (\(_, _, n) -> isPrime n) $
scanl
(\(i, _, m) p -> (succ i, p, p + m))
(0, 0, 0)
primes
main :: IO ()
main =
mapM_ print $
takeWhile (\(_, ... |
Change the programming language of this snippet from C++ to Haskell without modifying what it does. | #include <iostream>
bool is_prime(int n) {
if (n < 2) {
return false;
}
if (n % 2 == 0) {
return n == 2;
}
if (n % 3 == 0) {
return n == 3;
}
int i = 5;
while (i * i <= n) {
if (n % i == 0) {
return false;
}
i += 2;
... | import Data.List (scanl)
import Data.Numbers.Primes (isPrime, primes)
indexedPrimeSums :: [(Integer, Integer, Integer)]
indexedPrimeSums =
filter (\(_, _, n) -> isPrime n) $
scanl
(\(i, _, m) p -> (succ i, p, p + m))
(0, 0, 0)
primes
main :: IO ()
main =
mapM_ print $
takeWhile (\(_, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.