code
stringlengths
5
1M
repo_name
stringlengths
5
109
path
stringlengths
6
208
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1M
/* * Copyright 2013 Krisztian Lachata * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaloz.datafeed.processorrest.infrastructure.acl import org.apache.camel.Header import org.kaloz.datafeed.processor.api.instrument.{InstrumentPriceListRequestMessage, InstrumentPriceRequestMessage} import org.springframework.stereotype.Component @Component class ProcessorRestConverter { def toInstrumentPriceRequestMessage(@Header("provider") provider: String, @Header("instrument") instrument: String) = new InstrumentPriceRequestMessage( provider, instrument) def toInstrumentPriceListRequestMessage(@Header("provider") provider: String) = new InstrumentPriceListRequestMessage( provider ) }
lachatak/market-data-feed
market-data-processor-rest/src/main/scala/org/kaloz/datafeed/processorrest/infrastructure/acl/ProcessorRestConverter.scala
Scala
apache-2.0
1,213
package scaudio import scala.math.* import scutil.math.functions.* /** math utilities */ object math { // NOTE unboxed newtypes could be useful here val zeroGain = 0.0 val unitGain = 1.0 val unitDb = 0.0 val zeroFrequency = 0.0 val unitFrequency = 1.0 val secondsPerMinute = 60 //------------------------------------------------------------------------------ /** convert from an amplitude multiplication factor to a dB value */ inline def gain2db(gain:Double):Double = 20 * log10(gain) // roughly Math.log(gain) * 6.0 / Math.log(2); /** convert from a dB value to an amplitude multiplication factor */ inline def db2gain(dB:Double):Double = exp10(dB / 20) // roughly Math.exp(dB * Math.log(2) / 6.0); //------------------------------------------------------------------------------ /** convert from an amplitude multiplication factor to a dBi value */ inline def gain2dbi(gain:Double):Double = 10 * log10(gain) /** convert from a dBi value to an amplitude multiplication factor */ inline def dbi2gain(dB:Double):Double = exp10(dB / 10) //------------------------------------------------------------------------------ /** convert from a frequency factor to a linear 1-per-octave value */ inline def frequency2octave(frequency:Double):Double = log2(frequency) /** convert from a linear 1-per-octave value to a frequency factor */ inline def octave2frequency(octave:Double):Double = exp2(octave) //------------------------------------------------------------------------------ /** negative: first slow, then fast; positive: first fast, then slow */ def gammaFade(form:Double):Double=>Double = { val scale = exp(form) it => exp(log(it) * scale) } def cosineFade(it:Double):Double = (1 - cos(it * Pi)) / 2 }
ritschwumm/scaudio
src/main/scala/math.scala
Scala
bsd-2-clause
1,763
package me.liamdawson.firefighter.http.resources import me.liamdawson.firefighter.http.routing.Route import scala.language.implicitConversions object dsl { implicit def routeToEnhancedRoute(route: Route): EnhancedRoute = EnhancedRoute(route) implicit def resourceRoutingToResourceRoutings(routing: ResourceRouting): Seq[ResourceRouting] = Seq(routing) implicit def resourceRoutingsToResourceMatcher(routings: Seq[ResourceRouting]): ResourceMatcher = ResourceMatcher(routings) } case class EnhancedRoute(route: Route) { def ->(resource: Resource) = ResourceRouting(route, resource) }
liamdawson/firefighter
src/main/scala/me/liamdawson/firefighter/http/resources/dsl.scala
Scala
mit
596
package defw.webapp import org.scalatra._ import scalate.ScalateSupport class WebAppServlet extends ScalatraWebAppStack { get("/") { <html> <body> <h1>Hello, world!</h1> Say <a href="hello-scalate">hello to Scalate</a>. </body> </html> } /** * Accessing scalatra web service GET parameters * To use a named parameters approch */ get("/hello/:name/") { <p>Hello, {params("name")}</p> } /** * Accessing scalatra web service GET parameters * To use wildcard charactors */ get("/file/*.*") { val data = multiParams("splat") <p>{data.mkString("[", ",", "]")}</p> } }
takahish0306/scala-defw
webapp/src/main/scala/defw/webapp/WebAppServlet.scala
Scala
apache-2.0
650
/* * Copyright 2013 TeamNexus * * TeamNexus Licenses this file to you under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://opensource.org/licenses/mit-license.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License */ package com.nexus.webserver.handlers import com.nexus.webserver.{WebServerUtils, SslContextProvider, TWebServerHandler} import io.netty.channel._ import io.netty.handler.codec.http._ import com.nexus.util.Utils import java.io.{FileNotFoundException, RandomAccessFile, File} import java.util.Locale import java.text.SimpleDateFormat import io.netty.handler.stream.ChunkedFile /** * No description given * * @author jk-5 */ class WebServerHandlerHtml extends TWebServerHandler { private final val useSendFile = SslContextProvider.isValid private final val htdocs = System.getProperty("nexus.webserver.htdocslocation", "htdocs") private final val htdocsLocation = if(htdocs.endsWith("/")) htdocs.substring(0,htdocs.length -1) else htdocs override def handleRequest(ctx: ChannelHandlerContext, req: FullHttpRequest){ if(req.getMethod != HttpMethod.GET){ WebServerUtils.sendError(ctx, HttpResponseStatus.BAD_REQUEST) return } val uri = req.getUri.split("\\?", 2)(0) val path = htdocsLocation + Utils.sanitizeURI(uri) if(path == null){ WebServerUtils.sendError(ctx, HttpResponseStatus.FORBIDDEN) return } var file = new File(path) if(file.isDirectory){ val index = new File(file, "index.html") if(index.exists() && index.isFile) file = index } if(file.isHidden || !file.exists){ WebServerUtils.sendError(ctx, HttpResponseStatus.NOT_FOUND) return } if(file.isDirectory){ if(uri.endsWith("/")) { //this.sendFileList(ctx, file) //TODO: file list? }else WebServerUtils.sendRedirect(ctx, uri + "/") return } if(!file.isFile){ WebServerUtils.sendError(ctx, HttpResponseStatus.FORBIDDEN) return } val ifModifiedSince = req.headers().get(HttpHeaders.Names.IF_MODIFIED_SINCE) if(ifModifiedSince != null && !ifModifiedSince.isEmpty){ val dateFormatter = new SimpleDateFormat(WebServerUtils.HTTP_DATE_FORMAT, Locale.US) val ifModifiedSinceDate = dateFormatter.parse(ifModifiedSince) val ifModifiedSinceDateSeconds = ifModifiedSinceDate.getTime / 1000 val fileLastModifiedSeconds = file.lastModified() / 1000 if(ifModifiedSinceDateSeconds == fileLastModifiedSeconds){ WebServerUtils.sendNotModified(ctx) return } } var raf:RandomAccessFile = null try{ raf = new RandomAccessFile(file, "r") }catch{ case e: FileNotFoundException => { WebServerUtils.sendError(ctx, HttpResponseStatus.NOT_FOUND) return } } val fileLength = raf.length() val response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK) WebServerUtils.setContentLength(response, fileLength) WebServerUtils.setContentType(response, file) WebServerUtils.setDateAndCacheHeaders(response, file) if(HttpHeaders.isKeepAlive(req)) response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE) ctx.write(response) var sendFileFuture: ChannelFuture = null if(this.useSendFile) sendFileFuture = ctx.write(new DefaultFileRegion(raf.getChannel, 0, fileLength), ctx.newProgressivePromise()) else sendFileFuture = ctx.write(new ChunkedFile(raf, 0, fileLength, 8192), ctx.newProgressivePromise()) val lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT) if(!HttpHeaders.isKeepAlive(req)) lastContentFuture.addListener(ChannelFutureListener.CLOSE) } }
crvidya/nexus-scala
src/main/scala/com/nexus/webserver/handlers/WebServerHandlerHtml.scala
Scala
mit
4,078
package reactivemongo.api.commands.bson import reactivemongo.api.BSONSerializationPack import reactivemongo.api.commands._ import reactivemongo.bson._ object BSONIsMasterCommand extends IsMasterCommand[BSONSerializationPack.type] object BSONIsMasterCommandImplicits { import BSONIsMasterCommand._ implicit object IsMasterWriter extends BSONDocumentWriter[IsMaster.type] { def write(im: IsMaster.type) = BSONDocument("ismaster" -> 1) } implicit object IsMasterResultReader extends DealingWithGenericCommandErrorsReader[IsMasterResult] { def readResult(doc: BSONDocument): IsMasterResult = { def rs = doc.getAs[String]("me").map { me => new ReplicaSet( setName = doc.getAs[String]("setName").get, setVersion = doc.getAs[BSONNumberLike]("setVersion"). fold(-1)(_.toInt), me = me, primary = doc.getAs[String]("primary"), hosts = doc.getAs[Seq[String]]("hosts").getOrElse(Seq.empty), passives = doc.getAs[Seq[String]]("passives").getOrElse(Seq.empty), arbiters = doc.getAs[Seq[String]]("arbiters").getOrElse(Seq.empty), isSecondary = doc.getAs[BSONBooleanLike]( "secondary" ).fold(false)(_.toBoolean), isArbiterOnly = doc.getAs[BSONBooleanLike]( "arbiterOnly" ).fold(false)(_.toBoolean), isPassive = doc.getAs[BSONBooleanLike]( "passive" ).fold(false)(_.toBoolean), isHidden = doc.getAs[BSONBooleanLike]("hidden"). fold(false)(_.toBoolean), tags = doc.getAs[BSONDocument]("tags"), electionId = doc.getAs[BSONNumberLike]("electionId").fold(-1)(_.toInt) ) } IsMasterResult( isMaster = doc.getAs[BSONBooleanLike]( "ismaster" ).fold(false)(_.toBoolean), // `ismaster` maxBsonObjectSize = doc.getAs[BSONNumberLike]("maxBsonObjectSize"). fold[Int](16777216)(_.toInt), // default = 16 * 1024 * 1024 maxMessageSizeBytes = doc.getAs[BSONNumberLike]("maxMessageSizeBytes"). fold[Int](48000000)(_.toInt), // default = 48000000, mongod >= 2.4 maxWriteBatchSize = doc.getAs[BSONNumberLike]("maxWriteBatchSize"). fold[Int](1000)(_.toInt), localTime = doc.getAs[BSONDateTime]("localTime").map(_.value), // date? mongod >= 2.2 minWireVersion = doc.getAs[BSONNumberLike]("minWireVersion"). fold[Int](0)(_.toInt), // int? mongod >= 2.6 maxWireVersion = doc.getAs[BSONNumberLike]("maxWireVersion"). fold[Int](0)(_.toInt), // int? mongod >= 2.6 replicaSet = rs, // flattened in the result msg = doc.getAs[String]("msg") // Contains the value isdbgrid when isMaster returns from a mongos instance. ) } } }
maxime-gautre/ReactiveMongo
driver/src/main/scala/api/commands/bson/ismaster.scala
Scala
apache-2.0
2,808
package com.github.diegopacheco.scalaplayground.caliban import ExampleData._ import ExampleService.ExampleService import caliban.{GraphQL, RootResolver} import caliban.GraphQL.graphQL import caliban.schema.Annotations.{GQLDeprecated, GQLDescription} import caliban.schema.GenericSchema import caliban.wrappers.ApolloTracing.apolloTracing import caliban.wrappers.Wrappers._ import zio.URIO import zio.clock.Clock import zio.console.Console import zio.duration._ import zio.stream.ZStream import scala.language.postfixOps object ExampleApi extends GenericSchema[ExampleService] { case class Queries( @GQLDescription("Return all characters from a given origin") characters: CharactersArgs => URIO[ExampleService, List[Character]], @GQLDeprecated("Use `characters`") character: CharacterArgs => URIO[ExampleService, Option[Character]] ) case class Mutations(deleteCharacter: CharacterArgs => URIO[ExampleService, Boolean]) case class Subscriptions(characterDeleted: ZStream[ExampleService, Nothing, String]) implicit val roleSchema = gen[Role] implicit val characterSchema = gen[Character] implicit val characterArgsSchema = gen[CharacterArgs] implicit val charactersArgsSchema = gen[CharactersArgs] val api: GraphQL[Console with Clock with ExampleService] = graphQL( RootResolver( Queries( args => ExampleService.getCharacters(args.origin), args => ExampleService.findCharacter(args.name) ), Mutations(args => ExampleService.deleteCharacter(args.name)), Subscriptions(ExampleService.deletedEvents) ) ) @@ maxFields(200) @@ // query analyzer that limit query fields maxDepth(30) @@ // query analyzer that limit query depth timeout(3 seconds) @@ // wrapper that fails slow queries printSlowQueries(500 millis) @@ // wrapper that logs slow queries printErrors @@ // wrapper that logs errors apolloTracing // wrapper for https://github.com/apollographql/apollo-tracing }
diegopacheco/scala-playground
caliban-graphql-fun/src/main/scala/com/github/diegopacheco/scalaplayground/caliban/ExampleApi.scala
Scala
unlicense
2,194
/////////////////////////////////////////////////////////////////////////////// // CellDist.scala // // Copyright (C) 2010-2014 Ben Wing, The University of Texas at Austin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////////// package opennlp.textgrounder package gridlocate import collection.mutable import util.error.warning import util.print.errprint import langmodel.{Gram,LangModel} /** * Probability distribution over cells. Instances of this class are normally * generated by `CellDistFactory`. * @param cellprobs List of cells and associated probabilities * @param normalized Whether the probability distribution is normalized */ class CellDist[Co]( val cellprobs: Iterable[(GridCell[Co], Double)], val normalized: Boolean, val empty: Boolean ) { /** * Return a ranked list of all the cells. We may need to add the * specified correct cell to the list. See `Ranker.evaluate`. */ def get_ranked_cells(correct: Option[GridCell[Co]], include_correct: Boolean): IndexedSeq[(GridCell[Co], Double)] = { val probs = if (!include_correct) cellprobs else // Elements on right override those on left Map(correct.get -> 0.0) ++ cellprobs.toMap // sort by second element of tuple, in reverse order probs.toIndexedSeq sortWith (_._2 > _._2) } } /** * Factory object for creating CellDists, i.e. objects describing a * probability distribution over cells. */ class CellDistFactory[Co] { /** * Create normalized cell dist from unnormalized dist. */ def create_normalized_cell_dist(cellprobs: Iterable[(GridCell[Co], Double)], normalize: Boolean = true ) = { // Normalize the probabilities; but if all probabilities are 0, then // we can't normalize, so leave as-is. This will happen, for example, // for words never seen in the entire corpus. val totalprob = cellprobs.map(_._2).sum val (normalized, empty, norm_cellprobs) = if (totalprob == 0) (false, true, cellprobs) else if (!normalize) (false, false, cellprobs) else (true, false, cellprobs.map { case (cell, prob) => (cell, prob / totalprob) }) new CellDist[Co](norm_cellprobs, normalized, empty) } /** * Create a distribution over cells from the number of documents in * each cell. */ def get_cell_dist_from_doc_count(grid: Grid[Co], normalize: Boolean = true) = { create_normalized_cell_dist(grid.iter_nonempty_cells.map { cell => (cell, cell.num_docs.toDouble) }, normalize) } /** * Create a distribution over cells that is associated with a gram, * based on the relative probabilities of the gram in the language models * of the various cells. That is, if we have a set of cells, each with a * language model, then we can imagine conceptually inverting the process * to generate a cell distribution over grams. Basically, for a given gram, * look to see what its probability is in all cells; normalize, and we have * a cell distribution. */ def get_cell_dist(grid: Grid[Co], gram: Gram) = { create_normalized_cell_dist(grid.iter_nonempty_cells.map { cell => (cell, cell.grid_lm.gram_prob(gram)) }) } /** * Return a cell distribution over a language model, in the form of a * list of pairs of cells and probabilities. This works * by adding up the language models of the individual grams, * weighting by the count of the each gram. */ def get_cell_dist_for_lang_model[Co](grid: Grid[Co], lang_model: LangModel) = { val base_cells = grid.iter_nonempty_cells val parallel = !grid.driver.params.no_parallel val cells = if (parallel) base_cells.par else base_cells val norm_factors = lang_model.iter_grams.map { case (gram, count) => val raw_factor = cells.map(cell => cell.grid_lm.gram_prob(gram)).sum val norm_factor = if (raw_factor == 0) 1.0 else 1.0/raw_factor (gram, count * norm_factor) } val cellprobs = cells.map { cell => val cellprob = norm_factors.map { case (gram, factor) => factor * cell.grid_lm.gram_prob(gram) }.sum (cell, cellprob) } // Renormalize to produce a probability distribution; but if all // probabilities are 0, then we can't normalize, so leave as-is. // This will happen, for example, for words never seen in the entire // corpus. val totalprob = cellprobs.map(_._2).sum val (normalized, total_norm_factor) = if (totalprob == 0) (false, 1.0) else (true, 1.0/totalprob) val normed_cell_probs = cellprobs.map { case (cell, cellprob) => (cell, total_norm_factor * cellprob) } new CellDist[Co](normed_cell_probs.toIndexedSeq, normalized, normalized) } }
utcompling/textgrounder
src/main/scala/opennlp/textgrounder/gridlocate/CellDist.scala
Scala
apache-2.0
5,454
/* * Copyright 2001-2013 Artima, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.scalatest.examples.refspec.composingbeforeandaftereach import org.scalatest._ import refspec.RefSpec import collection.mutable.ListBuffer trait Builder extends BeforeAndAfterEach { this: Suite => val builder = new StringBuilder override def beforeEach() { builder.append("ScalaTest is ") super.beforeEach() // To be stackable, must call super.beforeEach } override def afterEach() { try super.afterEach() // To be stackable, must call super.afterEach finally builder.clear() } } trait Buffer extends BeforeAndAfterEach { this: Suite => val buffer = new ListBuffer[String] override def afterEach() { try super.afterEach() // To be stackable, must call super.afterEach finally buffer.clear() } } class ExampleSpec extends RefSpec with Builder with Buffer { object `Testing ` { def `should be easy` { builder.append("easy!") assert(builder.toString === "ScalaTest is easy!") assert(buffer.isEmpty) buffer += "sweet" } def `should be fun` { builder.append("fun!") assert(builder.toString === "ScalaTest is fun!") assert(buffer.isEmpty) buffer += "clear" } } }
dotty-staging/scalatest
examples/src/test/scala/org/scalatest/examples/refspec/composingbeforeandaftereach/ExampleSpec.scala
Scala
apache-2.0
1,798
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark import scala.collection.mutable import org.scalatest.{BeforeAndAfter, Ignore, PrivateMethodTester} import org.apache.spark.executor.TaskMetrics import org.apache.spark.scheduler._ import org.apache.spark.scheduler.ExternalClusterManager import org.apache.spark.scheduler.cluster.ExecutorInfo import org.apache.spark.scheduler.local.LocalSchedulerBackend import org.apache.spark.util.ManualClock /** * Test add and remove behavior of ExecutorAllocationManager. */ @Ignore class ExecutorAllocationManagerSuite extends SparkFunSuite with LocalSparkContext with BeforeAndAfter { import ExecutorAllocationManager._ import ExecutorAllocationManagerSuite._ private val contexts = new mutable.ListBuffer[SparkContext]() before { contexts.clear() } after { contexts.foreach(_.stop()) } test("verify min/max executors") { val conf = new SparkConf() .setMaster("myDummyLocalExternalClusterManager") .setAppName("test-executor-allocation-manager") .set("spark.dynamicAllocation.enabled", "true") .set("spark.dynamicAllocation.testing", "true") val sc0 = new SparkContext(conf) contexts += sc0 assert(sc0.executorAllocationManager.isDefined) sc0.stop() // Min < 0 val conf1 = conf.clone().set("spark.dynamicAllocation.minExecutors", "-1") intercept[SparkException] { contexts += new SparkContext(conf1) } // Max < 0 val conf2 = conf.clone().set("spark.dynamicAllocation.maxExecutors", "-1") intercept[SparkException] { contexts += new SparkContext(conf2) } // Both min and max, but min > max intercept[SparkException] { createSparkContext(2, 1) } // Both min and max, and min == max val sc1 = createSparkContext(1, 1) assert(sc1.executorAllocationManager.isDefined) sc1.stop() // Both min and max, and min < max val sc2 = createSparkContext(1, 2) assert(sc2.executorAllocationManager.isDefined) sc2.stop() } test("starting state") { sc = createSparkContext() val manager = sc.executorAllocationManager.get assert(numExecutorsTarget(manager) === 1) assert(executorsPendingToRemove(manager).isEmpty) assert(executorIds(manager).isEmpty) assert(addTime(manager) === ExecutorAllocationManager.NOT_SET) assert(removeTimes(manager).isEmpty) } test("add executors") { sc = createSparkContext(1, 10, 1) val manager = sc.executorAllocationManager.get sc.listenerBus.postToAll(SparkListenerStageSubmitted(createStageInfo(0, 1000))) // Keep adding until the limit is reached assert(numExecutorsTarget(manager) === 1) assert(numExecutorsToAdd(manager) === 1) assert(addExecutors(manager) === 1) assert(numExecutorsTarget(manager) === 2) assert(numExecutorsToAdd(manager) === 2) assert(addExecutors(manager) === 2) assert(numExecutorsTarget(manager) === 4) assert(numExecutorsToAdd(manager) === 4) assert(addExecutors(manager) === 4) assert(numExecutorsTarget(manager) === 8) assert(numExecutorsToAdd(manager) === 8) assert(addExecutors(manager) === 2) // reached the limit of 10 assert(numExecutorsTarget(manager) === 10) assert(numExecutorsToAdd(manager) === 1) assert(addExecutors(manager) === 0) assert(numExecutorsTarget(manager) === 10) assert(numExecutorsToAdd(manager) === 1) // Register previously requested executors onExecutorAdded(manager, "first") assert(numExecutorsTarget(manager) === 10) onExecutorAdded(manager, "second") onExecutorAdded(manager, "third") onExecutorAdded(manager, "fourth") assert(numExecutorsTarget(manager) === 10) onExecutorAdded(manager, "first") // duplicates should not count onExecutorAdded(manager, "second") assert(numExecutorsTarget(manager) === 10) // Try adding again // This should still fail because the number pending + running is still at the limit assert(addExecutors(manager) === 0) assert(numExecutorsTarget(manager) === 10) assert(numExecutorsToAdd(manager) === 1) assert(addExecutors(manager) === 0) assert(numExecutorsTarget(manager) === 10) assert(numExecutorsToAdd(manager) === 1) } test("add executors capped by num pending tasks") { sc = createSparkContext(0, 10, 0) val manager = sc.executorAllocationManager.get sc.listenerBus.postToAll(SparkListenerStageSubmitted(createStageInfo(0, 5))) // Verify that we're capped at number of tasks in the stage assert(numExecutorsTarget(manager) === 0) assert(numExecutorsToAdd(manager) === 1) assert(addExecutors(manager) === 1) assert(numExecutorsTarget(manager) === 1) assert(numExecutorsToAdd(manager) === 2) assert(addExecutors(manager) === 2) assert(numExecutorsTarget(manager) === 3) assert(numExecutorsToAdd(manager) === 4) assert(addExecutors(manager) === 2) assert(numExecutorsTarget(manager) === 5) assert(numExecutorsToAdd(manager) === 1) // Verify that running a task doesn't affect the target sc.listenerBus.postToAll(SparkListenerStageSubmitted(createStageInfo(1, 3))) sc.listenerBus.postToAll(SparkListenerExecutorAdded( 0L, "executor-1", new ExecutorInfo("host1", 1, Map.empty))) sc.listenerBus.postToAll(SparkListenerTaskStart(1, 0, createTaskInfo(0, 0, "executor-1"))) assert(numExecutorsTarget(manager) === 5) assert(addExecutors(manager) === 1) assert(numExecutorsTarget(manager) === 6) assert(numExecutorsToAdd(manager) === 2) assert(addExecutors(manager) === 2) assert(numExecutorsTarget(manager) === 8) assert(numExecutorsToAdd(manager) === 4) assert(addExecutors(manager) === 0) assert(numExecutorsTarget(manager) === 8) assert(numExecutorsToAdd(manager) === 1) // Verify that re-running a task doesn't blow things up sc.listenerBus.postToAll(SparkListenerStageSubmitted(createStageInfo(2, 3))) sc.listenerBus.postToAll(SparkListenerTaskStart(2, 0, createTaskInfo(0, 0, "executor-1"))) sc.listenerBus.postToAll(SparkListenerTaskStart(2, 0, createTaskInfo(1, 0, "executor-1"))) assert(addExecutors(manager) === 1) assert(numExecutorsTarget(manager) === 9) assert(numExecutorsToAdd(manager) === 2) assert(addExecutors(manager) === 1) assert(numExecutorsTarget(manager) === 10) assert(numExecutorsToAdd(manager) === 1) // Verify that running a task once we're at our limit doesn't blow things up sc.listenerBus.postToAll(SparkListenerTaskStart(2, 0, createTaskInfo(0, 1, "executor-1"))) assert(addExecutors(manager) === 0) assert(numExecutorsTarget(manager) === 10) } test("cancel pending executors when no longer needed") { sc = createSparkContext(0, 10, 0) val manager = sc.executorAllocationManager.get sc.listenerBus.postToAll(SparkListenerStageSubmitted(createStageInfo(2, 5))) assert(numExecutorsTarget(manager) === 0) assert(numExecutorsToAdd(manager) === 1) assert(addExecutors(manager) === 1) assert(numExecutorsTarget(manager) === 1) assert(numExecutorsToAdd(manager) === 2) assert(addExecutors(manager) === 2) assert(numExecutorsTarget(manager) === 3) val task1Info = createTaskInfo(0, 0, "executor-1") sc.listenerBus.postToAll(SparkListenerTaskStart(2, 0, task1Info)) assert(numExecutorsToAdd(manager) === 4) assert(addExecutors(manager) === 2) val task2Info = createTaskInfo(1, 0, "executor-1") sc.listenerBus.postToAll(SparkListenerTaskStart(2, 0, task2Info)) sc.listenerBus.postToAll(SparkListenerTaskEnd(2, 0, null, Success, task1Info, null)) sc.listenerBus.postToAll(SparkListenerTaskEnd(2, 0, null, Success, task2Info, null)) assert(adjustRequestedExecutors(manager) === -1) } test("remove executors") { sc = createSparkContext(5, 10, 5) val manager = sc.executorAllocationManager.get (1 to 10).map(_.toString).foreach { id => onExecutorAdded(manager, id) } // Keep removing until the limit is reached assert(executorsPendingToRemove(manager).isEmpty) assert(removeExecutor(manager, "1")) assert(executorsPendingToRemove(manager).size === 1) assert(executorsPendingToRemove(manager).contains("1")) assert(removeExecutor(manager, "2")) assert(removeExecutor(manager, "3")) assert(executorsPendingToRemove(manager).size === 3) assert(executorsPendingToRemove(manager).contains("2")) assert(executorsPendingToRemove(manager).contains("3")) assert(!removeExecutor(manager, "100")) // remove non-existent executors assert(!removeExecutor(manager, "101")) assert(executorsPendingToRemove(manager).size === 3) assert(removeExecutor(manager, "4")) assert(removeExecutor(manager, "5")) assert(!removeExecutor(manager, "6")) // reached the limit of 5 assert(executorsPendingToRemove(manager).size === 5) assert(executorsPendingToRemove(manager).contains("4")) assert(executorsPendingToRemove(manager).contains("5")) assert(!executorsPendingToRemove(manager).contains("6")) // Kill executors previously requested to remove onExecutorRemoved(manager, "1") assert(executorsPendingToRemove(manager).size === 4) assert(!executorsPendingToRemove(manager).contains("1")) onExecutorRemoved(manager, "2") onExecutorRemoved(manager, "3") assert(executorsPendingToRemove(manager).size === 2) assert(!executorsPendingToRemove(manager).contains("2")) assert(!executorsPendingToRemove(manager).contains("3")) onExecutorRemoved(manager, "2") // duplicates should not count onExecutorRemoved(manager, "3") assert(executorsPendingToRemove(manager).size === 2) onExecutorRemoved(manager, "4") onExecutorRemoved(manager, "5") assert(executorsPendingToRemove(manager).isEmpty) // Try removing again // This should still fail because the number pending + running is still at the limit assert(!removeExecutor(manager, "7")) assert(executorsPendingToRemove(manager).isEmpty) assert(!removeExecutor(manager, "8")) assert(executorsPendingToRemove(manager).isEmpty) } test("remove multiple executors") { sc = createSparkContext(5, 10, 5) val manager = sc.executorAllocationManager.get (1 to 10).map(_.toString).foreach { id => onExecutorAdded(manager, id) } // Keep removing until the limit is reached assert(executorsPendingToRemove(manager).isEmpty) assert(removeExecutors(manager, Seq("1")) === Seq("1")) assert(executorsPendingToRemove(manager).size === 1) assert(executorsPendingToRemove(manager).contains("1")) assert(removeExecutors(manager, Seq("2", "3")) === Seq("2", "3")) assert(executorsPendingToRemove(manager).size === 3) assert(executorsPendingToRemove(manager).contains("2")) assert(executorsPendingToRemove(manager).contains("3")) assert(!removeExecutor(manager, "100")) // remove non-existent executors assert(removeExecutors(manager, Seq("101", "102")) !== Seq("101", "102")) assert(executorsPendingToRemove(manager).size === 3) assert(removeExecutor(manager, "4")) assert(removeExecutors(manager, Seq("5")) === Seq("5")) assert(!removeExecutor(manager, "6")) // reached the limit of 5 assert(executorsPendingToRemove(manager).size === 5) assert(executorsPendingToRemove(manager).contains("4")) assert(executorsPendingToRemove(manager).contains("5")) assert(!executorsPendingToRemove(manager).contains("6")) // Kill executors previously requested to remove onExecutorRemoved(manager, "1") assert(executorsPendingToRemove(manager).size === 4) assert(!executorsPendingToRemove(manager).contains("1")) onExecutorRemoved(manager, "2") onExecutorRemoved(manager, "3") assert(executorsPendingToRemove(manager).size === 2) assert(!executorsPendingToRemove(manager).contains("2")) assert(!executorsPendingToRemove(manager).contains("3")) onExecutorRemoved(manager, "2") // duplicates should not count onExecutorRemoved(manager, "3") assert(executorsPendingToRemove(manager).size === 2) onExecutorRemoved(manager, "4") onExecutorRemoved(manager, "5") assert(executorsPendingToRemove(manager).isEmpty) // Try removing again // This should still fail because the number pending + running is still at the limit assert(!removeExecutor(manager, "7")) assert(executorsPendingToRemove(manager).isEmpty) assert(removeExecutors(manager, Seq("8")) !== Seq("8")) assert(executorsPendingToRemove(manager).isEmpty) } test ("interleaving add and remove") { sc = createSparkContext(5, 10, 5) val manager = sc.executorAllocationManager.get sc.listenerBus.postToAll(SparkListenerStageSubmitted(createStageInfo(0, 1000))) // Add a few executors assert(addExecutors(manager) === 1) assert(addExecutors(manager) === 2) onExecutorAdded(manager, "1") onExecutorAdded(manager, "2") onExecutorAdded(manager, "3") onExecutorAdded(manager, "4") onExecutorAdded(manager, "5") onExecutorAdded(manager, "6") onExecutorAdded(manager, "7") onExecutorAdded(manager, "8") assert(executorIds(manager).size === 8) // Remove until limit assert(removeExecutor(manager, "1")) assert(removeExecutors(manager, Seq("2", "3")) === Seq("2", "3")) assert(!removeExecutor(manager, "4")) // lower limit reached assert(!removeExecutor(manager, "5")) onExecutorRemoved(manager, "1") onExecutorRemoved(manager, "2") onExecutorRemoved(manager, "3") assert(executorIds(manager).size === 5) // Add until limit assert(addExecutors(manager) === 2) // upper limit reached assert(addExecutors(manager) === 0) assert(!removeExecutor(manager, "4")) // still at lower limit assert((manager, Seq("5")) !== Seq("5")) onExecutorAdded(manager, "9") onExecutorAdded(manager, "10") onExecutorAdded(manager, "11") onExecutorAdded(manager, "12") onExecutorAdded(manager, "13") assert(executorIds(manager).size === 10) // Remove succeeds again, now that we are no longer at the lower limit assert(removeExecutors(manager, Seq("4", "5", "6")) === Seq("4", "5", "6")) assert(removeExecutor(manager, "7")) assert(executorIds(manager).size === 10) assert(addExecutors(manager) === 0) onExecutorRemoved(manager, "4") onExecutorRemoved(manager, "5") assert(executorIds(manager).size === 8) // Number of executors pending restarts at 1 assert(numExecutorsToAdd(manager) === 1) assert(addExecutors(manager) === 0) assert(executorIds(manager).size === 8) onExecutorRemoved(manager, "6") onExecutorRemoved(manager, "7") onExecutorAdded(manager, "14") onExecutorAdded(manager, "15") assert(executorIds(manager).size === 8) assert(addExecutors(manager) === 0) // still at upper limit onExecutorAdded(manager, "16") onExecutorAdded(manager, "17") assert(executorIds(manager).size === 10) assert(numExecutorsTarget(manager) === 10) } test("starting/canceling add timer") { sc = createSparkContext(2, 10, 2) val clock = new ManualClock(8888L) val manager = sc.executorAllocationManager.get manager.setClock(clock) // Starting add timer is idempotent assert(addTime(manager) === NOT_SET) onSchedulerBacklogged(manager) val firstAddTime = addTime(manager) assert(firstAddTime === clock.getTimeMillis + schedulerBacklogTimeout * 1000) clock.advance(100L) onSchedulerBacklogged(manager) assert(addTime(manager) === firstAddTime) // timer is already started clock.advance(200L) onSchedulerBacklogged(manager) assert(addTime(manager) === firstAddTime) onSchedulerQueueEmpty(manager) // Restart add timer clock.advance(1000L) assert(addTime(manager) === NOT_SET) onSchedulerBacklogged(manager) val secondAddTime = addTime(manager) assert(secondAddTime === clock.getTimeMillis + schedulerBacklogTimeout * 1000) clock.advance(100L) onSchedulerBacklogged(manager) assert(addTime(manager) === secondAddTime) // timer is already started assert(addTime(manager) !== firstAddTime) assert(firstAddTime !== secondAddTime) } test("starting/canceling remove timers") { sc = createSparkContext(2, 10, 2) val clock = new ManualClock(14444L) val manager = sc.executorAllocationManager.get manager.setClock(clock) executorIds(manager).asInstanceOf[mutable.Set[String]] ++= List("1", "2", "3") // Starting remove timer is idempotent for each executor assert(removeTimes(manager).isEmpty) onExecutorIdle(manager, "1") assert(removeTimes(manager).size === 1) assert(removeTimes(manager).contains("1")) val firstRemoveTime = removeTimes(manager)("1") assert(firstRemoveTime === clock.getTimeMillis + executorIdleTimeout * 1000) clock.advance(100L) onExecutorIdle(manager, "1") assert(removeTimes(manager)("1") === firstRemoveTime) // timer is already started clock.advance(200L) onExecutorIdle(manager, "1") assert(removeTimes(manager)("1") === firstRemoveTime) clock.advance(300L) onExecutorIdle(manager, "2") assert(removeTimes(manager)("2") !== firstRemoveTime) // different executor assert(removeTimes(manager)("2") === clock.getTimeMillis + executorIdleTimeout * 1000) clock.advance(400L) onExecutorIdle(manager, "3") assert(removeTimes(manager)("3") !== firstRemoveTime) assert(removeTimes(manager)("3") === clock.getTimeMillis + executorIdleTimeout * 1000) assert(removeTimes(manager).size === 3) assert(removeTimes(manager).contains("2")) assert(removeTimes(manager).contains("3")) // Restart remove timer clock.advance(1000L) onExecutorBusy(manager, "1") assert(removeTimes(manager).size === 2) onExecutorIdle(manager, "1") assert(removeTimes(manager).size === 3) assert(removeTimes(manager).contains("1")) val secondRemoveTime = removeTimes(manager)("1") assert(secondRemoveTime === clock.getTimeMillis + executorIdleTimeout * 1000) assert(removeTimes(manager)("1") === secondRemoveTime) // timer is already started assert(removeTimes(manager)("1") !== firstRemoveTime) assert(firstRemoveTime !== secondRemoveTime) } test("mock polling loop with no events") { sc = createSparkContext(0, 20, 0) val manager = sc.executorAllocationManager.get val clock = new ManualClock(2020L) manager.setClock(clock) // No events - we should not be adding or removing assert(numExecutorsTarget(manager) === 0) assert(executorsPendingToRemove(manager).isEmpty) schedule(manager) assert(numExecutorsTarget(manager) === 0) assert(executorsPendingToRemove(manager).isEmpty) clock.advance(100L) schedule(manager) assert(numExecutorsTarget(manager) === 0) assert(executorsPendingToRemove(manager).isEmpty) clock.advance(1000L) schedule(manager) assert(numExecutorsTarget(manager) === 0) assert(executorsPendingToRemove(manager).isEmpty) clock.advance(10000L) schedule(manager) assert(numExecutorsTarget(manager) === 0) assert(executorsPendingToRemove(manager).isEmpty) } test("mock polling loop add behavior") { sc = createSparkContext(0, 20, 0) val clock = new ManualClock(2020L) val manager = sc.executorAllocationManager.get manager.setClock(clock) sc.listenerBus.postToAll(SparkListenerStageSubmitted(createStageInfo(0, 1000))) // Scheduler queue backlogged onSchedulerBacklogged(manager) clock.advance(schedulerBacklogTimeout * 1000 / 2) schedule(manager) assert(numExecutorsTarget(manager) === 0) // timer not exceeded yet clock.advance(schedulerBacklogTimeout * 1000) schedule(manager) assert(numExecutorsTarget(manager) === 1) // first timer exceeded clock.advance(sustainedSchedulerBacklogTimeout * 1000 / 2) schedule(manager) assert(numExecutorsTarget(manager) === 1) // second timer not exceeded yet clock.advance(sustainedSchedulerBacklogTimeout * 1000) schedule(manager) assert(numExecutorsTarget(manager) === 1 + 2) // second timer exceeded clock.advance(sustainedSchedulerBacklogTimeout * 1000) schedule(manager) assert(numExecutorsTarget(manager) === 1 + 2 + 4) // third timer exceeded // Scheduler queue drained onSchedulerQueueEmpty(manager) clock.advance(sustainedSchedulerBacklogTimeout * 1000) schedule(manager) assert(numExecutorsTarget(manager) === 7) // timer is canceled clock.advance(sustainedSchedulerBacklogTimeout * 1000) schedule(manager) assert(numExecutorsTarget(manager) === 7) // Scheduler queue backlogged again onSchedulerBacklogged(manager) clock.advance(schedulerBacklogTimeout * 1000) schedule(manager) assert(numExecutorsTarget(manager) === 7 + 1) // timer restarted clock.advance(sustainedSchedulerBacklogTimeout * 1000) schedule(manager) assert(numExecutorsTarget(manager) === 7 + 1 + 2) clock.advance(sustainedSchedulerBacklogTimeout * 1000) schedule(manager) assert(numExecutorsTarget(manager) === 7 + 1 + 2 + 4) clock.advance(sustainedSchedulerBacklogTimeout * 1000) schedule(manager) assert(numExecutorsTarget(manager) === 20) // limit reached } test("mock polling loop remove behavior") { sc = createSparkContext(1, 20, 1) val clock = new ManualClock(2020L) val manager = sc.executorAllocationManager.get manager.setClock(clock) // Remove idle executors on timeout onExecutorAdded(manager, "executor-1") onExecutorAdded(manager, "executor-2") onExecutorAdded(manager, "executor-3") assert(removeTimes(manager).size === 3) assert(executorsPendingToRemove(manager).isEmpty) clock.advance(executorIdleTimeout * 1000 / 2) schedule(manager) assert(removeTimes(manager).size === 3) // idle threshold not reached yet assert(executorsPendingToRemove(manager).isEmpty) clock.advance(executorIdleTimeout * 1000) schedule(manager) assert(removeTimes(manager).isEmpty) // idle threshold exceeded assert(executorsPendingToRemove(manager).size === 2) // limit reached (1 executor remaining) // Mark a subset as busy - only idle executors should be removed onExecutorAdded(manager, "executor-4") onExecutorAdded(manager, "executor-5") onExecutorAdded(manager, "executor-6") onExecutorAdded(manager, "executor-7") assert(removeTimes(manager).size === 5) // 5 active executors assert(executorsPendingToRemove(manager).size === 2) // 2 pending to be removed onExecutorBusy(manager, "executor-4") onExecutorBusy(manager, "executor-5") onExecutorBusy(manager, "executor-6") // 3 busy and 2 idle (of the 5 active ones) schedule(manager) assert(removeTimes(manager).size === 2) // remove only idle executors assert(!removeTimes(manager).contains("executor-4")) assert(!removeTimes(manager).contains("executor-5")) assert(!removeTimes(manager).contains("executor-6")) assert(executorsPendingToRemove(manager).size === 2) clock.advance(executorIdleTimeout * 1000) schedule(manager) assert(removeTimes(manager).isEmpty) // idle executors are removed assert(executorsPendingToRemove(manager).size === 4) assert(!executorsPendingToRemove(manager).contains("executor-4")) assert(!executorsPendingToRemove(manager).contains("executor-5")) assert(!executorsPendingToRemove(manager).contains("executor-6")) // Busy executors are now idle and should be removed onExecutorIdle(manager, "executor-4") onExecutorIdle(manager, "executor-5") onExecutorIdle(manager, "executor-6") schedule(manager) assert(removeTimes(manager).size === 3) // 0 busy and 3 idle assert(removeTimes(manager).contains("executor-4")) assert(removeTimes(manager).contains("executor-5")) assert(removeTimes(manager).contains("executor-6")) assert(executorsPendingToRemove(manager).size === 4) clock.advance(executorIdleTimeout * 1000) schedule(manager) assert(removeTimes(manager).isEmpty) assert(executorsPendingToRemove(manager).size === 6) // limit reached (1 executor remaining) } test("listeners trigger add executors correctly") { sc = createSparkContext(2, 10, 2) val manager = sc.executorAllocationManager.get assert(addTime(manager) === NOT_SET) // Starting a stage should start the add timer val numTasks = 10 sc.listenerBus.postToAll(SparkListenerStageSubmitted(createStageInfo(0, numTasks))) assert(addTime(manager) !== NOT_SET) // Starting a subset of the tasks should not cancel the add timer val taskInfos = (0 to numTasks - 1).map { i => createTaskInfo(i, i, "executor-1") } taskInfos.tail.foreach { info => sc.listenerBus.postToAll(SparkListenerTaskStart(0, 0, info)) } assert(addTime(manager) !== NOT_SET) // Starting all remaining tasks should cancel the add timer sc.listenerBus.postToAll(SparkListenerTaskStart(0, 0, taskInfos.head)) assert(addTime(manager) === NOT_SET) // Start two different stages // The add timer should be canceled only if all tasks in both stages start running sc.listenerBus.postToAll(SparkListenerStageSubmitted(createStageInfo(1, numTasks))) sc.listenerBus.postToAll(SparkListenerStageSubmitted(createStageInfo(2, numTasks))) assert(addTime(manager) !== NOT_SET) taskInfos.foreach { info => sc.listenerBus.postToAll(SparkListenerTaskStart(1, 0, info)) } assert(addTime(manager) !== NOT_SET) taskInfos.foreach { info => sc.listenerBus.postToAll(SparkListenerTaskStart(2, 0, info)) } assert(addTime(manager) === NOT_SET) } test("listeners trigger remove executors correctly") { sc = createSparkContext(2, 10, 2) val manager = sc.executorAllocationManager.get assert(removeTimes(manager).isEmpty) // Added executors should start the remove timers for each executor (1 to 5).map("executor-" + _).foreach { id => onExecutorAdded(manager, id) } assert(removeTimes(manager).size === 5) // Starting a task cancel the remove timer for that executor sc.listenerBus.postToAll(SparkListenerTaskStart(0, 0, createTaskInfo(0, 0, "executor-1"))) sc.listenerBus.postToAll(SparkListenerTaskStart(0, 0, createTaskInfo(1, 1, "executor-1"))) sc.listenerBus.postToAll(SparkListenerTaskStart(0, 0, createTaskInfo(2, 2, "executor-2"))) assert(removeTimes(manager).size === 3) assert(!removeTimes(manager).contains("executor-1")) assert(!removeTimes(manager).contains("executor-2")) // Finishing all tasks running on an executor should start the remove timer for that executor sc.listenerBus.postToAll(SparkListenerTaskEnd( 0, 0, "task-type", Success, createTaskInfo(0, 0, "executor-1"), new TaskMetrics)) sc.listenerBus.postToAll(SparkListenerTaskEnd( 0, 0, "task-type", Success, createTaskInfo(2, 2, "executor-2"), new TaskMetrics)) assert(removeTimes(manager).size === 4) assert(!removeTimes(manager).contains("executor-1")) // executor-1 has not finished yet assert(removeTimes(manager).contains("executor-2")) sc.listenerBus.postToAll(SparkListenerTaskEnd( 0, 0, "task-type", Success, createTaskInfo(1, 1, "executor-1"), new TaskMetrics)) assert(removeTimes(manager).size === 5) assert(removeTimes(manager).contains("executor-1")) // executor-1 has now finished } test("listeners trigger add and remove executor callbacks correctly") { sc = createSparkContext(2, 10, 2) val manager = sc.executorAllocationManager.get assert(executorIds(manager).isEmpty) assert(removeTimes(manager).isEmpty) // New executors have registered sc.listenerBus.postToAll(SparkListenerExecutorAdded( 0L, "executor-1", new ExecutorInfo("host1", 1, Map.empty))) assert(executorIds(manager).size === 1) assert(executorIds(manager).contains("executor-1")) assert(removeTimes(manager).size === 1) assert(removeTimes(manager).contains("executor-1")) sc.listenerBus.postToAll(SparkListenerExecutorAdded( 0L, "executor-2", new ExecutorInfo("host2", 1, Map.empty))) assert(executorIds(manager).size === 2) assert(executorIds(manager).contains("executor-2")) assert(removeTimes(manager).size === 2) assert(removeTimes(manager).contains("executor-2")) // Existing executors have disconnected sc.listenerBus.postToAll(SparkListenerExecutorRemoved(0L, "executor-1", "")) assert(executorIds(manager).size === 1) assert(!executorIds(manager).contains("executor-1")) assert(removeTimes(manager).size === 1) assert(!removeTimes(manager).contains("executor-1")) // Unknown executor has disconnected sc.listenerBus.postToAll(SparkListenerExecutorRemoved(0L, "executor-3", "")) assert(executorIds(manager).size === 1) assert(removeTimes(manager).size === 1) } test("SPARK-4951: call onTaskStart before onBlockManagerAdded") { sc = createSparkContext(2, 10, 2) val manager = sc.executorAllocationManager.get assert(executorIds(manager).isEmpty) assert(removeTimes(manager).isEmpty) sc.listenerBus.postToAll(SparkListenerTaskStart(0, 0, createTaskInfo(0, 0, "executor-1"))) sc.listenerBus.postToAll(SparkListenerExecutorAdded( 0L, "executor-1", new ExecutorInfo("host1", 1, Map.empty))) assert(executorIds(manager).size === 1) assert(executorIds(manager).contains("executor-1")) assert(removeTimes(manager).size === 0) } test("SPARK-4951: onExecutorAdded should not add a busy executor to removeTimes") { sc = createSparkContext(2, 10) val manager = sc.executorAllocationManager.get assert(executorIds(manager).isEmpty) assert(removeTimes(manager).isEmpty) sc.listenerBus.postToAll(SparkListenerExecutorAdded( 0L, "executor-1", new ExecutorInfo("host1", 1, Map.empty))) sc.listenerBus.postToAll(SparkListenerTaskStart(0, 0, createTaskInfo(0, 0, "executor-1"))) assert(executorIds(manager).size === 1) assert(executorIds(manager).contains("executor-1")) assert(removeTimes(manager).size === 0) sc.listenerBus.postToAll(SparkListenerExecutorAdded( 0L, "executor-2", new ExecutorInfo("host1", 1, Map.empty))) assert(executorIds(manager).size === 2) assert(executorIds(manager).contains("executor-2")) assert(removeTimes(manager).size === 1) assert(removeTimes(manager).contains("executor-2")) assert(!removeTimes(manager).contains("executor-1")) } test("avoid ramp up when target < running executors") { sc = createSparkContext(0, 100000, 0) val manager = sc.executorAllocationManager.get val stage1 = createStageInfo(0, 1000) sc.listenerBus.postToAll(SparkListenerStageSubmitted(stage1)) assert(addExecutors(manager) === 1) assert(addExecutors(manager) === 2) assert(addExecutors(manager) === 4) assert(addExecutors(manager) === 8) assert(numExecutorsTarget(manager) === 15) (0 until 15).foreach { i => onExecutorAdded(manager, s"executor-$i") } assert(executorIds(manager).size === 15) sc.listenerBus.postToAll(SparkListenerStageCompleted(stage1)) adjustRequestedExecutors(manager) assert(numExecutorsTarget(manager) === 0) sc.listenerBus.postToAll(SparkListenerStageSubmitted(createStageInfo(1, 1000))) addExecutors(manager) assert(numExecutorsTarget(manager) === 16) } test("avoid ramp down initial executors until first job is submitted") { sc = createSparkContext(2, 5, 3) val manager = sc.executorAllocationManager.get val clock = new ManualClock(10000L) manager.setClock(clock) // Verify the initial number of executors assert(numExecutorsTarget(manager) === 3) schedule(manager) // Verify whether the initial number of executors is kept with no pending tasks assert(numExecutorsTarget(manager) === 3) sc.listenerBus.postToAll(SparkListenerStageSubmitted(createStageInfo(1, 2))) clock.advance(100L) assert(maxNumExecutorsNeeded(manager) === 2) schedule(manager) // Verify that current number of executors should be ramp down when first job is submitted assert(numExecutorsTarget(manager) === 2) } test("avoid ramp down initial executors until idle executor is timeout") { sc = createSparkContext(2, 5, 3) val manager = sc.executorAllocationManager.get val clock = new ManualClock(10000L) manager.setClock(clock) // Verify the initial number of executors assert(numExecutorsTarget(manager) === 3) schedule(manager) // Verify the initial number of executors is kept when no pending tasks assert(numExecutorsTarget(manager) === 3) (0 until 3).foreach { i => onExecutorAdded(manager, s"executor-$i") } clock.advance(executorIdleTimeout * 1000) assert(maxNumExecutorsNeeded(manager) === 0) schedule(manager) // Verify executor is timeout but numExecutorsTarget is not recalculated assert(numExecutorsTarget(manager) === 3) // Schedule again to recalculate the numExecutorsTarget after executor is timeout schedule(manager) // Verify that current number of executors should be ramp down when executor is timeout assert(numExecutorsTarget(manager) === 2) } test("get pending task number and related locality preference") { sc = createSparkContext(2, 5, 3) val manager = sc.executorAllocationManager.get val localityPreferences1 = Seq( Seq(TaskLocation("host1"), TaskLocation("host2"), TaskLocation("host3")), Seq(TaskLocation("host1"), TaskLocation("host2"), TaskLocation("host4")), Seq(TaskLocation("host2"), TaskLocation("host3"), TaskLocation("host4")), Seq.empty, Seq.empty ) val stageInfo1 = createStageInfo(1, 5, localityPreferences1) sc.listenerBus.postToAll(SparkListenerStageSubmitted(stageInfo1)) assert(localityAwareTasks(manager) === 3) assert(hostToLocalTaskCount(manager) === Map("host1" -> 2, "host2" -> 3, "host3" -> 2, "host4" -> 2)) val localityPreferences2 = Seq( Seq(TaskLocation("host2"), TaskLocation("host3"), TaskLocation("host5")), Seq(TaskLocation("host3"), TaskLocation("host4"), TaskLocation("host5")), Seq.empty ) val stageInfo2 = createStageInfo(2, 3, localityPreferences2) sc.listenerBus.postToAll(SparkListenerStageSubmitted(stageInfo2)) assert(localityAwareTasks(manager) === 5) assert(hostToLocalTaskCount(manager) === Map("host1" -> 2, "host2" -> 4, "host3" -> 4, "host4" -> 3, "host5" -> 2)) sc.listenerBus.postToAll(SparkListenerStageCompleted(stageInfo1)) assert(localityAwareTasks(manager) === 2) assert(hostToLocalTaskCount(manager) === Map("host2" -> 1, "host3" -> 2, "host4" -> 1, "host5" -> 2)) } test("SPARK-8366: maxNumExecutorsNeeded should properly handle failed tasks") { sc = createSparkContext() val manager = sc.executorAllocationManager.get assert(maxNumExecutorsNeeded(manager) === 0) sc.listenerBus.postToAll(SparkListenerStageSubmitted(createStageInfo(0, 1))) assert(maxNumExecutorsNeeded(manager) === 1) val taskInfo = createTaskInfo(1, 1, "executor-1") sc.listenerBus.postToAll(SparkListenerTaskStart(0, 0, taskInfo)) assert(maxNumExecutorsNeeded(manager) === 1) // If the task is failed, we expect it to be resubmitted later. val taskEndReason = ExceptionFailure(null, null, null, null, None) sc.listenerBus.postToAll(SparkListenerTaskEnd(0, 0, null, taskEndReason, taskInfo, null)) assert(maxNumExecutorsNeeded(manager) === 1) } test("reset the state of allocation manager") { sc = createSparkContext() val manager = sc.executorAllocationManager.get assert(numExecutorsTarget(manager) === 1) assert(numExecutorsToAdd(manager) === 1) // Allocation manager is reset when adding executor requests are sent without reporting back // executor added. sc.listenerBus.postToAll(SparkListenerStageSubmitted(createStageInfo(0, 10))) assert(addExecutors(manager) === 1) assert(numExecutorsTarget(manager) === 2) assert(addExecutors(manager) === 2) assert(numExecutorsTarget(manager) === 4) assert(addExecutors(manager) === 1) assert(numExecutorsTarget(manager) === 5) manager.reset() assert(numExecutorsTarget(manager) === 1) assert(numExecutorsToAdd(manager) === 1) assert(executorIds(manager) === Set.empty) // Allocation manager is reset when executors are added. sc.listenerBus.postToAll(SparkListenerStageSubmitted(createStageInfo(0, 10))) addExecutors(manager) addExecutors(manager) addExecutors(manager) assert(numExecutorsTarget(manager) === 5) onExecutorAdded(manager, "first") onExecutorAdded(manager, "second") onExecutorAdded(manager, "third") onExecutorAdded(manager, "fourth") onExecutorAdded(manager, "fifth") assert(executorIds(manager) === Set("first", "second", "third", "fourth", "fifth")) // Cluster manager lost will make all the live executors lost, so here simulate this behavior onExecutorRemoved(manager, "first") onExecutorRemoved(manager, "second") onExecutorRemoved(manager, "third") onExecutorRemoved(manager, "fourth") onExecutorRemoved(manager, "fifth") manager.reset() assert(numExecutorsTarget(manager) === 1) assert(numExecutorsToAdd(manager) === 1) assert(executorIds(manager) === Set.empty) assert(removeTimes(manager) === Map.empty) // Allocation manager is reset when executors are pending to remove addExecutors(manager) addExecutors(manager) addExecutors(manager) assert(numExecutorsTarget(manager) === 5) onExecutorAdded(manager, "first") onExecutorAdded(manager, "second") onExecutorAdded(manager, "third") onExecutorAdded(manager, "fourth") onExecutorAdded(manager, "fifth") assert(executorIds(manager) === Set("first", "second", "third", "fourth", "fifth")) removeExecutor(manager, "first") removeExecutors(manager, Seq("second", "third")) assert(executorsPendingToRemove(manager) === Set("first", "second", "third")) assert(executorIds(manager) === Set("first", "second", "third", "fourth", "fifth")) // Cluster manager lost will make all the live executors lost, so here simulate this behavior onExecutorRemoved(manager, "first") onExecutorRemoved(manager, "second") onExecutorRemoved(manager, "third") onExecutorRemoved(manager, "fourth") onExecutorRemoved(manager, "fifth") manager.reset() assert(numExecutorsTarget(manager) === 1) assert(numExecutorsToAdd(manager) === 1) assert(executorsPendingToRemove(manager) === Set.empty) assert(removeTimes(manager) === Map.empty) } private def createSparkContext( minExecutors: Int = 1, maxExecutors: Int = 5, initialExecutors: Int = 1): SparkContext = { val conf = new SparkConf() .setMaster("myDummyLocalExternalClusterManager") .setAppName("test-executor-allocation-manager") .set("spark.dynamicAllocation.enabled", "true") .set("spark.dynamicAllocation.minExecutors", minExecutors.toString) .set("spark.dynamicAllocation.maxExecutors", maxExecutors.toString) .set("spark.dynamicAllocation.initialExecutors", initialExecutors.toString) .set("spark.dynamicAllocation.schedulerBacklogTimeout", s"${schedulerBacklogTimeout.toString}s") .set("spark.dynamicAllocation.sustainedSchedulerBacklogTimeout", s"${sustainedSchedulerBacklogTimeout.toString}s") .set("spark.dynamicAllocation.executorIdleTimeout", s"${executorIdleTimeout.toString}s") .set("spark.dynamicAllocation.testing", "true") val sc = new SparkContext(conf) contexts += sc sc } } /** * Helper methods for testing ExecutorAllocationManager. * This includes methods to access private methods and fields in ExecutorAllocationManager. */ private object ExecutorAllocationManagerSuite extends PrivateMethodTester { private val schedulerBacklogTimeout = 1L private val sustainedSchedulerBacklogTimeout = 2L private val executorIdleTimeout = 3L private def createStageInfo( stageId: Int, numTasks: Int, taskLocalityPreferences: Seq[Seq[TaskLocation]] = Seq.empty ): StageInfo = { new StageInfo(stageId, 0, "name", numTasks, Seq.empty, Seq.empty, "no details", taskLocalityPreferences = taskLocalityPreferences) } private def createTaskInfo(taskId: Int, taskIndex: Int, executorId: String): TaskInfo = { new TaskInfo(taskId, taskIndex, 0, 0, executorId, "", TaskLocality.ANY, speculative = false) } /* ------------------------------------------------------- * | Helper methods for accessing private methods and fields | * ------------------------------------------------------- */ private val _numExecutorsToAdd = PrivateMethod[Int]('numExecutorsToAdd) private val _numExecutorsTarget = PrivateMethod[Int]('numExecutorsTarget) private val _maxNumExecutorsNeeded = PrivateMethod[Int]('maxNumExecutorsNeeded) private val _executorsPendingToRemove = PrivateMethod[collection.Set[String]]('executorsPendingToRemove) private val _executorIds = PrivateMethod[collection.Set[String]]('executorIds) private val _addTime = PrivateMethod[Long]('addTime) private val _removeTimes = PrivateMethod[collection.Map[String, Long]]('removeTimes) private val _schedule = PrivateMethod[Unit]('schedule) private val _addExecutors = PrivateMethod[Int]('addExecutors) private val _updateAndSyncNumExecutorsTarget = PrivateMethod[Int]('updateAndSyncNumExecutorsTarget) private val _removeExecutor = PrivateMethod[Boolean]('removeExecutor) private val _removeExecutors = PrivateMethod[Seq[String]]('removeExecutors) private val _onExecutorAdded = PrivateMethod[Unit]('onExecutorAdded) private val _onExecutorRemoved = PrivateMethod[Unit]('onExecutorRemoved) private val _onSchedulerBacklogged = PrivateMethod[Unit]('onSchedulerBacklogged) private val _onSchedulerQueueEmpty = PrivateMethod[Unit]('onSchedulerQueueEmpty) private val _onExecutorIdle = PrivateMethod[Unit]('onExecutorIdle) private val _onExecutorBusy = PrivateMethod[Unit]('onExecutorBusy) private val _localityAwareTasks = PrivateMethod[Int]('localityAwareTasks) private val _hostToLocalTaskCount = PrivateMethod[Map[String, Int]]('hostToLocalTaskCount) private def numExecutorsToAdd(manager: ExecutorAllocationManager): Int = { manager invokePrivate _numExecutorsToAdd() } private def numExecutorsTarget(manager: ExecutorAllocationManager): Int = { manager invokePrivate _numExecutorsTarget() } private def executorsPendingToRemove( manager: ExecutorAllocationManager): collection.Set[String] = { manager invokePrivate _executorsPendingToRemove() } private def executorIds(manager: ExecutorAllocationManager): collection.Set[String] = { manager invokePrivate _executorIds() } private def addTime(manager: ExecutorAllocationManager): Long = { manager invokePrivate _addTime() } private def removeTimes(manager: ExecutorAllocationManager): collection.Map[String, Long] = { manager invokePrivate _removeTimes() } private def schedule(manager: ExecutorAllocationManager): Unit = { manager invokePrivate _schedule() } private def maxNumExecutorsNeeded(manager: ExecutorAllocationManager): Int = { manager invokePrivate _maxNumExecutorsNeeded() } private def addExecutors(manager: ExecutorAllocationManager): Int = { val maxNumExecutorsNeeded = manager invokePrivate _maxNumExecutorsNeeded() manager invokePrivate _addExecutors(maxNumExecutorsNeeded) } private def adjustRequestedExecutors(manager: ExecutorAllocationManager): Int = { manager invokePrivate _updateAndSyncNumExecutorsTarget(0L) } private def removeExecutor(manager: ExecutorAllocationManager, id: String): Boolean = { manager invokePrivate _removeExecutor(id) } private def removeExecutors(manager: ExecutorAllocationManager, ids: Seq[String]): Seq[String] = { manager invokePrivate _removeExecutors(ids) } private def onExecutorAdded(manager: ExecutorAllocationManager, id: String): Unit = { manager invokePrivate _onExecutorAdded(id) } private def onExecutorRemoved(manager: ExecutorAllocationManager, id: String): Unit = { manager invokePrivate _onExecutorRemoved(id) } private def onSchedulerBacklogged(manager: ExecutorAllocationManager): Unit = { manager invokePrivate _onSchedulerBacklogged() } private def onSchedulerQueueEmpty(manager: ExecutorAllocationManager): Unit = { manager invokePrivate _onSchedulerQueueEmpty() } private def onExecutorIdle(manager: ExecutorAllocationManager, id: String): Unit = { manager invokePrivate _onExecutorIdle(id) } private def onExecutorBusy(manager: ExecutorAllocationManager, id: String): Unit = { manager invokePrivate _onExecutorBusy(id) } private def localityAwareTasks(manager: ExecutorAllocationManager): Int = { manager invokePrivate _localityAwareTasks() } private def hostToLocalTaskCount(manager: ExecutorAllocationManager): Map[String, Int] = { manager invokePrivate _hostToLocalTaskCount() } } /** * A cluster manager which wraps around the scheduler and backend for local mode. It is used for * testing the dynamic allocation policy. */ private class DummyLocalExternalClusterManager extends ExternalClusterManager { def canCreate(masterURL: String): Boolean = masterURL == "myDummyLocalExternalClusterManager" override def createTaskScheduler( sc: SparkContext, masterURL: String): TaskScheduler = new TaskSchedulerImpl(sc, 1, isLocal = true) override def createSchedulerBackend( sc: SparkContext, masterURL: String, scheduler: TaskScheduler): SchedulerBackend = { val sb = new LocalSchedulerBackend(sc.getConf, scheduler.asInstanceOf[TaskSchedulerImpl], 1) new DummyLocalSchedulerBackend(sc, sb) } override def initialize(scheduler: TaskScheduler, backend: SchedulerBackend): Unit = { val sc = scheduler.asInstanceOf[TaskSchedulerImpl] sc.initialize(backend) } } /** * A scheduler backend which wraps around local scheduler backend and exposes the executor * allocation client interface for testing dynamic allocation. */ private class DummyLocalSchedulerBackend (sc: SparkContext, sb: SchedulerBackend) extends SchedulerBackend with ExecutorAllocationClient { override private[spark] def getExecutorIds(): Seq[String] = sc.getExecutorIds() override private[spark] def requestTotalExecutors( numExecutors: Int, localityAwareTasks: Int, hostToLocalTaskCount: Map[String, Int]): Boolean = sc.requestTotalExecutors(numExecutors, localityAwareTasks, hostToLocalTaskCount) override def requestExecutors(numAdditionalExecutors: Int): Boolean = sc.requestExecutors(numAdditionalExecutors) override def killExecutors(executorIds: Seq[String]): Seq[String] = { val response = sc.killExecutors(executorIds) if (response) { executorIds } else { Seq.empty[String] } } override def start(): Unit = sb.start() override def stop(): Unit = sb.stop() override def reviveOffers(): Unit = sb.reviveOffers() override def defaultParallelism(): Int = sb.defaultParallelism() }
metamx/spark
core/src/test/scala/org/apache/spark/ExecutorAllocationManagerSuite.scala
Scala
apache-2.0
48,173
package io.gustavoamigo.quill.pgsql.encoding.jodatime import java.sql.{Types, PreparedStatement} import io.getquill.source.jdbc.JdbcSource import org.joda.time._ trait Encoders { this: JdbcSource[_, _] => import Formatters._ private def genericEncoder[T](valueToString: (T => String) = (r: T) => r.toString): Encoder[T] = new Encoder[T] { override def apply(index: Int, value: T, row: PreparedStatement) = { val sqlLiteral = s"'${valueToString(value)}'" row.setObject(index + 1, sqlLiteral, Types.OTHER) row } } implicit val jodaDateTimeEncoder: Encoder[DateTime] = genericEncoder(_.toString(jodaTzDateTimeFormatter)) implicit val jodaLocalDateEncoder: Encoder[LocalDate] = genericEncoder(_.toString(jodaDateFormatter)) implicit val jodaLocalTimeEncoder: Encoder[LocalTime] = genericEncoder(_.toString(jodaTimeFormatter)) }
gustavoamigo/quill-pgsql
src/main/scala/io/gustavoamigo/quill/pgsql/encoding/jodatime/Encoders.scala
Scala
apache-2.0
886
package sri.relay import sri.universal.router.UniversalRouterComponentJS import scala.scalajs.js.annotation.ScalaJSDefined @ScalaJSDefined abstract class UniversalRouterRelayComponent[P <: RelayComponentProps, S] extends UniversalRouterComponentJS[P, S] {}
chandu0101/sri-relay
relay/src/main/scala/sri/relay/UniversalRouterRelayComponent.scala
Scala
apache-2.0
260
package com.gigaspaces.csvwriter import scala.util.Random /** * A mixin for generating random strings. */ trait RandomStrings { private val rand = new Random(System.currentTimeMillis()) /** * @return an alphabetic character */ def randChar(): Character = { (rand.nextInt(26) + 65).toChar } /** * @param len length of returned string * @return a random string, length len, comprised of alphabetic characters */ def randString(len: Int): String = { val builder = new StringBuilder for (i <- 1 to len ) builder.append(randChar()) builder.toString() } }
jasonnerothin/gs-csvwriter
src/main/scala/com/gigaspaces/csvwriter/RandomStrings.scala
Scala
apache-2.0
609
package org.elasticmq.performance import com.amazonaws.services.sqs.AmazonSQSClient import com.amazonaws.auth.BasicAWSCredentials import com.amazonaws.services.sqs.model.{CreateQueueRequest, DeleteMessageRequest, ReceiveMessageRequest, SendMessageRequest} import org.elasticmq.rest.sqs.{SQSRestServer, SQSRestServerBuilder} import org.elasticmq.test._ import scala.collection.JavaConversions._ import akka.actor.{Props, ActorSystem, ActorRef} import org.elasticmq.actor.QueueManagerActor import org.elasticmq.util.NowProvider import org.elasticmq.actor.reply._ import org.elasticmq.msg._ import org.elasticmq._ import scala.concurrent.Await import scala.concurrent.duration._ import org.joda.time.DateTime import org.elasticmq.msg.ReceiveMessages import org.elasticmq.QueueData import org.elasticmq.NewMessageData import org.elasticmq.msg.SendMessage import org.elasticmq.msg.CreateQueue import akka.util.Timeout object LocalPerformanceTest extends App { testAll() def testAll() { val iterations = 10 val msgsInIteration = 100000 testWithMq(new ActorBasedMQ, 3, 100000, "in-memory warmup", 1) //testWithMq(new ActorBasedMQ, iterations, msgsInIteration, "in-memory", 1) //testWithMq(new ActorBasedMQ, iterations, msgsInIteration, "in-memory", 2) //testWithMq(new ActorBasedMQ, iterations, msgsInIteration, "in-memory", 3) testWithMq(new RestSQSMQ, iterations, msgsInIteration, "rest-sqs + in-memory", 1) } def testWithMq(mq: MQ, iterations: Int, msgsInIteration: Int, name: String, threadCount: Int) { println("Running test for [%s], iterations: %d, msgs in iteration: %d, thread count: %d." .format(name, iterations, msgsInIteration, threadCount)) mq.start() val took = timed { val threads = for (i <- 1 to threadCount) yield { val t = new Thread(new Runnable() { def run() { runTest(mq, iterations, msgsInIteration, name + " " + i) } }) t.start() t } threads.foreach(_.join()) } val count = msgsInIteration * iterations * threadCount println("Overall %s throughput: %f".format(name, (count.toDouble / (took.toDouble / 1000.0)))) println() mq.stop() } private def runTest(mq: MQ, iterations: Int, msgsInIteration: Int, name: String) { var count = 0 val start = System.currentTimeMillis() for (i <- 1 to iterations) { val loopStart = System.currentTimeMillis() for (j <- 1 to msgsInIteration) { mq.sendMessage("Message" + (i*j)) } for (j <- 1 to msgsInIteration) { mq.receiveMessage() } count += msgsInIteration val loopEnd = System.currentTimeMillis() println("%-20s throughput: %f, %d".format(name, (count.toDouble / ((loopEnd-start).toDouble / 1000.0)), (loopEnd - loopStart))) } } class ActorBasedMQ extends MQWithQueueManagerActor class RestSQSMQ extends MQ { private var currentSQSClient: AmazonSQSClient = _ private var currentQueueUrl: String = _ private var currentRestServer: SQSRestServer = _ override def start() = { val queueManagerActor = super.start() currentRestServer = SQSRestServerBuilder .withActorSystem(actorSystem) .withQueueManagerActor(queueManagerActor) .start() currentSQSClient = new AmazonSQSClient(new BasicAWSCredentials("x", "x")) currentSQSClient.setEndpoint("http://localhost:9324") currentQueueUrl = currentSQSClient.createQueue( new CreateQueueRequest("testQueue").withAttributes(Map("VisibilityTimeout" -> "1"))) .getQueueUrl queueManagerActor } override def stop() { currentRestServer.stopAndGetFuture currentSQSClient.shutdown() super.stop() } def sendMessage(m: String) { currentSQSClient.sendMessage(new SendMessageRequest(currentQueueUrl, m)) } def receiveMessage() = { val msgs = currentSQSClient.receiveMessage(new ReceiveMessageRequest(currentQueueUrl)).getMessages if (msgs.size != 1) { throw new Exception(msgs.toString) } currentSQSClient.deleteMessage(new DeleteMessageRequest(currentQueueUrl, msgs.get(0).getReceiptHandle)) msgs.get(0).getBody } } trait MQ { var actorSystem: ActorSystem = _ def start(): ActorRef = { actorSystem = ActorSystem("performance-tests") val queueManagerActor = actorSystem.actorOf(Props(new QueueManagerActor(new NowProvider()))) queueManagerActor } def stop() { actorSystem.shutdown() actorSystem.awaitTermination() } def sendMessage(m: String) def receiveMessage(): String } trait MQWithQueueManagerActor extends MQ { private var currentQueue: ActorRef = _ implicit val timeout = Timeout(10000L) override def start() = { val queueManagerActor = super.start() currentQueue = Await.result(queueManagerActor ? CreateQueue(QueueData("testQueue", MillisVisibilityTimeout(1000), org.joda.time.Duration.ZERO, org.joda.time.Duration.ZERO, new DateTime(), new DateTime())), 10.seconds).right.get queueManagerActor } def sendMessage(m: String) { Await.result(currentQueue ? SendMessage(NewMessageData(None, m, Map.empty, ImmediateNextDelivery)), 10.seconds) } def receiveMessage() = { val messages = Await.result(currentQueue ? ReceiveMessages(DefaultVisibilityTimeout, 1, None), 10.seconds) val message = messages.head Await.result(currentQueue ? DeleteMessage(message.deliveryReceipt.get), 10.seconds) message.content } } }
everyonce/elasticmq
performance-tests/src/test/scala/org/elasticmq/performance/LocalPerformanceTest.scala
Scala
apache-2.0
5,598
/* * Copyright (c) 2014-2021 by The Monix Project Developers. * See the project homepage at: https://monix.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* package monix.benchmarks import java.util.concurrent.TimeUnit import monix.eval.Task import org.openjdk.jmh.annotations._ import scala.concurrent.Await import scala.concurrent.duration.Duration /** To do comparative benchmarks between versions: * * benchmarks/run-benchmark TaskAttemptBenchmark * * This will generate results in `benchmarks/results`. * * Or to run the benchmark from within SBT: * * jmh:run -i 10 -wi 10 -f 2 -t 1 monix.benchmarks.TaskAttemptBenchmark * * Which means "10 iterations", "10 warm-up iterations", "2 forks", "1 thread". * Please note that benchmarks should be usually executed at least in * 10 iterations (as a rule of thumb), but more is better. */ @State(Scope.Thread) @BenchmarkMode(Array(Mode.Throughput)) @OutputTimeUnit(TimeUnit.SECONDS) class TaskAttemptBenchmark { @Param(Array("10000")) var size: Int = _ @Benchmark def happyPath(): Int = { def loop(i: Int): Task[Int] = if (i < size) Task.pure(i + 1).attempt.flatMap(_.fold(Task.raiseError, loop)) else Task.pure(i) Await.result(loop(0).runAsync, Duration.Inf) } @Benchmark def errorRaised(): Int = { val dummy = new RuntimeException("dummy") val id = Task.pure[Int] _ def loop(i: Int): Task[Int] = if (i < size) Task.raiseError[Int](dummy) .flatMap(x => Task.pure(x + 1)) .attempt .flatMap(_.fold(_ => loop(i + 1), id)) else Task.pure(i) Await.result(loop(0).runAsync, Duration.Inf) } } */
monix/monix
benchmarks/shared/src/main/scala/monix/benchmarks/TaskAttemptBenchmark.scala
Scala
apache-2.0
2,209
/*********************************************************************** * Copyright (c) 2013-2016 Commonwealth Computer Research, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at * http://www.opensource.org/licenses/apache2.0.php. *************************************************************************/ package org.locationtech.geomesa.process import org.geotools.process.factory.AnnotatedBeanProcessFactory import org.geotools.text.Text import org.locationtech.geomesa.accumulo.process._ import org.locationtech.geomesa.accumulo.process.knn.KNearestNeighborSearchProcess import org.locationtech.geomesa.accumulo.process.proximity.ProximitySearchProcess import org.locationtech.geomesa.accumulo.process.query.QueryProcess import org.locationtech.geomesa.accumulo.process.stats.StatsIteratorProcess import org.locationtech.geomesa.accumulo.process.tube.TubeSelectProcess import org.locationtech.geomesa.accumulo.process.unique.UniqueProcess class ProcessFactory extends AnnotatedBeanProcessFactory( Text.text("GeoMesa Process Factory"), "geomesa", classOf[DensityProcess], classOf[Point2PointProcess], classOf[StatsIteratorProcess], classOf[TubeSelectProcess], classOf[ProximitySearchProcess], classOf[QueryProcess], classOf[KNearestNeighborSearchProcess], classOf[UniqueProcess], classOf[HashAttributeProcess], classOf[HashAttributeColorProcess], classOf[SamplingProcess], classOf[JoinProcess], classOf[RouteSearchProcess], classOf[BinConversionProcess] )
MutahirKazmi/geomesa
geomesa-process/src/main/scala/org/locationtech/geomesa/process/ProcessFactory.scala
Scala
apache-2.0
1,685
package com.fustigatedcat.heystk.agent.common.normalization import akka.actor.{ActorRef, Actor} import com.fustigatedcat.heystk.common.normalization.Log import com.typesafe.config.Config import org.slf4j.LoggerFactory class NormalizerActor(config : Config, system : NormalizerSystem, engine : ActorRef) extends Actor { val logger = LoggerFactory.getLogger(this.getClass) override def receive = { case log : Log => { logger.debug("Handling message [{}]", log) val norm = system.process(log) logger.debug("Created normalization [{}]", norm) engine ! norm } } }
fustigatedcat/heystk
agent-common/src/main/scala/com/fustigatedcat/heystk/agent/common/normalization/NormalizerActor.scala
Scala
gpl-3.0
602
/* * Scala.js (https://www.scala-js.org/) * * Copyright EPFL. * * Licensed under Apache License 2.0 * (https://www.apache.org/licenses/LICENSE-2.0). * * See the NOTICE file distributed with this work for * additional information regarding copyright ownership. */ package java.lang import scala.annotation.{switch, tailrec} import java.util.Comparator import scala.scalajs.js import scala.scalajs.js.annotation._ import scala.scalajs.runtime.linkingInfo import scala.scalajs.LinkingInfo.ESVersion import java.lang.constant.{Constable, ConstantDesc} import java.nio.ByteBuffer import java.nio.charset.Charset import java.util.Locale import java.util.regex._ import Utils.Implicits.enableJSStringOps /* This is the implementation of java.lang.String, which is a hijacked class. * Its instances are primitive strings. Constructors are not emitted. * * It should be declared as `class String`, but scalac really does not like * being forced to compile java.lang.String, so we call it `_String` instead. * The Scala.js compiler back-end applies some magic to rename it into `String` * when emitting the IR. */ final class _String private () // scalastyle:ignore extends AnyRef with java.io.Serializable with Comparable[String] with CharSequence with Constable with ConstantDesc { import _String._ @inline private def thisString: String = this.asInstanceOf[String] @inline def charAt(index: Int): Char = { this.asInstanceOf[js.Dynamic] .charCodeAt(index.asInstanceOf[js.Dynamic]) .asInstanceOf[Int] .toChar } def codePointAt(index: Int): Int = { if (linkingInfo.esVersion >= ESVersion.ES2015) { this.asInstanceOf[js.Dynamic] .codePointAt(index.asInstanceOf[js.Dynamic]) .asInstanceOf[Int] } else { val high = charAt(index) if (index+1 < length()) { val low = charAt(index+1) if (Character.isSurrogatePair(high, low)) Character.toCodePoint(high, low) else high.toInt } else { high.toInt } } } def codePointBefore(index: Int): Int = { val low = charAt(index - 1) if (index > 1) { val high = charAt(index - 2) if (Character.isSurrogatePair(high, low)) Character.toCodePoint(high, low) else low.toInt } else { low.toInt } } def codePointCount(beginIndex: Int, endIndex: Int): Int = Character.codePointCount(this, beginIndex, endIndex) def offsetByCodePoints(index: Int, codePointOffset: Int): Int = { val len = length() if (index < 0 || index > len) throw new StringIndexOutOfBoundsException(index) if (codePointOffset >= 0) { var i = 0 var result = index while (i != codePointOffset) { if (result >= len) throw new StringIndexOutOfBoundsException if ((result < len - 1) && Character.isHighSurrogate(charAt(result)) && Character.isLowSurrogate(charAt(result + 1))) { result += 2 } else { result += 1 } i += 1 } result } else { var i = 0 var result = index while (i != codePointOffset) { if (result <= 0) throw new StringIndexOutOfBoundsException if ((result > 1) && Character.isLowSurrogate(charAt(result - 1)) && Character.isHighSurrogate(charAt(result - 2))) { result -= 2 } else { result -= 1 } i -= 1 } result } } override def hashCode(): Int = { var res = 0 var mul = 1 // holds pow(31, length-i-1) var i = length() - 1 while (i >= 0) { res += charAt(i) * mul mul *= 31 i -= 1 } res } @inline override def equals(that: Any): scala.Boolean = this eq that.asInstanceOf[AnyRef] def compareTo(anotherString: String): Int = { // scalastyle:off return val thisLength = this.length() val strLength = anotherString.length() val minLength = Math.min(thisLength, strLength) var i = 0 while (i != minLength) { val cmp = this.charAt(i) - anotherString.charAt(i) if (cmp != 0) return cmp i += 1 } thisLength - strLength // scalastyle:on return } def compareToIgnoreCase(str: String): Int = { // scalastyle:off return val thisLength = this.length() val strLength = str.length() val minLength = Math.min(thisLength, strLength) var i = 0 while (i != minLength) { val cmp = caseFold(this.charAt(i)) - caseFold(str.charAt(i)) if (cmp != 0) return cmp i += 1 } thisLength - strLength // scalastyle:on return } @inline def equalsIgnoreCase(anotherString: String): scala.Boolean = { // scalastyle:off return val len = length() if (anotherString == null || anotherString.length() != len) { false } else { var i = 0 while (i != len) { if (caseFold(this.charAt(i)) != caseFold(anotherString.charAt(i))) return false i += 1 } true } // scalastyle:on return } /** Performs case folding of a single character for use by `equalsIgnoreCase` * and `compareToIgnoreCase`. * * This implementation respects the specification of those two methods, * although that behavior does not generally conform to Unicode Case * Folding. */ @inline private def caseFold(c: Char): Char = Character.toLowerCase(Character.toUpperCase(c)) @inline def concat(s: String): String = thisString + s @inline def contains(s: CharSequence): scala.Boolean = indexOf(s.toString) != -1 def endsWith(suffix: String): scala.Boolean = thisString.jsSubstring(this.length() - suffix.length()) == suffix def getBytes(): Array[scala.Byte] = getBytes(Charset.defaultCharset) def getBytes(charsetName: String): Array[scala.Byte] = getBytes(Charset.forName(charsetName)) def getBytes(charset: Charset): Array[scala.Byte] = { val buf = charset.encode(thisString) val res = new Array[scala.Byte](buf.remaining) buf.get(res) res } def getChars(srcBegin: Int, srcEnd: Int, dst: Array[Char], dstBegin: Int): Unit = { if (srcEnd > length() || srcBegin < 0 || srcEnd < 0 || srcBegin > srcEnd) throw new StringIndexOutOfBoundsException("Index out of Bound") val offset = dstBegin - srcBegin var i = srcBegin while (i < srcEnd) { dst(i + offset) = charAt(i) i += 1 } } def indexOf(ch: Int): Int = indexOf(Character.toString(ch)) def indexOf(ch: Int, fromIndex: Int): Int = indexOf(Character.toString(ch), fromIndex) @inline def indexOf(str: String): Int = thisString.jsIndexOf(str) @inline def indexOf(str: String, fromIndex: Int): Int = thisString.jsIndexOf(str, fromIndex) /* Just returning this string is a valid implementation for `intern` in * JavaScript, since strings are primitive values. Therefore, value equality * and reference equality is the same. */ @inline def intern(): String = thisString @inline def isEmpty(): scala.Boolean = (this: AnyRef) eq ("": AnyRef) def lastIndexOf(ch: Int): Int = lastIndexOf(Character.toString(ch)) def lastIndexOf(ch: Int, fromIndex: Int): Int = if (fromIndex < 0) -1 else lastIndexOf(Character.toString(ch), fromIndex) @inline def lastIndexOf(str: String): Int = thisString.jsLastIndexOf(str) @inline def lastIndexOf(str: String, fromIndex: Int): Int = if (fromIndex < 0) -1 else thisString.jsLastIndexOf(str, fromIndex) @inline def length(): Int = this.asInstanceOf[js.Dynamic].length.asInstanceOf[Int] @inline def matches(regex: String): scala.Boolean = Pattern.matches(regex, thisString) /* Both regionMatches ported from * https://github.com/gwtproject/gwt/blob/master/user/super/com/google/gwt/emul/java/lang/String.java */ def regionMatches(ignoreCase: scala.Boolean, toffset: Int, other: String, ooffset: Int, len: Int): scala.Boolean = { if (other == null) { throw new NullPointerException() } else if (toffset < 0 || ooffset < 0 || toffset + len > this.length() || ooffset + len > other.length()) { false } else if (len <= 0) { true } else { val left = this.substring(toffset, toffset + len) val right = other.substring(ooffset, ooffset + len) if (ignoreCase) left.equalsIgnoreCase(right) else left == right } } @inline def regionMatches(toffset: Int, other: String, ooffset: Int, len: Int): scala.Boolean = { regionMatches(false, toffset, other, ooffset, len) } def repeat(count: Int): String = { if (count < 0) { throw new IllegalArgumentException } else if (thisString == "" || count == 0) { "" } else if (thisString.length > (Int.MaxValue / count)) { throw new OutOfMemoryError } else { var str = thisString val resultLength = thisString.length * count var remainingIters = 31 - Integer.numberOfLeadingZeros(count) while (remainingIters > 0) { str += str remainingIters -= 1 } str += str.jsSubstring(0, resultLength - str.length) str } } @inline def replace(oldChar: Char, newChar: Char): String = replace(oldChar.toString, newChar.toString) @inline def replace(target: CharSequence, replacement: CharSequence): String = thisString.jsSplit(target.toString).join(replacement.toString) def replaceAll(regex: String, replacement: String): String = Pattern.compile(regex).matcher(thisString).replaceAll(replacement) def replaceFirst(regex: String, replacement: String): String = Pattern.compile(regex).matcher(thisString).replaceFirst(replacement) @inline def split(regex: String): Array[String] = split(regex, 0) def split(regex: String, limit: Int): Array[String] = Pattern.compile(regex).split(thisString, limit) @inline def startsWith(prefix: String): scala.Boolean = startsWith(prefix, 0) @inline def startsWith(prefix: String, toffset: Int): scala.Boolean = { (toffset <= length() && toffset >= 0 && thisString.jsSubstring(toffset, toffset + prefix.length()) == prefix) } @inline def subSequence(beginIndex: Int, endIndex: Int): CharSequence = substring(beginIndex, endIndex) @inline def substring(beginIndex: Int): String = thisString.jsSubstring(beginIndex) @inline def substring(beginIndex: Int, endIndex: Int): String = { this.asInstanceOf[js.Dynamic] .substring(beginIndex.asInstanceOf[js.Dynamic], endIndex.asInstanceOf[js.Dynamic]) .asInstanceOf[String] } def toCharArray(): Array[Char] = { val len = length() val result = new Array[Char](len) var i = 0 while (i < len) { result(i) = charAt(i) i += 1 } result } /* toLowerCase() and toUpperCase() * * The overloads without an explicit locale use the default locale, which is * the root locale by specification. They are implemented by direct * delegation to ECMAScript's `toLowerCase()` and `toUpperCase()`, which are * specified as locale-insensitive, therefore equivalent to the root locale. * * It turns out virtually every locale behaves in the same way as the root * locale for default case algorithms. Only Lithuanian (lt), Turkish (tr) * and Azeri (az) have different behaviors. * * The overloads with a `Locale` specifically test for those three languages * and delegate to dedicated methods to handle them. Those methods start by * handling their respective special cases, then delegate to the locale- * insensitive version. The special cases are specified in the Unicode * reference file at * * https://unicode.org/Public/13.0.0/ucd/SpecialCasing.txt * * That file first contains a bunch of locale-insensitive special cases, * which we do not need to handle. Only the last two sections about locale- * sensitive special-cases are important for us. * * Some of the rules are further context-sensitive, using predicates that are * defined in Section 3.13 "Default Case Algorithms" of the Unicode Standard, * available at * * http://www.unicode.org/versions/Unicode13.0.0/ * * We based the implementations on Unicode 13.0.0. It is worth noting that * there has been no non-comment changes in the SpecialCasing.txt file * between Unicode 4.1.0 and 13.0.0 (perhaps even earlier; the version 4.1.0 * is the earliest that is easily accessible). */ def toLowerCase(locale: Locale): String = { locale.getLanguage() match { case "lt" => toLowerCaseLithuanian() case "tr" | "az" => toLowerCaseTurkishAndAzeri() case _ => toLowerCase() } } private def toLowerCaseLithuanian(): String = { /* Relevant excerpt from SpecialCasing.txt * * # Lithuanian * * # Lithuanian retains the dot in a lowercase i when followed by accents. * * [...] * * # Introduce an explicit dot above when lowercasing capital I's and J's * # whenever there are more accents above. * # (of the accents used in Lithuanian: grave, acute, tilde above, and ogonek) * * 0049; 0069 0307; 0049; 0049; lt More_Above; # LATIN CAPITAL LETTER I * 004A; 006A 0307; 004A; 004A; lt More_Above; # LATIN CAPITAL LETTER J * 012E; 012F 0307; 012E; 012E; lt More_Above; # LATIN CAPITAL LETTER I WITH OGONEK * 00CC; 0069 0307 0300; 00CC; 00CC; lt; # LATIN CAPITAL LETTER I WITH GRAVE * 00CD; 0069 0307 0301; 00CD; 00CD; lt; # LATIN CAPITAL LETTER I WITH ACUTE * 0128; 0069 0307 0303; 0128; 0128; lt; # LATIN CAPITAL LETTER I WITH TILDE */ /* Tests whether we are in an `More_Above` context. * From Table 3.17 in the Unicode standard: * - Description: C is followed by a character of combining class * 230 (Above) with no intervening character of combining class 0 or * 230 (Above). * - Regex, after C: [^\\p{ccc=230}\\p{ccc=0}]*[\\p{ccc=230}] */ def moreAbove(i: Int): scala.Boolean = { import Character._ val len = length() @tailrec def loop(j: Int): scala.Boolean = { if (j == len) { false } else { val cp = this.codePointAt(j) combiningClassNoneOrAboveOrOther(cp) match { case CombiningClassIsNone => false case CombiningClassIsAbove => true case _ => loop(j + charCount(cp)) } } } loop(i + 1) } val preprocessed = replaceCharsAtIndex { i => (this.charAt(i): @switch) match { case '\\u0049' if moreAbove(i) => "\\u0069\\u0307" case '\\u004A' if moreAbove(i) => "\\u006A\\u0307" case '\\u012E' if moreAbove(i) => "\\u012F\\u0307" case '\\u00CC' => "\\u0069\\u0307\\u0300" case '\\u00CD' => "\\u0069\\u0307\\u0301" case '\\u0128' => "\\u0069\\u0307\\u0303" case _ => null } } preprocessed.toLowerCase() } private def toLowerCaseTurkishAndAzeri(): String = { /* Relevant excerpt from SpecialCasing.txt * * # Turkish and Azeri * * # I and i-dotless; I-dot and i are case pairs in Turkish and Azeri * # The following rules handle those cases. * * 0130; 0069; 0130; 0130; tr; # LATIN CAPITAL LETTER I WITH DOT ABOVE * 0130; 0069; 0130; 0130; az; # LATIN CAPITAL LETTER I WITH DOT ABOVE * * # When lowercasing, remove dot_above in the sequence I + dot_above, which will turn into i. * # This matches the behavior of the canonically equivalent I-dot_above * * 0307; ; 0307; 0307; tr After_I; # COMBINING DOT ABOVE * 0307; ; 0307; 0307; az After_I; # COMBINING DOT ABOVE * * # When lowercasing, unless an I is before a dot_above, it turns into a dotless i. * * 0049; 0131; 0049; 0049; tr Not_Before_Dot; # LATIN CAPITAL LETTER I * 0049; 0131; 0049; 0049; az Not_Before_Dot; # LATIN CAPITAL LETTER I */ /* Tests whether we are in an `After_I` context. * From Table 3.17 in the Unicode standard: * - Description: There is an uppercase I before C, and there is no * intervening combining character class 230 (Above) or 0. * - Regex, before C: [I]([^\\p{ccc=230}\\p{ccc=0}])* */ def afterI(i: Int): scala.Boolean = { val j = skipCharsWithCombiningClassOtherThanNoneOrAboveBackwards(i) j > 0 && charAt(j - 1) == 'I' } /* Tests whether we are in an `Before_Dot` context. * From Table 3.17 in the Unicode standard: * - Description: C is followed by combining dot above (U+0307). Any * sequence of characters with a combining class that is neither 0 nor * 230 may intervene between the current character and the combining dot * above. * - Regex, after C: ([^\\p{ccc=230}\\p{ccc=0}])*[\\u0307] */ def beforeDot(i: Int): scala.Boolean = { val j = skipCharsWithCombiningClassOtherThanNoneOrAboveForwards(i + 1) j != length() && charAt(j) == '\\u0307' } val preprocessed = replaceCharsAtIndex { i => (this.charAt(i): @switch) match { case '\\u0130' => "\\u0069" case '\\u0307' if afterI(i) => "" case '\\u0049' if !beforeDot(i) => "\\u0131" case _ => null } } preprocessed.toLowerCase() } @inline def toLowerCase(): String = this.asInstanceOf[js.Dynamic].toLowerCase().asInstanceOf[String] def toUpperCase(locale: Locale): String = { locale.getLanguage() match { case "lt" => toUpperCaseLithuanian() case "tr" | "az" => toUpperCaseTurkishAndAzeri() case _ => toUpperCase() } } private def toUpperCaseLithuanian(): String = { /* Relevant excerpt from SpecialCasing.txt * * # Lithuanian * * # Lithuanian retains the dot in a lowercase i when followed by accents. * * # Remove DOT ABOVE after "i" with upper or titlecase * * 0307; 0307; ; ; lt After_Soft_Dotted; # COMBINING DOT ABOVE */ /* Tests whether we are in an `After_Soft_Dotted` context. * From Table 3.17 in the Unicode standard: * - Description: There is a Soft_Dotted character before C, with no * intervening character of combining class 0 or 230 (Above). * - Regex, before C: [\\p{Soft_Dotted}]([^\\p{ccc=230} \\p{ccc=0}])* * * According to https://unicode.org/Public/13.0.0/ucd/PropList.txt, there * are 44 code points with the Soft_Dotted property. However, * experimentation on the JVM reveals that the JDK (8 and 14 were tested) * only recognizes 8 code points when deciding whether to remove the 0x0307 * code points. The following script reproduces the list: for (cp <- 0 to Character.MAX_CODE_POINT) { val input = new String(Array(cp, 0x0307, 0x0301), 0, 3) val output = input.toUpperCase(new java.util.Locale("lt")) if (!output.contains('\\u0307')) println(cp.toHexString) } */ def afterSoftDotted(i: Int): scala.Boolean = { val j = skipCharsWithCombiningClassOtherThanNoneOrAboveBackwards(i) j > 0 && (codePointBefore(j) match { case 0x0069 | 0x006a | 0x012f | 0x0268 | 0x0456 | 0x0458 | 0x1e2d | 0x1ecb => true case _ => false }) } val preprocessed = replaceCharsAtIndex { i => (this.charAt(i): @switch) match { case '\\u0307' if afterSoftDotted(i) => "" case _ => null } } preprocessed.toUpperCase() } private def toUpperCaseTurkishAndAzeri(): String = { /* Relevant excerpt from SpecialCasing.txt * * # Turkish and Azeri * * # When uppercasing, i turns into a dotted capital I * * 0069; 0069; 0130; 0130; tr; # LATIN SMALL LETTER I * 0069; 0069; 0130; 0130; az; # LATIN SMALL LETTER I */ val preprocessed = replaceCharsAtIndex { i => (this.charAt(i): @switch) match { case '\\u0069' => "\\u0130" case _ => null } } preprocessed.toUpperCase() } @inline def toUpperCase(): String = this.asInstanceOf[js.Dynamic].toUpperCase().asInstanceOf[String] /** Replaces special characters in this string (possibly in special contexts) * by dedicated strings. * * This method encodes the general pattern of * * - `toLowerCaseLithuanian()` * - `toLowerCaseTurkishAndAzeri()` * - `toUpperCaseLithuanian()` * - `toUpperCaseTurkishAndAzeri()` * * @param replacementAtIndex * A function from index to `String | Null`, which should return a special * replacement string for the character at the given index, or `null` if * the character at the given index is not special. */ @inline private def replaceCharsAtIndex( replacementAtIndex: js.Function1[Int, String]): String = { var prep = "" val len = this.length() var i = 0 var startOfSegment = 0 while (i != len) { val replacement = replacementAtIndex(i) if (replacement != null) { prep += this.substring(startOfSegment, i) prep += replacement startOfSegment = i + 1 } i += 1 } if (startOfSegment == 0) thisString // opt: no character needed replacing, directly return the original string else prep + this.substring(startOfSegment, i) } private def skipCharsWithCombiningClassOtherThanNoneOrAboveForwards(i: Int): Int = { // scalastyle:off return import Character._ val len = length() var j = i while (j != len) { val cp = codePointAt(j) if (combiningClassNoneOrAboveOrOther(cp) != CombiningClassIsOther) return j j += charCount(cp) } j // scalastyle:on return } private def skipCharsWithCombiningClassOtherThanNoneOrAboveBackwards(i: Int): Int = { // scalastyle:off return import Character._ var j = i while (j > 0) { val cp = codePointBefore(j) if (combiningClassNoneOrAboveOrOther(cp) != CombiningClassIsOther) return j j -= charCount(cp) } 0 // scalastyle:on return } def trim(): String = { val len = length() var start = 0 while (start != len && charAt(start) <= ' ') start += 1 if (start == len) { "" } else { /* If we get here, 0 <= start < len, so the original string is not empty. * We also know that charAt(start) > ' '. */ var end = len while (charAt(end - 1) <= ' ') // no need for a bounds check here since charAt(start) > ' ' end -= 1 if (start == 0 && end == len) thisString else substring(start, end) } } @inline override def toString(): String = thisString } object _String { // scalastyle:ignore final lazy val CASE_INSENSITIVE_ORDER: Comparator[String] = { new Comparator[String] with Serializable { def compare(o1: String, o2: String): Int = o1.compareToIgnoreCase(o2) } } // Constructors def `new`(): String = "" def `new`(value: Array[Char]): String = `new`(value, 0, value.length) def `new`(value: Array[Char], offset: Int, count: Int): String = { val end = offset + count if (offset < 0 || end < offset || end > value.length) throw new StringIndexOutOfBoundsException var result = "" var i = offset while (i != end) { result += value(i).toString i += 1 } result } def `new`(bytes: Array[scala.Byte]): String = `new`(bytes, Charset.defaultCharset) def `new`(bytes: Array[scala.Byte], charsetName: String): String = `new`(bytes, Charset.forName(charsetName)) def `new`(bytes: Array[scala.Byte], charset: Charset): String = charset.decode(ByteBuffer.wrap(bytes)).toString() def `new`(bytes: Array[scala.Byte], offset: Int, length: Int): String = `new`(bytes, offset, length, Charset.defaultCharset) def `new`(bytes: Array[scala.Byte], offset: Int, length: Int, charsetName: String): String = `new`(bytes, offset, length, Charset.forName(charsetName)) def `new`(bytes: Array[scala.Byte], offset: Int, length: Int, charset: Charset): String = charset.decode(ByteBuffer.wrap(bytes, offset, length)).toString() def `new`(codePoints: Array[Int], offset: Int, count: Int): String = { val end = offset + count if (offset < 0 || end < offset || end > codePoints.length) throw new StringIndexOutOfBoundsException var result = "" var i = offset while (i != end) { result += Character.toString(codePoints(i)) i += 1 } result } def `new`(original: String): String = { if (original == null) throw new NullPointerException original } def `new`(buffer: java.lang.StringBuffer): String = buffer.toString def `new`(builder: java.lang.StringBuilder): String = builder.toString // Static methods (aka methods on the companion object) def valueOf(b: scala.Boolean): String = b.toString() def valueOf(c: scala.Char): String = c.toString() def valueOf(i: scala.Int): String = i.toString() def valueOf(l: scala.Long): String = l.toString() def valueOf(f: scala.Float): String = f.toString() def valueOf(d: scala.Double): String = d.toString() @inline def valueOf(obj: Object): String = "" + obj // if (obj eq null), returns "null" def valueOf(data: Array[Char]): String = valueOf(data, 0, data.length) def valueOf(data: Array[Char], offset: Int, count: Int): String = `new`(data, offset, count) def format(format: String, args: Array[AnyRef]): String = new java.util.Formatter().format(format, args: _*).toString() def format(l: Locale, format: String, args: Array[AnyRef]): String = new java.util.Formatter(l).format(format, args: _*).toString() }
gzm0/scala-js
javalanglib/src/main/scala/java/lang/_String.scala
Scala
apache-2.0
26,063
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql import java.io.Closeable import java.util.concurrent.atomic.AtomicReference import scala.collection.JavaConverters._ import scala.reflect.runtime.universe.TypeTag import scala.util.control.NonFatal import org.apache.spark.{SPARK_VERSION, SparkConf, SparkContext, TaskContext} import org.apache.spark.annotation.{DeveloperApi, Evolving, Experimental, Stable, Unstable} import org.apache.spark.api.java.JavaRDD import org.apache.spark.internal.Logging import org.apache.spark.rdd.RDD import org.apache.spark.scheduler.{SparkListener, SparkListenerApplicationEnd} import org.apache.spark.sql.catalog.Catalog import org.apache.spark.sql.catalyst._ import org.apache.spark.sql.catalyst.analysis.UnresolvedRelation import org.apache.spark.sql.catalyst.encoders._ import org.apache.spark.sql.catalyst.expressions.AttributeReference import org.apache.spark.sql.catalyst.plans.logical.{LocalRelation, Range} import org.apache.spark.sql.execution._ import org.apache.spark.sql.execution.datasources.LogicalRelation import org.apache.spark.sql.internal._ import org.apache.spark.sql.internal.StaticSQLConf.CATALOG_IMPLEMENTATION import org.apache.spark.sql.sources.BaseRelation import org.apache.spark.sql.streaming._ import org.apache.spark.sql.types.{DataType, StructType} import org.apache.spark.sql.util.ExecutionListenerManager import org.apache.spark.util.{CallSite, Utils} /** * The entry point to programming Spark with the Dataset and DataFrame API. * * In environments that this has been created upfront (e.g. REPL, notebooks), use the builder * to get an existing session: * * {{{ * SparkSession.builder().getOrCreate() * }}} * * The builder can also be used to create a new session: * * {{{ * SparkSession.builder * .master("local") * .appName("Word Count") * .config("spark.some.config.option", "some-value") * .getOrCreate() * }}} * * @param sparkContext The Spark context associated with this Spark session. * @param existingSharedState If supplied, use the existing shared state * instead of creating a new one. * @param parentSessionState If supplied, inherit all session state (i.e. temporary * views, SQL config, UDFs etc) from parent. */ @Stable class SparkSession private( @transient val sparkContext: SparkContext, @transient private val existingSharedState: Option[SharedState], @transient private val parentSessionState: Option[SessionState], @transient private[sql] val extensions: SparkSessionExtensions) extends Serializable with Closeable with Logging { self => // The call site where this SparkSession was constructed. private val creationSite: CallSite = Utils.getCallSite() /** * Constructor used in Pyspark. Contains explicit application of Spark Session Extensions * which otherwise only occurs during getOrCreate. We cannot add this to the default constructor * since that would cause every new session to reinvoke Spark Session Extensions on the currently * running extensions. */ private[sql] def this(sc: SparkContext) { this(sc, None, None, SparkSession.applyExtensions( sc.getConf.get(StaticSQLConf.SPARK_SESSION_EXTENSIONS), new SparkSessionExtensions)) } sparkContext.assertNotStopped() // If there is no active SparkSession, uses the default SQL conf. Otherwise, use the session's. SQLConf.setSQLConfGetter(() => { SparkSession.getActiveSession.filterNot(_.sparkContext.isStopped).map(_.sessionState.conf) .getOrElse(SQLConf.getFallbackConf) }) /** * The version of Spark on which this application is running. * * @since 2.0.0 */ def version: String = SPARK_VERSION /* ----------------------- * | Session-related state | * ----------------------- */ /** * State shared across sessions, including the `SparkContext`, cached data, listener, * and a catalog that interacts with external systems. * * This is internal to Spark and there is no guarantee on interface stability. * * @since 2.2.0 */ @Unstable @transient lazy val sharedState: SharedState = { existingSharedState.getOrElse(new SharedState(sparkContext)) } /** * Initial options for session. This options are applied once when sessionState is created. */ @transient private[sql] val initialSessionOptions = new scala.collection.mutable.HashMap[String, String] /** * State isolated across sessions, including SQL configurations, temporary tables, registered * functions, and everything else that accepts a [[org.apache.spark.sql.internal.SQLConf]]. * If `parentSessionState` is not null, the `SessionState` will be a copy of the parent. * * This is internal to Spark and there is no guarantee on interface stability. * * @since 2.2.0 */ @Unstable @transient lazy val sessionState: SessionState = { parentSessionState .map(_.clone(this)) .getOrElse { val state = SparkSession.instantiateSessionState( SparkSession.sessionStateClassName(sparkContext.conf), self) initialSessionOptions.foreach { case (k, v) => state.conf.setConfString(k, v) } state } } /** * A wrapped version of this session in the form of a [[SQLContext]], for backward compatibility. * * @since 2.0.0 */ @transient val sqlContext: SQLContext = new SQLContext(this) /** * Runtime configuration interface for Spark. * * This is the interface through which the user can get and set all Spark and Hadoop * configurations that are relevant to Spark SQL. When getting the value of a config, * this defaults to the value set in the underlying `SparkContext`, if any. * * @since 2.0.0 */ @transient lazy val conf: RuntimeConfig = new RuntimeConfig(sessionState.conf) /** * :: Experimental :: * An interface to register custom [[org.apache.spark.sql.util.QueryExecutionListener]]s * that listen for execution metrics. * * @since 2.0.0 */ @Experimental @Evolving def listenerManager: ExecutionListenerManager = sessionState.listenerManager /** * :: Experimental :: * A collection of methods that are considered experimental, but can be used to hook into * the query planner for advanced functionality. * * @since 2.0.0 */ @Experimental @Unstable def experimental: ExperimentalMethods = sessionState.experimentalMethods /** * A collection of methods for registering user-defined functions (UDF). * * The following example registers a Scala closure as UDF: * {{{ * sparkSession.udf.register("myUDF", (arg1: Int, arg2: String) => arg2 + arg1) * }}} * * The following example registers a UDF in Java: * {{{ * sparkSession.udf().register("myUDF", * (Integer arg1, String arg2) -> arg2 + arg1, * DataTypes.StringType); * }}} * * @note The user-defined functions must be deterministic. Due to optimization, * duplicate invocations may be eliminated or the function may even be invoked more times than * it is present in the query. * * @since 2.0.0 */ def udf: UDFRegistration = sessionState.udfRegistration /** * :: Experimental :: * Returns a `StreamingQueryManager` that allows managing all the * `StreamingQuery`s active on `this`. * * @since 2.0.0 */ @Experimental @Unstable def streams: StreamingQueryManager = sessionState.streamingQueryManager /** * Start a new session with isolated SQL configurations, temporary tables, registered * functions are isolated, but sharing the underlying `SparkContext` and cached data. * * @note Other than the `SparkContext`, all shared state is initialized lazily. * This method will force the initialization of the shared state to ensure that parent * and child sessions are set up with the same shared state. If the underlying catalog * implementation is Hive, this will initialize the metastore, which may take some time. * * @since 2.0.0 */ def newSession(): SparkSession = { new SparkSession(sparkContext, Some(sharedState), parentSessionState = None, extensions) } /** * Create an identical copy of this `SparkSession`, sharing the underlying `SparkContext` * and shared state. All the state of this session (i.e. SQL configurations, temporary tables, * registered functions) is copied over, and the cloned session is set up with the same shared * state as this session. The cloned session is independent of this session, that is, any * non-global change in either session is not reflected in the other. * * @note Other than the `SparkContext`, all shared state is initialized lazily. * This method will force the initialization of the shared state to ensure that parent * and child sessions are set up with the same shared state. If the underlying catalog * implementation is Hive, this will initialize the metastore, which may take some time. */ private[sql] def cloneSession(): SparkSession = { val result = new SparkSession(sparkContext, Some(sharedState), Some(sessionState), extensions) result.sessionState // force copy of SessionState result } /* --------------------------------- * | Methods for creating DataFrames | * --------------------------------- */ /** * Returns a `DataFrame` with no rows or columns. * * @since 2.0.0 */ @transient lazy val emptyDataFrame: DataFrame = { createDataFrame(sparkContext.emptyRDD[Row].setName("empty"), StructType(Nil)) } /** * :: Experimental :: * Creates a new [[Dataset]] of type T containing zero elements. * * @return 2.0.0 */ @Experimental @Evolving def emptyDataset[T: Encoder]: Dataset[T] = { val encoder = implicitly[Encoder[T]] new Dataset(self, LocalRelation(encoder.schema.toAttributes), encoder) } /** * :: Experimental :: * Creates a `DataFrame` from an RDD of Product (e.g. case classes, tuples). * * @since 2.0.0 */ @Experimental @Evolving def createDataFrame[A <: Product : TypeTag](rdd: RDD[A]): DataFrame = { SparkSession.setActiveSession(this) val encoder = Encoders.product[A] Dataset.ofRows(self, ExternalRDD(rdd, self)(encoder)) } /** * :: Experimental :: * Creates a `DataFrame` from a local Seq of Product. * * @since 2.0.0 */ @Experimental @Evolving def createDataFrame[A <: Product : TypeTag](data: Seq[A]): DataFrame = { SparkSession.setActiveSession(this) val schema = ScalaReflection.schemaFor[A].dataType.asInstanceOf[StructType] val attributeSeq = schema.toAttributes Dataset.ofRows(self, LocalRelation.fromProduct(attributeSeq, data)) } /** * :: DeveloperApi :: * Creates a `DataFrame` from an `RDD` containing [[Row]]s using the given schema. * It is important to make sure that the structure of every [[Row]] of the provided RDD matches * the provided schema. Otherwise, there will be runtime exception. * Example: * {{{ * import org.apache.spark.sql._ * import org.apache.spark.sql.types._ * val sparkSession = new org.apache.spark.sql.SparkSession(sc) * * val schema = * StructType( * StructField("name", StringType, false) :: * StructField("age", IntegerType, true) :: Nil) * * val people = * sc.textFile("examples/src/main/resources/people.txt").map( * _.split(",")).map(p => Row(p(0), p(1).trim.toInt)) * val dataFrame = sparkSession.createDataFrame(people, schema) * dataFrame.printSchema * // root * // |-- name: string (nullable = false) * // |-- age: integer (nullable = true) * * dataFrame.createOrReplaceTempView("people") * sparkSession.sql("select name from people").collect.foreach(println) * }}} * * @since 2.0.0 */ @DeveloperApi @Evolving def createDataFrame(rowRDD: RDD[Row], schema: StructType): DataFrame = { createDataFrame(rowRDD, schema, needsConversion = true) } /** * :: DeveloperApi :: * Creates a `DataFrame` from a `JavaRDD` containing [[Row]]s using the given schema. * It is important to make sure that the structure of every [[Row]] of the provided RDD matches * the provided schema. Otherwise, there will be runtime exception. * * @since 2.0.0 */ @DeveloperApi @Evolving def createDataFrame(rowRDD: JavaRDD[Row], schema: StructType): DataFrame = { createDataFrame(rowRDD.rdd, schema) } /** * :: DeveloperApi :: * Creates a `DataFrame` from a `java.util.List` containing [[Row]]s using the given schema. * It is important to make sure that the structure of every [[Row]] of the provided List matches * the provided schema. Otherwise, there will be runtime exception. * * @since 2.0.0 */ @DeveloperApi @Evolving def createDataFrame(rows: java.util.List[Row], schema: StructType): DataFrame = { Dataset.ofRows(self, LocalRelation.fromExternalRows(schema.toAttributes, rows.asScala)) } /** * Applies a schema to an RDD of Java Beans. * * WARNING: Since there is no guaranteed ordering for fields in a Java Bean, * SELECT * queries will return the columns in an undefined order. * * @since 2.0.0 */ def createDataFrame(rdd: RDD[_], beanClass: Class[_]): DataFrame = { val attributeSeq: Seq[AttributeReference] = getSchema(beanClass) val className = beanClass.getName val rowRdd = rdd.mapPartitions { iter => // BeanInfo is not serializable so we must rediscover it remotely for each partition. SQLContext.beansToRows(iter, Utils.classForName(className), attributeSeq) } Dataset.ofRows(self, LogicalRDD(attributeSeq, rowRdd.setName(rdd.name))(self)) } /** * Applies a schema to an RDD of Java Beans. * * WARNING: Since there is no guaranteed ordering for fields in a Java Bean, * SELECT * queries will return the columns in an undefined order. * * @since 2.0.0 */ def createDataFrame(rdd: JavaRDD[_], beanClass: Class[_]): DataFrame = { createDataFrame(rdd.rdd, beanClass) } /** * Applies a schema to a List of Java Beans. * * WARNING: Since there is no guaranteed ordering for fields in a Java Bean, * SELECT * queries will return the columns in an undefined order. * @since 1.6.0 */ def createDataFrame(data: java.util.List[_], beanClass: Class[_]): DataFrame = { val attrSeq = getSchema(beanClass) val rows = SQLContext.beansToRows(data.asScala.iterator, beanClass, attrSeq) Dataset.ofRows(self, LocalRelation(attrSeq, rows.toSeq)) } /** * Convert a `BaseRelation` created for external data sources into a `DataFrame`. * * @since 2.0.0 */ def baseRelationToDataFrame(baseRelation: BaseRelation): DataFrame = { Dataset.ofRows(self, LogicalRelation(baseRelation)) } /* ------------------------------- * | Methods for creating DataSets | * ------------------------------- */ /** * :: Experimental :: * Creates a [[Dataset]] from a local Seq of data of a given type. This method requires an * encoder (to convert a JVM object of type `T` to and from the internal Spark SQL representation) * that is generally created automatically through implicits from a `SparkSession`, or can be * created explicitly by calling static methods on [[Encoders]]. * * == Example == * * {{{ * * import spark.implicits._ * case class Person(name: String, age: Long) * val data = Seq(Person("Michael", 29), Person("Andy", 30), Person("Justin", 19)) * val ds = spark.createDataset(data) * * ds.show() * // +-------+---+ * // | name|age| * // +-------+---+ * // |Michael| 29| * // | Andy| 30| * // | Justin| 19| * // +-------+---+ * }}} * * @since 2.0.0 */ @Experimental @Evolving def createDataset[T : Encoder](data: Seq[T]): Dataset[T] = { val enc = encoderFor[T] val attributes = enc.schema.toAttributes val encoded = data.map(d => enc.toRow(d).copy()) val plan = new LocalRelation(attributes, encoded) Dataset[T](self, plan) } /** * :: Experimental :: * Creates a [[Dataset]] from an RDD of a given type. This method requires an * encoder (to convert a JVM object of type `T` to and from the internal Spark SQL representation) * that is generally created automatically through implicits from a `SparkSession`, or can be * created explicitly by calling static methods on [[Encoders]]. * * @since 2.0.0 */ @Experimental @Evolving def createDataset[T : Encoder](data: RDD[T]): Dataset[T] = { Dataset[T](self, ExternalRDD(data, self)) } /** * :: Experimental :: * Creates a [[Dataset]] from a `java.util.List` of a given type. This method requires an * encoder (to convert a JVM object of type `T` to and from the internal Spark SQL representation) * that is generally created automatically through implicits from a `SparkSession`, or can be * created explicitly by calling static methods on [[Encoders]]. * * == Java Example == * * {{{ * List<String> data = Arrays.asList("hello", "world"); * Dataset<String> ds = spark.createDataset(data, Encoders.STRING()); * }}} * * @since 2.0.0 */ @Experimental @Evolving def createDataset[T : Encoder](data: java.util.List[T]): Dataset[T] = { createDataset(data.asScala) } /** * :: Experimental :: * Creates a [[Dataset]] with a single `LongType` column named `id`, containing elements * in a range from 0 to `end` (exclusive) with step value 1. * * @since 2.0.0 */ @Experimental @Evolving def range(end: Long): Dataset[java.lang.Long] = range(0, end) /** * :: Experimental :: * Creates a [[Dataset]] with a single `LongType` column named `id`, containing elements * in a range from `start` to `end` (exclusive) with step value 1. * * @since 2.0.0 */ @Experimental @Evolving def range(start: Long, end: Long): Dataset[java.lang.Long] = { range(start, end, step = 1, numPartitions = sparkContext.defaultParallelism) } /** * :: Experimental :: * Creates a [[Dataset]] with a single `LongType` column named `id`, containing elements * in a range from `start` to `end` (exclusive) with a step value. * * @since 2.0.0 */ @Experimental @Evolving def range(start: Long, end: Long, step: Long): Dataset[java.lang.Long] = { range(start, end, step, numPartitions = sparkContext.defaultParallelism) } /** * :: Experimental :: * Creates a [[Dataset]] with a single `LongType` column named `id`, containing elements * in a range from `start` to `end` (exclusive) with a step value, with partition number * specified. * * @since 2.0.0 */ @Experimental @Evolving def range(start: Long, end: Long, step: Long, numPartitions: Int): Dataset[java.lang.Long] = { new Dataset(self, Range(start, end, step, numPartitions), Encoders.LONG) } /** * Creates a `DataFrame` from an `RDD[InternalRow]`. */ private[sql] def internalCreateDataFrame( catalystRows: RDD[InternalRow], schema: StructType, isStreaming: Boolean = false): DataFrame = { // TODO: use MutableProjection when rowRDD is another DataFrame and the applied // schema differs from the existing schema on any field data type. val logicalPlan = LogicalRDD( schema.toAttributes, catalystRows, isStreaming = isStreaming)(self) Dataset.ofRows(self, logicalPlan) } /** * Creates a `DataFrame` from an `RDD[Row]`. * User can specify whether the input rows should be converted to Catalyst rows. */ private[sql] def createDataFrame( rowRDD: RDD[Row], schema: StructType, needsConversion: Boolean) = { // TODO: use MutableProjection when rowRDD is another DataFrame and the applied // schema differs from the existing schema on any field data type. val catalystRows = if (needsConversion) { val encoder = RowEncoder(schema) rowRDD.map(encoder.toRow) } else { rowRDD.map { r: Row => InternalRow.fromSeq(r.toSeq) } } internalCreateDataFrame(catalystRows.setName(rowRDD.name), schema) } /* ------------------------- * | Catalog-related methods | * ------------------------- */ /** * Interface through which the user may create, drop, alter or query underlying * databases, tables, functions etc. * * @since 2.0.0 */ @transient lazy val catalog: Catalog = new CatalogImpl(self) /** * Returns the specified table/view as a `DataFrame`. * * @param tableName is either a qualified or unqualified name that designates a table or view. * If a database is specified, it identifies the table/view from the database. * Otherwise, it first attempts to find a temporary view with the given name * and then match the table/view from the current database. * Note that, the global temporary view database is also valid here. * @since 2.0.0 */ def table(tableName: String): DataFrame = { table(sessionState.sqlParser.parseTableIdentifier(tableName)) } private[sql] def table(tableIdent: TableIdentifier): DataFrame = { Dataset.ofRows(self, UnresolvedRelation(tableIdent)) } /* ----------------- * | Everything else | * ----------------- */ /** * Executes a SQL query using Spark, returning the result as a `DataFrame`. * The dialect that is used for SQL parsing can be configured with 'spark.sql.dialect'. * * @since 2.0.0 */ def sql(sqlText: String): DataFrame = { val tracker = new QueryPlanningTracker val plan = tracker.measurePhase(QueryPlanningTracker.PARSING) { sessionState.sqlParser.parsePlan(sqlText) } Dataset.ofRows(self, plan, tracker) } /** * Returns a [[DataFrameReader]] that can be used to read non-streaming data in as a * `DataFrame`. * {{{ * sparkSession.read.parquet("/path/to/file.parquet") * sparkSession.read.schema(schema).json("/path/to/file.json") * }}} * * @since 2.0.0 */ def read: DataFrameReader = new DataFrameReader(self) /** * Returns a `DataStreamReader` that can be used to read streaming data in as a `DataFrame`. * {{{ * sparkSession.readStream.parquet("/path/to/directory/of/parquet/files") * sparkSession.readStream.schema(schema).json("/path/to/directory/of/json/files") * }}} * * @since 2.0.0 */ @Evolving def readStream: DataStreamReader = new DataStreamReader(self) /** * Executes some code block and prints to stdout the time taken to execute the block. This is * available in Scala only and is used primarily for interactive testing and debugging. * * @since 2.1.0 */ def time[T](f: => T): T = { val start = System.nanoTime() val ret = f val end = System.nanoTime() // scalastyle:off println println(s"Time taken: ${(end - start) / 1000 / 1000} ms") // scalastyle:on println ret } // scalastyle:off // Disable style checker so "implicits" object can start with lowercase i /** * :: Experimental :: * (Scala-specific) Implicit methods available in Scala for converting * common Scala objects into `DataFrame`s. * * {{{ * val sparkSession = SparkSession.builder.getOrCreate() * import sparkSession.implicits._ * }}} * * @since 2.0.0 */ @Experimental @Evolving object implicits extends SQLImplicits with Serializable { protected override def _sqlContext: SQLContext = SparkSession.this.sqlContext } // scalastyle:on /** * Stop the underlying `SparkContext`. * * @since 2.0.0 */ def stop(): Unit = { sparkContext.stop() } /** * Synonym for `stop()`. * * @since 2.1.0 */ override def close(): Unit = stop() /** * Parses the data type in our internal string representation. The data type string should * have the same format as the one generated by `toString` in scala. * It is only used by PySpark. */ protected[sql] def parseDataType(dataTypeString: String): DataType = { DataType.fromJson(dataTypeString) } /** * Apply a schema defined by the schemaString to an RDD. It is only used by PySpark. */ private[sql] def applySchemaToPythonRDD( rdd: RDD[Array[Any]], schemaString: String): DataFrame = { val schema = DataType.fromJson(schemaString).asInstanceOf[StructType] applySchemaToPythonRDD(rdd, schema) } /** * Apply `schema` to an RDD. * * @note Used by PySpark only */ private[sql] def applySchemaToPythonRDD( rdd: RDD[Array[Any]], schema: StructType): DataFrame = { val rowRdd = rdd.mapPartitions { iter => val fromJava = python.EvaluatePython.makeFromJava(schema) iter.map(r => fromJava(r).asInstanceOf[InternalRow]) } internalCreateDataFrame(rowRdd, schema) } /** * Returns a Catalyst Schema for the given java bean class. */ private def getSchema(beanClass: Class[_]): Seq[AttributeReference] = { val (dataType, _) = JavaTypeInference.inferDataType(beanClass) dataType.asInstanceOf[StructType].fields.map { f => AttributeReference(f.name, f.dataType, f.nullable)() } } } @Stable object SparkSession extends Logging { /** * Builder for [[SparkSession]]. */ @Stable class Builder extends Logging { private[this] val options = new scala.collection.mutable.HashMap[String, String] private[this] val extensions = new SparkSessionExtensions private[this] var userSuppliedContext: Option[SparkContext] = None private[spark] def sparkContext(sparkContext: SparkContext): Builder = synchronized { userSuppliedContext = Option(sparkContext) this } /** * Sets a name for the application, which will be shown in the Spark web UI. * If no application name is set, a randomly generated name will be used. * * @since 2.0.0 */ def appName(name: String): Builder = config("spark.app.name", name) /** * Sets a config option. Options set using this method are automatically propagated to * both `SparkConf` and SparkSession's own configuration. * * @since 2.0.0 */ def config(key: String, value: String): Builder = synchronized { options += key -> value this } /** * Sets a config option. Options set using this method are automatically propagated to * both `SparkConf` and SparkSession's own configuration. * * @since 2.0.0 */ def config(key: String, value: Long): Builder = synchronized { options += key -> value.toString this } /** * Sets a config option. Options set using this method are automatically propagated to * both `SparkConf` and SparkSession's own configuration. * * @since 2.0.0 */ def config(key: String, value: Double): Builder = synchronized { options += key -> value.toString this } /** * Sets a config option. Options set using this method are automatically propagated to * both `SparkConf` and SparkSession's own configuration. * * @since 2.0.0 */ def config(key: String, value: Boolean): Builder = synchronized { options += key -> value.toString this } /** * Sets a list of config options based on the given `SparkConf`. * * @since 2.0.0 */ def config(conf: SparkConf): Builder = synchronized { conf.getAll.foreach { case (k, v) => options += k -> v } this } /** * Sets the Spark master URL to connect to, such as "local" to run locally, "local[4]" to * run locally with 4 cores, or "spark://master:7077" to run on a Spark standalone cluster. * * @since 2.0.0 */ def master(master: String): Builder = config("spark.master", master) /** * Enables Hive support, including connectivity to a persistent Hive metastore, support for * Hive serdes, and Hive user-defined functions. * * @since 2.0.0 */ def enableHiveSupport(): Builder = synchronized { if (hiveClassesArePresent) { config(CATALOG_IMPLEMENTATION.key, "hive") } else { throw new IllegalArgumentException( "Unable to instantiate SparkSession with Hive support because " + "Hive classes are not found.") } } /** * Inject extensions into the [[SparkSession]]. This allows a user to add Analyzer rules, * Optimizer rules, Planning Strategies or a customized parser. * * @since 2.2.0 */ def withExtensions(f: SparkSessionExtensions => Unit): Builder = synchronized { f(extensions) this } /** * Gets an existing [[SparkSession]] or, if there is no existing one, creates a new * one based on the options set in this builder. * * This method first checks whether there is a valid thread-local SparkSession, * and if yes, return that one. It then checks whether there is a valid global * default SparkSession, and if yes, return that one. If no valid global default * SparkSession exists, the method creates a new SparkSession and assigns the * newly created SparkSession as the global default. * * In case an existing SparkSession is returned, the config options specified in * this builder will be applied to the existing SparkSession. * * @since 2.0.0 */ def getOrCreate(): SparkSession = synchronized { assertOnDriver() // Get the session from current thread's active session. var session = activeThreadSession.get() if ((session ne null) && !session.sparkContext.isStopped) { options.foreach { case (k, v) => session.sessionState.conf.setConfString(k, v) } if (options.nonEmpty) { logWarning("Using an existing SparkSession; some configuration may not take effect.") } return session } // Global synchronization so we will only set the default session once. SparkSession.synchronized { // If the current thread does not have an active session, get it from the global session. session = defaultSession.get() if ((session ne null) && !session.sparkContext.isStopped) { options.foreach { case (k, v) => session.sessionState.conf.setConfString(k, v) } if (options.nonEmpty) { logWarning("Using an existing SparkSession; some configuration may not take effect.") } return session } // No active nor global default session. Create a new one. val sparkContext = userSuppliedContext.getOrElse { val sparkConf = new SparkConf() options.foreach { case (k, v) => sparkConf.set(k, v) } // set a random app name if not given. if (!sparkConf.contains("spark.app.name")) { sparkConf.setAppName(java.util.UUID.randomUUID().toString) } SparkContext.getOrCreate(sparkConf) // Do not update `SparkConf` for existing `SparkContext`, as it's shared by all sessions. } applyExtensions( sparkContext.getConf.get(StaticSQLConf.SPARK_SESSION_EXTENSIONS), extensions) session = new SparkSession(sparkContext, None, None, extensions) options.foreach { case (k, v) => session.initialSessionOptions.put(k, v) } setDefaultSession(session) setActiveSession(session) // Register a successfully instantiated context to the singleton. This should be at the // end of the class definition so that the singleton is updated only if there is no // exception in the construction of the instance. sparkContext.addSparkListener(new SparkListener { override def onApplicationEnd(applicationEnd: SparkListenerApplicationEnd): Unit = { defaultSession.set(null) } }) } return session } } /** * Creates a [[SparkSession.Builder]] for constructing a [[SparkSession]]. * * @since 2.0.0 */ def builder(): Builder = new Builder /** * Changes the SparkSession that will be returned in this thread and its children when * SparkSession.getOrCreate() is called. This can be used to ensure that a given thread receives * a SparkSession with an isolated session, instead of the global (first created) context. * * @since 2.0.0 */ def setActiveSession(session: SparkSession): Unit = { activeThreadSession.set(session) } /** * Clears the active SparkSession for current thread. Subsequent calls to getOrCreate will * return the first created context instead of a thread-local override. * * @since 2.0.0 */ def clearActiveSession(): Unit = { activeThreadSession.remove() } /** * Sets the default SparkSession that is returned by the builder. * * @since 2.0.0 */ def setDefaultSession(session: SparkSession): Unit = { defaultSession.set(session) } /** * Clears the default SparkSession that is returned by the builder. * * @since 2.0.0 */ def clearDefaultSession(): Unit = { defaultSession.set(null) } /** * Returns the active SparkSession for the current thread, returned by the builder. * * @note Return None, when calling this function on executors * * @since 2.2.0 */ def getActiveSession: Option[SparkSession] = { if (TaskContext.get != null) { // Return None when running on executors. None } else { Option(activeThreadSession.get) } } /** * Returns the default SparkSession that is returned by the builder. * * @note Return None, when calling this function on executors * * @since 2.2.0 */ def getDefaultSession: Option[SparkSession] = { if (TaskContext.get != null) { // Return None when running on executors. None } else { Option(defaultSession.get) } } /** * Returns the currently active SparkSession, otherwise the default one. If there is no default * SparkSession, throws an exception. * * @since 2.4.0 */ def active: SparkSession = { getActiveSession.getOrElse(getDefaultSession.getOrElse( throw new IllegalStateException("No active or default Spark session found"))) } //////////////////////////////////////////////////////////////////////////////////////// // Private methods from now on //////////////////////////////////////////////////////////////////////////////////////// /** The active SparkSession for the current thread. */ private val activeThreadSession = new InheritableThreadLocal[SparkSession] /** Reference to the root SparkSession. */ private val defaultSession = new AtomicReference[SparkSession] private val HIVE_SESSION_STATE_BUILDER_CLASS_NAME = "org.apache.spark.sql.hive.HiveSessionStateBuilder" private def sessionStateClassName(conf: SparkConf): String = { conf.get(CATALOG_IMPLEMENTATION) match { case "hive" => HIVE_SESSION_STATE_BUILDER_CLASS_NAME case "in-memory" => classOf[SessionStateBuilder].getCanonicalName } } private def assertOnDriver(): Unit = { if (Utils.isTesting && TaskContext.get != null) { // we're accessing it during task execution, fail. throw new IllegalStateException( "SparkSession should only be created and accessed on the driver.") } } /** * Helper method to create an instance of `SessionState` based on `className` from conf. * The result is either `SessionState` or a Hive based `SessionState`. */ private def instantiateSessionState( className: String, sparkSession: SparkSession): SessionState = { try { // invoke `new [Hive]SessionStateBuilder(SparkSession, Option[SessionState])` val clazz = Utils.classForName(className) val ctor = clazz.getConstructors.head ctor.newInstance(sparkSession, None).asInstanceOf[BaseSessionStateBuilder].build() } catch { case NonFatal(e) => throw new IllegalArgumentException(s"Error while instantiating '$className':", e) } } /** * @return true if Hive classes can be loaded, otherwise false. */ private[spark] def hiveClassesArePresent: Boolean = { try { Utils.classForName(HIVE_SESSION_STATE_BUILDER_CLASS_NAME) Utils.classForName("org.apache.hadoop.hive.conf.HiveConf") true } catch { case _: ClassNotFoundException | _: NoClassDefFoundError => false } } private[spark] def cleanupAnyExistingSession(): Unit = { val session = getActiveSession.orElse(getDefaultSession) if (session.isDefined) { logWarning( s"""An existing Spark session exists as the active or default session. |This probably means another suite leaked it. Attempting to stop it before continuing. |This existing Spark session was created at: | |${session.get.creationSite.longForm} | """.stripMargin) session.get.stop() SparkSession.clearActiveSession() SparkSession.clearDefaultSession() } } /** * Initialize extensions for given extension classname. This class will be applied to the * extensions passed into this function. */ private def applyExtensions( extensionOption: Option[String], extensions: SparkSessionExtensions): SparkSessionExtensions = { if (extensionOption.isDefined) { val extensionConfClassName = extensionOption.get try { val extensionConfClass = Utils.classForName(extensionConfClassName) val extensionConf = extensionConfClass.getConstructor().newInstance() .asInstanceOf[SparkSessionExtensions => Unit] extensionConf(extensions) } catch { // Ignore the error if we cannot find the class or when the class has the wrong type. case e@(_: ClassCastException | _: ClassNotFoundException | _: NoClassDefFoundError) => logWarning(s"Cannot use $extensionConfClassName to configure session extensions.", e) } } extensions } }
guoxiaolongzte/spark
sql/core/src/main/scala/org/apache/spark/sql/SparkSession.scala
Scala
apache-2.0
39,062
/* * (C) Copyright IBM Corp. 2015 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package src.main.scala; import org.apache.log4j.Logger import org.apache.log4j.Level import scala.language.postfixOps import scala.util.Random import org.jblas.DoubleMatrix import org.apache.spark.storage.StorageLevel import org.apache.spark.{ SparkContext, SparkConf} import org.apache.spark.internal.Logging import org.apache.spark.rdd.RDD import java.io._ /** * Generate RDD(s) containing data for Matrix Factorization. * * This method samples training entries according to the oversampling factor * 'trainSampFact', which is a multiplicative factor of the number of * degrees of freedom of the matrix: rank*(m+n-rank). * * It optionally samples entries for a testing matrix using * 'testSampFact', the percentage of the number of training entries * to use for testing. * * This method takes the following inputs: * outputPath (String) Directory to save output. * m (Int) Number of rows in data matrix. * n (Int) Number of columns in data matrix. * rank (Int) Underlying rank of data matrix. * trainSampFact (Double) Oversampling factor. * noise (Boolean) Whether to add gaussian noise to training data. * sigma (Double) Standard deviation of added gaussian noise. * test (Boolean) Whether to create testing RDD. * testSampFact (Double) Percentage of training data to use as test data. * numPar (Int) Number of partitions of input data file */ object MFDataGenerator { def main(args: Array[String]) { if (args.length < 1) { println("Usage: MFDataGenerator " + "<outputDir> [m] [n] [rank] [trainSampFact] [noise] [sigma] [test] [testSampFact] [numPar]") System.exit(1) } Logger.getLogger("org.apache.spark").setLevel(Level.WARN) Logger.getLogger("org.eclipse.jetty.server").setLevel(Level.OFF) val outputPath: String = args(0) val m: Int = if (args.length > 1) args(1).toInt else 100 val n: Int = if (args.length > 2) args(2).toInt else 100 val rank: Int = if (args.length > 3) args(3).toInt else 10 val trainSampFact: Double = if (args.length > 4) args(4).toDouble else 1.0 val noise: Boolean = if (args.length > 5) args(5).toBoolean else false val sigma: Double = if (args.length > 6) args(6).toDouble else 0.1 val test: Boolean = if (args.length > 7) args(7).toBoolean else false val testSampFact: Double = if (args.length > 8) args(8).toDouble else 0.1 val defPar = if (System.getProperty("spark.default.parallelism") == null) 2 else System.getProperty("spark.default.parallelism").toInt val numPar: Int = if (args.length > 9) args(9).toInt else defPar val conf = new SparkConf().setAppName("MFDataGenerator") val sc = new SparkContext(conf) val A = DoubleMatrix.randn(m, rank) val B = DoubleMatrix.randn(rank, n) val z = 1 / scala.math.sqrt(scala.math.sqrt(rank)) A.mmuli(z) B.mmuli(z) val fullData = A.mmul(B) val df = rank * (m + n - rank) val sampSize = scala.math.min(scala.math.round(trainSampFact * df), scala.math.round(.99 * m * n)).toInt val rand = new Random() val mn = m * n /* val canonicalFilename="/mnt/nfs_dir/tmp_data/tmp" val file = new File(canonicalFilename) file.delete() if(!file.exists()) { file.createNewFile(); } val bw = new BufferedWriter(new FileWriter(file)) 1 to mn foreach {i=> bw.write(i.toString+"\\n");} bw.flush() bw.close() */ //val shuffled = rand.shuffle(1 to mn toList) // val shuffled = 1 to mn toList //val omega = shuffled.slice(0, sampSize) //val ordered = omega.sortWith(_ < _).toArray /* val my_rdd=sc.textFile("file://"+canonicalFilename,400) */ val my_rdd=sc.makeRDD(1 to mn, numPar) my_rdd.persist(StorageLevel.MEMORY_AND_DISK) val trainData: RDD[(Int, Int, Double)] = my_rdd .map(x => (fullData.indexRows(x.toInt - 1), fullData.indexColumns(x.toInt - 1), fullData.get(x.toInt - 1))) // trainData.persist(StorageLevel.MEMORY_AND_DISK) //val trainData: RDD[(Int, Int, Double)] = sc.parallelize(ordered) //.map(x => (fullData.indexRows(x - 1), fullData.indexColumns(x - 1), fullData.get(x - 1))) // optionally add gaussian noise if (noise) { trainData.map(x => (x._1, x._2, x._3 + rand.nextGaussian * sigma)) } trainData.map(x => x._1 + "," + x._2 + "," + x._3).saveAsTextFile(outputPath) // optionally generate testing data /* if (test) { val testSampSize = scala.math .min(scala.math.round(sampSize * testSampFact),scala.math.round(mn - sampSize)).toInt val testOmega = shuffled.slice(sampSize, sampSize + testSampSize) val testOrdered = testOmega.sortWith(_ < _).toArray val testData: RDD[(Int, Int, Double)] = sc.parallelize(testOrdered) .map(x => (fullData.indexRows(x - 1), fullData.indexColumns(x - 1), fullData.get(x - 1))) testData.map(x => x._1 + "," + x._2 + "," + x._3).saveAsTextFile(outputPath) }*/ sc.stop() } }
ElfoLiNk/spark-bench
MatrixFactorization/src/main/scala/MFDataGenerator.scala
Scala
apache-2.0
5,643
package core import org.scalatest.{FunSpec, Matchers} class UtilSpec extends FunSpec with Matchers { it("namedParametersInPath") { Util.namedParametersInPath("/users") should be(Seq.empty) Util.namedParametersInPath("/users/:guid") should be(Seq("guid")) Util.namedParametersInPath("/users/:guid.json") should be(Seq("guid")) Util.namedParametersInPath("/:org/foo/:version") should be(Seq("org", "version")) Util.namedParametersInPath("/:org/:service/:version") should be(Seq("org", "service", "version")) } it("isValidEnumValue") { val service = TestHelper.parseFile(s"spec/apibuilder-api.json").service() val visibilityEnum = service.enums.find(_.name == "visibility").getOrElse { sys.error("No visibility enum found") } Util.isValidEnumValue(visibilityEnum, "user") should be(true) Util.isValidEnumValue(visibilityEnum, "organization") should be(true) Util.isValidEnumValue(visibilityEnum, "foobar") should be(false) } it("isValidUri") { Seq( "http://www.apidoc.me", "https://www.apidoc.me", " http://www.apidoc.me ", " HTTPS://WWW.APIDOC.ME ", "http://apidoc.me", "https://api.apidoc.me", "file:///tmp/foo.json" ).foreach { uri => Util.isValidUri(uri) should be(true) } Seq( "www.apidoc.me", "apidoc", "bar baz" ).foreach { uri => Util.isValidUri(uri) should be(false) } } }
apicollective/apibuilder
core/src/test/scala/core/UtilSpec.scala
Scala
mit
1,448
package clock /* +1>> This source code is licensed as GPLv3 if not stated otherwise. >> NO responsibility taken for ANY harm, damage done >> to you, your data, animals, etc. >> +2>> >> Last modified: 2013-10-29 :: 20:37 >> Origin: patterns >> +3>> >> Copyright (c) 2013: >> >> | | | >> | ,---.,---|,---.|---. >> | | || |`---.| | >> `---'`---'`---'`---'`---' >> // Niklas Klügel >> +4>> >> Made in Bavaria by fat little elves - since 1983. */ import pattern._ abstract class Clock { def defaultMusicalDuration : MusicalDuration def accuracy : MusicalTime def currentMusicalTime : MusicalTime def start() : Unit def kill() : Unit def pause() : Unit def schedulePlayer(player: BasePlayer) : Unit } abstract class BaseClock extends Clock { protected var scheduled = Map[Double, Set[BasePlayer]]() protected val monitor = new Object protected var bpm = 120f protected def clockTempoDurationMillis: Long = (bpm2Millis(bpm)*accuracy.toDouble).toLong protected def bpm2Millis(bpm: Float): Float = { 60000.0f / bpm } def accuracy = MusicalDuration(1).d128 // == clock resolution def defaultMusicalDuration = MusicalDuration(0.5) protected var _currentMusicalTime = new MusicalTime(1) // logical time def currentMusicalTime = _currentMusicalTime private def nextBeat = 1-(_currentMusicalTime.toDouble % 1.0) /* private val runningThread = new Thread(new Runnable { def run() { while (running) { try { Thread.sleep(clockTempoDurationMillis) _currentMusicalTime = _currentMusicalTime + accuracy clock(accuracy.toDouble) } catch { case e : Throwable => e.printStackTrace//running = false } } } }) override def start() = { running = true runningThread.start() } override def kill() = { pause() monitor.synchronized { scheduled = Map() } } override def pause() = { running = false runningThread.interrupt() } */ //TODO: something to synchronize clocks, reset? override def schedulePlayer(player: BasePlayer) { // TODO: schedule on next beat this.schedule(player, nextBeat) } protected def schedule(player: BasePlayer, duration: Double) = { monitor.synchronized { val s = scheduled.get(duration) if (!s.isEmpty) { var set = s.get // dont permit double triggers if (!set.contains(player)) { set = set + player scheduled = scheduled + (duration -> set) } } else { scheduled = scheduled + (duration -> Set(player)) } } } protected def clock(passedTime: Double) = { scheduled = scheduled.map({ x => (x._1 - passedTime, x._2) }) var done = false while (!done && !scheduled.isEmpty) { monitor.synchronized { val currentMin = scheduled.minBy(_._1) if (currentMin._1 <= accuracy.toDouble) { scheduled = scheduled - currentMin._1 val set = currentMin._2 // could be dispatched to different threads... or every player // has own thread/actor?? val nextSet = set.map({x => val ctx = x.next(); (ctx, x) }).filter(! _._1.invalid) //schedule new set nextSet.foreach({ x => if(!x._1.invalid) { schedule(x._2, x._1.time.duration.toDouble) } }) } else { done = true } } } } } //TODO fix this mess class RTClock extends BaseClock { private var running = false; private val runningThread = new Thread(new Runnable { def run() { while (running) { try { Thread.sleep(clockTempoDurationMillis) _currentMusicalTime = _currentMusicalTime + accuracy clock(accuracy.toDouble) } catch { case e : Throwable => e.printStackTrace//running = false } } } }) override def start() = { running = true runningThread.start() } override def kill() = { pause() monitor.synchronized { scheduled = Map() } } override def pause() = { running = false runningThread.interrupt() } } class NRTClock extends BaseClock { def start() {} def kill() {} def pause() {} def render(start: MusicalTime, end: MusicalTime) = { _currentMusicalTime = start while(_currentMusicalTime <= end) { _currentMusicalTime + accuracy } } } class FakeClock extends Clock{ def defaultMusicalDuration = MusicalDuration(0.5) def currentMusicalTime = new MusicalTime(0) def accuracy = new MusicalTime(0.1) def start() {} def kill() {} def pause() {} def schedulePlayer(player: BasePlayer) {} } object FakeClock extends FakeClock
lodsb/patterns
src/main/scala/pattern/Clock.scala
Scala
gpl-3.0
4,928
/* Copyright 2014, 2015 Richard Wiedenhöft <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package xyz.wiedenhoeft.scalacrypt /* Exceptions MUST never be thrown in this project. They must be * returned inside a failure. */ /** Occurs when invalid padding is encountered. */ class BadPaddingException(message: String) extends Exception("Bad padding: " + message) /** Occurs when a block of illegal size is given to a block cipher. */ class IllegalBlockSizeException(message: String) extends Exception("Illegal block size: " + message) /** Occurs when ciphertexts are invalid. */ class InvalidCiphertextException(message: String) extends Exception("Invalid ciphertext: " + message) /** Occurs when during decryption problems are encountered. */ class DecryptionException(message: String) extends Exception("Decryption: " + message) /** Occurs when during encryption problems are encountered. */ class EncryptionException(message: String) extends Exception("Encryption: " + message) /** Occurs when problems are encountered during key creation. */ class KeyException(message: String) extends Exception("Key creation: " + message) /** Occurs when an iteratee behaves erratically. */ class IterateeException(message: String) extends Exception("Iteratee: " + message) /** Occurs when a keyed hash fails. */ class KeyedHashException(message: String) extends Exception("KeyedHash: " + message) /** Occurs when something is wrong with the given parameters. */ class ParameterException(val symbol: Symbol, message: String) extends Exception("Parameters: " + message)
Richard-W/scalacrypt
src/main/scala/Exceptions.scala
Scala
apache-2.0
2,108
/////////////////////////////////////////////////////////////////////////////// // FeatureVector.scala // // Copyright (C) 2012-2014 Ben Wing, The University of Texas at Austin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////////// package opennlp.textgrounder package learning /** * Feature vectors for machine learning. * * @author Ben Wing */ import collection.mutable import util.collection.{doublemap, intmap} import util.error._ import util.memoizer._ import util.print.errprint /** Classification of the different types of values used for features. * Currently this is only for features that will be rescaled to make * them comparable across different query documents. Only features that * do involve the query document are candidates for this, and even then * only when the feature represents a score that differs dramatically * in scale from one query to the other and where only the difference * really matters (e.g. for KL-divergence). Currently only FeatRescale * below will be rescaled. */ sealed abstract class FeatureValue /** A feature value not to be scaled. */ case object FeatRaw extends FeatureValue /** A feature value needing scaling. */ case object FeatRescale extends FeatureValue case object FeatBinary extends FeatureValue case object FeatProb extends FeatureValue case object FeatLogProb extends FeatureValue case object FeatCount extends FeatureValue /** * A more general classification of features, just into nominal vs. * numeric. */ sealed abstract class FeatureClass case object NominalFeature extends FeatureClass case object NumericFeature extends FeatureClass /** * Mapping of features and labels into integers. In the context of a * classifier, "features" need to be distinguished into "feature properties" * and "combined features". The former, sometimes termed a "contextual * predicate" in the context of binary features, is a semantic concept * describing a property that may be found of data instances or combinations * of instances and labels, while the latter describes the combination of * a feature property and a given label. For instance, in the context of * GridLocate where instances are documents and labels are cells, the * binary feature property "london" has the value of 1 for a document * containing the word "london" regardless of the cell it is paired with, * and the corresponding combined feature "[email protected],2.5" having a value * of 1 means that the document when paired with the cell centered at * 53.5,2.5 has the value of 1. The same document will have a distinct * combined feature "[email protected],-120.0" when combined with a different cell. * In this case the identity of the label (i.e. cell) isn't needed to * compute the feature value but in some cases it is, e.g. the matching * feature "london$matching-unigram-binary" indicating that the word * "london" occurred in both document and cell. Regardless, the * separation of feature properties into distinct combined features is * necessary so that different weights are computed in TADM. * * For a ranker, combined features do not include the identity of the * cell, and thus all combined features with the same feature property * will be treated as the same feature, and only a single weight will be * assigned. This is correct in the context of a ranker, where the labels * can be thought of as numbers 1 through N, which are not meaningfully * distinguishable in the way that different labels of a classifier are. * * To combine a feature property and a label, we don't actually create * a string like "[email protected],2.5"; instead, we map the feature property's * name to an integer, and map the label to an integer, and combine them * in a Long, which is then memoized to an Int. This is done to save * memory. * * NOTE: This is *NOT* thread-safe! That means we can't parallelize * feature generation currently. In any case it's not clear it helps. * An experiment involving an attempt to do parallel feature generation * for classification (see commented-out code in create_classifier_ranker()) * actually yielded slower times running on roller/learningcurve03 * (18 hours vs 15 hours) when classifying at 5 degrees/cell, as well as * extremely incorrect results (mean 1869.60 km, median 1669.41 km, * instead of mean 935.92 km, median 479.24 km). At this point the * functions below were not synchronized but the basic memoizer functions * were. This means that the majority of time was spent in memoization, * and the synchronization clashes combined with the effort to split up * the work of parallelizing a relatively small number of cells (c. 50) * made the time grow. The way to fix this is to use feature hashing * (see the Wikipedia article on this), where the hash code of the * feature string (suitably modded) is directly used as an index. In this * case there is no shared memoization table and hence no problems with * parallelization. With a suitably large number of different hash items, * there will be little or no accuracy degradation and dramatically * increased performance. */ abstract class FeatureLabelMapper { protected val label_mapper = new ToIntMemoizer[String] protected val property_mapper = new ToIntMemoizer[String] def feature_to_index(feature: String, label: LabelIndex): FeatIndex def feature_to_index_if(feature: String, label: LabelIndex): Option[FeatIndex] def feature_to_string(index: FeatIndex): String def feature_vector_length: Int def feature_property_label_index(index: FeatIndex): (FeatIndex, FeatIndex) def feature_property_to_string(index: FeatIndex) = property_mapper.to_raw(index) val features_to_rescale = mutable.BitSet() protected def add_feature_property(feattype: FeatureValue, prop: String) = { val index = property_mapper.to_index(prop) feattype match { case FeatRescale => features_to_rescale += index case _ => () } index } def note_feature(feattype: FeatureValue, feature: String, label: LabelIndex ): FeatIndex def label_to_index(label: String): LabelIndex = label_mapper.to_index(label) def label_to_index_if(label: String): Option[LabelIndex] = label_mapper.to_index_if(label) def label_to_string(index: LabelIndex): String = label_mapper.to_raw(index) def number_of_labels: Int = label_mapper.number_of_indices } /** * The non-label-attached version of the feature mapper, which maps * feature properties directly to integers. * * NOTE: This is *NOT* thread-safe! See above. */ class SimpleFeatureLabelMapper extends FeatureLabelMapper { def feature_to_index(feature: String, label: LabelIndex) = property_mapper.to_index(feature) def feature_to_index_if(feature: String, label: LabelIndex) = property_mapper.to_index_if(feature) def feature_to_string(index: FeatIndex) = property_mapper.to_raw(index) def feature_vector_length = property_mapper.number_of_indices def feature_property_label_index(index: FeatIndex) = (index, -1) def note_feature(feattype: FeatureValue, feature: String, label: LabelIndex ) = add_feature_property(feattype, feature) } /** * The label-attached version of the feature mapper, which maps the * combination of feature property and label to an integer. * * NOTE: This is *NOT* thread-safe! See above. */ class LabelAttachedFeatureLabelMapper extends FeatureLabelMapper { val combined_mapper = new LongToIntMemoizer private def combined_to_long(prop_index: FeatIndex, label: LabelIndex) = { // If label could be negative, we need to and it with 0xFFFFFFFFL to // convert it to an unsigned value, but that should never happen. assert_>=(label, 0) (prop_index.toLong << 32) + label } def feature_to_index(feature: String, label: LabelIndex) = { val prop_index = property_mapper.to_index(feature) combined_mapper.to_index(combined_to_long(prop_index, label)) } def feature_to_index_if(feature: String, label: LabelIndex) = { // Only map to Some(...) if both feature property and combined feature // already exist. property_mapper.to_index_if(feature).flatMap { prop_index => combined_mapper.to_index_if(combined_to_long(prop_index, label)) } } def feature_to_string(index: FeatIndex) = { val longval = combined_mapper.to_raw(index) val prop_index = (longval >> 32).toInt val label_index = (longval & 0xFFFFFFFF).toInt property_mapper.to_raw(prop_index) + "@" + label_mapper.to_raw(label_index) } def feature_vector_length = combined_mapper.number_of_indices def note_feature(feattype: FeatureValue, feature: String, label: LabelIndex ) = { val prop_index = add_feature_property(feattype, feature) combined_mapper.to_index(combined_to_long(prop_index, label)) } def feature_property_label_index(index: FeatIndex) = { val longval = combined_mapper.to_raw(index) val prop_index = (longval >> 32).toInt val label_index = (longval & 0xFFFFFFFF).toInt (prop_index, label_index) } } /** * A vector of real-valued features. In general, features are indexed * both by a non-negative integer and by a class label (i.e. a label for * the class that is associated with a particular instance by a classifier). * Commonly, the class label is ignored when looking up a feature's value. * Some implementations might want to evaluate the features on-the-fly * rather than store an actual vector of values. */ trait FeatureVector extends DataInstance { final def feature_vector = this def mapper: FeatureLabelMapper /** Return the length of the feature vector. This is the number of weights * that need to be created -- not necessarily the actual number of items * stored in the vector (which will be different especially in the case * of sparse vectors). */ def length: Int = mapper.feature_vector_length /** Return number of labels for which label-specific information is stored. * For a simple feature vector that ignores the label, this will be 1. * For an aggregate feature vector storing a separate set of features for * each label, this will be the number of different sets of features stored. * This is used only in a variable-depth linear classifier, where the * number of possible labels may vary depending on the particular instance * being classified. */ def depth: Int /** Return maximum label index compatible with this feature vector. For * feature vectors that ignore the label, return a large number, e.g. * `Int.MaxValue`. */ def max_label: LabelIndex /** Return the number of items stored in the vector. This will be different * from the length in the case of sparse vectors. */ def stored_entries: Int /** Return the value at index `i`, for class `label`. */ def apply(i: FeatIndex, label: LabelIndex): Double /** Return the squared magnitude of the feature vector for class `label`, * i.e. dot product of feature vector with itself */ def squared_magnitude(label: LabelIndex): Double /** Return the squared magnitude of the difference between the values of * this feature vector for the two labels `label1` and `label2`. */ def diff_squared_magnitude(label1: LabelIndex, label2: LabelIndex): Double /** Return the squared magnitude of the difference between the values of * this feature vector for `label1` and another feature vector for * `label2`. */ def diff_squared_magnitude_2(label1: LabelIndex, other: FeatureVector, label2: LabelIndex): Double /** Return the dot product of the given weight vector with the feature * vector for class `label`. */ def dot_product(weights: SimpleVector, label: LabelIndex): Double /** Update a weight vector by adding a scaled version of the feature vector, * with class `label`. */ def update_weights(weights: SimpleVector, scale: Double, label: LabelIndex) /** Display the feature at the given index as a string. */ def format_feature(index: FeatIndex) = mapper.feature_to_string(index) /** Display the label at the given index as a string. */ def format_label(index: FeatIndex) = mapper.label_to_string(index) def pretty_format(prefix: String): String def pretty_print_labeled(prefix: String, correct: LabelIndex) { errprint("$prefix: Label: %s(%s)", correct, mapper.label_to_string(correct)) errprint("$prefix: Featvec: %s", pretty_format(prefix)) } } object FeatureVector { /** Check that all feature vectors have the same mappers. */ def check_same_mappers(fvs: Iterable[FeatureVector]) { val mapper = fvs.head.mapper for (fv <- fvs) { assert_==(fv.mapper, mapper) } } } /** * A feature vector that ignores the class label. */ trait SimpleFeatureVector extends FeatureVector { /** Return the value at index `i`. */ def apply(i: FeatIndex): Double def apply(i: FeatIndex, label: LabelIndex) = apply(i) /** Return the squared magnitude of the difference between the values of * this feature vector for the two labels `label1` and `label2`. */ override def diff_squared_magnitude(label1: LabelIndex, label2: LabelIndex ) = 0 val depth = 1 val max_label = Int.MaxValue } object BasicFeatureVectorImpl { def diff_squared_magnitude_2(fv1: FeatureVector, label1: LabelIndex, fv2: FeatureVector, label2: LabelIndex) = { assert_==(fv1.length, fv2.length) (for (i <- 0 until fv1.length; va = fv1(i, label1) - fv2(i, label2)) yield va*va).sum } } /** * The most basic implementation of the feature vector operations, which * should always work (although not necessarily efficiently). */ trait BasicFeatureVectorImpl extends FeatureVector { def dot_product(weights: SimpleVector, label: LabelIndex) = (for (i <- 0 until length) yield apply(i, label)*weights(i)).sum def squared_magnitude(label: LabelIndex) = (for (i <- 0 until length; va = apply(i, label)) yield va*va).sum def diff_squared_magnitude(label1: LabelIndex, label2: LabelIndex) = (for (i <- 0 until length; va = apply(i, label1) - apply(i, label2)) yield va*va).sum def diff_squared_magnitude_2(label1: LabelIndex, other: FeatureVector, label2: LabelIndex) = BasicFeatureVectorImpl.diff_squared_magnitude_2(this, label1, other, label2) def update_weights(weights: SimpleVector, scale: Double, label: LabelIndex) { (0 until length).foreach { i => weights(i) += scale*apply(i, label) } } } /** * A vector of real-valued features, stored explicitly. If you want a "bias" * or "intercept" weight, you need to add it yourself. */ case class ArrayFeatureVector( values: SimpleVector, mapper: FeatureLabelMapper ) extends BasicFeatureVectorImpl with SimpleFeatureVector { assert_==(values.length, length) def stored_entries = length /** Return the value at index `i`. */ final def apply(i: FeatIndex) = values(i) final def update(i: FeatIndex, value: Double) { values(i) = value } def pretty_format(prefix: String) = " %s: %s" format (prefix, values) } trait SparseFeatureVector extends SimpleFeatureVector { def include_displayed_feature: Boolean = true def compute_toString(prefix: String, feature_values: Iterable[(FeatIndex, Double)]) = "%s(%s)" format (prefix, feature_values.toSeq.sorted.map { case (index, value) => { if (include_displayed_feature) "%s(%s)=%.2f" format (format_feature(index), index, value) else "%s=%.2f" format (index, value) } }.mkString(",") ) def pretty_feature_string(prefix: String, feature_values: Iterable[(FeatIndex, Double)]) = feature_values.toSeq.sorted.map { case (index, value) => { val featstr = if (include_displayed_feature) "%s(%s)" format (format_feature(index), index) else "%s" format index " %s: %-40s = %.2f" format (prefix, featstr, value) } }.mkString("\\n") def toIterable: Iterable[(FeatIndex, Double)] def string_prefix: String override def toString = compute_toString(string_prefix, toIterable) def pretty_format(prefix: String) = { "%s: %s".format(prefix, string_prefix) + "\\n" + pretty_feature_string(prefix, toIterable) } // Simple implementation of this to optimize in the common case // where the other vector is sparse. def diff_squared_magnitude_2(label1: LabelIndex, other: FeatureVector, label2: LabelIndex) = { other match { // When the other vector is sparse, we need to handle: first, all // the indices defined in this vector, and second, all the // indices defined in the other vector but not in this one. // We don't currently have an "is-defined-in" predicate, but we // effectively have "is-defined-and-non-zero" by just checking // the return value; so we deal with the possibility of indices // defined in this vector with a zero value by skipping them. // If the other vector has a value at that index, it will be // handled when we loop over the other vector. (Otherwise, the // index is 0 in both vectors and contributes nothing.) case sp2: SparseFeatureVector => { var res = 0.0 for ((ind, value) <- toIterable) { if (value != 0.0) { val va = value - sp2(ind) res += va * va } } for ((ind, value) <- sp2.toIterable) { if (this(ind) == 0.0) { res += value * value } } res } case _ => BasicFeatureVectorImpl.diff_squared_magnitude_2( this, label1, other, label2) } } } // abstract class CompressedSparseFeatureVector private[learning] ( // keys: Array[FeatIndex], values: Array[Double] // ) extends SparseFeatureVector { // (in FeatureVector.scala.template) // } // class BasicCompressedSparseFeatureVector private[learning] ( // keys: Array[FeatIndex], values: Array[Double], val length: Int // ) extends CompressedSparseFeatureVector(keys, values) { // (in FeatureVector.scala.template) // } /** * A feature vector in which the features are stored sparsely, i.e. only * the features with non-zero values are stored, using a hash table or * similar. The features are indexed by integers. (Features indexed by * other types, e.g. strings, should use a memoizer to convert to integers.) */ abstract class SimpleSparseFeatureVector( feature_values: Iterable[(FeatIndex, Double)] ) extends SparseFeatureVector { def stored_entries = feature_values.size def squared_magnitude(label: LabelIndex) = feature_values.map { case (index, value) => value * value }.sum def dot_product(weights: SimpleVector, label: LabelIndex) = feature_values.map { case (index, value) => value * weights(index) }.sum def update_weights(weights: SimpleVector, scale: Double, label: LabelIndex) { feature_values.map { case (index, value) => weights(index) += scale * value } } def toIterable = feature_values } /** * An implementation of a sparse feature vector storing the non-zero * features in a `Map`. */ class MapSparseFeatureVector( feature_values: collection.Map[FeatIndex, Double], val mapper: FeatureLabelMapper ) extends SimpleSparseFeatureVector(feature_values) { def apply(index: FeatIndex) = feature_values.getOrElse(index, 0.0) def string_prefix = "MapSparseFeatureVector" } class TupleArraySparseFeatureVector( feature_values: mutable.Buffer[(FeatIndex, Double)], val mapper: FeatureLabelMapper ) extends SimpleSparseFeatureVector(feature_values) { // Use an O(n) algorithm to look up a value at a given index. Luckily, // this operation isn't performed very often (if at all). We could // speed it up by storing the items sorted and use binary search. def apply(index: FeatIndex) = feature_values.find(_._1 == index) match { case Some((index, value)) => value case None => 0.0 } def string_prefix = "TupleArraySparseFeatureVector" } /** * An aggregate feature vector that stores a separate individual feature * vector for each of a set of labels. */ case class AggregateFeatureVector( fv: Array[FeatureVector] ) extends FeatureVector { FeatureVector.check_same_mappers(fv) def mapper = fv.head.mapper def depth = fv.length def max_label = depth - 1 def stored_entries = fv.map(_.stored_entries).sum def apply(i: FeatIndex, label: LabelIndex) = fv(label)(i, label) /** Return the squared magnitude of the feature vector for class `label`, * i.e. dot product of feature vector with itself */ def squared_magnitude(label: LabelIndex) = fv(label).squared_magnitude(label) /** Return the squared magnitude of the difference between the values of * this feature vector for the two labels `label1` and `label2`. */ def diff_squared_magnitude(label1: LabelIndex, label2: LabelIndex) = fv(label1).diff_squared_magnitude_2(label1, fv(label2), label2) /** Return the squared magnitude of the difference between the values of * this feature vector for the two labels `label1` and `label2`. */ def diff_squared_magnitude_2(label1: LabelIndex, other: FeatureVector, label2: LabelIndex) = { val fv2 = other match { case afv2: AggregateFeatureVector => afv2.fv(label2) case _ => other } fv(label1).diff_squared_magnitude_2(label1, fv2, label2) } def dot_product(weights: SimpleVector, label: LabelIndex) = fv(label).dot_product(weights, label) def update_weights(weights: SimpleVector, scale: Double, label: LabelIndex) = fv(label).update_weights(weights, scale, label) /** Display the feature at the given index as a string. */ override def format_feature(index: FeatIndex) = fv.head.format_feature(index) def pretty_format(prefix: String) = { (for (d <- 0 until depth) yield "Featvec at depth %s(%s): %s" format ( d, mapper.label_to_string(d), fv(d).pretty_format(prefix))).mkString("\\n") } /** * Return the component feature vectors as a lazy sequence of compressed * sparse feature vectors, by casting each item. Will throw an error if * the feature vectors are of the wrong type. */ def fetch_sparse_featvecs = { // Retrieve as the appropriate type of compressed sparse feature vectors. // This will be one of DoubleCompressedSparseFeatureVector, // FloatCompressedSparseFeatureVector, etc. fv.view map { x => x match { case y:CompressedSparseFeatureVectorType => y case _ => ??? } } } /** * Return the set of all features found in the aggregate. */ def find_all_features = { fetch_sparse_featvecs.foldLeft(Set[FeatIndex]()) { _ union _.keys.toSet } } /** * Find the features that do not have the same value for every component * feature vector. Return a set of such features. */ def find_diff_features = { // OK, we do this in a purely iterative fashion to create as little // garbage as possible, because we may be working with very large // arrays. The basic idea, since there may be different features in // different sparse feature vectors, is that we keep track of the // number of times each feature has been seen and the max and min // value of the feature. Then, a feature is the same across all // feature vectors if either: // // 1. It hasn't been seen at all (its count is 0); or, // 2. Its maxval and minval are the same and either // a. both are 0, or // b. both are non-zero and the feature was seen in every vector. // // We return a set of the features that aren't the same, because // all unseen features by definition are the same across all // feature vectors. Then, to compute the total set of features that // aren't the same, we take the union of the individual results -- // something we can do incrementally to save memory. val stats = new FeatureStats stats.accumulate(this, do_minmax = true) ( for ((k, count) <- stats.count; same = stats.min(k) == stats.max(k) && (stats.min(k) == 0 || count == depth); if !same) yield k ).toSet } /** * Destructively remove columns that are non-choice-specific, i.e. * not listed among the list of choice-specific features passed in. */ def remove_non_choice_specific_columns(diff_features: Set[FeatIndex]) { for (vec <- fetch_sparse_featvecs) { val need_to_remove = vec.keys.exists(!diff_features.contains(_)) if (need_to_remove) { val feats = (vec.keys zip vec.values).filter(diff_features contains _._1) vec.keys = feats.map(_._1).toArray vec.values = feats.view.map(_._2).map(to_feat_value(_)).toArray } } } /** * Destructively rescale the appropriate features in the given * feature vectors by subtracting their mean and then dividing by their * standard deviation. This only operates on features that have been * marked as needing standardization. Standardization is done to make it * easier to compare numeric feature values across different query * documents, which otherwise may differ greatly in scale. (This is the * case for KL-divergence scores, for example.) Whether standardization * is done depends on the type of the feature's value. For example, * binary features definitely don't need to be rescaled and * probabilities aren't currently rescaled, either. Features of only * a candidate also don't need to be rescaled as they don't suffer * from the problem of being compared with different query documents.) */ def rescale_featvecs() { val sparsevecs = fetch_sparse_featvecs // Get the sum and count of all features seen in any of the keys. // Here and below, when computing mean, std dev, etc., we ignore // unseen features rather than counting them as 0's. This wouldn't // work well for binary features, where we normally only store the // features with a value of 1, but we don't adjust those features // in any case. For other features, we assume that features that // are meant to be present and happen to have a value of 0 will be // noted as such. This means that we calculate mean and stddev // only for features that are present, and likewise rescale // only features that are present. Otherwise, we'd end up converting // all the absent features to present features with some non-zero // value, which seems non-sensical besides making the coding more // difficult as we currently can't expand a sparse feature vector, // only change the value of an existing feature. val stats = new FeatureStats stats.accumulate(this, do_sum = true) // Compute the mean of all seen instances of a feature. // Unseen features are ignored rather than counted as 0's. val meanmap = stats.sum map { case (key, sum) => (key, sum / stats.count(key)) } // Compute the sum of squared differences from the mean of all seen // instances of a feature. // Unseen features are ignored rather than counted as 0's. val sumsqmap = doublemap[FeatIndex]() for (vec <- sparsevecs; i <- 0 until vec.keys.size) { val k = vec.keys(i) val v = vec.values(i) val mean = meanmap(k) sumsqmap(k) += (v - mean) * (v - mean) } // Compute the standard deviation of all features. // Unseen features are ignored rather than counted as 0's. val stddevmap = sumsqmap map { case (key, sumsq) => (key, math.sqrt(sumsq / stats.count(key))) } // Now rescale the features that need to be. for (vec <- sparsevecs; i <- 0 until vec.keys.size) { val key = vec.keys(i) if (mapper.features_to_rescale contains key) { val stddev = stddevmap(key) // Must skip 0, NaN and infinity! Comparison between anything and // NaN will be false and won't pass the > 0 check. if (stddev > 0 && !stddev.isInfinite) { vec.values(i) = /* to_feat_value((vec.values(i) - meanmap(key))/stddev) // FIXME! We add 1 here somewhat arbitrarily because TADM ignores // features that have a mean of 0 (don't know why). to_feat_value((vec.values(i) - meanmap(key))/stddev + 1) */ // FIXME: Try just dividing by the standard deviation so the // spread is at least scaled correctly. This also ensures that // 0 values would remain as 0 so no problems arise due to // ignoring them. An alternative that might work for KL-divergence // and similar scores is to shift so that the minimum gets a value // of 0, as well as scaling by the stddev. // FIXME! In the case of the initial ranking, it's also rescaled // and adjusted in `evaluate_with_initial_ranking`. to_feat_value(vec.values(i)/stddev) } } } } } object AggregateFeatureVector { def check_aggregate(di: DataInstance) = { val fv = di.feature_vector fv match { case agg: AggregateFeatureVector => agg case _ => internal_error("Only operates with AggregateFeatureVectors") } } /** * Destructively remove all features that have the same values among all * components of each aggregate feature vector (even if they have different * values among different aggregate feature vectors). Features that don't * differ at all within any aggregate feature vector aren't useful for * distinguishing one candidate from another and may cause singularity * errors in R's mlogit() function, so need to be deleted. * * Return the set of removed features. */ def remove_all_non_choice_specific_columns( featvecs: Iterable[(DataInstance, LabelIndex)] ) = { val agg_featvecs = featvecs.view.map { x => check_aggregate(x._1) } // Find the set of all features that have different values in at least // one pair of component feature vectors in at least one aggregate // feature vector. val diff_features = agg_featvecs.map(_.find_diff_features).reduce(_ union _) val all_features = agg_featvecs.map(_.find_all_features).reduce(_ union _) val removed_features = all_features diff diff_features val headfv = featvecs.head._1.feature_vector errprint("Removing non-choice-specific features: %s", removed_features.toSeq.sorted.map(headfv.format_feature(_)) mkString " ") agg_featvecs.foreach(_.remove_non_choice_specific_columns(diff_features)) removed_features } } /** Compute statistics over features, e.g. how many times they occur, * what their sum and absolute sum is, what their min and max values are. * The accumulate() function counts each combination of doc+cell separately. */ class FeatureStats { // Count of features val count = intmap[FeatIndex]() // Count of feature vectors var num_fv = 0 // Min value of features val min = doublemap[FeatIndex]() // Max value of features val max = doublemap[FeatIndex]() // Sum of features val sum = doublemap[FeatIndex]() // Sum of absolute value of features val abssum = doublemap[FeatIndex]() /** * Accumulate statistics on features. */ def accumulate(agg: AggregateFeatureVector, do_minmax: Boolean = false, do_sum: Boolean = false, do_abssum: Boolean = false) { num_fv += agg.depth // We do this in a purely iterative fashion to create as little // garbage as possible, because we may be working with very large // arrays. See find_diff_features. for (vec <- agg.fetch_sparse_featvecs; i <- 0 until vec.keys.size) { val k = vec.keys(i) val v = vec.values(i) count(k) += 1 if (do_minmax) { if (!(min contains k) || v < min(k)) min(k) = v if (!(max contains k) || v > max(k)) max(k) = v } if (do_sum) sum(k) += v if (do_abssum) abssum(k) += v.abs } } /** * Accumulate statistics on features, at the document level rather than * the doc+cell level. */ def accumulate_doc_level(agg: AggregateFeatureVector, do_minmax: Boolean = false, do_sum: Boolean = false, do_abssum: Boolean = false) { num_fv += 1 // We do this in a purely iterative fashion to create as little // garbage as possible; see accumuate(). // // HACK! We assume that the features aren't really label-specific, // that the difference in label-specificness is only due to the necessity // of attaching labels to features for TADM. So we just look at the // first one. val vec = agg.fetch_sparse_featvecs.head for (i <- 0 until vec.keys.size) { val fk = vec.keys(i) val (k, _) = vec.mapper.feature_property_label_index(fk) val v = vec.values(i) count(k) += 1 if (do_minmax) { if (!(min contains k) || v < min(k)) min(k) = v if (!(max contains k) || v > max(k)) max(k) = v } if (do_sum) sum(k) += v if (do_abssum) abssum(k) += v.abs } } } /** * For each aggregate, we compute the fraction of times a given feature * in the correct label's feature vector is greater than, less than or * equal to the value in the other feature vectors in the aggregate, and * average over all aggregates. These three fraction will add up to 1 * for a given aggregate, and the averages will likewise add up to 1. * Note that for any feature seen anywhere in the aggregate we process * all feature vectors in the aggregate, treating unseen features as 0. * However, for features seen nowhere in the aggregate, they won't be * recorded, and hence we need to treat them as cases of all 100% * "equal to". In practice, because the averages add up to 1, we don't * need to keep track of the "equal to" fractions separately but instead * compute them from the other two; the sums of those two fractions * won't be affected by cases where a feature isn't seen in an aggregate. * * FIXME: Should we instead do this comparing the correct label to the * second-best rather than all the others? */ class FeatureDiscriminationStats { // Count of number of aggregates seen var num_agg = 0 // Sum of fractions of fv's other than the correct one where the // feature's value in the correct one is less than the value in the // others. See above. val less_than_other = doublemap[FeatIndex]() // Same for "greater than". val greater_than_other = doublemap[FeatIndex]() /** * Find the features that have different values from one component * feature vector to another. Return a set of such features. */ def accumulate(agg: AggregateFeatureVector, corrlab: LabelIndex) { num_agg += 1 for (feat <- agg.find_all_features) { val corrval = agg(feat, corrlab) var num_lto = 0 var num_gto = 0 for (lab <- 0 until agg.depth; if lab != corrlab) { val othval = agg(feat, lab) if (corrval < othval) num_lto += 1 else if (corrval > othval) num_gto += 1 } less_than_other(feat) += num_lto.toDouble / (agg.depth - 1) greater_than_other(feat) += num_gto.toDouble / (agg.depth - 1) } } }
utcompling/textgrounder
src/main/scala/opennlp/textgrounder/learning/FeatureVector.scala
Scala
apache-2.0
35,858
package skinny.orm.feature import scalikejdbc._ import skinny.orm.exception.OptimisticLockException import org.joda.time.DateTime import org.slf4j.LoggerFactory /** * Optimistic lock with timestamp. * * @tparam Entity entity */ trait OptimisticLockWithTimestampFeature[Entity] extends OptimisticLockWithTimestampFeatureWithId[Long, Entity] trait OptimisticLockWithTimestampFeatureWithId[Id, Entity] extends CRUDFeatureWithId[Id, Entity] { /** * Lock timestamp field name. */ def lockTimestampFieldName = "lockTimestamp" /** * Returns where condition part which search by primary key and lock timestamp. * * @param id primary key * @param timestamp lock timestamp * @return query part */ protected def byIdAndTimestamp(id: Long, timestamp: Option[DateTime]): SQLSyntax = timestamp .map { t => sqls.eq(column.field(primaryKeyFieldName), id).and.eq(column.field(lockTimestampFieldName), t) } .getOrElse { sqls.eq(column.field(primaryKeyFieldName), id).and.isNull(column.field(lockTimestampFieldName)) } /** * Returns update query builder which updates a single entity by primary key and lock timestamp. * * @param id primary key * @param timestamp lock timestamp * @return updated count */ def updateByIdAndTimestamp(id: Long, timestamp: Option[DateTime]): UpdateOperationBuilder = { updateBy(byIdAndTimestamp(id, timestamp)) } /** * Returns update query builder which updates a single entity by primary key and lock timestamp. * * @param id primary key * @param timestamp lock timestamp * @return updated count */ def updateByIdAndTimestamp(id: Long, timestamp: DateTime): UpdateOperationBuilder = { updateBy(byIdAndTimestamp(id, Option(timestamp))) } private[this] def updateByHandler(session: DBSession, where: SQLSyntax, namedValues: Seq[(SQLSyntax, Any)], count: Int): Unit = { if (count == 0) { throw new OptimisticLockException( s"Conflict ${lockTimestampFieldName} is detected (condition: '${where.value}', ${where.parameters.mkString(",")}})" ) } } afterUpdateBy(updateByHandler _) override def updateBy(where: SQLSyntax): UpdateOperationBuilder = new UpdateOperationBuilderWithVersion(this, where) /** * Update query builder/executor. * * @param mapper mapper * @param where condition */ class UpdateOperationBuilderWithVersion(mapper: CRUDFeatureWithId[Id, Entity], where: SQLSyntax) extends UpdateOperationBuilder(mapper = mapper, where = where, beforeHandlers = beforeUpdateByHandlers.toIndexedSeq, afterHandlers = afterUpdateByHandlers.toIndexedSeq) { // appends additional part of update query private[this] val c = defaultAlias.support.column.field(lockTimestampFieldName) addUpdateSQLPart(sqls"${c} = ${sqls.currentTimestamp}") } /** * Deletes a single entity by primary key and lock timestamp. * * @param id primary key * @param timestamp lock timestamp * @param s db session * @return deleted count */ def deleteByIdAndOptionalTimestamp(id: Long, timestamp: Option[DateTime])(implicit s: DBSession = autoSession): Int = { deleteBy(byIdAndTimestamp(id, timestamp)) } /** * Deletes a single entity by primary key and lock timestamp. * * @param id primary key * @param timestamp lock timestamp * @param s db session * @return deleted count */ def deleteByIdAndTimestamp(id: Long, timestamp: DateTime)(implicit s: DBSession = autoSession): Int = { deleteBy(byIdAndTimestamp(id, Option(timestamp))) } override def deleteBy(where: SQLSyntax)(implicit s: DBSession = autoSession): Int = { val count = super.deleteBy(where)(s) if (count == 0) { throw new OptimisticLockException( s"Conflict ${lockTimestampFieldName} is detected (condition: '${where.value}', ${where.parameters.mkString(",")}})" ) } else { count } } override def updateById(id: Id): UpdateOperationBuilder = { logger.info( "#updateById ignore optimistic lock. If you need to lock with version in this case, use #updateBy instead." ) super.updateBy(byId(id)) } override def deleteById(id: Id)(implicit s: DBSession = autoSession): Int = { logger.info( "#deleteById ignore optimistic lock. If you need to lock with version in this case, use #deleteBy instead." ) super.deleteBy(byId(id)) } }
seratch/skinny-framework
orm/src/main/scala/skinny/orm/feature/OptimisticLockWithTimestampFeature.scala
Scala
mit
4,744
/* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.hmrc.ct.accounts.frs102.boxes import uk.gov.hmrc.ct.accounts.frs102.retriever.Frs102AccountsBoxRetriever import uk.gov.hmrc.ct.box._ case class AC161(value: Option[Int]) extends CtBoxIdentifier(name = "Creditors after one year - Other creditors (PY)") with CtOptionalInteger with Input with ValidatableBox[Frs102AccountsBoxRetriever] with Validators { override def validate(boxRetriever: Frs102AccountsBoxRetriever): Set[CtValidation] = { collectErrors( validateMoney(value, min = 0) ) } }
hmrc/ct-calculations
src/main/scala/uk/gov/hmrc/ct/accounts/frs102/boxes/AC161.scala
Scala
apache-2.0
1,139
package org.pico.disposal object Noop extends (() => Unit) { override def apply(): Unit = () }
pico-works/pico-disposal
pico-disposal/src/main/scala/org/pico/disposal/Noop.scala
Scala
bsd-3-clause
98
/** * Copyright (C) 2016-2017 Lightbend Inc. <http://www.lightbend.com> */ package akka /** * Typically used together with `Future` to signal completion * but there is no actual value completed. More clearly signals intent * than `Unit` and is available both from Scala and Java (which `Unit` is not). */ sealed abstract class Done case object Done extends Done { /** * Java API: the singleton instance */ def getInstance(): Done = this }
rorygraves/perf_tester
corpus/akka/akka-actor/src/main/scala/akka/Done.scala
Scala
apache-2.0
457
package ozmi.lambda_core.sql import org.kiama.util.ParserUtilities /** * Created by attila on 4/20/2015. */ object SqlParser extends ParserUtilities { def keyword = keywords ("""[^a-zA-Z0-9_]""".r, List ("SELECT")) def literal : PackratParser[Literal] = decimalLit | integerLit | stringLit def integerLit : PackratParser[Literal] = """\\d+""".r ^^ { case string => IntegerLit (BigInt (string)) } def decimalLit : PackratParser[Literal] = """\\d+\\.\\d+""".r ^^ { case string => DecimalLit (BigDecimal (string)) } def stringLit : PackratParser[Literal] = """\\'([^\\'])*\\'""".r ^^ { case string => StringLit (string.substring(1, string.length - 1)) } def ident : PackratParser[String] = not (keyword) ~> """\\w+""".r def columnRef : PackratParser[ColumnRef] = opt (ident <~ ".") ~ ident ^^ { case objectName ~ columnName => ColumnRef (objectName, columnName) } def parensColumnExpr : PackratParser[ColumnExpr] = "(" ~> columnExpr <~ ")" def unaryMinus : PackratParser[ColumnExpr] = "-" ~> term ^^ { UnaryOp("-", _) } def term = literal | columnRef | parensColumnExpr | unaryMinus def binaryOp (level:Int) : PackratParser[((ColumnExpr, ColumnExpr) => ColumnExpr)] = { level match { case 1 => "+" ^^^ { (a:ColumnExpr, b:ColumnExpr) => BinaryOp("+", a,b) } | "-" ^^^ { (a:ColumnExpr, b:ColumnExpr) => BinaryOp("-", a,b) } case 2 => "*" ^^^ { (a:ColumnExpr, b:ColumnExpr) => BinaryOp("*", a,b) } | "/" ^^^ { (a:ColumnExpr, b:ColumnExpr) => BinaryOp("/", a,b) } case _ => throw new RuntimeException("bad precedence level "+level) } } val minPrec = 1 val maxPrec = 2 def binary (level : Int) : PackratParser[ColumnExpr] = if (level > maxPrec) term else binary (level+1) * binaryOp (level) def columnExpr = binary (minPrec) | term def parseColumnExpr (input : String) : Either[SqlExpr, String] = { parseString (columnExpr, input) } def objectRef : PackratParser[ObjectRef] = opt (ident <~ ".") ~ ident ^^ { case schemaName ~ objectName => ObjectRef (schemaName, objectName) } def singleColumnSelector : PackratParser[SingleColumnSelector] = columnExpr ~ opt (opt ("AS") ~> ident) ^^ { case columnExpr ~ alias => SingleColumnSelector (columnExpr, alias) } def allColumnsSelector : PackratParser[AllColumnsSelector] = opt (ident <~ ".") <~ "*" ^^ { case objectName => AllColumnsSelector (objectName) } def selector = singleColumnSelector | allColumnsSelector def select : PackratParser[Select] = "SELECT" ~> rep1sep (selector, ",") ~ ("FROM" ~> relation) ^^ { case selectors ~ baseRel => Select (baseRel, selectors) } def relation : PackratParser[Relation] = objectRef def parseRelationExpr (input : String) : Either[SqlExpr, String] = { parseString (select, input) } }
ozmi/lambda_core
src/main/scala/ozmi/lambda_core/sql/SqlParser.scala
Scala
mit
3,180
package org.romeo.loveletter.cli.Main import org.romeo.loveletter.game.GameManager import org.romeo.loveletter.persistence.MemoryDataStore import scala.io.StdIn import scala.util.Random /** * Created by tylerromeo on 1/13/17. */ object Main extends App { val gameId = "cli" val gameManager = new GameManager(new MemoryDataStore(), new Random()) var gameStarted: Boolean = false stdin foreach { command => processCommand(command) if (gameStarted) { val gameInfo = gameManager.getGameInfo(gameId) val currentPlayer = gameManager.getCurrentPlayerName(gameId) val playersHand = gameManager.getHandInfo(gameId, currentPlayer) println(gameInfo) println(s"Your hand:\\n$playersHand") } } def stdin: Stream[String] = StdIn.readLine("----------\\nEnter Command:") match { case s if s == null => Stream.empty case s => s #:: stdin } def processCommand(s: String): Unit = { val split = s.split("""\\s+""") split.toList match { case command :: cardName :: args if command == "play" || command == "discard" => { val target = args.headOption val guess = if (args.size >= 2) Some(args(1)) else None playCard(card = cardName, target = target, guess = guess) } case command :: args if command == "start" => startGame(players = args) case command :: _ if command == "quit" => sys.exit(0) case command :: _ if command == "help" => printHelp() case _ => printHelp() } } def printHelp(): Unit = { val help = """ |Rules are online at: http://www.alderac.com/tempest/files/2012/09/Love_Letter_Rules_Final.pdf |`help` to get this help |`start [player names]` to start a new game |`quit` to end the game |`play [card name] [?target] [?guess]` to play a card. (play can be omitted) |`discard` is equivalent to `play` |Source for bot at: https://github.com/tylerjromeo/love-letter-slack-commands """.stripMargin println(help) } def startGame(players: List[String]): Unit = { gameManager.startGame(gameId, players) match { case Left(m) => println(s"Could not start game: $m") case Right(game) => { gameStarted = true println(s"Game started") } } } def playCard(card: String, target: Option[String], guess: Option[String]): Unit = { gameManager.takeTurn(gameId, gameManager.getCurrentPlayerName(gameId), card, target, guess) match { case Left(m) => println(s"Error: ${m.msg}") case Right(m) => println(m.map(_.msg).mkString("\\n")) } } }
tylerjromeo/love-letter-slack-commands
src/main/scala-2.11/org/romeo/loveletter/cli/Main/Main.scala
Scala
mit
2,628
package com.sunway.screen.gamescreen import com.github.dunnololda.scage.support.Vec /** * Created by Mr_RexZ on 12/6/2016. */ trait MoveableObject { protected var speed = 5.0f protected var rotation = 0.0f def step = Vec(-0.4f * speed * math.sin(math.toRadians(rotation)).toFloat, 0.4f * speed * math.cos(math.toRadians(rotation)).toFloat) }
MrRexZ/DistributedSystemAssignment2
src/main/scala/com/sunway/screen/gamescreen/MoveableObject.scala
Scala
mit
358
package com.sksamuel.elastic4s import org.slf4j.{Logger, LoggerFactory} import scala.concurrent.duration.{Duration, _} import scala.language.higherKinds /** * An [[ElasticClient]] is used to execute HTTP requests against an ElasticSearch cluster. * This class delegates the actual HTTP calls to an instance of [[HttpClient]]. * * Any third party HTTP client library can be made to work with elastic4s by creating an * instance of the HttpClient typeclass wrapping the underlying client library and * then creating the ElasticClient with it. * * @param client the HTTP client library to use **/ case class ElasticClient(client: HttpClient) extends AutoCloseable { protected val logger: Logger = LoggerFactory.getLogger(getClass.getName) /** * Returns a String containing the request details. * The string will have the HTTP method, endpoint, params and if applicable the request body. */ def show[T](t: T)(implicit handler: Handler[T, _]): String = Show[ElasticRequest].show(handler.build(t)) // Executes the given request type T, and returns an effect of Response[U] // where U is particular to the request type. // For example a search request will return a Response[SearchResponse]. def execute[T, U, F[_]](t: T)(implicit executor: Executor[F], functor: Functor[F], handler: Handler[T, U], manifest: Manifest[U], options: CommonRequestOptions): F[Response[U]] = { val request = handler.build(t) val request2 = if (options.timeout.toMillis > 0) { request.addParameter("timeout", options.timeout.toMillis + "ms") } else { request } val request3 = if (options.masterNodeTimeout.toMillis > 0) { request2.addParameter("master_timeout", options.masterNodeTimeout.toMillis + "ms") } else { request2 } val f = executor.exec(client, request3) functor.map(f) { resp => handler.responseHandler.handle(resp) match { case Right(u) => RequestSuccess(resp.statusCode, resp.entity.map(_.content), resp.headers, u) case Left(error) => RequestFailure(resp.statusCode, resp.entity.map(_.content), resp.headers, error) } } } def close(): Unit = client.close() } case class CommonRequestOptions(timeout: Duration, masterNodeTimeout: Duration) object CommonRequestOptions { implicit val defaults: CommonRequestOptions = CommonRequestOptions(0.seconds, 0.seconds) }
sksamuel/elastic4s
elastic4s-core/src/main/scala/com/sksamuel/elastic4s/ElasticClient.scala
Scala
apache-2.0
2,560
/* * Copyright (c) 2017 Magomed Abdurakhmanov, Hypertino * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ package com.hypertino.facade.filters.annotated import com.hypertino.binders.annotations.fieldName import com.hypertino.binders.value.Value import com.hypertino.facade.filter.model._ import com.hypertino.facade.filter.parser.{ExpressionEvaluator, PreparedExpression} import com.hypertino.facade.raml.RamlFieldAnnotation import monix.eval.Task case class SetFieldAnnotation( @fieldName("if") predicate: Option[PreparedExpression], source: PreparedExpression, stages: Set[FieldFilterStage] = Set(FieldFilterStageRequest) ) extends RamlFieldAnnotation { def name: String = "set" } class SetFieldFilter(annotation: SetFieldAnnotation, expressionEvaluator: ExpressionEvaluator) extends FieldFilter { def apply(context: FieldFilterContext): Task[Option[Value]] = Task.now { Some(expressionEvaluator.evaluate(context.expressionEvaluatorContext, annotation.source)) } } class SetFieldFilterFactory(protected val predicateEvaluator: ExpressionEvaluator) extends RamlFieldFilterFactory { def createFieldFilter(fieldName: String, typeName: String, annotation: RamlFieldAnnotation): FieldFilter = { new SetFieldFilter(annotation.asInstanceOf[SetFieldAnnotation], predicateEvaluator) } override def createRamlAnnotation(name: String, value: Value): RamlFieldAnnotation = { value.to[SetFieldAnnotation] } }
hypertino/hyperfacade
src/main/scala/com/hypertino/facade/filters/annotated/SetFieldRequestFilter.scala
Scala
mpl-2.0
1,714
/* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.hmrc.play.audit.model import uk.gov.hmrc.play.audit.http.connector.AuditConnector import uk.gov.hmrc.http.HeaderCarrier import scala.concurrent.Future import scala.util.Try import scala.language.implicitConversions sealed trait AuditAsMagnet[A] { import uk.gov.hmrc.play.audit.model.Audit.OutputTransformer val txName: String val inputs: Map[String, String] val outputTransformer: OutputTransformer[A] val eventTypes: (String, String) def apply(f: (String, Map[String, String], OutputTransformer[A], (String, String)) => A): A = f(txName, inputs, outputTransformer, eventTypes) } object AuditAsMagnet { import uk.gov.hmrc.play.audit.model.Audit.{EventTypeFlowDescriptions, OutputTransformer, defaultEventTypes} implicit def inputAsStringDefaultEventTypes[A](parms: (String, String, OutputTransformer[A])): AuditAsMagnet[A] = auditAsMagnet(parms._1, Map("" -> parms._2), defaultEventTypes, parms._3) implicit def inputAsString[A](parms: (String, String, EventTypeFlowDescriptions, OutputTransformer[A])): AuditAsMagnet[A] = auditAsMagnet(parms._1, Map("" -> parms._2), parms._3, parms._4) implicit def inputAsMapDefaultEventTypes[A](parms: (String, Map[String, String], OutputTransformer[A])): AuditAsMagnet[A] = auditAsMagnet(parms._1, parms._2, defaultEventTypes, parms._3) implicit def inputAsMap[A](parms: (String, Map[String, String], EventTypeFlowDescriptions, OutputTransformer[A])): AuditAsMagnet[A] = auditAsMagnet(parms._1, parms._2, parms._3, parms._4) private def auditAsMagnet[A]( txN: String, ins: Map[String, String], et: EventTypeFlowDescriptions, ot: OutputTransformer[A]) = new AuditAsMagnet[A] { val txName = txN val inputs = ins val outputTransformer = ot val eventTypes = et } } object EventTypes { val Succeeded = "TxSucceeded" val Failed = "TxFailed" } object Audit { import EventTypes._ type OutputTransformer[A] = (A => TransactionResult) type Body[A] = () => A type AsyncBody[A] = () => Future[A] type EventTypeFlowDescriptions = (String, String) val defaultEventTypes: EventTypeFlowDescriptions = (Succeeded, Failed) def apply(applicationName: String, auditConnector: AuditConnector) = new Audit(applicationName, auditConnector) } trait AuditTags { val xRequestId = "X-Request-ID" val TransactionName = "transactionName" } class Audit(applicationName: String, auditConnector: AuditConnector) extends AuditTags { import Audit._ import scala.concurrent.ExecutionContext.Implicits.global def sendDataEvent: (DataEvent) => Unit = auditConnector.sendEvent(_) def sendMergedDataEvent: (MergedDataEvent) => Unit = auditConnector.sendMergedEvent(_) private def sendEvent[A](auditMagnet: AuditAsMagnet[A], eventType: String, outputs: Map[String, String])(implicit hc: HeaderCarrier): Unit = { val requestId = hc.requestId.map(_.value).getOrElse("") sendDataEvent(DataEvent( auditSource = applicationName, auditType = eventType, tags = Map(xRequestId -> requestId, TransactionName -> auditMagnet.txName), detail = auditMagnet.inputs.map(inputKeys) ++ outputs)) } private def givenResultSendAuditEvent[A](auditMagnet: AuditAsMagnet[A])(implicit hc: HeaderCarrier): PartialFunction[TransactionResult, Unit] = { case TransactionSuccess(m) => sendEvent(auditMagnet, auditMagnet.eventTypes._1, m.map(outputKeys)) case TransactionFailure(r, m) => sendEvent(auditMagnet, auditMagnet.eventTypes._2, r.map(reason => Map("transactionFailureReason" -> reason)).getOrElse(Map.empty) ++ m.map(outputKeys)) } def asyncAs[A](auditMagnet: AuditAsMagnet[A])(body: AsyncBody[A])(implicit hc: HeaderCarrier): Future[A] = { // import MdcLoggingExecutionContext._ val invokedBody: Future[A] = try { body() } catch { case e: Exception => Future.failed[A](e) } invokedBody .map ( auditMagnet.outputTransformer ) .recover { case e: Exception => TransactionFailure(s"Exception Generated: ${e.getMessage}") } .map ( givenResultSendAuditEvent(auditMagnet) ) invokedBody } def as[A](auditMagnet: AuditAsMagnet[A])(body: Body[A])(implicit hc: HeaderCarrier): A = { val result: Try[A] = Try(body()) result .map ( auditMagnet.outputTransformer ) .recover { case e: Exception => TransactionFailure(s"Exception Generated: ${ e.getMessage }") } .map ( givenResultSendAuditEvent(auditMagnet) ) result.get } private val inputKeys = prependKeysWith("input") _ private val outputKeys = prependKeysWith("output") _ private def prependKeysWith(prefix: String)(entry: (String, String)) = entry match { case ("", value) => prefix -> value case (key, value) => s"$prefix-$key" -> value } } sealed trait TransactionResult { def outputs: Map[String, String] } case class TransactionFailure(reason: Option[String] = None, outputs: Map[String, String] = Map()) extends TransactionResult object TransactionFailure { def apply(reason: String, outputs: (String, String)*): TransactionFailure = TransactionFailure(Some(reason), Map(outputs: _*)) def apply(outputs: (String, String)*): TransactionFailure = TransactionFailure(outputs = Map(outputs: _*)) } case class TransactionSuccess(outputs: Map[String, String] = Map()) extends TransactionResult object TransactionSuccess { def apply(output: String): TransactionSuccess = TransactionSuccess(Map("" -> output)) def apply(outputs: (String, String)*): TransactionSuccess = TransactionSuccess(Map(outputs: _*)) }
hmrc/play-auditing
src-common/main/scala/uk/gov/hmrc/play/audit/model/Audit.scala
Scala
apache-2.0
6,176
/* * Copyright 2017 Datamountaineer. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datamountaineer.streamreactor.connect.coap.source import com.datamountaineer.streamreactor.connect.coap.configs.CoapSetting import com.datamountaineer.streamreactor.connect.coap.connection.CoapManager import com.datamountaineer.streamreactor.connect.coap.domain.CoapMessageConverter import com.typesafe.scalalogging.StrictLogging import org.apache.kafka.connect.source.SourceRecord import org.eclipse.californium.core.{CoapHandler, CoapObserveRelation, CoapResponse, WebLink} import java.util import java.util.concurrent.LinkedBlockingQueue /** * Created by [email protected] on 27/12/2016. * stream-reactor */ object CoapReaderFactory { def apply(settings: Set[CoapSetting], queue: LinkedBlockingQueue[SourceRecord]): Set[CoapReader] = { settings.map(s => CoapReader(s, queue)) } } case class CoapReader(setting: CoapSetting, queue: LinkedBlockingQueue[SourceRecord]) extends CoapManager(setting) { logger.info(s"Initialising COAP Reader for ${setting.kcql.getSource}") val handler = new MessageHandler(setting.kcql.getSource, setting.kcql.getTarget, queue) var observing = false var relation : Option[CoapObserveRelation] = None read //start observing def read(): Unit = { observing = true logger.info(s"Starting observation of resource ${setting.uri}/${setting.kcql.getSource} and writing to ${setting.kcql.getTarget}") relation = Some(client.observe(handler)) } def stop(): Unit = { relation.foreach(r => r.proactiveCancel()) client.delete(handler) client.shutdown() observing = false } def discover: util.Set[WebLink] = client.discover() } /** * A message handler class convert and add any responses * to a blocking queue * */ class MessageHandler(resource: String, topic: String, queue: LinkedBlockingQueue[SourceRecord]) extends CoapHandler with StrictLogging { val converter = CoapMessageConverter() override def onError(): Unit = { logger.warn(s"Message dropped for $topic!") } override def onLoad(response: CoapResponse): Unit = { val records = converter.convert(resource, topic, response.advanced()) logger.debug(s"Received ${response.advanced().toString} for $topic") logger.debug(s"Records in queue ${queue.size()} for $topic") queue.put(records) } }
datamountaineer/stream-reactor
kafka-connect-coap/src/main/scala/com/datamountaineer/streamreactor/connect/coap/source/CoapReaderFactory.scala
Scala
apache-2.0
2,894
package akka.persistence.jdbc.query import akka.persistence.query.{ EventEnvelope, NoOffset, Sequence } import akka.pattern._ import scala.concurrent.duration._ abstract class LogicalDeleteQueryTest(config: String) extends QueryTestSpec(config) { implicit val askTimeout = 500.millis it should "return logically deleted events when using CurrentEventsByTag (backward compatibility)" in withActorSystem { implicit system => val journalOps = new ScalaJdbcReadJournalOperations(system) withTestActors(replyToMessages = true) { (actor1, _, _) => (actor1 ? withTags(1, "number")).futureValue (actor1 ? withTags(2, "number")).futureValue (actor1 ? withTags(3, "number")).futureValue // delete and wait for confirmation (actor1 ? DeleteCmd(1)).futureValue journalOps.withCurrentEventsByTag()("number", NoOffset) { tp => tp.request(Int.MaxValue) tp.expectNextPF { case EventEnvelope(Sequence(1), _, _, _) => } tp.expectNextPF { case EventEnvelope(Sequence(2), _, _, _) => } tp.expectNextPF { case EventEnvelope(Sequence(3), _, _, _) => } tp.expectComplete() } } } it should "return logically deleted events when using EventsByTag (backward compatibility)" in withActorSystem { implicit system => val journalOps = new ScalaJdbcReadJournalOperations(system) withTestActors(replyToMessages = true) { (actor1, _, _) => (actor1 ? withTags(1, "number")).futureValue (actor1 ? withTags(2, "number")).futureValue (actor1 ? withTags(3, "number")).futureValue // delete and wait for confirmation (actor1 ? DeleteCmd(1)).futureValue shouldBe "deleted-1" journalOps.withEventsByTag()("number", NoOffset) { tp => tp.request(Int.MaxValue) tp.expectNextPF { case EventEnvelope(Sequence(1), _, _, _) => } tp.expectNextPF { case EventEnvelope(Sequence(2), _, _, _) => } tp.expectNextPF { case EventEnvelope(Sequence(3), _, _, _) => } tp.cancel() } } } it should "return logically deleted events when using CurrentEventsByPersistenceId (backward compatibility)" in withActorSystem { implicit system => val journalOps = new ScalaJdbcReadJournalOperations(system) withTestActors(replyToMessages = true) { (actor1, _, _) => (actor1 ? withTags(1, "number")).futureValue (actor1 ? withTags(2, "number")).futureValue (actor1 ? withTags(3, "number")).futureValue // delete and wait for confirmation (actor1 ? DeleteCmd(1)).futureValue shouldBe "deleted-1" journalOps.withCurrentEventsByPersistenceId()("my-1") { tp => tp.request(Int.MaxValue) tp.expectNextPF { case EventEnvelope(Sequence(1), _, _, _) => } tp.expectNextPF { case EventEnvelope(Sequence(2), _, _, _) => } tp.expectNextPF { case EventEnvelope(Sequence(3), _, _, _) => } tp.expectComplete() } } } it should "return logically deleted events when using EventsByPersistenceId (backward compatibility)" in withActorSystem { implicit system => val journalOps = new ScalaJdbcReadJournalOperations(system) withTestActors(replyToMessages = true) { (actor1, _, _) => (actor1 ? withTags(1, "number")).futureValue (actor1 ? withTags(2, "number")).futureValue (actor1 ? withTags(3, "number")).futureValue // delete and wait for confirmation (actor1 ? DeleteCmd(1)).futureValue shouldBe "deleted-1" journalOps.withEventsByPersistenceId()("my-1") { tp => tp.request(Int.MaxValue) tp.expectNextPF { case EventEnvelope(Sequence(1), _, _, _) => } tp.expectNextPF { case EventEnvelope(Sequence(2), _, _, _) => } tp.expectNextPF { case EventEnvelope(Sequence(3), _, _, _) => } tp.cancel() } } } } class PostgresLogicalDeleteQueryTest extends LogicalDeleteQueryTest("postgres-application.conf") with PostgresCleaner class MySQLLogicalDeleteQueryTest extends LogicalDeleteQueryTest("mysql-application.conf") with MysqlCleaner class OracleLogicalDeleteQueryTest extends LogicalDeleteQueryTest("oracle-application.conf") with OracleCleaner class SqlServerLogicalDeleteQueryTest extends LogicalDeleteQueryTest("sqlserver-application.conf") with SqlServerCleaner class H2LogicalDeleteQueryTest extends LogicalDeleteQueryTest("h2-application.conf") with H2Cleaner
gavares/akka-persistence-jdbc
src/test/scala/akka/persistence/jdbc/query/LogicalDeleteQueryTest.scala
Scala
apache-2.0
4,387
/* * Copyright 2018 Vladimir Konstantinov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.illfaku.korro.internal.common import akka.actor._ import io.netty.channel.Channel private[internal] class HttpActor(channel: Channel) extends Actor { override def receive = { case msg => channel.writeAndFlush(msg, channel.voidPromise) } }
oxy-development/korro
src/main/scala/com/github/illfaku/korro/internal/common/HttpActor.scala
Scala
apache-2.0
874
package controllers import entities.{AuthToken, UserId} import scala.util.{Success, Failure} import play.api.mvc.{Controller, RequestHeader} import scala.concurrent.Future import utils.Utils._ import scala.util.Success import scala.util.Failure import scala.Some import service.RedisService import play.api.libs.concurrent.Execution.Implicits._ import akka.event.slf4j.Logger import utils.Logging /** * Controller handling REST API interactions */ object API extends Controller with Logging { /** * as an authenticated user, follow the user with UID to_follow. Idempotent. */ def follow(to_follow: String) = AuthenticatedAPI.async { implicit request => { val user_id = request.user val r = for { _ <- RedisService.follow_user(user_id, UserId(to_follow)) } yield Accepted r.onComplete{ case Failure(t) => log.error(s"unfollow failed:\n$t") case Success(_) => } r } } /** * as an authenticated user, unfollow the user with UID to_unfollow. Idempotent. */ def unfollow(to_unfollow: String) = AuthenticatedAPI.async { implicit request => { val user_id = request.user val r = for { _ <- RedisService.unfollow_user(user_id, UserId(to_unfollow)) } yield Accepted r.onComplete{ case Failure(t) => log.error(s"unfollow failed:\n$t") case Success(_) => } r } } }
alanktwong/typesafe_activators
redis-twitter-clone/app/controllers/Api.scala
Scala
mit
1,433
package com.siftlogic.apps import org.apache.spark.sql.SparkSession object CachingExampleSparkApp { def main(args: Array[String]): Unit = { implicit val sparkSession = SparkSession.builder().appName("Caching Example").master("local").getOrCreate() import sparkSession.implicits._ val words = sparkSession.createDataset(Seq("spark", "apache spark", "spark", "word", "count")) .cache() //CACHED INPUT //.persist(StorageLevel.DISK_ONLY) //.persist(StorageLevel.MEMORY_AND_DISK) // CHECK StorageLevel val numberOfWordsWithSpark = words.filter(_.contains("spark")).count() val numberOfWordsWithoutSpark = words.filter(!_.contains("spark")).count() println(s"With: $numberOfWordsWithoutSpark Without: $numberOfWordsWithSpark") } }
przemek1990/introduction-to-spark
src/main/scala/com/siftlogic/apps/CachingExampleSparkApp.scala
Scala
gpl-3.0
786
package io.iohk.ethereum.testing import akka.actor.ActorRef import akka.testkit.TestActor.AutoPilot object ActorsTesting { def simpleAutoPilot(makeResponse: PartialFunction[Any, Any]): AutoPilot = { new AutoPilot { def run(sender: ActorRef, msg: Any) = { val response = makeResponse.lift(msg) response match { case Some(value) => sender ! value case _ => () } this } } } }
input-output-hk/etc-client
src/test/scala/io/iohk/ethereum/testing/ActorsTesting.scala
Scala
mit
450
package controllers import play.api.mvc._, Results._ import lila.app._ import views._ object Page extends LilaController { private def page(bookmark: String) = Open { implicit ctx => OptionOk(Prismic oneShotBookmark bookmark) { case (doc, resolver) => views.html.site.page(doc, resolver) } } def thanks = page("thanks") def tos = page("tos") def helpLichess = page("help") def streamHowTo = page("stream-howto") def contact = page("contact") def kingOfTheHill = page("king-of-the-hill") def privacy = page("privacy") }
r0k3/lila
app/controllers/Page.scala
Scala
mit
562
/* * Copyright (c) 2014. Webtrends (http://www.webtrends.com) * @author cuthbertm on 11/20/14 12:23 PM */ package com.webtrends.harness.component.spotifyapi import akka.actor.ActorRef import com.webtrends.harness.component.Component trait SpotifyAPI { this: Component => var SpotifyAPIRef:Option[ActorRef] = None def startSpotifyAPI : ActorRef = { SpotifyAPIRef = Some(context.actorOf(SpotifyAPIActor.props, SpotifyAPI.SpotifyAPIName)) SpotifyAPIRef.get } } object SpotifyAPI { val SpotifyAPIName = "SpotifyAPI" }
Crashfreak/SpotifyAPI
src/main/scala/com/webtrends/harness/component/spotifyapi/SpotifyAPI.scala
Scala
apache-2.0
537
package breeze.linalg import breeze.generic.UFunc import scala.reflect.ClassTag import breeze.storage.DefaultArrayValue /** * returns a vector along the diagonal of v. * Requires a square matrix? * @param m the matrix * @tparam V */ object diag extends UFunc with diagLowPrio2 { implicit def diagDVDMImpl[V:ClassTag:DefaultArrayValue]:diag.Impl[DenseVector[V], DenseMatrix[V]] = new diag.Impl[DenseVector[V], DenseMatrix[V]] { def apply(t: DenseVector[V]): DenseMatrix[V] = { val r = DenseMatrix.zeros[V](t.length, t.length) diag(r) := t r } } implicit def diagDMDVImpl[V]:diag.Impl[DenseMatrix[V], DenseVector[V]] = new diag.Impl[DenseMatrix[V], DenseVector[V]] { def apply(m: DenseMatrix[V]): DenseVector[V] = { require(m.rows == m.cols, "m must be square") new DenseVector(m.data, m.offset, m.majorStride + 1, m.rows) } } } trait diagLowPrio extends UFunc { this: UFunc => } trait diagLowPrio2 extends UFunc with diagLowPrio { this: UFunc => }
wavelets/breeze
src/main/scala/breeze/linalg/diag.scala
Scala
apache-2.0
1,016
package mesosphere.marathon.state import org.apache.mesos.{ Protos => mesos } case class Parameter( key: String, value: String) { def toProto: mesos.Parameter = mesos.Parameter.newBuilder .setKey(key) .setValue(value) .build } object Parameter { def apply(proto: mesos.Parameter): Parameter = Parameter( proto.getKey, proto.getValue ) }
timcharper/marathon
src/main/scala/mesosphere/marathon/state/Parameter.scala
Scala
apache-2.0
396
package unfiltered.request import org.scalatest.{Matchers, WordSpec} import unfiltered.response._ import test.AgentStrings class AgentSpecJetty extends AgentSpec with unfiltered.scalatest.jetty.Planned class AgentSpecNetty extends AgentSpec with unfiltered.scalatest.netty.Planned trait AgentSpec extends WordSpec with Matchers with unfiltered.scalatest.Hosted { def intent[A,B]: unfiltered.Cycle.Intent[A,B] = { case GET(_) & AgentIs.Chrome(_) => ResponseString("chromium") case GET(_) & AgentIs.Safari(_) & AgentIs.Mobile(_) => ResponseString("safari mobile") case GET(_) & AgentIs.Safari(_) => ResponseString("safari") case GET(_) & AgentIs.FireFox(_) => ResponseString("firefox") case GET(_) & AgentIs.IE(_) => ResponseString("ie") } "AgentIs should" should { "match chrome" in { val resp = http(host / "test" <:< Map("User-Agent" -> AgentStrings.chrome.head) as_str) resp should be("chromium") } "match safari" in { val resp = http(host / "test" <:< Map("User-Agent" -> AgentStrings.safari.head) as_str) resp should be("safari") } "match mobile safari" in { val resp = http(host / "test" <:< Map("User-Agent" -> "Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B5097d Safari/6531.22.7") as_str) resp should be("safari mobile") } "match firefox" in { val resp = http(host / "test" <:< Map("User-Agent" -> AgentStrings.firefox.head) as_str) resp should be("firefox") } "match ie" in { val resp = http(host / "test" <:< Map("User-Agent" -> AgentStrings.ie.head) as_str) resp should be("ie") } } }
peel/unfiltered
agents/src/test/scala/AgentSpec.scala
Scala
mit
1,709
package chat.tox.antox.wrapper import chat.tox.antox.utils.Hex object ToxAddress { val MAX_ADDRESS_LENGTH = 76 def isAddressValid(address: String): Boolean = { if (address.length != MAX_ADDRESS_LENGTH || !address.matches("^[0-9A-F]+$")) { return false } var x = 0 try { var i = 0 while (i < address.length) { x = x ^ java.lang.Integer.valueOf(address.substring(i, i + 4), 16) i += 4 } } catch { case e: NumberFormatException => return false } x == 0 } def removePrefix(address: String): String = { val prefix = "tox:" if (address.toLowerCase.contains(prefix)) { address.substring(prefix.length) } else { address } } } case class ToxAddress(address: String) { if (!ToxAddress.isAddressValid(address)) { throw new IllegalArgumentException(s"address must be $ToxAddress.MAX_ADDRESS_LENGTH hex chars long") } def this(bytes: Array[Byte]) = this(Hex.bytesToHexString(bytes)) def bytes: Array[Byte] = Hex.hexStringToBytes(address) def key: FriendKey = new FriendKey(address.substring(0, ToxKey.MAX_KEY_LENGTH)) override def toString: String = address }
wiiam/Antox
app/src/main/scala/chat/tox/antox/wrapper/ToxAddress.scala
Scala
gpl-3.0
1,201
package x7c1.linen.modern.display.unread import android.support.v7.widget.RecyclerView.Adapter import android.view.ViewGroup import x7c1.linen.glue.res.layout.{MenuRow, MenuRowLabel, MenuRowSeparator, MenuRowTitle} import x7c1.wheat.macros.logger.Log import x7c1.wheat.modern.menu.{MenuItems, MenuText} class DrawerMenuRowAdapter( items: MenuItems[MenuRow]) extends Adapter[MenuRow]{ override def getItemCount: Int = items.length override def onBindViewHolder(holder: MenuRow, position: Int): Unit = { items.bind(holder, position){ case (row: MenuRowLabel, item: DrawerMenuLabel) => row.text setText item.text row.itemView setOnClickListener item.onClick case (row: MenuRowTitle, item: MenuText) => row.text setText item.text case (row: MenuRowSeparator, _) => case (row, item) => Log error s"unknown row:$row, item:$item, position:$position" } } override def getItemViewType(position: Int): Int = { items.viewTypeAt(position) } override def onCreateViewHolder(parent: ViewGroup, viewType: Int): MenuRow = { items.inflate(parent, viewType) } }
x7c1/Linen
linen-modern/src/main/scala/x7c1/linen/modern/display/unread/DrawerMenuRowAdapter.scala
Scala
mit
1,140
package helper.services import scala.concurrent.Future import org.elasticsearch.indices.IndexAlreadyExistsException import org.elasticsearch.common.xcontent.XContentFactory._ import esclient.queries.{GetFillableIndexQuery, CreateFillableLogIndexQuery, DeleteFillableIndexQuery, IndexDocumentQuery} import esclient.Elasticsearch class LogIndexService(es: Elasticsearch) { val esClient = es.client implicit val context = scala.concurrent.ExecutionContext.Implicits.global def deleteLogIndex(index: String): Future[Int] = { DeleteFillableIndexQuery(esClient, index).execute map { closeResponse => if (closeResponse.isAcknowledged) 200 else 404 } recover { case e: Throwable => 404 case _ => 404 } } def createLogIndex(index: String, shards: Int, replicas: Int): Future[Int] = { CreateFillableLogIndexQuery(esClient, index, shards, replicas).execute map { createResponse => if (createResponse.isAcknowledged) 200 else 404 } recover { case e: IndexAlreadyExistsException => 400 case _ => 404 } } def addLogEntry(indexName: String, typed: String, chosen: String): Future[Int] = { GetFillableIndexQuery(esClient).execute flatMap { index => { if (index.getState.getMetaData.getIndices.containsKey(indexName)) { val doc = jsonBuilder() .startObject() .field("timestamp", System.currentTimeMillis()) .field("typed", typed) .field("chosen", chosen) .endObject().string() IndexDocumentQuery(esClient, indexName, doc).execute map { indexResponse => 200 } recover { case _ => 400 } } else { Future.successful(202) } } } recover { case _ => 400 } } }
MeiSign/Fillable
app/helper/services/LogIndexService.scala
Scala
apache-2.0
1,806
/*initLocally*/ class Test { def foo() { /*start*/1/*end*/ } } /* /*initLocally*/ class Test { var i: Int = _ def foo() { /*start*/ i = 1 i/*end*/ } } */
triggerNZ/intellij-scala
testdata/introduceField/SimpleFromMethodInitLocally.scala
Scala
apache-2.0
176
package org.jetbrains.plugins.scala package lang package surroundWith package surrounders package expression /** * author: Dmitry Krasilschikov */ import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.plugins.scala.lang.psi.api.expr.ScParenthesisedExpr import org.jetbrains.plugins.scala.lang.psi.impl.expr._ /* * Surrounds expression with while: while { <Cursor> } { Expression } */ class ScalaWithWhileSurrounder extends ScalaExpressionSurrounder { override def getTemplateAsString(elements: Array[PsiElement]): String = "while (true) {" + super.getTemplateAsString(elements) + "}" override def getTemplateDescription = "while" override def getSurroundSelectionRange(withWhileNode: ASTNode): TextRange = { val element: PsiElement = withWhileNode.getPsi match { case x: ScParenthesisedExpr => x.expr match { case Some(y) => y case _ => return x.getTextRange } case x => x } val whileStmt = element.asInstanceOf[ScWhileStmtImpl] val conditionNode: ASTNode = (whileStmt.condition: @unchecked) match { case Some(c) => c.getNode } val startOffset = conditionNode.getTextRange.getStartOffset val endOffset = conditionNode.getTextRange.getEndOffset new TextRange(startOffset, endOffset) } }
ilinum/intellij-scala
src/org/jetbrains/plugins/scala/lang/surroundWith/surrounders/expression/ScalaWithWhileSurrounder.scala
Scala
apache-2.0
1,362
package core.api import com.lvxingpai.model.geo.GeoEntity import com.lvxingpai.model.marketplace.product.Commodity import com.lvxingpai.model.marketplace.seller.Seller import core.model.misc.ApplySeller import org.bson.types.ObjectId import org.mongodb.morphia.Datastore import scala.collection.JavaConversions._ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future /** * * Created by topy on 2015/11/3. */ object SellerAPI { def getSeller(id: Long)(implicit ds: Datastore): Future[Option[Seller]] = { Future { Option(ds.find(classOf[Seller], "sellerId", id).get) } } def getSeller(id: Long, fields: Seq[String])(implicit ds: Datastore): Future[Option[Seller]] = { Future { Option(ds.find(classOf[Seller], "sellerId", id).retrievedFields(true, fields: _*).get) } } def getSeller(sellers: Seq[Seller], fields: Seq[String])(implicit ds: Datastore): Future[Option[Seq[Seller]]] = { Future { Option(ds.createQuery(classOf[Seller]).field("sellerId").in(sellers.map(_.sellerId)).retrievedFields(true, fields: _*).order("-lastSalesVolume").asList()) } } def getSeller(commodity: Option[Commodity])(implicit ds: Datastore): Future[Option[Seller]] = { Future { commodity match { case None => None case c if c.get.seller == null => None case _ => Option(ds.find(classOf[Seller], "sellerId", commodity.get.seller.sellerId).get) } } } def addSubLocalities(sellerId: Long, locality: Seq[GeoEntity])(implicit ds: Datastore): Future[Unit] = { Future { val statusQuery = ds.createQuery(classOf[Seller]) field "sellerId" equal sellerId val statusOps = ds.createUpdateOperations(classOf[Seller]).set("subLocalities", seqAsJavaList(locality)) ds.update(statusQuery, statusOps) } } def getSubLocalities(sellerId: Long)(implicit ds: Datastore): Future[Option[Seq[GeoEntity]]] = { Future { val seller = ds.find(classOf[Seller], "sellerId", sellerId).retrievedFields(true, Seq("subLocalities"): _*).get() Option(seller.subLocalities) } } def getSellers(locId: Seq[ObjectId])(implicit ds: Datastore): Future[Option[Seq[Long]]] = { Future { val query = ds.createQuery(classOf[Seller]) query.or( query.criteria("serviceZones.id").in(locId), query.criteria("subLocalities.id").in(locId) ) query.retrievedFields(true, Seq("sellerId"): _*) val sellers = query.asList() Option(sellers.map(_.sellerId)) } } def addApplySeller(name: String, tel: String, province: String, city: String, travel: String, license: String, email: String, memo: String)(implicit ds: Datastore): Future[Unit] = { Future { val applySeller = new ApplySeller applySeller.name = name applySeller.tel = tel applySeller.province = province applySeller.city = city applySeller.travel = travel applySeller.license = license applySeller.email = email applySeller.memo = memo ds.save[ApplySeller](applySeller) } } }
Lvxingpai/Hanse
app/core/api/SellerAPI.scala
Scala
apache-2.0
3,093
package com.yoohaemin.hufsclassroom.http import cats.effect.IO import org.http4s.EntityBody object ResponseBodyUtils { implicit class ByteVector2String(body: EntityBody[IO]) { def asString: String = { val array = body.compile.toVector.unsafeRunSync().toArray new String(array.map(_.toChar)) } } }
yoo-haemin/hufs-classroom
service/test/src/com/yoohaemin/hufsclassroom/http/ResponseBodyUtils.scala
Scala
agpl-3.0
325
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kafka.perf import java.util.concurrent.{CountDownLatch, Executors} import java.util.concurrent.atomic.AtomicLong import kafka.producer._ import org.apache.log4j.Logger import kafka.message.{CompressionCodec, Message} import java.text.SimpleDateFormat import java.util.{Random, Properties} import kafka.utils.Logging /** * Load test for the producer */ object ProducerPerformance extends Logging { def main(args: Array[String]) { val logger = Logger.getLogger(getClass) val config = new ProducerPerfConfig(args) if(!config.isFixSize) logger.info("WARN: Throughput will be slower due to changing message size per request") val totalBytesSent = new AtomicLong(0) val totalMessagesSent = new AtomicLong(0) val executor = Executors.newFixedThreadPool(config.numThreads) val allDone = new CountDownLatch(config.numThreads) val startMs = System.currentTimeMillis val rand = new java.util.Random if(!config.hideHeader) { if(!config.showDetailedStats) println("start.time, end.time, compression, message.size, batch.size, total.data.sent.in.MB, MB.sec, " + "total.data.sent.in.nMsg, nMsg.sec") else println("time, compression, thread.id, message.size, batch.size, total.data.sent.in.MB, MB.sec, " + "total.data.sent.in.nMsg, nMsg.sec") } for(i <- 0 until config.numThreads) { executor.execute(new ProducerThread(i, config, totalBytesSent, totalMessagesSent, allDone, rand)) } allDone.await() val endMs = System.currentTimeMillis val elapsedSecs = (endMs - startMs) / 1000.0 if(!config.showDetailedStats) { val totalMBSent = (totalBytesSent.get * 1.0)/ (1024 * 1024) println(("%s, %s, %d, %d, %d, %.2f, %.4f, %d, %.4f").format(config.dateFormat.format(startMs), config.dateFormat.format(endMs), config.compressionCodec.codec, config.messageSize, config.batchSize, totalMBSent, totalMBSent/elapsedSecs, totalMessagesSent.get, totalMessagesSent.get/elapsedSecs)) } System.exit(0) } class ProducerPerfConfig(args: Array[String]) extends PerfConfig(args) { val brokerInfoOpt = parser.accepts("brokerinfo", "REQUIRED: broker info (either from zookeeper or a list.") .withRequiredArg .describedAs("broker.list=brokerid:hostname:port or zk.connect=host:port") .ofType(classOf[String]) val messageSizeOpt = parser.accepts("message-size", "The size of each message.") .withRequiredArg .describedAs("size") .ofType(classOf[java.lang.Integer]) .defaultsTo(100) val varyMessageSizeOpt = parser.accepts("vary-message-size", "If set, message size will vary up to the given maximum.") val asyncOpt = parser.accepts("async", "If set, messages are sent asynchronously.") val batchSizeOpt = parser.accepts("batch-size", "Number of messages to send in a single batch.") .withRequiredArg .describedAs("size") .ofType(classOf[java.lang.Integer]) .defaultsTo(200) val numThreadsOpt = parser.accepts("threads", "Number of sending threads.") .withRequiredArg .describedAs("count") .ofType(classOf[java.lang.Integer]) .defaultsTo(10) val compressionCodecOption = parser.accepts("compression-codec", "If set, messages are sent compressed") .withRequiredArg .describedAs("compression codec ") .ofType(classOf[java.lang.Integer]) .defaultsTo(0) val options = parser.parse(args : _*) for(arg <- List(topicOpt, brokerInfoOpt, numMessagesOpt)) { if(!options.has(arg)) { System.err.println("Missing required argument \\"" + arg + "\\"") parser.printHelpOn(System.err) System.exit(1) } } val topic = options.valueOf(topicOpt) val numMessages = options.valueOf(numMessagesOpt).longValue val reportingInterval = options.valueOf(reportingIntervalOpt).intValue val showDetailedStats = options.has(showDetailedStatsOpt) val dateFormat = new SimpleDateFormat(options.valueOf(dateFormatOpt)) val hideHeader = options.has(hideHeaderOpt) val brokerInfo = options.valueOf(brokerInfoOpt) val messageSize = options.valueOf(messageSizeOpt).intValue val isFixSize = !options.has(varyMessageSizeOpt) val isAsync = options.has(asyncOpt) var batchSize = options.valueOf(batchSizeOpt).intValue val numThreads = options.valueOf(numThreadsOpt).intValue val compressionCodec = CompressionCodec.getCompressionCodec(options.valueOf(compressionCodecOption).intValue) } private def getStringOfLength(len: Int) : String = { val strArray = new Array[Char](len) for (i <- 0 until len) strArray(i) = 'x' return new String(strArray) } private def getByteArrayOfLength(len: Int): Array[Byte] = { //new Array[Byte](len) new Array[Byte]( if (len == 0) 5 else len ) } class ProducerThread(val threadId: Int, val config: ProducerPerfConfig, val totalBytesSent: AtomicLong, val totalMessagesSent: AtomicLong, val allDone: CountDownLatch, val rand: Random) extends Runnable { val props = new Properties() val brokerInfoList = config.brokerInfo.split("=") if (brokerInfoList(0) == "zk.connect") { props.put("zk.connect", brokerInfoList(1)) props.put("zk.sessiontimeout.ms", "300000") } else props.put("broker.list", brokerInfoList(1)) props.put("compression.codec", config.compressionCodec.codec.toString) props.put("reconnect.interval", Integer.MAX_VALUE.toString) props.put("buffer.size", (64*1024).toString) if(config.isAsync) { props.put("producer.type","async") props.put("batch.size", config.batchSize.toString) props.put("queue.enqueueTimeout.ms", "-1") } val producerConfig = new ProducerConfig(props) val producer = new Producer[Message, Message](producerConfig) override def run { var bytesSent = 0L var lastBytesSent = 0L var nSends = 0 var lastNSends = 0 val message = new Message(new Array[Byte](config.messageSize)) var reportTime = System.currentTimeMillis() var lastReportTime = reportTime val messagesPerThread = if(!config.isAsync) config.numMessages / config.numThreads / config.batchSize else config.numMessages / config.numThreads debug("Messages per thread = " + messagesPerThread) var messageSet: List[Message] = Nil if(config.isFixSize) { for(k <- 0 until config.batchSize) { messageSet ::= message } } var j: Long = 0L while(j < messagesPerThread) { var strLength = config.messageSize if (!config.isFixSize) { for(k <- 0 until config.batchSize) { strLength = rand.nextInt(config.messageSize) val message = new Message(getByteArrayOfLength(strLength)) messageSet ::= message bytesSent += message.payloadSize } }else if(!config.isAsync) { bytesSent += config.batchSize*message.payloadSize } try { if(!config.isAsync) { producer.send(new ProducerData[Message,Message](config.topic, null, messageSet)) if(!config.isFixSize) messageSet = Nil nSends += config.batchSize }else { if(!config.isFixSize) { strLength = rand.nextInt(config.messageSize) val messageBytes = getByteArrayOfLength(strLength) rand.nextBytes(messageBytes) val message = new Message(messageBytes) producer.send(new ProducerData[Message,Message](config.topic, message)) debug(config.topic + "-checksum:" + message.checksum) bytesSent += message.payloadSize }else { producer.send(new ProducerData[Message,Message](config.topic, message)) debug(config.topic + "-checksum:" + message.checksum) bytesSent += message.payloadSize } nSends += 1 } }catch { case e: Exception => e.printStackTrace } if(nSends % config.reportingInterval == 0) { reportTime = System.currentTimeMillis() val elapsed = (reportTime - lastReportTime)/ 1000.0 val mbBytesSent = ((bytesSent - lastBytesSent) * 1.0)/(1024 * 1024) val numMessagesPerSec = (nSends - lastNSends) / elapsed val mbPerSec = mbBytesSent / elapsed val formattedReportTime = config.dateFormat.format(reportTime) if(config.showDetailedStats) println(("%s, %d, %d, %d, %d, %.2f, %.4f, %d, %.4f").format(formattedReportTime, config.compressionCodec.codec, threadId, config.messageSize, config.batchSize, (bytesSent*1.0)/(1024 * 1024), mbPerSec, nSends, numMessagesPerSec)) lastReportTime = reportTime lastBytesSent = bytesSent lastNSends = nSends } j += 1 } producer.close() totalBytesSent.addAndGet(bytesSent) totalMessagesSent.addAndGet(nSends) allDone.countDown() } } }
piavlo/operations-debs-kafka
perf/src/main/scala/kafka/perf/ProducerPerformance.scala
Scala
apache-2.0
10,020
import akka.actor._ case class SpecialOrder(number : Integer, customer : ActorRef) class SpecialCustomer(loadBalancer : ActorRef) extends Actor { var currentOrder = 1 def receive = { case Food => println(self.path.name + ": Thanks for that.") currentOrder += 1 loadBalancer ! SpecialOrder(currentOrder, self) case Initiate => loadBalancer ! SpecialOrder(currentOrder, self) } } class SpecialWaiter extends Actor { // 10 orders per person. val limit = 5 def receive = { case SpecialOrder(number : Integer, customer : ActorRef) => if(number > limit) customer ! PoisonPill else { println("Waiter: #" + self.path.name + " Here's order # " + number + " " + customer.path.name) customer ! Food } } } class LoadBalancer(numWaiters : Integer) extends Actor { /* * Load balancer for restaurant waiters. * Will distribute load with equal probability * to all the waiters. Good performance in expectation. */ val waitersList = (for(waiter <- 1 to numWaiters) yield(context.actorOf(Props[SpecialWaiter], name = "waiter" + waiter))) val waiters = waitersList.toArray val r = scala.util.Random def receive = { case SpecialOrder(number : Integer, customer : ActorRef) => getRandomWaiter ! SpecialOrder(number, customer) } def getRandomWaiter = waiters(r.nextInt(waiters.size)) } object ComplexWorkflow extends App { val customerLimit = 2 val system = ActorSystem("RestaurantSystemLoadBalancer") val loadBalancer = system.actorOf(Props(new LoadBalancer(5)), name = "loadbalancer") val customers = for(i <- 1 to customerLimit) yield system.actorOf(Props(new SpecialCustomer(loadBalancer)), name = "customer" + i) customers.foreach { x => x ! Initiate } }
adijo/parallelized-workflow-simulation
src/main/scala/MultipleWaiters.scala
Scala
apache-2.0
1,977
package com.github.jmcs.domain.unaryexpression import com.github.jmcs.domain.Expression import com.github.jmcs.domain.UnaryExpression /** * Created with IntelliJ IDEA. * User: Marcelo * Date: 30/07/13 * Time: 22:54 * To change this template use File | Settings | File Templates. */ class BinaryLogarithmExpression(override val expression: Expression) extends UnaryExpression(expression) { def evaluate(): Any = useCache(() => BigDecimal(Math.log(expression.evaluate.asInstanceOf[BigDecimal].toDouble) / Math.log(2))) def getOperationSymbol = "lb" }
MarceloPortilho/jmc-scala
src/main/java/com/github/jmcs/domain/unaryexpression/BinaryLogarithmExpression.scala
Scala
apache-2.0
581
/* * Copyright 2013 Maurício Linhares * * Maurício Linhares licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.github.mauricio.async.db /** * * Represents the collection of rows that is returned from a statement inside a {@link QueryResult}. It's basically * a collection of Array[Any]. Mutating fields in this array will not affect the database in any way * */ trait ResultSet extends IndexedSeq[RowData] { /** * * The names of the columns returned by the statement. * * @return */ def columnNames : IndexedSeq[String] }
outbrain/postgresql-async
db-async-common/src/main/scala/com/github/mauricio/async/db/ResultSet.scala
Scala
apache-2.0
1,089
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.deploy.k8s.features.bindings import scala.collection.JavaConverters._ import io.fabric8.kubernetes.api.model.{ContainerBuilder, EnvVarBuilder, HasMetadata} import org.apache.spark.deploy.k8s.{KubernetesConf, KubernetesDriverSpecificConf, KubernetesUtils, SparkPod} import org.apache.spark.deploy.k8s.Constants._ import org.apache.spark.deploy.k8s.features.KubernetesFeatureConfigStep private[spark] class RDriverFeatureStep( kubernetesConf: KubernetesConf[KubernetesDriverSpecificConf]) extends KubernetesFeatureConfigStep { override def configurePod(pod: SparkPod): SparkPod = { val roleConf = kubernetesConf.roleSpecificConf require(roleConf.mainAppResource.isDefined, "R Main Resource must be defined") val maybeRArgs = Option(roleConf.appArgs).filter(_.nonEmpty).map( rArgs => new EnvVarBuilder() .withName(ENV_R_ARGS) .withValue(rArgs.mkString(",")) .build()) val envSeq = Seq(new EnvVarBuilder() .withName(ENV_R_PRIMARY) .withValue(KubernetesUtils.resolveFileUri(kubernetesConf.sparkRMainResource().get)) .build()) val rEnvs = envSeq ++ maybeRArgs.toSeq val withRPrimaryContainer = new ContainerBuilder(pod.container) .addAllToEnv(rEnvs.asJava) .addToArgs("driver-r") .addToArgs("--properties-file", SPARK_CONF_PATH) .addToArgs("--class", roleConf.mainClass) .build() SparkPod(pod.pod, withRPrimaryContainer) } override def getAdditionalPodSystemProperties(): Map[String, String] = Map.empty override def getAdditionalKubernetesResources(): Seq[HasMetadata] = Seq.empty }
rikima/spark
resource-managers/kubernetes/core/src/main/scala/org/apache/spark/deploy/k8s/features/bindings/RDriverFeatureStep.scala
Scala
apache-2.0
2,479
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.execution.datasources.csv import java.io.{ByteArrayOutputStream, EOFException, File, FileOutputStream} import java.nio.charset.{Charset, StandardCharsets, UnsupportedCharsetException} import java.nio.file.{Files, StandardOpenOption} import java.sql.{Date, Timestamp} import java.text.SimpleDateFormat import java.util.Locale import java.util.zip.GZIPOutputStream import scala.collection.JavaConverters._ import scala.util.Properties import com.univocity.parsers.common.TextParsingException import org.apache.commons.lang3.time.FastDateFormat import org.apache.hadoop.io.SequenceFile.CompressionType import org.apache.hadoop.io.compress.GzipCodec import org.apache.log4j.{AppenderSkeleton, LogManager} import org.apache.log4j.spi.LoggingEvent import org.apache.spark.{SparkException, TestUtils} import org.apache.spark.sql.{AnalysisException, DataFrame, QueryTest, Row} import org.apache.spark.sql.catalyst.util.DateTimeUtils import org.apache.spark.sql.internal.SQLConf import org.apache.spark.sql.test.SharedSparkSession import org.apache.spark.sql.types._ class CSVSuite extends QueryTest with SharedSparkSession with TestCsvData { import testImplicits._ private val carsFile = "test-data/cars.csv" private val carsMalformedFile = "test-data/cars-malformed.csv" private val carsFile8859 = "test-data/cars_iso-8859-1.csv" private val carsTsvFile = "test-data/cars.tsv" private val carsAltFile = "test-data/cars-alternative.csv" private val carsUnbalancedQuotesFile = "test-data/cars-unbalanced-quotes.csv" private val carsNullFile = "test-data/cars-null.csv" private val carsEmptyValueFile = "test-data/cars-empty-value.csv" private val carsBlankColName = "test-data/cars-blank-column-name.csv" private val carsCrlf = "test-data/cars-crlf.csv" private val emptyFile = "test-data/empty.csv" private val commentsFile = "test-data/comments.csv" private val disableCommentsFile = "test-data/disable_comments.csv" private val boolFile = "test-data/bool.csv" private val decimalFile = "test-data/decimal.csv" private val simpleSparseFile = "test-data/simple_sparse.csv" private val numbersFile = "test-data/numbers.csv" private val datesFile = "test-data/dates.csv" private val unescapedQuotesFile = "test-data/unescaped-quotes.csv" private val valueMalformedFile = "test-data/value-malformed.csv" private val badAfterGoodFile = "test-data/bad_after_good.csv" /** Verifies data and schema. */ private def verifyCars( df: DataFrame, withHeader: Boolean, numCars: Int = 3, numFields: Int = 5, checkHeader: Boolean = true, checkValues: Boolean = true, checkTypes: Boolean = false): Unit = { val numColumns = numFields val numRows = if (withHeader) numCars else numCars + 1 // schema assert(df.schema.fieldNames.length === numColumns) assert(df.count === numRows) if (checkHeader) { if (withHeader) { assert(df.schema.fieldNames === Array("year", "make", "model", "comment", "blank")) } else { assert(df.schema.fieldNames === Array("_c0", "_c1", "_c2", "_c3", "_c4")) } } if (checkValues) { val yearValues = List("2012", "1997", "2015") val actualYears = if (!withHeader) "year" :: yearValues else yearValues val years = if (withHeader) df.select("year").collect() else df.select("_c0").collect() years.zipWithIndex.foreach { case (year, index) => if (checkTypes) { assert(year === Row(actualYears(index).toInt)) } else { assert(year === Row(actualYears(index))) } } } } test("simple csv test") { val cars = spark .read .format("csv") .option("header", "false") .load(testFile(carsFile)) verifyCars(cars, withHeader = false, checkTypes = false) } test("simple csv test with calling another function to load") { val cars = spark .read .option("header", "false") .csv(testFile(carsFile)) verifyCars(cars, withHeader = false, checkTypes = false) } test("simple csv test with type inference") { val cars = spark .read .format("csv") .option("header", "true") .option("inferSchema", "true") .load(testFile(carsFile)) verifyCars(cars, withHeader = true, checkTypes = true) } test("simple csv test with string dataset") { val csvDataset = spark.read.text(testFile(carsFile)).as[String] val cars = spark.read .option("header", "true") .option("inferSchema", "true") .csv(csvDataset) verifyCars(cars, withHeader = true, checkTypes = true) val carsWithoutHeader = spark.read .option("header", "false") .csv(csvDataset) verifyCars(carsWithoutHeader, withHeader = false, checkTypes = false) } test("test inferring booleans") { val result = spark.read .format("csv") .option("header", "true") .option("inferSchema", "true") .load(testFile(boolFile)) val expectedSchema = StructType(List( StructField("bool", BooleanType, nullable = true))) assert(result.schema === expectedSchema) } test("test inferring decimals") { val result = spark.read .format("csv") .option("comment", "~") .option("header", "true") .option("inferSchema", "true") .load(testFile(decimalFile)) val expectedSchema = StructType(List( StructField("decimal", DecimalType(20, 0), nullable = true), StructField("long", LongType, nullable = true), StructField("double", DoubleType, nullable = true))) assert(result.schema === expectedSchema) } test("test with alternative delimiter and quote") { val cars = spark.read .format("csv") .options(Map("quote" -> "\\'", "delimiter" -> "|", "header" -> "true")) .load(testFile(carsAltFile)) verifyCars(cars, withHeader = true) } test("parse unescaped quotes with maxCharsPerColumn") { val rows = spark.read .format("csv") .option("maxCharsPerColumn", "4") .load(testFile(unescapedQuotesFile)) val expectedRows = Seq(Row("\\"a\\"b", "ccc", "ddd"), Row("ab", "cc\\"c", "ddd\\"")) checkAnswer(rows, expectedRows) } test("bad encoding name") { val exception = intercept[UnsupportedCharsetException] { spark .read .format("csv") .option("charset", "1-9588-osi") .load(testFile(carsFile8859)) } assert(exception.getMessage.contains("1-9588-osi")) } test("test different encoding") { withView("carsTable") { // scalastyle:off spark.sql( s""" |CREATE TEMPORARY VIEW carsTable USING csv |OPTIONS (path "${testFile(carsFile8859)}", header "true", |charset "iso-8859-1", delimiter "þ") """.stripMargin.replaceAll("\\n", " ")) // scalastyle:on verifyCars(spark.table("carsTable"), withHeader = true) } } test("crlf line separators in multiline mode") { val cars = spark .read .format("csv") .option("multiLine", "true") .option("header", "true") .load(testFile(carsCrlf)) verifyCars(cars, withHeader = true) } test("test aliases sep and encoding for delimiter and charset") { // scalastyle:off val cars = spark .read .format("csv") .option("header", "true") .option("encoding", "iso-8859-1") .option("sep", "þ") .load(testFile(carsFile8859)) // scalastyle:on verifyCars(cars, withHeader = true) } test("DDL test with tab separated file") { withView("carsTable") { spark.sql( s""" |CREATE TEMPORARY VIEW carsTable USING csv |OPTIONS (path "${testFile(carsTsvFile)}", header "true", delimiter "\\t") """.stripMargin.replaceAll("\\n", " ")) verifyCars(spark.table("carsTable"), numFields = 6, withHeader = true, checkHeader = false) } } test("DDL test parsing decimal type") { withView("carsTable") { spark.sql( s""" |CREATE TEMPORARY VIEW carsTable |(yearMade double, makeName string, modelName string, priceTag decimal, | comments string, grp string) |USING csv |OPTIONS (path "${testFile(carsTsvFile)}", header "true", delimiter "\\t") """.stripMargin.replaceAll("\\n", " ")) assert( spark.sql("SELECT makeName FROM carsTable where priceTag > 60000").collect().size === 1) } } test("test for DROPMALFORMED parsing mode") { withSQLConf(SQLConf.CSV_PARSER_COLUMN_PRUNING.key -> "false") { Seq(false, true).foreach { multiLine => val cars = spark.read .format("csv") .option("multiLine", multiLine) .options(Map("header" -> "true", "mode" -> "dropmalformed")) .load(testFile(carsFile)) assert(cars.select("year").collect().size === 2) } } } test("test for blank column names on read and select columns") { val cars = spark.read .format("csv") .options(Map("header" -> "true", "inferSchema" -> "true")) .load(testFile(carsBlankColName)) assert(cars.select("customer").collect().size == 2) assert(cars.select("_c0").collect().size == 2) assert(cars.select("_c1").collect().size == 2) } test("test for FAILFAST parsing mode") { Seq(false, true).foreach { multiLine => val exception = intercept[SparkException] { spark.read .format("csv") .option("multiLine", multiLine) .options(Map("header" -> "true", "mode" -> "failfast")) .load(testFile(carsFile)).collect() } assert(exception.getMessage.contains("Malformed CSV record")) } } test("test for tokens more than the fields in the schema") { val cars = spark .read .format("csv") .option("header", "false") .option("comment", "~") .load(testFile(carsMalformedFile)) verifyCars(cars, withHeader = false, checkTypes = false) } test("test with null quote character") { val cars = spark.read .format("csv") .option("header", "true") .option("quote", "") .load(testFile(carsUnbalancedQuotesFile)) verifyCars(cars, withHeader = true, checkValues = false) } test("test with empty file and known schema") { val result = spark.read .format("csv") .schema(StructType(List(StructField("column", StringType, false)))) .load(testFile(emptyFile)) assert(result.collect.size === 0) assert(result.schema.fieldNames.size === 1) } test("DDL test with empty file") { withView("carsTable") { spark.sql( s""" |CREATE TEMPORARY VIEW carsTable |(yearMade double, makeName string, modelName string, comments string, grp string) |USING csv |OPTIONS (path "${testFile(emptyFile)}", header "false") """.stripMargin.replaceAll("\\n", " ")) assert(spark.sql("SELECT count(*) FROM carsTable").collect().head(0) === 0) } } test("DDL test with schema") { withView("carsTable") { spark.sql( s""" |CREATE TEMPORARY VIEW carsTable |(yearMade double, makeName string, modelName string, comments string, blank string) |USING csv |OPTIONS (path "${testFile(carsFile)}", header "true") """.stripMargin.replaceAll("\\n", " ")) val cars = spark.table("carsTable") verifyCars(cars, withHeader = true, checkHeader = false, checkValues = false) assert( cars.schema.fieldNames === Array("yearMade", "makeName", "modelName", "comments", "blank")) } } test("save csv") { withTempDir { dir => val csvDir = new File(dir, "csv").getCanonicalPath val cars = spark.read .format("csv") .option("header", "true") .load(testFile(carsFile)) cars.coalesce(1).write .option("header", "true") .csv(csvDir) val carsCopy = spark.read .format("csv") .option("header", "true") .load(csvDir) verifyCars(carsCopy, withHeader = true) } } test("save csv with quote") { withTempDir { dir => val csvDir = new File(dir, "csv").getCanonicalPath val cars = spark.read .format("csv") .option("header", "true") .load(testFile(carsFile)) cars.coalesce(1).write .format("csv") .option("header", "true") .option("quote", "\\"") .save(csvDir) val carsCopy = spark.read .format("csv") .option("header", "true") .option("quote", "\\"") .load(csvDir) verifyCars(carsCopy, withHeader = true) } } test("save csv with quoteAll enabled") { withTempDir { dir => val csvDir = new File(dir, "csv").getCanonicalPath val data = Seq(("test \\"quote\\"", 123, "it \\"works\\"!", "\\"very\\" well")) val df = spark.createDataFrame(data) // escapeQuotes should be true by default df.coalesce(1).write .format("csv") .option("quote", "\\"") .option("escape", "\\"") .option("quoteAll", "true") .save(csvDir) val results = spark.read .format("text") .load(csvDir) .collect() val expected = "\\"test \\"\\"quote\\"\\"\\",\\"123\\",\\"it \\"\\"works\\"\\"!\\",\\"\\"\\"very\\"\\" well\\"" assert(results.toSeq.map(_.toSeq) === Seq(Seq(expected))) } } test("save csv with quote escaping enabled") { withTempDir { dir => val csvDir = new File(dir, "csv").getCanonicalPath val data = Seq(("test \\"quote\\"", 123, "it \\"works\\"!", "\\"very\\" well")) val df = spark.createDataFrame(data) // escapeQuotes should be true by default df.coalesce(1).write .format("csv") .option("quote", "\\"") .option("escape", "\\"") .save(csvDir) val results = spark.read .format("text") .load(csvDir) .collect() val expected = "\\"test \\"\\"quote\\"\\"\\",123,\\"it \\"\\"works\\"\\"!\\",\\"\\"\\"very\\"\\" well\\"" assert(results.toSeq.map(_.toSeq) === Seq(Seq(expected))) } } test("save csv with quote escaping disabled") { withTempDir { dir => val csvDir = new File(dir, "csv").getCanonicalPath val data = Seq(("test \\"quote\\"", 123, "it \\"works\\"!", "\\"very\\" well")) val df = spark.createDataFrame(data) // escapeQuotes should be true by default df.coalesce(1).write .format("csv") .option("quote", "\\"") .option("escapeQuotes", "false") .option("escape", "\\"") .save(csvDir) val results = spark.read .format("text") .load(csvDir) .collect() val expected = "test \\"quote\\",123,it \\"works\\"!,\\"\\"\\"very\\"\\" well\\"" assert(results.toSeq.map(_.toSeq) === Seq(Seq(expected))) } } test("save csv with quote escaping, using charToEscapeQuoteEscaping option") { withTempPath { path => // original text val df1 = Seq( """You are "beautiful"""", """Yes, \\"in the inside"\\""" ).toDF() // text written in CSV with following options: // quote character: " // escape character: \\ // character to escape quote escaping: # val df2 = Seq( """"You are \\"beautiful\\""""", """"Yes, #\\\\"in the inside\\"#\\"""" ).toDF() df2.coalesce(1).write.text(path.getAbsolutePath) val df3 = spark.read .format("csv") .option("quote", "\\"") .option("escape", "\\\\") .option("charToEscapeQuoteEscaping", "#") .load(path.getAbsolutePath) checkAnswer(df1, df3) } } test("SPARK-19018: Save csv with custom charset") { // scalastyle:off nonascii val content = "µß áâä ÁÂÄ" // scalastyle:on nonascii Seq("iso-8859-1", "utf-8", "utf-16", "utf-32", "windows-1250").foreach { encoding => withTempPath { path => val csvDir = new File(path, "csv") Seq(content).toDF().write .option("encoding", encoding) .csv(csvDir.getCanonicalPath) csvDir.listFiles().filter(_.getName.endsWith("csv")).foreach({ csvFile => val readback = Files.readAllBytes(csvFile.toPath) val expected = (content + Properties.lineSeparator).getBytes(Charset.forName(encoding)) assert(readback === expected) }) } } } test("SPARK-19018: error handling for unsupported charsets") { val exception = intercept[SparkException] { withTempPath { path => val csvDir = new File(path, "csv").getCanonicalPath Seq("a,A,c,A,b,B").toDF().write .option("encoding", "1-9588-osi") .csv(csvDir) } } assert(exception.getCause.getMessage.contains("1-9588-osi")) } test("commented lines in CSV data") { Seq("false", "true").foreach { multiLine => val results = spark.read .format("csv") .options(Map("comment" -> "~", "header" -> "false", "multiLine" -> multiLine)) .load(testFile(commentsFile)) .collect() val expected = Seq(Seq("1", "2", "3", "4", "5.01", "2015-08-20 15:57:00"), Seq("6", "7", "8", "9", "0", "2015-08-21 16:58:01"), Seq("1", "2", "3", "4", "5", "2015-08-23 18:00:42")) assert(results.toSeq.map(_.toSeq) === expected) } } test("inferring schema with commented lines in CSV data") { val results = spark.read .format("csv") .options(Map("comment" -> "~", "header" -> "false", "inferSchema" -> "true")) .option("timestampFormat", "yyyy-MM-dd HH:mm:ss") .load(testFile(commentsFile)) .collect() val expected = Seq(Seq(1, 2, 3, 4, 5.01D, Timestamp.valueOf("2015-08-20 15:57:00")), Seq(6, 7, 8, 9, 0, Timestamp.valueOf("2015-08-21 16:58:01")), Seq(1, 2, 3, 4, 5, Timestamp.valueOf("2015-08-23 18:00:42"))) assert(results.toSeq.map(_.toSeq) === expected) } test("inferring timestamp types via custom date format") { val options = Map( "header" -> "true", "inferSchema" -> "true", "timestampFormat" -> "dd/MM/yyyy HH:mm") val results = spark.read .format("csv") .options(options) .load(testFile(datesFile)) .select("date") .collect() val dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.US) val expected = Seq(Seq(new Timestamp(dateFormat.parse("26/08/2015 18:00").getTime)), Seq(new Timestamp(dateFormat.parse("27/10/2014 18:30").getTime)), Seq(new Timestamp(dateFormat.parse("28/01/2016 20:00").getTime))) assert(results.toSeq.map(_.toSeq) === expected) } test("load date types via custom date format") { val customSchema = new StructType(Array(StructField("date", DateType, true))) val options = Map( "header" -> "true", "inferSchema" -> "false", "dateFormat" -> "dd/MM/yyyy HH:mm") val results = spark.read .format("csv") .options(options) .option("timeZone", "UTC") .schema(customSchema) .load(testFile(datesFile)) .select("date") .collect() val dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm", Locale.US) val expected = Seq( new Date(dateFormat.parse("26/08/2015 18:00").getTime), new Date(dateFormat.parse("27/10/2014 18:30").getTime), new Date(dateFormat.parse("28/01/2016 20:00").getTime)) val dates = results.toSeq.map(_.toSeq.head) expected.zip(dates).foreach { case (expectedDate, date) => // As it truncates the hours, minutes and etc., we only check // if the dates (days, months and years) are the same via `toString()`. assert(expectedDate.toString === date.toString) } } test("setting comment to null disables comment support") { val results = spark.read .format("csv") .options(Map("comment" -> "", "header" -> "false")) .load(testFile(disableCommentsFile)) .collect() val expected = Seq( Seq("#1", "2", "3"), Seq("4", "5", "6")) assert(results.toSeq.map(_.toSeq) === expected) } test("nullable fields with user defined null value of \\"null\\"") { // year,make,model,comment,blank val dataSchema = StructType(List( StructField("year", IntegerType, nullable = true), StructField("make", StringType, nullable = false), StructField("model", StringType, nullable = false), StructField("comment", StringType, nullable = true), StructField("blank", StringType, nullable = true))) val cars = spark.read .format("csv") .schema(dataSchema) .options(Map("header" -> "true", "nullValue" -> "null")) .load(testFile(carsNullFile)) verifyCars(cars, withHeader = true, checkValues = false) val results = cars.collect() assert(results(0).toSeq === Array(2012, "Tesla", "S", null, null)) assert(results(2).toSeq === Array(null, "Chevy", "Volt", null, null)) } test("empty fields with user defined empty values") { // year,make,model,comment,blank val dataSchema = StructType(List( StructField("year", IntegerType, nullable = true), StructField("make", StringType, nullable = false), StructField("model", StringType, nullable = false), StructField("comment", StringType, nullable = true), StructField("blank", StringType, nullable = true))) val cars = spark.read .format("csv") .schema(dataSchema) .option("header", "true") .option("emptyValue", "empty") .load(testFile(carsEmptyValueFile)) verifyCars(cars, withHeader = true, checkValues = false) val results = cars.collect() assert(results(0).toSeq === Array(2012, "Tesla", "S", "empty", "empty")) assert(results(1).toSeq === Array(1997, "Ford", "E350", "Go get one now they are going fast", null)) assert(results(2).toSeq === Array(2015, "Chevy", "Volt", null, "empty")) } test("save csv with empty fields with user defined empty values") { withTempDir { dir => val csvDir = new File(dir, "csv").getCanonicalPath // year,make,model,comment,blank val dataSchema = StructType(List( StructField("year", IntegerType, nullable = true), StructField("make", StringType, nullable = false), StructField("model", StringType, nullable = false), StructField("comment", StringType, nullable = true), StructField("blank", StringType, nullable = true))) val cars = spark.read .format("csv") .schema(dataSchema) .option("header", "true") .option("nullValue", "NULL") .load(testFile(carsEmptyValueFile)) cars.coalesce(1).write .format("csv") .option("header", "true") .option("emptyValue", "empty") .option("nullValue", null) .save(csvDir) val carsCopy = spark.read .format("csv") .schema(dataSchema) .option("header", "true") .load(csvDir) verifyCars(carsCopy, withHeader = true, checkValues = false) val results = carsCopy.collect() assert(results(0).toSeq === Array(2012, "Tesla", "S", "empty", "empty")) assert(results(1).toSeq === Array(1997, "Ford", "E350", "Go get one now they are going fast", null)) assert(results(2).toSeq === Array(2015, "Chevy", "Volt", null, "empty")) } } test("save csv with compression codec option") { withTempDir { dir => val csvDir = new File(dir, "csv").getCanonicalPath val cars = spark.read .format("csv") .option("header", "true") .load(testFile(carsFile)) cars.coalesce(1).write .format("csv") .option("header", "true") .option("compression", "gZiP") .save(csvDir) val compressedFiles = new File(csvDir).listFiles() assert(compressedFiles.exists(_.getName.endsWith(".csv.gz"))) val carsCopy = spark.read .format("csv") .option("header", "true") .load(csvDir) verifyCars(carsCopy, withHeader = true) } } test("SPARK-13543 Write the output as uncompressed via option()") { val extraOptions = Map( "mapreduce.output.fileoutputformat.compress" -> "true", "mapreduce.output.fileoutputformat.compress.type" -> CompressionType.BLOCK.toString, "mapreduce.map.output.compress" -> "true", "mapreduce.map.output.compress.codec" -> classOf[GzipCodec].getName ) withTempDir { dir => val csvDir = new File(dir, "csv").getCanonicalPath val cars = spark.read .format("csv") .option("header", "true") .options(extraOptions) .load(testFile(carsFile)) cars.coalesce(1).write .format("csv") .option("header", "true") .option("compression", "none") .options(extraOptions) .save(csvDir) val compressedFiles = new File(csvDir).listFiles() assert(compressedFiles.exists(!_.getName.endsWith(".csv.gz"))) val carsCopy = spark.read .format("csv") .option("header", "true") .options(extraOptions) .load(csvDir) verifyCars(carsCopy, withHeader = true) } } test("Schema inference correctly identifies the datatype when data is sparse.") { val df = spark.read .format("csv") .option("header", "true") .option("inferSchema", "true") .load(testFile(simpleSparseFile)) assert( df.schema.fields.map(field => field.dataType).deep == Array(IntegerType, IntegerType, IntegerType, IntegerType).deep) } test("old csv data source name works") { val cars = spark .read .format("com.databricks.spark.csv") .option("header", "false") .load(testFile(carsFile)) verifyCars(cars, withHeader = false, checkTypes = false) } test("nulls, NaNs and Infinity values can be parsed") { val numbers = spark .read .format("csv") .schema(StructType(List( StructField("int", IntegerType, true), StructField("long", LongType, true), StructField("float", FloatType, true), StructField("double", DoubleType, true) ))) .options(Map( "header" -> "true", "mode" -> "DROPMALFORMED", "nullValue" -> "--", "nanValue" -> "NAN", "negativeInf" -> "-INF", "positiveInf" -> "INF")) .load(testFile(numbersFile)) assert(numbers.count() == 8) } test("SPARK-15585 turn off quotations") { val cars = spark.read .format("csv") .option("header", "true") .option("quote", "") .load(testFile(carsUnbalancedQuotesFile)) verifyCars(cars, withHeader = true, checkValues = false) } test("Write timestamps correctly in ISO8601 format by default") { withTempDir { dir => val iso8601timestampsPath = s"${dir.getCanonicalPath}/iso8601timestamps.csv" val timestamps = spark.read .format("csv") .option("inferSchema", "true") .option("header", "true") .option("timestampFormat", "dd/MM/yyyy HH:mm") .load(testFile(datesFile)) timestamps.write .format("csv") .option("header", "true") .save(iso8601timestampsPath) // This will load back the timestamps as string. val stringSchema = StructType(StructField("date", StringType, true) :: Nil) val iso8601Timestamps = spark.read .format("csv") .schema(stringSchema) .option("header", "true") .load(iso8601timestampsPath) val iso8501 = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.US) val expectedTimestamps = timestamps.collect().map { r => // This should be ISO8601 formatted string. Row(iso8501.format(r.toSeq.head)) } checkAnswer(iso8601Timestamps, expectedTimestamps) } } test("Write dates correctly in ISO8601 format by default") { withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> "UTC") { withTempDir { dir => val customSchema = new StructType(Array(StructField("date", DateType, true))) val iso8601datesPath = s"${dir.getCanonicalPath}/iso8601dates.csv" val dates = spark.read .format("csv") .schema(customSchema) .option("header", "true") .option("inferSchema", "false") .option("dateFormat", "dd/MM/yyyy HH:mm") .load(testFile(datesFile)) dates.write .format("csv") .option("header", "true") .save(iso8601datesPath) // This will load back the dates as string. val stringSchema = StructType(StructField("date", StringType, true) :: Nil) val iso8601dates = spark.read .format("csv") .schema(stringSchema) .option("header", "true") .load(iso8601datesPath) val iso8501 = FastDateFormat.getInstance("yyyy-MM-dd", Locale.US) val expectedDates = dates.collect().map { r => // This should be ISO8601 formatted string. Row(iso8501.format(r.toSeq.head)) } checkAnswer(iso8601dates, expectedDates) } } } test("Roundtrip in reading and writing timestamps") { withTempDir { dir => val iso8601timestampsPath = s"${dir.getCanonicalPath}/iso8601timestamps.csv" val timestamps = spark.read .format("csv") .option("header", "true") .option("inferSchema", "true") .load(testFile(datesFile)) timestamps.write .format("csv") .option("header", "true") .save(iso8601timestampsPath) val iso8601timestamps = spark.read .format("csv") .option("header", "true") .option("inferSchema", "true") .load(iso8601timestampsPath) checkAnswer(iso8601timestamps, timestamps) } } test("Write dates correctly with dateFormat option") { val customSchema = new StructType(Array(StructField("date", DateType, true))) withTempDir { dir => // With dateFormat option. val datesWithFormatPath = s"${dir.getCanonicalPath}/datesWithFormat.csv" val datesWithFormat = spark.read .format("csv") .schema(customSchema) .option("header", "true") .option("dateFormat", "dd/MM/yyyy HH:mm") .load(testFile(datesFile)) datesWithFormat.write .format("csv") .option("header", "true") .option("dateFormat", "yyyy/MM/dd") .save(datesWithFormatPath) // This will load back the dates as string. val stringSchema = StructType(StructField("date", StringType, true) :: Nil) val stringDatesWithFormat = spark.read .format("csv") .schema(stringSchema) .option("header", "true") .load(datesWithFormatPath) val expectedStringDatesWithFormat = Seq( Row("2015/08/26"), Row("2014/10/27"), Row("2016/01/28")) checkAnswer(stringDatesWithFormat, expectedStringDatesWithFormat) } } test("Write timestamps correctly with timestampFormat option") { withTempDir { dir => // With dateFormat option. val timestampsWithFormatPath = s"${dir.getCanonicalPath}/timestampsWithFormat.csv" val timestampsWithFormat = spark.read .format("csv") .option("header", "true") .option("inferSchema", "true") .option("timestampFormat", "dd/MM/yyyy HH:mm") .load(testFile(datesFile)) timestampsWithFormat.write .format("csv") .option("header", "true") .option("timestampFormat", "yyyy/MM/dd HH:mm") .save(timestampsWithFormatPath) // This will load back the timestamps as string. val stringSchema = StructType(StructField("date", StringType, true) :: Nil) val stringTimestampsWithFormat = spark.read .format("csv") .schema(stringSchema) .option("header", "true") .load(timestampsWithFormatPath) val expectedStringTimestampsWithFormat = Seq( Row("2015/08/26 18:00"), Row("2014/10/27 18:30"), Row("2016/01/28 20:00")) checkAnswer(stringTimestampsWithFormat, expectedStringTimestampsWithFormat) } } test("Write timestamps correctly with timestampFormat option and timeZone option") { withTempDir { dir => // With dateFormat option and timeZone option. val timestampsWithFormatPath = s"${dir.getCanonicalPath}/timestampsWithFormat.csv" val timestampsWithFormat = spark.read .format("csv") .option("header", "true") .option("inferSchema", "true") .option("timestampFormat", "dd/MM/yyyy HH:mm") .load(testFile(datesFile)) timestampsWithFormat.write .format("csv") .option("header", "true") .option("timestampFormat", "yyyy/MM/dd HH:mm") .option(DateTimeUtils.TIMEZONE_OPTION, "GMT") .save(timestampsWithFormatPath) // This will load back the timestamps as string. val stringSchema = StructType(StructField("date", StringType, true) :: Nil) val stringTimestampsWithFormat = spark.read .format("csv") .schema(stringSchema) .option("header", "true") .load(timestampsWithFormatPath) val expectedStringTimestampsWithFormat = Seq( Row("2015/08/27 01:00"), Row("2014/10/28 01:30"), Row("2016/01/29 04:00")) checkAnswer(stringTimestampsWithFormat, expectedStringTimestampsWithFormat) val readBack = spark.read .format("csv") .option("header", "true") .option("inferSchema", "true") .option("timestampFormat", "yyyy/MM/dd HH:mm") .option(DateTimeUtils.TIMEZONE_OPTION, "GMT") .load(timestampsWithFormatPath) checkAnswer(readBack, timestampsWithFormat) } } test("load duplicated field names consistently with null or empty strings - case sensitive") { withSQLConf(SQLConf.CASE_SENSITIVE.key -> "true") { withTempPath { path => Seq("a,a,c,A,b,B").toDF().write.text(path.getAbsolutePath) val actualSchema = spark.read .format("csv") .option("header", true) .load(path.getAbsolutePath) .schema val fields = Seq("a0", "a1", "c", "A", "b", "B").map(StructField(_, StringType, true)) val expectedSchema = StructType(fields) assert(actualSchema == expectedSchema) } } } test("load duplicated field names consistently with null or empty strings - case insensitive") { withSQLConf(SQLConf.CASE_SENSITIVE.key -> "false") { withTempPath { path => Seq("a,A,c,A,b,B").toDF().write.text(path.getAbsolutePath) val actualSchema = spark.read .format("csv") .option("header", true) .load(path.getAbsolutePath) .schema val fields = Seq("a0", "A1", "c", "A3", "b4", "B5").map(StructField(_, StringType, true)) val expectedSchema = StructType(fields) assert(actualSchema == expectedSchema) } } } test("load null when the schema is larger than parsed tokens ") { withTempPath { path => Seq("1").toDF().write.text(path.getAbsolutePath) val schema = StructType( StructField("a", IntegerType, true) :: StructField("b", IntegerType, true) :: Nil) val df = spark.read .schema(schema) .option("header", "false") .csv(path.getAbsolutePath) checkAnswer(df, Row(1, null)) } } test("SPARK-18699 put malformed records in a `columnNameOfCorruptRecord` field") { Seq(false, true).foreach { multiLine => val schema = new StructType().add("a", IntegerType).add("b", DateType) // We use `PERMISSIVE` mode by default if invalid string is given. val df1 = spark .read .option("mode", "abcd") .option("multiLine", multiLine) .schema(schema) .csv(testFile(valueMalformedFile)) checkAnswer(df1, Row(0, null) :: Row(1, java.sql.Date.valueOf("1983-08-04")) :: Nil) // If `schema` has `columnNameOfCorruptRecord`, it should handle corrupt records val columnNameOfCorruptRecord = "_unparsed" val schemaWithCorrField1 = schema.add(columnNameOfCorruptRecord, StringType) val df2 = spark .read .option("mode", "Permissive") .option("columnNameOfCorruptRecord", columnNameOfCorruptRecord) .option("multiLine", multiLine) .schema(schemaWithCorrField1) .csv(testFile(valueMalformedFile)) checkAnswer(df2, Row(0, null, "0,2013-111-11 12:13:14") :: Row(1, java.sql.Date.valueOf("1983-08-04"), null) :: Nil) // We put a `columnNameOfCorruptRecord` field in the middle of a schema val schemaWithCorrField2 = new StructType() .add("a", IntegerType) .add(columnNameOfCorruptRecord, StringType) .add("b", DateType) val df3 = spark .read .option("mode", "permissive") .option("columnNameOfCorruptRecord", columnNameOfCorruptRecord) .option("multiLine", multiLine) .schema(schemaWithCorrField2) .csv(testFile(valueMalformedFile)) checkAnswer(df3, Row(0, "0,2013-111-11 12:13:14", null) :: Row(1, null, java.sql.Date.valueOf("1983-08-04")) :: Nil) val errMsg = intercept[AnalysisException] { spark .read .option("mode", "PERMISSIVE") .option("columnNameOfCorruptRecord", columnNameOfCorruptRecord) .option("multiLine", multiLine) .schema(schema.add(columnNameOfCorruptRecord, IntegerType)) .csv(testFile(valueMalformedFile)) .collect }.getMessage assert(errMsg.startsWith("The field for corrupt records must be string type and nullable")) } } test("Enabling/disabling ignoreCorruptFiles") { val inputFile = File.createTempFile("input-", ".gz") try { // Create a corrupt gzip file val byteOutput = new ByteArrayOutputStream() val gzip = new GZIPOutputStream(byteOutput) try { gzip.write(Array[Byte](1, 2, 3, 4)) } finally { gzip.close() } val bytes = byteOutput.toByteArray val o = new FileOutputStream(inputFile) try { // It's corrupt since we only write half of bytes into the file. o.write(bytes.take(bytes.length / 2)) } finally { o.close() } withSQLConf(SQLConf.IGNORE_CORRUPT_FILES.key -> "false") { val e = intercept[SparkException] { spark.read.csv(inputFile.toURI.toString).collect() } assert(e.getCause.isInstanceOf[EOFException]) assert(e.getCause.getMessage === "Unexpected end of input stream") } withSQLConf(SQLConf.IGNORE_CORRUPT_FILES.key -> "true") { assert(spark.read.csv(inputFile.toURI.toString).collect().isEmpty) } } finally { inputFile.delete() } } test("SPARK-19610: Parse normal multi-line CSV files") { val primitiveFieldAndType = Seq( """" |string","integer | | |","long | |","bigInteger",double,boolean,null""".stripMargin, """"this is a |simple |string."," | |10"," |21474836470","92233720368547758070"," | |1.7976931348623157E308",true,""".stripMargin) withTempPath { path => primitiveFieldAndType.toDF("value").coalesce(1).write.text(path.getAbsolutePath) val df = spark.read .option("header", true) .option("multiLine", true) .csv(path.getAbsolutePath) // Check if headers have new lines in the names. val actualFields = df.schema.fieldNames.toSeq val expectedFields = Seq("\\nstring", "integer\\n\\n\\n", "long\\n\\n", "bigInteger", "double", "boolean", "null") assert(actualFields === expectedFields) // Check if the rows have new lines in the values. val expected = Row( "this is a\\nsimple\\nstring.", "\\n\\n10", "\\n21474836470", "92233720368547758070", "\\n\\n1.7976931348623157E308", "true", null) checkAnswer(df, expected) } } test("Empty file produces empty dataframe with empty schema") { Seq(false, true).foreach { multiLine => val df = spark.read.format("csv") .option("header", true) .option("multiLine", multiLine) .load(testFile(emptyFile)) assert(df.schema === spark.emptyDataFrame.schema) checkAnswer(df, spark.emptyDataFrame) } } test("Empty string dataset produces empty dataframe and keep user-defined schema") { val df1 = spark.read.csv(spark.emptyDataset[String]) assert(df1.schema === spark.emptyDataFrame.schema) checkAnswer(df1, spark.emptyDataFrame) val schema = StructType(StructField("a", StringType) :: Nil) val df2 = spark.read.schema(schema).csv(spark.emptyDataset[String]) assert(df2.schema === schema) } test("ignoreLeadingWhiteSpace and ignoreTrailingWhiteSpace options - read") { val input = " a,b , c " // For reading, default of both `ignoreLeadingWhiteSpace` and`ignoreTrailingWhiteSpace` // are `false`. So, these are excluded. val combinations = Seq( (true, true), (false, true), (true, false)) // Check if read rows ignore whitespaces as configured. val expectedRows = Seq( Row("a", "b", "c"), Row(" a", "b", " c"), Row("a", "b ", "c ")) combinations.zip(expectedRows) .foreach { case ((ignoreLeadingWhiteSpace, ignoreTrailingWhiteSpace), expected) => val df = spark.read .option("ignoreLeadingWhiteSpace", ignoreLeadingWhiteSpace) .option("ignoreTrailingWhiteSpace", ignoreTrailingWhiteSpace) .csv(Seq(input).toDS()) checkAnswer(df, expected) } } test("SPARK-18579: ignoreLeadingWhiteSpace and ignoreTrailingWhiteSpace options - write") { val df = Seq((" a", "b ", " c ")).toDF() // For writing, default of both `ignoreLeadingWhiteSpace` and `ignoreTrailingWhiteSpace` // are `true`. So, these are excluded. val combinations = Seq( (false, false), (false, true), (true, false)) // Check if written lines ignore each whitespaces as configured. val expectedLines = Seq( " a,b , c ", " a,b, c", "a,b ,c ") combinations.zip(expectedLines) .foreach { case ((ignoreLeadingWhiteSpace, ignoreTrailingWhiteSpace), expected) => withTempPath { path => df.write .option("ignoreLeadingWhiteSpace", ignoreLeadingWhiteSpace) .option("ignoreTrailingWhiteSpace", ignoreTrailingWhiteSpace) .csv(path.getAbsolutePath) // Read back the written lines. val readBack = spark.read.text(path.getAbsolutePath) checkAnswer(readBack, Row(expected)) } } } test("SPARK-21263: Invalid float and double are handled correctly in different modes") { val exception = intercept[SparkException] { spark.read.schema("a DOUBLE") .option("mode", "FAILFAST") .csv(Seq("10u12").toDS()) .collect() } assert(exception.getMessage.contains("""input string: "10u12"""")) val count = spark.read.schema("a FLOAT") .option("mode", "DROPMALFORMED") .csv(Seq("10u12").toDS()) .count() assert(count == 0) val results = spark.read.schema("a FLOAT") .option("mode", "PERMISSIVE") .csv(Seq("10u12").toDS()) checkAnswer(results, Row(null)) } test("SPARK-20978: Fill the malformed column when the number of tokens is less than schema") { val df = spark.read .schema("a string, b string, unparsed string") .option("columnNameOfCorruptRecord", "unparsed") .csv(Seq("a").toDS()) checkAnswer(df, Row("a", null, "a")) } test("SPARK-21610: Corrupt records are not handled properly when creating a dataframe " + "from a file") { val columnNameOfCorruptRecord = "_corrupt_record" val schema = new StructType() .add("a", IntegerType) .add("b", DateType) .add(columnNameOfCorruptRecord, StringType) // negative cases val msg = intercept[AnalysisException] { spark .read .option("columnNameOfCorruptRecord", columnNameOfCorruptRecord) .schema(schema) .csv(testFile(valueMalformedFile)) .select(columnNameOfCorruptRecord) .collect() }.getMessage assert(msg.contains("only include the internal corrupt record column")) // workaround val df = spark .read .option("columnNameOfCorruptRecord", columnNameOfCorruptRecord) .schema(schema) .csv(testFile(valueMalformedFile)) .cache() assert(df.filter($"_corrupt_record".isNotNull).count() == 1) assert(df.filter($"_corrupt_record".isNull).count() == 1) checkAnswer( df.select(columnNameOfCorruptRecord), Row("0,2013-111-11 12:13:14") :: Row(null) :: Nil ) } test("SPARK-23846: schema inferring touches less data if samplingRatio < 1.0") { // Set default values for the DataSource parameters to make sure // that whole test file is mapped to only one partition. This will guarantee // reliable sampling of the input file. withSQLConf( SQLConf.FILES_MAX_PARTITION_BYTES.key -> (128 * 1024 * 1024).toString, SQLConf.FILES_OPEN_COST_IN_BYTES.key -> (4 * 1024 * 1024).toString )(withTempPath { path => val ds = sampledTestData.coalesce(1) ds.write.text(path.getAbsolutePath) val readback = spark.read .option("inferSchema", true).option("samplingRatio", 0.1) .csv(path.getCanonicalPath) assert(readback.schema == new StructType().add("_c0", IntegerType)) }) } test("SPARK-23846: usage of samplingRatio while parsing a dataset of strings") { val ds = sampledTestData.coalesce(1) val readback = spark.read .option("inferSchema", true).option("samplingRatio", 0.1) .csv(ds) assert(readback.schema == new StructType().add("_c0", IntegerType)) } test("SPARK-23846: samplingRatio is out of the range (0, 1.0]") { val ds = spark.range(0, 100, 1, 1).map(_.toString) val errorMsg0 = intercept[IllegalArgumentException] { spark.read.option("inferSchema", true).option("samplingRatio", -1).csv(ds) }.getMessage assert(errorMsg0.contains("samplingRatio (-1.0) should be greater than 0")) val errorMsg1 = intercept[IllegalArgumentException] { spark.read.option("inferSchema", true).option("samplingRatio", 0).csv(ds) }.getMessage assert(errorMsg1.contains("samplingRatio (0.0) should be greater than 0")) val sampled = spark.read.option("inferSchema", true).option("samplingRatio", 1.0).csv(ds) assert(sampled.count() == ds.count()) } test("SPARK-17916: An empty string should not be coerced to null when nullValue is passed.") { val litNull: String = null val df = Seq( (1, "John Doe"), (2, ""), (3, "-"), (4, litNull) ).toDF("id", "name") // Checks for new behavior where an empty string is not coerced to null when `nullValue` is // set to anything but an empty string literal. withTempPath { path => df.write .option("nullValue", "-") .csv(path.getAbsolutePath) val computed = spark.read .option("nullValue", "-") .schema(df.schema) .csv(path.getAbsolutePath) val expected = Seq( (1, "John Doe"), (2, ""), (3, litNull), (4, litNull) ).toDF("id", "name") checkAnswer(computed, expected) } // Keeps the old behavior where empty string us coerced to nullValue is not passed. withTempPath { path => df.write .csv(path.getAbsolutePath) val computed = spark.read .schema(df.schema) .csv(path.getAbsolutePath) val expected = Seq( (1, "John Doe"), (2, litNull), (3, "-"), (4, litNull) ).toDF("id", "name") checkAnswer(computed, expected) } } test("SPARK-25241: An empty string should not be coerced to null when emptyValue is passed.") { val litNull: String = null val df = Seq( (1, "John Doe"), (2, ""), (3, "-"), (4, litNull) ).toDF("id", "name") // Checks for new behavior where a null is not coerced to an empty string when `emptyValue` is // set to anything but an empty string literal. withTempPath { path => df.write .option("emptyValue", "-") .csv(path.getAbsolutePath) val computed = spark.read .option("emptyValue", "-") .schema(df.schema) .csv(path.getAbsolutePath) val expected = Seq( (1, "John Doe"), (2, "-"), (3, "-"), (4, "-") ).toDF("id", "name") checkAnswer(computed, expected) } // Keeps the old behavior where empty string us coerced to emptyValue is not passed. withTempPath { path => df.write .csv(path.getAbsolutePath) val computed = spark.read .schema(df.schema) .csv(path.getAbsolutePath) val expected = Seq( (1, "John Doe"), (2, litNull), (3, "-"), (4, litNull) ).toDF("id", "name") checkAnswer(computed, expected) } } test("SPARK-24329: skip lines with comments, and one or multiple whitespaces") { val schema = new StructType().add("colA", StringType) val ds = spark .read .schema(schema) .option("multiLine", false) .option("header", true) .option("comment", "#") .option("ignoreLeadingWhiteSpace", false) .option("ignoreTrailingWhiteSpace", false) .csv(testFile("test-data/comments-whitespaces.csv")) checkAnswer(ds, Seq(Row(""" "a" """))) } test("SPARK-24244: Select a subset of all columns") { withTempPath { path => import collection.JavaConverters._ val schema = new StructType() .add("f1", IntegerType).add("f2", IntegerType).add("f3", IntegerType) .add("f4", IntegerType).add("f5", IntegerType).add("f6", IntegerType) .add("f7", IntegerType).add("f8", IntegerType).add("f9", IntegerType) .add("f10", IntegerType).add("f11", IntegerType).add("f12", IntegerType) .add("f13", IntegerType).add("f14", IntegerType).add("f15", IntegerType) val odf = spark.createDataFrame(List( Row(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), Row(-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15) ).asJava, schema) odf.write.csv(path.getCanonicalPath) val idf = spark.read .schema(schema) .csv(path.getCanonicalPath) .select('f15, 'f10, 'f5) assert(idf.count() == 2) checkAnswer(idf, List(Row(15, 10, 5), Row(-15, -10, -5))) } } def checkHeader(multiLine: Boolean): Unit = { withSQLConf(SQLConf.CASE_SENSITIVE.key -> "true") { withTempPath { path => val oschema = new StructType().add("f1", DoubleType).add("f2", DoubleType) val odf = spark.createDataFrame(List(Row(1.0, 1234.5)).asJava, oschema) odf.write.option("header", true).csv(path.getCanonicalPath) val ischema = new StructType().add("f2", DoubleType).add("f1", DoubleType) val exception = intercept[SparkException] { spark.read .schema(ischema) .option("multiLine", multiLine) .option("header", true) .option("enforceSchema", false) .csv(path.getCanonicalPath) .collect() } assert(exception.getMessage.contains("CSV header does not conform to the schema")) val shortSchema = new StructType().add("f1", DoubleType) val exceptionForShortSchema = intercept[SparkException] { spark.read .schema(shortSchema) .option("multiLine", multiLine) .option("header", true) .option("enforceSchema", false) .csv(path.getCanonicalPath) .collect() } assert(exceptionForShortSchema.getMessage.contains( "Number of column in CSV header is not equal to number of fields in the schema")) val longSchema = new StructType() .add("f1", DoubleType) .add("f2", DoubleType) .add("f3", DoubleType) val exceptionForLongSchema = intercept[SparkException] { spark.read .schema(longSchema) .option("multiLine", multiLine) .option("header", true) .option("enforceSchema", false) .csv(path.getCanonicalPath) .collect() } assert(exceptionForLongSchema.getMessage.contains("Header length: 2, schema size: 3")) val caseSensitiveSchema = new StructType().add("F1", DoubleType).add("f2", DoubleType) val caseSensitiveException = intercept[SparkException] { spark.read .schema(caseSensitiveSchema) .option("multiLine", multiLine) .option("header", true) .option("enforceSchema", false) .csv(path.getCanonicalPath) .collect() } assert(caseSensitiveException.getMessage.contains( "CSV header does not conform to the schema")) } } } test(s"SPARK-23786: Checking column names against schema in the multiline mode") { checkHeader(multiLine = true) } test(s"SPARK-23786: Checking column names against schema in the per-line mode") { checkHeader(multiLine = false) } test("SPARK-23786: CSV header must not be checked if it doesn't exist") { withTempPath { path => val oschema = new StructType().add("f1", DoubleType).add("f2", DoubleType) val odf = spark.createDataFrame(List(Row(1.0, 1234.5)).asJava, oschema) odf.write.option("header", false).csv(path.getCanonicalPath) val ischema = new StructType().add("f2", DoubleType).add("f1", DoubleType) val idf = spark.read .schema(ischema) .option("header", false) .option("enforceSchema", false) .csv(path.getCanonicalPath) checkAnswer(idf, odf) } } test("SPARK-23786: Ignore column name case if spark.sql.caseSensitive is false") { withSQLConf(SQLConf.CASE_SENSITIVE.key -> "false") { withTempPath { path => val oschema = new StructType().add("A", StringType) val odf = spark.createDataFrame(List(Row("0")).asJava, oschema) odf.write.option("header", true).csv(path.getCanonicalPath) val ischema = new StructType().add("a", StringType) val idf = spark.read.schema(ischema) .option("header", true) .option("enforceSchema", false) .csv(path.getCanonicalPath) checkAnswer(idf, odf) } } } test("SPARK-23786: check header on parsing of dataset of strings") { val ds = Seq("columnA,columnB", "1.0,1000.0").toDS() val ischema = new StructType().add("columnB", DoubleType).add("columnA", DoubleType) val exception = intercept[IllegalArgumentException] { spark.read.schema(ischema).option("header", true).option("enforceSchema", false).csv(ds) } assert(exception.getMessage.contains("CSV header does not conform to the schema")) } test("SPARK-23786: enforce inferred schema") { val expectedSchema = new StructType().add("_c0", DoubleType).add("_c1", StringType) val withHeader = spark.read .option("inferSchema", true) .option("enforceSchema", false) .option("header", true) .csv(Seq("_c0,_c1", "1.0,a").toDS()) assert(withHeader.schema == expectedSchema) checkAnswer(withHeader, Seq(Row(1.0, "a"))) // Ignore the inferSchema flag if an user sets a schema val schema = new StructType().add("colA", DoubleType).add("colB", StringType) val ds = spark.read .option("inferSchema", true) .option("enforceSchema", false) .option("header", true) .schema(schema) .csv(Seq("colA,colB", "1.0,a").toDS()) assert(ds.schema == schema) checkAnswer(ds, Seq(Row(1.0, "a"))) val exception = intercept[IllegalArgumentException] { spark.read .option("inferSchema", true) .option("enforceSchema", false) .option("header", true) .schema(schema) .csv(Seq("col1,col2", "1.0,a").toDS()) } assert(exception.getMessage.contains("CSV header does not conform to the schema")) } test("SPARK-23786: warning should be printed if CSV header doesn't conform to schema") { class TestAppender extends AppenderSkeleton { var events = new java.util.ArrayList[LoggingEvent] override def close(): Unit = {} override def requiresLayout: Boolean = false protected def append(event: LoggingEvent): Unit = events.add(event) } val testAppender1 = new TestAppender withLogAppender(testAppender1) { val ds = Seq("columnA,columnB", "1.0,1000.0").toDS() val ischema = new StructType().add("columnB", DoubleType).add("columnA", DoubleType) spark.read.schema(ischema).option("header", true).option("enforceSchema", true).csv(ds) } assert(testAppender1.events.asScala .exists(msg => msg.getRenderedMessage.contains("CSV header does not conform to the schema"))) val testAppender2 = new TestAppender withLogAppender(testAppender2) { withTempPath { path => val oschema = new StructType().add("f1", DoubleType).add("f2", DoubleType) val odf = spark.createDataFrame(List(Row(1.0, 1234.5)).asJava, oschema) odf.write.option("header", true).csv(path.getCanonicalPath) val ischema = new StructType().add("f2", DoubleType).add("f1", DoubleType) spark.read .schema(ischema) .option("header", true) .option("enforceSchema", true) .csv(path.getCanonicalPath) .collect() } } assert(testAppender2.events.asScala .exists(msg => msg.getRenderedMessage.contains("CSV header does not conform to the schema"))) } test("SPARK-25134: check header on parsing of dataset with projection and column pruning") { withSQLConf(SQLConf.CSV_PARSER_COLUMN_PRUNING.key -> "true") { Seq(false, true).foreach { multiLine => withTempPath { path => val dir = path.getAbsolutePath Seq(("a", "b")).toDF("columnA", "columnB").write .format("csv") .option("header", true) .save(dir) // schema with one column checkAnswer(spark.read .format("csv") .option("header", true) .option("enforceSchema", false) .option("multiLine", multiLine) .load(dir) .select("columnA"), Row("a")) // empty schema assert(spark.read .format("csv") .option("header", true) .option("enforceSchema", false) .option("multiLine", multiLine) .load(dir) .count() === 1L) } } } } test("SPARK-24645 skip parsing when columnPruning enabled and partitions scanned only") { withSQLConf(SQLConf.CSV_PARSER_COLUMN_PRUNING.key -> "true") { withTempPath { path => val dir = path.getAbsolutePath spark.range(10).selectExpr("id % 2 AS p", "id").write.partitionBy("p").csv(dir) checkAnswer(spark.read.csv(dir).selectExpr("sum(p)"), Row(5)) } } } test("SPARK-24676 project required data from parsed data when columnPruning disabled") { withSQLConf(SQLConf.CSV_PARSER_COLUMN_PRUNING.key -> "false") { withTempPath { path => val dir = path.getAbsolutePath spark.range(10).selectExpr("id % 2 AS p", "id AS c0", "id AS c1").write.partitionBy("p") .option("header", "true").csv(dir) val df1 = spark.read.option("header", true).csv(dir).selectExpr("sum(p)", "count(c0)") checkAnswer(df1, Row(5, 10)) // empty required column case val df2 = spark.read.option("header", true).csv(dir).selectExpr("sum(p)") checkAnswer(df2, Row(5)) } // the case where tokens length != parsedSchema length withTempPath { path => val dir = path.getAbsolutePath Seq("1,2").toDF().write.text(dir) // more tokens val df1 = spark.read.schema("c0 int").format("csv").option("mode", "permissive").load(dir) checkAnswer(df1, Row(1)) // less tokens val df2 = spark.read.schema("c0 int, c1 int, c2 int").format("csv") .option("mode", "permissive").load(dir) checkAnswer(df2, Row(1, 2, null)) } } } test("count() for malformed input") { def countForMalformedCSV(expected: Long, input: Seq[String]): Unit = { val schema = new StructType().add("a", IntegerType) val strings = spark.createDataset(input) val df = spark.read.schema(schema).option("header", false).csv(strings) assert(df.count() == expected) } def checkCount(expected: Long): Unit = { val validRec = "1" val inputs = Seq( Seq("{-}", validRec), Seq(validRec, "?"), Seq("0xAC", validRec), Seq(validRec, "0.314"), Seq("\\\\\\\\\\\\", validRec) ) inputs.foreach { input => countForMalformedCSV(expected, input) } } checkCount(2) countForMalformedCSV(0, Seq("")) } test("SPARK-25387: bad input should not cause NPE") { val schema = StructType(StructField("a", IntegerType) :: Nil) val input = spark.createDataset(Seq("\\u0000\\u0000\\u0001234")) checkAnswer(spark.read.schema(schema).csv(input), Row(null)) checkAnswer(spark.read.option("multiLine", true).schema(schema).csv(input), Row(null)) assert(spark.read.csv(input).collect().toSet == Set(Row())) } test("field names of inferred schema shouldn't compare to the first row") { val input = Seq("1,2").toDS() val df = spark.read.option("enforceSchema", false).csv(input) checkAnswer(df, Row("1", "2")) } test("using the backward slash as the delimiter") { val input = Seq("""abc\\1""").toDS() val delimiter = """\\\\""" checkAnswer(spark.read.option("delimiter", delimiter).csv(input), Row("abc", "1")) checkAnswer(spark.read.option("inferSchema", true).option("delimiter", delimiter).csv(input), Row("abc", 1)) val schema = new StructType().add("a", StringType).add("b", IntegerType) checkAnswer(spark.read.schema(schema).option("delimiter", delimiter).csv(input), Row("abc", 1)) } test("using spark.sql.columnNameOfCorruptRecord") { withSQLConf(SQLConf.COLUMN_NAME_OF_CORRUPT_RECORD.key -> "_unparsed") { val csv = "\\"" val df = spark.read .schema("a int, _unparsed string") .csv(Seq(csv).toDS()) checkAnswer(df, Row(null, csv)) } } test("encoding in multiLine mode") { val df = spark.range(3).toDF() Seq("UTF-8", "ISO-8859-1", "CP1251", "US-ASCII", "UTF-16BE", "UTF-32LE").foreach { encoding => Seq(true, false).foreach { header => withTempPath { path => df.write .option("encoding", encoding) .option("header", header) .csv(path.getCanonicalPath) val readback = spark.read .option("multiLine", true) .option("encoding", encoding) .option("inferSchema", true) .option("header", header) .csv(path.getCanonicalPath) checkAnswer(readback, df) } } } } test("""Support line separator - default value \\r, \\r\\n and \\n""") { val data = "\\"a\\",1\\r\\"c\\",2\\r\\n\\"d\\",3\\n" withTempPath { path => Files.write(path.toPath, data.getBytes(StandardCharsets.UTF_8)) val df = spark.read.option("inferSchema", true).csv(path.getAbsolutePath) val expectedSchema = StructType(StructField("_c0", StringType) :: StructField("_c1", IntegerType) :: Nil) checkAnswer(df, Seq(("a", 1), ("c", 2), ("d", 3)).toDF()) assert(df.schema === expectedSchema) } } def testLineSeparator(lineSep: String, encoding: String, inferSchema: Boolean, id: Int): Unit = { test(s"Support line separator in ${encoding} #${id}") { // Read val data = s""""a",1$lineSep |c,2$lineSep" |d",3""".stripMargin val dataWithTrailingLineSep = s"$data$lineSep" Seq(data, dataWithTrailingLineSep).foreach { lines => withTempPath { path => Files.write(path.toPath, lines.getBytes(encoding)) val schema = StructType(StructField("_c0", StringType) :: StructField("_c1", LongType) :: Nil) val expected = Seq(("a", 1), ("\\nc", 2), ("\\nd", 3)) .toDF("_c0", "_c1") Seq(false, true).foreach { multiLine => val reader = spark .read .option("lineSep", lineSep) .option("multiLine", multiLine) .option("encoding", encoding) val df = if (inferSchema) { reader.option("inferSchema", true).csv(path.getAbsolutePath) } else { reader.schema(schema).csv(path.getAbsolutePath) } checkAnswer(df, expected) } } } // Write withTempPath { path => Seq("a", "b", "c").toDF("value").coalesce(1) .write .option("lineSep", lineSep) .option("encoding", encoding) .csv(path.getAbsolutePath) val partFile = TestUtils.recursiveList(path).filter(f => f.getName.startsWith("part-")).head val readBack = new String(Files.readAllBytes(partFile.toPath), encoding) assert( readBack === s"a${lineSep}b${lineSep}c${lineSep}") } // Roundtrip withTempPath { path => val df = Seq("a", "b", "c").toDF() df.write .option("lineSep", lineSep) .option("encoding", encoding) .csv(path.getAbsolutePath) val readBack = spark .read .option("lineSep", lineSep) .option("encoding", encoding) .csv(path.getAbsolutePath) checkAnswer(df, readBack) } } } // scalastyle:off nonascii List( (0, "|", "UTF-8", false), (1, "^", "UTF-16BE", true), (2, ":", "ISO-8859-1", true), (3, "!", "UTF-32LE", false), (4, 0x1E.toChar.toString, "UTF-8", true), (5, "아", "UTF-32BE", false), (6, "у", "CP1251", true), (8, "\\r", "UTF-16LE", true), (9, "\\u000d", "UTF-32BE", false), (10, "=", "US-ASCII", false), (11, "$", "utf-32le", true) ).foreach { case (testNum, sep, encoding, inferSchema) => testLineSeparator(sep, encoding, inferSchema, testNum) } // scalastyle:on nonascii test("lineSep restrictions") { val errMsg1 = intercept[IllegalArgumentException] { spark.read.option("lineSep", "").csv(testFile(carsFile)).collect }.getMessage assert(errMsg1.contains("'lineSep' cannot be an empty string")) val errMsg2 = intercept[IllegalArgumentException] { spark.read.option("lineSep", "123").csv(testFile(carsFile)).collect }.getMessage assert(errMsg2.contains("'lineSep' can contain only 1 character")) } test("SPARK-26208: write and read empty data to csv file with headers") { withTempPath { path => val df1 = spark.range(10).repartition(2).filter(_ < 0).map(_.toString).toDF // we have 2 partitions but they are both empty and will be filtered out upon writing // thanks to SPARK-23271 one new empty partition will be inserted df1.write.format("csv").option("header", true).save(path.getAbsolutePath) val df2 = spark.read.format("csv").option("header", true).option("inferSchema", false) .load(path.getAbsolutePath) assert(df1.schema === df2.schema) checkAnswer(df1, df2) } } test("do not produce empty files for empty partitions") { withTempPath { dir => val path = dir.getCanonicalPath spark.emptyDataset[String].write.csv(path) val files = new File(path).listFiles() assert(!files.exists(_.getName.endsWith("csv"))) } } test("Do not reuse last good value for bad input field") { val schema = StructType( StructField("col1", StringType) :: StructField("col2", DateType) :: Nil ) val rows = spark.read .schema(schema) .format("csv") .load(testFile(badAfterGoodFile)) val expectedRows = Seq( Row("good record", java.sql.Date.valueOf("1999-08-01")), Row("bad record", null)) checkAnswer(rows, expectedRows) } test("SPARK-27512: Decimal type inference should not handle ',' for backward compatibility") { assert(spark.read .option("delimiter", "|") .option("inferSchema", "true") .csv(Seq("1,2").toDS).schema.head.dataType === StringType) } test("SPARK-27873: disabling enforceSchema should not fail columnNameOfCorruptRecord") { Seq("csv", "").foreach { reader => withSQLConf(SQLConf.USE_V1_SOURCE_READER_LIST.key -> reader) { withTempPath { path => val df = Seq(("0", "2013-111-11")).toDF("a", "b") df.write .option("header", "true") .csv(path.getAbsolutePath) val schema = StructType.fromDDL("a int, b date") val columnNameOfCorruptRecord = "_unparsed" val schemaWithCorrField = schema.add(columnNameOfCorruptRecord, StringType) val readDF = spark .read .option("mode", "Permissive") .option("header", "true") .option("enforceSchema", false) .option("columnNameOfCorruptRecord", columnNameOfCorruptRecord) .schema(schemaWithCorrField) .csv(path.getAbsoluteFile.toString) checkAnswer(readDF, Row(0, null, "0,2013-111-11") :: Nil) } } } } test("SPARK-28431: prevent CSV datasource throw TextParsingException with large size message") { withTempPath { path => val maxCharsPerCol = 10000 val str = "a" * (maxCharsPerCol + 1) Files.write( path.toPath, str.getBytes(StandardCharsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE ) val errMsg = intercept[TextParsingException] { spark.read .option("maxCharsPerColumn", maxCharsPerCol) .csv(path.getAbsolutePath) .count() }.getMessage assert(errMsg.contains("..."), "expect the TextParsingException truncate the error content to be 1000 length.") } } }
techaddict/spark
sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/csv/CSVSuite.scala
Scala
apache-2.0
71,591
/** * Original work: Swagger Codegen (https://github.com/swagger-api/swagger-codegen) * Copyright 2016 Swagger (http://swagger.io) * * Derivative work: Swagger Codegen - Play Scala (https://github.com/mohiva/swagger-codegen-play-scala) * Modifications Copyright 2016 Mohiva Organisation (license at mohiva dot com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.mohiva.swagger.codegen.core import akka.stream.scaladsl.{ Source, StreamConverters } import akka.util.ByteString import com.mohiva.swagger.codegen.core.ApiRequest._ import play.api.http.MediaType import play.api.libs.json._ import play.api.libs.ws._ import play.api.mvc.MultipartFormData.{ DataPart, FilePart, Part } import scala.concurrent.Future import scala.reflect.ClassTag /** * Some default Json formats. */ object ApiJsonFormats { /** * Converts an enum value to Json and vice versa. */ implicit def enumValueFormat[T <: Enumeration: ClassTag]: Format[T#Value] = new Format[T#Value] { def reads(json: JsValue): JsResult[T#Value] = { val c = implicitly[ClassTag[T]].runtimeClass val enum = c.getField("MODULE$").get(null).asInstanceOf[T] json.asOpt[String].map { value => enum.values.find(_.toString == value) match { case Some(v) => JsSuccess(v) case _ => JsError("invalid") } } getOrElse JsError("string") } def writes(value: T#Value): JsValue = JsString(value.toString) } } /** * Some API param types and implicits. */ object ApiParams { /** * Extractor used to unapply empty values only in pattern matching. */ object EmptyValue { def unapply(n: Any): Option[Any] = n match { case (None | Seq() | "" | ArrayValues(Seq(), _)) => Some(n) case _ => None } } /** * Case class used to unapply numeric values only in pattern matching. */ sealed case class NumericValue(value: String) object NumericValue { def unapply(n: Any): Option[NumericValue] = n match { case (_: Int | _: Long | _: Float | _: Double | _: Boolean | _: Byte) => Some(NumericValue(String.valueOf(n))) case _ => None } } /** * Used for params being arrays. */ sealed case class ArrayValues(values: Seq[Any], format: CollectionFormat = CollectionFormats.CSV) object ArrayValues { def apply(values: Option[Seq[Any]], format: CollectionFormat): ArrayValues = ArrayValues(values.getOrElse(Seq.empty), format) def apply(values: Option[Seq[Any]]): ArrayValues = ArrayValues(values, CollectionFormats.CSV) } /** * Defines how arrays should be rendered in query strings. */ sealed trait CollectionFormat object CollectionFormats { trait MergedArrayFormat extends CollectionFormat { def separator: String } case object CSV extends MergedArrayFormat { override val separator = "," } case object TSV extends MergedArrayFormat { override val separator = "\\t" } case object SSV extends MergedArrayFormat { override val separator = " " } case object PIPES extends MergedArrayFormat { override val separator = "|" } case object MULTI extends CollectionFormat } /** * Normalize `Map[String, Any]` parameters so that it can be used without hassle. * * None values will be filtered out. */ implicit class AnyMapNormalizers(val m: Map[String, Any]) { def normalize: Seq[(String, Any)] = m.mapValues(_.normalize).toSeq.flatMap { case (_, EmptyValue(_)) => Seq() case (name, ArrayValues(values, format)) if format == CollectionFormats.MULTI => val containsFile = (value: Any) => value match { case _: ApiFile => true case _ => false } if (values.exists(containsFile)) { values.zipWithIndex.map { case (v, i) => name + i.toString -> v } } else { values.map { v => name -> v } } case (k, v) => Seq(k -> v) } } /** * Normalize `Any` parameters so that it can be used without hassle. */ implicit class AnyParametersNormalizer(value: Any) { import CollectionFormats._ def normalize: Any = { def n(value: Any): Any = value match { case Some(opt) => n(opt) case arr @ ArrayValues(values, CollectionFormats.MULTI) => arr.copy(values.map(n)) case ArrayValues(values, format: MergedArrayFormat) => values.mkString(format.separator) case sequence: Seq[Any] => n(ArrayValues(sequence)) case NumericValue(numeric) => numeric.value case v => v } n(value) } } } /** * A Play request. */ trait PlayRequest { /** * Executes the request. * * @return A response. */ def execute(): Future[WSResponse] } /** * The companion object of the [[PlayRequest]]. */ object PlayRequest { import ApiParams._ /** * An implicits that allows to convert an API request into a Play request. * * @param apiRequest The API request to convert. */ implicit class ApiRequestToPlayRequest(apiRequest: ApiRequest) { /** * Converts an API request to a Play request. * * @param config The global API config. * @param wsClient The Play WS client. * @return A Play request. */ def toPlay(config: ApiConfig, wsClient: WSClient): PlayRequest = new PlayRequest { /** * A request pipeline. */ type Pipeline = PartialFunction[WSRequest, WSRequest] /** * The request pipeline. */ private val requestPipeline = requestTimeoutPipeline andThen requestMethodPipeline andThen authenticationPipeline andThen headerPipeline andThen queryPipeline /** * The complete configured request to execute. */ private val request = requestPipeline(wsClient.url(url)) /** * Executes the request. * * @return A response. */ def execute(): Future[WSResponse] = request.execute() /** * Builds the URL to which the request should be sent. * * Searches in the following locations in the following order: * - request config * - global config * - Swagger SPEC file * * @return The URL to which the request should be sent. */ private def url: String = { val base = apiRequest.config.url.getOrElse(config.url.getOrElse(apiRequest.basePath)) val path = apiRequest.operationPath.replaceAll("\\\\{format\\\\}", "json") val pathParams = apiRequest.pathParams.normalize .foldLeft(path) { case (p, (name, value)) => p.replaceAll(s"\\\\{$name\\\\}", String.valueOf(value)) } base.stripSuffix("/") + pathParams } /** * Adds the request method, and the body based on the this method. * * The body will be sent only for the following request methods: * - POST * - PUT * - PATCH * - DELETE */ private def requestMethodPipeline: Pipeline = { case wsRequest => apiRequest.method match { case RequestMethod.POST | RequestMethod.PUT | RequestMethod.PATCH | RequestMethod.DELETE => bodyPipeline(wsRequest.withMethod(apiRequest.method.name)) case _ => wsRequest.withMethod(apiRequest.method.name) } } /** * Adds the request timeout. */ private def requestTimeoutPipeline: Pipeline = { case wsRequest => wsRequest.withRequestTimeout(apiRequest.config.timeout.getOrElse(config.requestTimeout)) } /** * Ads the body. * * First it checks the `bodyParam` of the API request and then it checks the form part of the request. */ private def bodyPipeline: Pipeline = { case wsRequest => apiRequest.bodyParam.normalize match { case file: ApiFile => wsRequest.withBody(StreamConverters.fromInputStream(() => file.content)) case NumericValue(numeric) => wsRequest.withBody(numeric.value) case string: String => wsRequest.withBody(String.valueOf(string)) case json: JsValue => wsRequest.withBody(json) case _ => val contentType = apiRequest.contentType.flatMap(MediaType.parse.apply).map(mt => mt.mediaType + "/" + mt.mediaSubType) apiRequest.formParams.normalize match { case p if p.isEmpty => wsRequest case p if contentType.contains("multipart/form-data") => val body = p.foldLeft(List[Part[Source[ByteString, Any]]]()) { case (parts, (key, value)) => value match { case f: ApiFile => parts :+ FilePart(key, f.name, None, StreamConverters.fromInputStream(() => f.content)) case _ => parts :+ DataPart(key, String.valueOf(value)) } } wsRequest.withBody(Source(body))(WSBodyWritables.bodyWritableOf_Multipart) case p => // default: application/x-www-form-urlencoded wsRequest.withBody(p.toMap.mapValues(v => Seq(String.valueOf(v)))) } } } /** * Adds the authentication. */ private def authenticationPipeline: Pipeline = { case wsRequest => apiRequest.credentials.foldLeft(wsRequest) { case (req, BasicCredentials(username, password)) => req.withAuth(username, password, WSAuthScheme.BASIC) case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) => req.addHttpHeaders(keyName -> keyValue.value) case (req, _) => req } } /** * Adds the headers. */ private def headerPipeline: Pipeline = { case wsRequest => wsRequest.addHttpHeaders(apiRequest.headerParams.normalize.map { case (k, v) => k -> String.valueOf(v) }: _*) } /** * Adds the query params. */ private def queryPipeline: Pipeline = { case wsRequest => val queryParams = apiRequest.credentials.foldLeft(apiRequest.queryParams) { case (params, ApiKeyCredentials(key, keyName, ApiKeyLocations.QUERY)) => params + (keyName -> key.value) case (params, _) => params }.normalize.map { case (k, v) => k -> String.valueOf(v) } wsRequest.addQueryStringParameters(queryParams.toList: _*) } } } }
akkie/swagger-codegen-play-scala
clientstub/src/main/scala/com/mohiva/swagger/codegen/core/ApiImplicits.scala
Scala
apache-2.0
11,120
package play.api import play.api.mvc._ /** * A Play plugin. * * You can define a Play plugin this way: * {{{ * class MyPlugin(app: Application) extends Plugin * }}} * * The plugin class must be declared in a play.plugins file available in the classpath root: * {{{ * 1000:myapp.MyPlugin * }}} * The associated int defines the plugin priority. */ trait Plugin { /** * Called when the application starts. */ def onStart() {} /** * Called when the application stops. */ def onStop() {} /** * Is the plugin enabled? */ def enabled: Boolean = true }
noel-yap/setter-for-catan
play-2.1.1/framework/src/play/src/main/scala/play/api/Plugins.scala
Scala
apache-2.0
595
package org.scalamu.report import org.scalamu.core.coverage.Statement import org.scalamu.core.api.{SourceInfo, TestedMutant} import org.scalamu.core.testapi.AbstractTestSuite import scala.io.Source import scala.collection.{Map, Set, SortedSet} final case class SourceFileSummary( name: String, lines: Seq[Line], statements: Set[Statement], coveredStatements: Set[Statement], mutantsByLine: Map[Int, Set[TestedMutant]], exercisedTests: SortedSet[AbstractTestSuite] ) extends CoverageStats { override def mutants: Set[TestedMutant] = mutantsByLine.values.flatMap(identity)(collection.breakOut) } object SourceFileSummary { def apply( info: SourceInfo, statements: Set[Statement], invoked: Set[Statement], mutants: Set[TestedMutant], tests: Set[AbstractTestSuite] ): SourceFileSummary = { val mutantsByLine = mutants.groupBy(_.info.pos.line) val lines = Source .fromFile(info.fullPath.toFile, "utf-8") .getLines() .zipWithIndex .map { case (contents, number) => val lineNumber = number + 1 Line(contents, lineNumber, mutantsByLine.getOrElse(lineNumber, Set.empty)) } .toSeq implicit val testSuiteOrdering: Ordering[AbstractTestSuite] = Ordering.by[AbstractTestSuite, String](_.toString) SourceFileSummary( info.name.toString, lines, statements, invoked, mutantsByLine, tests.to[SortedSet] ) } }
sugakandrey/scalamu
report/src/main/scala/org/scalamu/report/SourceFileSummary.scala
Scala
gpl-3.0
1,464
/* * Distributed as part of Scalala, a linear algebra library. * * Copyright (C) 2008- Daniel Ramage * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110 USA */ package scalala; package tensor; import scalar.Scalar; import domain._; import scalala.generic.collection._; import scalala.operators._; import generic.TensorTriplesMonadic; /** * Implementation trait for tensors indexed by two keys, such as Matrices. * * TODO: Make up mind about whether implementing classes should provide * which one (or both) of the pairs interface and triples interface. * * @author dramage */ trait Tensor2Like [@specialized(Int) K1, @specialized(Int) K2, @specialized(Int,Long,Float,Double,Boolean) V, +D1<:Domain1[K1], +D2<:Domain1[K2], +D<:Domain2[K1,K2], +T<:Domain2[K2,K1], +This<:Tensor2[K1,K2,V]] extends TensorLike[(K1,K2),V,D,This] with operators.MatrixOps[This] { self => def checkKey(k1 : K1, k2 : K2) : Unit = { if (!domain._1.contains(k1) || !domain._2.contains(k2)) { throw new DomainException((k1,k2)+" not in domain"); } } /* final */ override def checkKey(pos : (K1,K2)) : Unit = checkKey(pos._1, pos._2); /** Gets the value indexed by (i,j). */ def apply(i : K1, j : K2) : V; /** Fixed alias for apply(i,j). */ /* final */ override def apply(pos : (K1,K2)) : V = apply(pos._1, pos._2); /** Select all columns within a given row. */ def apply[TT>:This,That](i : K1, j : SelectAll)(implicit bf : CanSliceRow[TT,K1,That]) : That = bf.apply(repr, i); /** Select all rows within a given column. */ def apply[TT>:This,That](i : SelectAll, j : K2)(implicit bf : CanSliceCol[TT,K2,That]) : That = bf.apply(repr, j); /** Select a sub-matrix of the requested rows and columns. */ def apply[TT>:This,That](i : Seq[K1], j : Seq[K2])(implicit bf : CanSliceMatrix[TT,K1,K2,That]) : That = bf.apply(repr, i, j); /** Select all columns for a specified set of rows. */ def apply[TT>:This,That](i : Seq[K1], j : SelectAll)(implicit bf : CanSliceMatrix[TT,K1,K2,That]) : That = bf.apply(repr, i, domain._2.toIndexedSeq); /** Select all rows for a specified set of columns. */ def apply[TT>:This,That](i : SelectAll, j : Seq[K2])(implicit bf : CanSliceMatrix[TT,K1,K2,That]) : That = bf.apply(repr, domain._1.toIndexedSeq, j); /** Select specified columns within a row. */ def apply[TT>:This,That1,That2](i : K1, j : IndexedSeq[K2]) (implicit s1 : CanSliceRow[TT,K1,That1], s2 : CanSliceVector[That1,K2,That2]) : That2 = s2.apply(s1.apply(repr, i), j); /** Select specified rows within a column. */ def apply[TT>:This,That1,That2](i : IndexedSeq[K1], j : K2) (implicit s1 : CanSliceCol[TT,K2,That1], s2 : CanSliceVector[That1,K1,That2]) : That2 = s2.apply(s1.apply(repr, j), i); /** Transpose of the matrix. */ def t : Tensor2[K2,K1,V] = new Tensor2Transpose.Impl[K2,K1,V,This](repr); // // triples accessors // def triples : TensorTriplesMonadic[K1,K2,V,This] = new TensorTriplesMonadic[K1,K2,V,This] { override def repr = self.repr; } def foreachTriple[U](fn : (K1,K2,V)=>U) : Unit = foreachPair((k,v) => fn(k._1, k._2, v)); def foreachNonZeroTriple[U](fn : (K1,K2,V)=>U) : Boolean = foreachNonZeroPair((k,v) => fn(k._1, k._2, v)); def mapTriples[TT>:This,RV,That](fn : (K1,K2,V)=>RV) (implicit bf : CanMapKeyValuePairs[TT, (K1,K2), V, RV, That]) : That = mapPairs[TT,RV,That]((k,v) => fn(k._1,k._2,v))(bf); def mapNonZeroTriples[TT>:This,RV,That](fn : (K1,K2,V)=>RV) (implicit bf : CanMapKeyValuePairs[TT, (K1,K2), V, RV, That]) : That = mapNonZeroPairs[TT,RV,That]((k,v) => fn(k._1,k._2,v))(bf); def triplesIterator : Iterator[(K1,K2,V)] = pairsIterator.map(pair => (pair._1._1,pair._1._2,pair._2)); def triplesIteratorNonZero : Iterator[(K1,K2,V)] = pairsIteratorNonZero.map(pair => (pair._1._1,pair._1._2,pair._2)); // // equality // override protected def canEqual(other : Any) : Boolean = other match { case that : Tensor2[_,_,_] => true; case _ => false; } } /** * Tensors indexed by two keys, such as matrices. * * @author dramage */ trait Tensor2 [@specialized(Int) K1, @specialized(Int) K2, @specialized(Int,Long,Float,Double,Boolean) V] extends Tensor[(K1,K2),V] with Tensor2Like[K1,K2,V,Domain1[K1],Domain1[K2],Domain2[K1,K2],Domain2[K2,K1],Tensor2[K1,K2,V]] object Tensor2 { /** Constructs a tensor for the given domain. */ def apply[K1,K2,V:Scalar](domain : Domain2[K1,K2]) = mutable.Tensor2.apply(domain); implicit def canSliceRow[T2<:Tensor2[K1,K2,V],K1,K2,V:Scalar] : CanSliceRow[Tensor2[K1,K2,V],K1,Tensor1Row[K2,V]] = new CanSliceRow[Tensor2[K1,K2,V],K1,Tensor1Row[K2,V]] { override def apply(from : Tensor2[K1,K2,V], row : K1) = new RowSliceImpl[K1,K2,V,Tensor2[K1,K2,V]](from,row); } implicit def canSliceCol[K1,K2,V:Scalar] : CanSliceCol[Tensor2[K1,K2,V],K2,Tensor1Col[K1,V]] = new CanSliceCol[Tensor2[K1,K2,V],K2,Tensor1Col[K1,V]] { override def apply(from : Tensor2[K1,K2,V], col : K2) = new ColSliceImpl[K1,K2,V,Tensor2[K1,K2,V]](from, col); } implicit def canSliceMatrix[K1,K2,V:Scalar] : CanSliceMatrix[Tensor2[K1,K2,V],K1,K2,Matrix[V]] = new CanSliceMatrix[Tensor2[K1,K2,V],K1,K2,Matrix[V]] { override def apply(from : Tensor2[K1,K2,V], keys1 : Seq[K1], keys2 : Seq[K2]) = new MatrixSliceImpl[K1,K2,V,Tensor2[K1,K2,V]](from, keys1, keys2); } implicit def canMulTensor2ByTensor1Col[ @specialized(Int) K1, @specialized(Int) K2, @specialized(Int,Double) V1, K, AR, ADomainRow, ADomainCol, ADomain, @specialized(Int,Double) V2, V, BD, @specialized(Int,Double) RV, That] (implicit viewA : K=>Tensor2[K1,K2,V1], sliceA : CanSliceRow[K,K1,AR], domainA : CanGetDomain2[K,ADomainRow,ADomainCol,ADomain], viewB : V=>Tensor1Col[K2,V2], mul : BinaryOp[AR,V,OpMulRowVectorBy,RV], bf : CanBuildTensorFrom[V,ADomainRow,K1,RV,That], scalar : Scalar[RV]) : BinaryOp[K, V, OpMulMatrixBy, That] = new BinaryOp[K, V, OpMulMatrixBy, That] { override def opType = OpMulMatrixBy; override def apply(a : K, b : V) = { val builder = bf(b, domainA._1(a)); for (i <- a.domain._1) { builder(i) = mul(sliceA(a,i), b); } builder.result; } } implicit def canMulMatrixByMatrix[ @specialized(Int) K1, @specialized(Int) K2, @specialized(Int) K3, @specialized(Int,Double) V1, A, ARow, ADomainRow, InnerDomain, ADomain, @specialized(Int,Double) V2, B, BCol, BDomainCol, BDomain, @specialized(Int,Double) RV, RDomain, That] (implicit viewA : A=>Tensor2[K1,K2,V1], sliceA : CanSliceRow[A,K1,ARow], domainA : CanGetDomain2[A,ADomainRow,InnerDomain,ADomain], viewB : B=>Tensor2[K2,K3,V2], sliceB : CanSliceCol[B,K3,BCol], domainB : CanGetDomain2[B,InnerDomain,BDomainCol,BDomain], mul : BinaryOp[ARow,BCol,OpMulInner,RV], domainR : CanBuildDomain2[ADomainRow,BDomainCol,RDomain], bf : CanBuildTensorForBinaryOp[A,B,RDomain,(K1,K3),RV,OpMulMatrixBy,That], scalar : Scalar[RV]) : BinaryOp[A, B, OpMulMatrixBy, That] = new BinaryOp[A, B, OpMulMatrixBy, That] { override def opType = OpMulMatrixBy; override def apply(a : A, b : B) = { val domain = domainR(domainA._1(a), domainB._2(b)); val builder = bf(a, b, domain); for (i <- a.domain._1; j <- b.domain._2) { builder((i,j)) = mul(sliceA(a,i), sliceB(b,j)); } builder.result; } } trait RowSliceLike[K1,K2,V,+Coll<:Tensor2[K1,K2,V],+This<:RowSlice[K1,K2,V,Coll]] extends Tensor1SliceLike[(K1,K2),IterableDomain[(K1,K2)],K2,Domain1[K2],V,Coll,This] with Tensor1RowLike[K2,V,Domain1[K2],This] { def row : K1; override def domain = underlying.domain._2; override def size = domain.size; override def lookup(key : K2) = (row,key); } trait RowSlice[K1,K2,V,+Coll<:Tensor2[K1,K2,V]] extends Tensor1Slice[(K1,K2),K2,V,Coll] with Tensor1Row[K2,V] with RowSliceLike[K1,K2,V,Coll,RowSlice[K1,K2,V,Coll]]; class RowSliceImpl[K1,K2,V,+Coll<:Tensor2[K1,K2,V]] (override val underlying : Coll, override val row : K1) (implicit override val scalar : Scalar[V]) extends RowSlice[K1,K2,V,Coll]; trait ColSliceLike[K1,K2,V,+Coll<:Tensor2[K1,K2,V],+This<:ColSlice[K1,K2,V,Coll]] extends Tensor1SliceLike[(K1,K2),IterableDomain[(K1,K2)],K1,Domain1[K1],V,Coll,This] with Tensor1ColLike[K1,V,Domain1[K1],This] { def col : K2; override val domain = underlying.domain._1; override def size = domain.size; override def lookup(key : K1) = (key,col); } trait ColSlice[K1,K2,V,+Coll<:Tensor2[K1,K2,V]] extends Tensor1Slice[(K1,K2),K1,V,Coll] with Tensor1Col[K1,V] with ColSliceLike[K1,K2,V,Coll,ColSlice[K1,K2,V,Coll]]; class ColSliceImpl[K1,K2,V,+Coll<:Tensor2[K1,K2,V]] (override val underlying : Coll, override val col : K2) (implicit override val scalar : Scalar[V]) extends ColSlice[K1,K2,V,Coll]; trait MatrixSliceLike [@specialized(Int) K1, @specialized(Int) K2, @specialized(Int,Long,Float,Double,Boolean) V, +D1<:Domain1[K1], +D2<:Domain1[K2], +D<:Domain2[K1,K2], +T<:Domain2[K2,K1], +Coll<:Tensor2[K1,K2,V], +This<:MatrixSlice[K1,K2,V,Coll]] extends TensorSliceLike[(K1,K2),D,(Int,Int),TableDomain,V,Coll,This] with MatrixLike[V,This] { def lookup1(i : Int) : K1; def lookup2(j : Int) : K2; /* final */ override def lookup(tup : (Int,Int)) = (lookup1(tup._1), lookup2(tup._2)); override def apply(i : Int, j : Int) : V = underlying.apply(lookup1(i), lookup2(j)); } trait MatrixSlice [@specialized(Int,Long) K1, @specialized(Int,Long) K2, @specialized(Int,Long,Float,Double,Boolean) V, +Coll<:Tensor2[K1,K2,V]] extends TensorSlice[(K1,K2),(Int,Int),V,Coll] with Matrix[V] with MatrixSliceLike[K1,K2,V,Domain1[K1],Domain1[K2],Domain2[K1,K2],Domain2[K2,K1],Coll,MatrixSlice[K1,K2,V,Coll]]; class MatrixSliceImpl[K1, K2, V, +Coll<:Tensor2[K1,K2,V]] (override val underlying : Coll, val keys1 : Seq[K1], val keys2 : Seq[K2]) (implicit override val scalar : Scalar[V]) extends MatrixSlice[K1, K2, V, Coll] { override def numRows = keys1.size; override def numCols = keys2.size; override def lookup1(i : Int) = keys1(i); override def lookup2(j : Int) = keys2(j); override val domain = TableDomain(keys1.length, keys2.length); } }
scalala/Scalala
src/main/scala/scalala/tensor/Tensor2.scala
Scala
lgpl-2.1
11,090
package sample.cluster.transformation //#messages final case class TransformationJob(text: String) final case class TransformationResult(text: String) final case class JobFailed(reason: String, job: TransformationJob) case object BackendRegistration //#messages
jastice/intellij-scala
scala/scala-impl/testdata/localProjects/akka-samples/src/main/scala/sample/cluster/transformation/TransformationMessages.scala
Scala
apache-2.0
263
package beam.agentsim.infrastructure case class ParkingInquiryResponse(stall: ParkingStall, requestId: Int)
colinsheppard/beam
src/main/scala/beam/agentsim/infrastructure/ParkingInquiryResponse.scala
Scala
gpl-3.0
109
package svstm.vbox class VBoxBody[+A](val value: A, val version: Int, val next: VBoxBody[A]) { def this(v0: A) = this(v0, 0, null) def getBody(maxVersion: Int) : VBoxBody[A] = if (version > maxVersion) next.getBody(maxVersion) else this }
fcristovao/SVSTM
src/main/scala/svstm/vbox/VBoxBody.scala
Scala
apache-2.0
259
package pl.umk.bugclassification.scmparser.git.parsers import org.slf4j.LoggerFactory import pl.umk.bugclassification.scmparser.git.parsers.results.Commit import scala.util.parsing.combinator.RegexParsers object CommitParser extends RegexParsers with CommonParser { val log = LoggerFactory.getLogger(CommitParser.getClass) override def skipWhitespace = false def commitList: Parser[List[Commit]] = commit.* //<~ (not(sha1)|not(newline)) def commit: Parser[Commit] = properCommit <~ newline.? def properCommit = (sha1 ~ author ~ date ~ message ~ filenames) ^^ { case s ~ a ~ d ~ m ~ f => { val c = new Commit(s, a, d, m, f) log.debug("parsed {Commit={}}", c) c } } def sha1: Parser[String] = ("commit(\\\\s*)".r ~> sha1Text <~ newline) ^^ (s => s) def author: Parser[String] = ("Author:(\\\\s*)".r ~> authorName <~ newline) ^^ (a => a) def date: Parser[String] = ("Date:(\\\\s*)".r ~> dateValue <~ newline) ^^ (dv => dv) def message: Parser[String] = (newline ~> messageText <~ newline.?) ^^ (mt => mt) def filenames: Parser[List[String]] = (newline.? ~> rep(filename) <~ newline.?) ^^ { case files => files} def filename: Parser[String] = "^(?!(commit [0-9a-f]{40}))\\\\S+[\\\\S ]*\\\\n".r ^^ { case s => s.trim() } def authorName: Parser[String] = ".*[^\\\\n]".r ^^ { case s => s } def dateValue: Parser[String] = "[^\\\\n]*".r ^^ { case s => s } def messageText: Parser[String] = "(\\\\s{4}.*)*".r ^^ { case s => s } def commitsFromLog(input: String): List[Commit] = parseAll(commitList, input) match { case Success(result, _) => result case failure: NoSuccess => { log.error(failure.toString) scala.sys.error(failure.toString) } } }
mfejzer/CommitClassification
src/main/scala/pl/umk/bugclassification/scmparser/git/parsers/CommitParser.scala
Scala
bsd-3-clause
1,754
package inverse_macros package object lazys { @inline final def defer[A](body: => A): A@lzy = throw LazyContext(() => body) }
hiroshi-cl/InverseMacros
inverse_macros_libraries/src/main/scala/inverse_macros/lazys/package.scala
Scala
bsd-2-clause
129
package com.scalaAsm.x86 package Instructions package General // Description: Convert Word to Doubleword // Category: general/conver trait CWD extends InstructionDefinition { val mnemonic = "CWD" } object CWD extends ZeroOperands[CWD] with CWDImpl trait CWDImpl extends CWD { implicit object _0 extends NoOp{ val opcode: OneOpcode = 0x99 override def hasImplicitOperand = true } }
bdwashbu/scala-x86-inst
src/main/scala/com/scalaAsm/x86/Instructions/General/CWD.scala
Scala
apache-2.0
403
/* * Copyright (c) 2015, Nightfall Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package moe.nightfall.instrumentality.mc194 import java.lang.ref.WeakReference import java.util.concurrent.ConcurrentLinkedQueue import moe.nightfall.instrumentality.animations.AnimSet import moe.nightfall.instrumentality.{Loader, PMXModel} import net.minecraft.client.Minecraft import net.minecraft.entity.player.EntityPlayer /** * A not-thread-safe implementation of a sort-of hashmap, for one specific purpose: * We need to know when players are deallocated from memory so we can delete their VBOs. */ object InstanceCache { // TODO SCALA Use scala classes, ACTUALLY, rewrite all of this using FP // NOTE TO WHOEVER WROTE THAT ^ : Whatever you do, the hashmap needs to use weak references in the key field private val cacheDivisions: Array[collection.mutable.Set[ModelCacheEntry]] = new Array(0x100) private val changes: ConcurrentLinkedQueue[ChangeEntry] = new ConcurrentLinkedQueue[ChangeEntry] /** * Updates existing players, * and removes GL objects used by players whose memory has been freed. * This ensures MC is done with the object by the time we free the GL object. */ def update(dt: Double) { for (div <- 0 until cacheDivisions.length) { if (cacheDivisions(div) != null) { val cache = cacheDivisions(div).clone // TODO SCALA This is ugly val i = cacheDivisions(div).iterator while (i.hasNext) { val mce = i.next() if (mce.playerRef.get() == null) { if (mce.value != null) mce.value.cleanupGL() Loader.currentFileListeners -= mce.cfHook cache.remove(mce) } else { if (mce.value != null) mce.value.update(dt) } } if (cacheDivisions(div).size == 0) cacheDivisions(div) = null } } var ch = Seq[ChangeEntry]() while (true) { val ce = changes.poll() if (ce == null) { ch.foreach((c) => changes.add(c)) return } val pent = Minecraft.getMinecraft.theWorld.getPlayerEntityByName(ce.changeTarget) if (pent == null) { // NOTE: Forge's magical stacktrace thing only works with the functions directly System.err.println("Could not apply change to \\"" + ce.changeTarget + "\\" : entity does not exist") ch = ch :+ ce } else { setModel(pent, ce.newModel, ce.newAnims) } } } /** * @param player The EntityPlayer to apply a model to. * @param model The model to apply. * @return The MCE(Note that MCEs are reused - they are always assigned to the same EntityPlayer, though.) */ def setModel(player: EntityPlayer, model: PMXModel, animSet: AnimSet): ModelCacheEntry = { val div = player.hashCode() & 0xFF00 >> 8 var dll = cacheDivisions(div) if (dll == null) { dll = collection.mutable.Set() cacheDivisions(div) = dll } var nm = dll.find(_.playerRef.get == player).orNull if (nm == null) { nm = new ModelCacheEntry() nm.playerRef = new WeakReference(player) dll += nm } else { if (nm.value != null) { nm.value.cleanupGL() nm.value = null } } if (model == null) return nm // This is the only case where nm.value ends up != null nm.value = new PlayerInstance(model, animSet) return nm } // TODO SCALA Return option def getModel(player: EntityPlayer): ModelCacheEntry = { val div = player.hashCode() & 0xFF00 >> 8 var dll = cacheDivisions(div) if (dll == null) dll = collection.mutable.Set() cacheDivisions(div) = dll return dll.find(_.playerRef.get == player) orNull } // This is how MT writes are done def queueChange(user: EntityPlayer, pm: PMXModel, as: AnimSet) { queueChange(user.getUniqueID.toString, pm, as) } def queueChange(user: String, pm: PMXModel, as: AnimSet) { val ce = new ChangeEntry(user, pm, as) changes.add(ce) } } class ModelCacheEntry { var value: PlayerInstance = null // EntityPlayer. Don't keep not-weak references long-term anywhere in the code. var playerRef: WeakReference[EntityPlayer] = null // If != null, is the currentFileListeners Runnable. Is removed from there when the MCE is removed. var cfHook: () => Unit = null } private class ChangeEntry( // Uses a string because it can be called from another thread. // Hopefully people can't change name while connected to a server, // if this is wrong, then change this to a GUID. // getCommandSenderName is used, since that's what the world uses to find a player val changeTarget: String, val newModel: PMXModel, val newAnims: AnimSet )
Nightfall/Instrumentality
mc194/src/main/scala/moe/nightfall/instrumentality/mc194/InstanceCache.scala
Scala
bsd-2-clause
6,699
/** * Generated by API Builder - https://www.apibuilder.io * Service version: 0.14.85 * apibuilder 0.14.93 app.apibuilder.io/apicollective/apibuilder-generator/latest/anorm_2_8_parsers */ package io.apibuilder.generator.v0.anorm.conversions { import anorm.{Column, MetaDataItem, TypeDoesNotMatch} import play.api.libs.json.{JsArray, JsObject, JsValue} import scala.util.{Failure, Success, Try} import play.api.libs.json.JodaReads._ /** * Conversions to collections of objects using JSON. */ object Util { def parser[T]( f: play.api.libs.json.JsValue => T ) = anorm.Column.nonNull { (value, meta) => val MetaDataItem(columnName, nullable, clazz) = meta value match { case json: org.postgresql.util.PGobject => parseJson(f, columnName.qualified, json.getValue) case json: java.lang.String => parseJson(f, columnName.qualified, json) case _=> { Left( TypeDoesNotMatch( s"Column[${columnName.qualified}] error converting $value to Json. Expected instance of type[org.postgresql.util.PGobject] and not[${value.asInstanceOf[AnyRef].getClass}]" ) ) } } } private[this] def parseJson[T](f: play.api.libs.json.JsValue => T, columnName: String, value: String) = { Try { f( play.api.libs.json.Json.parse(value) ) } match { case Success(result) => Right(result) case Failure(ex) => Left( TypeDoesNotMatch( s"Column[$columnName] error parsing json $value: $ex" ) ) } } } object Types { import io.apibuilder.generator.v0.models.json._ implicit val columnToSeqApibuilderGeneratorFileFlag: Column[Seq[_root_.io.apibuilder.generator.v0.models.FileFlag]] = Util.parser { _.as[Seq[_root_.io.apibuilder.generator.v0.models.FileFlag]] } implicit val columnToMapApibuilderGeneratorFileFlag: Column[Map[String, _root_.io.apibuilder.generator.v0.models.FileFlag]] = Util.parser { _.as[Map[String, _root_.io.apibuilder.generator.v0.models.FileFlag]] } implicit val columnToSeqApibuilderGeneratorAttribute: Column[Seq[_root_.io.apibuilder.generator.v0.models.Attribute]] = Util.parser { _.as[Seq[_root_.io.apibuilder.generator.v0.models.Attribute]] } implicit val columnToMapApibuilderGeneratorAttribute: Column[Map[String, _root_.io.apibuilder.generator.v0.models.Attribute]] = Util.parser { _.as[Map[String, _root_.io.apibuilder.generator.v0.models.Attribute]] } implicit val columnToSeqApibuilderGeneratorError: Column[Seq[_root_.io.apibuilder.generator.v0.models.Error]] = Util.parser { _.as[Seq[_root_.io.apibuilder.generator.v0.models.Error]] } implicit val columnToMapApibuilderGeneratorError: Column[Map[String, _root_.io.apibuilder.generator.v0.models.Error]] = Util.parser { _.as[Map[String, _root_.io.apibuilder.generator.v0.models.Error]] } implicit val columnToSeqApibuilderGeneratorFile: Column[Seq[_root_.io.apibuilder.generator.v0.models.File]] = Util.parser { _.as[Seq[_root_.io.apibuilder.generator.v0.models.File]] } implicit val columnToMapApibuilderGeneratorFile: Column[Map[String, _root_.io.apibuilder.generator.v0.models.File]] = Util.parser { _.as[Map[String, _root_.io.apibuilder.generator.v0.models.File]] } implicit val columnToSeqApibuilderGeneratorGenerator: Column[Seq[_root_.io.apibuilder.generator.v0.models.Generator]] = Util.parser { _.as[Seq[_root_.io.apibuilder.generator.v0.models.Generator]] } implicit val columnToMapApibuilderGeneratorGenerator: Column[Map[String, _root_.io.apibuilder.generator.v0.models.Generator]] = Util.parser { _.as[Map[String, _root_.io.apibuilder.generator.v0.models.Generator]] } implicit val columnToSeqApibuilderGeneratorHealthcheck: Column[Seq[_root_.io.apibuilder.generator.v0.models.Healthcheck]] = Util.parser { _.as[Seq[_root_.io.apibuilder.generator.v0.models.Healthcheck]] } implicit val columnToMapApibuilderGeneratorHealthcheck: Column[Map[String, _root_.io.apibuilder.generator.v0.models.Healthcheck]] = Util.parser { _.as[Map[String, _root_.io.apibuilder.generator.v0.models.Healthcheck]] } implicit val columnToSeqApibuilderGeneratorInvocation: Column[Seq[_root_.io.apibuilder.generator.v0.models.Invocation]] = Util.parser { _.as[Seq[_root_.io.apibuilder.generator.v0.models.Invocation]] } implicit val columnToMapApibuilderGeneratorInvocation: Column[Map[String, _root_.io.apibuilder.generator.v0.models.Invocation]] = Util.parser { _.as[Map[String, _root_.io.apibuilder.generator.v0.models.Invocation]] } implicit val columnToSeqApibuilderGeneratorInvocationForm: Column[Seq[_root_.io.apibuilder.generator.v0.models.InvocationForm]] = Util.parser { _.as[Seq[_root_.io.apibuilder.generator.v0.models.InvocationForm]] } implicit val columnToMapApibuilderGeneratorInvocationForm: Column[Map[String, _root_.io.apibuilder.generator.v0.models.InvocationForm]] = Util.parser { _.as[Map[String, _root_.io.apibuilder.generator.v0.models.InvocationForm]] } } object Standard { implicit val columnToJsObject: Column[play.api.libs.json.JsObject] = Util.parser { _.as[play.api.libs.json.JsObject] } implicit val columnToSeqBoolean: Column[Seq[Boolean]] = Util.parser { _.as[Seq[Boolean]] } implicit val columnToMapBoolean: Column[Map[String, Boolean]] = Util.parser { _.as[Map[String, Boolean]] } implicit val columnToSeqDouble: Column[Seq[Double]] = Util.parser { _.as[Seq[Double]] } implicit val columnToMapDouble: Column[Map[String, Double]] = Util.parser { _.as[Map[String, Double]] } implicit val columnToSeqInt: Column[Seq[Int]] = Util.parser { _.as[Seq[Int]] } implicit val columnToMapInt: Column[Map[String, Int]] = Util.parser { _.as[Map[String, Int]] } implicit val columnToSeqLong: Column[Seq[Long]] = Util.parser { _.as[Seq[Long]] } implicit val columnToMapLong: Column[Map[String, Long]] = Util.parser { _.as[Map[String, Long]] } implicit val columnToSeqLocalDate: Column[Seq[_root_.org.joda.time.LocalDate]] = Util.parser { _.as[Seq[_root_.org.joda.time.LocalDate]] } implicit val columnToMapLocalDate: Column[Map[String, _root_.org.joda.time.LocalDate]] = Util.parser { _.as[Map[String, _root_.org.joda.time.LocalDate]] } implicit val columnToSeqDateTime: Column[Seq[_root_.org.joda.time.DateTime]] = Util.parser { _.as[Seq[_root_.org.joda.time.DateTime]] } implicit val columnToMapDateTime: Column[Map[String, _root_.org.joda.time.DateTime]] = Util.parser { _.as[Map[String, _root_.org.joda.time.DateTime]] } implicit val columnToSeqBigDecimal: Column[Seq[BigDecimal]] = Util.parser { _.as[Seq[BigDecimal]] } implicit val columnToMapBigDecimal: Column[Map[String, BigDecimal]] = Util.parser { _.as[Map[String, BigDecimal]] } implicit val columnToSeqJsObject: Column[Seq[_root_.play.api.libs.json.JsObject]] = Util.parser { _.as[Seq[_root_.play.api.libs.json.JsObject]] } implicit val columnToMapJsObject: Column[Map[String, _root_.play.api.libs.json.JsObject]] = Util.parser { _.as[Map[String, _root_.play.api.libs.json.JsObject]] } implicit val columnToSeqJsValue: Column[Seq[_root_.play.api.libs.json.JsValue]] = Util.parser { _.as[Seq[_root_.play.api.libs.json.JsValue]] } implicit val columnToMapJsValue: Column[Map[String, _root_.play.api.libs.json.JsValue]] = Util.parser { _.as[Map[String, _root_.play.api.libs.json.JsValue]] } implicit val columnToSeqString: Column[Seq[String]] = Util.parser { _.as[Seq[String]] } implicit val columnToMapString: Column[Map[String, String]] = Util.parser { _.as[Map[String, String]] } implicit val columnToSeqUUID: Column[Seq[_root_.java.util.UUID]] = Util.parser { _.as[Seq[_root_.java.util.UUID]] } implicit val columnToMapUUID: Column[Map[String, _root_.java.util.UUID]] = Util.parser { _.as[Map[String, _root_.java.util.UUID]] } } }
mbryzek/apidoc
api/app/generated/ApicollectiveApibuilderGeneratorV0Conversions.scala
Scala
mit
7,877
package test.roundeights.hasher import org.specs2.mutable._ import com.roundeights.hasher.{Algo, Hasher} class AlgoTest extends Specification { def hashTest ( algo: Algo, data: TestData, hash: String ) = { "Using " + algo + ", the apply methods on the Algo object" in { "Hash a String" in { algo( data.str ).hex must_== hash } "Hash a StringBuilder" in { algo( data.builder ).hex must_== hash } "Hash an Array of Bytes" in { algo( data.bytes ).hex must_== hash } "Hash a Stream" in { algo( data.stream ).hex must_== hash } "Hash a Reader" in { algo( data.reader ).hex must_== hash } "Hash a Source" in { algo( data.source ).hex must_== hash } } "Hashing multiple times with " + algo + " should return the same result" in { algo( data.str ).hex must_== hash algo( data.str ).hex must_== hash algo( data.str ).hex must_== hash } } def compareTest ( algo: Algo, data: TestData, hash: String ) = { "Using " + algo + ", the compare methods on the Algo object" in { "match with a String" in { (algo( data.str ) hash= hash) .aka( "Comparing a String to " + hash ) must beTrue } "match with a StringBuilder" in { (algo( data.builder ) hash= hash) .aka( "Comparing a StringBuilder to " + hash ) must beTrue } "match with an Array of Bytes" in { (algo( data.bytes ) hash= hash) .aka( "Comparing a Byte Array to " + hash ) must beTrue } "match with a Stream" in { (algo( data.stream ) hash= hash ) .aka( "Comparing a Stream to " + hash ) must beTrue } "match with a Reader" in { (algo( data.reader ) hash= hash ) .aka( "Comparing a Reader to " + hash ) must beTrue } "match with a Source" in { (algo( data.source ) hash= hash ) .aka( "Comparing a Source to " + hash ) must beTrue } } "Comparing multiple times with " + algo + " should still match" in { "match with a String" in { (algo( data.str ) hash= hash ) .aka( "Comparing a String to " + hash ) must beTrue (algo( data.str ) hash= hash ) .aka( "Comparing a String to " + hash ) must beTrue (algo( data.str ) hash= hash ) .aka( "Comparing a String to " + hash ) must beTrue } } } // BCrypt produces salted hashes, so we can only assert against the format // of the resulting hashes def testBCrypt( data: TestData ) { "Using BCrypt, the apply methods on the Algo object" in { "Hash a String" in { Algo.bcrypt()(data.str).hex must beMatching("^[a-zA-Z0-9]{120}$") } "Hash a StringBuilder" in { Algo.bcrypt()(data.builder).hex must beMatching("^[a-zA-Z0-9]{120}$") } "Hash an Array of Bytes" in { Algo.bcrypt()(data.bytes).hex must beMatching("^[a-zA-Z0-9]{120}$") } "Hash a Stream" in { Algo.bcrypt()(data.stream).hex must beMatching("^[a-zA-Z0-9]{120}$") } "Hash a Reader" in { Algo.bcrypt()(data.reader).hex must beMatching("^[a-zA-Z0-9]{120}$") } "Hash a Source" in { Algo.bcrypt()(data.source).hex must beMatching("^[a-zA-Z0-9]{120}$") } } } // A simple test "Simple plain text data" should { testBCrypt( TestData.test ) TestData.test.runAgainstUnsalted(hashTest) TestData.test.runAgainstAll(compareTest) } // Test an internationalized, multi-byte string "Internationalized plain text values" should { testBCrypt( TestData.international ) TestData.international.runAgainstUnsalted(hashTest) TestData.international.runAgainstAll(compareTest) } // Test a string large enough that it blows out the buffers "Large values" should { testBCrypt( TestData.large ) TestData.large.runAgainstUnsalted(hashTest) TestData.large.runAgainstAll(compareTest) } // Test hashing a blank string "Blank string" should { testBCrypt( TestData.blank ) TestData.blank.runAgainstUnsalted(hashTest) TestData.blank.runAgainstAll(compareTest) } }
Nycto/Hasher
src/test/scala/hasher/AlgoTest.scala
Scala
mit
4,977
package chat.tox.antox.av import chat.tox.antox.utils.AntoxLog import chat.tox.antox.wrapper.{CallNumber, ContactKey} import rx.lang.scala.JavaConversions._ import rx.lang.scala.subjects.BehaviorSubject import rx.lang.scala.{Observable, Subject} class CallManager { private val callsSubject = BehaviorSubject[Map[CallNumber, Call]](Map.empty[CallNumber, Call]) def calls: Seq[Call] = { // TODO: getValue !! try { callsSubject.getValue.values.toSeq } catch { case e: Exception => { e.printStackTrace() null } case e: java.lang.NoSuchMethodError => { e.printStackTrace() null } } } val activeCallObservable = callsSubject.map(_.values.filter(_.active)) private val callAddedSubject = Subject[Call]() val callAddedObservable: Observable[Call] = callAddedSubject.asJavaObservable def add(call: Call): Unit = { AntoxLog.debug("Adding call") callAddedSubject.onNext(call) // TODO: getValue !! -> can't logout when it crashes here try { callsSubject.onNext(callsSubject.getValue + (call.callNumber -> call)) } catch { case e: Exception => e.printStackTrace() case e: java.lang.NoSuchMethodError => e.printStackTrace() } call.endedObservable.subscribe { _ => remove(call.callNumber) } } def get(callNumber: CallNumber): Option[Call] = { calls.find(_.callNumber == callNumber) } def get(callKey: ContactKey): Option[Call] = { calls.find(_.contactKey == callKey) } private def remove(callNumber: CallNumber): Unit = { AntoxLog.debug("Removing call") // TODO: getValue !! try { callsSubject.onNext(callsSubject.getValue - callNumber) } catch { case e: Exception => e.printStackTrace() case e: java.lang.NoSuchMethodError => e.printStackTrace() } } def removeAndEndAll(): Unit = { // TODO: getValue !! try { callsSubject.getValue.foreach { case (callNumber, call) => if (call.active) call.end() remove(callNumber) } } catch { case e: Exception => e.printStackTrace() case e: java.lang.NoSuchMethodError => e.printStackTrace() } } }
subliun/Antox
app/src/main/scala/chat/tox/antox/av/CallManager.scala
Scala
gpl-3.0
2,218
package org.jetbrains.plugins.scala.debugger.evaluation.evaluator import com.intellij.debugger.engine.evaluation.expression.{Evaluator, Modifier} import com.intellij.debugger.engine.evaluation.{EvaluateExceptionUtil, EvaluationContextImpl} import com.sun.jdi.BooleanValue /** * User: Alefas * Date: 19.10.11 */ class ScalaIfEvaluator(condition: Evaluator, ifBranch: Evaluator, elseBranch: Option[Evaluator]) extends Evaluator { private var modifier: Modifier = null def evaluate(context: EvaluationContextImpl): AnyRef = { var value: AnyRef = condition.evaluate(context) value match { case v: BooleanValue => if (v.booleanValue) { value = ifBranch.evaluate(context) modifier = ifBranch.getModifier } else { elseBranch match { case Some(elseBranch) => value = elseBranch.evaluate(context) modifier = elseBranch.getModifier return value case None => modifier = null } } case _ => throw EvaluateExceptionUtil.BOOLEAN_EXPECTED } if (elseBranch == None) value = context.getDebugProcess.getVirtualMachineProxy.mirrorOf() value } def getModifier: Modifier = modifier }
triggerNZ/intellij-scala
src/org/jetbrains/plugins/scala/debugger/evaluation/evaluator/ScalaIfEvaluator.scala
Scala
apache-2.0
1,273
package org.openurp.edu.eams.teach.lesson.task.web.action import org.openurp.base.Semester import org.openurp.edu.base.Project import org.openurp.edu.base.Student class TeachTaskStdSearchAction extends TeachTaskSearchAction { def index(): String = { val std = getLoginStudent if (null == std) { return forwardError("error.std.stdNo.needed") } val semesterId = getInt("semester.id") val projectId = getInt("project.id") val project = (if (null == projectId) std.getProject else entityDao.get(classOf[Project], projectId)) var semester: Semester = null semester = if (null != semesterId && null == projectId) semesterService.getSemester(semesterId) else semesterService.getCurSemester(project) if (null == semester) { return forwardError("error.semester.notMaded") } put("semester", semester) put("cur_project", project) put("semesters", semesterService.getCalendar(project).getSemesters) put("departmentAll", departmentService.getColleges) forward() } }
openurp/edu-eams-webapp
schedule/src/main/scala/org/openurp/edu/eams/teach/lesson/task/web/action/TeachTaskStdSearchAction.scala
Scala
gpl-3.0
1,034
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.plan.nodes.physical.batch import org.apache.flink.runtime.operators.DamBehavior import org.apache.flink.table.api.BatchTableEnvironment import org.apache.flink.table.codegen.ValuesCodeGenerator import org.apache.flink.table.dataformat.BaseRow import org.apache.flink.table.plan.nodes.exec.{BatchExecNode, ExecNode} import org.apache.calcite.plan.{RelOptCluster, RelTraitSet} import org.apache.calcite.rel.`type`.RelDataType import org.apache.calcite.rel.core.Values import org.apache.calcite.rel.{RelNode, RelWriter} import org.apache.calcite.rex.RexLiteral import com.google.common.collect.ImmutableList import java.util import org.apache.flink.api.dag.Transformation import scala.collection.JavaConversions._ /** * Batch physical RelNode for [[Values]]. */ class BatchExecValues( cluster: RelOptCluster, traitSet: RelTraitSet, tuples: ImmutableList[ImmutableList[RexLiteral]], outputRowType: RelDataType) extends Values(cluster, outputRowType, tuples, traitSet) with BatchPhysicalRel with BatchExecNode[BaseRow] { override def deriveRowType(): RelDataType = outputRowType override def copy(traitSet: RelTraitSet, inputs: util.List[RelNode]): RelNode = { new BatchExecValues(cluster, traitSet, getTuples, outputRowType) } override def explainTerms(pw: RelWriter): RelWriter = { super.explainTerms(pw) .item("values", getRowType.getFieldNames.toList.mkString(", ")) } //~ ExecNode methods ----------------------------------------------------------- override def getDamBehavior: DamBehavior = DamBehavior.PIPELINED override def getInputNodes: util.List[ExecNode[BatchTableEnvironment, _]] = List() override def replaceInputNode( ordinalInParent: Int, newInputNode: ExecNode[BatchTableEnvironment, _]): Unit = { replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode]) } override protected def translateToPlanInternal( tableEnv: BatchTableEnvironment): Transformation[BaseRow] = { val inputFormat = ValuesCodeGenerator.generatorInputFormat( tableEnv, getRowType, tuples, getRelTypeName) val transformation = tableEnv.streamEnv.createInput(inputFormat, inputFormat.getProducedType).getTransformation transformation.setParallelism(getResource.getParallelism) transformation } }
shaoxuan-wang/flink
flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/plan/nodes/physical/batch/BatchExecValues.scala
Scala
apache-2.0
3,167
/* * Copyright 2017-2020 Aleksey Fomkin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package korolev.internal import java.util.concurrent.atomic.AtomicInteger import scala.collection.mutable import scala.annotation.switch import korolev.Context.FileHandler import korolev.data.Bytes import korolev.web.{FormData, PathAndQuery} import korolev.effect.syntax._ import korolev.effect.{AsyncTable, Effect, Queue, Reporter, Stream} import levsha.Id import levsha.impl.DiffRenderContext.ChangesPerformer /** * Typed interface to client side */ final class Frontend[F[_]: Effect](incomingMessages: Stream[F, String])(implicit reporter: Reporter) { import Frontend._ private val lastDescriptor = new AtomicInteger(0) private val remoteDomChangesPerformer = new RemoteDomChangesPerformer() private val customCallbacks = mutable.Map.empty[String, String => F[Unit]] private val downloadFiles = mutable.Map.empty[String, DownloadFileMeta[F]] private val stringPromises = AsyncTable.unsafeCreateEmpty[F, String, String] private val formDataPromises = AsyncTable.unsafeCreateEmpty[F, String, FormData] private val filesPromises = AsyncTable.unsafeCreateEmpty[F, String, Stream[F, Bytes]] // Store file name and it`s length as data private val fileNamePromises = AsyncTable.unsafeCreateEmpty[F, String, List[(String, Long)]] private val outgoingQueue = Queue[F, String]() private val List(rawDomEvents, rawBrowserHistoryChanges, rawClientMessages) = incomingMessages .map(parseMessage) .sort(3) { case (CallbackType.DomEvent.code, _) => 0 case (CallbackType.History.code, _) => 1 case _ => 2 } val (outgoingConsumed, outgoingMessages: Stream[F, String]) = outgoingQueue.stream.handleConsumed val domEventMessages: Stream[F, Frontend.DomEventMessage] = rawDomEvents.map { case (_, args) => val Array(renderNum, target, tpe) = args.split(':') DomEventMessage(renderNum.toInt, Id(target), tpe) } val browserHistoryMessages: Stream[F, PathAndQuery] = rawBrowserHistoryChanges.map { case (_, args) => PathAndQuery.fromString(args) } private def send(args: Any*): F[Unit] = { def escape(sb: StringBuilder, s: String, unicode: Boolean): Unit = { sb.append('"') var i = 0 val len = s.length while (i < len) { (s.charAt(i): @switch) match { case '"' => sb.append("\\\\\\"") case '\\\\' => sb.append("\\\\\\\\") case '\\b' => sb.append("\\\\b") case '\\f' => sb.append("\\\\f") case '\\n' => sb.append("\\\\n") case '\\r' => sb.append("\\\\r") case '\\t' => sb.append("\\\\t") case c => if (c < ' ' || (c > '~' && unicode)) sb.append("\\\\u%04x" format c.toInt) else sb.append(c) } i += 1 } sb.append('"') () } val sb = new StringBuilder() sb.append('[') args.foreach { case s: String => escape(sb, s, unicode = true) sb.append(',') case x => sb.append(x.toString) sb.append(',') } sb.update(sb.length - 1, ' ') // replace last comma to space sb.append(']') outgoingQueue.enqueue(sb.mkString) } def listenEvent(name: String, preventDefault: Boolean): F[Unit] = send(Procedure.ListenEvent.code, name, preventDefault) def uploadForm(id: Id): F[FormData] = for { descriptor <- nextDescriptor() _ <- send(Procedure.UploadForm.code, id.mkString, descriptor) result <- formDataPromises.get(descriptor) } yield result def listFiles(id: Id): F[List[(String, Long)]] = for { descriptor <- nextDescriptor() _ <- send(Procedure.ListFiles.code, id.mkString, descriptor) files <- fileNamePromises.get(descriptor) } yield files def uploadFile(id: Id, handler: FileHandler): F[Stream[F, Bytes]] = for { descriptor <- nextDescriptor() _ <- send(Procedure.UploadFile.code, id.mkString, descriptor, handler.fileName) file <- filesPromises.get(descriptor) } yield file def downloadFile(name: String, stream: Stream[F, Bytes], size: Option[Long], mimeType: String): F[Unit] = { val (consumed, updatedStream) = stream.handleConsumed val id = lastDescriptor.getAndIncrement().toString consumed.runAsync(_ => downloadFiles.remove(name)) downloadFiles.put(id, DownloadFileMeta(updatedStream, size, mimeType)) send(Procedure.DownloadFile.code, id, name) } def resolveFileDownload(descriptor: String): F[Option[DownloadFileMeta[F]]] = Effect[F].delay(downloadFiles.get(descriptor)) def focus(id: Id): F[Unit] = send(Procedure.Focus.code, id.mkString) private def nextDescriptor() = Effect[F].delay(lastDescriptor.getAndIncrement().toString) def extractProperty(id: Id, name: String): F[String] = { for { descriptor <- nextDescriptor() _ <- send(Procedure.ExtractProperty.code, descriptor, id.mkString, name) result <- stringPromises.get(descriptor) } yield result } def setProperty(id: Id, name: String, value: Any): F[Unit] = { send(Procedure.ModifyDom.code, ModifyDomProcedure.SetAttr.code, id.mkString, 0, name, value, true) } def evalJs(code: String): F[String] = for { descriptor <- nextDescriptor() _ <- send(Procedure.EvalJs.code, descriptor, code) result <- stringPromises.get(descriptor) } yield result def resetForm(id: Id): F[Unit] = send(Procedure.RestForm.code, id.mkString) def changePageUrl(pq: PathAndQuery): F[Unit] = send(Procedure.ChangePageUrl.code, pq.mkString) def setRenderNum(i: Int): F[Unit] = send(Procedure.SetRenderNum.code, i) def reload(): F[Unit] = send(Procedure.Reload.code) def reloadCss(): F[Unit] = send(Procedure.ReloadCss.code) def extractEventData(renderNum: Int): F[String] = for { descriptor <- nextDescriptor() _ <- send(Procedure.ExtractEventData.code, descriptor, renderNum) result <- stringPromises.get(descriptor) } yield result def performDomChanges(f: ChangesPerformer => Unit): F[Unit] = for { _ <- Effect[F] .delay { remoteDomChangesPerformer.buffer.append(Procedure.ModifyDom.code) f(remoteDomChangesPerformer) } _ <- send(remoteDomChangesPerformer.buffer.toSeq: _*) _ <- Effect[F].delay(remoteDomChangesPerformer.buffer.clear()) } yield () def resolveFile(descriptor: String, file: Stream[F, Bytes]): F[Unit] = filesPromises .put(descriptor, file) .after(filesPromises.remove(descriptor)) def resolveFileNames(descriptor: String, handler: List[(String, Long)]): F[Unit] = fileNamePromises .put(descriptor, handler) .after(fileNamePromises.remove(descriptor)) def resolveFormData(descriptor: String, formData: Either[Throwable, FormData]): F[Unit] = formDataPromises .putEither(descriptor, formData) .after(formDataPromises.remove(descriptor)) def registerCustomCallback(name: String)(f: String => F[Unit]): F[Unit] = Effect[F].delay { customCallbacks.put(name, f) () } private def unescapeJsonString(s: String): String = { val sb = new StringBuilder() var i = 1 val len = s.length - 1 while (i < len) { val c = s.charAt(i) var charsConsumed = 0 if (c != '\\\\') { charsConsumed = 1 sb.append(c) } else { charsConsumed = 2 (s.charAt(i + 1): @switch) match { case '\\\\' => sb.append('\\\\') case '"' => sb.append('"') case 'b' => sb.append('\\b') case 'f' => sb.append('\\f') case 'n' => sb.append('\\n') case 'r' => sb.append('\\r') case 't' => sb.append('\\t') case 'u' => val code = s.substring(i + 2, i + 6) charsConsumed = 6 sb.append(Integer.parseInt(code, 16).toChar) } } i += charsConsumed } sb.result() } private def parseMessage(json: String) = { val tokens = json .substring(1, json.length - 1) // remove brackets .split(",", 2) // split to tokens val callbackType = tokens(0) val args = if (tokens.length > 1) unescapeJsonString(tokens(1)) else "" (callbackType.toInt, args) } rawClientMessages .foreach { case (CallbackType.Heartbeat.code, _) => Effect[F].unit case (CallbackType.ExtractPropertyResponse.code, args) => val Array(descriptor, propertyType, value) = args.split(":", 3) propertyType.toInt match { case PropertyType.Error.code => stringPromises .fail(descriptor, ClientSideException(value)) .after(stringPromises.remove(descriptor)) case _ => stringPromises .put(descriptor, value) .after(stringPromises.remove(descriptor)) } case (CallbackType.ExtractEventDataResponse.code, args) => val Array(descriptor, value) = args.split(":", 2) stringPromises .put(descriptor, value) .after(stringPromises.remove(descriptor)) case (CallbackType.EvalJsResponse.code, args) => val Array(descriptor, status, json) = args.split(":", 3) status.toInt match { case EvalJsStatus.Success.code => stringPromises .put(descriptor, json) .after(stringPromises.remove(descriptor)) case EvalJsStatus.Failure.code => stringPromises .fail(descriptor, ClientSideException(json)) .after(stringPromises.remove(descriptor)) } case (CallbackType.CustomCallback.code, args) => val Array(name, arg) = args.split(":", 2) customCallbacks.get(name) match { case Some(f) => f(arg) case None => Effect[F].unit } case (callbackType, args) => Effect[F].fail(UnknownCallbackException(callbackType, args)) } .runAsyncForget } object Frontend { final case class DomEventMessage(renderNum: Int, target: Id, eventType: String) sealed abstract class Procedure(final val code: Int) object Procedure { case object SetRenderNum extends Procedure(0) // (n) case object Reload extends Procedure(1) // () case object ListenEvent extends Procedure(2) // (type, preventDefault) case object ExtractProperty extends Procedure(3) // (id, propertyName, descriptor) case object ModifyDom extends Procedure(4) // (commands) case object Focus extends Procedure(5) // (id) { case object ChangePageUrl extends Procedure(6) // (path) case object UploadForm extends Procedure(7) // (id, descriptor) case object ReloadCss extends Procedure(8) // () case object KeepAlive extends Procedure(9) // () case object EvalJs extends Procedure(10) // (code) case object ExtractEventData extends Procedure(11) // (descriptor, renderNum) case object ListFiles extends Procedure(12) // (id, descriptor) case object UploadFile extends Procedure(13) // (id, descriptor, fileName) case object RestForm extends Procedure(14) // (id) case object DownloadFile extends Procedure(15) // (descriptor, fileName) val All = Set( SetRenderNum, Reload, ListenEvent, ExtractProperty, ModifyDom, Focus, ChangePageUrl, UploadForm, ReloadCss, KeepAlive, EvalJs, ExtractEventData, ListFiles, UploadFile, RestForm, DownloadFile ) def apply(n: Int): Option[Procedure] = All.find(_.code == n) } sealed abstract class ModifyDomProcedure(final val code: Int) object ModifyDomProcedure { case object Create extends ModifyDomProcedure(0) // (id, childId, xmlNs, tag) case object CreateText extends ModifyDomProcedure(1) // (id, childId, text) case object Remove extends ModifyDomProcedure(2) // (id, childId) case object SetAttr extends ModifyDomProcedure(3) // (id, xmlNs, name, value, isProperty) case object RemoveAttr extends ModifyDomProcedure(4) // (id, xmlNs, name, isProperty) case object SetStyle extends ModifyDomProcedure(5) // (id, name, value) case object RemoveStyle extends ModifyDomProcedure(6) // (id, name) } sealed abstract class PropertyType(final val code: Int) object PropertyType { case object String extends PropertyType(0) case object Number extends PropertyType(1) case object Boolean extends PropertyType(2) case object Object extends PropertyType(3) case object Error extends PropertyType(4) } sealed abstract class EvalJsStatus(final val code: Int) object EvalJsStatus { case object Success extends EvalJsStatus(0) case object Failure extends EvalJsStatus(1) } sealed abstract class CallbackType(final val code: Int) object CallbackType { case object DomEvent extends CallbackType(0) // `$renderNum:$elementId:$eventType` case object CustomCallback extends CallbackType(1) // `$name:arg` case object ExtractPropertyResponse extends CallbackType(2) // `$descriptor:$value` case object History extends CallbackType(3) // URL case object EvalJsResponse extends CallbackType(4) // `$descriptor:$status:$value` case object ExtractEventDataResponse extends CallbackType(5) // `$descriptor:$dataJson` case object Heartbeat extends CallbackType(6) // `$descriptor:$anyvalue` final val All = Set(DomEvent, CustomCallback, ExtractPropertyResponse, History, EvalJsResponse, ExtractEventDataResponse, Heartbeat) def apply(n: Int): Option[CallbackType] = All.find(_.code == n) } case class ClientSideException(message: String) extends Exception(message) case class UnknownCallbackException(callbackType: Int, args: String) extends Exception(s"Unknown callback $callbackType with args '$args' received") final case class DownloadFileMeta[F[_]: Effect](stream: Stream[F, Bytes], size: Option[Long], mimeType: String) val ReloadMessage: String = "[1]" }
fomkin/korolev
modules/korolev/src/main/scala/korolev/internal/Frontend.scala
Scala
apache-2.0
14,816
//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** @author Arash Fard, Usman Nisar, Ayushi Jain, Aravind Kalimurthy, John Miller * @version 1.3 * @date Thu Nov 25 11:28:31 EDT 2013 * @see LICENSE (MIT style license file). * * `MGraph` Strict Simulation Using Mutable Sets */ package scalation.graphalytics.mutable import scala.collection.mutable.{ArrayStack, ListBuffer, Map, HashMap, MutableList} import scala.collection.mutable.{Set => SET} import scala.reflect.ClassTag import scala.util.control.Breaks.{break, breakable} import scalation.graphalytics.mutable.{ExampleMGraphD => EX_GRAPH} import scalation.stat.Statistic //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The 'MStrictSim' class provides an implementation for strict simulation * graph pattern matching. This version uses `DualSim`. * @see hipore.com/ijbd/2014/IJBD%20Vol%201%20No%201%202014.pdf * @param q the query graph Q(U, D, k) * @param g the data graph G(V, E, l) */ class MStrictSim [TLabel: ClassTag] (g: MGraph [TLabel], q: MGraph [TLabel]) extends GraphMatcher (g, q) { private val listOfDistinctReducedSet = new ListBuffer [SET [String]] () // contains total number of matches // after post processing private val mapOfBallWithSize = Map [Int, Long] () // contains balls left after // post processing with diameter. private val listOfMatchedBallVertices = MutableList [Int] () // contains list of center vertices private val qmet = new GraphMetrics (q.clone, false) // creating graph metrics object of query graph private val dataSize = g.size // size of the data graph private val querySize = q.size // size of the query graph private val phi0 = new MDualSim (g, q).mappings () println (s"phi0 = ${phi0.deep}") //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Apply the Strict Graph Simulation pattern matching algorithm to find the mappings * from the query graph 'q' to the data graph 'g'. These are represented by a * multi-valued function 'phi' that maps each query graph vertex 'u' to a * set of data graph vertices '{v}'. */ def mappings (): Array [SET [Int]] = merge (mappings2 ()) //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Mapping results per ball. */ def mappings2 (): HashMap [Int, Array [SET [Int]]] = strictSim (phi0) //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Merged mapping results, the union over all balls. */ def merge (matches: Map [Int, Array [SET [Int]]]): Array [SET [Int]] = { val phi_all = Array.ofDim [SET [Int]] (querySize) for (i <- 0 until querySize) phi_all (i) = SET [Int] () for ((c, phi_c) <- matches) { println (s"(c, phi_c) = ($c, ${phi_c.deep})") for (i <- 0 until querySize) phi_all(i) ++= phi_c(i) } // for phi_all } // merge //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Performs strict simulation to find mappings with balls. * @param phi the initial mapping after applying Dual to the whole graph */ def strictSim (phi: Array [SET [Int]]): HashMap [Int, Array [SET [Int]]] = { if (phi.size == 0) { println ("No dual match."); return null } // exit if no match after dual simulation println (s"phi = ${phi.deep}") val newGraph = filterGraph (phi) // if doing strong sim more than once, must clone g val prunedSize = phi.clone.flatten.toSet.size // size of feasible matches after strict simulation val qDiameter = qmet.diam // get the query diameter val balls = HashMap [Int, Ball [TLabel]] () // map of balls: center -> ball val matches = HashMap [Int, Array [SET [Int]]] () // map of matches in balls: center -> match val gCenters = (0 until q.size).flatMap(phi(_)) // set of mapped data graph centers val bCenters = SET [Int] () // set of centers for all balls var ballSum = 0 for (center <- gCenters) { // for each mapped data graph center val ball = new Ball (newGraph, center, qDiameter) // create a new ball for that center vertex ballSum += ball.nodesInBall.size // calculate ball size val mat = dualFilter (phi.clone, ball) // perform dual filter on the ball println (s"center = $center, mat = ${mat.deep}") balls.put (center, ball) if (mat.size != 0) { bCenters += center; matches += center -> mat } else println ("No match for ball centered at " + center + "\n") } // for println ("SEQUENTIAL: Data Graph Name: " + g.name + "\n Number of Data Graph Nodes: " + dataSize + "\n Query Graph Name: " + q.name + "\n Number of Query Graph Nodes: " + querySize + "\n Number of Strict Matches: " + bCenters.size + "\n Graph Size after Pruning: " + prunedSize + " nodes" + "\n Query Diameter: " + qDiameter + "\n Average Ball Size: " + (ballSum / prunedSize.toDouble) + "\n Total Distinct Edges: " + calculateTotalEdges (g, balls, bCenters) + "\n Total Distinct Vertices: " + calculateTotalVertices ()) println ("Ball Diameter Metrics(Min, Max, Mean, StdDev): " + calculateBallDiameterMetrics (balls) ) matches } // strictSim //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Prune the data graph by consider only those vertices and edges which * are part of feasible matches after performing initial dual simulation. * @param phi mappings from a query vertex u_q to { graph vertices v_g } */ def filterGraph (phi: Array [SET [Int]]): MGraph [TLabel] = { val nodesInSimset = phi.flatten.toSet // get all the vertices of feasible matches for (i <- 0 until dataSize) g.ch(i) &= nodesInSimset // prune via intersection val newCh = Array.ofDim [SET [Int]] (dataSize) for (i <- 0 until dataSize) newCh(i) = SET [Int] () for (u <- 0 until q.size; w <- phi(u)) { // new ch and pa set for data graph based upon feasible vertices for (v <- q.ch(u)) newCh(w) |= (g.ch(w) & phi(v)) } // for new MGraph (newCh, g.label, g.elabel, g.inverse, g.name + "2") // create a new data graph } // filterGraph //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Perform dual simulation onto the ball. * @param phi mappings from a query vertex u_q to { graph vertices v_g } * @param ball the Ball B(Graph, Center, Radius) */ def dualFilter (phi: Array [SET [Int]], ball: Ball [TLabel]): Array [SET [Int]] = { for (v <- phi.indices) phi(v) &= ball.nodesInBall // project simset onto ball val filterSet = new ArrayStack [(Int, Int)] () var filtered = false for (u <- phi.indices; v <- phi(u) if ball.borderNodes contains v) { filtered = false // filtering ball based on child relationship breakable { for (u1 <- q.ch(u)) { if ((ball.post (v) & phi (u1)).isEmpty) { filterSet.push ((u, v)) filtered = true break } // if }} // breakable for if (! filtered) { // filtering ball based on parent relationship, breakable { for (u2 <- q.pa(u)) { // if no child has been filtered out if ((ball.pre (v) & phi(u2)).isEmpty) { filterSet.push ((u, v)) break } // if }} // breakable for } // if } // for while (! filterSet.isEmpty) { // refine ch and pa relationship for the vertex v, val (u, v) = filterSet.pop () // which is now not a feasible match phi(u) -= v for (u2 <- q.pa(u); v2 <- (ball.pre (v) & phi(u2)) if (ball.post (v2) & phi(u)).isEmpty) filterSet.push ((u2, v2)) for (u1 <- q.ch(u); v1 <- (ball.post (v) & phi(u1)) if (ball.pre (v1) & phi(u)).isEmpty) filterSet.push ((u1, v1)) } // while val chSet = HashMap [Int, SET [Int]] () val paSet = HashMap [Int, SET [Int]] () // create new ch and pa set for the ball after above pruning for (u <- phi.indices; v <- phi(u); uc <- q.ch(u); vc <- (ball.post (v) & phi(uc))) { chSet.getOrElseUpdate (v, SET [Int] ()) += vc paSet.getOrElseUpdate (vc, SET [Int] ()) += v } // for // Finding max perfect subgraph val stack = new ArrayStack [Int] () val visited = SET (ball.center) stack.push (ball.center) while (! stack.isEmpty) { val v = stack.pop () for (child <- (chSet.getOrElse (v, SET ()) | paSet.getOrElse (v, SET ()))) { if (! visited.contains (child)) { stack.push (child) visited += child } // if } // for } // while for ( v <- phi.indices) phi(v) = phi(v) & visited //fixes the edges in the ball //(note that it does not change the parent set; this is only used for printing) //uncomment if you want to see the ball after finding maximum perfect subgraph ball.chMap = Map [Int, SET [Int]] () val matchNodes = phi.flatten.toSet for ((n, nset) <- chSet; nc <- nset) { if ((matchNodes contains n) && (matchNodes contains nc)) ball.chMap.getOrElseUpdate (n, SET () ) += nc } // for for (v <- phi.indices if phi(v).isEmpty) return Array [SET [Int]] () phi } //dualFilter //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Count distinct vertices left after post processing. */ def calculateTotalVertices (): Int = { val totalSet = SET [String] () for (i <- 0 until listOfDistinctReducedSet.length) totalSet ++= listOfDistinctReducedSet(i) totalSet.size } // calculateTotalVertices //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Count distinct edges left after post processing. * @param g the data graph G(V, E, l) * @param balls mappings from a center vertex to the Ball B(Graph, Center, Radius) * @param matchCenters set of all vertices which are considered as center */ def calculateTotalEdges (g: MGraph [TLabel], balls: Map [Int, Ball [TLabel]], matchCenters: SET [Int]): Int = { val distinctEdges = SET [String] () for (vert_id <- 0 until g.ch.length; if balls.keySet.contains (vert_id)) { balls.get (vert_id).get.chMap.foreach (i => i._2.foreach (j => distinctEdges += (i._1.toString + "_" + j.toString))) } // for distinctEdges.size } // calculateTotalEdges //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Calculate statistics (e.g., min, max, average diameter and standard deviation) * on the balls left after post-processing. * @param balls mappings from a center vertex to the Ball B(Graph, Center, Radius) */ def calculateBallDiameterMetrics (balls: Map [Int, Ball [TLabel]]): Statistic = { val ballStats = new Statistic () for (vert_id <- listOfMatchedBallVertices) ballStats.tally (balls.get (vert_id).get.getBallDiameter) ballStats } // calculateBallDiameterMetrics //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** Return the vertex from an array of central vertices, those which have * highest 'ch' set size and lowest frequency of label in the query graph, i.e., * highest ratio. * @param centr the array of vertices whose eccentricity is equal to the radius */ def selectivityCriteria (qmet: GraphMetrics [TLabel]): Int = { var index = 0 var max = 0.0 for (ctr <- qmet.central) { val ratio = qmet.g.ch(ctr).size.toDouble / qmet.g.labelMap (qmet.g.label(ctr)).size.toDouble if (max < ratio) { max = ratio; index = ctr } } // for index } // selectivityCriteria } // MStrictSim class //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :::::::::::: /** The `MStrictSimTest` object is used to test the `MStrictSim` class. * > run-main scalation.graphalytics.mutable.MStrictSimTest */ object MStrictSimTest extends App { val g = EX_GRAPH.g1p val q = EX_GRAPH.q1p println (s"g.checkEdges = ${g.checkEdges}") g.printG () println (s"q.checkEdges = ${q.checkEdges}") q.printG () (new MStrictSim (g, q)).test ("MStrictSim") // Strict Graph Simulation Pattern Matcher } // MStrictSimTest object //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :::::::::::: /** The `MStrictSimTest2` object is used to test the `MStrictSim` class. * > run-main scalation.graphalytics.mutable.MStrictSimTest2 */ object MStrictSimTest2 extends App { val g = EX_GRAPH.g2p val q = EX_GRAPH.q2p println (s"g.checkEdges = ${g.checkEdges}") g.printG () println (s"q.checkEdges = ${q.checkEdges}") q.printG () (new MStrictSim (g, q)).test ("MStrictSim") // Strict Graph Simulation Pattern Matcher } // MStrictSimTest2 object //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: /** The `MStrictSimTest3` object test the `MStrictSim` class by passing data graph * and query graph relative file paths. * > run-main scalation.graphalytics.mutable.MStrictSimTest3 */ object MStrictSimTest3 extends App { val g = MGraphIO [Double] ("gfile") val q = MGraphIO [Double] ("qfile") println (s"q.checkEdges = ${q.checkEdges}") q.printG () (new MStrictSim (g, q)).test ("MStrictSim") // Strict Graph Simulation Pattern Matcher } // MStrictSimTest3 object
scalation/fda
scalation_1.3/scalation_modeling/src/main/scala/scalation/graphalytics/mutable/MStrictSim.scala
Scala
mit
15,158
package com.lorandszakacs.util.mongodb import com.lorandszakacs.util.effects._ import com.lorandszakacs.util.math.Identifier import org.scalatest._ import org.scalatest.flatspec.FixtureAnyFlatSpec /** * * N.B. * Known to fail in ``sbt``. But in Intellij, they run. And normal application start does find the configs. * So no idea why this happens only during ``sbt test`` *{{{ * [info] com.typesafe.config.ConfigException$Missing: No configuration setting found for key 'akka' * .... *}}} * * @author Lorand Szakacs, [email protected] * @since 15 Jul 2017 * */ class MongoCollectionTest extends FixtureAnyFlatSpec with OneInstancePerTest with Matchers { implicit private val cs: ContextShift[IO] = IO.contextShift(ExecutionContext.global) implicit private val dbIOScheduler: DBIOScheduler = DBIOScheduler(ExecutionContext.global) implicit private val futureLift: FutureLift[IO] = FutureLift.instance[IO] class EntityRepository(override protected val db: Database)( implicit implicit override protected val dbIOScheduler: DBIOScheduler, implicit override protected val futureLift: FutureLift[IO], ) extends MongoCollection[Entity, String, BSONString] { implicit protected def entityHandler: BSONDocumentHandler[Entity] = BSONMacros.handler[Entity] implicit override protected lazy val idHandler: BSONHandler[BSONString, String] = BSONStringHandler implicit override protected lazy val identifier: Identifier[Entity, String] = Identifier { e => e.id } override def collectionName: String = "test_entities" } case class Entity( @Annotations.Key("_id") id: String, opt: Option[String], actual: String, ) override protected def withFixture(test: OneArgTest): Outcome = { val dbName = Database.testName(this.getClass.getSimpleName, test.text) val db = new Database( uri = """mongodb://localhost:27016""", dbName = dbName, ) val repo = new EntityRepository(db) db.drop().unsafeSyncGet() val outcome: Outcome = withFixture(test.toNoArgTest(repo)) val f = if (outcome.isFailed || outcome.isCanceled) { db.shutdown() } else { for { _ <- db.drop() _ <- db.shutdown() } yield () } f.unsafeSyncGet() outcome } override type FixtureParam = EntityRepository //=========================================================================== //=========================================================================== behavior of "MongoCollection" it should "001 single: write + read + update + remove" in { repo => val original = Entity( id = "1", opt = Some("OPTIONAL"), actual = "VALUE", ) withClue("we create") { repo.create(original).unsafeSyncGet() } withClue("we read") { val read = repo .find(original.id) .unsafeSyncGet() .getOrElse( fail("... expected entity"), ) assert(read == original) } val updateNoOpt = original.copy(opt = None) withClue("we createOrUpdate") { repo.createOrUpdate(updateNoOpt).unsafeSyncGet() } withClue("we read after update") { val read = repo .find(updateNoOpt.id) .unsafeSyncGet() .getOrElse( fail("... expected entity"), ) assert(read == updateNoOpt) } withClue("we remove") { repo.remove(original.id).unsafeSyncGet() } withClue("we read after remove") { val read = repo.find(original.id).unsafeSyncGet() assert(read.isEmpty) } } //=========================================================================== //=========================================================================== it should "002: attempt to write twice" in { repo => val original = Entity( id = "1", opt = Some("OPTIONAL"), actual = "VALUE", ) withClue("we create") { repo.create(original).unsafeSyncGet() } withClue("we create... again, should get exception") { the[MongoDBException] thrownBy { repo.create(original).unsafeSyncGet() } } } //=========================================================================== //=========================================================================== it should "003: bulk create + many read + bulk update" in { repo => val e1 = Entity( id = "1", opt = Some("OPTIONAL"), actual = "VALUE", ) val e2 = Entity( id = "2", opt = Some("OPTIONAL2"), actual = "VALUE2", ) val e3 = Entity( id = "3", opt = Some("OPTIONAL3"), actual = "VALUE3", ) withClue("we create all") { repo.create(List(e1, e2, e3)).unsafeSyncGet() } withClue("we get all") { val all = repo.findAll.unsafeSyncGet() assert(List(e1, e2, e3) === all.sortBy(_.id)) } withClue("we get only ones with IDS 1, 2 -- query") { val q = document( _id -> document( $in -> array(e1.id, e2.id), ), ) val found = repo.findMany(q).unsafeSyncGet() assert(List(e1, e2) == found.sortBy(_.id)) } withClue("we get only ones with IDS 1, 2 -- id method") { val found = repo.findManyById(List(e1.id, e2.id)).unsafeSyncGet() assert(List(e1, e2) == found.sortBy(_.id)) } val e1U = e1.copy(opt = None) val e2U = e2.copy(opt = None) withClue("bulk update two") { repo.createOrUpdate(List(e1U, e2U)).unsafeSyncGet() } withClue("get all after bulk update of two") { val all = repo.findAll.unsafeSyncGet() assert(List(e1U, e2U, e3) == all.sortBy(_.id)) } } //=========================================================================== //=========================================================================== it should "004: bulk create + double create" in { repo => val e1 = Entity( id = "1", opt = Some("OPTIONAL"), actual = "VALUE", ) val e2 = Entity( id = "2", opt = Some("OPTIONAL2"), actual = "VALUE2", ) val e3 = Entity( id = "3", opt = Some("OPTIONAL3"), actual = "VALUE3", ) withClue("we create all") { repo.create(List(e1, e2, e3)).unsafeSyncGet() } withClue("we get all") { val all = repo.findAll.unsafeSyncGet() assert(List(e1, e2, e3) === all.sortBy(_.id)) } val e1U = e1.copy(opt = None) val e2U = e2.copy(opt = None) withClue("bulk update two") { the[MongoDBException] thrownBy { repo.create(List(e1U, e2U)).unsafeSyncGet() } } withClue("get all after failed bulk update, they should be ok") { val all = repo.findAll.unsafeSyncGet() assert(List(e1, e2, e3) == all.sortBy(_.id)) } } }
lorandszakacs/sg-downloader
util/src/test/scala/com/lorandszakacs/util/mongodb/MongoCollectionTest.scala
Scala
apache-2.0
6,958
package com.sksamuel.elastic4s.examples import com.sksamuel.elastic4s.ElasticDsl import com.sksamuel.elastic4s.source.Indexable // examples of the count API in dot notation class UpdateDotDsl extends ElasticDsl { // update a doc by id in a given index / type.specifying a replacement doc update("id").in("index" / "type").doc("name" -> "sam", "occuptation" -> "build breaker") // update a doc by id in a given index / type specifying a replacement doc with the optimistic locking set update("id").in("index" / "type").version(3).doc("name" -> "sam", "occuptation" -> "build breaker") // update by id, using an implicit indexable for the updated doc case class Document(a: String, b: String, c: String) val somedoc = Document("a", "b", "c") implicit case object DocumentIndexable extends Indexable[Document] { override def json(t: Document): String = ??? } update("id").in("index" / "type").source(somedoc) // update by id, using a script update("id").in("index" / "type").script("ctx._source.somefield = 'value'") // update by id, using a script, where the script language is specified update("id").in("index" / "type").script("ctx._source.somefield = 'value'").lang("sillylang") // update by id, using a script which has parameters which are passed in as a map update("id").in("index" / "type").script("ctx._source.somefield = myparam").params(Map("myparam" -> "sam")) }
l15k4/elastic4s
elastic4s-examples/src/main/scala/com/sksamuel/elastic4s/examples/UpdateDotDsl.scala
Scala
apache-2.0
1,417
/* Copyright (C) 2008-2014 University of Massachusetts Amherst. This file is part of "FACTORIE" (Factor graphs, Imperative, Extensible) http://factorie.cs.umass.edu, http://github.com/factorie Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cc.factorie.optimize import cc.factorie._ import cc.factorie.la._ import scala.collection.mutable.ArrayBuffer import cc.factorie.util.FastLogging import cc.factorie.model.{WeightsMap, WeightsSet} // TODO What kind of regularization would be used with LBFGS other than L2? // If nothing, then incorporate it directly into LBFGS. -akm /** A quasi-Newton batch gradient optimizer. Limited-memory BFGS, as described in Byrd, Nocedal, and Schnabel, "Representations of Quasi-Newton Matrices and Their Use in Limited Memory Methods" */ class LBFGS(var numIterations: Double = 1000, var maxIterations: Int = 1000, var tolerance: Double = 0.0001, var gradientTolerance : Double= 0.001, val eps : Double = 1.0e-5, val rankOfApproximation : Int = 4, val initialStepSize : Double = 1.0) extends GradientOptimizer with FastLogging { private var _isConverged = false def isConverged = _isConverged case class StepTooSmallException(msg:String) extends Exception(msg) var lineMaximizer: BackTrackLineOptimizer = null // The number of corrections used in BFGS update // ideally 3 <= m <= 7. Larger m means more cpu time, memory. // State of search // g = gradient // s = list of m previous "parameters" values // y = list of m previous "g" values // rho = intermediate calculation var g: WeightsMap = null var oldg: WeightsMap = null var direction: WeightsMap = null var params: WeightsSet = null var oldParams: WeightsMap = null var s: ArrayBuffer[WeightsMap] = null var y: ArrayBuffer[WeightsMap] = null var rho: ArrayBuffer[Double] = null var alpha: Array[Double] = null var step = 1.0 var iterations: Int = 0 var oldValue: Double = Double.NegativeInfinity // override to evaluate on dev set, save the intermediate model, etc. def postIteration(iter: Int): Unit = () def reset(): Unit = { _isConverged = false step = 1.0 iterations = 0 oldValue = Double.NegativeInfinity g = null s = null y = null rho = null alpha = null params = null oldParams = null direction = null oldg = null } def initializeWeights(weights: WeightsSet): Unit = { } def finalizeWeights(weights: WeightsSet): Unit = { } def step(weights:WeightsSet, gradient:WeightsMap, value:Double): Unit = { if (_isConverged) return //todo: is the right behavior to set _isConverged = true if exceeded numIters? if (iterations > numIterations) { logger.warn("LBFGS: Failed to converge: too many iterations"); _isConverged = true; return } //if first time in, initialize if (g == null) { logger.debug("LBFGS: Initial value = " + value) iterations = 0 s = new ArrayBuffer[WeightsMap] y = new ArrayBuffer[WeightsMap] rho = new ArrayBuffer[Double] alpha = new Array[Double](rankOfApproximation) params = weights oldParams = params.copy //use copy to get the right size g = gradient oldg = gradient.copy direction = gradient.copy if (direction.twoNorm == 0) { logger.info("LBFGS: Initial initial gradient is zero; saying converged") g = null _isConverged = true //return true; } direction.*=(1.0 / direction.twoNorm) // take a step in the direction lineMaximizer = new BackTrackLineOptimizer(gradient, direction, initialStepSize) lineMaximizer.step(weights, gradient, value) //todo: change this to just check if lineOptimizer has converged // if (step == 0.0) { // // could not step in this direction // // give up and say converged // g = null // reset search // step = 1.0 // logger.error("Line search could not step in the current direction. " + // "(This is not necessarily cause for alarm. Sometimes this happens close to the maximum," + // " where the function may be very flat.)") // //throw new StepTooSmallException("Line search could not step in current direction.") // return false // } oldValue = value }else if(!lineMaximizer.isConverged){ lineMaximizer.step(weights, gradient, value) } //else{ if (lineMaximizer.isConverged) { //first, check for convergence: iterations += 1 logger.debug("LBFGS: At iteration " + iterations + ", value = " + value) //params and g are just aliases for the names of the variables passed in g = gradient params = weights if (2.0 * math.abs(value - oldValue) <= tolerance * (math.abs(value) + math.abs(oldValue) + eps)) { logger.debug("LBFGS: Exiting on termination #1: value difference below tolerance (oldValue: " + oldValue + " newValue: " + value) _isConverged = true return } val gg = g.twoNorm if (gg < gradientTolerance) { logger.trace("LBFGS: Exiting on termination #2: gradient=" + gg + " < " + gradientTolerance) _isConverged = true return } if (gg == 0.0) { logger.trace("LBFGS: Exiting on termination #3: gradient==0.0") _isConverged = true return } logger.trace("Gradient = " + gg) iterations += 1 if (iterations > maxIterations) { logger.warn("Too many iterations in L-BFGS.java. Continuing with current parameters.") _isConverged = true return } // get difference between previous 2 gradients and parameters var sy = 0.0 var yy = 0.0 //todo: these next check are quite inefficient, but is a hack to avoid doing the following line on tensors: //params(i).isInfinite && oldParams(i).isInfinite && (params(i) * oldParams(i) > 0)) 0.0 if(!params.toArray.forall(d => !(d == Double.PositiveInfinity || d == Double.NegativeInfinity))) throw new IllegalStateException("Weight value can't be infinite") if(!gradient.toArray.forall(d => !(d == Double.PositiveInfinity || d == Double.NegativeInfinity))) throw new IllegalStateException("gradient value can't be infinite") oldParams = params - oldParams oldg = g - oldg sy = oldParams dot oldg yy = oldg.twoNormSquared direction := gradient if (sy > 0) throw new IllegalStateException("sy=" + sy + "> 0") val gamma = sy / yy // scaling factor if (gamma > 0) throw new IllegalStateException("gamma=" + gamma + "> 0") pushDbl(rho, 1.0 / sy) pushTensor(s, oldParams) pushTensor(y, oldg) // calculate new direction assert(s.size == y.size) for (i <- s.size -1 to 0 by -1) { // alpha(i) = rho(i) * ArrayOps.dot(direction, s(i)) alpha(i) = rho(i) * (direction dot s(i)) // ArrayOps.incr(direction, y(i), -1.0 * alpha(i)) direction.+=(y(i),-1.0 * alpha(i)) } direction.*=(gamma) for (i <- 0 until s.size) { //val beta = rho(i) * ArrayOps.dot(direction, y(i)) val beta = rho(i) * (direction dot y(i)) //ArrayOps.incr(direction, s(i), alpha(i) - beta) direction.+=(s(i),alpha(i) - beta) } oldParams := params oldValue = value oldg := g direction.*=(-1) lineMaximizer = null postIteration(iterations) lineMaximizer = new BackTrackLineOptimizer(gradient, direction, initialStepSize) lineMaximizer.step(weights, gradient, value) } } def pushTensor(l: ArrayBuffer[WeightsMap], toadd: WeightsMap): Unit = { assert(l.size <= rankOfApproximation) if (l.size == rankOfApproximation) { l.remove(0) l += toadd.copy //todo: change back to this circular thing below // val last = l(0) // Array.copy(toadd, 0, last, 0, toadd.length) // forIndex(l.size - 1)(i => {l(i) = l(i + 1)}) // l(m - 1) = last } else { l += toadd.copy } } def pushDbl(l: ArrayBuffer[Double], toadd: Double): Unit = { assert(l.size <= rankOfApproximation) if (l.size == rankOfApproximation) l.remove(0) l += toadd } } //class L2RegularizedLBFGS(var l2: Double = 0.1) extends LBFGS { // override def step(weightsSet: Tensor, gradient: Tensor, value: Double, margin: Double) { // gradient += (weightsSet, -l2) // super.step(weightsSet, gradient, value - l2 * (weightsSet dot weightsSet), margin) // } //}
hlin117/factorie
src/main/scala/cc/factorie/optimize/LBFGS.scala
Scala
apache-2.0
9,206
/* __ *\\ ** ________ ___ / / ___ Scala API ** ** / __/ __// _ | / / / _ | (c) 2003-2013, LAMP/EPFL ** ** __\\ \\/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** ** /____/\\___/_/ |_/____/_/ | | ** ** |/ ** \\* */ package scala package sys package process import processInternal._ import ProcessBuilder._ /** Represents a sequence of one or more external processes that can be * executed. A `ProcessBuilder` can be a single external process, or a * combination of other `ProcessBuilder`. One can control where the * output of an external process will go to, and where its input will come * from, or leave that decision to whoever starts it. * * One creates a `ProcessBuilder` through factories provided in * [[scala.sys.process.Process]]'s companion object, or implicit conversions * based on these factories made available in the package object * [[scala.sys.process]]. Here are some examples: * {{{ * import scala.sys.process._ * * // Executes "ls" and sends output to stdout * "ls".! * * // Execute "ls" and assign a `Stream[String]` of its output to "contents". * val contents = Process("ls").lineStream * * // Here we use a `Seq` to make the parameter whitespace-safe * def contentsOf(dir: String): String = Seq("ls", dir).!! * }}} * * The methods of `ProcessBuilder` are divided in three categories: the ones that * combine two `ProcessBuilder` to create a third, the ones that redirect input * or output of a `ProcessBuilder`, and the ones that execute * the external processes associated with it. * * ==Combining `ProcessBuilder`== * * Two existing `ProcessBuilder` can be combined in the following ways: * * - They can be executed in parallel, with the output of the first being fed * as input to the second, like Unix pipes. This is achieved with the `#|` * method. * - They can be executed in sequence, with the second starting as soon as * the first ends. This is done by the `###` method. * - The execution of the second one can be conditioned by the return code * (exit status) of the first, either only when it's zero, or only when it's * not zero. The methods `#&&` and `#||` accomplish these tasks. * * ==Redirecting Input/Output== * * Though control of input and output can be done when executing the process, * there's a few methods that create a new `ProcessBuilder` with a * pre-configured input or output. They are `#<`, `#>` and `#>>`, and may take * as input either another `ProcessBuilder` (like the pipe described above), or * something else such as a `java.io.File` or a `java.io.InputStream`. * For example: * {{{ * new URL("http://databinder.net/dispatch/About") #> "grep JSON" #>> new File("About_JSON") ! * }}} * * ==Starting Processes== * * To execute all external commands associated with a `ProcessBuilder`, one * may use one of four groups of methods. Each of these methods have various * overloads and variations to enable further control over the I/O. These * methods are: * * - `run`: the most general method, it returns a * [[scala.sys.process.Process]] immediately, and the external command * executes concurrently. * - `!`: blocks until all external commands exit, and returns the exit code * of the last one in the chain of execution. * - `!!`: blocks until all external commands exit, and returns a `String` * with the output generated. * - `lineStream`: returns immediately like `run`, and the output being generated * is provided through a `Stream[String]`. Getting the next element of that * `Stream` may block until it becomes available. This method will throw an * exception if the return code is different than zero -- if this is not * desired, use the `lineStream_!` method. * * ==Handling Input and Output== * * If not specified, the input of the external commands executed with `run` or * `!` will not be tied to anything, and the output will be redirected to the * stdout and stderr of the Scala process. For the methods `!!` and `lineStream`, no * input will be provided, and the output will be directed according to the * semantics of these methods. * * Some methods will cause stdin to be used as input. Output can be controlled * with a [[scala.sys.process.ProcessLogger]] -- `!!` and `lineStream` will only * redirect error output when passed a `ProcessLogger`. If one desires full * control over input and output, then a [[scala.sys.process.ProcessIO]] can be * used with `run`. * * For example, we could silence the error output from `lineStream_!` like this: * {{{ * val etcFiles = "find /etc" lineStream_! ProcessLogger(line => ()) * }}} * * ==Extended Example== * * Let's examine in detail one example of usage: * {{{ * import scala.sys.process._ * "find src -name *.scala -exec grep null {} ;" #| "xargs test -z" #&& "echo null-free" #|| "echo null detected" ! * }}} * Note that every `String` is implicitly converted into a `ProcessBuilder` * through the implicits imported from [[scala.sys.process]]. These `ProcessBuilder` are then * combined in three different ways. * * 1. `#|` pipes the output of the first command into the input of the second command. It * mirrors a shell pipe (`|`). * 1. `#&&` conditionally executes the second command if the previous one finished with * exit value 0. It mirrors shell's `&&`. * 1. `#||` conditionally executes the third command if the exit value of the previous * command is different than zero. It mirrors shell's `||`. * * Finally, `!` at the end executes the commands, and returns the exit value. * Whatever is printed will be sent to the Scala process standard output. If * we wanted to capture it, we could run that with `!!` instead. * * Note: though it is not shown above, the equivalent of a shell's `;` would be * `###`. The reason for this name is that `;` is a reserved token in Scala. * * Note: the `lines` method, though deprecated, may conflict with the `StringLike` * method of the same name. To avoid this, one may wish to call the builders in * `Process` instead of importing `scala.sys.process._`. The example above would be * {{{ * import scala.sys.process.Process * Process("find src -name *.scala -exec grep null {} ;") #| Process("xargs test -z") #&& Process("echo null-free") #|| Process("echo null detected") ! * }}} */ trait ProcessBuilder extends Source with Sink { /** Starts the process represented by this builder, blocks until it exits, and * returns the output as a String. Standard error is sent to the console. If * the exit code is non-zero, an exception is thrown. */ def !! : String /** Starts the process represented by this builder, blocks until it exits, and * returns the output as a String. Standard error is sent to the provided * ProcessLogger. If the exit code is non-zero, an exception is thrown. */ def !!(log: ProcessLogger): String /** Starts the process represented by this builder, blocks until it exits, and * returns the output as a String. Standard error is sent to the console. If * the exit code is non-zero, an exception is thrown. The newly started * process reads from standard input of the current process. */ def !!< : String /** Starts the process represented by this builder, blocks until it exits, and * returns the output as a String. Standard error is sent to the provided * ProcessLogger. If the exit code is non-zero, an exception is thrown. The * newly started process reads from standard input of the current process. */ def !!<(log: ProcessLogger): String /** Starts the process represented by this builder. The output is returned as * a Stream that blocks when lines are not available but the process has not * completed. Standard error is sent to the console. If the process exits * with a non-zero value, the Stream will provide all lines up to termination * and then throw an exception. */ def lineStream: Stream[String] /** Deprecated (renamed). Use `lineStream` instead. */ @deprecated("use lineStream instead", "2.11.0") def lines: Stream[String] = lineStream /** Starts the process represented by this builder. The output is returned as * a Stream that blocks when lines are not available but the process has not * completed. Standard error is sent to the provided ProcessLogger. If the * process exits with a non-zero value, the Stream will provide all lines up * to termination and then throw an exception. */ def lineStream(log: ProcessLogger): Stream[String] /** Deprecated (renamed). Use `lineStream(log: ProcessLogger)` instead. */ @deprecated("use stream instead", "2.11.0") def lines(log: ProcessLogger): Stream[String] = lineStream(log) /** Starts the process represented by this builder. The output is returned as * a Stream that blocks when lines are not available but the process has not * completed. Standard error is sent to the console. If the process exits * with a non-zero value, the Stream will provide all lines up to termination * but will not throw an exception. */ def lineStream_! : Stream[String] /** Deprecated (renamed). Use `lineStream_!` instead. */ @deprecated("use lineStream_! instead", "2.11.0") def lines_! : Stream[String] = lineStream_! /** Starts the process represented by this builder. The output is returned as * a Stream that blocks when lines are not available but the process has not * completed. Standard error is sent to the provided ProcessLogger. If the * process exits with a non-zero value, the Stream will provide all lines up * to termination but will not throw an exception. */ def lineStream_!(log: ProcessLogger): Stream[String] /** Deprecated (renamed). Use `lineStream_!(log: ProcessLogger)` instead. */ @deprecated("use stream_! instead", "2.11.0") def lines_!(log: ProcessLogger): Stream[String] = lineStream_!(log) /** Starts the process represented by this builder, blocks until it exits, and * returns the exit code. Standard output and error are sent to the console. */ def ! : Int /** Starts the process represented by this builder, blocks until it exits, and * returns the exit code. Standard output and error are sent to the given * ProcessLogger. */ def !(log: ProcessLogger): Int /** Starts the process represented by this builder, blocks until it exits, and * returns the exit code. Standard output and error are sent to the console. * The newly started process reads from standard input of the current process. */ def !< : Int /** Starts the process represented by this builder, blocks until it exits, and * returns the exit code. Standard output and error are sent to the given * ProcessLogger. The newly started process reads from standard input of the * current process. */ def !<(log: ProcessLogger): Int /** Starts the process represented by this builder. Standard output and error * are sent to the console.*/ def run(): Process /** Starts the process represented by this builder. Standard output and error * are sent to the given ProcessLogger. */ def run(log: ProcessLogger): Process /** Starts the process represented by this builder. I/O is handled by the * given ProcessIO instance. */ def run(io: ProcessIO): Process /** Starts the process represented by this builder. Standard output and error * are sent to the console. The newly started process reads from standard * input of the current process if `connectInput` is true. */ def run(connectInput: Boolean): Process /** Starts the process represented by this builder, blocks until it exits, and * returns the exit code. Standard output and error are sent to the given * ProcessLogger. The newly started process reads from standard input of the * current process if `connectInput` is true. */ def run(log: ProcessLogger, connectInput: Boolean): Process /** Constructs a command that runs this command first and then `other` if this * command succeeds. */ def #&& (other: ProcessBuilder): ProcessBuilder /** Constructs a command that runs this command first and then `other` if this * command does not succeed. */ def #|| (other: ProcessBuilder): ProcessBuilder /** Constructs a command that will run this command and pipes the output to * `other`. `other` must be a simple command. */ def #| (other: ProcessBuilder): ProcessBuilder /** Constructs a command that will run this command and then `other`. The * exit code will be the exit code of `other`. */ def ### (other: ProcessBuilder): ProcessBuilder /** True if this command can be the target of a pipe. */ def canPipeTo: Boolean /** True if this command has an exit code which should be propagated to the * user. Given a pipe between A and B, if B.hasExitValue is true then the * exit code will be the one from B; if it is false, the one from A. This * exists to prevent output redirections (implemented as pipes) from masking * useful process error codes. */ def hasExitValue: Boolean } /** This object contains traits used to describe input and output sources. */ object ProcessBuilder extends ProcessBuilderImpl { /** Used when creating [[scala.sys.process.ProcessBuilder.Source]] from an URL. */ trait URLBuilder extends Source { } /** Used when creating [[scala.sys.process.ProcessBuilder.Source]] and/or * [[scala.sys.process.ProcessBuilder.Sink]] from a file. */ trait FileBuilder extends Sink with Source { /** Append the contents of a `java.io.File` to this file */ def #<<(f: File): ProcessBuilder /** Append the contents from a `java.net.URL` to this file */ def #<<(u: URL): ProcessBuilder /** Append the contents of a `java.io.InputStream` to this file */ def #<<(i: => InputStream): ProcessBuilder /** Append the contents of a [[scala.sys.process.ProcessBuilder]] to this file */ def #<<(p: ProcessBuilder): ProcessBuilder } /** Represents everything that can be used as an input to a * [[scala.sys.process.ProcessBuilder]]. */ trait Source { protected def toSource: ProcessBuilder /** Writes the output stream of this process to the given file. */ def #> (f: File): ProcessBuilder = toFile(f, append = false) /** Appends the output stream of this process to the given file. */ def #>> (f: File): ProcessBuilder = toFile(f, append = true) /** Writes the output stream of this process to the given OutputStream. The * argument is call-by-name, so the stream is recreated, written, and closed each * time this process is executed. */ def #>(out: => OutputStream): ProcessBuilder = #> (new OStreamBuilder(out, "<output stream>")) /** Writes the output stream of this process to a [[scala.sys.process.ProcessBuilder]]. */ def #>(b: ProcessBuilder): ProcessBuilder = new PipedBuilder(toSource, b, false) /** Returns a [[scala.sys.process.ProcessBuilder]] representing this `Source`. */ def cat = toSource private def toFile(f: File, append: Boolean) = #> (new FileOutput(f, append)) } /** Represents everything that can receive an output from a * [[scala.sys.process.ProcessBuilder]]. */ trait Sink { protected def toSink: ProcessBuilder /** Reads the given file into the input stream of this process. */ def #< (f: File): ProcessBuilder = #< (new FileInput(f)) /** Reads the given URL into the input stream of this process. */ def #< (f: URL): ProcessBuilder = #< (new URLInput(f)) /** Reads the given InputStream into the input stream of this process. The * argument is call-by-name, so the stream is recreated, read, and closed each * time this process is executed. */ def #<(in: => InputStream): ProcessBuilder = #< (new IStreamBuilder(in, "<input stream>")) /** Reads the output of a [[scala.sys.process.ProcessBuilder]] into the input stream of this process. */ def #<(b: ProcessBuilder): ProcessBuilder = new PipedBuilder(b, toSink, false) } }
felixmulder/scala
src/library/scala/sys/process/ProcessBuilder.scala
Scala
bsd-3-clause
16,674
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package system.stress import system.utils.KafkaUtils import scala.concurrent.duration.DurationInt import scala.language.postfixOps import org.junit.runner.RunWith import org.scalatest.FlatSpec import org.scalatest.Matchers import org.scalatest.junit.JUnitRunner import common.TestHelpers import common.Wsk import common.WskActorSystem import common.WskProps import common.WskTestHelpers import spray.json.DefaultJsonProtocol._ import spray.json._ @RunWith(classOf[JUnitRunner]) class BasicStressTest extends FlatSpec with Matchers with WskActorSystem with TestHelpers with WskTestHelpers with KafkaUtils { val topic = "test" val sessionTimeout = 10 seconds implicit val wskprops = WskProps() val wsk = new Wsk() val messagingPackage = "/whisk.system/messaging" val messageHubFeed = "messageHubFeed" val messageHubProduce = "messageHubProduce" behavior of "Message Hub provider" it should "rapidly create and delete many triggers" in { stressTriggerCreateAndDelete(totalIterations = 100, keepNthTrigger = 5) } /* * Recursively create and delete (potentially) lots of triggers * * @param totalIterations The total number of triggers to create * @param keepNthTrigger Optionally, do not delete the trigger created on every N iterations * @param currentIteration Used for recursion * @param storedTriggers The list of trigger names that were created, but not deleted (see keepNthTrigger) */ def stressTriggerCreateAndDelete(totalIterations : Int, keepNthTrigger : Int, currentIteration : Int = 0, storedTriggers : List[String] = List[String]()) { if(currentIteration < totalIterations) { val currentTime = s"${System.currentTimeMillis}" // use this to print non-zero-based iteration numbers you know... for humans val iterationLabel = currentIteration + 1 val triggerName = s"/_/dummyMessageHubTrigger-$currentTime" println(s"\\nCreating trigger #${iterationLabel}: ${triggerName}") val feedCreationResult = wsk.trigger.create(triggerName, feed = Some(s"$messagingPackage/$messageHubFeed"), parameters = Map( "user" -> getAsJson("user"), "password" -> getAsJson("password"), "api_key" -> getAsJson("api_key"), "kafka_admin_url" -> getAsJson("kafka_admin_url"), "kafka_brokers_sasl" -> getAsJson("brokers"), "topic" -> topic.toJson)) println("Waiting for trigger create") withActivation(wsk.activation, feedCreationResult, initialWait = 5 seconds, totalWait = 60 seconds) { activation => // should be successful activation.response.success shouldBe true } // optionally allow triggers to pile up on the provider if((iterationLabel % keepNthTrigger) != 0) { println("Deleting trigger") val feedDeletionResult = wsk.trigger.delete(triggerName) feedDeletionResult.stdout should include("ok") stressTriggerCreateAndDelete(totalIterations, keepNthTrigger, currentIteration + 1, storedTriggers) } else { println("I think I'll keep this trigger...") stressTriggerCreateAndDelete(totalIterations, keepNthTrigger, currentIteration + 1, triggerName :: storedTriggers) } } else { println("\\nCompleted all iterations, now cleaning up stored triggers.") for(triggerName <- storedTriggers) { println(s"Deleting trigger: ${triggerName}") val feedDeletionResult = wsk.trigger.delete(triggerName) feedDeletionResult.stdout should include("ok") } } } }
dubeejw/openwhisk-package-kafka
tests/src/test/scala/system/stress/StressTest.scala
Scala
apache-2.0
4,703
package adt.bson.mongo.bulk import adt.bson.mongo.WriteError import adt.bson.{BsonObject, BsonValue} import scala.language.implicitConversions /** * Avoids name collision with the [[WriteRequest]] Scala version if both are imported. */ object JavaBulkModels extends JavaBulkModels trait JavaBulkModels { type JavaBulkWriteError = com.mongodb.bulk.BulkWriteError type JavaBulkWriteResult = com.mongodb.bulk.BulkWriteResult type JavaBulkWriteUpsert = com.mongodb.bulk.BulkWriteUpsert type JavaDeleteRequest = com.mongodb.bulk.DeleteRequest type JavaIndexRequest = com.mongodb.bulk.IndexRequest type JavaInsertRequest = com.mongodb.bulk.InsertRequest type JavaUpdateRequest = com.mongodb.bulk.UpdateRequest type JavaWriteConcernError = com.mongodb.bulk.WriteConcernError type JavaWriteRequest = com.mongodb.bulk.WriteRequest type JavaWriteRequestType = com.mongodb.bulk.WriteRequest.Type } object JavaWriteRequest { type Type = com.mongodb.bulk.WriteRequest.Type object Type { final val DELETE = com.mongodb.bulk.WriteRequest.Type.DELETE final val INSERT = com.mongodb.bulk.WriteRequest.Type.INSERT final val REPLACE = com.mongodb.bulk.WriteRequest.Type.REPLACE final val UPDATE = com.mongodb.bulk.WriteRequest.Type.UPDATE } } /** * Constructs a new instance (substitutes [[com.mongodb.bulk.BulkWriteError]]). * * @param code the error code * @param message the error message * @param details details about the error * @param index the index of the item in the bulk write operation that had this error */ case class BulkWriteError(code: Int, message: String, details: BsonObject, index: Int) extends WriteError /** * Represents an item in the bulk write that was upserted (substitutes [[com.mongodb.bulk.BulkWriteUpsert]]). * * @param index the index in the list of bulk write requests that the upsert occurred in * @param id the id of the document that was inserted as the result of the upsert */ case class BulkWriteUpsert(index: Int, id: BsonValue) object BulkWriteUpsert { implicit def from(upsert: JavaBulkWriteUpsert): BulkWriteUpsert = BulkWriteUpsert(upsert.getIndex, upsert.getId.toBson) } /** * An error representing a failure by the server to apply the requested write concern to the bulk operation * (substitutes [[com.mongodb.bulk.WriteConcernError]]). * * @param code the error code * @param message the error message * @param details any details */ case class WriteConcernError(code: Int, message: String, details: BsonObject)
jeffmay/bson-adt
bson-adt-mongo3-async/src/main/scala/adt/bson/mongo/bulk/JavaBulkModels.scala
Scala
apache-2.0
2,551
package structures package laws trait MonadFilterLaws[F[_]] extends MonadLaws[F] { implicit val typeClass: MonadFilter[F] import MonadFilter.ops._, typeClass.empty def monadFilterLeftDistributivity[A, B](f: A => F[B]): IsEqual[F[B]] = empty[A].flatMap(f) =?= empty[B] def monadFilterRightDistributivity[A](fa: F[A]): IsEqual[F[A]] = fa.flatMap { a => empty[A] } =?= empty[A] } object MonadFilterLaws { def apply[F[_]: MonadFilter]: MonadFilterLaws[F] = new MonadFilterLaws[F] { val typeClass = MonadFilter[F] } }
mpilquist/Structures
laws/src/main/scala/structures/laws/MonadFilterLaws.scala
Scala
bsd-3-clause
543
/* * Copyright (c) <2015-2016>, see CONTRIBUTORS * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.usi.inf.l3.sana.robustj.typechecker import ch.usi.inf.l3.sana import sana.robustj import sana.arrooj import sana.arrayj import sana.ooj import sana.brokenj import sana.primj import sana.tiny import sana.calcj import tiny.core.TransformationComponent import tiny.dsl._ // ASTs import robustj.ast._ import arrooj.ast.Implicits._ import arrayj.ast.{TreeUtils => _, TreeCopiers => _, TreeFactories => _, _} import ooj.ast.{TreeUtils => _, TreeCopiers => _, TreeFactories => _, MethodDefApi => _, TreeUpgraders => _, _} import brokenj.ast.{TreeUtils => _, TreeCopiers => _, TreeFactories => _, _} import primj.ast.{TreeUtils => _, TreeCopiers => _, TreeFactories => _, MethodDefApi => PMethodDefApi, ProgramApi => _, _} import calcj.ast.{TreeUtils => _, TreeCopiers => _, TreeFactories => _, _} import tiny.ast.{TreeCopiers => _, TreeFactories => _, _} import tiny.types.Type import tiny.symbols.Symbol import robustj.symbols.MethodSymbol import tiny.errors.ErrorReporting.{error, warning} import tiny.source.Position import robustj.errors.ErrorCodes._ import robustj.types.TypeUtils /* Program: DONE CompilationUnit: DONE PackageDef: DONE ClassDef: DONE Template: DONE ValDef: DONE Block: DONE New: DONE Select: DONE This: DONE Super: DONE Ident: DONE TypeUse: DONE Cast: DONE Literal: DONE Binary: DONE Unary: DONE Assign: DONE If: DONE While: DONE For: DONE Ternary: DONE Return: DONE Label: DONE Break: DONE Continue: DONE Case: DONE Switch: DONE ArrayInitializer: DONE ArrayAccess: DONE ArrayTypeUse: DONE ArrayCreation: DONE Catch: DONE MethodDef: DONE Apply: DONE Try: Throw: DONE */ /** * A class to represent a handled (caught or declared) exception * * @param tpe the type of this exception * @param pos the position of this exception * @param state the state of this exception, possible states: * <li> It is declared in the method signature (in the throws clause) * <li> it is handled by a catch-block and is already thrown * <li> it is handled by a catch-block and is not thrown yet */ case class HandledException(tpe: Type, pos: Position, state: State) { override def equals(other: Any): Boolean = other match { case null => false case that: HandledException => this.pos == that.pos case _ => false } override def hashCode: Int = 43 * this.pos.hashCode } /** * A utility trait for performing different exception-handling related checks */ trait ExceptionUtils { /** * Given a list of handled exceptions and an exception type, updates the first * handled exception that has the same type as `t`, if it has the state * UnusedCaught, it marks it as UsedCaught. * * @param t the type of exception to update * @param he the list of handled exceptions */ def updateFirstOccurance(t: Type, he: List[HandledException]): Option[List[HandledException]] = he match { case (h::hs) if t <:< h.tpe => if(h.state == ThrownClause) Some(he) else Some(HandledException(h.tpe, h.pos, UsedCaught)::hs) case (h::hs) if t >:> h.tpe => if(h.state == ThrownClause) updateFirstOccurance(t, hs).map(h::_) else updateFirstOccurance(t, hs) .map(HandledException(h.tpe, h.pos, UsedCaught)::_) case (h::hs) => updateFirstOccurance(t, hs).map(h::_) case Nil => None } /** * Given two lists of handled-exceptions, unifies them. In case * the same exception has the state UsedCaught in one list, then in the * resulting list it will have UseCaught too. */ def unify(fst: List[HandledException], snd: List[HandledException]): List[HandledException] = { for { f <- fst } yield { if(snd.exists(s => (f == s && (f.state == UsedCaught || s.state == UsedCaught)))) { f.copy(state = UsedCaught) } else f } } /** * Given lists lists of handled-exceptions, unifies them. In case * the same exception has the state UsedCaught in one list, then in the * resulting list it will have UseCaught too. */ def unify(fst: List[HandledException], snd: List[HandledException], thrd: List[HandledException]): List[HandledException] = for { f <- fst } yield { if(snd.exists(s => (f == s && (f.state == UsedCaught || s.state == UsedCaught))) || thrd.exists(s => (f == s && (f.state == UsedCaught || s.state == UsedCaught)))) { f.copy(state = UsedCaught) } else f } } object ExceptionUtils extends ExceptionUtils /** The state of an exception */ trait State /** An exception is declared in the method signature (throws clause) */ case object ThrownClause extends State /** An exception is caught by a catch block, and is already thrown */ case object UsedCaught extends State /** An exception is caught by a catch block, and is not thrown yet */ case object UnusedCaught extends State /** * This phase makes that all reported "checked" exceptions are declared, and * all declared exceptions are declared. */ trait ExceptionHandlingCheckerComponent extends TransformationComponent[(Tree, List[HandledException]), List[HandledException]] { def check: ((Tree, List[HandledException])) => List[HandledException] } // Interesting cases @component(tree, handledExceptions) trait MethodDefExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (mthd: PMethodDefApi) => { mthd match { case mthd: MethodDefApi => val he1 = getHandledExceptions(mthd) val he2 = check((mthd.body, he1 ++ handledExceptions)) val he3 = he2.drop(he1.length) unify(he3, handledExceptions) case mthd: PMethodDefApi => val res = TreeUpgraders.upgradeMethodDef(mthd) check((res, handledExceptions)) } } /** @see {{{ExceptionUtils.unify}}} */ protected def unify(fst: List[HandledException], snd: List[HandledException]): List[HandledException] = ExceptionUtils.unify(fst, snd) /** * Return all the declared (handled) exception of a method * * @param mthd the method to return its declared (handled) exceptions */ protected def getHandledExceptions( mthd: MethodDefApi): List[HandledException] = { mthd.symbol.map { case sym: MethodSymbol => for { sym <- sym.throwsSymbols tpe <- sym.tpe pos <- mthd.pos } yield HandledException(tpe, pos, ThrownClause) case e => Nil }.getOrElse(Nil) } } @component(tree, handledExceptions) trait ThrowExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (thrw: ThrowApi) => { val he = check((thrw.expr, handledExceptions)) thrw.expr.tpe.flatMap(updateFirstOccurance(_, he)).getOrElse(he) } /** @see [[ExceptionUtils.updateFirstOccurance]] */ protected def updateFirstOccurance(t: Type, he: List[HandledException]): Option[List[HandledException]] = ExceptionUtils.updateFirstOccurance(t, he) } @component(tree, handledExceptions) trait ApplyExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (apply: ApplyApi) => { val he = check((apply.fun, handledExceptions)) val he1 = checkThrownExceptions(apply, he) apply.args.foldLeft(he1) { (z, y) => check((y, z)) } } /** @see [[ExceptionUtils.updateFirstOccurance]] */ protected def updateFirstOccurance(t: Type, he: List[HandledException]): Option[List[HandledException]] = ExceptionUtils.updateFirstOccurance(t, he) /** * Check if all the possible exceptions that may be thrown by this * method/function is handled either by a try-catch statement or * declared by the enclosing method of this expression. * * @param apply the method/function application in question * @param he the exceptions that are handled at this point */ protected def checkThrownExceptions(apply: ApplyApi, he: List[HandledException]): List[HandledException] = { val thrownExceptions = apply.fun.symbol match { case Some(s: MethodSymbol) => s.throwsSymbols case _ => Nil } thrownExceptions.foldLeft(he) { (z, y) => if(isCheckedException(y.tpe)) { y.tpe.flatMap(updateFirstOccurance(_, z)) match { case Some(he) => he case None => error(UNREPORTED_EXCEPTION, "", "", apply.pos) z } } else z } } /** @see [[robustj.types.TypeUtils.isCheckedException]] */ protected def isCheckedException(tpe: Option[Type]): Boolean = TypeUtils.isCheckedException(tpe) } @component(tree, handledExceptions) trait TryExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (tri: TryApi) => { val handled = getHandledExceptions(tri.catches) val he1 = handled ++ handledExceptions val he2 = check((tri.tryClause, he1)) val (handled2, he3) = he2.splitAt(handled.size) val he4 = tri.catches.foldLeft(he3)((z, y) => { val z2 = check((y, z)) unify(z, z2) }) val he5 = tri.finallyClause.map(f => check((f, he4))).getOrElse(he4) checkHandledExceptions(handled2) unify(he3, he4, he5) } /** @see {{{ExceptionUtils.unify}}} */ protected def unify(fst: List[HandledException], snd: List[HandledException]): List[HandledException] = ExceptionUtils.unify(fst, snd) /** @see {{{ExceptionUtils.unify}}} */ protected def unify(fst: List[HandledException], snd: List[HandledException], thd: List[HandledException]): List[HandledException] = ExceptionUtils.unify(fst, snd, thd) /** * Return all the caught (handled) exceptions by this try-catch statement * * @param catches the list of catch-blocks of this try-catch statement */ protected def getHandledExceptions(catches: List[CatchApi]): List[HandledException] = for { ctch <- catches tpe <- ctch.eparam.tpe pos <- ctch.eparam.pos } yield HandledException(tpe, pos, UnusedCaught) /** * Checks if all the definitively checked exceptions that are handled * are actually thrown in the body of the method * * @param he the list to be checked */ protected def checkHandledExceptions(he: List[HandledException]): Unit = for { handled <- he if isDefinitivelyCheckedException(Some(handled.tpe)) && handled.state == UnusedCaught } { error(HANDLING_NON_THROWN_EXCEPTION, "", "", Some(handled.pos)) } /** @see [[robustj.types.TypeUtils.isDefinitivelyCheckedException]] */ protected def isDefinitivelyCheckedException(p: Option[Type]): Boolean = TypeUtils.isDefinitivelyCheckedException(p) } // boring cases @component(tree, handledExceptions) trait ProgramExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (prg: ProgramApi) => { prg.members.foreach(m => check((m, Nil))) Nil } } @component(tree, handledExceptions) trait CompilationUnitExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (cunit: CompilationUnitApi) => { check((cunit.module, Nil)) } } @component(tree, handledExceptions) trait PackageDefExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (pkg: PackageDefApi) => { pkg.members.foreach(m => check((m, Nil))) Nil } } @component(tree, handledExceptions) trait ClassDefExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (clazz: ClassDefApi) => { check((clazz.body, Nil)) } } @component(tree, handledExceptions) trait TemplateExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (template: TemplateApi) => { template.members.foreach(m => check((m, Nil))) Nil } } @component(tree, handledExceptions) trait NewExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (nw: NewApi) => { check((nw.app, handledExceptions)) } } @component(tree, handledExceptions) trait SelectExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (select: SelectApi) => { val he = check((select.qual, handledExceptions)) check((select.tree, he)) } } @component(tree, handledExceptions) trait ThisExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (ths: ThisApi) => handledExceptions } @component(tree, handledExceptions) trait SuperExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (spr: SuperApi) => handledExceptions } @component(tree, handledExceptions) trait ArrayCreationExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (creation: ArrayCreationApi) => { creation.size.map(size => check((size, handledExceptions))) .getOrElse(handledExceptions) } } @component(tree, handledExceptions) trait ArrayAccessExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (access: ArrayAccessApi) => { val he = check((access.array, handledExceptions)) check((access.index, he)) } } // @component(tree, handledExceptions) // trait ArrayTypeUseExceptionHandlingCheckerComponent // extends ExceptionHandlingCheckerComponent { // (tuse: ArrayTypeUseApi) => handledExceptions // } @component(tree, handledExceptions) trait ArrayInitializerExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (init: ArrayInitializerApi) => { init.elements.foldLeft(handledExceptions) { (z, y) => check((y, z)) } } } // @component(tree, handledExceptions) // trait ContinueExceptionHandlingCheckerComponent // extends ExceptionHandlingCheckerComponent { // (cont: ContinueApi) => handledExceptions // } // // @component(tree, handledExceptions) // trait BreakExceptionHandlingCheckerComponent // extends ExceptionHandlingCheckerComponent { // (break: BreakApi) => handledExceptions // // } @component(tree, handledExceptions) trait LabelExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (label: LabelApi) => check((label.stmt, handledExceptions)) } @component(tree, handledExceptions) trait CatchExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (ctch: CatchApi) => check((ctch.catchClause, handledExceptions)) } // boring cases @component(tree, handledExceptions) trait ValDefExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (vdef: ValDefApi) => check((vdef.rhs, handledExceptions)) } @component(tree, handledExceptions) trait AssignExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (assgn: AssignApi) => { val he = check((assgn.lhs, handledExceptions)) check((assgn.rhs, he)) } } @component(tree, handledExceptions) trait ReturnExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (ret: ReturnApi) => ret.expr.map(expr => check((expr, handledExceptions))) .getOrElse(handledExceptions) } @component(tree, handledExceptions) trait IfExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (ifelse: IfApi) => { val he1 = check((ifelse.cond, handledExceptions)) val he2 = check((ifelse.thenp, he1)) check((ifelse.elsep, he2)) } } @component(tree, handledExceptions) trait WhileExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (wile: WhileApi) => { val he = check((wile.cond, handledExceptions)) check((wile.body, he)) } } @component(tree, handledExceptions) trait BlockExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (block: BlockApi) => { block.stmts.foldLeft(handledExceptions){(z, y) => check((y, z)) } } } @component(tree, handledExceptions) trait ForExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (forloop: ForApi) => { val he1 = forloop.inits.foldLeft(handledExceptions){(z, y) => check((y, z)) } val he2 = check((forloop.cond, he1)) val he3 = forloop.steps.foldLeft(he2){(z, y) => check((y, z)) } check((forloop.body, he3)) } } @component(tree, handledExceptions) trait TernaryExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (ternary: TernaryApi) => { val he1 = check((ternary.cond, handledExceptions)) val he2 = check((ternary.thenp, he1)) check((ternary.elsep, he2)) } } @component(tree, handledExceptions) trait CastExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (cast: CastApi) => { check((cast.expr, handledExceptions)) } } @component(tree, handledExceptions) trait UnaryExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (unary: UnaryApi) => { check((unary.expr, handledExceptions)) } } @component(tree, handledExceptions) trait BinaryExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (binary: BinaryApi) => { val he = check((binary.lhs, handledExceptions)) check((binary.rhs, he)) } } @component(tree, handledExceptions) trait SwitchExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (switch: SwitchApi) => { val he = check((switch.expr, handledExceptions)) switch.cases.foldLeft(he){(z, y) => check((y, z)) } } } @component(tree, handledExceptions) trait CaseExceptionHandlingCheckerComponent extends ExceptionHandlingCheckerComponent { (cse: CaseApi) => { check((cse.body, handledExceptions)) } } // even more boring cases // @component(tree, handledExceptions) // trait IdentExceptionHandlingCheckerComponent // extends ExceptionHandlingCheckerComponent { // (ident: IdentApi) => handledExceptions // } // // @component(tree, handledExceptions) // trait TypeUseExceptionHandlingCheckerComponent // extends ExceptionHandlingCheckerComponent { // (tuse: TypeUseApi) => handledExceptions // } // // // // @component(tree, handledExceptions) // trait LiteralExceptionHandlingCheckerComponent // extends ExceptionHandlingCheckerComponent { // (lit: LiteralApi) => handledExceptions // }
amanjpro/languages-a-la-carte
robustj/src/main/scala/typechecker/exceptioncheckers.scala
Scala
bsd-3-clause
20,118
package com.twitter.finagle.kestrel.protocol import org.jboss.netty.buffer.ChannelBuffer import com.twitter.util.{Time, Duration} sealed abstract class Command sealed abstract class GetCommand extends Command { val queueName: ChannelBuffer val timeout: Option[Duration] } case class Get(val queueName: ChannelBuffer, val timeout: Option[Duration] = None) extends GetCommand case class Open(val queueName: ChannelBuffer, val timeout: Option[Duration] = None) extends GetCommand case class Close(val queueName: ChannelBuffer, val timeout: Option[Duration] = None) extends GetCommand case class CloseAndOpen(val queueName: ChannelBuffer, val timeout: Option[Duration] = None) extends GetCommand case class Abort(val queueName: ChannelBuffer, val timeout: Option[Duration] = None) extends GetCommand case class Peek(val queueName: ChannelBuffer, val timeout: Option[Duration] = None) extends GetCommand case class Set(queueName: ChannelBuffer, expiry: Time, value: ChannelBuffer) extends Command case class Delete(queueName: ChannelBuffer) extends Command case class Flush(queueName: ChannelBuffer) extends Command case class FlushAll() extends Command case class Version() extends Command case class ShutDown() extends Command case class Reload() extends Command case class DumpConfig() extends Command case class Stats() extends Command case class DumpStats() extends Command
enachb/finagle_2.9_durgh
finagle-kestrel/src/main/scala/com/twitter/finagle/kestrel/protocol/Command.scala
Scala
apache-2.0
2,077
package ozmi.lambda_core package lib import org.scalacheck.Prop.forAll import org.scalacheck.{Gen, Properties} object CollSpec extends Properties("Coll") { import ozmi.lambda_core.lib.Coll._ import ozmi.lambda_core.lib.Num._ import ozmi.lambda_core.lib.Ord._ lazy val saneBigDecimal = for { unscaledVal <- Gen.choose(-1000, 1000) scale <- Gen.choose(0, 100) } yield BigDecimal(unscaledVal, scale) lazy val saneBigDecimalSeq = Gen.containerOf[Seq, BigDecimal](saneBigDecimal) property("Filter") = forAll (saneBigDecimalSeq) { (coll: Seq[BigDecimal]) => val predicate = (i: BigDecimal) => i < 100 val predicateEx = Lambda (Seq ("i"), LessThan (Lookup ("i"), Literal (BigDecimal (100)))) Library.eval (Filter (Literal (coll), predicateEx)) == Literal (coll filter predicate) } property("Map") = forAll (saneBigDecimalSeq) { (coll: Seq[BigDecimal]) => val mapping = (i: BigDecimal) => i * 2 val mappingEx = Lambda (Seq ("i"), Multiply (Lookup ("i"), Literal (BigDecimal (2)))) Library.eval (Map (Literal (coll), mappingEx)) == Literal (coll map mapping) } property("Reduce") = forAll (saneBigDecimalSeq) { (coll: Seq[BigDecimal]) => val reduction = (a: BigDecimal, b: BigDecimal) => a + b val reductionEx = Lambda (Seq ("a", "b"), Add (Lookup ("a"), Lookup ("b"))) val expected = if (coll.isEmpty) Literal (null) else Literal (coll reduce reduction) Library.eval (Reduce (Literal (coll), reductionEx)) == expected } }
ozmi/lambda_core
src/test/scala/ozmi/lambda_core/lib/CollSpec.scala
Scala
mit
1,682
package org.jetbrains.plugins.scala package codeInspection package unusedInspections import com.intellij.codeHighlighting._ import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import org.jetbrains.plugins.scala.lang.psi.api.ScalaFile class ScalaUnusedLocalSymbolPassFactory extends TextEditorHighlightingPassFactory with TextEditorHighlightingPassFactoryRegistrar { override def createHighlightingPass(file: PsiFile, editor: Editor): TextEditorHighlightingPass = file match { case scalaFile: ScalaFile => new ScalaUnusedLocalSymbolPass(scalaFile, Option(editor.getDocument)) case _ => null } override def registerHighlightingPassFactory(registrar: TextEditorHighlightingPassRegistrar, project: Project): Unit = { registrar.registerTextEditorHighlightingPass(this, Array[Int](Pass.UPDATE_ALL), null, false, -1) } }
JetBrains/intellij-scala
scala/scala-impl/src/org/jetbrains/plugins/scala/codeInspection/unusedInspections/ScalaUnusedLocalSymbolPassFactory.scala
Scala
apache-2.0
908
/* Copyright 2013 Twitter, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.twitter.summingbird.storm import backtype.storm.{ Config => BacktypeStormConfig, LocalCluster, Testing } import backtype.storm.generated.StormTopology import backtype.storm.testing.{ CompleteTopologyParam, MockedSources } import com.twitter.algebird.{MapAlgebra, Semigroup} import com.twitter.storehaus.{ ReadableStore, JMapStore } import com.twitter.storehaus.algebra.MergeableStore import com.twitter.summingbird._ import com.twitter.summingbird.batch.{BatchID, Batcher} import com.twitter.summingbird.storm.spout.TraversableSpout import com.twitter.summingbird.storm.option._ import com.twitter.summingbird.memory._ import com.twitter.summingbird.planner._ import com.twitter.tormenta.spout.Spout import com.twitter.util.Future import java.util.{Collections, HashMap, Map => JMap, UUID} import java.util.concurrent.atomic.AtomicInteger import org.specs2.mutable._ import org.scalacheck._ import org.scalacheck.Prop._ import org.scalacheck.Properties import scala.collection.JavaConverters._ import scala.collection.mutable.{ ArrayBuffer, HashMap => MutableHashMap, Map => MutableMap, SynchronizedBuffer, SynchronizedMap } import java.security.Permission /** * Tests for Summingbird's Storm planner. */ /** * State required to perform a single Storm test run. */ case class TestState[T, K, V]( store: JMap[(K, BatchID), Option[V]] = Collections.synchronizedMap(new HashMap[(K, BatchID), Option[V]]()), used: ArrayBuffer[T] = new ArrayBuffer[T] with SynchronizedBuffer[T], placed: AtomicInteger = new AtomicInteger ) object TrueGlobalState { val data = new MutableHashMap[String, TestState[Int, Int, Int]] with SynchronizedMap[String, TestState[Int, Int, Int]] } class MySecurityManager extends SecurityManager { override def checkExit(status: Int): Unit = { throw new SecurityException(); } override def checkAccess(t: Thread) = {} override def checkPermission(p: Permission) = {} } /* * This is a wrapper to run a storm topology. * We use the SecurityManager code to catch the System.exit storm calls when it * fails. We wrap it into a normal exception instead so it can report better/retry. */ object StormRunner { private def completeTopologyParam(conf: BacktypeStormConfig) = { val ret = new CompleteTopologyParam() ret.setMockedSources(new MockedSources) ret.setStormConf(conf) ret.setCleanupState(false) ret } private def tryRun(plannedTopology: PlannedTopology): Unit = { //Before running the external Command val oldSecManager = System.getSecurityManager() System.setSecurityManager(new MySecurityManager()); try { val cluster = new LocalCluster() Testing.completeTopology(cluster, plannedTopology.topology, completeTopologyParam(plannedTopology.config)) // Sleep to prevent this race: https://github.com/nathanmarz/storm/pull/667 Thread.sleep(1000) cluster.shutdown } finally { System.setSecurityManager(oldSecManager) } } def run(plannedTopology: PlannedTopology) { this.synchronized { try { tryRun(plannedTopology) } catch { case _: Throwable => Thread.sleep(3000) tryRun(plannedTopology) } } } } object StormLaws extends Specification { sequential import MapAlgebra.sparseEquiv // This is dangerous, obviously. The Storm platform graphs tested // here use the UnitBatcher, so the actual time extraction isn't // needed. implicit def extractor[T]: TimeExtractor[T] = TimeExtractor(_ => 0L) implicit val batcher = Batcher.unit /** * Global state shared by all tests. */ val globalState = TrueGlobalState.data /** * Returns a MergeableStore that routes get, put and merge calls * through to the backing store in the proper globalState entry. */ def testingStore(id: String) = new MergeableStore[(Int, BatchID), Int] with java.io.Serializable { val semigroup = implicitly[Semigroup[Int]] def wrappedStore = globalState(id).store private def getOpt(k: (Int, BatchID)) = Option(wrappedStore.get(k)).flatMap(i => i) override def get(k: (Int, BatchID)) = Future.value(getOpt(k)) override def put(pair: ((Int, BatchID), Option[Int])) = { val (k, optV) = pair if (optV.isDefined) wrappedStore.put(k, optV) else wrappedStore.remove(k) globalState(id).placed.incrementAndGet Future.Unit } override def merge(pair: ((Int, BatchID), Int)) = { val (k, v) = pair val oldV = getOpt(k) val newV = Semigroup.plus(Some(v), oldV) wrappedStore.put(k, newV) globalState(id).placed.incrementAndGet Future.value(oldV) } } val testFn = sample[Int => List[(Int, Int)]] val storm = Storm.local(Map( )) def sample[T: Arbitrary]: T = Arbitrary.arbitrary[T].sample.get def genStore: (String, Storm#Store[Int, Int]) = { val id = UUID.randomUUID.toString globalState += (id -> TestState()) val store = MergeableStoreSupplier(() => testingStore(id), Batcher.unit) (id, store) } def genSink:() => ((Int) => Future[Unit]) = () => {x: Int => append(x) Future.Unit } /** * Perform a single run of TestGraphs.singleStepJob using the * supplied list of integers and the testFn defined above. */ def runOnce(original: List[Int])(mkJob: (Producer[Storm, Int], Storm#Store[Int, Int]) => TailProducer[Storm, Any]) : TestState[Int, Int, Int] = { val (id, store) = genStore val job = mkJob( Storm.source(TraversableSpout(original)), store ) val topo = storm.plan(job) StormRunner.run(topo) globalState(id) } def memoryPlanWithoutSummer(original: List[Int])(mkJob: (Producer[Memory, Int], Memory#Sink[Int]) => TailProducer[Memory, Int]) : List[Int] = { val memory = new Memory val outputList = ArrayBuffer[Int]() val sink: (Int) => Unit = {x: Int => outputList += x} val job = mkJob( Memory.toSource(original), sink ) val topo = memory.plan(job) memory.run(topo) outputList.toList } val outputList = new ArrayBuffer[Int] with SynchronizedBuffer[Int] def append(x: Int):Unit = { StormLaws.outputList += x } def runWithOutSummer(original: List[Int])(mkJob: (Producer[Storm, Int], Storm#Sink[Int]) => TailProducer[Storm, Int]) : List[Int] = { val cluster = new LocalCluster() val job = mkJob( Storm.source(TraversableSpout(original)), Storm.sink[Int]({ (x: Int) => append(x); Future.Unit }) ) val topo = storm.plan(job) StormRunner.run(topo) StormLaws.outputList.toList } val nextFn = { pair: ((Int, (Int, Option[Int]))) => val (k, (v, joinedV)) = pair List((k -> joinedV.getOrElse(10))) } val serviceFn = sample[Int => Option[Int]] val service = StoreWrapper[Int, Int](() => ReadableStore.fromFn(serviceFn)) // ALL TESTS START AFTER THIS LINE "StormPlatform matches Scala for single step jobs" in { val original = sample[List[Int]] val returnedState = runOnce(original)( TestGraphs.singleStepJob[Storm, Int, Int, Int](_,_)(testFn) ) Equiv[Map[Int, Int]].equiv( TestGraphs.singleStepInScala(original)(testFn), returnedState.store.asScala.toMap .collect { case ((k, batchID), Some(v)) => (k, v) } ) must beTrue } "FlatMap to nothing" in { val original = sample[List[Int]] val fn = {(x: Int) => List[(Int, Int)]()} val returnedState = runOnce(original)( TestGraphs.singleStepJob[Storm, Int, Int, Int](_,_)(fn) ) Equiv[Map[Int, Int]].equiv( TestGraphs.singleStepInScala(original)(fn), returnedState.store.asScala.toMap .collect { case ((k, batchID), Some(v)) => (k, v) } ) must beTrue } "OptionMap and FlatMap" in { val original = sample[List[Int]] val fnA = sample[Int => Option[Int]] val fnB = sample[Int => List[(Int,Int)]] val returnedState = runOnce(original)( TestGraphs.twinStepOptionMapFlatMapJob[Storm, Int, Int, Int, Int](_,_)(fnA, fnB) ) Equiv[Map[Int, Int]].equiv( TestGraphs.twinStepOptionMapFlatMapScala(original)(fnA, fnB), returnedState.store.asScala.toMap .collect { case ((k, batchID), Some(v)) => (k, v) } ) must beTrue } "OptionMap to nothing and FlatMap" in { val original = sample[List[Int]] val fnA = {(x: Int) => None } val fnB = sample[Int => List[(Int,Int)]] val returnedState = runOnce(original)( TestGraphs.twinStepOptionMapFlatMapJob[Storm, Int, Int, Int, Int](_,_)(fnA, fnB) ) Equiv[Map[Int, Int]].equiv( TestGraphs.twinStepOptionMapFlatMapScala(original)(fnA, fnB), returnedState.store.asScala.toMap .collect { case ((k, batchID), Some(v)) => (k, v) } ) must beTrue } "StormPlatform matches Scala for large expansion single step jobs" in { val original = sample[List[Int]] val expander = sample[Int => List[(Int, Int)]] val expansionFunc = {(x: Int) => expander(x).flatMap{case (k, v) => List((k, v), (k, v), (k, v), (k, v), (k, v))} } val returnedState = runOnce(original)( TestGraphs.singleStepJob[Storm, Int, Int, Int](_,_)(expansionFunc) ) Equiv[Map[Int, Int]].equiv( TestGraphs.singleStepInScala(original)(expansionFunc), returnedState.store.asScala.toMap .collect { case ((k, batchID), Some(v)) => (k, v) } ) must beTrue } "StormPlatform matches Scala for flatmap keys jobs" in { val original = List(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ,41, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ,41) // sample[List[Int]] val fnA = sample[Int => List[(Int, Int)]] val fnB = sample[Int => List[Int]] val returnedState = runOnce(original)( TestGraphs.singleStepMapKeysJob[Storm, Int, Int, Int, Int](_,_)(fnA, fnB) ) Equiv[Map[Int, Int]].equiv( TestGraphs.singleStepMapKeysInScala(original)(fnA, fnB), returnedState.store.asScala.toMap .collect { case ((k, batchID), Some(v)) => (k, v) } ) must beTrue } "StormPlatform matches Scala for left join jobs" in { val original = sample[List[Int]] val staticFunc = { i: Int => List((i -> i)) } val returnedState = runOnce(original)( TestGraphs.leftJoinJob[Storm, Int, Int, Int, Int, Int](_, service, _)(staticFunc)(nextFn) ) Equiv[Map[Int, Int]].equiv( TestGraphs.leftJoinInScala(original)(serviceFn) (staticFunc)(nextFn), returnedState.store.asScala.toMap .collect { case ((k, batchID), Some(v)) => (k, v) } ) must beTrue } "StormPlatform matches Scala for optionMap only jobs" in { val original = sample[List[Int]] val (id, store) = genStore val cluster = new LocalCluster() val producer = Storm.source(TraversableSpout(original)) .filter(_ % 2 == 0) .map(_ -> 10) .sumByKey(store) val topo = storm.plan(producer) StormRunner.run(topo) Equiv[Map[Int, Int]].equiv( MapAlgebra.sumByKey(original.filter(_ % 2 == 0).map(_ -> 10)), globalState(id).store.asScala .toMap .collect { case ((k, batchID), Some(v)) => (k, v) } ) must beTrue } "StormPlatform matches Scala for MapOnly/NoSummer" in { val original = sample[List[Int]] val doubler = {x: Int => List(x*2)} val stormOutputList = runWithOutSummer(original)( TestGraphs.mapOnlyJob[Storm, Int, Int](_, _)(doubler) ).sorted val memoryOutputList = memoryPlanWithoutSummer(original) (TestGraphs.mapOnlyJob[Memory, Int, Int](_, _)(doubler)).sorted stormOutputList must_==(memoryOutputList) } "StormPlatform with multiple summers" in { val original = List(1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ,41, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ,41) // sample[List[Int]] val doubler = {(x): (Int) => List((x -> x*2))} val simpleOp = {(x): (Int) => List(x * 10)} val source = Storm.source(TraversableSpout(original)) val (store1Id, store1) = genStore val (store2Id, store2) = genStore val tail = TestGraphs.multipleSummerJob[Storm, Int, Int, Int, Int, Int, Int](source, store1, store2)(simpleOp, doubler, doubler) val topo = storm.plan(tail) StormRunner.run(topo) val (scalaA, scalaB) = TestGraphs.multipleSummerJobInScala(original)(simpleOp, doubler, doubler) val store1Map = globalState(store1Id).store.asScala.toMap val store2Map = globalState(store2Id).store.asScala.toMap Equiv[Map[Int, Int]].equiv( scalaA, store1Map .collect { case ((k, batchID), Some(v)) => (k, v) } ) must beTrue Equiv[Map[Int, Int]].equiv( scalaB, store2Map .collect { case ((k, batchID), Some(v)) => (k, v) } ) must beTrue } "StormPlatform should be efficent in real world job" in { val original1 = sample[List[Int]] val original2 = sample[List[Int]] val original3 = sample[List[Int]] val original4 = sample[List[Int]] val source1 = Storm.source(TraversableSpout(original1)) val source2 = Storm.source(TraversableSpout(original2)) val source3 = Storm.source(TraversableSpout(original3)) val source4 = Storm.source(TraversableSpout(original4)) val fn1 = sample[(Int) => List[(Int, Int)]] val fn2 = sample[(Int) => List[(Int, Int)]] val fn3 = sample[(Int) => List[(Int, Int)]] val (store1Id, store1) = genStore val preJoinFn = sample[(Int) => (Int, Int)] val postJoinFn = sample[((Int, (Int, Option[Int]))) => List[(Int, Int)]] val serviceFn = sample[Int => Option[Int]] val service = StoreWrapper[Int, Int](() => ReadableStore.fromFn(serviceFn)) val tail = TestGraphs.realJoinTestJob[Storm, Int, Int, Int, Int, Int, Int, Int, Int, Int](source1, source2, source3, source4, service, store1, fn1, fn2, fn3, preJoinFn, postJoinFn) val topo = storm.plan(tail) OnlinePlan(tail).nodes.size must beLessThan(10) StormRunner.run(topo) val scalaA = TestGraphs.realJoinTestJobInScala(original1, original2, original3, original4, serviceFn, fn1, fn2, fn3, preJoinFn, postJoinFn) val store1Map = globalState(store1Id).store.asScala.toMap Equiv[Map[Int, Int]].equiv( scalaA, store1Map .collect { case ((k, batchID), Some(v)) => (k, v) } ) must beTrue } }
sengt/summingbird-batch
summingbird-storm/src/test/scala/com/twitter/summingbird/storm/StormLaws.scala
Scala
apache-2.0
15,176
package com.github.agourlay.cornichon.util import io.circe.{ Encoder, Json, JsonObject } import scala.concurrent.duration.FiniteDuration object CirceUtil { // taken from https://github.com/circe/circe/pull/978 implicit final val finiteDurationEncoder: Encoder[FiniteDuration] = new Encoder[FiniteDuration] { final def apply(a: FiniteDuration): Json = Json.fromJsonObject( JsonObject( "length" -> Json.fromLong(a.length), "unit" -> Json.fromString(a.unit.name))) } }
agourlay/cornichon
cornichon-core/src/main/scala/com/github/agourlay/cornichon/util/CirceUtil.scala
Scala
apache-2.0
513
package im.actor.api import treehugger.forest._, definitions._ import treehuggerDSL._ trait DebugHelpersTrees { protected val debugTree: Tree = OBJECTDEF("Debug") withFlags PRIVATEWITHIN("api") := BLOCK( IMPORT("com.typesafe.config.ConfigFactory"), DEF("isDebug", BooleanClass) := REF("ConfigFactory") DOT "load" DOT "getBoolean" APPLY LIT("debug-mode") ) }
actorapp/sbt-actor-api
src/main/scala/im/actor/api/DebugHelpersTrees.scala
Scala
mit
379
/* utils-pbts.scala Some property-based test code for utils */ package scalaglm import breeze.linalg._ import breeze.numerics._ import math.abs import org.scalatest._ import flatspec._ import matchers._ import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks class UtilsPbts extends AnyFlatSpec with should.Matchers with ScalaCheckPropertyChecks { import Utils._ forAll { (x0: Double, x1: Double, x2: Double) => whenever (abs(x0) < 1e80 && abs(x1) < 1e80 && abs(x2) < 1e80) { val A = DenseMatrix((1,2,3),(0,4,5),(0,0,6)) map (_.toDouble) val x = DenseVector(x0, x1, x2) val y = A * x val xx = backSolve(A,y) norm(x-xx) < 1e-5 + 1e-5*norm(x) shouldBe true } } }
darrenjw/scala-glm
src/test/scala/utils-pbts.scala
Scala
apache-2.0
720
package org.sisioh.aws4s.cfn.model import com.amazonaws.services.cloudformation.model.CancelUpdateStackRequest import org.sisioh.aws4s.PimpedType object CancelUpdateStackRequestFactory { def create(): CancelUpdateStackRequest = new CancelUpdateStackRequest() } class RichCancelUpdateStackRequest(val underlying: CancelUpdateStackRequest) extends AnyVal with PimpedType[CancelUpdateStackRequest] { def stackNameOpt: Option[String] = Option(underlying.getStackName) def stackNameOpt_=(value: Option[String]): Unit = underlying.setStackName(value.orNull) def withStackNameOpt(value: Option[String]): CancelUpdateStackRequest = underlying.withStackName(value.orNull) }
everpeace/aws4s
aws4s-cfn/src/main/scala/org/sisioh/aws4s/cfn/model/RichCancelUpdateStackRequest.scala
Scala
mit
694
package com.twitter.finagle.liveness import com.twitter.app.GlobalFlag import com.twitter.conversions.time._ import com.twitter.finagle.{Status, Stack} import com.twitter.finagle.stats.{NullStatsReceiver, StatsReceiver} import com.twitter.finagle.util.parsers.{double, duration, int, list} import com.twitter.util.{Duration, Future} import java.util.logging.Logger /** * Failure detectors attempt to gauge the liveness of a peer, * usually by sending ping messages and evaluating response * times. */ private[liveness] trait FailureDetector { def status: Status } /** * The null failure detector is the most conservative: it uses * no information, and always gauges the session to be * [[Status.Open]]. */ private object NullFailureDetector extends FailureDetector { def status: Status = Status.Open } /** * The mock failure detector is for testing, and invokes the passed in * `fn` to decide what `status` to return. */ private class MockFailureDetector(fn: () => Status) extends FailureDetector { def status: Status = fn() } /** * GlobalFlag to configure FailureDetection used only in the * absence of any app-specified config. This is the default * behavior. * * Value of: * "none": turn off threshold failure detector * "threshold:minPeriod:threshold:win:closeTimeout": * use the specified configuration for failure detection */ object sessionFailureDetector extends GlobalFlag[String]( "threshold:5.seconds:2:100:4.seconds", "The failure detector used to determine session liveness " + "[none|threshold:minPeriod:threshold:win:closeTimeout]") /** * Companion object capable of creating a FailureDetector based on parameterized config. */ object FailureDetector { /** * Base type used to identify and configure the [[FailureDetector]]. */ sealed trait Config /** * Default config type which tells the [[FailureDetector]] to extract * config values from the sessionFailureDetector GlobalFlag. */ case object GlobalFlagConfig extends Config /** * Indicated to use the [[com.twitter.finagle.liveness.NullFailureDetector]] * when creating a new detector */ case object NullConfig extends Config /** * Indicated to use the [[com.twitter.finagle.liveness.MockFailureDetector]] * when creating a new detector */ case class MockConfig(fn: () => Status) extends Config /** * Indicated to use the [[com.twitter.finagle.liveness.ThresholdFailureDetector]] * configured with these values when creating a new detector. * * The default `windowSize` and `threshold` are chosen from examining a * representative ping distribution in a Twitter data center. With long tail * distribution, we want a reasonably large window size to capture long RTTs * in the history. A small threshold makes the detection sensitive to potential * failures. There can be a low rate of false positive, which is fine in most * production cases with cluster redundancy. * * `closeTimeout` allows a session to be closed when a ping response times out * after 4 seconds. This allows sessions to be reestablished when there may be * a networking issue, so that it can choose an alternative networking path instead. * The default 4 seconds is pretty conservative regarding normal ping RTT. */ case class ThresholdConfig( minPeriod: Duration = 5.seconds, threshold: Double = 2, windowSize: Int = 100, closeTimeout: Duration = 4.seconds) extends Config /** * Helper class for configuring a [[FailureDetector]] within a * [[com.twitter.finagle.Stackable]] client */ case class Param(param: Config) { def mk(): (Param, Stack.Param[Param]) = (this, Param.param) } case object Param { implicit val param = Stack.Param(Param(GlobalFlagConfig)) } private[this] val log = Logger.getLogger(getClass.getName) /** * Instantiate a new FailureDetector based on the config type */ private[finagle] def apply( config: Config, ping: () => Future[Unit], statsReceiver: StatsReceiver ): FailureDetector = { config match { case NullConfig => NullFailureDetector case MockConfig(fn) => new MockFailureDetector(fn) case cfg: ThresholdConfig => new ThresholdFailureDetector(ping, cfg.minPeriod, cfg.threshold, cfg.windowSize, cfg.closeTimeout, statsReceiver = statsReceiver) case GlobalFlagConfig => parseConfigFromFlags(ping, statsReceiver = statsReceiver) } } /** * Fallback behavior: parse the sessionFailureDetector global flag and * instantiate the proper config. */ private def parseConfigFromFlags( ping: () => Future[Unit], nanoTime: () => Long = System.nanoTime, statsReceiver: StatsReceiver = NullStatsReceiver ): FailureDetector = { sessionFailureDetector() match { case list("threshold", duration(min), double(threshold), int(win), duration(closeTimeout)) => new ThresholdFailureDetector( ping, min, threshold, win, closeTimeout, nanoTime, statsReceiver) case list("threshold", duration(min), double(threshold), int(win)) => new ThresholdFailureDetector( ping, min, threshold, win, nanoTime = nanoTime, statsReceiver = statsReceiver) case list("threshold", duration(min), double(threshold)) => new ThresholdFailureDetector( ping, min, threshold, nanoTime = nanoTime, statsReceiver = statsReceiver) case list("threshold", duration(min)) => new ThresholdFailureDetector( ping, min, nanoTime = nanoTime, statsReceiver = statsReceiver) case list("threshold") => new ThresholdFailureDetector( ping, nanoTime = nanoTime, statsReceiver = statsReceiver) case list("none") => NullFailureDetector case list(_*) => log.warning(s"unknown failure detector ${sessionFailureDetector()} specified") NullFailureDetector } } }
koshelev/finagle
finagle-core/src/main/scala/com/twitter/finagle/liveness/FailureDetector.scala
Scala
apache-2.0
5,968
/*********************************************************************** * Copyright (c) 2013-2018 Commonwealth Computer Research, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at * http://www.opensource.org/licenses/apache2.0.php. ***********************************************************************/ package org.locationtech.geomesa.lambda.tools.data import com.beust.jcommander.Parameters import org.locationtech.geomesa.lambda.data.LambdaDataStore import org.locationtech.geomesa.lambda.tools.{LambdaDataStoreCommand, LambdaDataStoreParams} import org.locationtech.geomesa.tools.data.{CreateSchemaCommand, CreateSchemaParams} class LambdaCreateSchemaCommand extends CreateSchemaCommand[LambdaDataStore] with LambdaDataStoreCommand { override val params = new LambdaCreateSchemaParams() } @Parameters(commandDescription = "Create a GeoMesa feature type") class LambdaCreateSchemaParams extends CreateSchemaParams with LambdaDataStoreParams
jahhulbert-ccri/geomesa
geomesa-lambda/geomesa-lambda-tools/src/main/scala/org/locationtech/geomesa/lambda/tools/data/LambdaCreateSchemaCommand.scala
Scala
apache-2.0
1,111
package exceptions class BadBindingException(val msg: String) extends RuntimeException(msg)
j-c-w/mlc
src/main/scala/exceptions/BadBindingException.scala
Scala
gpl-3.0
93
package com.goyeau.kubernetes.client.operation import cats.Applicative import cats.implicits._ import com.goyeau.kubernetes.client.KubernetesClient import com.goyeau.kubernetes.client.Utils.retry import io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta import munit.FunSuite import org.http4s.Status trait CreatableTests[F[_], Resource <: { def metadata: Option[ObjectMeta] }] extends FunSuite with MinikubeClientProvider[F] { def namespacedApi(namespaceName: String)(implicit client: KubernetesClient[F]): Creatable[F, Resource] def getChecked(namespaceName: String, resourceName: String)(implicit client: KubernetesClient[F]): F[Resource] def sampleResource(resourceName: String, labels: Map[String, String] = Map.empty): Resource def modifyResource(resource: Resource): Resource def checkUpdated(updatedResource: Resource): Unit def createChecked(namespaceName: String, resourceName: String)(implicit client: KubernetesClient[F] ): F[Resource] = createChecked(namespaceName, resourceName, Map.empty) def createWithResourceChecked(namespaceName: String, resourceName: String)(implicit client: KubernetesClient[F] ): F[Resource] = createWithResourceChecked(namespaceName, resourceName, Map.empty) def createChecked(namespaceName: String, resourceName: String, labels: Map[String, String])(implicit client: KubernetesClient[F] ): F[Resource] = { val resource = sampleResource(resourceName, labels) for { status <- namespacedApi(namespaceName).create(resource) _ = assertEquals(status, Status.Created) resource <- getChecked(namespaceName, resourceName) } yield resource } def createWithResourceChecked(namespaceName: String, resourceName: String, labels: Map[String, String])(implicit client: KubernetesClient[F] ): F[Resource] = { val resource = sampleResource(resourceName, labels) for { _ <- namespacedApi(namespaceName).createWithResource(resource) retrievedResource <- getChecked(namespaceName, resourceName) } yield retrievedResource } test(s"create a $resourceName") { usingMinikube { implicit client => createChecked(resourceName.toLowerCase, "create-resource") } } test(s"create a $resourceName with resource") { usingMinikube { implicit client => createWithResourceChecked(resourceName.toLowerCase, "create-resource-1") } } test(s"create a $resourceName") { usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) resourceName = "create-update-resource" status <- namespacedApi(namespaceName).createOrUpdate(sampleResource(resourceName)) _ = assertEquals(status, Status.Created) _ <- getChecked(namespaceName, resourceName) } yield () } } test(s"create a $resourceName with resource") { usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) resourceName = "create-update-resource-1" _ <- namespacedApi(namespaceName).createOrUpdateWithResource(sampleResource(resourceName)) _ <- getChecked(namespaceName, resourceName) } yield () } } def createOrUpdate(namespaceName: String, resourceName: String)(implicit client: KubernetesClient[F]) = for { resource <- getChecked(namespaceName, resourceName) status <- namespacedApi(namespaceName).createOrUpdate(modifyResource(resource)) _ = assertEquals(status, Status.Ok) } yield () test(s"update a $resourceName already created") { usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) resourceName <- Applicative[F].pure("update-resource") _ <- createChecked(namespaceName, resourceName) _ <- retry(createOrUpdate(namespaceName, resourceName)) updatedResource <- getChecked(namespaceName, resourceName) _ = checkUpdated(updatedResource) } yield () } } def createOrUpdateWithResource(namespaceName: String, resourceName: String)(implicit client: KubernetesClient[F] ) = for { retrievedResource <- getChecked(namespaceName, resourceName) updatedResource <- namespacedApi(namespaceName).createOrUpdateWithResource(modifyResource(retrievedResource)) } yield updatedResource test(s"update a $resourceName already created with resource") { usingMinikube { implicit client => for { namespaceName <- Applicative[F].pure(resourceName.toLowerCase) resourceName <- Applicative[F].pure("update-resource-1") _ <- createChecked(namespaceName, resourceName) updatedResource <- retry(createOrUpdateWithResource(namespaceName, resourceName)) _ = checkUpdated(updatedResource) retrievedResource <- getChecked(namespaceName, resourceName) _ = checkUpdated(retrievedResource) } yield () } } }
joan38/kubernetes-client
kubernetes-client/test/src/com/goyeau/kubernetes/client/operation/CreatableTests.scala
Scala
apache-2.0
5,040
package fr.renoux.gaston.util object TupleImplicits { @inline final implicit class CoupleOps[A, B](val wrapped: (A, B)) extends AnyVal { @inline def map1[C](f: A => C): (C, B) = (f(wrapped._1), wrapped._2) @inline def map2[C](f: B => C): (A, C) = (wrapped._1, f(wrapped._2)) } }
gaelrenoux/gaston
src/main/scala/fr/renoux/gaston/util/TupleImplicits.scala
Scala
apache-2.0
296
/* Scala.js compiler * Copyright 2013 LAMP/EPFL * @author Sébastien Doeraene */ package org.scalajs.core.compiler import scala.tools.nsc._ /** Core definitions for Scala.js * * @author Sébastien Doeraene */ trait JSDefinitions { self: JSGlobalAddons => import global._ // scalastyle:off line.size.limit object jsDefinitions extends JSDefinitionsClass // scalastyle:ignore import definitions._ import rootMirror._ class JSDefinitionsClass { lazy val ScalaJSJSPackage = getPackage(newTermNameCached("scala.scalajs.js")) // compat 2.10/2.11 lazy val JSPackage_typeOf = getMemberMethod(ScalaJSJSPackage, newTermName("typeOf")) lazy val JSPackage_constructorOf = getMemberMethod(ScalaJSJSPackage, newTermName("constructorOf")) lazy val JSPackage_debugger = getMemberMethod(ScalaJSJSPackage, newTermName("debugger")) lazy val JSPackage_native = getMemberMethod(ScalaJSJSPackage, newTermName("native")) lazy val JSPackage_undefined = getMemberMethod(ScalaJSJSPackage, newTermName("undefined")) lazy val JSNativeAnnotation = getRequiredClass("scala.scalajs.js.native") lazy val JSAnyClass = getRequiredClass("scala.scalajs.js.Any") lazy val JSDynamicClass = getRequiredClass("scala.scalajs.js.Dynamic") lazy val JSDictionaryClass = getRequiredClass("scala.scalajs.js.Dictionary") lazy val JSDictionary_delete = getMemberMethod(JSDictionaryClass, newTermName("delete")) lazy val JSObjectClass = getRequiredClass("scala.scalajs.js.Object") lazy val JSThisFunctionClass = getRequiredClass("scala.scalajs.js.ThisFunction") lazy val JSGlobalScopeClass = getRequiredClass("scala.scalajs.js.GlobalScope") lazy val UndefOrClass = getRequiredClass("scala.scalajs.js.UndefOr") lazy val UnionClass = getRequiredClass("scala.scalajs.js.$bar") lazy val JSArrayClass = getRequiredClass("scala.scalajs.js.Array") lazy val JSArray_apply = getMemberMethod(JSArrayClass, newTermName("apply")) lazy val JSArray_update = getMemberMethod(JSArrayClass, newTermName("update")) lazy val JSFunctionClasses = (0 to 22) map (n => getRequiredClass("scala.scalajs.js.Function"+n)) lazy val JSThisFunctionClasses = (0 to 21) map (n => getRequiredClass("scala.scalajs.js.ThisFunction"+n)) lazy val AllJSFunctionClasses = JSFunctionClasses ++ JSThisFunctionClasses lazy val RuntimeExceptionClass = requiredClass[RuntimeException] lazy val JavaScriptExceptionClass = getClassIfDefined("scala.scalajs.js.JavaScriptException") lazy val JSNameAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSName") lazy val JSFullNameAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSFullName") lazy val JSBracketAccessAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSBracketAccess") lazy val JSBracketCallAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSBracketCall") lazy val JSExportAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExport") lazy val JSExportDescendentObjectsAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExportDescendentObjects") lazy val JSExportDescendentClassesAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExportDescendentClasses") lazy val JSExportAllAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExportAll") lazy val JSExportNamedAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExportNamed") lazy val JSExportStaticAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExportStatic") lazy val JSExportTopLevelAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSExportTopLevel") lazy val JSImportAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSImport") lazy val JSGlobalScopeAnnotation = getRequiredClass("scala.scalajs.js.annotation.JSGlobalScope") lazy val ScalaJSDefinedAnnotation = getRequiredClass("scala.scalajs.js.annotation.ScalaJSDefined") lazy val SJSDefinedAnonymousClassAnnotation = getRequiredClass("scala.scalajs.js.annotation.SJSDefinedAnonymousClass") lazy val HasJSNativeLoadSpecAnnotation = getRequiredClass("scala.scalajs.js.annotation.internal.HasJSNativeLoadSpec") lazy val JSOptionalAnnotation = getRequiredClass("scala.scalajs.js.annotation.internal.JSOptional") lazy val JavaDefaultMethodAnnotation = getRequiredClass("scala.scalajs.js.annotation.JavaDefaultMethod") lazy val JSImportNamespaceObject = getRequiredModule("scala.scalajs.js.annotation.JSImport.Namespace") lazy val JSAnyTpe = JSAnyClass.toTypeConstructor lazy val JSObjectTpe = JSObjectClass.toTypeConstructor lazy val JSGlobalScopeTpe = JSGlobalScopeClass.toTypeConstructor lazy val JSFunctionTpes = JSFunctionClasses.map(_.toTypeConstructor) lazy val JSAnyModule = JSAnyClass.companionModule def JSAny_fromFunction(arity: Int): TermSymbol = getMemberMethod(JSAnyModule, newTermName("fromFunction"+arity)) lazy val JSDynamicModule = JSDynamicClass.companionModule lazy val JSDynamic_newInstance = getMemberMethod(JSDynamicModule, newTermName("newInstance")) lazy val JSDynamicLiteral = getMemberModule(JSDynamicModule, newTermName("literal")) lazy val JSDynamicLiteral_applyDynamicNamed = getMemberMethod(JSDynamicLiteral, newTermName("applyDynamicNamed")) lazy val JSDynamicLiteral_applyDynamic = getMemberMethod(JSDynamicLiteral, newTermName("applyDynamic")) lazy val JSObjectModule = JSObjectClass.companionModule lazy val JSObject_hasProperty = getMemberMethod(JSObjectModule, newTermName("hasProperty")) lazy val JSObject_properties = getMemberMethod(JSObjectModule, newTermName("properties")) lazy val JSArrayModule = JSArrayClass.companionModule lazy val JSArray_create = getMemberMethod(JSArrayModule, newTermName("apply")) lazy val JSThisFunctionModule = JSThisFunctionClass.companionModule def JSThisFunction_fromFunction(arity: Int): TermSymbol = getMemberMethod(JSThisFunctionModule, newTermName("fromFunction"+arity)) lazy val JSConstructorTagModule = getRequiredModule("scala.scalajs.js.ConstructorTag") lazy val JSConstructorTag_materialize = getMemberMethod(JSConstructorTagModule, newTermName("materialize")) lazy val RawJSTypeAnnot = getRequiredClass("scala.scalajs.js.annotation.RawJSType") lazy val ExposedJSMemberAnnot = getRequiredClass("scala.scalajs.js.annotation.ExposedJSMember") lazy val RuntimeStringModule = getRequiredModule("scala.scalajs.runtime.RuntimeString") lazy val RuntimeStringModuleClass = RuntimeStringModule.moduleClass lazy val BooleanReflectiveCallClass = getRequiredClass("scala.scalajs.runtime.BooleanReflectiveCall") lazy val NumberReflectiveCallClass = getRequiredClass("scala.scalajs.runtime.NumberReflectiveCall") lazy val IntegerReflectiveCallClass = getRequiredClass("scala.scalajs.runtime.IntegerReflectiveCall") lazy val LongReflectiveCallClass = getRequiredClass("scala.scalajs.runtime.LongReflectiveCall") lazy val RuntimePackageModule = getPackageObject("scala.scalajs.runtime") lazy val Runtime_wrapJavaScriptException = getMemberMethod(RuntimePackageModule, newTermName("wrapJavaScriptException")) lazy val Runtime_unwrapJavaScriptException = getMemberMethod(RuntimePackageModule, newTermName("unwrapJavaScriptException")) lazy val Runtime_genTraversableOnce2jsArray = getMemberMethod(RuntimePackageModule, newTermName("genTraversableOnce2jsArray")) lazy val Runtime_jsTupleArray2jsObject = getMemberMethod(RuntimePackageModule, newTermName("jsTupleArray2jsObject")) lazy val Runtime_constructorOf = getMemberMethod(RuntimePackageModule, newTermName("constructorOf")) lazy val Runtime_newConstructorTag = getMemberMethod(RuntimePackageModule, newTermName("newConstructorTag")) lazy val Runtime_propertiesOf = getMemberMethod(RuntimePackageModule, newTermName("propertiesOf")) lazy val Runtime_linkingInfo = getMemberMethod(RuntimePackageModule, newTermName("linkingInfo")) lazy val WrappedArrayClass = getRequiredClass("scala.scalajs.js.WrappedArray") lazy val WrappedArray_ctor = WrappedArrayClass.primaryConstructor // This is a def, since similar symbols (arrayUpdateMethod, etc.) are in runDefinitions // (rather than definitions) and we weren't sure if it is safe to make this a lazy val def ScalaRunTime_isArray: Symbol = getMemberMethod(ScalaRunTimeModule, newTermName("isArray")).suchThat(_.tpe.params.size == 2) lazy val BoxesRunTime_boxToCharacter = getMemberMethod(BoxesRunTimeModule, newTermName("boxToCharacter")) lazy val BoxesRunTime_unboxToChar = getMemberMethod(BoxesRunTimeModule, newTermName("unboxToChar")) lazy val ReflectModule = getRequiredModule("scala.scalajs.reflect.Reflect") lazy val Reflect_registerLoadableModuleClass = getMemberMethod(ReflectModule, newTermName("registerLoadableModuleClass")) lazy val Reflect_registerInstantiatableClass = getMemberMethod(ReflectModule, newTermName("registerInstantiatableClass")) lazy val EnableReflectiveInstantiationAnnotation = getRequiredClass("scala.scalajs.reflect.annotation.EnableReflectiveInstantiation") } // scalastyle:on line.size.limit }
xuwei-k/scala-js
compiler/src/main/scala/org/scalajs/core/compiler/JSDefinitions.scala
Scala
bsd-3-clause
9,416
/* * Copyright 2010 WorldWide Conferencing, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.liftweb { package util { import _root_.net.liftweb.common._ /** * A wiring Cell. A Cell can be a ValueCell which holds * a value which can be set (and thus update the dependencies), * a FuncCell (a cell that is a function that depends on other cells), * or a DynamicCell which has a value that updates each time the cell is * accessed. */ trait Cell[T] { /** * The cell's value and most recent change time */ def currentValue: (T, Long) /** * Get the cell's value */ def get: T = currentValue._1 /** * Create a new Cell by applying the function to this cell */ def lift[A](f: T => A): Cell[A] = FuncCell(this)(f) def lift[A,B](cell: Cell[B])(f: (T, B) => A) = FuncCell(this, cell)(f) } object Cell { def apply[T](v: T): ValueCell[T] = new ValueCell[T](v) } /** * A cell that changes value on each access. This kind of cell * could be used to access an external resource. <b>Warning</b> * the function may be accessed many times during a single wiring * recalculation, so it's best to use this as a front to a value * that's memoized for some duration. */ final case class DynamicCell[T](f: () => T) extends Cell[T] { /** * The cell's value and most recent change time */ def currentValue: (T, Long) = f() -> System.nanoTime() } /** * The companion object that has a helpful constructor */ object ValueCell { def apply[A](value: A): ValueCell[A] = new ValueCell(value) implicit def vcToT[T](in: ValueCell[T]): T = in.get } /** * A ValueCell holds a value that can be mutated. */ final class ValueCell[A](initialValue: A) extends Cell[A] with LiftValue[A] { private var value: A = initialValue private var ct: Long = System.nanoTime() /** * The cell's value and most recent change time */ def currentValue: (A, Long) = synchronized { (value, ct) } /** * Get the cell's value */ def set(v: A): A = synchronized { value = v ct = System.nanoTime() value } override def toString(): String = synchronized { "ValueCell("+value+")" } override def hashCode(): Int = synchronized { if (null.asInstanceOf[Object] eq value.asInstanceOf[Object]) 0 else value.hashCode() } override def equals(other: Any): Boolean = synchronized { other match { case vc: ValueCell[_] => value == vc.get case _ => false } } } /** * A collection of Cells og a given type */ final case class SeqCell[T](cells: Cell[T]*) extends Cell[Seq[T]] { /** * The cell's value and most recent change time */ def currentValue: (Seq[T], Long) = { val tcv = cells.map(_.currentValue) tcv.map(_._1) -> tcv.foldLeft(0L)((max, c) => if (max > c._2) max else c._2) } } /** * The companion object for FuncCell (function cells) */ object FuncCell { /** * Construct a function cell based on a single parameter */ def apply[A, Z](a: Cell[A])(f: A => Z): Cell[Z] = FuncCell1(a, f) /** * Construct a function cell based on two parameters */ def apply[A, B, Z](a: Cell[A], b: Cell[B])(f: (A, B) => Z): Cell[Z] = FuncCell2(a, b, f) /** * Construct a function cell based on three parameters */ def apply[A, B, C, Z](a: Cell[A], b: Cell[B], c: Cell[C])(f: (A, B, C) => Z): Cell[Z] = FuncCell3(a, b, c, f) /** * Construct a function cell based on four parameters */ def apply[A, B, C, D, Z](a: Cell[A], b: Cell[B], c: Cell[C], d: Cell[D])(f: (A, B, C, D) => Z): Cell[Z] = FuncCell4(a, b, c, d, f) /** * Construct a function cell based on five parameters */ def apply[A, B, C, D, E, Z](a: Cell[A], b: Cell[B], c: Cell[C], d: Cell[D], e: Cell[E])(f: (A, B, C, D, E) => Z): Cell[Z] = FuncCell5(a, b, c, d, e, f) } final case class FuncCell1[A, Z](a: Cell[A], f: A => Z) extends Cell[Z] { private var value: Z = _ private var ct: Long = 0 def currentValue: (Z, Long) = synchronized { val (v, t) = a.currentValue if (t > ct) { value = f(v) ct = t } (value -> ct) } } final case class FuncCell2[A, B, Z](a: Cell[A], b: Cell[B], f: (A, B) => Z) extends Cell[Z] { private var value: Z = _ private var ct: Long = 0 def currentValue: (Z, Long) = synchronized { val (v1, t1) = a.currentValue val (v2, t2) = b.currentValue val t = WiringHelper.max(t1, t2) if (t > ct) { value = f(v1, v2) ct = t } (value -> ct) } } final case class FuncCell3[A, B, C, Z](a: Cell[A], b: Cell[B], c: Cell[C], f: (A, B, C) => Z) extends Cell[Z] { private var value: Z = _ private var ct: Long = 0 def currentValue: (Z, Long) = synchronized { val (v1, t1) = a.currentValue val (v2, t2) = b.currentValue val (v3, t3) = c.currentValue val t = WiringHelper.max(t1, t2, t3) if (t > ct) { value = f(v1, v2, v3) ct = t } (value -> ct) } } final case class FuncCell4[A, B, C, D, Z](a: Cell[A], b: Cell[B], c: Cell[C], d: Cell[D], f: (A, B, C, D) => Z) extends Cell[Z] { private var value: Z = _ private var ct: Long = 0 def currentValue: (Z, Long) = synchronized { val (v1, t1) = a.currentValue val (v2, t2) = b.currentValue val (v3, t3) = c.currentValue val (v4, t4) = d.currentValue val t = WiringHelper.max(t1, t2, t3, t4) if (t > ct) { value = f(v1, v2, v3, v4) ct = t } (value -> ct) } } final case class FuncCell5[A, B, C, D, E, Z](a: Cell[A], b: Cell[B], c: Cell[C], d: Cell[D], e: Cell[E], f: (A, B, C, D, E) => Z) extends Cell[Z] { private var value: Z = _ private var ct: Long = 0 def currentValue: (Z, Long) = synchronized { val (v1, t1) = a.currentValue val (v2, t2) = b.currentValue val (v3, t3) = c.currentValue val (v4, t4) = d.currentValue val (v5, t5) = e.currentValue val t = WiringHelper.max(t1, t2, t3, t4, t5) if (t > ct) { value = f(v1, v2, v3, v4, v5) ct = t } (value -> ct) } } private object WiringHelper { def max(a: Long, b: Long*): Long = b.foldLeft(a){ (v1, v2) => if (v1 > v2) v1 else v2 } } } }
lift/lift
framework/lift-base/lift-util/src/main/scala/net/liftweb/util/Wiring.scala
Scala
apache-2.0
7,063