本文整理汇总了Scala中java.util.Random类的典型用法代码示例。如果您正苦于以下问题:Scala Random类的具体用法?Scala Random怎么用?Scala Random使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Random类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: TestProducer
//设置package包名称以及导入依赖的类
package com.rockiey.kafka
import java.util.{Date, Properties, Random}
import kafka.producer.{KeyedMessage, Producer, ProducerConfig}
import org.junit.{After, Before, Test}
class TestProducer {
val brokers = "localhost:9092"
val topic = "test"
val rnd = new Random()
val props = new Properties()
props.put("metadata.broker.list", brokers)
props.put("serializer.class", "kafka.serializer.StringEncoder")
//props.put("partitioner.class", "com.colobu.kafka.SimplePartitioner")
props.put("producer.type", "async")
//props.put("request.required.acks", "1")
var producer: Producer[String, String] = null
@Before
def before: Unit = {
val config = new ProducerConfig(props)
producer = new Producer[String, String](config)
}
@After
def after: Unit = {
producer.close()
}
def produce(events: Int): Unit = {
val t = System.currentTimeMillis()
for (nEvents <- Range(0, events)) {
val runtime = new Date().getTime()
val ip = "192.168.2." + rnd.nextInt(255)
val msg = runtime + "," + nEvents + ",www.example.com," + ip
val data = new KeyedMessage[String, String](topic, ip, msg)
producer.send(data)
}
System.out.println("sent per second: " + events * 1000 / (System.currentTimeMillis() - t))
}
@Test
def testProducer: Unit = {
produce(100)
}
@Test
def testConsumer {
}
}
开发者ID:rockie-yang,项目名称:explore-spark-kafka,代码行数:58,代码来源:TestProducer.scala
示例2: BlockLightSource
//设置package包名称以及导入依赖的类
package xyz.domi1819.invisiblights
import java.util.Random
import net.minecraft.block.Block
import net.minecraft.block.material.Material
import net.minecraft.creativetab.CreativeTabs
import net.minecraft.init.Items
import net.minecraft.item.Item
import net.minecraft.util.AxisAlignedBB
import net.minecraft.world.{IBlockAccess, World}
class BlockLightSource extends Block(Material.circuits) {
var visibleFlag = false
setHardness(0.1F)
setResistance(0.1F)
setLightLevel(1)
setCreativeTab(CreativeTabs.tabRedstone)
setBlockName("blockLightSource")
setBlockTextureName("invisiblights:light")
setBlockUnbreakable()
override def getSelectedBoundingBoxFromPool(world: World, x: Int, y: Int, z: Int): AxisAlignedBB = {
setBlockBoundsBasedOnState(world, x, y, z)
if (visibleFlag) AxisAlignedBB.getBoundingBox(x, y, z, x + 1, y + 1, z + 1)
else AxisAlignedBB.getBoundingBox(0, 0, 0, 0, 0, 0)
}
override def setBlockBoundsBasedOnState(world: IBlockAccess, x: Int, y: Int, z: Int) {
if (visibleFlag) setBlockBounds(0, 0, 0, 1, 1, 1)
else setBlockBounds(0, 0, 0, 0, 0, 0)
}
override def getCollisionBoundingBoxFromPool(world: World, x: Int, y: Int, z: Int): AxisAlignedBB = {
setBlockBoundsBasedOnState(world, x, y, z)
null
}
override def isReplaceable(world: IBlockAccess, x: Int, y: Int, z: Int): Boolean = true
override def getItemDropped(i: Int, random: Random, j: Int): Item = Items.glowstone_dust
override def getRenderBlockPass: Int = 1
override def quantityDropped(rand: Random): Int = 0
override def isOpaqueCube: Boolean = false
override def shouldSideBeRendered(world: IBlockAccess, x: Int, y: Int, z: Int, side: Int): Boolean = world.getBlock(x, y, z) != this
}
开发者ID:domi1819,项目名称:InvisibLights,代码行数:51,代码来源:BlockLightSource.scala
示例3: slowEquals
//设置package包名称以及导入依赖的类
package conf.security
import java.security.SecureRandom
import java.util.Random
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
import base64.Decode.{apply => fromBase64, urlSafe => fromBase64UrlSafe}
import base64.Encode.{apply => toBase64, urlSafe => toBase64UrlSafe}
import com.github.t3hnar.bcrypt._
import org.apache.commons.lang3.RandomStringUtils
def slowEquals(a: Array[Byte], b: Array[Byte]): Boolean = {
var diff = a.length ^ b.length;
for (i <- 0 until math.min(a.length, b.length)) diff |= a(i) ^ b(i)
return diff == 0
}
val hashParts = hashedPassword.split(HashPartSeparator)
if (hashParts.length != 3) return false
if (!hashParts(0).forall(_.isDigit)) return false
val nrOfIterations = hashParts(0).toInt // this will throw a NumberFormatException for non-Int numbers...
val hash = fromBase64UrlSafe(hashParts(1))
val salt = fromBase64UrlSafe(hashParts(2))
if (hash.isLeft || salt.isLeft) return false
if (hash.right.get.length == 0 || salt.right.get.length == 0) return false
val calculatedHash = pbkdf2(password, salt.right.get, nrOfIterations)
slowEquals(calculatedHash, hash.right.get)
}
private def pbkdf2(password: String, salt: Array[Byte], nrOfIterations: Int): Array[Byte] = {
val keySpec = new PBEKeySpec(password.toCharArray(), salt, nrOfIterations, SizeOfPasswordHashInBytes * 8)
val keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
keyFactory.generateSecret(keySpec).getEncoded()
}
private def generateRandomBytes(length: Int): Array[Byte] = {
val keyData = new Array[Byte](length)
RandomSource.nextBytes(keyData)
keyData
}
override def hashAuth(key: String): String = {
hashPassword(key)
}
override def hashCheck(key: String, hash: String): Boolean = {
validatePassword(key, hash)
}
}
}
开发者ID:Masebeni,项目名称:hwork,代码行数:52,代码来源:AuthUtil.scala
示例4: Util
//设置package包名称以及导入依赖的类
package conf.util
import java.util.Random
import org.apache.commons.lang3.RandomStringUtils
object Util {
import java.net._
def md5Hash(text: String): String = {
val hash = text + InetAddress.getLocalHost.getHostName
java.security.MessageDigest.getInstance("MD5").digest(hash.getBytes()).map(0xFF & _).map {
"%02x".format(_)
}.foldLeft("") {
_ + _
}
}
private def generateOrganisationCode(name: String): String = {
val count: Int = 4
val useLetters: Boolean = true
val useNumbers: Boolean = false
val choseFrom = name.toCharArray
RandomStringUtils.random(count, 0, 0, useLetters, useNumbers, choseFrom, new Random())
}
private def getSalt(): String = {
val length: Int = 5
val useLetters: Boolean = true
val useNumbers: Boolean = true
RandomStringUtils.random(length, useLetters, useNumbers)
}
def codeGen(name: String): String = {
val code = generateOrganisationCode(name)
.toCharArray
.sortWith(_ < _)
.mkString("").toUpperCase
val salt = getSalt()
.toCharArray
.sortWith(_ < _)
.mkString("").toUpperCase
(code + "-" + salt)
}
}
开发者ID:Masebeni,项目名称:hwork,代码行数:50,代码来源:Util.scala
示例5: T02_RandomLogger
//设置package包名称以及导入依赖的类
package streaming
import java.io.PrintWriter
import java.net.ServerSocket
import scala.collection.mutable
object T02_RandomLogger {
def generateContent(index: Int): String = {
import scala.collection.mutable.ListBuffer
var charList = ListBuffer[Char]()
for (i <- 65 to 90) {
charList += i.toChar
}
val charArray = charList.toArray
charArray(index).toString
}
def index = {
import java.util.Random
val rand = new Random
rand.nextInt(7)
}
def main(args: Array[String]) {
var port = 9999
var sec = 1000l
val map = new mutable.HashMap[String,Int]()
if (args.length >= 2) {
port = args(0).toInt
sec = args(1).toLong
}
println("listening:" + port)
val listener = new ServerSocket(port)
while (true) {
println("waiting...")
val socket = listener.accept()
println("accept:" + socket)
new Thread() {
override def run = {
println("got client:" + socket.getInetAddress)
val out = new PrintWriter(socket.getOutputStream, true)
while (true) {
Thread.sleep(sec)
val content = generateContent(index)
map.put(content,map.getOrElse(content,0)+1);
out.write(content+"\n")
out.flush()
println(map)
}
socket.close()
}
}.start()
}
}
}
开发者ID:IMJIU,项目名称:Spark1.6,代码行数:59,代码来源:T02_RandomLogger.scala
示例6: Main
//设置package包名称以及导入依赖的类
package net.shiroka.cat
import java.util.Random
import scala.collection.JavaConverters._
import akka.actor._
import com.typesafe.config.ConfigFactory
object Main {
val roles = ConfigFactory.load.getConfig("akka.cluster").getStringList("roles").asScala
val primaryRole: String = roles.headOption.getOrElse(sys.error("empty roles"))
def main(args: Array[String]): Unit = {
implicit lazy val system = ActorSystem("cluster")
primaryRole match {
case "seed" =>
Cat.startProxy
case "sensor" =>
Cat.startProxy
system.actorOf(Props(classOf[Sensor], new Random()), "cat")
case "cat" =>
Cat.startSharding
journal.RedisSweeper.startSingleton("redis-sweeper", Some("cat"))
case role => sys.error(s"Unexpected role $role")
}
Profiler.run(system)
TinyHttpServer.serve(8080)
}
}
开发者ID:ikuo,项目名称:cat-cluster,代码行数:33,代码来源:Main.scala
示例7: Sensor
//设置package包名称以及导入依赖的类
package net.shiroka.cat
import java.util.Random
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext
import akka.actor._
import akka.cluster._
import akka.cluster.sharding._
import akka.cluster.ClusterEvent._
import net.ceedubs.ficus.Ficus._
import pb.cat.Meow
class Sensor(val random: Random = new Random()) extends Actor {
import Sensor._
implicit val ec: ExecutionContext = context.dispatcher
private var started: Option[Cancellable] = None
val system = context.system
val cat = ClusterSharding(context.system).shardRegion(Cat.shardingName)
val cluster = Cluster(context.system)
override def preStart(): Unit = cluster.subscribe(self, classOf[MemberUp], classOf[MemberEvent])
override def postStop(): Unit = cluster.unsubscribe(self)
def receive = {
case Sense => (0 until batchSize).foreach(_ =>
cat ! Meow(randomCatId, System.currentTimeMillis() / 1000L))
case state: CurrentClusterState =>
state.members
.find(member => member.status == MemberStatus.Up && member.address == cluster.selfAddress)
.foreach(_ => self ! Start)
case MemberUp(member) =>
if (member.address == cluster.selfAddress) { self ! Start }
case msg: MemberEvent =>
if (cluster.state.unreachable.size == 0) { self ! Start }
else { stop }
case Start => start
}
private def stop: Unit = {
this.started.foreach(_.cancel)
this.started = None
}
private def start: Unit =
if (started.isEmpty) {
this.started = Some(system.scheduler.schedule(2.seconds, interval, self, Sense))
}
private def randomCatId: String = s"cat-${random.nextInt(Cat.maxEntities)}"
}
object Sensor extends Config {
val configKey = "sensor"
val interval = config.as[FiniteDuration]("interval")
val batchSize = config.as[Int]("batch.size")
object Start
object Sense
}
开发者ID:ikuo,项目名称:cat-cluster,代码行数:61,代码来源:Sensor.scala
示例8: SessionDataFileHDFSWriter
//设置package包名称以及导入依赖的类
package com.malaska.spark.training.streaming.dstream.sessionization
import java.io.BufferedWriter
import java.io.FileWriter
import org.apache.hadoop.fs.FileSystem
import org.apache.hadoop.conf.Configuration
import java.io.OutputStreamWriter
import org.apache.hadoop.fs.Path
import java.util.Random
object SessionDataFileHDFSWriter {
val eol = System.getProperty("line.separator");
def main(args: Array[String]) {
if (args.length == 0) {
println("SessionDataFileWriter {tempDir} {distDir} {numberOfFiles} {numberOfEventsPerFile} {waitBetweenFiles}");
return;
}
val conf = new Configuration
conf.addResource(new Path("/etc/hadoop/conf/core-site.xml"))
conf.addResource(new Path("/etc/hadoop/conf/mapred-site.xml"))
conf.addResource(new Path("/etc/hadoop/conf/hdfs-site.xml"))
val fs = FileSystem.get(new Configuration)
val rootTempDir = args(0)
val rootDistDir = args(1)
val files = args(2).toInt
val loops = args(3).toInt
val waitBetweenFiles = args(4).toInt
val r = new Random
for (f <- 1 to files) {
val rootName = "/weblog." + System.currentTimeMillis()
val tmpPath = new Path(rootTempDir + rootName + ".tmp")
val writer = new BufferedWriter(new OutputStreamWriter(fs.create(tmpPath)))
print(f + ": [")
val randomLoops = loops + r.nextInt(loops)
for (i <- 1 to randomLoops) {
writer.write(SessionDataGenerator.getNextEvent + eol)
if (i%100 == 0) {
print(".")
}
}
println("]")
writer.close
val distPath = new Path(rootDistDir + rootName + ".dat")
fs.rename(tmpPath, distPath)
Thread.sleep(waitBetweenFiles)
}
println("Done")
}
}
开发者ID:TedBear42,项目名称:spark_training,代码行数:58,代码来源:SessionDataFileHDFSWriter.scala
示例9: SaltedExample
//设置package包名称以及导入依赖的类
package com.malaska.spark.training.salted
import java.util.Random
import org.apache.log4j.{Level, Logger}
import org.apache.spark.sql.SparkSession
object SaltedExample {
Logger.getLogger("org").setLevel(Level.OFF)
Logger.getLogger("akka").setLevel(Level.OFF)
def main(args:Array[String]): Unit = {
val jsonPath = args(0)
val sparkSession = SparkSession.builder
.master("local")
.appName("my-spark-app")
.config("spark.some.config.option", "config-value")
.getOrCreate()
val jsonDfLeft = sparkSession.read.json(jsonPath)
val saltedLeft = jsonDfLeft.rdd.flatMap(r => {
val group = r.getAs[String]("group")
val value = r.getAs[Long]("value")
Seq((group + "_" + 0, value),(group + "_" + 1, value))
})
val jsonDfRight = sparkSession.read.json(jsonPath)
val saltedRight = jsonDfRight.rdd.mapPartitions(it => {
val random = new Random()
it.map(r => {
val group = r.getAs[String]("group")
val value = r.getAs[Long]("value")
(group + "_" + random.nextInt(2), value)
})
})
jsonDfLeft.join(jsonDfRight).collect().foreach(r => {
println("Normal.result:" + r)
})
println("----")
saltedLeft.join(saltedRight).collect().foreach(r => {
println("Salted.result:" + r)
})
}
}
开发者ID:TedBear42,项目名称:spark_training,代码行数:54,代码来源:SaltedExample.scala
示例10: AppleCustomPartitioner
//设置package包名称以及导入依赖的类
package com.malaska.spark.training.partitioning
import java.util.Random
import org.apache.spark.Partitioner
class AppleCustomPartitioner(numOfParts:Int) extends Partitioner {
override def numPartitions: Int = numOfParts
def random = new Random()
override def getPartition(key: Any): Int = {
val k = key.asInstanceOf[(String, Long)]
val ticker = k._1
if (ticker.equals("apple")) {
val saltedTicker = ticker + random.nextInt(9)
Math.abs(saltedTicker.hashCode) % numPartitions
} else {
Math.abs(ticker.hashCode) % numPartitions
}
}
}
开发者ID:TedBear42,项目名称:spark_training,代码行数:23,代码来源:AppleCustomPartitioner.scala
示例11: next
//设置package包名称以及导入依赖的类
package edu.neu.coe.scala.ga
package rng
import java.util.Random
trait RNG[+A] {
def next: RNG[A]
def value: A
}
abstract class RNG_Java[+A](n: Long) extends RNG[A] {
// must be overridden by sub-classes
def value: A
def newRNG(n: Long): RNG[A]
// may be overridden (if you want to define your own pseudo-random sequence)
def nextSeed: Long = RNG_Java.nextSeed(n)
// base method -- not normally overridden
def next: RNG[A] = newRNG(nextSeed)
def state = n
}
object RNG_Java {
def nextSeed(n: Long): Long = new Random(n).nextLong
}
case class LongRNG(n: Long) extends RNG_Java[Long](n) {
def newRNG(n: Long): RNG[Long] = LongRNG(n)
def value = n
}
case class DoubleRNG(n: Long) extends RNG_Java[Double](n) {
def newRNG(n: Long) = DoubleRNG(n)
def value = n.toDouble/Long.MaxValue
override def toString = s"DoubleRNG: $n->$value"
}
case class UniformDouble(x: Double) extends AnyVal with Ordered[UniformDouble] {
def + (y: Double) = x + y
def compare(that: UniformDouble): Int = x.compare(that.x)
}
object DoubleRNG {
def apply: RNG[Double] = DoubleRNG(System.currentTimeMillis())
}
object UniformDoubleRNG {
def apply: RNG[UniformDouble] = UniformDoubleRNG(System.currentTimeMillis())
implicit val u: Unit = Unit
}
object GaussianRNG {
def apply: RNG[(Double,Double)] = GaussianRNG(System.currentTimeMillis())
}
object UniformDouble {
def create(x: Double)(implicit y: Unit) = if (x>=0 && x<=1) new UniformDouble(x) else throw new IllegalArgumentException(s"$x is not in range 0..1")
def + (x: Double, y: UniformDouble) = y+x
}
开发者ID:menezesl,项目名称:Scala-repo,代码行数:61,代码来源:RNG.scala
示例12: next
//设置package包名称以及导入依赖的类
package edu.neu.coe.scala
package rng
import java.util.Random
trait RNG[+A] {
def next: RNG[A]
def value: A
}
abstract class RNG_Java[+A](n: Long) extends RNG[A] {
// must be overridden by sub-classes
def value: A
def newRNG(n: Long): RNG[A]
// may be overridden (if you want to define your own pseudo-random sequence)
def nextSeed: Long = RNG_Java.nextSeed(n)
// base method -- not normally overridden
def next: RNG[A] = newRNG(nextSeed)
def state = n
}
object RNG_Java {
def nextSeed(n: Long): Long = new Random(n).nextLong
}
case class LongRNG(n: Long) extends RNG_Java[Long](n) {
def newRNG(n: Long): RNG[Long] = ???
def value = ???
}
case class DoubleRNG(n: Long) extends RNG_Java[Double](n) {
def newRNG(n: Long) = ???
def value = ???
override def toString = s"DoubleRNG: $n->$value"
}
case class UniformDouble(x: Double) extends AnyVal {
def + (y: Double) = x + y
}
object UniformDoubleRNG {
def apply: RNG[UniformDouble] = UniformDoubleRNG(System.currentTimeMillis())
}
object GaussianRNG {
def apply: RNG[(Double,Double)] = GaussianRNG(System.currentTimeMillis())
}
object UniformDouble {
def apply(x: Double, y: Unit) = if (x>=0 && x<=1) new UniformDouble(x) else throw new IllegalArgumentException(s"$x is not in range 0..1")
def + (x: Double, y: UniformDouble) = y+x
}
开发者ID:menezesl,项目名称:Scala-repo,代码行数:55,代码来源:RNG.scala
示例13: BidirectionalPPREstimatorSpec
//设置package包名称以及导入依赖的类
package soal.ppr
import java.util.Random
import co.teapot.tempest.graph.ConcurrentHashMapDynamicGraph
import org.scalatest.{FlatSpec, Matchers}
import scala.collection.mutable
import scala.io.Source
class BidirectionalPPREstimatorSpec extends FlatSpec with Matchers {
val graph = ConcurrentHashMapDynamicGraph.readGraph("src/test/resources/test_graph.txt")
val teleportProb = 0.2f
val random = new Random(2) // Seed for consistent tests
val estimator = new BidirectionalPPREstimator(graph, teleportProb, random)
val truePPRs = BidirectionalPPREstimatorSpec.testGraphTruePPRs
"BidirectionalPPRSearcher.estimateInversePPR" should "be correct on the test graph" in {
val pprErrorTolerance = 2.0e-6f
for (((s, t), truePPR) <- truePPRs) {
val inversePPRs = estimator.estimatePPRToTarget(t, pprErrorTolerance)
withClue (s"Testing Pair ($s, $t)") {
inversePPRs(s) should equal (truePPR +- pprErrorTolerance)
}
}
}
"BidirectionalPPRSearcher.estimatePPR" should "be correct on the test graph" in {
val relativeError = 0.01f
val stPairs = Array(0 -> 1, 2 -> 3, 5 -> 9, 0 -> 0)
for ((s, t) <- stPairs) {
withClue (s"Testing Pair ($s, $t)") {
estimator.estimatePPRSingleSource(s, t, 0.03f, relativeError) should equal (
truePPRs((s, t)) +- truePPRs((s, t)) * relativeError * 2)
}
}
}
}
object BidirectionalPPREstimatorSpec {
def testGraphTruePPRs: collection.Map[(Int, Int), Float] = {
val pprMap = new mutable.HashMap[(Int, Int), Float] {
override def default(key: (Int, Int)) = 0.0f
}
for (line <- Source.fromFile("src/test/resources/test_graph_true_pprs.txt").getLines()) {
val pieces = line.split("\t")
val (startId, targetId, truePPR) = (pieces(0).toInt, pieces(1).toInt, pieces(2).toFloat)
pprMap((startId, targetId)) = truePPR
}
pprMap
}
}
开发者ID:teapot-co,项目名称:tempest,代码行数:54,代码来源:BidirectionalPPREstimatorSpec.scala
示例14: DiscreteAliasSamplerSpec
//设置package包名称以及导入依赖的类
package soal.util
import java.util.Random
import org.scalatest.{FlatSpec, Matchers}
class DiscreteAliasSamplerSpec extends FlatSpec with Matchers {
val random = new Random(1)
def testDistribution(unnormalizedProbabilities: Array[Float],
values: Seq[Int],
nSamples: Int = 10000
): Unit = {
val probabilities = unnormalizedProbabilities map { _ / unnormalizedProbabilities.sum }
val n = unnormalizedProbabilities.size
val valueToIndex = (values zip (0 until n)).toMap
val sampler = new DiscreteAliasSampler(values, unnormalizedProbabilities, random)
val sampleCounts = Array.fill(n)(0)
val tol = 4.0f / math.sqrt(nSamples).toFloat
for (i <- 0 until nSamples) {
val v = sampler.sample()
sampleCounts(valueToIndex(v)) += 1
}
for (i <- 0 until n) {
sampleCounts(i).toFloat / nSamples should equal (probabilities(i) +- tol)
}
def f(v: Int): Float = v.toFloat * v.toFloat // compute expectation of v => v^2
val trueExpectation = ((probabilities zip values) map { case (p, v) => p * v * v }).sum
sampler.expectation(f) shouldEqual (trueExpectation +- trueExpectation * 1.00001f)
}
"A Discrete Distribution" should "support sampling" in {
testDistribution(Array(575.6355f, 89.733475f, 86.90718f, 721.26416f), Array(2, 3, 5, 7))
testDistribution(Array(2.0f, 5.0f, 3.0f), Array(17, 11, 13))
testDistribution(Array(1.0f, 1.0f, 1.0f, 1.0f), Array(-2, 3, -5, 7))
testDistribution(Array(0.9f, 0.1f), Array(19, 17))
an[IllegalArgumentException] should be thrownBy {
new DiscreteAliasSampler(Array(1), Array(1.0f, 2.0f))
}
}
}
开发者ID:teapot-co,项目名称:tempest,代码行数:44,代码来源:DiscreteAliasSamplerSpec.scala
示例15: RandomTest
//设置package包名称以及导入依赖的类
package xyztr
import java.security.SecureRandom
import java.util.Random
import org.jboss.netty.util.CharsetUtil
import org.scalatest.{FlatSpec, Matchers}
class RandomTest extends FlatSpec with Matchers {
"SecureRandom" should "generate completely random numbers by default" in {
val rg = new SecureRandom()
val randomLong = rg.nextLong
randomLong should not be 606409227870597303L
}
"SecureRandom" should "generate completely random numbers even if the same seed is used" in {
val seed = new String("seed").getBytes(CharsetUtil.UTF_8)
val rg1 = new SecureRandom()
val rg2 = new SecureRandom()
rg1.setSeed(seed)
rg2.setSeed(seed)
val b1 = Crypto.toBytes(1, 2, 3, 4, 5, 6, 7, 8)
val b2 = Crypto.toBytes(1, 2, 3, 4, 5, 6, 7, 8)
rg1.nextBytes(b1)
rg2.nextBytes(b2)
b1 should not be b2
}
"Random" should "generate completely non-random numbers if the same seed is used" in {
val seed = 77
val rg1 = new Random(seed)
val rg2 = new Random(seed)
val b1 = Crypto.toBytes(1, 2, 3, 4, 5, 6, 7, 8)
val b2 = Crypto.toBytes(1, 2, 3, 4, 5, 6, 7, 8)
rg1.nextBytes(b1)
rg2.nextBytes(b2)
b1 should be(b2)
}
}
开发者ID:matshenricson,项目名称:xyztr,代码行数:42,代码来源:RandomTest.scala
示例16: User
//设置package包名称以及导入依赖的类
package tictactoe
import java.util.Random
import HumanPlayer._
abstract class User {
val id: Player
def getMove(board: Board): Move
}
case class HumanPlayer(id: Player) extends User {
def getMove(board: Board): Move = {
println(board.toString)
var input = ""
do {
input = Console readLine "Enter a number from 1-9: "
} while (!validInputs(input) || !board.emptyPositions(input.toInt - 1))
Move(id, input.toInt - 1)
}
}
object HumanPlayer {
val validInputs = Set("1", "2", "3", "4", "5", "6", "7", "8", "9")
}
case class RobotPlayer(id: Player) extends User {
private val opponentId = id match {
case X => O
case O => X
}
def getMove(board: Board): Move = {
val rand = new Random(System.currentTimeMillis)
val positions = board.emptyPositions.toList
val randIndex = rand.nextInt(positions.length)
Move(id, positions(randIndex))
}
// def score(board: Board): Int = { }
}
开发者ID:noahklein,项目名称:tic-tac-scala,代码行数:41,代码来源:User.scala
示例17: ScalaTraining
//设置package包名称以及导入依赖的类
import scala.concurrent.Future
import java.util.Random
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Success, Failure}
object ScalaTraining {
object FlakyUsersAPI {
private val failAfterThreshold: Double = .5
case class User(name: String, age: Int)
case class UsersException(message: String) extends Exception(message)
def findAll(): Seq[User] = {
if (new Random().nextDouble() > failAfterThreshold) throw UsersException("Our API is flaky")
else List(User("bob", 33), User("mary", 24))
}
}
object LatentFuture {
private val MAX_SECOND = 3
def apply[T](n: => T) = Future {
Thread.sleep(1000 * new Random().nextInt(MAX_SECOND));
n
}
}
object MyUserModel {
case class MyUser(name: String, age: Int)
case class MyUserException(message: String) extends Exception(message)
}
def registerSimple = LatentFuture { 100 }.onComplete {
case Success(_) => println("woooo")
case Failure(ex) => println("noo")
}
def registerNonsimply = LatentFuture { FlakyUsersAPI.findAll() }.onComplete {
case Success(users) => println(users.toString)
case Failure(ex) => println(s"Exception: ${ex.getMessage}")
}
def recoverBetter = LatentFuture { FlakyUsersAPI.findAll() }
.map { _.map { user => MyUserModel.MyUser(user.name, user.age )}}
.recover {
case FlakyUsersAPI.UsersException(message) =>
throw MyUserModel.MyUserException("An issue occured attempting to connect to API")
}
def registerRecovered = recoverBetter.onComplete {
case Success(users) => println(users.toString)
case Failure(ex) => println(ex.getMessage)
}
// Future.sequence is simply a way to transoform a List(Future(1), Future(2)...) to Future(List(1,2,3...))
}
开发者ID:kevinninglei,项目名称:scalalabs,代码行数:60,代码来源:04_scala_training.scala
示例18: NTMWallBuilder
//设置package包名称以及导入依赖的类
package ru.ispras.modis.tm.chinesetm
import java.util.Random
import ru.ispras.modis.tm.attribute.AttributeType
import ru.ispras.modis.tm.builder.PLSABuilder
import ru.ispras.modis.tm.documents.{Alphabet, Document}
import ru.ispras.modis.tm.initialapproximationgenerator.RandomInitialApproximationGenerator
import ru.ispras.modis.tm.matrix.Theta
import ru.ispras.modis.tm.regularizer.SymmetricDirichlet
import ru.ispras.modis.tm.sparsifier.ZeroSparsifier
import ru.ispras.modis.tm.stoppingcriteria.MaxNumberOfIterationStoppingCriteria
import ru.ispras.modis.tm.utils.ModelParameters
class NTMWallBuilder(numberOfTopics: Int,
alphabet: Alphabet,
documents: Seq[Document],
random: Random,
numberOfIteration: Int,
private val noisePrior: Float,
private val backgroundPrior: Float,
private val topicPrior: Float,
private val topicWeightPrior: Float)
extends PLSABuilder(numberOfTopics, alphabet, documents, random, numberOfIteration) {
initialApproximationGenerator = new RandomInitialApproximationGenerator(random)
thetaSparsifier = new ZeroSparsifier()
phiSparsifier = new ZeroSparsifier()
stoppingCriteria = new MaxNumberOfIterationStoppingCriteria(numberOfIteration)
regularizer = new SymmetricDirichlet(topicPrior, topicWeightPrior)
stoppingCriteria = new MaxNumberOfIterationStoppingCriteria(numberOfIteration)
override protected def brickBuilder(modelParameters: ModelParameters): Map[AttributeType, NTMBrick] = {
modelParameters.numberOfWords.map {case (key, value) =>
(key, NTMBrick(modelParameters, key, regularizer, phiSparsifier, documents, noisePrior, backgroundPrior))
}
}
override def build(): NTMWall = {
val bricks = brickBuilder(modelParameters)
val (theta, phi) = initialApproximationGenerator(modelParameters, documents)
new NTMWall(bricks,
stoppingCriteria,
thetaSparsifier,
regularizer,
documents,
phi,
theta: Theta)
}
}
开发者ID:ispras,项目名称:atr4s,代码行数:56,代码来源:NTMWallBuilder.scala
示例19: BucketedHistogramBenchmark
//设置package包名称以及导入依赖的类
package com.twitter.finagle.stats
import com.twitter.finagle.benchmark.StdBenchAnnotations
import java.util.Random
import org.openjdk.jmh.annotations._
import org.openjdk.jmh.infra.Blackhole
// ./sbt 'project finagle-benchmark' 'jmh:run BucketedHistogramBenchmark'
class BucketedHistogramBenchmark extends StdBenchAnnotations {
import BucketedHistogramBenchmark._
@Benchmark
@OperationsPerInvocation(N)
def add(data: DataState, add: AddState, bh: Blackhole): Int = {
var i = 0
while (i < data.datas.length) {
bh.consume(add.histogram.add(data.datas(i)))
i += 1
}
i
}
@Benchmark
def percentiles(state: PercentileState): Array[Long] = {
state.histogram.getQuantiles(BucketedHistogramBenchmark.percentiles)
}
}
object BucketedHistogramBenchmark {
final val N = 10000
final val percentiles = Array[Double](0.5, 0.9, 0.95, 0.99, 0.999, 0.9999)
@State(Scope.Benchmark)
class DataState {
val datas: Array[Long] = {
val rng = new Random(1010101)
Array.fill(N) { (rng.nextDouble() * 100000L).toLong }
}
}
@State(Scope.Thread)
class AddState {
val histogram = BucketedHistogram()
}
@State(Scope.Thread)
class PercentileState {
val histogram = BucketedHistogram()
@Setup
def setup(state: DataState): Unit = {
state.datas.foreach(histogram.add)
}
}
}
开发者ID:wenkeyang,项目名称:finagle,代码行数:60,代码来源:BucketedHistogramBenchmark.scala
示例20: ServiceFactoryCacheBenchmark
//设置package包名称以及导入依赖的类
package com.twitter.finagle.factory
import com.twitter.finagle.{ClientConnection, Service, ServiceFactory}
import com.twitter.finagle.benchmark.StdBenchAnnotations
import com.twitter.finagle.stats.NullStatsReceiver
import com.twitter.util.Future
import java.util.Random
import java.util.concurrent.atomic.AtomicInteger
import org.openjdk.jmh.annotations.{Benchmark, Scope, State}
// ko todo: run with some concurrency
@State(Scope.Benchmark)
class ServiceFactoryCacheBenchmark extends StdBenchAnnotations {
import ServiceFactoryCacheBenchmark._
@Benchmark
def apply(state: CacheState): Future[Service[Int, Int]] =
state.cache(state.nextKey(), state.conn)
}
object ServiceFactoryCacheBenchmark {
private[this] val newFactory: Int => ServiceFactory[Int, Int] = key => {
val svc = Service.mk[Int, Int] { in => Future.value(key + in) }
ServiceFactory.const(svc)
}
// use 12 inputs into a cache of size 8 so as to get some misses
private[this] val MaxCacheSize = 8
private[this] val MaxInput = 12
@State(Scope.Benchmark)
class CacheState {
val conn: ClientConnection = ClientConnection.nil
val cache = new ServiceFactoryCache[Int, Int, Int](
newFactory,
NullStatsReceiver,
MaxCacheSize)
def nextKey(): Int = {
val offset = pos.incrementAndGet()
inputs(offset % inputs.length)
}
private[this] val pos: AtomicInteger = new AtomicInteger(0)
private[this] val inputs: Array[Int] = {
val rng = new Random(12345L)
Array.fill(1024) { rng.nextInt(MaxInput) }
}
}
}
开发者ID:wenkeyang,项目名称:finagle,代码行数:56,代码来源:ServiceFactoryCacheBenchmark.scala
注:本文中的java.util.Random类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论