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 2015 - 2016 Red Bull Media House GmbH <http://www.redbullmediahouse.com> - all rights reserved.
*
* 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.rbmhtechnology.eventuate.serializer
import akka.actor.ExtendedActorSystem
import akka.serialization._
import com.rbmhtechnology.eventuate.ReplicationProtocol.SynchronizeReplicationProgressFailure
import com.rbmhtechnology.eventuate.ReplicationProtocol.SynchronizeReplicationProgressSourceException
import com.rbmhtechnology.eventuate.ReplicationProtocol.SynchronizeReplicationProgressSuccess
import com.rbmhtechnology.eventuate._
import com.rbmhtechnology.eventuate.ReplicationProtocol._
import com.rbmhtechnology.eventuate.serializer.ReplicationProtocolFormats._
import scala.collection.JavaConverters._
import scala.collection.breakOut
import scala.collection.immutable.VectorBuilder
class ReplicationProtocolSerializer(system: ExtendedActorSystem) extends Serializer {
val eventSerializer = new DurableEventSerializer(system)
val filterSerializer = new ReplicationFilterSerializer(system)
import eventSerializer.commonSerializer
val GetReplicationEndpointInfoClass = GetReplicationEndpointInfo.getClass
val GetReplicationEndpointInfoSuccessClass = classOf[GetReplicationEndpointInfoSuccess]
val SynchronizeReplicationProgressClass = classOf[SynchronizeReplicationProgress]
val SynchronizeReplicationProgressSuccessClass = classOf[SynchronizeReplicationProgressSuccess]
val SynchronizeReplicationProgressFailureClass = classOf[SynchronizeReplicationProgressFailure]
val SynchronizeReplicationProgressSourceExceptionClass = classOf[SynchronizeReplicationProgressSourceException]
val ReplicationReadEnvelopeClass = classOf[ReplicationReadEnvelope]
val ReplicationReadClass = classOf[ReplicationRead]
val ReplicationReadSuccessClass = classOf[ReplicationReadSuccess]
val ReplicationReadFailureClass = classOf[ReplicationReadFailure]
val ReplicationDueClass = ReplicationDue.getClass
val ReplicationReadSourceExceptionClass = classOf[ReplicationReadSourceException]
val IncompatibleApplicationVersionExceptionClass = classOf[IncompatibleApplicationVersionException]
override def identifier: Int = 22565
override def includeManifest: Boolean = true
override def toBinary(o: AnyRef): Array[Byte] = {
o match {
case GetReplicationEndpointInfo =>
GetReplicationEndpointInfoFormat.newBuilder().build().toByteArray
case m: GetReplicationEndpointInfoSuccess =>
getReplicationEndpointInfoSuccessFormatBuilder(m).build().toByteArray
case m: SynchronizeReplicationProgress =>
synchronizeReplicationProgressFormatBuilder(m).build().toByteArray
case m: SynchronizeReplicationProgressSuccess =>
synchronizeReplicationProgressSuccessFormatBuilder(m).build().toByteArray
case m: SynchronizeReplicationProgressFailure =>
synchronizeReplicationProgressFailureFormatBuilder(m).build().toByteArray
case m: ReplicationReadEnvelope =>
replicationReadEnvelopeFormatBuilder(m).build().toByteArray
case m: ReplicationRead =>
replicationReadFormatBuilder(m).build().toByteArray
case m: ReplicationReadSuccess =>
replicationReadSuccessFormatBuilder(m).build().toByteArray
case m: ReplicationReadFailure =>
replicationReadFailureFormatBuilder(m).build().toByteArray
case ReplicationDue =>
ReplicationDueFormat.newBuilder().build().toByteArray
case m: ReplicationReadSourceException =>
replicationReadSourceExceptionFormatBuilder(m).build().toByteArray
case m: IncompatibleApplicationVersionException =>
incompatibleApplicationVersionExceptionFormatBuilder(m).build().toByteArray
case m: SynchronizeReplicationProgressSourceException =>
synchronizeReplicationProgressSourceExceptionFormatBuilder(m).build().toByteArray
case _ =>
throw new IllegalArgumentException(s"can't serialize object of type ${o.getClass}")
}
}
override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = manifest match {
case None => throw new IllegalArgumentException("manifest required")
case Some(clazz) => clazz match {
case GetReplicationEndpointInfoClass =>
GetReplicationEndpointInfo
case GetReplicationEndpointInfoSuccessClass =>
getReplicationEndpointInfoSuccess(GetReplicationEndpointInfoSuccessFormat.parseFrom(bytes))
case SynchronizeReplicationProgressClass =>
synchronizeReplicationProgress(SynchronizeReplicationProgressFormat.parseFrom(bytes))
case SynchronizeReplicationProgressSuccessClass =>
synchronizeReplicationProgressSuccess(SynchronizeReplicationProgressSuccessFormat.parseFrom(bytes))
case SynchronizeReplicationProgressFailureClass =>
synchronizeReplicationProgressFailure(SynchronizeReplicationProgressFailureFormat.parseFrom(bytes))
case ReplicationReadEnvelopeClass =>
replicationReadEnvelope(ReplicationReadEnvelopeFormat.parseFrom(bytes))
case ReplicationReadClass =>
replicationRead(ReplicationReadFormat.parseFrom(bytes))
case ReplicationReadSuccessClass =>
replicationReadSuccess(ReplicationReadSuccessFormat.parseFrom(bytes))
case ReplicationReadFailureClass =>
replicationReadFailure(ReplicationReadFailureFormat.parseFrom(bytes))
case ReplicationDueClass =>
ReplicationDue
case ReplicationReadSourceExceptionClass =>
replicationReadSourceException(ReplicationReadSourceExceptionFormat.parseFrom(bytes))
case IncompatibleApplicationVersionExceptionClass =>
incompatibleApplicationVersionException(IncompatibleApplicationVersionExceptionFormat.parseFrom(bytes))
case SynchronizeReplicationProgressSourceExceptionClass =>
synchronizeReplicationProgressSourceException(SynchronizeReplicationProgressSourceExceptionFormat.parseFrom(bytes))
case _ =>
throw new IllegalArgumentException(s"can't deserialize object of type ${clazz}")
}
}
// --------------------------------------------------------------------------------
// toBinary helpers
// --------------------------------------------------------------------------------
private def replicationReadFailureFormatBuilder(message: ReplicationReadFailure): ReplicationReadFailureFormat.Builder = {
val builder = ReplicationReadFailureFormat.newBuilder()
builder.setCause(commonSerializer.payloadFormatBuilder(message.cause))
builder.setTargetLogId(message.targetLogId)
builder
}
private def replicationReadSuccessFormatBuilder(message: ReplicationReadSuccess): ReplicationReadSuccessFormat.Builder = {
val builder = ReplicationReadSuccessFormat.newBuilder()
message.events.foreach(event => builder.addEvents(eventSerializer.durableEventFormatBuilder(event)))
builder.setFromSequenceNr(message.fromSequenceNr)
builder.setReplicationProgress(message.replicationProgress)
builder.setTargetLogId(message.targetLogId)
builder.setCurrentSourceVersionVector(commonSerializer.vectorTimeFormatBuilder(message.currentSourceVersionVector))
builder
}
private def replicationReadFormatBuilder(message: ReplicationRead): ReplicationReadFormat.Builder = {
val builder = ReplicationReadFormat.newBuilder()
builder.setFromSequenceNr(message.fromSequenceNr)
builder.setMax(message.max)
builder.setScanLimit(message.scanLimit)
builder.setFilter(filterSerializer.filterTreeFormatBuilder(message.filter))
builder.setTargetLogId(message.targetLogId)
builder.setReplicator(Serialization.serializedActorPath(message.replicator))
builder.setCurrentTargetVersionVector(commonSerializer.vectorTimeFormatBuilder(message.currentTargetVersionVector))
builder
}
private def replicationReadEnvelopeFormatBuilder(message: ReplicationReadEnvelope): ReplicationReadEnvelopeFormat.Builder = {
val builder = ReplicationReadEnvelopeFormat.newBuilder()
builder.setPayload(replicationReadFormatBuilder(message.payload))
builder.setLogName(message.logName)
builder.setTargetApplicationName(message.targetApplicationName)
builder.setTargetApplicationVersion(applicationVersionFormatBuilder(message.targetApplicationVersion))
builder
}
private def getReplicationEndpointInfoSuccessFormatBuilder(message: GetReplicationEndpointInfoSuccess): GetReplicationEndpointInfoSuccessFormat.Builder =
GetReplicationEndpointInfoSuccessFormat.newBuilder().setInfo(replicationEndpointInfoFormatBuilder(message.info))
private def synchronizeReplicationProgressFormatBuilder(message: SynchronizeReplicationProgress): SynchronizeReplicationProgressFormat.Builder =
SynchronizeReplicationProgressFormat.newBuilder().setInfo(replicationEndpointInfoFormatBuilder(message.info))
private def synchronizeReplicationProgressSuccessFormatBuilder(message: SynchronizeReplicationProgressSuccess): SynchronizeReplicationProgressSuccessFormat.Builder =
SynchronizeReplicationProgressSuccessFormat.newBuilder().setInfo(replicationEndpointInfoFormatBuilder(message.info))
private def synchronizeReplicationProgressFailureFormatBuilder(message: SynchronizeReplicationProgressFailure): SynchronizeReplicationProgressFailureFormat.Builder =
SynchronizeReplicationProgressFailureFormat.newBuilder().setCause(commonSerializer.payloadFormatBuilder(message.cause))
private def replicationEndpointInfoFormatBuilder(info: ReplicationEndpointInfo): ReplicationEndpointInfoFormat.Builder = {
val builder = ReplicationEndpointInfoFormat.newBuilder()
builder.setEndpointId(info.endpointId)
info.logSequenceNrs.foreach(logInfo => builder.addLogInfos(logInfoFormatBuilder(logInfo)))
builder
}
private def logInfoFormatBuilder(info: (String, Long)): LogInfoFormat.Builder = {
val builder = LogInfoFormat.newBuilder()
builder.setLogName(info._1)
builder.setSequenceNr(info._2)
builder
}
private def applicationVersionFormatBuilder(applicationVersion: ApplicationVersion): ApplicationVersionFormat.Builder = {
val builder = ApplicationVersionFormat.newBuilder()
builder.setMajor(applicationVersion.major)
builder.setMinor(applicationVersion.minor)
builder
}
private def incompatibleApplicationVersionExceptionFormatBuilder(exception: IncompatibleApplicationVersionException): IncompatibleApplicationVersionExceptionFormat.Builder = {
val builder = IncompatibleApplicationVersionExceptionFormat.newBuilder()
builder.setSourceEndpointId(exception.sourceEndpointId)
builder.setSourceApplicationVersion(applicationVersionFormatBuilder(exception.sourceApplicationVersion))
builder.setTargetApplicationVersion(applicationVersionFormatBuilder(exception.targetApplicationVersion))
builder
}
private def replicationReadSourceExceptionFormatBuilder(exception: ReplicationReadSourceException): ReplicationReadSourceExceptionFormat.Builder = {
val builder = ReplicationReadSourceExceptionFormat.newBuilder()
builder.setMessage(exception.getMessage)
builder
}
private def synchronizeReplicationProgressSourceExceptionFormatBuilder(ex: SynchronizeReplicationProgressSourceException): SynchronizeReplicationProgressSourceExceptionFormat.Builder =
SynchronizeReplicationProgressSourceExceptionFormat.newBuilder().setMessage(ex.message)
// --------------------------------------------------------------------------------
// fromBinary helpers
// --------------------------------------------------------------------------------
private def replicationReadFailure(messageFormat: ReplicationReadFailureFormat): ReplicationReadFailure =
ReplicationReadFailure(
commonSerializer.payload(messageFormat.getCause).asInstanceOf[ReplicationReadException],
messageFormat.getTargetLogId)
private def replicationReadSuccess(messageFormat: ReplicationReadSuccessFormat): ReplicationReadSuccess = {
val builder = new VectorBuilder[DurableEvent]
messageFormat.getEventsList.iterator.asScala.foreach { eventFormat =>
builder += eventSerializer.durableEvent(eventFormat)
}
ReplicationReadSuccess(
builder.result(),
messageFormat.getFromSequenceNr,
messageFormat.getReplicationProgress,
messageFormat.getTargetLogId,
commonSerializer.vectorTime(messageFormat.getCurrentSourceVersionVector))
}
private def replicationRead(messageFormat: ReplicationReadFormat): ReplicationRead =
ReplicationRead(
messageFormat.getFromSequenceNr,
messageFormat.getMax,
messageFormat.getScanLimit,
filterSerializer.filterTree(messageFormat.getFilter),
messageFormat.getTargetLogId,
system.provider.resolveActorRef(messageFormat.getReplicator),
commonSerializer.vectorTime(messageFormat.getCurrentTargetVersionVector))
private def replicationReadEnvelope(messageFormat: ReplicationReadEnvelopeFormat): ReplicationReadEnvelope =
ReplicationReadEnvelope(
replicationRead(messageFormat.getPayload),
messageFormat.getLogName,
messageFormat.getTargetApplicationName,
applicationVersion(messageFormat.getTargetApplicationVersion))
private def getReplicationEndpointInfoSuccess(messageFormat: GetReplicationEndpointInfoSuccessFormat) =
GetReplicationEndpointInfoSuccess(replicationEndpointInfo(messageFormat.getInfo))
private def synchronizeReplicationProgress(messageFormat: SynchronizeReplicationProgressFormat) =
SynchronizeReplicationProgress(replicationEndpointInfo(messageFormat.getInfo))
private def synchronizeReplicationProgressSuccess(messageFormat: SynchronizeReplicationProgressSuccessFormat) =
SynchronizeReplicationProgressSuccess(replicationEndpointInfo(messageFormat.getInfo))
private def synchronizeReplicationProgressFailure(messageFormat: SynchronizeReplicationProgressFailureFormat): SynchronizeReplicationProgressFailure =
SynchronizeReplicationProgressFailure(commonSerializer.payload(messageFormat.getCause).asInstanceOf[SynchronizeReplicationProgressException])
private def replicationEndpointInfo(infoFormat: ReplicationEndpointInfoFormat): ReplicationEndpointInfo = {
ReplicationEndpointInfo(
infoFormat.getEndpointId,
infoFormat.getLogInfosList.asScala.map(logInfo)(breakOut))
}
private def logInfo(infoFormat: LogInfoFormat): (String, Long) =
infoFormat.getLogName -> infoFormat.getSequenceNr
private def applicationVersion(applicationVersionFormat: ApplicationVersionFormat): ApplicationVersion =
ApplicationVersion(applicationVersionFormat.getMajor, applicationVersionFormat.getMinor)
private def incompatibleApplicationVersionException(exceptionFormat: IncompatibleApplicationVersionExceptionFormat): IncompatibleApplicationVersionException =
IncompatibleApplicationVersionException(
exceptionFormat.getSourceEndpointId,
applicationVersion(exceptionFormat.getSourceApplicationVersion),
applicationVersion(exceptionFormat.getTargetApplicationVersion))
private def replicationReadSourceException(exceptionFormat: ReplicationReadSourceExceptionFormat): ReplicationReadSourceException =
ReplicationReadSourceException(exceptionFormat.getMessage)
private def synchronizeReplicationProgressSourceException(exceptionFormat: SynchronizeReplicationProgressSourceExceptionFormat): SynchronizeReplicationProgressSourceException =
SynchronizeReplicationProgressSourceException(exceptionFormat.getMessage)
}
| ianclegg/eventuate | eventuate-core/src/main/scala/com/rbmhtechnology/eventuate/serializer/ReplicationProtocolSerializer.scala | Scala | apache-2.0 | 16,007 |
package org.json4s
object ParserUtil {
class ParseException(message: String, cause: Exception) extends Exception(message, cause)
private val EOF = (-1).asInstanceOf[Char]
def unquote(string: String): String =
unquote(new Buffer(new java.io.StringReader(string), false))
private[json4s] def unquote(buf: Buffer): String = {
def unquote0(buf: Buffer, base: String): String = {
val s = new java.lang.StringBuilder(base)
var c = '\\'
while (c != '"') {
if (c == '\\') {
buf.next match {
case '"' => s.append('"')
case '\\' => s.append('\\')
case '/' => s.append('/')
case 'b' => s.append('\b')
case 'f' => s.append('\f')
case 'n' => s.append('\n')
case 'r' => s.append('\r')
case 't' => s.append('\t')
case 'u' =>
val chars = Array(buf.next, buf.next, buf.next, buf.next)
val codePoint = Integer.parseInt(new String(chars), 16)
s.appendCodePoint(codePoint)
case _ => s.append('\\')
}
} else s.append(c)
c = buf.next
}
s.toString
}
buf.eofIsFailure = true
buf.mark
var c = buf.next
while (c != '"') {
if (c == '\\') {
val s = unquote0(buf, buf.substring)
buf.eofIsFailure = false
return s
}
c = buf.next
}
buf.eofIsFailure = false
buf.substring
}
/* Buffer used to parse JSON.
* Buffer is divided to one or more segments (preallocated in Segments pool).
*/
private[json4s] class Buffer(in: java.io.Reader, closeAutomatically: Boolean) {
var offset = 0
var curMark = -1
var curMarkSegment = -1
var eofIsFailure = false
private[this] var segments: List[Segment] = List(Segments.apply())
private[this] var segment: Array[Char] = segments.head.seg
private[this] var cur = 0 // Pointer which points current parsing location
private[this] var curSegmentIdx = 0 // Pointer which points current segment
def mark = { curMark = cur; curMarkSegment = curSegmentIdx }
def back = cur = cur-1
def next: Char = {
if (cur == offset && read < 0) {
if (eofIsFailure) throw new ParseException("unexpected eof", null) else EOF
} else {
val c = segment(cur)
cur += 1
c
}
}
def substring = {
if (curSegmentIdx == curMarkSegment) new String(segment, curMark, cur-curMark-1)
else { // slower path for case when string is in two or more segments
var parts: List[(Int, Int, Array[Char])] = Nil
var i = curSegmentIdx
while (i >= curMarkSegment) {
val s = segments(i).seg
val start = if (i == curMarkSegment) curMark else 0
val end = if (i == curSegmentIdx) cur else s.length+1
parts = (start, end, s) :: parts
i = i-1
}
val len = parts.map(p => p._2 - p._1 - 1).foldLeft(0)(_ + _)
val chars = new Array[Char](len)
i = 0
var pos = 0
while (i < parts.size) {
val (start, end, b) = parts(i)
val partLen = end-start-1
System.arraycopy(b, start, chars, pos, partLen)
pos = pos + partLen
i = i+1
}
new String(chars)
}
}
def near = new String(segment, (cur-20) max 0, (cur + 1) min Segments.segmentSize)
def release = segments.foreach(Segments.release)
private[json4s] def automaticClose = if (closeAutomatically) in.close
private[this] def read = {
if (offset >= segment.length) {
val newSegment = Segments.apply()
offset = 0
segment = newSegment.seg
segments = segments ::: List(newSegment)
curSegmentIdx = segments.length - 1
}
val length = in.read(segment, offset, segment.length-offset)
cur = offset
offset += length
length
}
}
/* A pool of preallocated char arrays.
*/
private[json4s] object Segments {
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.atomic.AtomicInteger
private[json4s] var segmentSize = 1000
private[this] val maxNumOfSegments = 10000
private[this] var segmentCount = new AtomicInteger(0)
private[this] val segments = new ArrayBlockingQueue[Segment](maxNumOfSegments)
private[json4s] def clear = segments.clear
def apply(): Segment = {
val s = acquire
// Give back a disposable segment if pool is exhausted.
if (s != null) s else DisposableSegment(new Array(segmentSize))
}
private[this] def acquire: Segment = {
val curCount = segmentCount.get
val createNew =
if (segments.size == 0 && curCount < maxNumOfSegments)
segmentCount.compareAndSet(curCount, curCount + 1)
else false
if (createNew) RecycledSegment(new Array(segmentSize)) else segments.poll
}
def release(s: Segment) = s match {
case _: RecycledSegment => segments.offer(s)
case _ =>
}
}
sealed trait Segment {
val seg: Array[Char]
}
case class RecycledSegment(seg: Array[Char]) extends Segment
case class DisposableSegment(seg: Array[Char]) extends Segment
private val BrokenDouble = BigDecimal("2.2250738585072012e-308")
private[json4s] def parseDouble(s: String) = {
val d = BigDecimal(s)
if (d == BrokenDouble) sys.error("Error parsing 2.2250738585072012e-308")
else d.doubleValue
}
}
| nornagon/json4s | core/src/main/scala/org/json4s/ParserUtil.scala | Scala | apache-2.0 | 5,508 |
/*
* Author : Prasad Shivanna
* UB person no : 50170323
* UBIT Name : prasadsh
* Date : 10/05/2015
* email : prasadsh@buffalo.edu
*
*/
/*
Imports required for program Execution
*/
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import org.apache.spark.graphx._
import org.apache.spark.graphx.util._
import org.apache.log4j.Logger
import sys.process._
import java.io._
import java.io.FileNotFoundException
import java.io.IOException
import java.util.Calendar
// Exception to be throw in case of invalid config
case class InvalidConfigException(message: String) extends Exception(message)
/**
* Config class with all default values set
*/
case class Config(
numVertices: Int = 100,
numEdges:Int = 100,
graphType:String = "",
partitionCount: Int = 0,
mu: Double = 4.0,
sigma: Double = 1.3,
seed: Long = 1,
edgeListFile: String = null,
partitionStrategy: String = "EdgePartition2D"
)
/**
* Implements a Breadth First Search on the user provided graph
* @example this program can be used to generate various kinds of graph such as
* 1) Star graph - with all nodes pointing to one central node
* 2) Small world graph - This is also known as Log Normal graph,
* whose out degree distribution is log normal
* The default values of mu and sigma are taken from the pregel paper
* 3) rmatGraph - A random graph generator using the R-MAT model,
* Graphx has fixed the values for rmat{a-d} ,
* if required the graph generator can be extended and implemented to take user required values
*/
class GraphBFS{
/**
* Parse the arguments and generate config object
* @tparam args the array of command line arguments
* on successful parsing
* @return valid config object
* Throws exception in case of any error in validations
*/
def parseArgs(args: Array[String]) : Config = {
val graphTypes = List("LogNormal", "RMAT" ,"EdgeList", "Star")
val partitionStrategies = List("CanonicalRandomVertexCut", "EdgePartition1D", "EdgePartition2D", "RandomVertexCut")
// Generating the parser with all validations
val parser = new scopt.OptionParser[Config]("Jar"){
head("GraphX BFS","0.1")
opt[String] ('g',"graphType") required() validate { x => if(graphTypes.contains(x)) success else failure("Invalid type of graph")} action { (x,c) => c.copy(graphType = x)} text("Type of graph to be generated")
opt[String] ('p', "partitionStrategy") validate { x => if(partitionStrategies.contains(x)) success else failure("Invalid partitionStrategy")} action { (x,c) => c.copy(partitionStrategy = x)} text("partitionStrategy to be used")
opt[Int] ('v',"numVertices") validate { x => if (x <= 0) failure("vertices shud be > 0") else success} action { (x,c) => c.copy(numVertices = x)} text("Number of Vertices")
opt[Int] ('e',"numEdges") validate { x => if (x <= 0) failure("edges shud be > 0") else success} action { (x,c) => c.copy(numEdges = x)} text("Number of Edges")
opt[Int] ('n',"partitionCount") validate { x => if (x < 0) failure("number of edge parts shud be > 0") else success} action { (x,c) => c.copy(partitionCount = x)} text("Number of edge partitions to be made")
opt[Double] ('m',"mu") action { (x,c) => c.copy(mu = x)} text("Mu value for graph generation")
opt[Double] ('s',"sigma") action { (x,c) => c.copy(sigma = x)} text("Sigma value for graph generation")
opt[Long] ("seed") action { (x,c) => c.copy(seed = x)} text("Seed value for graph generation")
opt[String] ('f',"edgeListFile") action{ (x,c) => c.copy(edgeListFile = x)} text("Edge List file name")
help("help") text("prints this usage text")
}
parser.parse(args, Config()) match {
case Some(c) => c
case None => throw new InvalidConfigException("Invalid config")
}
}
/**
* Vertex function to be used by pregel API
* @tparam id - of the vertex being operated on
* @tparam attr - attribute already stored with the vertex
* @tparam msg - inbound message recieved during pregel iteration
* @return - min of attr and msg
*/
val vprog = { (id: VertexId, attr: Double, msg: Double) => math.min(attr,msg) }
/**
* SendMessage function to be used by pregel API
* @tparam EdgeTriplet - the edge triplet
* if Either one of the vertices is visited , then a message is sent to the other vertex
* if both are visited or not visited then no action is performed
* @return Iterator of vertexid and the message to be sent
*/
val sendMessage = { (triplet: EdgeTriplet[Double, Int]) =>
var iter:Iterator[(VertexId, Double)] = Iterator.empty
val isSrcMarked = triplet.srcAttr != Double.PositiveInfinity
val isDstMarked = triplet.dstAttr != Double.PositiveInfinity
if(!(isSrcMarked && isDstMarked)){
if(isSrcMarked){
iter = Iterator((triplet.dstId,triplet.srcAttr+1))
}else{
iter = Iterator((triplet.srcId,triplet.dstAttr+1))
}
}
iter
}
/**
* Reduce Message function to be used by pregel API
* @tparam messages recieved by one vertex
* @return the min of messages
*/
val reduceMessage = { (a: Double, b: Double) => math.min(a,b) }
/**
* Utility function to calculate time difference and round off
* @tparam 2 timestamps in nano seconds
* @return Returns the difference of them in milliseconds
*/
def calcTime(s1:Long, s2:Long): String = { BigDecimal((s1-s2)/1e6).setScale(2, BigDecimal.RoundingMode.HALF_UP).toString }
/**
* Generates a graph with the given config and spark context object
* @tparam config - the configuration object
* @tparam spark context object of the current running application
* @return the graph generated as per the config object
*/
def generateGraph(config: Config, sparkContext: SparkContext) = {
if (config.graphType == "LogNormal") {
GraphGenerators.logNormalGraph(sparkContext, config.numVertices, config.partitionCount, config.mu, config.sigma, config.seed)
}
else if(config.graphType == "RMAT"){
GraphGenerators.rmatGraph(sparkContext, config.numVertices, config.numEdges)
}
else if(config.graphType == "Star"){
GraphGenerators.starGraph(sparkContext, config.numVertices)
}
else {
GraphLoader.edgeListFile(sparkContext, config.edgeListFile)
}
}
/**
* The entrypoint to the graph processing function
*/
def main(args: Array[String]) {
val mainTime = System.nanoTime()
val config: Config = parseArgs(args)
val timeStamp = (System.currentTimeMillis/1000).toString
// Setting the appId based on type of graph specified
val appIdName = config.graphType +"_"+timeStamp
val sparkContext = new SparkContext(new SparkConf().setAppName(appIdName))
// Getting the log object
val log = Logger.getLogger(getClass.getName)
// Log prefix to identify the user generated logs
val logPrefix = "PRASAD:" + appIdName + ":"
log.info(logPrefix+ "args: " + args.mkString(","))
log.info(logPrefix + "Final generated Config")
sparkContext.getConf.getAll.foreach( con => log.info(logPrefix + "Conf: " + con))
log.info(logPrefix + "START:Time: " + Calendar.getInstance.getTime.toString)
log.info(logPrefix +s" appName: ${sparkContext.appName}, appId: ${sparkContext.applicationId}, master:${sparkContext.master} , numPartitions: ${config.partitionCount}")
val partitionStrategy = PartitionStrategy.fromString(config.partitionStrategy)
// Generating graph based on user configuration
val graph = generateGraph(config, sparkContext)
graph.cache()
val numPartitions: Int = if(config.partitionCount > 0) config.partitionCount else graph.edges.partitions.size
log.info(logPrefix + "LOAD:Time: "+calcTime(System.nanoTime, mainTime))
// Python script to log the metrics for the current running application
val pythonScript = sys.env("PYTHON_METRICS_SCRIPT")
// File to store the extracted metrics
val metricsJson = sys.env("METRICS_OUTPUT_FILE")
// Graph properties used for logging
val vCount = graph.vertices.count
val eCount = graph.edges.count
val master = sparkContext.master.trim.split(":")(1).replace("//","")
// Root vertex from which BFS is destined to start
val rootVertex: VertexId = graph.vertices.first()._1
val graphMapTime = System.nanoTime()
// Graph with Root vertex marked as 0 and rest are marked as unvisited
val initialGraph = graph.partitionBy(partitionStrategy, numPartitions).mapVertices((id, attr) => if (id == rootVertex) 0.0 else Double.PositiveInfinity)
// Unpersisting the previous graph and caching newly generated graph
graph.unpersist(blocking = false)
initialGraph.cache()
log.info(logPrefix + "BFS root Vertex: " + rootVertex)
log.info(logPrefix +"MapVertices: Time: "+ calcTime(System.nanoTime, graphMapTime))
// Pregel required properties
// Initial message sent to all vertices
val initialMessage = Double.PositiveInfinity
// Number of iterations the pregel api is run for
val maxIterations = Int.MaxValue
val activeEdgeDirection = EdgeDirection.Either
val bfsStart = System.nanoTime()
// Invoke pregel function with required parameters to perform BFS
val bfs = initialGraph.pregel(initialMessage, maxIterations, activeEdgeDirection)(vprog, sendMessage, reduceMessage)
// Unpersisting the graph
initialGraph.unpersist(blocking=false)
val bfsTime = calcTime(System.nanoTime, bfsStart)
log.info(logPrefix +"BFS: Time: "+ bfsTime)
//Generating a unique name for the metrics to be logged
val graphName = List(appIdName, config.partitionStrategy , vCount.toString, eCount.toString, numPartitions.toString,bfsTime.toString).mkString("_")
val metricsScript = List("python",pythonScript,master,graphName,metricsJson).mkString(" ")
log.info(logPrefix + s"metricScript: $pythonScript, outputFile: $metricsJson , graphName: $graphName, master: $master, " )
val logMetricTime = System.nanoTime()
//Logging all the metrics required for evaluation
val metricProcess = Process(metricsScript).!!
log.info(logPrefix + s"Log metrics output: $metricProcess")
log.info(logPrefix + "Log Metrics: Time: "+ calcTime(System.nanoTime, logMetricTime))
log.info(logPrefix + "Total: Time: "+ calcTime(System.nanoTime, mainTime))
log.info(logPrefix + "END: Time: " + Calendar.getInstance.getTime.toString)
}
}
object Driver extends App{
override def main(args: Array[String]) = {
val graph = new GraphBFS()
graph.main(args)
}
} | prasad223/GraphxBFS | src/main/scala/GraphBFS.scala | Scala | apache-2.0 | 10,577 |
/*
* 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.planner.expressions.utils
import org.apache.flink.api.common.typeinfo.Types
import org.apache.flink.api.java.typeutils.{ObjectArrayTypeInfo, RowTypeInfo}
import org.apache.flink.table.data.DecimalDataUtils
import org.apache.flink.table.planner.utils.DateTimeTestUtil.localDate
import org.apache.flink.table.runtime.typeutils.DecimalDataTypeInfo
import org.apache.flink.types.Row
abstract class RowTypeTestBase extends ExpressionTestBase {
override def testData: Row = {
val row = new Row(3)
row.setField(0, 2)
row.setField(1, "foo")
row.setField(2, true)
val nestedRow = new Row(2)
nestedRow.setField(0, 3)
nestedRow.setField(1, row)
val specialTypeRow = new Row(3)
specialTypeRow.setField(0, localDate("1984-03-12"))
specialTypeRow.setField(1, DecimalDataUtils.castFrom("0.00000000", 9, 8))
specialTypeRow.setField(2, Array[java.lang.Integer](1, 2, 3))
val testData = new Row(7)
testData.setField(0, null)
testData.setField(1, 1)
testData.setField(2, row)
testData.setField(3, nestedRow)
testData.setField(4, specialTypeRow)
testData.setField(5, Row.of("foo", null))
testData.setField(6, Row.of(null, null))
testData
}
override def typeInfo: RowTypeInfo = {
new RowTypeInfo(
/* 0 */ Types.STRING,
/* 1 */ Types.INT,
/* 2 */ Types.ROW(Types.INT, Types.STRING, Types.BOOLEAN),
/* 3 */ Types.ROW(Types.INT, Types.ROW(Types.INT, Types.STRING, Types.BOOLEAN)),
/* 4 */ Types.ROW(
Types.LOCAL_DATE,
DecimalDataTypeInfo.of(9, 8),
ObjectArrayTypeInfo.getInfoFor(Types.INT)),
/* 5 */ Types.ROW(Types.STRING, Types.BOOLEAN),
/* 6 */ Types.ROW(Types.STRING, Types.STRING)
)
}
}
| lincoln-lil/flink | flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/planner/expressions/utils/RowTypeTestBase.scala | Scala | apache-2.0 | 2,596 |
package xyz.hyperreal.upload
import spray.http._
import MediaTypes._
import java.io.{ByteArrayInputStream, ByteArrayOutputStream, File}
import java.nio.file.Files
import javax.imageio.ImageIO
import java.awt.image.BufferedImage
import java.awt.Image
object Images {
def http( image: Array[Byte] ) = HttpResponse( entity = HttpEntity(ContentType(`image/jpeg`), HttpData(image)) )
def avatar( image: Array[Byte], size: Int, thumb: Int ) = (toJPEG( image, Some(size, size) ), toJPEG( image, Some(thumb, thumb) ))
def toJPEG( image: Array[Byte], resize: Option[(Int, Int)] ) = convert( image, "JPEG", resize )
def convert( image: Array[Byte], typ: String, resize: Option[(Int, Int)] ) = {
val img = ImageIO.read( new ByteArrayInputStream(image) ) match {
case null => sys.error( "can't decode image" )
case x => x
}
val scale = resize != None
val (width, height) =
resize match {
case Some( (w, h) ) => (w, h)
case None => (img.getWidth, img.getHeight)
}
val buf = new BufferedImage( width, height, BufferedImage.TYPE_INT_RGB )
val data = new ByteArrayOutputStream
buf.getGraphics.drawImage( if (scale) img.getScaledInstance(width, height, Image.SCALE_SMOOTH) else img, 0, 0, null )
ImageIO.write( buf, typ, data )
data.toByteArray
}
} | edadma/spray-upload | src/main/scala/Images.scala | Scala | mit | 1,290 |
import scala.quoted._
object Macro {
inline def ff[T](implicit t: Type[T]): Int = ${ impl[T] }
def impl[T](using QuoteContext): Expr[Int] = '{4}
}
| som-snytt/dotty | tests/pos-macros/i4023b/Macro_1.scala | Scala | apache-2.0 | 151 |
/*
* 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.catalyst.catalog
import java.net.URI
import java.util.TimeZone
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.Path
import org.scalatest.BeforeAndAfterEach
import org.apache.spark.SparkFunSuite
import org.apache.spark.sql.AnalysisException
import org.apache.spark.sql.catalyst.{FunctionIdentifier, TableIdentifier}
import org.apache.spark.sql.catalyst.analysis.{FunctionAlreadyExistsException, NoSuchDatabaseException, NoSuchFunctionException}
import org.apache.spark.sql.catalyst.analysis.TableAlreadyExistsException
import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.connector.catalog.SupportsNamespaces.{PROP_OWNER_NAME, PROP_OWNER_TYPE}
import org.apache.spark.sql.types._
import org.apache.spark.util.Utils
/**
* A reasonable complete test suite (i.e. behaviors) for a [[ExternalCatalog]].
*
* Implementations of the [[ExternalCatalog]] interface can create test suites by extending this.
*/
abstract class ExternalCatalogSuite extends SparkFunSuite with BeforeAndAfterEach {
protected val utils: CatalogTestUtils
import utils._
protected def resetState(): Unit = { }
// Clear all state after each test
override def afterEach(): Unit = {
try {
resetState()
} finally {
super.afterEach()
}
}
// --------------------------------------------------------------------------
// Databases
// --------------------------------------------------------------------------
test("basic create and list databases") {
val catalog = newEmptyCatalog()
catalog.createDatabase(newDb("default"), ignoreIfExists = true)
assert(catalog.databaseExists("default"))
assert(!catalog.databaseExists("testing"))
assert(!catalog.databaseExists("testing2"))
catalog.createDatabase(newDb("testing"), ignoreIfExists = false)
assert(catalog.databaseExists("testing"))
assert(catalog.listDatabases().toSet == Set("default", "testing"))
catalog.createDatabase(newDb("testing2"), ignoreIfExists = false)
assert(catalog.listDatabases().toSet == Set("default", "testing", "testing2"))
assert(catalog.databaseExists("testing2"))
assert(!catalog.databaseExists("does_not_exist"))
}
test("get database when a database exists") {
val db1 = newBasicCatalog().getDatabase("db1")
assert(db1.name == "db1")
assert(db1.description.contains("db1"))
}
test("get database should throw exception when the database does not exist") {
intercept[AnalysisException] { newBasicCatalog().getDatabase("db_that_does_not_exist") }
}
test("list databases without pattern") {
val catalog = newBasicCatalog()
assert(catalog.listDatabases().toSet == Set("default", "db1", "db2", "db3"))
}
test("list databases with pattern") {
val catalog = newBasicCatalog()
assert(catalog.listDatabases("db").toSet == Set.empty)
assert(catalog.listDatabases("db*").toSet == Set("db1", "db2", "db3"))
assert(catalog.listDatabases("*1").toSet == Set("db1"))
assert(catalog.listDatabases("db2").toSet == Set("db2"))
}
test("drop database") {
val catalog = newBasicCatalog()
catalog.dropDatabase("db1", ignoreIfNotExists = false, cascade = false)
assert(catalog.listDatabases().toSet == Set("default", "db2", "db3"))
}
test("drop database when the database is not empty") {
// Throw exception if there are functions left
val catalog1 = newBasicCatalog()
catalog1.dropTable("db2", "tbl1", ignoreIfNotExists = false, purge = false)
catalog1.dropTable("db2", "tbl2", ignoreIfNotExists = false, purge = false)
intercept[AnalysisException] {
catalog1.dropDatabase("db2", ignoreIfNotExists = false, cascade = false)
}
resetState()
// Throw exception if there are tables left
val catalog2 = newBasicCatalog()
catalog2.dropFunction("db2", "func1")
intercept[AnalysisException] {
catalog2.dropDatabase("db2", ignoreIfNotExists = false, cascade = false)
}
resetState()
// When cascade is true, it should drop them
val catalog3 = newBasicCatalog()
catalog3.dropDatabase("db2", ignoreIfNotExists = false, cascade = true)
assert(catalog3.listDatabases().toSet == Set("default", "db1", "db3"))
}
test("drop database when the database does not exist") {
val catalog = newBasicCatalog()
intercept[AnalysisException] {
catalog.dropDatabase("db_that_does_not_exist", ignoreIfNotExists = false, cascade = false)
}
catalog.dropDatabase("db_that_does_not_exist", ignoreIfNotExists = true, cascade = false)
}
test("alter database") {
val catalog = newBasicCatalog()
val db1 = catalog.getDatabase("db1")
// Note: alter properties here because Hive does not support altering other fields
catalog.alterDatabase(db1.copy(properties = Map("k" -> "v3", "good" -> "true")))
val newDb1 = catalog.getDatabase("db1")
val reversedProperties = Seq(PROP_OWNER_NAME, PROP_OWNER_TYPE)
assert((db1.properties -- reversedProperties).isEmpty)
assert((newDb1.properties -- reversedProperties).size == 2)
assert(newDb1.properties.get("k") == Some("v3"))
assert(newDb1.properties.get("good") == Some("true"))
}
test("alter database should throw exception when the database does not exist") {
intercept[AnalysisException] {
newBasicCatalog().alterDatabase(newDb("does_not_exist"))
}
}
// --------------------------------------------------------------------------
// Tables
// --------------------------------------------------------------------------
test("the table type of an external table should be EXTERNAL_TABLE") {
val catalog = newBasicCatalog()
val table = newTable("external_table1", "db2").copy(tableType = CatalogTableType.EXTERNAL)
catalog.createTable(table, ignoreIfExists = false)
val actual = catalog.getTable("db2", "external_table1")
assert(actual.tableType === CatalogTableType.EXTERNAL)
}
test("create table when the table already exists") {
val catalog = newBasicCatalog()
assert(catalog.listTables("db2").toSet == Set("tbl1", "tbl2"))
val table = newTable("tbl1", "db2")
intercept[TableAlreadyExistsException] {
catalog.createTable(table, ignoreIfExists = false)
}
}
test("drop table") {
val catalog = newBasicCatalog()
assert(catalog.listTables("db2").toSet == Set("tbl1", "tbl2"))
catalog.dropTable("db2", "tbl1", ignoreIfNotExists = false, purge = false)
assert(catalog.listTables("db2").toSet == Set("tbl2"))
}
test("drop table when database/table does not exist") {
val catalog = newBasicCatalog()
// Should always throw exception when the database does not exist
intercept[AnalysisException] {
catalog.dropTable("unknown_db", "unknown_table", ignoreIfNotExists = false, purge = false)
}
intercept[AnalysisException] {
catalog.dropTable("unknown_db", "unknown_table", ignoreIfNotExists = true, purge = false)
}
// Should throw exception when the table does not exist, if ignoreIfNotExists is false
intercept[AnalysisException] {
catalog.dropTable("db2", "unknown_table", ignoreIfNotExists = false, purge = false)
}
catalog.dropTable("db2", "unknown_table", ignoreIfNotExists = true, purge = false)
}
test("rename table") {
val catalog = newBasicCatalog()
assert(catalog.listTables("db2").toSet == Set("tbl1", "tbl2"))
catalog.renameTable("db2", "tbl1", "tblone")
assert(catalog.listTables("db2").toSet == Set("tblone", "tbl2"))
}
test("rename table when database/table does not exist") {
val catalog = newBasicCatalog()
intercept[AnalysisException] {
catalog.renameTable("unknown_db", "unknown_table", "unknown_table")
}
intercept[AnalysisException] {
catalog.renameTable("db2", "unknown_table", "unknown_table")
}
}
test("rename table when destination table already exists") {
val catalog = newBasicCatalog()
intercept[AnalysisException] {
catalog.renameTable("db2", "tbl1", "tbl2")
}
}
test("alter table") {
val catalog = newBasicCatalog()
val tbl1 = catalog.getTable("db2", "tbl1")
catalog.alterTable(tbl1.copy(properties = Map("toh" -> "frem")))
val newTbl1 = catalog.getTable("db2", "tbl1")
assert(!tbl1.properties.contains("toh"))
assert(newTbl1.properties.size == tbl1.properties.size + 1)
assert(newTbl1.properties.get("toh") == Some("frem"))
}
test("alter table when database/table does not exist") {
val catalog = newBasicCatalog()
intercept[AnalysisException] {
catalog.alterTable(newTable("tbl1", "unknown_db"))
}
intercept[AnalysisException] {
catalog.alterTable(newTable("unknown_table", "db2"))
}
}
test("alter table schema") {
val catalog = newBasicCatalog()
val newDataSchema = StructType(Seq(
StructField("col1", IntegerType),
StructField("new_field_2", StringType)))
catalog.alterTableDataSchema("db2", "tbl1", newDataSchema)
val newTbl1 = catalog.getTable("db2", "tbl1")
assert(newTbl1.dataSchema == newDataSchema)
}
test("alter table stats") {
val catalog = newBasicCatalog()
val oldTableStats = catalog.getTable("db2", "tbl1").stats
assert(oldTableStats.isEmpty)
val newStats = CatalogStatistics(sizeInBytes = 1)
catalog.alterTableStats("db2", "tbl1", Some(newStats))
val newTableStats = catalog.getTable("db2", "tbl1").stats
assert(newTableStats.get == newStats)
}
test("get table") {
assert(newBasicCatalog().getTable("db2", "tbl1").identifier.table == "tbl1")
}
test("get table when database/table does not exist") {
val catalog = newBasicCatalog()
intercept[AnalysisException] {
catalog.getTable("unknown_db", "unknown_table")
}
intercept[AnalysisException] {
catalog.getTable("db2", "unknown_table")
}
}
test("get tables by name") {
assert(newBasicCatalog().getTablesByName("db2", Seq("tbl1", "tbl2"))
.map(_.identifier.table) == Seq("tbl1", "tbl2"))
}
test("get tables by name when some tables do not exists") {
assert(newBasicCatalog().getTablesByName("db2", Seq("tbl1", "tblnotexist"))
.map(_.identifier.table) == Seq("tbl1"))
}
test("get tables by name when contains invalid name") {
// scalastyle:off
val name = "砖"
// scalastyle:on
assert(newBasicCatalog().getTablesByName("db2", Seq("tbl1", name))
.map(_.identifier.table) == Seq("tbl1"))
}
test("get tables by name when empty table list") {
assert(newBasicCatalog().getTablesByName("db2", Seq.empty).isEmpty)
}
test("list tables without pattern") {
val catalog = newBasicCatalog()
intercept[AnalysisException] { catalog.listTables("unknown_db") }
assert(catalog.listTables("db1").toSet == Set.empty)
assert(catalog.listTables("db2").toSet == Set("tbl1", "tbl2"))
}
test("list tables with pattern") {
val catalog = newBasicCatalog()
intercept[AnalysisException] { catalog.listTables("unknown_db", "*") }
assert(catalog.listTables("db1", "*").toSet == Set.empty)
assert(catalog.listTables("db2", "*").toSet == Set("tbl1", "tbl2"))
assert(catalog.listTables("db2", "tbl*").toSet == Set("tbl1", "tbl2"))
assert(catalog.listTables("db2", "*1").toSet == Set("tbl1"))
}
test("column names should be case-preserving and column nullability should be retained") {
val catalog = newBasicCatalog()
val tbl = CatalogTable(
identifier = TableIdentifier("tbl", Some("db1")),
tableType = CatalogTableType.MANAGED,
storage = storageFormat,
schema = new StructType()
.add("HelLo", "int", nullable = false)
.add("WoRLd", "int", nullable = true),
provider = Some(defaultProvider),
partitionColumnNames = Seq("WoRLd"),
bucketSpec = Some(BucketSpec(4, Seq("HelLo"), Nil)))
catalog.createTable(tbl, ignoreIfExists = false)
val readBack = catalog.getTable("db1", "tbl")
assert(readBack.schema == tbl.schema)
assert(readBack.partitionColumnNames == tbl.partitionColumnNames)
assert(readBack.bucketSpec == tbl.bucketSpec)
}
// --------------------------------------------------------------------------
// Partitions
// --------------------------------------------------------------------------
test("basic create and list partitions") {
val catalog = newEmptyCatalog()
catalog.createDatabase(newDb("mydb"), ignoreIfExists = false)
catalog.createTable(newTable("tbl", "mydb"), ignoreIfExists = false)
catalog.createPartitions("mydb", "tbl", Seq(part1, part2), ignoreIfExists = false)
assert(catalogPartitionsEqual(catalog, "mydb", "tbl", Seq(part1, part2)))
}
test("create partitions when database/table does not exist") {
val catalog = newBasicCatalog()
intercept[AnalysisException] {
catalog.createPartitions("does_not_exist", "tbl1", Seq(), ignoreIfExists = false)
}
intercept[AnalysisException] {
catalog.createPartitions("db2", "does_not_exist", Seq(), ignoreIfExists = false)
}
}
test("create partitions that already exist") {
val catalog = newBasicCatalog()
intercept[AnalysisException] {
catalog.createPartitions("db2", "tbl2", Seq(part1), ignoreIfExists = false)
}
catalog.createPartitions("db2", "tbl2", Seq(part1), ignoreIfExists = true)
}
test("create partitions without location") {
val catalog = newBasicCatalog()
val table = CatalogTable(
identifier = TableIdentifier("tbl", Some("db1")),
tableType = CatalogTableType.MANAGED,
storage = CatalogStorageFormat.empty,
schema = new StructType()
.add("col1", "int")
.add("col2", "string")
.add("partCol1", "int")
.add("partCol2", "string"),
provider = Some(defaultProvider),
partitionColumnNames = Seq("partCol1", "partCol2"))
catalog.createTable(table, ignoreIfExists = false)
val partition = CatalogTablePartition(Map("partCol1" -> "1", "partCol2" -> "2"), storageFormat)
catalog.createPartitions("db1", "tbl", Seq(partition), ignoreIfExists = false)
val partitionLocation = catalog.getPartition(
"db1",
"tbl",
Map("partCol1" -> "1", "partCol2" -> "2")).location
val tableLocation = new Path(catalog.getTable("db1", "tbl").location)
val defaultPartitionLocation = new Path(new Path(tableLocation, "partCol1=1"), "partCol2=2")
assert(new Path(partitionLocation) == defaultPartitionLocation)
}
test("create/drop partitions in managed tables with location") {
val catalog = newBasicCatalog()
val table = CatalogTable(
identifier = TableIdentifier("tbl", Some("db1")),
tableType = CatalogTableType.MANAGED,
storage = CatalogStorageFormat.empty,
schema = new StructType()
.add("col1", "int")
.add("col2", "string")
.add("partCol1", "int")
.add("partCol2", "string"),
provider = Some(defaultProvider),
partitionColumnNames = Seq("partCol1", "partCol2"))
catalog.createTable(table, ignoreIfExists = false)
val newLocationPart1 = newUriForDatabase()
val newLocationPart2 = newUriForDatabase()
val partition1 =
CatalogTablePartition(Map("partCol1" -> "1", "partCol2" -> "2"),
storageFormat.copy(locationUri = Some(newLocationPart1)))
val partition2 =
CatalogTablePartition(Map("partCol1" -> "3", "partCol2" -> "4"),
storageFormat.copy(locationUri = Some(newLocationPart2)))
catalog.createPartitions("db1", "tbl", Seq(partition1), ignoreIfExists = false)
catalog.createPartitions("db1", "tbl", Seq(partition2), ignoreIfExists = false)
assert(exists(newLocationPart1))
assert(exists(newLocationPart2))
// the corresponding directory is dropped.
catalog.dropPartitions("db1", "tbl", Seq(partition1.spec),
ignoreIfNotExists = false, purge = false, retainData = false)
assert(!exists(newLocationPart1))
// all the remaining directories are dropped.
catalog.dropTable("db1", "tbl", ignoreIfNotExists = false, purge = false)
assert(!exists(newLocationPart2))
}
test("list partition names") {
val catalog = newBasicCatalog()
val newPart = CatalogTablePartition(Map("a" -> "1", "b" -> "%="), storageFormat)
catalog.createPartitions("db2", "tbl2", Seq(newPart), ignoreIfExists = false)
val partitionNames = catalog.listPartitionNames("db2", "tbl2")
assert(partitionNames == Seq("a=1/b=%25%3D", "a=1/b=2", "a=3/b=4"))
}
test("list partition names with partial partition spec") {
val catalog = newBasicCatalog()
val newPart = CatalogTablePartition(Map("a" -> "1", "b" -> "%="), storageFormat)
catalog.createPartitions("db2", "tbl2", Seq(newPart), ignoreIfExists = false)
val partitionNames1 = catalog.listPartitionNames("db2", "tbl2", Some(Map("a" -> "1")))
assert(partitionNames1 == Seq("a=1/b=%25%3D", "a=1/b=2"))
// Partial partition specs including "weird" partition values should use the unescaped values
val partitionNames2 = catalog.listPartitionNames("db2", "tbl2", Some(Map("b" -> "%=")))
assert(partitionNames2 == Seq("a=1/b=%25%3D"))
val partitionNames3 = catalog.listPartitionNames("db2", "tbl2", Some(Map("b" -> "%25%3D")))
assert(partitionNames3.isEmpty)
}
test("list partitions with partial partition spec") {
val catalog = newBasicCatalog()
val parts = catalog.listPartitions("db2", "tbl2", Some(Map("a" -> "1")))
assert(parts.length == 1)
assert(parts.head.spec == part1.spec)
// if no partition is matched for the given partition spec, an empty list should be returned.
assert(catalog.listPartitions("db2", "tbl2", Some(Map("a" -> "unknown", "b" -> "1"))).isEmpty)
assert(catalog.listPartitions("db2", "tbl2", Some(Map("a" -> "unknown"))).isEmpty)
}
test("SPARK-21457: list partitions with special chars") {
val catalog = newBasicCatalog()
assert(catalog.listPartitions("db2", "tbl1").isEmpty)
val part1 = CatalogTablePartition(Map("a" -> "1", "b" -> "i+j"), storageFormat)
val part2 = CatalogTablePartition(Map("a" -> "1", "b" -> "i.j"), storageFormat)
catalog.createPartitions("db2", "tbl1", Seq(part1, part2), ignoreIfExists = false)
assert(catalog.listPartitions("db2", "tbl1", Some(part1.spec)).map(_.spec) == Seq(part1.spec))
assert(catalog.listPartitions("db2", "tbl1", Some(part2.spec)).map(_.spec) == Seq(part2.spec))
}
test("list partitions by filter") {
val tz = TimeZone.getDefault.getID
val catalog = newBasicCatalog()
def checkAnswer(
table: CatalogTable, filters: Seq[Expression], expected: Set[CatalogTablePartition])
: Unit = {
assertResult(expected.map(_.spec)) {
catalog.listPartitionsByFilter(table.database, table.identifier.identifier, filters, tz)
.map(_.spec).toSet
}
}
val tbl2 = catalog.getTable("db2", "tbl2")
checkAnswer(tbl2, Seq.empty, Set(part1, part2))
checkAnswer(tbl2, Seq('a.int <= 1), Set(part1))
checkAnswer(tbl2, Seq('a.int === 2), Set.empty)
checkAnswer(tbl2, Seq(In('a.int * 10, Seq(30))), Set(part2))
checkAnswer(tbl2, Seq(Not(In('a.int, Seq(4)))), Set(part1, part2))
checkAnswer(tbl2, Seq('a.int === 1, 'b.string === "2"), Set(part1))
checkAnswer(tbl2, Seq('a.int === 1 && 'b.string === "2"), Set(part1))
checkAnswer(tbl2, Seq('a.int === 1, 'b.string === "x"), Set.empty)
checkAnswer(tbl2, Seq('a.int === 1 || 'b.string === "x"), Set(part1))
intercept[AnalysisException] {
try {
checkAnswer(tbl2, Seq('a.int > 0 && 'col1.int > 0), Set.empty)
} catch {
// HiveExternalCatalog may be the first one to notice and throw an exception, which will
// then be caught and converted to a RuntimeException with a descriptive message.
case ex: RuntimeException if ex.getMessage.contains("MetaException") =>
throw new AnalysisException(ex.getMessage)
}
}
}
test("drop partitions") {
val catalog = newBasicCatalog()
assert(catalogPartitionsEqual(catalog, "db2", "tbl2", Seq(part1, part2)))
catalog.dropPartitions(
"db2", "tbl2", Seq(part1.spec), ignoreIfNotExists = false, purge = false, retainData = false)
assert(catalogPartitionsEqual(catalog, "db2", "tbl2", Seq(part2)))
resetState()
val catalog2 = newBasicCatalog()
assert(catalogPartitionsEqual(catalog2, "db2", "tbl2", Seq(part1, part2)))
catalog2.dropPartitions(
"db2", "tbl2", Seq(part1.spec, part2.spec), ignoreIfNotExists = false, purge = false,
retainData = false)
assert(catalog2.listPartitions("db2", "tbl2").isEmpty)
}
test("drop partitions when database/table does not exist") {
val catalog = newBasicCatalog()
intercept[AnalysisException] {
catalog.dropPartitions(
"does_not_exist", "tbl1", Seq(), ignoreIfNotExists = false, purge = false,
retainData = false)
}
intercept[AnalysisException] {
catalog.dropPartitions(
"db2", "does_not_exist", Seq(), ignoreIfNotExists = false, purge = false,
retainData = false)
}
}
test("drop partitions that do not exist") {
val catalog = newBasicCatalog()
intercept[AnalysisException] {
catalog.dropPartitions(
"db2", "tbl2", Seq(part3.spec), ignoreIfNotExists = false, purge = false,
retainData = false)
}
catalog.dropPartitions(
"db2", "tbl2", Seq(part3.spec), ignoreIfNotExists = true, purge = false, retainData = false)
}
test("get partition") {
val catalog = newBasicCatalog()
assert(catalog.getPartition("db2", "tbl2", part1.spec).spec == part1.spec)
assert(catalog.getPartition("db2", "tbl2", part2.spec).spec == part2.spec)
intercept[AnalysisException] {
catalog.getPartition("db2", "tbl1", part3.spec)
}
}
test("get partition when database/table does not exist") {
val catalog = newBasicCatalog()
intercept[AnalysisException] {
catalog.getPartition("does_not_exist", "tbl1", part1.spec)
}
intercept[AnalysisException] {
catalog.getPartition("db2", "does_not_exist", part1.spec)
}
}
test("rename partitions") {
val catalog = newBasicCatalog()
val newPart1 = part1.copy(spec = Map("a" -> "100", "b" -> "101"))
val newPart2 = part2.copy(spec = Map("a" -> "200", "b" -> "201"))
val newSpecs = Seq(newPart1.spec, newPart2.spec)
catalog.renamePartitions("db2", "tbl2", Seq(part1.spec, part2.spec), newSpecs)
assert(catalog.getPartition("db2", "tbl2", newPart1.spec).spec === newPart1.spec)
assert(catalog.getPartition("db2", "tbl2", newPart2.spec).spec === newPart2.spec)
// The old partitions should no longer exist
intercept[AnalysisException] { catalog.getPartition("db2", "tbl2", part1.spec) }
intercept[AnalysisException] { catalog.getPartition("db2", "tbl2", part2.spec) }
}
test("rename partitions should update the location for managed table") {
val catalog = newBasicCatalog()
val table = CatalogTable(
identifier = TableIdentifier("tbl", Some("db1")),
tableType = CatalogTableType.MANAGED,
storage = CatalogStorageFormat.empty,
schema = new StructType()
.add("col1", "int")
.add("col2", "string")
.add("partCol1", "int")
.add("partCol2", "string"),
provider = Some(defaultProvider),
partitionColumnNames = Seq("partCol1", "partCol2"))
catalog.createTable(table, ignoreIfExists = false)
val tableLocation = new Path(catalog.getTable("db1", "tbl").location)
val mixedCasePart1 = CatalogTablePartition(
Map("partCol1" -> "1", "partCol2" -> "2"), storageFormat)
val mixedCasePart2 = CatalogTablePartition(
Map("partCol1" -> "3", "partCol2" -> "4"), storageFormat)
catalog.createPartitions("db1", "tbl", Seq(mixedCasePart1), ignoreIfExists = false)
assert(
new Path(catalog.getPartition("db1", "tbl", mixedCasePart1.spec).location) ==
new Path(new Path(tableLocation, "partCol1=1"), "partCol2=2"))
catalog.renamePartitions("db1", "tbl", Seq(mixedCasePart1.spec), Seq(mixedCasePart2.spec))
assert(
new Path(catalog.getPartition("db1", "tbl", mixedCasePart2.spec).location) ==
new Path(new Path(tableLocation, "partCol1=3"), "partCol2=4"))
// For external tables, RENAME PARTITION should not update the partition location.
val existingPartLoc = catalog.getPartition("db2", "tbl2", part1.spec).location
catalog.renamePartitions("db2", "tbl2", Seq(part1.spec), Seq(part3.spec))
assert(
new Path(catalog.getPartition("db2", "tbl2", part3.spec).location) ==
new Path(existingPartLoc))
}
test("rename partitions when database/table does not exist") {
val catalog = newBasicCatalog()
intercept[AnalysisException] {
catalog.renamePartitions("does_not_exist", "tbl1", Seq(part1.spec), Seq(part2.spec))
}
intercept[AnalysisException] {
catalog.renamePartitions("db2", "does_not_exist", Seq(part1.spec), Seq(part2.spec))
}
}
test("rename partitions when the new partition already exists") {
val catalog = newBasicCatalog()
intercept[AnalysisException] {
catalog.renamePartitions("db2", "tbl2", Seq(part1.spec), Seq(part2.spec))
}
}
test("alter partitions") {
val catalog = newBasicCatalog()
try {
val newLocation = newUriForDatabase()
val newSerde = "com.sparkbricks.text.EasySerde"
val newSerdeProps = Map("spark" -> "bricks", "compressed" -> "false")
// alter but keep spec the same
val oldPart1 = catalog.getPartition("db2", "tbl2", part1.spec)
val oldPart2 = catalog.getPartition("db2", "tbl2", part2.spec)
catalog.alterPartitions("db2", "tbl2", Seq(
oldPart1.copy(storage = storageFormat.copy(locationUri = Some(newLocation))),
oldPart2.copy(storage = storageFormat.copy(locationUri = Some(newLocation)))))
val newPart1 = catalog.getPartition("db2", "tbl2", part1.spec)
val newPart2 = catalog.getPartition("db2", "tbl2", part2.spec)
assert(newPart1.storage.locationUri == Some(newLocation))
assert(newPart2.storage.locationUri == Some(newLocation))
assert(oldPart1.storage.locationUri != Some(newLocation))
assert(oldPart2.storage.locationUri != Some(newLocation))
// alter other storage information
catalog.alterPartitions("db2", "tbl2", Seq(
oldPart1.copy(storage = storageFormat.copy(serde = Some(newSerde))),
oldPart2.copy(storage = storageFormat.copy(properties = newSerdeProps))))
val newPart1b = catalog.getPartition("db2", "tbl2", part1.spec)
val newPart2b = catalog.getPartition("db2", "tbl2", part2.spec)
assert(newPart1b.storage.serde == Some(newSerde))
assert(newPart2b.storage.properties == newSerdeProps)
// alter but change spec, should fail because new partition specs do not exist yet
val badPart1 = part1.copy(spec = Map("a" -> "v1", "b" -> "v2"))
val badPart2 = part2.copy(spec = Map("a" -> "v3", "b" -> "v4"))
intercept[AnalysisException] {
catalog.alterPartitions("db2", "tbl2", Seq(badPart1, badPart2))
}
} finally {
// Remember to restore the original current database, which we assume to be "default"
catalog.setCurrentDatabase("default")
}
}
test("alter partitions when database/table does not exist") {
val catalog = newBasicCatalog()
intercept[AnalysisException] {
catalog.alterPartitions("does_not_exist", "tbl1", Seq(part1))
}
intercept[AnalysisException] {
catalog.alterPartitions("db2", "does_not_exist", Seq(part1))
}
}
// --------------------------------------------------------------------------
// Functions
// --------------------------------------------------------------------------
test("basic create and list functions") {
val catalog = newEmptyCatalog()
catalog.createDatabase(newDb("mydb"), ignoreIfExists = false)
catalog.createFunction("mydb", newFunc("myfunc"))
assert(catalog.listFunctions("mydb", "*").toSet == Set("myfunc"))
}
test("create function when database does not exist") {
val catalog = newBasicCatalog()
intercept[NoSuchDatabaseException] {
catalog.createFunction("does_not_exist", newFunc())
}
}
test("create function that already exists") {
val catalog = newBasicCatalog()
intercept[FunctionAlreadyExistsException] {
catalog.createFunction("db2", newFunc("func1"))
}
}
test("drop function") {
val catalog = newBasicCatalog()
assert(catalog.listFunctions("db2", "*").toSet == Set("func1"))
catalog.dropFunction("db2", "func1")
assert(catalog.listFunctions("db2", "*").isEmpty)
}
test("drop function when database does not exist") {
val catalog = newBasicCatalog()
intercept[NoSuchDatabaseException] {
catalog.dropFunction("does_not_exist", "something")
}
}
test("drop function that does not exist") {
val catalog = newBasicCatalog()
intercept[NoSuchFunctionException] {
catalog.dropFunction("db2", "does_not_exist")
}
}
test("get function") {
val catalog = newBasicCatalog()
assert(catalog.getFunction("db2", "func1") ==
CatalogFunction(FunctionIdentifier("func1", Some("db2")), funcClass,
Seq.empty[FunctionResource]))
intercept[NoSuchFunctionException] {
catalog.getFunction("db2", "does_not_exist")
}
}
test("get function when database does not exist") {
val catalog = newBasicCatalog()
intercept[NoSuchDatabaseException] {
catalog.getFunction("does_not_exist", "func1")
}
}
test("rename function") {
val catalog = newBasicCatalog()
val newName = "funcky"
assert(catalog.getFunction("db2", "func1").className == funcClass)
catalog.renameFunction("db2", "func1", newName)
intercept[NoSuchFunctionException] { catalog.getFunction("db2", "func1") }
assert(catalog.getFunction("db2", newName).identifier.funcName == newName)
assert(catalog.getFunction("db2", newName).className == funcClass)
intercept[NoSuchFunctionException] { catalog.renameFunction("db2", "does_not_exist", "me") }
}
test("rename function when database does not exist") {
val catalog = newBasicCatalog()
intercept[NoSuchDatabaseException] {
catalog.renameFunction("does_not_exist", "func1", "func5")
}
}
test("rename function when new function already exists") {
val catalog = newBasicCatalog()
catalog.createFunction("db2", newFunc("func2", Some("db2")))
intercept[FunctionAlreadyExistsException] {
catalog.renameFunction("db2", "func1", "func2")
}
}
test("alter function") {
val catalog = newBasicCatalog()
assert(catalog.getFunction("db2", "func1").className == funcClass)
val myNewFunc = catalog.getFunction("db2", "func1").copy(className = newFuncClass)
catalog.alterFunction("db2", myNewFunc)
assert(catalog.getFunction("db2", "func1").className == newFuncClass)
}
test("list functions") {
val catalog = newBasicCatalog()
catalog.createFunction("db2", newFunc("func2"))
catalog.createFunction("db2", newFunc("not_me"))
assert(catalog.listFunctions("db2", "*").toSet == Set("func1", "func2", "not_me"))
assert(catalog.listFunctions("db2", "func*").toSet == Set("func1", "func2"))
}
// --------------------------------------------------------------------------
// File System operations
// --------------------------------------------------------------------------
private def exists(uri: URI, children: String*): Boolean = {
val base = new Path(uri)
val finalPath = children.foldLeft(base) {
case (parent, child) => new Path(parent, child)
}
base.getFileSystem(new Configuration()).exists(finalPath)
}
test("create/drop database should create/delete the directory") {
val catalog = newBasicCatalog()
val db = newDb("mydb")
catalog.createDatabase(db, ignoreIfExists = false)
assert(exists(db.locationUri))
catalog.dropDatabase("mydb", ignoreIfNotExists = false, cascade = false)
assert(!exists(db.locationUri))
}
test("create/drop/rename table should create/delete/rename the directory") {
val catalog = newBasicCatalog()
val db = catalog.getDatabase("db1")
val table = CatalogTable(
identifier = TableIdentifier("my_table", Some("db1")),
tableType = CatalogTableType.MANAGED,
storage = CatalogStorageFormat.empty,
schema = new StructType().add("a", "int").add("b", "string"),
provider = Some(defaultProvider)
)
catalog.createTable(table, ignoreIfExists = false)
assert(exists(db.locationUri, "my_table"))
catalog.renameTable("db1", "my_table", "your_table")
assert(!exists(db.locationUri, "my_table"))
assert(exists(db.locationUri, "your_table"))
catalog.dropTable("db1", "your_table", ignoreIfNotExists = false, purge = false)
assert(!exists(db.locationUri, "your_table"))
val externalTable = CatalogTable(
identifier = TableIdentifier("external_table", Some("db1")),
tableType = CatalogTableType.EXTERNAL,
storage = CatalogStorageFormat(
Some(Utils.createTempDir().toURI),
None, None, None, false, Map.empty),
schema = new StructType().add("a", "int").add("b", "string"),
provider = Some(defaultProvider)
)
catalog.createTable(externalTable, ignoreIfExists = false)
assert(!exists(db.locationUri, "external_table"))
}
test("create/drop/rename partitions should create/delete/rename the directory") {
val catalog = newBasicCatalog()
val table = CatalogTable(
identifier = TableIdentifier("tbl", Some("db1")),
tableType = CatalogTableType.MANAGED,
storage = CatalogStorageFormat.empty,
schema = new StructType()
.add("col1", "int")
.add("col2", "string")
.add("partCol1", "int")
.add("partCol2", "string"),
provider = Some(defaultProvider),
partitionColumnNames = Seq("partCol1", "partCol2"))
catalog.createTable(table, ignoreIfExists = false)
val tableLocation = catalog.getTable("db1", "tbl").location
val part1 = CatalogTablePartition(Map("partCol1" -> "1", "partCol2" -> "2"), storageFormat)
val part2 = CatalogTablePartition(Map("partCol1" -> "3", "partCol2" -> "4"), storageFormat)
val part3 = CatalogTablePartition(Map("partCol1" -> "5", "partCol2" -> "6"), storageFormat)
catalog.createPartitions("db1", "tbl", Seq(part1, part2), ignoreIfExists = false)
assert(exists(tableLocation, "partCol1=1", "partCol2=2"))
assert(exists(tableLocation, "partCol1=3", "partCol2=4"))
catalog.renamePartitions("db1", "tbl", Seq(part1.spec), Seq(part3.spec))
assert(!exists(tableLocation, "partCol1=1", "partCol2=2"))
assert(exists(tableLocation, "partCol1=5", "partCol2=6"))
catalog.dropPartitions("db1", "tbl", Seq(part2.spec, part3.spec), ignoreIfNotExists = false,
purge = false, retainData = false)
assert(!exists(tableLocation, "partCol1=3", "partCol2=4"))
assert(!exists(tableLocation, "partCol1=5", "partCol2=6"))
val tempPath = Utils.createTempDir()
// create partition with existing directory is OK.
val partWithExistingDir = CatalogTablePartition(
Map("partCol1" -> "7", "partCol2" -> "8"),
CatalogStorageFormat(
Some(tempPath.toURI),
None, None, None, false, Map.empty))
catalog.createPartitions("db1", "tbl", Seq(partWithExistingDir), ignoreIfExists = false)
tempPath.delete()
// create partition with non-existing directory will create that directory.
val partWithNonExistingDir = CatalogTablePartition(
Map("partCol1" -> "9", "partCol2" -> "10"),
CatalogStorageFormat(
Some(tempPath.toURI),
None, None, None, false, Map.empty))
catalog.createPartitions("db1", "tbl", Seq(partWithNonExistingDir), ignoreIfExists = false)
assert(tempPath.exists())
}
test("drop partition from external table should not delete the directory") {
val catalog = newBasicCatalog()
catalog.createPartitions("db2", "tbl1", Seq(part1), ignoreIfExists = false)
val partPath = new Path(catalog.getPartition("db2", "tbl1", part1.spec).location)
val fs = partPath.getFileSystem(new Configuration)
assert(fs.exists(partPath))
catalog.dropPartitions(
"db2", "tbl1", Seq(part1.spec), ignoreIfNotExists = false, purge = false, retainData = false)
assert(fs.exists(partPath))
}
}
/**
* A collection of utility fields and methods for tests related to the [[ExternalCatalog]].
*/
abstract class CatalogTestUtils {
// Unimplemented methods
val tableInputFormat: String
val tableOutputFormat: String
val defaultProvider: String
def newEmptyCatalog(): ExternalCatalog
// These fields must be lazy because they rely on fields that are not implemented yet
lazy val storageFormat = CatalogStorageFormat(
locationUri = None,
inputFormat = Some(tableInputFormat),
outputFormat = Some(tableOutputFormat),
serde = None,
compressed = false,
properties = Map.empty)
lazy val part1 = CatalogTablePartition(Map("a" -> "1", "b" -> "2"), storageFormat)
lazy val part2 = CatalogTablePartition(Map("a" -> "3", "b" -> "4"), storageFormat)
lazy val part3 = CatalogTablePartition(Map("a" -> "5", "b" -> "6"), storageFormat)
lazy val partWithMixedOrder = CatalogTablePartition(Map("b" -> "6", "a" -> "6"), storageFormat)
lazy val partWithLessColumns = CatalogTablePartition(Map("a" -> "1"), storageFormat)
lazy val partWithMoreColumns =
CatalogTablePartition(Map("a" -> "5", "b" -> "6", "c" -> "7"), storageFormat)
lazy val partWithUnknownColumns =
CatalogTablePartition(Map("a" -> "5", "unknown" -> "6"), storageFormat)
lazy val partWithEmptyValue =
CatalogTablePartition(Map("a" -> "3", "b" -> ""), storageFormat)
lazy val funcClass = "org.apache.spark.myFunc"
lazy val newFuncClass = "org.apache.spark.myNewFunc"
/**
* Creates a basic catalog, with the following structure:
*
* default
* db1
* db2
* - tbl1
* - tbl2
* - part1
* - part2
* - func1
* db3
* - view1
*/
def newBasicCatalog(): ExternalCatalog = {
val catalog = newEmptyCatalog()
// When testing against a real catalog, the default database may already exist
catalog.createDatabase(newDb("default"), ignoreIfExists = true)
catalog.createDatabase(newDb("db1"), ignoreIfExists = false)
catalog.createDatabase(newDb("db2"), ignoreIfExists = false)
catalog.createDatabase(newDb("db3"), ignoreIfExists = false)
catalog.createTable(newTable("tbl1", "db2"), ignoreIfExists = false)
catalog.createTable(newTable("tbl2", "db2"), ignoreIfExists = false)
catalog.createPartitions("db2", "tbl2", Seq(part1, part2), ignoreIfExists = false)
catalog.createFunction("db2", newFunc("func1", Some("db2")))
catalog
}
def newFunc(): CatalogFunction = newFunc("funcName")
def newUriForDatabase(): URI = new URI(Utils.createTempDir().toURI.toString.stripSuffix("/"))
def newDb(name: String): CatalogDatabase = {
CatalogDatabase(name, name + " description", newUriForDatabase(), Map.empty)
}
def newTable(name: String, db: String): CatalogTable = newTable(name, Some(db))
def newTable(name: String, database: Option[String] = None): CatalogTable = {
CatalogTable(
identifier = TableIdentifier(name, database),
tableType = CatalogTableType.EXTERNAL,
storage = storageFormat.copy(locationUri = Some(Utils.createTempDir().toURI)),
schema = new StructType()
.add("col1", "int")
.add("col2", "string")
.add("a", "int")
.add("b", "string"),
provider = Some(defaultProvider),
partitionColumnNames = Seq("a", "b"),
bucketSpec = Some(BucketSpec(4, Seq("col1"), Nil)))
}
def newView(
db: String,
name: String,
props: Map[String, String]): CatalogTable = {
CatalogTable(
identifier = TableIdentifier(name, Some(db)),
tableType = CatalogTableType.VIEW,
storage = CatalogStorageFormat.empty,
schema = new StructType()
.add("col1", "int")
.add("col2", "string")
.add("a", "int")
.add("b", "string"),
viewText = Some("SELECT * FROM tbl1"),
properties = props)
}
def newFunc(name: String, database: Option[String] = None): CatalogFunction = {
CatalogFunction(FunctionIdentifier(name, database), funcClass, Seq.empty[FunctionResource])
}
/**
* Whether the catalog's table partitions equal the ones given.
* Note: Hive sets some random serde things, so we just compare the specs here.
*/
def catalogPartitionsEqual(
catalog: ExternalCatalog,
db: String,
table: String,
parts: Seq[CatalogTablePartition]): Boolean = {
catalog.listPartitions(db, table).map(_.spec).toSet == parts.map(_.spec).toSet
}
}
| jkbradley/spark | sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/catalog/ExternalCatalogSuite.scala | Scala | apache-2.0 | 41,868 |
/*
* 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.util.{Locale, Properties}
import scala.collection.JavaConverters._
import org.apache.spark.annotation.Stable
import org.apache.spark.sql.catalyst.TableIdentifier
import org.apache.spark.sql.catalyst.analysis.{EliminateSubqueryAliases, NoSuchTableException, UnresolvedRelation}
import org.apache.spark.sql.catalyst.catalog._
import org.apache.spark.sql.catalyst.expressions.Literal
import org.apache.spark.sql.catalyst.plans.logical.{AppendData, CreateTableAsSelect, LogicalPlan, OverwriteByExpression, OverwritePartitionsDynamic, ReplaceTableAsSelect}
import org.apache.spark.sql.catalyst.plans.logical.sql.InsertIntoStatement
import org.apache.spark.sql.catalyst.util.CaseInsensitiveMap
import org.apache.spark.sql.connector.catalog.{CatalogPlugin, Identifier, SupportsWrite, TableCatalog, TableProvider, V1Table}
import org.apache.spark.sql.connector.catalog.TableCapability._
import org.apache.spark.sql.connector.expressions.{BucketTransform, FieldReference, IdentityTransform, LiteralValue, Transform}
import org.apache.spark.sql.execution.SQLExecution
import org.apache.spark.sql.execution.command.DDLUtils
import org.apache.spark.sql.execution.datasources.{CreateTable, DataSource, DataSourceUtils, LogicalRelation}
import org.apache.spark.sql.execution.datasources.v2._
import org.apache.spark.sql.internal.SQLConf.PartitionOverwriteMode
import org.apache.spark.sql.sources.BaseRelation
import org.apache.spark.sql.types.{IntegerType, StructType}
import org.apache.spark.sql.util.CaseInsensitiveStringMap
/**
* Interface used to write a [[Dataset]] to external storage systems (e.g. file systems,
* key-value stores, etc). Use `Dataset.write` to access this.
*
* @since 1.4.0
*/
@Stable
final class DataFrameWriter[T] private[sql](ds: Dataset[T]) {
private val df = ds.toDF()
/**
* Specifies the behavior when data or table already exists. Options include:
* <ul>
* <li>`SaveMode.Overwrite`: overwrite the existing data.</li>
* <li>`SaveMode.Append`: append the data.</li>
* <li>`SaveMode.Ignore`: ignore the operation (i.e. no-op).</li>
* <li>`SaveMode.ErrorIfExists`: throw an exception at runtime.</li>
* </ul>
* <p>
* When writing to data source v1, the default option is `ErrorIfExists`. When writing to data
* source v2, the default option is `Append`.
*
* @since 1.4.0
*/
def mode(saveMode: SaveMode): DataFrameWriter[T] = {
this.mode = saveMode
this
}
/**
* Specifies the behavior when data or table already exists. Options include:
* <ul>
* <li>`overwrite`: overwrite the existing data.</li>
* <li>`append`: append the data.</li>
* <li>`ignore`: ignore the operation (i.e. no-op).</li>
* <li>`error` or `errorifexists`: default option, throw an exception at runtime.</li>
* </ul>
*
* @since 1.4.0
*/
def mode(saveMode: String): DataFrameWriter[T] = {
saveMode.toLowerCase(Locale.ROOT) match {
case "overwrite" => mode(SaveMode.Overwrite)
case "append" => mode(SaveMode.Append)
case "ignore" => mode(SaveMode.Ignore)
case "error" | "errorifexists" => mode(SaveMode.ErrorIfExists)
case "default" => this
case _ => throw new IllegalArgumentException(s"Unknown save mode: $saveMode. " +
"Accepted save modes are 'overwrite', 'append', 'ignore', 'error', 'errorifexists'.")
}
}
/**
* Specifies the underlying output data source. Built-in options include "parquet", "json", etc.
*
* @since 1.4.0
*/
def format(source: String): DataFrameWriter[T] = {
this.source = source
this
}
/**
* Adds an output option for the underlying data source.
*
* You can set the following option(s):
* <ul>
* <li>`timeZone` (default session local timezone): sets the string that indicates a timezone
* to be used to format timestamps in the JSON/CSV datasources or partition values.</li>
* </ul>
*
* @since 1.4.0
*/
def option(key: String, value: String): DataFrameWriter[T] = {
this.extraOptions += (key -> value)
this
}
/**
* Adds an output option for the underlying data source.
*
* @since 2.0.0
*/
def option(key: String, value: Boolean): DataFrameWriter[T] = option(key, value.toString)
/**
* Adds an output option for the underlying data source.
*
* @since 2.0.0
*/
def option(key: String, value: Long): DataFrameWriter[T] = option(key, value.toString)
/**
* Adds an output option for the underlying data source.
*
* @since 2.0.0
*/
def option(key: String, value: Double): DataFrameWriter[T] = option(key, value.toString)
/**
* (Scala-specific) Adds output options for the underlying data source.
*
* You can set the following option(s):
* <ul>
* <li>`timeZone` (default session local timezone): sets the string that indicates a timezone
* to be used to format timestamps in the JSON/CSV datasources or partition values.</li>
* </ul>
*
* @since 1.4.0
*/
def options(options: scala.collection.Map[String, String]): DataFrameWriter[T] = {
this.extraOptions ++= options
this
}
/**
* Adds output options for the underlying data source.
*
* You can set the following option(s):
* <ul>
* <li>`timeZone` (default session local timezone): sets the string that indicates a timezone
* to be used to format timestamps in the JSON/CSV datasources or partition values.</li>
* </ul>
*
* @since 1.4.0
*/
def options(options: java.util.Map[String, String]): DataFrameWriter[T] = {
this.options(options.asScala)
this
}
/**
* Partitions the output by the given columns on the file system. If specified, the output is
* laid out on the file system similar to Hive's partitioning scheme. As an example, when we
* partition a dataset by year and then month, the directory layout would look like:
* <ul>
* <li>year=2016/month=01/</li>
* <li>year=2016/month=02/</li>
* </ul>
*
* Partitioning is one of the most widely used techniques to optimize physical data layout.
* It provides a coarse-grained index for skipping unnecessary data reads when queries have
* predicates on the partitioned columns. In order for partitioning to work well, the number
* of distinct values in each column should typically be less than tens of thousands.
*
* This is applicable for all file-based data sources (e.g. Parquet, JSON) starting with Spark
* 2.1.0.
*
* @since 1.4.0
*/
@scala.annotation.varargs
def partitionBy(colNames: String*): DataFrameWriter[T] = {
this.partitioningColumns = Option(colNames)
this
}
/**
* Buckets the output by the given columns. If specified, the output is laid out on the file
* system similar to Hive's bucketing scheme.
*
* This is applicable for all file-based data sources (e.g. Parquet, JSON) starting with Spark
* 2.1.0.
*
* @since 2.0
*/
@scala.annotation.varargs
def bucketBy(numBuckets: Int, colName: String, colNames: String*): DataFrameWriter[T] = {
this.numBuckets = Option(numBuckets)
this.bucketColumnNames = Option(colName +: colNames)
this
}
/**
* Sorts the output in each bucket by the given columns.
*
* This is applicable for all file-based data sources (e.g. Parquet, JSON) starting with Spark
* 2.1.0.
*
* @since 2.0
*/
@scala.annotation.varargs
def sortBy(colName: String, colNames: String*): DataFrameWriter[T] = {
this.sortColumnNames = Option(colName +: colNames)
this
}
/**
* Saves the content of the `DataFrame` at the specified path.
*
* @since 1.4.0
*/
def save(path: String): Unit = {
this.extraOptions += ("path" -> path)
save()
}
/**
* Saves the content of the `DataFrame` as the specified table.
*
* @since 1.4.0
*/
def save(): Unit = {
if (source.toLowerCase(Locale.ROOT) == DDLUtils.HIVE_PROVIDER) {
throw new AnalysisException("Hive data source can only be used with tables, you can not " +
"write files of Hive data source directly.")
}
assertNotBucketed("save")
val maybeV2Provider = lookupV2Provider()
if (maybeV2Provider.isDefined) {
val provider = maybeV2Provider.get
val sessionOptions = DataSourceV2Utils.extractSessionConfigs(
provider, df.sparkSession.sessionState.conf)
val options = sessionOptions ++ extraOptions
val dsOptions = new CaseInsensitiveStringMap(options.asJava)
import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Implicits._
provider.getTable(dsOptions) match {
case table: SupportsWrite if table.supports(BATCH_WRITE) =>
if (partitioningColumns.nonEmpty) {
throw new AnalysisException("Cannot write data to TableProvider implementation " +
"if partition columns are specified.")
}
lazy val relation = DataSourceV2Relation.create(table, dsOptions)
mode match {
case SaveMode.Append =>
runCommand(df.sparkSession, "save") {
AppendData.byName(relation, df.logicalPlan, extraOptions.toMap)
}
case SaveMode.Overwrite if table.supportsAny(TRUNCATE, OVERWRITE_BY_FILTER) =>
// truncate the table
runCommand(df.sparkSession, "save") {
OverwriteByExpression.byName(
relation, df.logicalPlan, Literal(true), extraOptions.toMap)
}
case other =>
throw new AnalysisException(s"TableProvider implementation $source cannot be " +
s"written with $other mode, please use Append or Overwrite " +
"modes instead.")
}
// Streaming also uses the data source V2 API. So it may be that the data source implements
// v2, but has no v2 implementation for batch writes. In that case, we fall back to saving
// as though it's a V1 source.
case _ => saveToV1Source()
}
} else {
saveToV1Source()
}
}
private def saveToV1Source(): Unit = {
partitioningColumns.foreach { columns =>
extraOptions += (DataSourceUtils.PARTITIONING_COLUMNS_KEY ->
DataSourceUtils.encodePartitioningColumns(columns))
}
// Code path for data source v1.
runCommand(df.sparkSession, "save") {
DataSource(
sparkSession = df.sparkSession,
className = source,
partitionColumns = partitioningColumns.getOrElse(Nil),
options = extraOptions.toMap).planForWriting(mode, df.logicalPlan)
}
}
/**
* Inserts the content of the `DataFrame` to the specified table. It requires that
* the schema of the `DataFrame` is the same as the schema of the table.
*
* @note Unlike `saveAsTable`, `insertInto` ignores the column names and just uses position-based
* resolution. For example:
*
* @note SaveMode.ErrorIfExists and SaveMode.Ignore behave as SaveMode.Append in `insertInto` as
* `insertInto` is not a table creating operation.
*
* {{{
* scala> Seq((1, 2)).toDF("i", "j").write.mode("overwrite").saveAsTable("t1")
* scala> Seq((3, 4)).toDF("j", "i").write.insertInto("t1")
* scala> Seq((5, 6)).toDF("a", "b").write.insertInto("t1")
* scala> sql("select * from t1").show
* +---+---+
* | i| j|
* +---+---+
* | 5| 6|
* | 3| 4|
* | 1| 2|
* +---+---+
* }}}
*
* Because it inserts data to an existing table, format or options will be ignored.
*
* @since 1.4.0
*/
def insertInto(tableName: String): Unit = {
import df.sparkSession.sessionState.analyzer.{AsTableIdentifier, CatalogObjectIdentifier}
import org.apache.spark.sql.connector.catalog.CatalogV2Implicits._
assertNotBucketed("insertInto")
if (partitioningColumns.isDefined) {
throw new AnalysisException(
"insertInto() can't be used together with partitionBy(). " +
"Partition columns have already been defined for the table. " +
"It is not necessary to use partitionBy()."
)
}
val session = df.sparkSession
val canUseV2 = lookupV2Provider().isDefined
val sessionCatalog = session.sessionState.analyzer.sessionCatalog
session.sessionState.sqlParser.parseMultipartIdentifier(tableName) match {
case CatalogObjectIdentifier(Some(catalog), ident) =>
insertInto(catalog, ident)
case CatalogObjectIdentifier(None, ident) if canUseV2 && ident.namespace().length <= 1 =>
insertInto(sessionCatalog, ident)
case AsTableIdentifier(tableIdentifier) =>
insertInto(tableIdentifier)
case other =>
throw new AnalysisException(
s"Couldn't find a catalog to handle the identifier ${other.quoted}.")
}
}
private def insertInto(catalog: CatalogPlugin, ident: Identifier): Unit = {
import org.apache.spark.sql.connector.catalog.CatalogV2Implicits._
val table = catalog.asTableCatalog.loadTable(ident) match {
case _: V1Table =>
return insertInto(TableIdentifier(ident.name(), ident.namespace().headOption))
case t =>
DataSourceV2Relation.create(t)
}
val command = mode match {
case SaveMode.Append | SaveMode.ErrorIfExists | SaveMode.Ignore =>
AppendData.byPosition(table, df.logicalPlan, extraOptions.toMap)
case SaveMode.Overwrite =>
val conf = df.sparkSession.sessionState.conf
val dynamicPartitionOverwrite = table.table.partitioning.size > 0 &&
conf.partitionOverwriteMode == PartitionOverwriteMode.DYNAMIC
if (dynamicPartitionOverwrite) {
OverwritePartitionsDynamic.byPosition(table, df.logicalPlan, extraOptions.toMap)
} else {
OverwriteByExpression.byPosition(table, df.logicalPlan, Literal(true), extraOptions.toMap)
}
}
runCommand(df.sparkSession, "insertInto") {
command
}
}
private def insertInto(tableIdent: TableIdentifier): Unit = {
runCommand(df.sparkSession, "insertInto") {
InsertIntoStatement(
table = UnresolvedRelation(tableIdent),
partitionSpec = Map.empty[String, Option[String]],
query = df.logicalPlan,
overwrite = mode == SaveMode.Overwrite,
ifPartitionNotExists = false)
}
}
private def getBucketSpec: Option[BucketSpec] = {
if (sortColumnNames.isDefined && numBuckets.isEmpty) {
throw new AnalysisException("sortBy must be used together with bucketBy")
}
numBuckets.map { n =>
BucketSpec(n, bucketColumnNames.get, sortColumnNames.getOrElse(Nil))
}
}
private def assertNotBucketed(operation: String): Unit = {
if (getBucketSpec.isDefined) {
if (sortColumnNames.isEmpty) {
throw new AnalysisException(s"'$operation' does not support bucketBy right now")
} else {
throw new AnalysisException(s"'$operation' does not support bucketBy and sortBy right now")
}
}
}
private def assertNotPartitioned(operation: String): Unit = {
if (partitioningColumns.isDefined) {
throw new AnalysisException(s"'$operation' does not support partitioning")
}
}
/**
* Saves the content of the `DataFrame` as the specified table.
*
* In the case the table already exists, behavior of this function depends on the
* save mode, specified by the `mode` function (default to throwing an exception).
* When `mode` is `Overwrite`, the schema of the `DataFrame` does not need to be
* the same as that of the existing table.
*
* When `mode` is `Append`, if there is an existing table, we will use the format and options of
* the existing table. The column order in the schema of the `DataFrame` doesn't need to be same
* as that of the existing table. Unlike `insertInto`, `saveAsTable` will use the column names to
* find the correct column positions. For example:
*
* {{{
* scala> Seq((1, 2)).toDF("i", "j").write.mode("overwrite").saveAsTable("t1")
* scala> Seq((3, 4)).toDF("j", "i").write.mode("append").saveAsTable("t1")
* scala> sql("select * from t1").show
* +---+---+
* | i| j|
* +---+---+
* | 1| 2|
* | 4| 3|
* +---+---+
* }}}
*
* In this method, save mode is used to determine the behavior if the data source table exists in
* Spark catalog. We will always overwrite the underlying data of data source (e.g. a table in
* JDBC data source) if the table doesn't exist in Spark catalog, and will always append to the
* underlying data of data source if the table already exists.
*
* When the DataFrame is created from a non-partitioned `HadoopFsRelation` with a single input
* path, and the data source provider can be mapped to an existing Hive builtin SerDe (i.e. ORC
* and Parquet), the table is persisted in a Hive compatible format, which means other systems
* like Hive will be able to read this table. Otherwise, the table is persisted in a Spark SQL
* specific format.
*
* @since 1.4.0
*/
def saveAsTable(tableName: String): Unit = {
import df.sparkSession.sessionState.analyzer.{AsTableIdentifier, CatalogObjectIdentifier}
import org.apache.spark.sql.connector.catalog.CatalogV2Implicits._
val session = df.sparkSession
val canUseV2 = lookupV2Provider().isDefined
val sessionCatalog = session.sessionState.analyzer.sessionCatalog
session.sessionState.sqlParser.parseMultipartIdentifier(tableName) match {
case CatalogObjectIdentifier(Some(catalog), ident) =>
saveAsTable(catalog.asTableCatalog, ident)
case CatalogObjectIdentifier(None, ident) if canUseV2 && ident.namespace().length <= 1 =>
saveAsTable(sessionCatalog.asTableCatalog, ident)
case AsTableIdentifier(tableIdentifier) =>
saveAsTable(tableIdentifier)
case other =>
throw new AnalysisException(
s"Couldn't find a catalog to handle the identifier ${other.quoted}.")
}
}
private def saveAsTable(catalog: TableCatalog, ident: Identifier): Unit = {
val partitioning = partitioningColumns.map { colNames =>
colNames.map(name => IdentityTransform(FieldReference(name)))
}.getOrElse(Seq.empty[Transform])
val bucketing = bucketColumnNames.map { cols =>
Seq(BucketTransform(LiteralValue(numBuckets.get, IntegerType), cols.map(FieldReference(_))))
}.getOrElse(Seq.empty[Transform])
val partitionTransforms = partitioning ++ bucketing
val tableOpt = try Option(catalog.loadTable(ident)) catch {
case _: NoSuchTableException => None
}
def getLocationIfExists: Option[(String, String)] = {
val opts = CaseInsensitiveMap(extraOptions.toMap)
opts.get("path").map("location" -> _)
}
val command = (mode, tableOpt) match {
case (_, Some(table: V1Table)) =>
return saveAsTable(TableIdentifier(ident.name(), ident.namespace().headOption))
case (SaveMode.Append, Some(table)) =>
AppendData.byName(DataSourceV2Relation.create(table), df.logicalPlan)
case (SaveMode.Overwrite, _) =>
ReplaceTableAsSelect(
catalog,
ident,
partitionTransforms,
df.queryExecution.analyzed,
Map("provider" -> source) ++ getLocationIfExists,
extraOptions.toMap,
orCreate = true) // Create the table if it doesn't exist
case (other, _) =>
// We have a potential race condition here in AppendMode, if the table suddenly gets
// created between our existence check and physical execution, but this can't be helped
// in any case.
CreateTableAsSelect(
catalog,
ident,
partitionTransforms,
df.queryExecution.analyzed,
Map("provider" -> source) ++ getLocationIfExists,
extraOptions.toMap,
ignoreIfExists = other == SaveMode.Ignore)
}
runCommand(df.sparkSession, "saveAsTable") {
command
}
}
private def saveAsTable(tableIdent: TableIdentifier): Unit = {
val catalog = df.sparkSession.sessionState.catalog
val tableExists = catalog.tableExists(tableIdent)
val db = tableIdent.database.getOrElse(catalog.getCurrentDatabase)
val tableIdentWithDB = tableIdent.copy(database = Some(db))
val tableName = tableIdentWithDB.unquotedString
(tableExists, mode) match {
case (true, SaveMode.Ignore) =>
// Do nothing
case (true, SaveMode.ErrorIfExists) =>
throw new AnalysisException(s"Table $tableIdent already exists.")
case (true, SaveMode.Overwrite) =>
// Get all input data source or hive relations of the query.
val srcRelations = df.logicalPlan.collect {
case LogicalRelation(src: BaseRelation, _, _, _) => src
case relation: HiveTableRelation => relation.tableMeta.identifier
}
val tableRelation = df.sparkSession.table(tableIdentWithDB).queryExecution.analyzed
EliminateSubqueryAliases(tableRelation) match {
// check if the table is a data source table (the relation is a BaseRelation).
case LogicalRelation(dest: BaseRelation, _, _, _) if srcRelations.contains(dest) =>
throw new AnalysisException(
s"Cannot overwrite table $tableName that is also being read from")
// check hive table relation when overwrite mode
case relation: HiveTableRelation
if srcRelations.contains(relation.tableMeta.identifier) =>
throw new AnalysisException(
s"Cannot overwrite table $tableName that is also being read from")
case _ => // OK
}
// Drop the existing table
catalog.dropTable(tableIdentWithDB, ignoreIfNotExists = true, purge = false)
createTable(tableIdentWithDB)
// Refresh the cache of the table in the catalog.
catalog.refreshTable(tableIdentWithDB)
case _ => createTable(tableIdent)
}
}
private def createTable(tableIdent: TableIdentifier): Unit = {
val storage = DataSource.buildStorageFormatFromOptions(extraOptions.toMap)
val tableType = if (storage.locationUri.isDefined) {
CatalogTableType.EXTERNAL
} else {
CatalogTableType.MANAGED
}
val tableDesc = CatalogTable(
identifier = tableIdent,
tableType = tableType,
storage = storage,
schema = new StructType,
provider = Some(source),
partitionColumnNames = partitioningColumns.getOrElse(Nil),
bucketSpec = getBucketSpec)
runCommand(df.sparkSession, "saveAsTable")(
CreateTable(tableDesc, mode, Some(df.logicalPlan)))
}
/**
* Saves the content of the `DataFrame` to an external database table via JDBC. In the case the
* table already exists in the external database, behavior of this function depends on the
* save mode, specified by the `mode` function (default to throwing an exception).
*
* Don't create too many partitions in parallel on a large cluster; otherwise Spark might crash
* your external database systems.
*
* You can set the following JDBC-specific option(s) for storing JDBC:
* <ul>
* <li>`truncate` (default `false`): use `TRUNCATE TABLE` instead of `DROP TABLE`.</li>
* </ul>
*
* In case of failures, users should turn off `truncate` option to use `DROP TABLE` again. Also,
* due to the different behavior of `TRUNCATE TABLE` among DBMS, it's not always safe to use this.
* MySQLDialect, DB2Dialect, MsSqlServerDialect, DerbyDialect, and OracleDialect supports this
* while PostgresDialect and default JDBCDirect doesn't. For unknown and unsupported JDBCDirect,
* the user option `truncate` is ignored.
*
* @param url JDBC database url of the form `jdbc:subprotocol:subname`
* @param table Name of the table in the external database.
* @param connectionProperties JDBC database connection arguments, a list of arbitrary string
* tag/value. Normally at least a "user" and "password" property
* should be included. "batchsize" can be used to control the
* number of rows per insert. "isolationLevel" can be one of
* "NONE", "READ_COMMITTED", "READ_UNCOMMITTED", "REPEATABLE_READ",
* or "SERIALIZABLE", corresponding to standard transaction
* isolation levels defined by JDBC's Connection object, with default
* of "READ_UNCOMMITTED".
* @since 1.4.0
*/
def jdbc(url: String, table: String, connectionProperties: Properties): Unit = {
assertNotPartitioned("jdbc")
assertNotBucketed("jdbc")
// connectionProperties should override settings in extraOptions.
this.extraOptions ++= connectionProperties.asScala
// explicit url and dbtable should override all
this.extraOptions += ("url" -> url, "dbtable" -> table)
format("jdbc").save()
}
/**
* Saves the content of the `DataFrame` in JSON format (<a href="http://jsonlines.org/">
* JSON Lines text format or newline-delimited JSON</a>) at the specified path.
* This is equivalent to:
* {{{
* format("json").save(path)
* }}}
*
* You can set the following JSON-specific option(s) for writing JSON files:
* <ul>
* <li>`compression` (default `null`): compression codec to use when saving to file. This can be
* one of the known case-insensitive shorten names (`none`, `bzip2`, `gzip`, `lz4`,
* `snappy` and `deflate`). </li>
* <li>`dateFormat` (default `uuuu-MM-dd`): sets the string that indicates a date format.
* Custom date formats follow the formats at `java.time.format.DateTimeFormatter`.
* This applies to date type.</li>
* <li>`timestampFormat` (default `uuuu-MM-dd'T'HH:mm:ss.SSSXXX`): sets the string that
* indicates a timestamp format. Custom date formats follow the formats at
* `java.time.format.DateTimeFormatter`. This applies to timestamp type.</li>
* <li>`encoding` (by default it is not set): specifies encoding (charset) of saved json
* files. If it is not set, the UTF-8 charset will be used. </li>
* <li>`lineSep` (default `\\n`): defines the line separator that should be used for writing.</li>
* </ul>
*
* @since 1.4.0
*/
def json(path: String): Unit = {
format("json").save(path)
}
/**
* Saves the content of the `DataFrame` in Parquet format at the specified path.
* This is equivalent to:
* {{{
* format("parquet").save(path)
* }}}
*
* You can set the following Parquet-specific option(s) for writing Parquet files:
* <ul>
* <li>`compression` (default is the value specified in `spark.sql.parquet.compression.codec`):
* compression codec to use when saving to file. This can be one of the known case-insensitive
* shorten names(`none`, `uncompressed`, `snappy`, `gzip`, `lzo`, `brotli`, `lz4`, and `zstd`).
* This will override `spark.sql.parquet.compression.codec`.</li>
* </ul>
*
* @since 1.4.0
*/
def parquet(path: String): Unit = {
format("parquet").save(path)
}
/**
* Saves the content of the `DataFrame` in ORC format at the specified path.
* This is equivalent to:
* {{{
* format("orc").save(path)
* }}}
*
* You can set the following ORC-specific option(s) for writing ORC files:
* <ul>
* <li>`compression` (default is the value specified in `spark.sql.orc.compression.codec`):
* compression codec to use when saving to file. This can be one of the known case-insensitive
* shorten names(`none`, `snappy`, `zlib`, and `lzo`). This will override
* `orc.compress` and `spark.sql.orc.compression.codec`. If `orc.compress` is given,
* it overrides `spark.sql.orc.compression.codec`.</li>
* </ul>
*
* @since 1.5.0
*/
def orc(path: String): Unit = {
format("orc").save(path)
}
/**
* Saves the content of the `DataFrame` in a text file at the specified path.
* The DataFrame must have only one column that is of string type.
* Each row becomes a new line in the output file. For example:
* {{{
* // Scala:
* df.write.text("/path/to/output")
*
* // Java:
* df.write().text("/path/to/output")
* }}}
* The text files will be encoded as UTF-8.
*
* You can set the following option(s) for writing text files:
* <ul>
* <li>`compression` (default `null`): compression codec to use when saving to file. This can be
* one of the known case-insensitive shorten names (`none`, `bzip2`, `gzip`, `lz4`,
* `snappy` and `deflate`). </li>
* <li>`lineSep` (default `\\n`): defines the line separator that should be used for writing.</li>
* </ul>
*
* @since 1.6.0
*/
def text(path: String): Unit = {
format("text").save(path)
}
/**
* Saves the content of the `DataFrame` in CSV format at the specified path.
* This is equivalent to:
* {{{
* format("csv").save(path)
* }}}
*
* You can set the following CSV-specific option(s) for writing CSV files:
* <ul>
* <li>`sep` (default `,`): sets a single character as a separator for each
* field and value.</li>
* <li>`quote` (default `"`): sets a single character used for escaping quoted values where
* the separator can be part of the value. If an empty string is set, it uses `u0000`
* (null character).</li>
* <li>`escape` (default `\\`): sets a single character used for escaping quotes inside
* an already quoted value.</li>
* <li>`charToEscapeQuoteEscaping` (default `escape` or `\\0`): sets a single character used for
* escaping the escape for the quote character. The default value is escape character when escape
* and quote characters are different, `\\0` otherwise.</li>
* <li>`escapeQuotes` (default `true`): a flag indicating whether values containing
* quotes should always be enclosed in quotes. Default is to escape all values containing
* a quote character.</li>
* <li>`quoteAll` (default `false`): a flag indicating whether all values should always be
* enclosed in quotes. Default is to only escape values containing a quote character.</li>
* <li>`header` (default `false`): writes the names of columns as the first line.</li>
* <li>`nullValue` (default empty string): sets the string representation of a null value.</li>
* <li>`emptyValue` (default `""`): sets the string representation of an empty value.</li>
* <li>`encoding` (by default it is not set): specifies encoding (charset) of saved csv
* files. If it is not set, the UTF-8 charset will be used.</li>
* <li>`compression` (default `null`): compression codec to use when saving to file. This can be
* one of the known case-insensitive shorten names (`none`, `bzip2`, `gzip`, `lz4`,
* `snappy` and `deflate`). </li>
* <li>`dateFormat` (default `uuuu-MM-dd`): sets the string that indicates a date format.
* Custom date formats follow the formats at `java.time.format.DateTimeFormatter`.
* This applies to date type.</li>
* <li>`timestampFormat` (default `uuuu-MM-dd'T'HH:mm:ss.SSSXXX`): sets the string that
* indicates a timestamp format. Custom date formats follow the formats at
* `java.time.format.DateTimeFormatter`. This applies to timestamp type.</li>
* <li>`ignoreLeadingWhiteSpace` (default `true`): a flag indicating whether or not leading
* whitespaces from values being written should be skipped.</li>
* <li>`ignoreTrailingWhiteSpace` (default `true`): a flag indicating defines whether or not
* trailing whitespaces from values being written should be skipped.</li>
* <li>`lineSep` (default `\\n`): defines the line separator that should be used for writing.
* Maximum length is 1 character.</li>
* </ul>
*
* @since 2.0.0
*/
def csv(path: String): Unit = {
format("csv").save(path)
}
/**
* Wrap a DataFrameWriter action to track the QueryExecution and time cost, then report to the
* user-registered callback functions.
*/
private def runCommand(session: SparkSession, name: String)(command: LogicalPlan): Unit = {
val qe = session.sessionState.executePlan(command)
// call `QueryExecution.toRDD` to trigger the execution of commands.
SQLExecution.withNewExecutionId(session, qe, Some(name))(qe.toRdd)
}
private def lookupV2Provider(): Option[TableProvider] = {
DataSource.lookupDataSourceV2(source, df.sparkSession.sessionState.conf) match {
// TODO(SPARK-28396): File source v2 write path is currently broken.
case Some(_: FileDataSourceV2) => None
case other => other
}
}
///////////////////////////////////////////////////////////////////////////////////////
// Builder pattern config options
///////////////////////////////////////////////////////////////////////////////////////
private var source: String = df.sparkSession.sessionState.conf.defaultDataSourceName
private var mode: SaveMode = SaveMode.ErrorIfExists
private val extraOptions = new scala.collection.mutable.HashMap[String, String]
private var partitioningColumns: Option[Seq[String]] = None
private var bucketColumnNames: Option[Seq[String]] = None
private var numBuckets: Option[Int] = None
private var sortColumnNames: Option[Seq[String]] = None
}
| bdrillard/spark | sql/core/src/main/scala/org/apache/spark/sql/DataFrameWriter.scala | Scala | apache-2.0 | 34,164 |
/*
* Copyright 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 influxdbreporter.core
import com.codahale.metrics.Clock
import influxdbreporter.core.writers.Writer
import scala.concurrent.ExecutionContext
import scala.concurrent.duration.FiniteDuration
class InfluxdbReporter[S](registry: MetricRegistry,
writer: Writer[S],
clientFactory: MetricClientFactory[S],
interval: FiniteDuration,
batcher: Batcher[S] = new InfluxBatcher[S],
buffer: Option[WriterDataBuffer[S]] = None,
clock: Clock = Clock.defaultClock(),
name: Option[String] = None)
(implicit executionContext: ExecutionContext)
extends ScheduledReporter[S](registry, interval, writer, clientFactory, batcher, buffer, clock, name) {
def withInterval(newInterval: FiniteDuration): InfluxdbReporter[S] =
new InfluxdbReporter[S](registry, writer, clientFactory, newInterval, batcher, buffer, clock, name)
} | TouK/influxdb-reporter | core/src/main/scala/influxdbreporter/core/InfluxdbReporter.scala | Scala | apache-2.0 | 1,610 |
package scalan.collections
/**
* Author: Alexander Slesarenko
* Date: 1/26/13
*/
import scalan._
import scalan.common.OverloadHack.Overloaded1
trait BitSets { self: CollectionsDsl with BitSetsDsl =>
type BS = Rep[BitSet]
trait BitSet extends Def[BitSet] {
def bits: Rep[Collection[Boolean]]
def union(that: Rep[BitSet]) = {
val flags = (bits zip that.bits) map { case Pair(x,y) => x || y }
BitSet(flags)
}
def length: Rep[Int] = bits.length
def contains(n: Rep[Int]): Rep[Boolean] = bits(n)
def add(n: Rep[Int]): Rep[BitSet] = BitSet(bits.update(n, true))
@OverloadId("many")
def add(ns: Coll[Int])(implicit o: Overloaded1): Rep[BitSet] = BitSet(bits.updateMany(ns, Collection.replicate(ns.length, true)))
}
trait BitSetCompanion {
def apply(flags: Coll[Boolean]): Rep[BitSet] = BoolCollBitSet(flags)
@OverloadId("many")
def apply(flags: Rep[Array[Boolean]])(implicit o: Overloaded1): Rep[BitSet] =
BitSet(Collection.fromArray(flags))
def empty(range: Rep[Int]) = BitSet(Collection.replicate(range, false))
}
abstract class BoolCollBitSet(val bits: Rep[Collection[Boolean]]) extends BitSet {
}
trait BoolCollBitSetCompanion
}
| PCMNN/scalan-ce | collections/src/main/scala/scalan/collections/BitSets.scala | Scala | apache-2.0 | 1,214 |
package connectorFamily.connector
import org.junit.Test
import org.junit.Assert._
import OldExamples._
class TestOldConnector {
@Test def TestComposition() {
// all should type&check
def pp(c:Any) = println(c)
println("--- testing OLD connectors ---")
// examples from the paper
pp(lossy & fifo)
pp(lossy*id & xrd)
pp(swap & sdrain)
pp(lossy & xr)
// adding compact closed aspect (duals)
pp(lossy.inv*id & eps)
pp(eta*id & id*eps)
pp(eta &
(dupl & sync*fifof & sync*dupl & sync*sync*fifo) * sync.inv &
sync*sync*epsr)
pp(id.inv*eta &
(id.inv*dupl & eps*fifof & dupl & id*fifo) * id.inv &
id*epsr)
}
@Test def TestContexts() {
type Conn = OldConnector[SimpleRep]
type ConnCtx = OldConnectorCtx[SimpleRep]
val base = new Context(
(r:Conn) => eta & (dupl & id * fifof) * id.inv & id * r
)
val more = new Context(
(r:Conn) => (dupl & id*fifo) * id.inv & id * r
)
def seq(n:Int): ConnCtx = n match {
case 0 => base(epsr)
case _ => val prev = seq(n-1)
base(more(prev.hole))
}
assertEquals("Contexts match.",seq(3).ctx,base)
assertEquals("Expected seq_0",
"eta ; dupl ; id*fifof*id' ; id*epsr: ø -> 1",
seq(0).toString)
assertEquals("Expected seq_1",
"eta ; dupl ; id*fifof*id' ; id*dupl ; id*fifo*id' ; id*epsr: ø -> 2",
seq(1).toString)
assertEquals("Expected seq_2",
"eta ; dupl ; id*fifof*id' ; id*dupl ; id*fifo*id' ; id*dupl ; id*fifo*id' ; id*epsr: ø -> 3",
seq(2).toString)
}
@Test def TestBigConnector() {
type Conn = OldConnector[SimpleRep]
type ConnCtx = OldConnectorCtx[SimpleRep]
val syncMerge = //new Context(
(ab: Conn) =>
dupl &
(xr(3) &
dupl * dupl(3) * dupl &
id * mrg * id * mrg * id &
id * id * swap * id &
fifo * ab * fifo * fifo &
id * id * swap * id &
dupl * xr * dupl(3) * xr * dupl &
id * sdrain * sdrain * id * sdrain * sdrain * id &
mrg(3) &
dupl
) * fifo &
id * sdrain
// )
val lossyAB = syncMerge(lossy*lossy)
assertEquals("Type-checking sync merge.",
(lossyAB.from,lossyAB.to),
(Interface(1),Interface(1)))
}
} | joseproenca/connector-family | src/test/scala/connectorFamily/connector/TestOldConnector.scala | Scala | mit | 2,414 |
package org.hammerlab.bgzf.block
import org.hammerlab.bgzf.Pos
case class PosIterator(block: Long,
uncompressedSize: Int)
extends Iterator[Pos] {
var up = 0
override def hasNext: Boolean = up < uncompressedSize
override def next(): Pos = {
val pos = Pos(block, up)
up += 1
pos
}
}
object PosIterator {
implicit def apply(metadata: Metadata): PosIterator =
PosIterator(
metadata.start,
metadata.uncompressedSize
)
}
| ryan-williams/spark-bam | bgzf/src/main/scala/org/hammerlab/bgzf/block/PosIterator.scala | Scala | apache-2.0 | 485 |
package scalaprops
import scalaz._
import scalaz.std.anyVal._
import scalaz.std.function._
import ScalapropsScalaz._
object FreeApTest extends Scalaprops {
private[this] implicit def freeApEqual[F[_]: Functor, A](implicit
E: Eq1[F],
A: Equal[A]
): Equal[FreeAp[F, A]] =
FreeTest.freeEqual[F, A].contramap(_.monadic)
private[this] def freeApGen0[F[_]: Functor, A](implicit
G1: Gen[A],
G2: Gen[F[A]]
): Gen[FreeAp[F, A]] =
Gen.oneOf(
G1.map(FreeAp.pure),
G2.map(FreeAp.lift(_))
)
private[this] implicit def freeApGen[F[_]: Functor, A: Gen](implicit
G1: Gen[F[A]],
G2: Gen[F[Byte]],
G3: Gen[F[Byte => A]]
): Gen[FreeAp[F, A]] =
Gen.oneOf(
freeApGen0[F, A],
Apply[Gen].apply2(G2, freeApGen0[F, Byte => A])(FreeAp.apply[F, Byte, A](_, _))
)
val id = {
type F[A] = FreeAp[Id.Id, A]
Properties.list(
scalazlaws.equal.all[F[Byte]],
scalazlaws.applicative.all[F]
)
}
val maybe = {
type F[A] = FreeAp[Maybe, A]
Properties.list(
scalazlaws.equal.all[F[Byte]],
scalazlaws.applicative.all[F]
)
}
val iList = {
type F[A] = FreeAp[IList, A]
Properties.list(
scalazlaws.equal.all[F[Byte]],
scalazlaws.applicative.all[F]
)
}
val nel = {
type F[A] = FreeAp[NonEmptyList, A]
Properties.list(
scalazlaws.equal.all[F[Byte]],
scalazlaws.applicative.all[F]
)
}
val disjunction = {
type G[A] = Short \/ A
type F[A] = FreeAp[G, A]
Properties.list(
scalazlaws.equal.all[F[Byte]],
scalazlaws.applicative.all[F]
)
}
val function1 = {
type G[A] = Short => A
type F[A] = FreeAp[G, A]
Properties.list(
scalazlaws.equal.all[F[Byte]],
scalazlaws.applicative.laws[F], // exclude applyComposition law. because too slow
scalazlaws.functor.all[F]
)
}
val state = {
type G[A] = State[Short, A]
type F[A] = FreeAp[G, A]
Properties.list(
scalazlaws.equal.all[F[Byte]],
scalazlaws.applicative.laws[F], // exclude applyComposition law. because too slow
scalazlaws.functor.all[F]
)
}
val writer = {
type G[A] = Writer[Short, A]
type F[A] = FreeAp[G, A]
Properties.list(
scalazlaws.equal.all[F[Byte]],
scalazlaws.applicative.all[F]
)
}
val writerMaybe = {
type G[A] = WriterT[Short, Maybe, A]
type F[A] = FreeAp[G, A]
Properties.list(
scalazlaws.equal.all[F[Byte]],
scalazlaws.applicative.all[F]
)
}
val writerIList = {
type G[A] = WriterT[Short, IList, A]
type F[A] = FreeAp[G, A]
Properties.list(
scalazlaws.equal.all[F[Byte]],
scalazlaws.applicative.all[F]
)
}
}
| scalaprops/scalaprops | scalaz/src/test/scala/scalaprops/FreeApTest.scala | Scala | mit | 2,736 |
// -*- mode: Scala;-*-
// Filename: TheMessage.scala
// Authors: lgm
// Creation: Fri Oct 16 14:18:12 2009
// Copyright: Not supplied
// Description:
// ------------------------------------------------------------------------
package com.biosimilarity.lift.model.msg
import com.biosimilarity.lift.lib._
import com.biosimilarity.lift.lib.moniker._
import java.net.URI
import java.util.UUID
trait Header {
def msgId : UUID
//def to : URI
def to : Moniker
//def from : URI
def from : Moniker
def flowId : UUID
}
trait Message[Justfication,BodyType] {
def body : BodyType
def justification : Option[Justfication]
}
abstract class Request[Response,BodyType](
override val msgId : UUID,
//override val to : URI,
override val to : Moniker,
//override val from : URI,
override val from : Moniker,
override val flowId : UUID,
override val body : BodyType,
override val justification : Option[Response]
) extends Message[Response,BodyType] with Header
class AbstractJustifiedRequest[ReqBody,RspBody](
override val msgId : UUID,
//override val to : URI,
override val to : Moniker,
//override val from : URI,
override val from : Moniker,
override val flowId : UUID,
override val body : ReqBody,
override val justification : Option[Response[AbstractJustifiedRequest[ReqBody,RspBody],RspBody]]
) extends Request[Response[AbstractJustifiedRequest[ReqBody,RspBody],RspBody],ReqBody](
msgId, to, from, flowId, body, justification
)
object AbstractJustifiedRequest {
def apply[ReqBody,RspBody](
msgId : UUID,
//to : URI,
to : Moniker,
//from : URI,
from : Moniker,
flowId : UUID,
body : ReqBody,
justification : Option[Response[AbstractJustifiedRequest[ReqBody,RspBody],RspBody]]
)
: AbstractJustifiedRequest[ReqBody,RspBody] = {
new AbstractJustifiedRequest(
msgId, to, from, flowId, body, justification
)
}
def unapply[ReqBody,RspBody]( ajr : AbstractJustifiedRequest[ReqBody,RspBody] )
: //Option[(UUID,URI,URI,UUID,ReqBody,Option[Response[AbstractJustifiedRequest[ReqBody,RspBody],RspBody]])]
Option[(UUID,Moniker,Moniker,UUID,ReqBody,Option[Response[AbstractJustifiedRequest[ReqBody,RspBody],RspBody]])]
= {
Some(( ajr.msgId, ajr.to, ajr.from, ajr.flowId, ajr.body, ajr.justification ))
}
}
case class JustifiedRequest[ReqBody,RspBody](
override val msgId : UUID,
//override val to : URI,
override val to : Moniker,
//override val from : URI,
override val from : Moniker,
override val flowId : UUID,
override val body : ReqBody,
override val justification : Option[Response[AbstractJustifiedRequest[ReqBody,RspBody],RspBody]]
) extends AbstractJustifiedRequest[ReqBody,RspBody](
msgId, to, from, flowId, body, justification
)
case class URIJustifiedRequest[ReqBody](
override val msgId : UUID,
//override val to : URI,
override val to : Moniker,
//override val from : URI,
override val from : Moniker,
override val flowId : UUID,
override val body : ReqBody,
override val justification : Option[Response[AbstractJustifiedRequest[ReqBody,URI],URI]]
) extends AbstractJustifiedRequest[ReqBody,URI](
msgId, to, from, flowId, body, justification
)
abstract class Response[Request,BodyType](
override val msgId : UUID,
//override val to : URI,
override val to : Moniker,
//override val from : URI,
override val from : Moniker,
override val flowId : UUID,
override val body : BodyType,
override val justification : Option[Request]
) extends Message[Request,BodyType] with Header
class AbstractJustifiedResponse[ReqBody,RspBody](
override val msgId : UUID,
//override val to : URI,
override val to : Moniker,
//override val from : URI,
override val from : Moniker,
override val flowId : UUID,
override val body : RspBody,
override val justification : Option[Request[AbstractJustifiedResponse[ReqBody,RspBody],ReqBody]]
) extends Response[Request[AbstractJustifiedResponse[ReqBody,RspBody],ReqBody],RspBody](
msgId, to, from, flowId, body, justification
)
object AbstractJustifiedResponse {
def apply[ReqBody,RspBody](
msgId : UUID,
//to : URI,
to : Moniker,
//from : URI,
from : Moniker,
flowId : UUID,
body : RspBody,
justification : Option[Request[AbstractJustifiedResponse[ReqBody,RspBody],ReqBody]]
) : AbstractJustifiedResponse[ReqBody,RspBody] = {
new AbstractJustifiedResponse(
msgId, to, from, flowId, body, justification
)
}
def unapply[ReqBody,RspBody]( ajr : AbstractJustifiedResponse[ReqBody,RspBody] )
: //Option[(UUID,URI,URI,UUID,RspBody,Option[Request[AbstractJustifiedResponse[ReqBody,RspBody],ReqBody]])]
Option[(UUID,Moniker,Moniker,UUID,RspBody,Option[Request[AbstractJustifiedResponse[ReqBody,RspBody],ReqBody]])]
= {
Some( ( ajr.msgId, ajr.to, ajr.from, ajr.flowId, ajr.body, ajr.justification ) )
}
}
case class JustifiedResponse[ReqBody,RspBody](
override val msgId : UUID,
//override val to : URI,
override val to : Moniker,
//override val from : URI,
override val from : Moniker,
override val flowId : UUID,
override val body : RspBody,
override val justification : Option[Request[AbstractJustifiedResponse[ReqBody,RspBody],ReqBody]]
) extends AbstractJustifiedResponse[ReqBody,RspBody](
msgId, to, from, flowId, body, justification
)
case class URIJustifiedResponse[RspBody](
override val msgId : UUID,
//override val to : URI,
override val to : Moniker,
//override val from : URI,
override val from : Moniker,
override val flowId : UUID,
override val body : RspBody,
override val justification : Option[Request[AbstractJustifiedResponse[URI,RspBody],URI]]
) extends AbstractJustifiedResponse[URI,RspBody](
msgId, to, from, flowId, body, justification
)
// Inspection and other control plane messages
trait InspectionRequest
extends Message[Unit,Unit]
with Header
with UUIDOps {
val flowId : UUID = getUUID()
}
//case class InspectRequests( to : URI, from : URI )
case class InspectRequests( to : Moniker, from : Moniker )
extends InspectionRequest {
override def msgId = getUUID()
override def body = {}
override def justification = None
}
//case class InspectResponses( to : URI, from : URI )
case class InspectResponses( to : Moniker, from : Moniker )
extends InspectionRequest {
override def msgId = getUUID()
override def body = {}
override def justification = None
}
//case class InspectNamespace( to : URI, from : URI )
case class InspectNamespace( to : Moniker, from : Moniker )
extends InspectionRequest {
override def msgId = getUUID()
override def body = {}
override def justification = None
}
trait InspectionResponse[Request] extends Message[Request,Unit] {}
| leithaus/strategies | src/main/scala/com/biosimilarity/lib/msg/Message.scala | Scala | cc0-1.0 | 7,204 |
// Copyright: 2010 - 2017 https://github.com/ensime/ensime-server/graphs
// License: http://www.gnu.org/licenses/lgpl-3.0.en.html
package spray.json
import org.scalacheck._
import org.scalatest._
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import Matchers._
object JsValueGenerators {
import Gen._
import Arbitrary.arbitrary
val parseableString: Gen[String] = Gen.someOf(('\u0020' to '\u007E').toVector).map(_.mkString)
val genString: Gen[JsString] = parseableString.map(JsString(_))
val genBoolean: Gen[JsBoolean] = oneOf(JsFalse, JsTrue)
val genLongNumber: Gen[JsNumber] = arbitrary[Long].map(JsNumber(_))
val genIntNumber: Gen[JsNumber] = arbitrary[Long].map(JsNumber(_))
val genDoubleNumber: Gen[JsNumber] = arbitrary[Long].map(JsNumber(_))
def genArray(depth: Int): Gen[JsArray] =
if (depth == 0) JsArray()
else
for {
n <- choose(0, 15)
els <- Gen.containerOfN[List, JsValue](n, genValue(depth - 1))
} yield JsArray(els.toVector)
def genField(depth: Int): Gen[(String, JsValue)] =
for {
key <- parseableString
value <- genValue(depth)
} yield key -> value
def genObject(depth: Int): Gen[JsObject] =
if (depth == 0) JsObject()
else
for {
n <- choose(0, 15)
fields <- Gen.containerOfN[List, (String, JsValue)](n, genField(depth - 1))
} yield JsObject(fields: _*)
def genValue(depth: Int): Gen[JsValue] =
oneOf(
JsNull: Gen[JsValue],
genString,
genBoolean,
genLongNumber,
genDoubleNumber,
genIntNumber,
genArray(depth),
genObject(depth)
)
implicit val arbitraryValue: Arbitrary[JsValue] = Arbitrary(genValue(5))
}
class RoundTripSpecs extends WordSpec with GeneratorDrivenPropertyChecks {
import JsValueGenerators.arbitraryValue
"Parsing / Printing round-trip" should {
"starting from JSON using compactPrint" in forAll { (json: JsValue) =>
json.compactPrint.parseJson shouldEqual json
}
"starting from JSON using prettyPrint" in forAll { (json: JsValue) =>
json.prettyPrint.parseJson shouldEqual json
}
}
}
| VlachJosef/ensime-server | json/src/test/scala/spray/json/RoundTripSpecs.scala | Scala | gpl-3.0 | 2,137 |
package sbt
package internal
package parser
import java.io.File
import org.specs2.mutable.SpecificationLike
trait SplitExpression {
def split(s: String, file: File = new File("noFile"))(
implicit splitter: SplitExpressions.SplitExpression) = splitter(file, s.split("\\n").toSeq)
}
trait SplitExpressionsBehavior extends SplitExpression { this: SpecificationLike =>
def newExpressionsSplitter(implicit splitter: SplitExpressions.SplitExpression): Unit = {
"parse a two settings without intervening blank line" in {
val (imports, settings) = split("""version := "1.0"
scalaVersion := "2.10.4"""")
imports.isEmpty should beTrue
settings.size === 2
}
"parse a setting and val without intervening blank line" in {
val (imports, settings) =
split("""version := "1.0"
lazy val root = (project in file(".")).enablePlugins(PlayScala)""")
imports.isEmpty should beTrue
settings.size === 2
}
"parse a config containing two imports and a setting with no blank line" in {
val (imports, settingsAndDefs) = split(
"""import foo.Bar
import foo.Bar
version := "1.0"
""".stripMargin
)
imports.size === 2
settingsAndDefs.size === 1
}
}
}
| Duhemm/sbt | main/src/test/scala/sbt/internal/parser/SplitExpressionsBehavior.scala | Scala | bsd-3-clause | 1,279 |
package xitrum.metrics
import akka.actor.{Actor, ActorRef, Terminated}
import akka.cluster.metrics.{ClusterMetricsChanged, ClusterMetricsExtension, NodeMetrics}
import akka.cluster.metrics.StandardMetrics.{Cpu, HeapMemory}
import io.netty.handler.codec.http.HttpResponseStatus
import xitrum.{FutureAction, Config, SockJsAction, SockJsText}
import xitrum.annotation.{GET, Last, SOCKJS}
import xitrum.util.SeriDeseri
import xitrum.view.DocType
/** JMX metrics collector for single node application. */
class MetricsCollector(localPublisher: ActorRef) extends Actor {
def receive: Receive = {
case Collect => localPublisher ! MetricsManager.jmx.sample()
case _ =>
}
}
/** JMX metrics collector for clustered node application. */
class ClusterMetricsCollector(localPublisher: ActorRef) extends Actor {
private val extension = ClusterMetricsExtension(context.system)
override def preStart(): Unit = {
extension.subscribe(self)
}
override def postStop(): Unit = {
extension.unsubscribe(self)
}
def receive: Receive = {
case m: ClusterMetricsChanged =>
localPublisher ! m
case UnSubscribe =>
extension.unsubscribe(self)
case _ =>
}
}
/**
* Example: XitrumMetricsChannel
*/
class MetricsPublisher extends Actor {
private var clients = Seq[ActorRef]()
private var lastPublished = System.currentTimeMillis()
private var cachedNodeMetrics: NodeMetrics = _
private var cachedClusterMetrics: Set[NodeMetrics] = _
private var cachedRegistryAsJson: String = _
def receive: Receive = {
case ClusterMetricsChanged(clusterMetrics) =>
cachedClusterMetrics = clusterMetrics
case nodeMetrics: NodeMetrics =>
cachedNodeMetrics = nodeMetrics
case Publish(registryAsJson) =>
cachedRegistryAsJson = registryAsJson
clients.foreach { client =>
client ! Publish(registryAsJson)
if (cachedNodeMetrics != null) client ! cachedNodeMetrics
// Ignore if clusterd metricsManager sent duplicated requests
if (System.currentTimeMillis - lastPublished > Config.xitrum.metrics.get.collectActorInterval.toMillis) {
if (cachedClusterMetrics != null) client ! cachedClusterMetrics.toList
lastPublished = System.currentTimeMillis
}
}
case Pull =>
sender() ! Publish(MetricsManager.registryAsJson)
if (cachedNodeMetrics != null) sender() ! cachedNodeMetrics
if (cachedClusterMetrics != null) sender() ! cachedClusterMetrics.toList
case Subscribe =>
clients = clients :+ sender()
context.watch(sender())
case UnSubscribe =>
clients = clients.filterNot(_ == sender())
context.unwatch(sender())
case Terminated(client) =>
clients = clients.filterNot(_ == client)
case _ =>
}
}
/** Javascript fragment for establish metrics JSON sockJS channel. */
trait MetricsViewer extends FutureAction {
def jsAddMetricsNameSpace(namespace: String = null): Unit = {
jsAddToView(s"""
(function (namespace) {
var ns = namespace || window;
var url = '${sockJsUrl[XitrumMetricsChannel]}';
var pullTimer;
var initMetricsChannel = function(onMessageFunc) {
var socket;
socket = new SockJS(url);
socket.onopen = function(event) {
socket.send('${MetricsManager.metrics.apiKey}');
pullTimer = setInterval(function() { socket.send('pull') }, 2000);
};
socket.onclose = function(e) {
clearInterval(pullTimer);
// Reconnect
setTimeout(function() { initMetricsChannel(onMessageFunc) }, 2000);
};
socket.onmessage = function(e) { onMessageFunc(e.data); }
};
ns.initMetricsChannel = initMetricsChannel;
})($namespace);
"""
)
}
}
/**
* Default metrics viewer page.
* This page could be overwritten in user application with any style.
*/
@Last
@GET("xitrum/metrics/viewer")
class XitrumMetricsViewer extends FutureAction with MetricsViewer {
beforeFilter {
val apiKey = param("api_key")
if (apiKey != MetricsManager.metrics.apiKey) {
response.setStatus(HttpResponseStatus.UNAUTHORIZED)
respondHtml(<p>Unauthorized</p>)
}
}
lazy val html: String = DocType.html5(
<html>
<head>
{xitrumCss}
{jsDefaults}
<script type="text/javascript" src={webJarsUrl("d3/3.5.17", "d3.js", "d3.min.js")}></script>
<script type="text/javascript" src={webJarsUrl(s"xitrum/${xitrum.version}/metrics.js")}></script>
<title>Xitrum Default Metrics Viewer</title>
</head>
<body class="metricsViewer">
<h2>Xitrum Default Metrics Viewer</h2>
<div>
<h3><a href="http://doc.akka.io/api/akka/snapshot/index.html#akka.cluster.NodeMetrics" target="_blank" >NodeMetrics</a> Status</h3>
<div class="metricsContent">
<div id='heapMemory' class="metricsTableWrapper">
<table id='heapMemoryTableHeader' class='metricsTableHeader'>
<caption>NodeMetrics(HeapMemory)</caption>
<tr><th>Time</th><th>Node</th><th>Committed(MB)</th><th>Used(MB)</th><th>Max(MB)</th></tr>
</table>
<table id='heapMemoryTable' class='metricsTable'>
</table>
</div>
<div id="heapMemoryGraph" class="metricsGraph nodeMetricsGraph"></div>
<div class="clearBoth"></div>
</div>
<hr/>
<div class="metricsContent">
<div id='cpu' class="metricsTableWrapper">
<table id='cpuTableHeader' class='metricsTableHeader'>
<caption>NodeMetrics(CPU)</caption>
<tr><th>Time</th><th>Node</th><th>Processors</th><th>Load Average</th></tr>
</table>
<table id='cpuTable' class='metricsTable'>
</table>
</div>
<div id="cpuGraph" class="metricsGraph"></div>
<div class="clearBoth"></div>
</div>
</div>
<hr/>
<div>
<h3>Application <a href="http://metrics.codahale.com/" target="_blank" >Metrics</a> Status</h3>
<div class="metricsContent">
<div id='metrics_registry'>
<div id='histograms' class="metricsTableWrapper">
<table id='histogramsTableHeader' class='metricsTableHeader'>
<caption>Histograms</caption>
<tr><th>Node</th><th>Key</th><th>Count</th><th>Min(ms)</th><th>Max(ms)</th><th>Mean(ms)</th></tr>
</table>
<table id='histogramsTable' class='metricsTable'>
</table>
</div>
<div id="histogramsGraph" class="metricsGraph"></div>
<div class="clearBoth"></div>
</div>
</div>
</div>
{jsForView}
</body>
</html>
)
lazy val focusHtml: String = DocType.html5(
<html>
<head>
{xitrumCss}
{jsDefaults}
<script type="text/javascript" src={webJarsUrl("d3/3.5.17", "d3.js", "d3.min.js")}></script>
<script type="text/javascript" src={webJarsUrl(s"xitrum/${xitrum.version}/metrics.js")}></script>
<title>Xitrum Default Metrics Viewer</title>
</head>
<body class="metricsViewer">
<div>
<h3 id="title"></h3>
<div id="focusGraph"></div>
</div>
{jsForView}
</body>
</html>
)
def execute(): Unit = {
jsAddMetricsNameSpace("window")
paramo("focusAction") match {
case Some(key) =>
jsAddToView("initMetricsChannel(channelOnMessageWithKey('"+ key +"'));")
respondHtml(focusHtml)
case None =>
jsAddToView("initMetricsChannel(channelOnMessage);")
respondHtml(html)
}
}
}
/** SockJS channel for metrics JSON. */
@SOCKJS("xitrum/metrics/channel")
class XitrumMetricsChannel extends SockJsAction with PublisherLookUp {
def execute(): Unit = {
checkAPIKey()
}
private def checkAPIKey(): Unit = {
context.become {
case SockJsText(text) if text == MetricsManager.metrics.apiKey =>
lookUpPublisher()
case SockJsText(key) =>
respondSockJsText("Wrong apikey")
respondSockJsClose()
case ignore =>
log.warn("Unexpected message: " + ignore)
}
}
override def doWithPublisher(publisher: ActorRef): Unit = {
publisher ! Subscribe
context.watch(publisher)
context.become {
case msg: Seq[_] =>
msg.asInstanceOf[Seq[NodeMetrics]].foreach { nodeMetrics =>
sendHeapMemory(nodeMetrics)
sendCpu(nodeMetrics)
}
case nodeMetrics: NodeMetrics =>
sendHeapMemory(nodeMetrics)
sendCpu(nodeMetrics)
case Publish(registryAsJson) =>
respondSockJsText(registryAsJson)
case SockJsText(text) =>
if (text == "pull" ) publisher ! Pull
case Terminated(`publisher`) =>
lookUpPublisher()
case _ =>
}
}
private def sendHeapMemory(nodeMetrics: NodeMetrics): Unit = {
nodeMetrics match {
case HeapMemory(address, timestamp, used, committed, max) =>
respondSockJsText(SeriDeseri.toJson(Map(
"TYPE" -> "heapMemory",
"SYSTEM" -> address.system,
"HOST" -> address.host,
"PORT" -> address.port,
"HASH" -> address.hashCode,
"TIMESTAMP" -> timestamp,
"USED" -> used,
"COMMITTED" -> committed,
"MAX" -> max
)))
case _ =>
}
}
private def sendCpu(nodeMetrics: NodeMetrics):Unit = {
nodeMetrics match {
case Cpu(address, timestamp, Some(systemLoadAverage), cpuCombined, cpuStolen, processors) =>
respondSockJsText(SeriDeseri.toJson(Map(
"TYPE" -> "cpu",
"SYSTEM" -> address.system,
"HOST" -> address.host,
"PORT" -> address.port,
"HASH" -> address.hashCode,
"TIMESTAMP" -> timestamp,
"SYSTEMLOADAVERAGE" -> systemLoadAverage,
"CPUCOMBINED" -> cpuCombined,
"PROCESSORS" -> processors
)))
case _ =>
}
}
}
| xitrum-framework/xitrum | src/main/scala/xitrum/metrics/MetricsAction.scala | Scala | mit | 10,274 |
/**
* Copyright 2011-2016 GatlingCorp (http://gatling.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 io.gatling.core
import io.gatling.core.body.{ RawFileBodies, ElFileBodies }
import io.gatling.core.check.extractor.css.{ CssExtractorFactory, CssSelectors }
import io.gatling.core.check.extractor.jsonpath.{ JsonPathExtractorFactory, JsonPaths }
import io.gatling.core.check.extractor.regex.{ RegexExtractorFactory, Patterns }
import io.gatling.core.check.extractor.xpath.{ SaxonXPathExtractorFactory, Saxon, JdkXPathExtractorFactory, JdkXmlParsers }
import io.gatling.core.config.GatlingConfiguration
import io.gatling.core.json.JsonParsers
trait CoreDefaultImplicits {
implicit def configuration: GatlingConfiguration
implicit lazy val defaultPatterns = new Patterns
implicit lazy val defaultRegexExtractorFactory = new RegexExtractorFactory
implicit lazy val defaultJsonParsers: JsonParsers = JsonParsers()
implicit lazy val defaultJsonPaths = new JsonPaths
implicit lazy val defaultJsonPathExtractorFactory = new JsonPathExtractorFactory
implicit lazy val defaultJdkXmlParsers = new JdkXmlParsers
implicit lazy val defaultJdkXPathExtractorFactory = new JdkXPathExtractorFactory
implicit lazy val defaultSaxon = new Saxon
implicit lazy val defaultSaxonXPathExtractorFactory = new SaxonXPathExtractorFactory
implicit lazy val defaultCssSelectors = new CssSelectors
implicit lazy val defaultCssExtractorFactory = new CssExtractorFactory
implicit lazy val elFileBodies = new ElFileBodies
implicit lazy val rawFileBodies = new RawFileBodies
}
| ryez/gatling | gatling-core/src/main/scala/io/gatling/core/CoreDefaultImplicits.scala | Scala | apache-2.0 | 2,104 |
package org.jetbrains
import com.intellij.util.{Function => IdeaFunction, PathUtil}
import com.intellij.openapi.util.{Pair => IdeaPair}
import reflect.ClassTag
import _root_.java.io._
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import _root_.java.lang.{Boolean => JavaBoolean}
import com.intellij.openapi.vfs.{VirtualFile, VfsUtil}
import com.intellij.openapi.util.io.FileUtil
/**
* @author Pavel Fatin
*/
package object sbt {
implicit def toIdeaFunction1[A, B](f: A => B): IdeaFunction[A, B] = new IdeaFunction[A, B] {
def fun(a: A) = f(a)
}
implicit def toIdeaPredicate[A](f: A => Boolean): IdeaFunction[A, JavaBoolean] = new IdeaFunction[A, JavaBoolean] {
def fun(a: A) = JavaBoolean.valueOf(f(a))
}
implicit def toIdeaFunction2[A, B, C](f: (A, B) => C): IdeaFunction[IdeaPair[A, B], C] = new IdeaFunction[IdeaPair[A, B], C] {
def fun(pair: IdeaPair[A, B]) = f(pair.getFirst, pair.getSecond)
}
implicit class RichFile(file: File) {
def /(path: String): File = new File(file, path)
def `<<`: File = << (1)
def `<<`(level: Int): File = RichFile.parent(file, level)
def path: String = file.getPath
def absolutePath: String = file.getAbsolutePath
def canonicalPath: String = ExternalSystemApiUtil.toCanonicalPath(file.getAbsolutePath)
def canonicalFile: File = new File(canonicalPath)
def url: String = VfsUtil.getUrlForLibraryRoot(file)
def isAncestorOf(aFile: File): Boolean = FileUtil.isAncestor(file, aFile, true)
def isUnder(root: File): Boolean = FileUtil.isAncestor(root, file, true)
def isOutsideOf(root: File): Boolean = !FileUtil.isAncestor(root, file, false)
def write(lines: String*) {
writeLinesTo(file, lines: _*)
}
def copyTo(destination: File) {
copy(file, destination)
}
}
private object RichFile {
def parent(file: File, level: Int): File =
if (level > 0) parent(file.getParentFile, level - 1) else file
}
implicit class RichVirtualFile(entry: VirtualFile) {
def containsDirectory(name: String): Boolean = find(name).exists(_.isDirectory)
def containsFile(name: String): Boolean = find(name).exists(_.isFile)
def find(name: String): Option[VirtualFile] = Option(entry.findChild(name))
def isFile: Boolean = !entry.isDirectory
}
implicit class RichString(path: String) {
def toFile: File = new File(path)
}
implicit class RichBoolean(val b: Boolean) {
def option[A](a: => A): Option[A] = if(b) Some(a) else None
def either[A, B](right: => B)(left: => A): Either[A, B] = if (b) Right(right) else Left(left)
def seq[A](a: A*): Seq[A] = if (b) Seq(a: _*) else Seq.empty
}
implicit class RichSeq[T](xs: Seq[T]) {
def distinctBy[A](f: T => A): Seq[T] = {
val (_, ys) = xs.foldLeft((Set.empty[A], Vector.empty[T])) {
case ((set, acc), x) =>
val v = f(x)
if (set.contains(v)) (set, acc) else (set + v, acc :+ x)
}
ys
}
}
def jarWith[T : ClassTag]: File = {
val tClass = implicitly[ClassTag[T]].runtimeClass
Option(PathUtil.getJarPathForClass(tClass)).map(new File(_)).getOrElse {
throw new RuntimeException("Jar file not found for class " + tClass.getName)
}
}
def using[A <: Closeable, B](resource: A)(block: A => B): B = {
try {
block(resource)
} finally {
resource.close()
}
}
def writeLinesTo(file: File, lines: String*) {
using(new PrintWriter(new FileWriter(file))) { writer =>
lines.foreach(writer.println(_))
writer.flush()
}
}
def copy(source: File, destination: File) {
using(new BufferedInputStream(new FileInputStream(source))) { in =>
using(new BufferedOutputStream(new FileOutputStream(destination))) { out =>
var eof = false
while (!eof) {
val b = in.read()
if (b == -1) eof = true else out.write(b)
}
out.flush()
}
}
}
def usingTempFile[T](prefix: String, suffix: Option[String] = None)(block: File => T): T = {
val file = FileUtil.createTempFile(prefix, suffix.orNull, true)
try {
block(file)
} finally {
file.delete()
}
}
private val NameWithExtension = """(.+)(\..+?)""".r
private def parse(fileName: String): (String, String) = fileName match {
case NameWithExtension(name, extension) => (name, extension)
case name => (name, "")
}
}
| consulo/consulo-scala | SBT/src/main/scala/org/jetbrains/sbt/package.scala | Scala | apache-2.0 | 4,446 |
/*
* 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.command
import org.apache.spark.sql.catalyst.analysis.{AnalysisTest, UnresolvedNamespace}
import org.apache.spark.sql.catalyst.parser.CatalystSqlParser.parsePlan
import org.apache.spark.sql.catalyst.plans.logical.DropNamespace
class DropNamespaceParserSuite extends AnalysisTest {
test("drop namespace") {
comparePlans(
parsePlan("DROP NAMESPACE a.b.c"),
DropNamespace(
UnresolvedNamespace(Seq("a", "b", "c")), ifExists = false, cascade = false))
comparePlans(
parsePlan("DROP NAMESPACE IF EXISTS a.b.c"),
DropNamespace(
UnresolvedNamespace(Seq("a", "b", "c")), ifExists = true, cascade = false))
comparePlans(
parsePlan("DROP NAMESPACE IF EXISTS a.b.c RESTRICT"),
DropNamespace(
UnresolvedNamespace(Seq("a", "b", "c")), ifExists = true, cascade = false))
comparePlans(
parsePlan("DROP NAMESPACE IF EXISTS a.b.c CASCADE"),
DropNamespace(
UnresolvedNamespace(Seq("a", "b", "c")), ifExists = true, cascade = true))
comparePlans(
parsePlan("DROP NAMESPACE a.b.c CASCADE"),
DropNamespace(
UnresolvedNamespace(Seq("a", "b", "c")), ifExists = false, cascade = true))
}
}
| ueshin/apache-spark | sql/core/src/test/scala/org/apache/spark/sql/execution/command/DropNamespaceParserSuite.scala | Scala | apache-2.0 | 2,036 |
/**
* (c) Copyright 2013 WibiData, Inc.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.kiji.mapreduce.shellext
import org.kiji.schema.shell.ddl.ColumnName
/**
* A single clause in the main <tt>MAP FIELDS ... AS ( <clauses< )</tt> list.
*
* <p>This can specify a single field to column mapping, a default column family to load
* to, or other properties of the import.</p>
*
* <p>Instances of <tt>FieldMappingElem</tt> are examined in {{FieldMapping#generateJson}};
* if you add a new subclass, you must modify the typecase in that method.</p>
*/
abstract class FieldMappingElem
/**
* A <tt>fieldname => family:qualifier</tt> clause in a field mapping that
* maps the specified field into the specified target column.
*
* @param fieldName the name of the input field.
* @param colName the name of the target column
*/
class SingleFieldMapping(val fieldName: String, val col: ColumnName) extends FieldMappingElem {
/** {@inheritDoc} */
override def equals(other: Any): Boolean = {
other match {
case single: SingleFieldMapping => {
return fieldName == single.fieldName && col.equals(single.col)
}
case _ => { return false }
}
}
/** {@inheritDoc} */
override def hashCode(): Int = {
return fieldName.hashCode() ^ col.hashCode()
}
}
/**
* A <tt>DEFAULT FAMILY (family)</tt> clause in a field mapping; all fields that are not
* explicitly used elsewhere in the field mapping are mapped to <tt>familyName:fieldName</tt>.
*
* @param familyName the name of the column family where target fields should be written.
*/
class DefaultFamilyMapping(val familyName: String) extends FieldMappingElem {
/** {@inheritDoc} */
override def equals(other: Any): Boolean = {
other match {
case default: DefaultFamilyMapping => {
return familyName == default.familyName
}
case _ => { return false }
}
}
/** {@inheritDoc} */
override def hashCode(): Int = {
return familyName.hashCode()
}
}
/**
* A <tt>field => $ENTITY</tt> clause, specifying that the named field is to be used
* as the target entity id during the import.
*
* @param fieldName the name of the field to use as the entity id.
*/
class EntityFieldMapping(val fieldName: String) extends FieldMappingElem {
/** {@inheritDoc} */
override def equals(other: Any): Boolean = {
other match {
case entity: EntityFieldMapping => {
return fieldName == entity.fieldName
}
case _ => { return false }
}
}
/** {@inheritDoc} */
override def hashCode(): Int = {
return fieldName.hashCode()
}
}
/**
* A <tt>field => $TIMESTAMP</tt> clause, specifying that the named field is to be used
* as the timestamp for the imported record during the import.
*
* @param fieldName the name of the field to use as the timestamp.
*/
class TimestampFieldMapping(val fieldName: String) extends FieldMappingElem {
/** {@inheritDoc} */
override def equals(other: Any): Boolean = {
other match {
case timestamp: TimestampFieldMapping => {
return fieldName == timestamp.fieldName
}
case _ => { return false }
}
}
/** {@inheritDoc} */
override def hashCode(): Int = {
return fieldName.hashCode()
}
}
| kijiproject/kiji-mapreduce-lib | schema-shell-ext/src/main/scala/org/kiji/mapreduce/shellext/FieldMappingElem.scala | Scala | apache-2.0 | 3,899 |
/**
* Licensed to Big Data Genomics (BDG) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The BDG 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.bdgenomics.guacamole.reads
import org.bdgenomics.guacamole.TestUtil
import org.bdgenomics.guacamole.TestUtil.Implicits._
import org.scalatest.Matchers
class UnmappedReadSuite extends TestUtil.SparkFunSuite with Matchers {
test("unmappedread is not mapped") {
val read = UnmappedRead(
5, // token
"TCGACCCTCGA",
Array[Byte]((10 to 20).map(_.toByte): _*),
true,
"some sample name",
false,
isPositiveStrand = true,
matePropertiesOpt = Some(
MateProperties(
isFirstInPair = true,
inferredInsertSize = Some(300),
isMateMapped = true,
Some("chr5"),
Some(100L),
false
)
)
)
read.isMapped should be(false)
read.asInstanceOf[Read].isMapped should be(false)
read.getMappedReadOpt should be(None)
val collectionMappedReads: Seq[Read] = Seq(read)
collectionMappedReads(0).isMapped should be(false)
}
}
| ryan-williams/guacamole | src/test/scala/org/bdgenomics/guacamole/reads/UnmappedReadSuite.scala | Scala | apache-2.0 | 1,765 |
/*
* Copyright (C) 2016 Christopher Batey and Dogan Narinc
*
* 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.scassandra.codec.datatype
import java.net.InetAddress
import scodec.Attempt.Failure
import scodec.bits.ByteVector
class InetSpec extends DataTypeSpec {
val codec = DataType.Inet.codec
val ipv4LocalBytes = Array[Byte](127, 0, 0, 1)
val ipv4Local = InetAddress.getByAddress(ipv4LocalBytes)
val ipv6LocalBytes = Array[Byte](0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)
val ipv6Local = InetAddress.getByAddress(ipv6LocalBytes)
"codec" must "encode Inet4Address as inet format" in {
codec.encode(ipv4Local).require.bytes shouldEqual ByteVector(ipv4LocalBytes)
}
it must "encode Inet6Address as inet format" in {
codec.encode(ipv6Local).require.bytes shouldEqual ByteVector(ipv6LocalBytes)
}
it must "encode String than can be parsed as a Inet as inet format" in {
codec.encode("127.0.0.1").require.bytes shouldEqual ByteVector(ipv4LocalBytes)
codec.encode("::1").require.bytes shouldEqual ByteVector(ipv6LocalBytes)
}
it must "fail to encode value that doesn't map to a double" in {
codec.encode("hello") should matchPattern { case Failure(_) => }
codec.encode(true) should matchPattern { case Failure(_) => }
codec.encode(false) should matchPattern { case Failure(_) => }
codec.encode(List()) should matchPattern { case Failure(_) => }
codec.encode(Map()) should matchPattern { case Failure(_) => }
}
it must "encode and decode back as InetAddress" in {
encodeAndDecode(codec, ipv4Local)
encodeAndDecode(codec, ipv6Local)
encodeAndDecode(codec, "127.0.0.1", ipv4Local)
encodeAndDecode(codec, "::1", ipv6Local)
}
}
| mikefero/cpp-driver | gtests/src/integration/scassandra/server/codec/src/test/scala/org/scassandra/codec/datatype/InetSpec.scala | Scala | apache-2.0 | 2,237 |
package com.krux.hyperion.examples
import org.scalatest.WordSpec
import org.json4s.JsonDSL._
import org.json4s._
class ExampleHiveActivitySpec extends WordSpec {
"ExampleHiveActivitySpec" should {
"produce correct pipeline JSON" in {
val pipelineJson = ExampleHiveActivity.toJson
val objectsField = pipelineJson.children.head.children.sortBy(o => (o \\ "name").toString)
assert(objectsField.size == 5)
val defaultObj = objectsField(1)
val defaultObjShouldBe = ("id" -> "Default") ~
("name" -> "Default") ~
("scheduleType" -> "cron") ~
("failureAndRerunMode" -> "CASCADE") ~
("pipelineLogUri" -> "s3://your-bucket/datapipeline-logs/") ~
("role" -> "DataPipelineDefaultRole") ~
("resourceRole" -> "DataPipelineDefaultResourceRole") ~
("schedule" -> ("ref" -> "PipelineSchedule"))
assert(defaultObj === defaultObjShouldBe)
val mapReduceCluster = objectsField.head
val mapReduceClusterId = (mapReduceCluster \\ "id").values.toString
assert(mapReduceClusterId.startsWith("MapReduceCluster_"))
val mapReduceClusterShouldBe =
("id" -> mapReduceClusterId) ~
("name" -> "Cluster with release label") ~
("bootstrapAction" -> Seq.empty[String]) ~
("masterInstanceType" -> "m3.xlarge") ~
("coreInstanceType" -> "m3.xlarge") ~
("coreInstanceCount" -> "2") ~
("taskInstanceType" -> "#{my_InstanceType}") ~
("taskInstanceCount" -> "#{my_InstanceCount}") ~
("terminateAfter" -> "8 hours") ~
("keyPair" -> "your-aws-key-pair") ~
("type" -> "EmrCluster") ~
("region" -> "us-east-1") ~
("role" -> "DataPipelineDefaultRole") ~
("resourceRole" -> "DataPipelineDefaultResourceRole") ~
("releaseLabel" -> "emr-4.4.0") ~
("initTimeout" -> "1 hours")
assert(mapReduceCluster === mapReduceClusterShouldBe)
val pipelineSchedule = objectsField(3)
val pipelineScheduleShouldBe =
("id" -> "PipelineSchedule") ~
("name" -> "PipelineSchedule") ~
("period" -> "1 days") ~
("startAt" -> "FIRST_ACTIVATION_DATE_TIME") ~
("occurrences" -> "3") ~
("type" -> "Schedule")
assert(pipelineSchedule === pipelineScheduleShouldBe)
val dataNode = objectsField(4)
val dataNodeId = (dataNode \\ "id").values.toString
assert(dataNodeId.startsWith("S3Folder_"))
val dataNodeShouldBe =
("id" -> dataNodeId) ~
("name" -> dataNodeId) ~
("directoryPath" -> "#{my_S3Location}") ~
("type" -> "S3DataNode")
assert(dataNode === dataNodeShouldBe)
val hiveActivity = objectsField(2)
val hiveActivityId = (hiveActivity \\ "id").values.toString
assert(hiveActivityId.startsWith("HiveActivity_"))
val hiveActivityShouldBe =
("id" -> hiveActivityId) ~
("name" -> hiveActivityId) ~
("hiveScript" -> s"INSERT OVERWRITE TABLE $${output1} SELECT x.a FROM $${input1} x JOIN $${input2} y ON x.id = y.id;") ~
("stage" -> "true") ~
("input" -> Seq("ref" -> dataNodeId, "ref" -> dataNodeId)) ~
("output" -> Seq("ref" -> dataNodeId)) ~
("runsOn" -> ("ref" -> mapReduceClusterId)) ~
("type" -> "HiveActivity")
assert(hiveActivity === hiveActivityShouldBe)
}
}
}
| sethyates/hyperion | examples/src/test/scala/com/krux/hyperion/examples/ExampleHiveActivitySpec.scala | Scala | apache-2.0 | 3,435 |
/*
* 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.streaming.kafka
import scala.util.Random
import kafka.common.TopicAndPartition
import org.scalatest.BeforeAndAfterAll
import org.apache.spark.SparkFunSuite
class KafkaClusterSuite extends SparkFunSuite with BeforeAndAfterAll {
private val topic = "kcsuitetopic" + Random.nextInt(10000)
private val topicAndPartition = TopicAndPartition(topic, 0)
//
private var kc: KafkaCluster = null
private var kafkaTestUtils: KafkaTestUtils = _
override def beforeAll() {
kafkaTestUtils = new KafkaTestUtils
kafkaTestUtils.setup()
kafkaTestUtils.createTopic(topic)
kafkaTestUtils.sendMessages(topic, Map("a" -> 1))
kc = new KafkaCluster(Map("metadata.broker.list" -> kafkaTestUtils.brokerAddress))
}
override def afterAll() {
if (kafkaTestUtils != null) {
kafkaTestUtils.teardown()
kafkaTestUtils = null
}
}
test("metadata apis") {//元数据API
val leader = kc.findLeaders(Set(topicAndPartition)).right.get(topicAndPartition)
val leaderAddress = s"${leader._1}:${leader._2}"
assert(leaderAddress === kafkaTestUtils.brokerAddress, "didn't get leader")
val parts = kc.getPartitions(Set(topic)).right.get
assert(parts(topicAndPartition), "didn't get partitions")
val err = kc.getPartitions(Set(topic + "BAD"))
assert(err.isLeft, "getPartitions for a nonexistant topic should be an error")
}
test("leader offset apis") {//指挥者偏移API
val earliest = kc.getEarliestLeaderOffsets(Set(topicAndPartition)).right.get
assert(earliest(topicAndPartition).offset === 0, "didn't get earliest")
val latest = kc.getLatestLeaderOffsets(Set(topicAndPartition)).right.get
assert(latest(topicAndPartition).offset === 1, "didn't get latest")
}
test("consumer offset apis") {//消费者偏移API
val group = "kcsuitegroup" + Random.nextInt(10000)
val offset = Random.nextInt(10000)
val set = kc.setConsumerOffsets(group, Map(topicAndPartition -> offset))
assert(set.isRight, "didn't set consumer offsets")
val get = kc.getConsumerOffsets(group, Set(topicAndPartition)).right.get
assert(get(topicAndPartition) === offset, "didn't get consumer offsets")
}
}
| tophua/spark1.52 | external/kafka/src/test/scala/org/apache/spark/streaming/kafka/KafkaClusterSuite.scala | Scala | apache-2.0 | 3,010 |
/*
* Copyright (c) 2014-2020 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)
}
}
*/ | alexandru/monifu | benchmarks/shared/src/main/scala/monix/benchmarks/TaskAttemptBenchmark.scala | Scala | apache-2.0 | 2,209 |
/*
* 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.streaming.kinesis
import scala.reflect.ClassTag
import com.amazonaws.services.kinesis.clientlibrary.lib.worker.InitialPositionInStream
import com.amazonaws.services.kinesis.model.Record
import org.apache.spark.annotation.Evolving
import org.apache.spark.rdd.RDD
import org.apache.spark.storage.{BlockId, StorageLevel}
import org.apache.spark.streaming.{Duration, StreamingContext, Time}
import org.apache.spark.streaming.api.java.JavaStreamingContext
import org.apache.spark.streaming.dstream.ReceiverInputDStream
import org.apache.spark.streaming.kinesis.KinesisInitialPositions.Latest
import org.apache.spark.streaming.receiver.Receiver
import org.apache.spark.streaming.scheduler.ReceivedBlockInfo
private[kinesis] class KinesisInputDStream[T: ClassTag](
_ssc: StreamingContext,
val streamName: String,
val endpointUrl: String,
val regionName: String,
val initialPosition: KinesisInitialPosition,
val checkpointAppName: String,
val checkpointInterval: Duration,
val _storageLevel: StorageLevel,
val messageHandler: Record => T,
val kinesisCreds: SparkAWSCredentials,
val dynamoDBCreds: Option[SparkAWSCredentials],
val cloudWatchCreds: Option[SparkAWSCredentials]
) extends ReceiverInputDStream[T](_ssc) {
import KinesisReadConfigurations._
private[streaming]
override def createBlockRDD(time: Time, blockInfos: Seq[ReceivedBlockInfo]): RDD[T] = {
// This returns true even for when blockInfos is empty
val allBlocksHaveRanges = blockInfos.map { _.metadataOption }.forall(_.nonEmpty)
if (allBlocksHaveRanges) {
// Create a KinesisBackedBlockRDD, even when there are no blocks
val blockIds = blockInfos.map { _.blockId.asInstanceOf[BlockId] }.toArray
val seqNumRanges = blockInfos.map {
_.metadataOption.get.asInstanceOf[SequenceNumberRanges] }.toArray
val isBlockIdValid = blockInfos.map { _.isBlockIdValid() }.toArray
logDebug(s"Creating KinesisBackedBlockRDD for $time with ${seqNumRanges.length} " +
s"seq number ranges: ${seqNumRanges.mkString(", ")} ")
new KinesisBackedBlockRDD(
context.sc, regionName, endpointUrl, blockIds, seqNumRanges,
isBlockIdValid = isBlockIdValid,
messageHandler = messageHandler,
kinesisCreds = kinesisCreds,
kinesisReadConfigs = KinesisReadConfigurations(ssc))
} else {
logWarning("Kinesis sequence number information was not present with some block metadata," +
" it may not be possible to recover from failures")
super.createBlockRDD(time, blockInfos)
}
}
override def getReceiver(): Receiver[T] = {
new KinesisReceiver(streamName, endpointUrl, regionName, initialPosition,
checkpointAppName, checkpointInterval, _storageLevel, messageHandler,
kinesisCreds, dynamoDBCreds, cloudWatchCreds)
}
}
@Evolving
object KinesisInputDStream {
/**
* Builder for [[KinesisInputDStream]] instances.
*
* @since 2.2.0
*/
@Evolving
class Builder {
// Required params
private var streamingContext: Option[StreamingContext] = None
private var streamName: Option[String] = None
private var checkpointAppName: Option[String] = None
// Params with defaults
private var endpointUrl: Option[String] = None
private var regionName: Option[String] = None
private var initialPosition: Option[KinesisInitialPosition] = None
private var checkpointInterval: Option[Duration] = None
private var storageLevel: Option[StorageLevel] = None
private var kinesisCredsProvider: Option[SparkAWSCredentials] = None
private var dynamoDBCredsProvider: Option[SparkAWSCredentials] = None
private var cloudWatchCredsProvider: Option[SparkAWSCredentials] = None
/**
* Sets the StreamingContext that will be used to construct the Kinesis DStream. This is a
* required parameter.
*
* @param ssc [[StreamingContext]] used to construct Kinesis DStreams
* @return Reference to this [[KinesisInputDStream.Builder]]
*/
def streamingContext(ssc: StreamingContext): Builder = {
streamingContext = Option(ssc)
this
}
/**
* Sets the StreamingContext that will be used to construct the Kinesis DStream. This is a
* required parameter.
*
* @param jssc [[JavaStreamingContext]] used to construct Kinesis DStreams
* @return Reference to this [[KinesisInputDStream.Builder]]
*/
def streamingContext(jssc: JavaStreamingContext): Builder = {
streamingContext = Option(jssc.ssc)
this
}
/**
* Sets the name of the Kinesis stream that the DStream will read from. This is a required
* parameter.
*
* @param streamName Name of Kinesis stream that the DStream will read from
* @return Reference to this [[KinesisInputDStream.Builder]]
*/
def streamName(streamName: String): Builder = {
this.streamName = Option(streamName)
this
}
/**
* Sets the KCL application name to use when checkpointing state to DynamoDB. This is a
* required parameter.
*
* @param appName Value to use for the KCL app name (used when creating the DynamoDB checkpoint
* table and when writing metrics to CloudWatch)
* @return Reference to this [[KinesisInputDStream.Builder]]
*/
def checkpointAppName(appName: String): Builder = {
checkpointAppName = Option(appName)
this
}
/**
* Sets the AWS Kinesis endpoint URL. Defaults to "https://kinesis.us-east-1.amazonaws.com" if
* no custom value is specified
*
* @param url Kinesis endpoint URL to use
* @return Reference to this [[KinesisInputDStream.Builder]]
*/
def endpointUrl(url: String): Builder = {
endpointUrl = Option(url)
this
}
/**
* Sets the AWS region to construct clients for. Defaults to "us-east-1" if no custom value
* is specified.
*
* @param regionName Name of AWS region to use (e.g. "us-west-2")
* @return Reference to this [[KinesisInputDStream.Builder]]
*/
def regionName(regionName: String): Builder = {
this.regionName = Option(regionName)
this
}
/**
* Sets the initial position data is read from in the Kinesis stream. Defaults to
* [[KinesisInitialPositions.Latest]] if no custom value is specified.
*
* @param initialPosition [[KinesisInitialPosition]] value specifying where Spark Streaming
* will start reading records in the Kinesis stream from
* @return Reference to this [[KinesisInputDStream.Builder]]
*/
def initialPosition(initialPosition: KinesisInitialPosition): Builder = {
this.initialPosition = Option(initialPosition)
this
}
/**
* Sets the initial position data is read from in the Kinesis stream. Defaults to
* [[InitialPositionInStream.LATEST]] if no custom value is specified.
* This function would be removed when we deprecate the KinesisUtils.
*
* @param initialPosition InitialPositionInStream value specifying where Spark Streaming
* will start reading records in the Kinesis stream from
* @return Reference to this [[KinesisInputDStream.Builder]]
*/
@deprecated("use initialPosition(initialPosition: KinesisInitialPosition)", "2.3.0")
def initialPositionInStream(initialPosition: InitialPositionInStream): Builder = {
this.initialPosition = Option(
KinesisInitialPositions.fromKinesisInitialPosition(initialPosition))
this
}
/**
* Sets how often the KCL application state is checkpointed to DynamoDB. Defaults to the Spark
* Streaming batch interval if no custom value is specified.
*
* @param interval [[Duration]] specifying how often the KCL state should be checkpointed to
* DynamoDB.
* @return Reference to this [[KinesisInputDStream.Builder]]
*/
def checkpointInterval(interval: Duration): Builder = {
checkpointInterval = Option(interval)
this
}
/**
* Sets the storage level of the blocks for the DStream created. Defaults to
* [[StorageLevel.MEMORY_AND_DISK_2]] if no custom value is specified.
*
* @param storageLevel [[StorageLevel]] to use for the DStream data blocks
* @return Reference to this [[KinesisInputDStream.Builder]]
*/
def storageLevel(storageLevel: StorageLevel): Builder = {
this.storageLevel = Option(storageLevel)
this
}
/**
* Sets the [[SparkAWSCredentials]] to use for authenticating to the AWS Kinesis
* endpoint. Defaults to [[DefaultCredentialsProvider]] if no custom value is specified.
*
* @param credentials [[SparkAWSCredentials]] to use for Kinesis authentication
*/
def kinesisCredentials(credentials: SparkAWSCredentials): Builder = {
kinesisCredsProvider = Option(credentials)
this
}
/**
* Sets the [[SparkAWSCredentials]] to use for authenticating to the AWS DynamoDB
* endpoint. Will use the same credentials used for AWS Kinesis if no custom value is set.
*
* @param credentials [[SparkAWSCredentials]] to use for DynamoDB authentication
*/
def dynamoDBCredentials(credentials: SparkAWSCredentials): Builder = {
dynamoDBCredsProvider = Option(credentials)
this
}
/**
* Sets the [[SparkAWSCredentials]] to use for authenticating to the AWS CloudWatch
* endpoint. Will use the same credentials used for AWS Kinesis if no custom value is set.
*
* @param credentials [[SparkAWSCredentials]] to use for CloudWatch authentication
*/
def cloudWatchCredentials(credentials: SparkAWSCredentials): Builder = {
cloudWatchCredsProvider = Option(credentials)
this
}
/**
* Create a new instance of [[KinesisInputDStream]] with configured parameters and the provided
* message handler.
*
* @param handler Function converting [[Record]] instances read by the KCL to DStream type [[T]]
* @return Instance of [[KinesisInputDStream]] constructed with configured parameters
*/
def buildWithMessageHandler[T: ClassTag](
handler: Record => T): KinesisInputDStream[T] = {
val ssc = getRequiredParam(streamingContext, "streamingContext")
new KinesisInputDStream(
ssc,
getRequiredParam(streamName, "streamName"),
endpointUrl.getOrElse(DEFAULT_KINESIS_ENDPOINT_URL),
regionName.getOrElse(DEFAULT_KINESIS_REGION_NAME),
initialPosition.getOrElse(DEFAULT_INITIAL_POSITION),
getRequiredParam(checkpointAppName, "checkpointAppName"),
checkpointInterval.getOrElse(ssc.graph.batchDuration),
storageLevel.getOrElse(DEFAULT_STORAGE_LEVEL),
ssc.sc.clean(handler),
kinesisCredsProvider.getOrElse(DefaultCredentials),
dynamoDBCredsProvider,
cloudWatchCredsProvider)
}
/**
* Create a new instance of [[KinesisInputDStream]] with configured parameters and using the
* default message handler, which returns [[Array[Byte]]].
*
* @return Instance of [[KinesisInputDStream]] constructed with configured parameters
*/
def build(): KinesisInputDStream[Array[Byte]] = buildWithMessageHandler(defaultMessageHandler)
private def getRequiredParam[T](param: Option[T], paramName: String): T = param.getOrElse {
throw new IllegalArgumentException(s"No value provided for required parameter $paramName")
}
}
/**
* Creates a [[KinesisInputDStream.Builder]] for constructing [[KinesisInputDStream]] instances.
*
* @since 2.2.0
* @return [[KinesisInputDStream.Builder]] instance
*/
def builder: Builder = new Builder
private[kinesis] def defaultMessageHandler(record: Record): Array[Byte] = {
if (record == null) return null
val byteBuffer = record.getData()
val byteArray = new Array[Byte](byteBuffer.remaining())
byteBuffer.get(byteArray)
byteArray
}
private[kinesis] val DEFAULT_KINESIS_ENDPOINT_URL: String =
"https://kinesis.us-east-1.amazonaws.com"
private[kinesis] val DEFAULT_KINESIS_REGION_NAME: String = "us-east-1"
private[kinesis] val DEFAULT_INITIAL_POSITION: KinesisInitialPosition = new Latest()
private[kinesis] val DEFAULT_STORAGE_LEVEL: StorageLevel = StorageLevel.MEMORY_AND_DISK_2
}
| aosagie/spark | external/kinesis-asl/src/main/scala/org/apache/spark/streaming/kinesis/KinesisInputDStream.scala | Scala | apache-2.0 | 13,230 |
package com.twitter.finagle.mux
import com.twitter.concurrent.AsyncQueue
import com.twitter.conversions.time._
import com.twitter.finagle.mux.transport.Message
import com.twitter.finagle.transport.QueueTransport
import com.twitter.finagle.{Failure, Status}
import com.twitter.io.Buf
import com.twitter.util.{Await, Return}
import java.net.SocketAddress
import java.security.cert.{Certificate, X509Certificate}
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.mock.MockitoSugar
import org.scalatest.{OneInstancePerTest, FunSuite}
import scala.collection.immutable.Queue
@RunWith(classOf[JUnitRunner])
class HandshakeTest extends FunSuite
with OneInstancePerTest
with MockitoSugar {
import Message.{encode => enc, decode => dec}
val clientToServer = new AsyncQueue[Buf]
val serverToClient = new AsyncQueue[Buf]
val clientTransport = new QueueTransport(
writeq = clientToServer,
readq = serverToClient)
val serverTransport = new QueueTransport(
writeq = serverToClient,
readq = clientToServer)
test("handshake") {
var clientNegotiated = false
var serverNegotiated = false
val client = Handshake.client(
trans = clientTransport,
version = 0x0001,
headers = Seq.empty,
negotiate = (_, trans) => {
clientNegotiated = true
trans.map(enc, dec)
}
)
val server = Handshake.server(
trans = serverTransport,
version = 0x0001,
headers = identity,
negotiate = (_, trans) => {
serverNegotiated = true
trans.map(enc, dec)
}
)
// ensure negotiation is complete
Await.result(client.write(Message.Tping(1)), 5.seconds)
Await.result(server.write(Message.Rping(1)), 5.seconds)
assert(serverNegotiated)
assert(clientNegotiated)
}
test("sync operations are proxied") {
val remote = new java.net.SocketAddress { }
val local = new java.net.SocketAddress { }
val peerCert = Some(mock[X509Certificate])
val q = new AsyncQueue[Buf]
val trans = new QueueTransport(q, q) {
override val localAddress: SocketAddress = local
override val remoteAddress: SocketAddress = remote
override def peerCertificate: Option[Certificate] = peerCert
}
val client = Handshake.client(
trans = trans,
version = 0x0001,
headers = Seq.empty,
negotiate = (_, trans) => {
trans.map(enc, dec)
}
)
assert(client.localAddress == local)
assert(client.remoteAddress == remote)
assert(client.peerCertificate == peerCert)
val server = Handshake.server(
trans = trans,
version = 0x0001,
headers = identity,
negotiate = (_, trans) => {
trans.map(enc, dec)
}
)
assert(server.localAddress == local)
assert(server.remoteAddress == remote)
assert(server.peerCertificate == peerCert)
}
test("exceptions in negotiate propagate") {
val clientExc = new Exception("boom!")
val client = Handshake.client(
trans = clientTransport,
version = 0x0001,
headers = Seq.empty,
negotiate = (_, trans) => {
throw clientExc
trans.map(enc, dec)
}
)
val serverExc = new Exception("boom!")
val server = Handshake.server(
trans = serverTransport,
version = 0x0001,
headers = identity,
negotiate = (_, trans) => {
throw serverExc
trans.map(enc, dec)
}
)
assert(intercept[Exception] {
Await.result(client.read(), 5.seconds)
} == clientExc)
assert(intercept[Exception] {
Await.result(client.write(Message.Tping(1)), 5.seconds)
} == clientExc)
assert(intercept[Exception] {
Await.result(server.read(), 5.seconds)
} == serverExc)
assert(intercept[Exception] {
Await.result(server.write(Message.Rping(1)), 5.seconds)
} == serverExc)
}
test("pre handshake") {
var negotiated = false
val client = Handshake.client(
trans = clientTransport,
version = 0x0001,
headers = Nil,
negotiate = (_, trans) => {
negotiated = true
trans.map(enc, dec)
}
)
val f = client.write(Message.Tping(2))
assert(dec(Await.result(clientToServer.poll(), 5.seconds)) ==
Message.Rerr(1, "tinit check"))
assert(!negotiated)
assert(!f.isDefined)
}
test("client handshake") {
val version = 10: Short
val headers = Seq(Buf.Utf8("key") -> Buf.Utf8("value"))
var negotiated = false
val client = Handshake.client(
trans = clientTransport,
version = version,
headers = headers,
negotiate = (_, trans) => {
negotiated = true
trans.map(enc, dec)
}
)
val f = client.write(Message.Tping(2))
assert(dec(Await.result(clientToServer.poll(), 5.seconds)) ==
Message.Rerr(1, "tinit check"))
assert(!negotiated)
assert(!f.isDefined)
serverToClient.offer(enc(Message.Rerr(1, "tinit check")))
assert(dec(Await.result(clientToServer.poll(), 5.seconds)) ==
Message.Tinit(1, version, headers))
assert(!negotiated)
assert(!f.isDefined)
serverToClient.offer(enc(Message.Rinit(1, version, Seq.empty)))
assert(negotiated)
assert(f.isDefined && Await.result(f.liftToTry, 5.seconds).isReturn)
}
test("client fails gracefully") {
var negotiated = false
val client = Handshake.client(
trans = clientTransport,
version = 0x0001,
headers = Seq.empty,
negotiate = (_, trans) => {
negotiated = true
trans.map(enc, dec)
}
)
val f = client.write(Message.Tping(2))
assert(dec(Await.result(clientToServer.poll(), 5.seconds)) ==
Message.Rerr(1, "tinit check"))
assert(!negotiated)
assert(!f.isDefined)
serverToClient.offer(enc(Message.Rerr(1, "unexpected message Rerr")))
assert(!negotiated)
assert(f.isDefined && Await.result(f.liftToTry, 5.seconds).isReturn)
}
test("server handshake") {
val version = 10: Short
val hdrs = Seq(Buf.Utf8("key") -> Buf.Utf8("value"))
var negotiated = false
val server = Handshake.server(
trans = serverTransport,
version = version,
headers = _ => hdrs,
negotiate = (_, trans) => {
negotiated = true
trans.map(enc, dec)
}
)
clientToServer.offer(enc(Message.Tinit(1, version, Seq.empty)))
assert(dec(Await.result(serverToClient.poll(), 5.seconds)) ==
Message.Rinit(1, version, hdrs))
assert(negotiated)
}
test("version mismatch") {
var clientNegotiated = false
var serverNegotiated = false
val clientVersion: Short = 2
val serverVersion: Short = 1
val client = Handshake.client(
trans = clientTransport,
version = clientVersion,
headers = Seq.empty,
negotiate = (_, trans) => {
clientNegotiated = true
trans.map(enc, dec)
}
)
val server = Handshake.server(
trans = serverTransport,
version = serverVersion,
headers = identity,
negotiate = (_, trans) => {
serverNegotiated = true
trans.map(enc, dec)
}
)
val f0 = intercept[Failure] {
Await.result(client.write(Message.Tping(1)), 5.seconds)
}
val f1 = intercept[Failure] {
Await.result(server.write(Message.Rping(1)), 5.seconds)
}
val msg = s"unsupported version $clientVersion, expected $serverVersion"
assert(f0.getMessage == msg)
assert(f1.getMessage == msg)
assert(!clientNegotiated && !serverNegotiated)
Await.result(serverTransport.onClose, 5.seconds)
Await.result(clientTransport.onClose, 5.seconds)
assert(client.status == Status.Closed)
assert(server.status == Status.Closed)
}
test("server passes non-init messages through") {
var negotiated = false
val server = Handshake.server(
trans = serverTransport,
version = 0x0001,
headers = identity,
negotiate = (_, trans) => {
negotiated = true
trans.map(enc, dec)
}
)
clientToServer.offer(enc(Message.Tping(1)))
assert(serverToClient.drain() == Return(Queue.empty))
assert(Await.result(server.read(), 5.seconds) == Message.Tping(1))
assert(!negotiated)
}
} | koshelev/finagle | finagle-mux/src/test/scala/com/twitter/finagle/mux/HandshakeTest.scala | Scala | apache-2.0 | 8,295 |
package com.twitter.finagle
import java.net.InetSocketAddress
import java.util.{Map => JMap}
import scala.collection.JavaConverters._
import scala.util.control.NoStackTrace
/**
* An [[Address]] represents the physical location of a single host or
* endpoint. It also includes [[Addr.Metadata]] (typically set by [[Namer]]s
* and [[Resolver]]s) that provides additional configuration to client stacks.
*
* Note that a bound [[Addr]] contains a set of [[Address]]es and [[Addr.Metadata]]
* that pertains to the entire set.
*/
sealed trait Address
object Address {
private[finagle] val failing: Address =
Address.Failed(new IllegalArgumentException("failing") with NoStackTrace)
/**
* An address represented by an Internet socket address.
*/
case class Inet(
addr: InetSocketAddress,
metadata: Addr.Metadata)
extends Address
/**
* An address that fails with the given `cause`.
*/
case class Failed(cause: Throwable) extends Address
/** Create a new [[Address]] with given [[java.net.InetSocketAddress]]. */
def apply(addr: InetSocketAddress): Address =
Address.Inet(addr, Addr.Metadata.empty)
/** Create a new [[Address]] with given `host` and `port`. */
def apply(host: String, port: Int): Address =
Address(new InetSocketAddress(host, port))
/** Create a new loopback [[Address]] with the given `port`. */
def apply(port: Int): Address =
Address(new InetSocketAddress(port))
}
package exp {
object Address {
/** Create a new [[Address]] with the given [[com.twitter.finagle.ServiceFactory]]. */
def apply[Req, Rep](factory: com.twitter.finagle.ServiceFactory[Req, Rep]): Address =
Address.ServiceFactory(factory, Addr.Metadata.empty)
/**
* An endpoint address represented by a [[com.twitter.finagle.ServiceFactory]]
* that implements the endpoint.
*/
case class ServiceFactory[Req, Rep](
factory: com.twitter.finagle.ServiceFactory[Req, Rep],
metadata: Addr.Metadata)
extends Address
}
}
/**
* A Java adaptation of the [[com.twitter.finagle.Address]] companion object.
*/
object Addresses {
/**
* @see com.twitter.finagle.Address.Inet
*/
def newInetAddress(ia: InetSocketAddress): Address =
Address.Inet(ia, Addr.Metadata.empty)
/**
* @see com.twitter.finagle.Address.Inet
*/
def newInetAddress(ia: InetSocketAddress, metadata: JMap[String, Any]): Address =
Address.Inet(ia, metadata.asScala.toMap)
/**
* @see com.twitter.finagle.Address.Failed
*/
def newFailedAddress(cause: Throwable): Address =
Address.Failed(cause)
}
| lukiano/finagle | finagle-core/src/main/scala/com/twitter/finagle/Address.scala | Scala | apache-2.0 | 2,614 |
/**
* Copyright 2015, deepsense.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 io.deepsense.deeplang.params
import spray.json.DefaultJsonProtocol._
import spray.json._
import io.deepsense.deeplang.UnitSpec
import io.deepsense.deeplang.doperations.inout.InputStorageTypeChoice.File
import io.deepsense.deeplang.exceptions.DeepLangException
import io.deepsense.deeplang.params.ParameterType._
import io.deepsense.deeplang.params.choice.{Choice, ChoiceParam}
import io.deepsense.deeplang.params.exceptions.ParamValueNotProvidedException
class ParamsSpec extends UnitSpec {
import ParamsSpec._
"Class with Params" should {
"return array of its params ordered asc by index" in {
val p = WithParams()
p.params should contain theSameElementsInOrderAs Seq(p.param2, p.param1)
}
"validate its params" in {
val p = WithParams()
p.set1(4)
p.validateParams should contain theSameElementsAs
new ParamValueNotProvidedException(nameOfParam2) +: p.param1.validate(4)
}
"describe its params as json ordered as in params Array()" in {
val p = WithParams()
p.paramsToJson shouldBe JsArray(
p.param2.toJson(maybeDefault = None),
p.param1.toJson(maybeDefault = Some(defaultForParam1))
)
}
"describe values of its params as json" in {
val p = WithParams()
p.set1(4)
p.paramValuesToJson shouldBe JsObject(
p.param1.name -> 4.toJson
)
}
"set values of its params from json" when {
"some params get overwritten" in {
val p = WithParams()
p.set1(4)
p.setParamsFromJson(JsObject(
p.param1.name -> 5.toJson,
p.param2.name -> 6.toJson
))
p.get1 shouldBe 5
p.get2 shouldBe 6
}
"json is null" in {
val p = WithParams()
p.set1(4)
p.setParamsFromJson(JsNull)
p.get1 shouldBe 4
}
"value of some param is JsNull" in {
val p = WithParams()
p.set1(4)
p.setParamsFromJson(JsObject(
p.param1.name -> JsNull,
p.param2.name -> 6.toJson
))
p.get1 shouldBe defaultForParam1
p.get2 shouldBe 6
}
"value of some param that doesn't have default is JsNull" in {
val p = WithParams()
p.set2(17)
p.setParamsFromJson(JsObject(
p.param2.name -> JsNull
))
p.is2Defined shouldBe false
}
"ignoreNulls is set" in {
val p = WithParams()
p.set1(4)
p.setParamsFromJson(JsObject(
p.param1.name -> JsNull,
p.param2.name -> 6.toJson
), ignoreNulls = true)
p.get1 shouldBe 4
p.get2 shouldBe 6
}
}
"throw Deserialization exception" when {
"unknown param name is used it should be ignored" in {
val p = WithParams()
p.setParamsFromJson(JsObject(
"unknownName" -> 5.toJson,
p.param2.name -> 6.toJson))
p.get1 shouldBe defaultForParam1
}
}
}
"Params.isSet" should {
"return true" when {
"param value is set" in {
val p = WithParams()
p.set1(3)
p.is1Set shouldBe true
}
}
"return false" when {
"param value is not set" in {
val p = WithParams()
p.is1Set shouldBe false
}
}
}
"Params.isDefined" should {
"return true" when {
"param value is set" in {
val p = WithParams()
p.set1(3)
p.is1Defined shouldBe true
}
"param value is not set, but default value is" in {
val p = WithParams()
p.is1Defined shouldBe true
}
}
"return false" when {
"neither value nor default value is set" in {
val p = WithParams()
p.is2Defined shouldBe false
}
}
}
"Params.clear" should {
"clear param value" in {
val p = WithParams()
p.set1(3)
p.clear1
p.is1Set shouldBe false
}
}
"Params.$" should {
"return param value" when {
"it is defined" in {
val p = WithParams()
p.set1(3)
p.get1 shouldBe 3
}
}
"return default value" when {
"value is not defined, but default is" in {
val p = WithParams()
p.get1 shouldBe defaultForParam1
}
}
"throw exception" when {
"neither param value nor default is defined" in {
val p = WithParams()
val exception = intercept [ParamValueNotProvidedException] {
p.get2
}
exception.name shouldBe p.param2.name
}
}
}
"Params.extractParamMap" should {
"return enriched paramMap" in {
val p = WithParams()
p.set2(8)
val extraParam = MockParam("c")
val extraPair = ParamPair(extraParam, 9)
val extraMap = ParamMap(extraPair)
p.extractParamMap(extraMap) shouldBe ParamMap(
ParamPair(p.param1, defaultForParam1),
ParamPair(p.param2, 8),
extraPair
)
}
}
"Params.sameAs" should {
val valueOne = 100
val valueTwo = 5
"return true" when {
"classes of both objects are the same and object have" +
" the same parameters with the same values" in {
val withParamsA1 = new WithParamsA
val withParamsA2 = new WithParamsA
withParamsA1.sameAs(withParamsA2) shouldBe true
withParamsA1.set1(valueOne)
withParamsA2.set1(valueOne)
withParamsA1.sameAs(withParamsA2) shouldBe true
withParamsA1.set2(valueTwo)
withParamsA2.set2(valueTwo)
withParamsA1.sameAs(withParamsA2) shouldBe true
}
"comparing replicated Params" in {
val withParamsA1 = new WithParamsA
val withParamsA2 = withParamsA1.replicate()
withParamsA1.eq(withParamsA2) shouldBe false
withParamsA1.sameAs(withParamsA2) shouldBe true
}
}
"return false" when {
"classes of both objects are different" in {
val withParamsA = new WithParamsA
val withParamsB = new WithParamsB
withParamsA.sameAs(withParamsB) shouldBe false
}
"parameters have different values" in {
val file1 = new File()
val file2 = new File()
file1.setSourceFile("path")
file1.sameAs(file2) shouldBe false
file1.setSourceFile("path1")
file2.setSourceFile("path2")
file1.sameAs(file2) shouldBe false
}
}
}
}
object ParamsSpec extends UnitSpec {
case class MockException(override val message: String) extends DeepLangException(message)
case class MockParam(name: String) extends Param[Int] {
override val description: Option[String] = Some("description")
override val parameterType: ParameterType = mock[ParameterType]
override def valueToJson(value: Int): JsValue = value.toJson
override def valueFromJson(jsValue: JsValue): Int = jsValue.convertTo[Int]
override def validate(value: Int): Vector[DeepLangException] = Vector(MockException(name))
override def replicate(name: String): MockParam = copy(name = name)
}
val defaultForParam1 = 1
val nameOfParam2 = "name of param2"
// This class also shows how Params trait is to be used
case class WithParams() extends Params {
val param2 = MockParam(nameOfParam2)
val param1 = MockParam("name of param1")
val params: Array[Param[_]] = Array(param2, param1)
def set1(v: Int): this.type = set(param1 -> v)
def set2(v: Int): this.type = set(param2 -> v)
def get1: Int = $(param1)
def get2: Int = $(param2)
def is1Set: Boolean = isSet(param1)
def is1Defined: Boolean = isDefined(param1)
def is2Defined: Boolean = isDefined(param2)
def clear1: this.type = clear(param1)
setDefault(param1 -> defaultForParam1)
}
class WithParamsA extends WithParams
class WithParamsB extends WithParams
case class ParamsWithChoice() extends Params {
val choiceParam = ChoiceParam[ChoiceWithRepeatedParameter](
name = "choice",
description = Some("choice"))
def setChoice(v: ChoiceWithRepeatedParameter): this.type = set(choiceParam, v)
override val params: Array[Param[_]] = Array(choiceParam)
}
sealed trait ChoiceWithRepeatedParameter extends Choice {
override val choiceOrder: List[Class[_ <: ChoiceWithRepeatedParameter]] = List(
classOf[ChoiceOne],
classOf[ChoiceTwo])
}
case class ChoiceOne() extends ChoiceWithRepeatedParameter {
override val name = "one"
val numericParam = NumericParam(
name = "x",
description = Some("numericParam"))
override val params: Array[Param[_]] = Array(numericParam)
}
case class ChoiceTwo() extends ChoiceWithRepeatedParameter {
override val name = "two"
val numericParam = NumericParam(
name = "x",
description = Some("numericParam"))
override val params: Array[Param[_]] = Array(numericParam)
}
object DeclareParamsFixtures {
val outsideParam = MockParam("outside name")
class ParamsFromOutside extends Params {
val param = MockParam("name")
val params: Array[Param[_]] = Array(outsideParam, param)
}
class ParamsWithNotUniqueNames extends Params {
val param1 = MockParam("some name")
val param2 = MockParam(param1.name)
val params: Array[Param[_]] = Array(param1, param2)
}
class NotAllParamsDeclared extends Params {
val param1 = MockParam("some name")
val param2 = MockParam("some other name")
val params: Array[Param[_]] = Array(param1)
}
class ParamsRepeated extends Params {
val param1 = MockParam("some name")
val param2 = MockParam("some other name")
val params: Array[Param[_]] = Array(param1, param2, param1)
}
}
}
| deepsense-io/seahorse-workflow-executor | deeplang/src/test/scala/io/deepsense/deeplang/params/ParamsSpec.scala | Scala | apache-2.0 | 10,275 |
package moe.pizza.auth.graphdb
import org.scalatest.{MustMatchers, WordSpec}
import org.scalatest.mock.MockitoSugar
class EveMapDbSpec extends WordSpec with MustMatchers with MockitoSugar {
"EveMapDb" when {
"being used" should {
"do all of the normal expected things" in {
val e = new EveMapDb("map-tests1")
// initialise the database
e.provisionIfRequired()
e.withGraph { g =>
g.getEdgeType("gate") must not equal (null)
}
// fail gracefully on bad system names
e.getDistanceBetweenSystemsByName("amor", "jota") must equal(None)
// fail gracefully on bad system numbers
e.getDistanceBetweenSystemsById(1, -42) must equal(None)
// correctly find the distance between named systems
e.getDistanceBetweenSystemsByName("Amarr", "Jita") must equal(Some(10))
// correctly find the distance between system ids
e.getDistanceBetweenSystemsById(30000142, 30004711) must equal(
Some(40))
// describe the distance between the same system and itself as 0
e.getDistanceBetweenSystemsById(30000142, 30000142) must equal(Some(0))
e.getDistanceBetweenSystemsByName("Amarr", "Amarr") must equal(Some(0))
e.cleanUp()
}
}
}
}
| xxpizzaxx/pizza-auth-3 | src/test/scala/moe/pizza/auth/graphdb/EveMapDbSpec.scala | Scala | mit | 1,295 |
package spark
import java.io._
import java.net.InetAddress
import java.util.UUID
import java.util.concurrent.{Executors, ThreadFactory, ThreadPoolExecutor}
import scala.collection.mutable.ArrayBuffer
import scala.util.Random
/**
* Various utility methods used by Spark.
*/
object Utils {
def serialize[T](o: T): Array[Byte] = {
val bos = new ByteArrayOutputStream()
val oos = new ObjectOutputStream(bos)
oos.writeObject(o)
oos.close
return bos.toByteArray
}
def deserialize[T](bytes: Array[Byte]): T = {
val bis = new ByteArrayInputStream(bytes)
val ois = new ObjectInputStream(bis)
return ois.readObject.asInstanceOf[T]
}
def deserialize[T](bytes: Array[Byte], loader: ClassLoader): T = {
val bis = new ByteArrayInputStream(bytes)
val ois = new ObjectInputStream(bis) {
override def resolveClass(desc: ObjectStreamClass) =
Class.forName(desc.getName, false, loader)
}
return ois.readObject.asInstanceOf[T]
}
def isAlpha(c: Char) = {
(c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
}
def splitWords(s: String): Seq[String] = {
val buf = new ArrayBuffer[String]
var i = 0
while (i < s.length) {
var j = i
while (j < s.length && isAlpha(s.charAt(j))) {
j += 1
}
if (j > i) {
buf += s.substring(i, j);
}
i = j
while (i < s.length && !isAlpha(s.charAt(i))) {
i += 1
}
}
return buf
}
// Create a temporary directory inside the given parent directory
def createTempDir(root: String = System.getProperty("java.io.tmpdir")): File =
{
var attempts = 0
val maxAttempts = 10
var dir: File = null
while (dir == null) {
attempts += 1
if (attempts > maxAttempts) {
throw new IOException("Failed to create a temp directory " +
"after " + maxAttempts + " attempts!")
}
try {
dir = new File(root, "spark-" + UUID.randomUUID.toString)
if (dir.exists() || !dir.mkdirs()) {
dir = null
}
} catch { case e: IOException => ; }
}
return dir
}
// Copy all data from an InputStream to an OutputStream
def copyStream(in: InputStream,
out: OutputStream,
closeStreams: Boolean = false)
{
val buf = new Array[Byte](8192)
var n = 0
while (n != -1) {
n = in.read(buf)
if (n != -1) {
out.write(buf, 0, n)
}
}
if (closeStreams) {
in.close()
out.close()
}
}
// Shuffle the elements of a collection into a random order, returning the
// result in a new collection. Unlike scala.util.Random.shuffle, this method
// uses a local random number generator, avoiding inter-thread contention.
def randomize[T](seq: TraversableOnce[T]): Seq[T] = {
val buf = new ArrayBuffer[T]()
buf ++= seq
val rand = new Random()
for (i <- (buf.size - 1) to 1 by -1) {
val j = rand.nextInt(i)
val tmp = buf(j)
buf(j) = buf(i)
buf(i) = tmp
}
buf
}
/**
* Get the local host's IP address in dotted-quad format (e.g. 1.2.3.4)
*/
def localIpAddress(): String = InetAddress.getLocalHost.getHostAddress
/**
* Returns a standard ThreadFactory except all threads are daemons
*/
private def newDaemonThreadFactory: ThreadFactory = {
new ThreadFactory {
def newThread(r: Runnable): Thread = {
var t = Executors.defaultThreadFactory.newThread (r)
t.setDaemon (true)
return t
}
}
}
/**
* Wrapper over newCachedThreadPool
*/
def newDaemonCachedThreadPool(): ThreadPoolExecutor = {
var threadPool =
Executors.newCachedThreadPool.asInstanceOf[ThreadPoolExecutor]
threadPool.setThreadFactory (newDaemonThreadFactory)
return threadPool
}
/**
* Wrapper over newFixedThreadPool
*/
def newDaemonFixedThreadPool(nThreads: Int): ThreadPoolExecutor = {
var threadPool =
Executors.newFixedThreadPool(nThreads).asInstanceOf[ThreadPoolExecutor]
threadPool.setThreadFactory(newDaemonThreadFactory)
return threadPool
}
/**
* Get the local machine's hostname
*/
def localHostName(): String = {
return InetAddress.getLocalHost().getHostName
}
}
| jperla/spark-advancers | core/src/main/scala/spark/Utils.scala | Scala | bsd-3-clause | 4,295 |
package au.com.feedbacker.util
import au.com.feedbacker.controllers.Report
import au.com.feedbacker.model.{FeedbackCycle, FeedbackGroup, Nomination, QuestionResponse}
/**
* Created by lachlang on 14/03/2017.
*/
class CsvReport {
def createReportForPerson(report: Report): String = {
s"""Feedback for: ${report.person.name}
| ${serialiseReviewCycles(report.reviewCycle)}
|
""".stripMargin
}
def createReportForCycle(cycle: FeedbackCycle, nominations: Seq[Nomination]): String = {
s"""Feedback for: ${cycle.label}
|${serialiseNominations(nominations)}
|
""".stripMargin
}
private def serialiseReviewCycles(feedback: Seq[FeedbackGroup], output: String = ""): String = {
feedback match {
case Nil => output
case fg::fgs => serialiseReviewCycles(fgs, s"\\n$output\\n\\n${fg.cycle.label},${fg.cycle.endDate}\\n${serialiseNominations(fg.feedback)}")
}
}
private def serialiseNominations(nominations: Seq[Nomination], output: String = ""): String = {
nominations match {
case Nil => output
case n::ns => serialiseNominations(ns, s"$output\\nFeedback from ${n.to.map(_.name).getOrElse("")} for ${n.from.map(_.name).getOrElse("")} on ${n.lastUpdated.getOrElse("not submitted")}\\n${serialiseQuestions(1, n.questions).toString}")
}
}
private def serialiseQuestions(count: Int, questions: Seq[QuestionResponse], qf: QuestionFormat = QuestionFormat()): QuestionFormat = {
questions match {
case Nil => qf
case q::qs => serialiseQuestions(count + 1, qs, QuestionFormat(s"${qf.questionCount},Question ${count}", s"${qf.questionText},${q.text.replace(',',' ')}", s"${qf.response},${q.response.getOrElse("").replace(',',' ')}", s"${qf.comments},${q.comments.getOrElse("").replace(',',' ').replace('\\n',' ')}"))
}
}
}
object CsvReport extends CsvReport
case class QuestionFormat(questionCount: String = "", questionText: String = "", response: String = "", comments: String = "") {
override def toString(): String = s"${this.questionCount}\\n${this.questionText}\\n${this.response}\\n${this.comments}"
}
| lachlang/feedbacker | app/au/com/feedbacker/util/CsvReport.scala | Scala | apache-2.0 | 2,132 |
/*
* Copyright 2016 Nicolas Rinaudo
*
* 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 kantan.codecs.enumeratum
import kantan.codecs.enumeratum.laws.discipline.Enumerated
import kantan.codecs.enumeratum.laws.discipline.arbitrary._
import kantan.codecs.laws.discipline.{StringCodecTests, StringDecoderTests, StringEncoderTests}
import kantan.codecs.laws.discipline.DisciplineSuite
class EnumCodecTests extends DisciplineSuite {
checkAll("StringDecoder[Enumerated]", StringDecoderTests[Enumerated].decoder[Int, Int])
checkAll("StringEncoder[Enumerated]", StringEncoderTests[Enumerated].encoder[Int, Int])
checkAll("StringCodec[Enumerated]", StringCodecTests[Enumerated].codec[Int, Int])
}
| nrinaudo/kantan.codecs | enumeratum/core/shared/src/test/scala/kantan/codecs/enumeratum/EnumCodecTests.scala | Scala | apache-2.0 | 1,218 |
package se.chimps.bitziness.core.generic
import org.scalatest.FunSuite
class ErrorMappingTest extends FunSuite {
val subject = new ErrorMapper
test("Errors go straight through") {
val error = new RuntimeException("Some random error.")
val response = subject.errorMapping(error)
assert(error.equals(response))
}
}
class ErrorMapper extends ErrorMapping[Any] {
override def errorMapping:PartialFunction[Throwable, Any] = {
case e:Throwable => e
}
} | Meduzz/Bitziness | src/test/scala/se/chimps/bitziness/core/generic/ErrorMappingTest.scala | Scala | apache-2.0 | 477 |
/*
* 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.
*/
// scalastyle:off println
package org.apache.spark.examples
import java.util.Random
import breeze.linalg.{Vector, DenseVector}
/**
* Logistic regression based classification.
* 基于逻辑回归的分类
* This is an example implementation for learning how to use Spark. For more conventional use,
* 这是一个学习如何使用Spark的例子实现,为更传统的使用,LogisticRegressionWithSGD(SGD随机梯度下降)
* please refer to either org.apache.spark.mllib.classification.LogisticRegressionWithSGD or
* org.apache.spark.mllib.classification.LogisticRegressionWithLBFGS(BFGS是逆秩2拟牛顿法) based on your needs.
*/
object LocalFileLR {
val D = 10 // Numer of dimensions 维度
val rand = new Random(42)
case class DataPoint(x: Vector[Double], y: Double)
//解析每一行数据,生成DataPoint对像
def parsePoint(line: String): DataPoint = {
val nums = line.split(' ').map(_.toDouble)
DataPoint(new DenseVector(nums.slice(1, D + 1)), nums(0))
}
def showWarning() {
System.err.println(
"""WARN: This is a naive implementation of Logistic Regression and is given as an example!
|Please use either org.apache.spark.mllib.classification.LogisticRegressionWithSGD or
|org.apache.spark.mllib.classification.LogisticRegressionWithLBFGS(BFGS是逆秩2拟牛顿法)
|for more conventional use.
""".stripMargin)
}
def main(args: Array[String]) {
showWarning()
//fromFile读取文件,转换成Array[String]
val lines = scala.io.Source.fromFile(args(0)).getLines().toArray
//调用parsePoint解析每一行数据
val points = lines.map(parsePoint _)
val ITERATIONS = args(1).toInt
// Initialize w to a random value
//初始化W到一个随机值数组
var w = DenseVector.fill(D){2 * rand.nextDouble - 1}
println("Initial w: " + w)
for (i <- 1 to ITERATIONS) {
println("On iteration " + i)
var gradient = DenseVector.zeros[Double](D)
for (p <- points) {
val scale = (1 / (1 + math.exp(-p.y * (w.dot(p.x)))) - 1) * p.y
gradient += p.x * scale
}
w -= gradient
}
println("Final w: " + w)
}
}
// scalastyle:on println | tophua/spark1.52 | examples/src/main/scala/org/apache/spark/examples/LocalFileLR.scala | Scala | apache-2.0 | 3,017 |
package im.actor.server.api.rpc.service.auth
import java.time.{ ZoneOffset, LocalDateTime }
import im.actor.server.acl.ACLUtils
import im.actor.util.log.AnyRefLogSource
import scala.concurrent._, duration._
import scala.concurrent.forkjoin.ThreadLocalRandom
import scala.language.postfixOps
import scalaz._
import akka.actor.{ ActorRef, ActorSystem }
import akka.event.Logging
import akka.util.Timeout
import org.joda.time.DateTime
import shapeless._
import slick.dbio.DBIO
import slick.driver.PostgresDriver.api._
import im.actor.api.rpc.DBIOResult._
import im.actor.api.rpc._
import im.actor.api.rpc.auth.ApiEmailActivationType._
import im.actor.api.rpc.auth._
import im.actor.api.rpc.misc._
import im.actor.api.rpc.users.ApiSex.ApiSex
import im.actor.server.activation.internal.CodeActivation
import im.actor.server.db.DbExtension
import im.actor.server.oauth.{ OAuth2ProvidersDomains, GoogleProvider }
import im.actor.server.persist.auth.AuthTransaction
import im.actor.server.sequence.SeqUpdatesExtension
import im.actor.server.session._
import im.actor.server.social.{ SocialExtension, SocialManagerRegion }
import im.actor.util.misc.PhoneNumberUtils._
import im.actor.server.user.{ UserViewRegion, UserExtension, UserOffice, UserProcessorRegion }
import im.actor.util.misc._
import im.actor.server.{ persist, models }
case class PubSubMediator(mediator: ActorRef)
class AuthServiceImpl(val activationContext: CodeActivation, mediator: ActorRef)(
implicit
val sessionRegion: SessionRegion,
val actorSystem: ActorSystem,
val oauth2Service: GoogleProvider
) extends AuthService with AuthHelpers with Helpers {
import AnyRefLogSource._
import IdUtils._
private trait SignType
private case class Up(name: String, isSilent: Boolean) extends SignType
private case object In extends SignType
override implicit val ec: ExecutionContext = actorSystem.dispatcher
protected implicit val db: Database = DbExtension(actorSystem).db
protected implicit val seqUpdExt: SeqUpdatesExtension = SeqUpdatesExtension(actorSystem)
protected implicit val userProcessorRegion: UserProcessorRegion = UserExtension(actorSystem).processorRegion
protected implicit val userViewRegion: UserViewRegion = UserExtension(actorSystem).viewRegion
protected implicit val socialRegion: SocialManagerRegion = SocialExtension(actorSystem).region
protected val log = Logging(actorSystem, this)
private val maxGroupSize: Int = 300
implicit val mediatorWrap = PubSubMediator(mediator)
implicit protected val timeout = Timeout(10 seconds)
override def jhandleGetAuthSessions(clientData: ClientData): Future[HandlerResult[ResponseGetAuthSessions]] = {
val authorizedAction = requireAuth(clientData).map { client ⇒
for {
sessionModels ← persist.AuthSession.findByUserId(client.userId)
} yield {
val sessionStructs = sessionModels map { sessionModel ⇒
val authHolder =
if (client.authId == sessionModel.authId) {
ApiAuthHolder.ThisDevice
} else {
ApiAuthHolder.OtherDevice
}
ApiAuthSession(
sessionModel.id,
authHolder,
sessionModel.appId,
sessionModel.appTitle,
sessionModel.deviceTitle,
(sessionModel.authTime.getMillis / 1000).toInt,
sessionModel.authLocation,
sessionModel.latitude,
sessionModel.longitude
)
}
Ok(ResponseGetAuthSessions(sessionStructs.toVector))
}
}
db.run(toDBIOAction(authorizedAction))
}
def jhandleCompleteOAuth2(transactionHash: String, code: String, clientData: ClientData): Future[HandlerResult[ResponseAuth]] = {
val action: Result[ResponseAuth] =
for {
transaction ← fromDBIOOption(AuthErrors.InvalidAuthTransaction)(persist.auth.AuthEmailTransaction.find(transactionHash))
token ← fromDBIOOption(AuthErrors.FailedToGetOAuth2Token)(oauth2Service.completeOAuth(code, transaction.email, transaction.redirectUri))
profile ← fromFutureOption(AuthErrors.FailedToGetOAuth2Token)(oauth2Service.fetchProfile(token.accessToken))
_ ← fromBoolean(AuthErrors.OAuthUserIdDoesNotMatch)(transaction.email == profile.email)
_ ← fromDBIO(persist.OAuth2Token.createOrUpdate(token))
_ ← fromDBIO(AuthTransaction.updateSetChecked(transactionHash))
email ← fromDBIOOption(AuthErrors.EmailUnoccupied)(persist.UserEmail.find(transaction.email))
user ← authorizeT(email.userId, profile.locale.getOrElse(""), clientData)
userStruct ← fromDBIO(DBIO.from(UserOffice.getApiStruct(user.id, user.id, clientData.authId)))
//refresh session data
authSession = models.AuthSession(
userId = user.id,
id = nextIntId(ThreadLocalRandom.current()),
authId = clientData.authId,
appId = transaction.appId,
appTitle = models.AuthSession.appTitleOf(transaction.appId),
deviceHash = transaction.deviceHash,
deviceTitle = transaction.deviceTitle,
authTime = DateTime.now,
authLocation = "",
latitude = None,
longitude = None
)
_ ← fromDBIO(refreshAuthSession(transaction.deviceHash, authSession))
_ ← fromDBIO(persist.auth.AuthTransaction.delete(transactionHash))
ack ← fromFuture(authorize(user.id, clientData))
} yield ResponseAuth(userStruct, misc.ApiConfig(maxGroupSize))
db.run(action.run)
}
def jhandleGetOAuth2Params(transactionHash: String, redirectUrl: String, clientData: ClientData): Future[HandlerResult[ResponseGetOAuth2Params]] = {
val action =
for {
transaction ← fromDBIOOption(AuthErrors.InvalidAuthTransaction)(persist.auth.AuthEmailTransaction.find(transactionHash))
url ← fromOption(AuthErrors.RedirectUrlInvalid)(oauth2Service.getAuthUrl(redirectUrl, transaction.email))
_ ← fromDBIO(persist.auth.AuthEmailTransaction.updateRedirectUri(transaction.transactionHash, redirectUrl))
} yield ResponseGetOAuth2Params(url)
db.run(action.run)
}
def jhandleStartPhoneAuth(phoneNumber: Long, appId: Int, apiKey: String, deviceHash: Array[Byte], deviceTitle: String, clientData: ClientData): Future[HandlerResult[ResponseStartPhoneAuth]] = {
val action = for {
normalizedPhone ← fromOption(AuthErrors.PhoneNumberInvalid)(normalizeLong(phoneNumber).headOption)
optAuthTransaction ← fromDBIO(persist.auth.AuthPhoneTransaction.findByPhoneAndDeviceHash(normalizedPhone, deviceHash))
transactionHash ← optAuthTransaction match {
case Some(transaction) ⇒ point(transaction.transactionHash)
case None ⇒
val accessSalt = ACLUtils.nextAccessSalt()
val transactionHash = ACLUtils.authTransactionHash(accessSalt)
val phoneAuthTransaction = models.AuthPhoneTransaction(normalizedPhone, transactionHash, appId, apiKey, deviceHash, deviceTitle, accessSalt)
for {
_ ← fromDBIO(persist.auth.AuthPhoneTransaction.create(phoneAuthTransaction))
_ ← fromDBIO(sendSmsCode(normalizedPhone, genSmsCode(normalizedPhone), Some(transactionHash)))
} yield transactionHash
}
isRegistered ← fromDBIO(persist.UserPhone.exists(normalizedPhone))
} yield ResponseStartPhoneAuth(transactionHash, isRegistered)
db.run(action.run)
}
def jhandleSignUp(transactionHash: String, name: String, sex: Option[ApiSex], clientData: ClientData): Future[HandlerResult[ResponseAuth]] = {
val action: Result[ResponseAuth] =
for {
//retrieve `authTransaction`
transaction ← fromDBIOOption(AuthErrors.InvalidAuthTransaction)(persist.auth.AuthTransaction.findChildren(transactionHash))
//ensure that `authTransaction` is checked
_ ← fromBoolean(AuthErrors.NotValidated)(transaction.isChecked)
signInORsignUp ← transaction match {
case p: models.AuthPhoneTransaction ⇒ newUserPhoneSignUp(p, name, sex)
case e: models.AuthEmailTransaction ⇒ newUserEmailSignUp(e, name, sex)
}
//fallback to sign up if user exists
user ← signInORsignUp match {
case -\\/((userId, countryCode)) ⇒ authorizeT(userId, countryCode, clientData)
case \\/-(user) ⇒ handleUserCreate(user, transaction, clientData.authId)
}
userStruct ← fromDBIO(DBIO.from(UserOffice.getApiStruct(user.id, user.id, clientData.authId)))
//refresh session data
authSession = models.AuthSession(
userId = user.id,
id = nextIntId(ThreadLocalRandom.current()),
authId = clientData.authId,
appId = transaction.appId,
appTitle = models.AuthSession.appTitleOf(transaction.appId),
deviceHash = transaction.deviceHash,
deviceTitle = transaction.deviceTitle,
authTime = DateTime.now,
authLocation = "",
latitude = None,
longitude = None
)
_ ← fromDBIO(refreshAuthSession(transaction.deviceHash, authSession))
ack ← fromFuture(authorize(user.id, clientData))
} yield ResponseAuth(userStruct, misc.ApiConfig(maxGroupSize))
db.run(action.run)
}
def jhandleStartEmailAuth(email: String, appId: Int, apiKey: String, deviceHash: Array[Byte], deviceTitle: String, clientData: ClientData): Future[HandlerResult[ResponseStartEmailAuth]] = {
val action = for {
validEmail ← fromEither(validEmail(email).leftMap(validationFailed("EMAIL_INVALID", _))) //it actually does not change input email
activationType = if (OAuth2ProvidersDomains.supportsOAuth2(email)) OAUTH2 else CODE
isRegistered ← fromDBIO(persist.UserEmail.exists(validEmail))
optTransaction ← fromDBIO(persist.auth.AuthEmailTransaction.findByEmailAndDeviceHash(validEmail, deviceHash))
transactionHash ← optTransaction match {
case Some(trans) ⇒ point(trans.transactionHash)
case None ⇒
val accessSalt = ACLUtils.nextAccessSalt()
val transactionHash = ACLUtils.authTransactionHash(accessSalt)
val emailAuthTransaction = models.AuthEmailTransaction(validEmail, None, transactionHash, appId, apiKey, deviceHash, deviceTitle, accessSalt)
activationType match {
case CODE ⇒
for {
_ ← fromDBIO(persist.auth.AuthEmailTransaction.create(emailAuthTransaction))
_ ← fromDBIO(sendEmailCode(email, genCode(), transactionHash))
} yield transactionHash
case OAUTH2 ⇒
for {
_ ← fromDBIO(persist.auth.AuthEmailTransaction.create(emailAuthTransaction))
} yield transactionHash
}
}
} yield ResponseStartEmailAuth(transactionHash, isRegistered, activationType)
db.run(action.run)
}
//TODO: add email code validation
def jhandleValidateCode(transactionHash: String, code: String, clientData: ClientData): Future[HandlerResult[ResponseAuth]] = {
val action: Result[ResponseAuth] =
for {
//retreive `authTransaction`
transaction ← fromDBIOOption(AuthErrors.InvalidAuthTransaction)(persist.auth.AuthTransaction.findChildren(transactionHash))
//validate code
userAndCounty ← validateCode(transaction, code)
(userId, countryCode) = userAndCounty
//sign in user and delete auth transaction
user ← authorizeT(userId, countryCode, clientData)
userStruct ← fromDBIO(DBIO.from(UserOffice.getApiStruct(user.id, user.id, clientData.authId)))
_ ← fromDBIO(persist.auth.AuthTransaction.delete(transaction.transactionHash))
//refresh session data
authSession = models.AuthSession(
userId = user.id,
id = nextIntId(ThreadLocalRandom.current()),
authId = clientData.authId,
appId = transaction.appId,
appTitle = models.AuthSession.appTitleOf(transaction.appId),
deviceHash = transaction.deviceHash,
deviceTitle = transaction.deviceTitle,
authTime = DateTime.now,
authLocation = "",
latitude = None,
longitude = None
)
_ ← fromDBIO(refreshAuthSession(transaction.deviceHash, authSession))
ack ← fromFuture(authorize(user.id, clientData))
} yield ResponseAuth(userStruct, misc.ApiConfig(maxGroupSize))
db.run(action.run)
}
override def jhandleSignOut(clientData: ClientData): Future[HandlerResult[ResponseVoid]] = {
val action = requireAuth(clientData) map { implicit client ⇒
persist.AuthSession.findByAuthId(client.authId) flatMap {
case Some(session) ⇒
for (_ ← DBIO.from(UserOffice.logout(session))) yield Ok(misc.ResponseVoid)
case None ⇒ throw new Exception(s"Cannot find AuthSession for authId: ${client.authId}")
}
}
db.run(toDBIOAction(action))
}
override def jhandleTerminateAllSessions(clientData: ClientData): Future[HandlerResult[ResponseVoid]] = {
val authorizedAction = requireAuth(clientData).map { client ⇒
for {
sessions ← persist.AuthSession.findByUserId(client.userId) map (_.filterNot(_.authId == client.authId))
_ ← DBIO.from(Future.sequence(sessions map UserOffice.logout))
} yield {
Ok(ResponseVoid)
}
}
db.run(toDBIOAction(authorizedAction))
}
override def jhandleTerminateSession(id: Int, clientData: ClientData): Future[HandlerResult[ResponseVoid]] = {
val authorizedAction = requireAuth(clientData).map { client ⇒
persist.AuthSession.find(client.userId, id).headOption flatMap {
case Some(session) ⇒
for (_ ← DBIO.from(UserOffice.logout(session))) yield Ok(ResponseVoid)
case None ⇒
DBIO.successful(Error(AuthErrors.AuthSessionNotFound))
}
}
db.run(toDBIOAction(authorizedAction))
}
//TODO: move deprecated methods to separate trait
@deprecated("schema api changes", "2015-06-09")
override def jhandleSendAuthCallObsolete(
phoneNumber: Long,
smsHash: String,
appId: Int,
apiKey: String,
clientData: ClientData
): Future[HandlerResult[ResponseVoid]] =
Future {
throw new Exception("Not implemented")
}
@deprecated("schema api changes", "2015-06-09")
override def jhandleSendAuthCodeObsolete(
rawPhoneNumber: Long,
appId: Int,
apiKey: String,
clientData: ClientData
): Future[HandlerResult[ResponseSendAuthCodeObsolete]] = {
PhoneNumberUtils.normalizeLong(rawPhoneNumber).headOption match {
case None ⇒
Future.successful(Error(AuthErrors.PhoneNumberInvalid))
case Some(normPhoneNumber) ⇒
val action = persist.AuthSmsCodeObsolete.findByPhoneNumber(normPhoneNumber).headOption.flatMap {
case Some(models.AuthSmsCodeObsolete(_, _, smsHash, smsCode, _)) ⇒
DBIO.successful(normPhoneNumber :: smsHash :: smsCode :: HNil)
case None ⇒
val smsHash = genSmsHash()
val smsCode = genSmsCode(normPhoneNumber)
for (
_ ← persist.AuthSmsCodeObsolete.create(
id = ThreadLocalRandom.current().nextLong(),
phoneNumber = normPhoneNumber,
smsHash = smsHash,
smsCode = smsCode
)
) yield (normPhoneNumber :: smsHash :: smsCode :: HNil)
}.flatMap { res ⇒
persist.UserPhone.exists(normPhoneNumber) map (res :+ _)
}.map {
case number :: smsHash :: smsCode :: isRegistered :: HNil ⇒
sendSmsCode(number, smsCode, None)
Ok(ResponseSendAuthCodeObsolete(smsHash, isRegistered))
}
db.run(action)
}
}
@deprecated("schema api changes", "2015-06-09")
override def jhandleSignInObsolete(
rawPhoneNumber: Long,
smsHash: String,
smsCode: String,
deviceHash: Array[Byte],
deviceTitle: String,
appId: Int,
appKey: String,
clientData: ClientData
): Future[HandlerResult[ResponseAuth]] =
handleSign(
In,
rawPhoneNumber, smsHash, smsCode,
deviceHash, deviceTitle, appId, appKey,
clientData
)
@deprecated("schema api changes", "2015-06-09")
override def jhandleSignUpObsolete(
rawPhoneNumber: Long,
smsHash: String,
smsCode: String,
name: String,
deviceHash: Array[Byte],
deviceTitle: String,
appId: Int,
appKey: String,
isSilent: Boolean,
clientData: ClientData
): Future[HandlerResult[ResponseAuth]] =
handleSign(
Up(name, isSilent),
rawPhoneNumber, smsHash, smsCode,
deviceHash, deviceTitle, appId, appKey,
clientData
)
private def handleSign(
signType: SignType,
rawPhoneNumber: Long,
smsHash: String,
smsCode: String,
deviceHash: Array[Byte],
deviceTitle: String,
appId: Int,
appKey: String,
clientData: ClientData
): Future[HandlerResult[ResponseAuth]] = {
normalizeWithCountry(rawPhoneNumber).headOption match {
case None ⇒ Future.successful(Error(AuthErrors.PhoneNumberInvalid))
case Some((normPhoneNumber, countryCode)) ⇒
if (smsCode.isEmpty) Future.successful(Error(AuthErrors.PhoneCodeEmpty))
else {
val action = (for {
optCode ← persist.AuthSmsCodeObsolete.findByPhoneNumber(normPhoneNumber).headOption
optPhone ← persist.UserPhone.findByPhoneNumber(normPhoneNumber).headOption
} yield (optCode :: optPhone :: HNil)).flatMap {
case None :: _ :: HNil ⇒ DBIO.successful(Error(AuthErrors.PhoneCodeExpired))
case Some(smsCodeModel) :: _ :: HNil if smsCodeModel.smsHash != smsHash ⇒
DBIO.successful(Error(AuthErrors.PhoneCodeExpired))
case Some(smsCodeModel) :: _ :: HNil if smsCodeModel.smsCode != smsCode ⇒
DBIO.successful(Error(AuthErrors.PhoneCodeInvalid))
case Some(_) :: optPhone :: HNil ⇒
signType match {
case Up(rawName, isSilent) ⇒
persist.AuthSmsCodeObsolete.deleteByPhoneNumber(normPhoneNumber).andThen(
optPhone match {
// Phone does not exist, register the user
case None ⇒ withValidName(rawName) { name ⇒
val rnd = ThreadLocalRandom.current()
val userId = nextIntId(rnd)
//todo: move this to UserOffice
val user = models.User(userId, ACLUtils.nextAccessSalt(rnd), name, countryCode, models.NoSex, models.UserState.Registered, LocalDateTime.now(ZoneOffset.UTC))
for {
_ ← DBIO.from(UserOffice.create(user.id, user.accessSalt, user.name, user.countryCode, im.actor.api.rpc.users.ApiSex(user.sex.toInt), isBot = false))
_ ← DBIO.from(UserOffice.auth(userId, clientData.authId))
_ ← DBIO.from(UserOffice.addPhone(user.id, normPhoneNumber))
_ ← persist.AvatarData.create(models.AvatarData.empty(models.AvatarData.OfUser, user.id.toLong))
} yield {
\\/-(user :: HNil)
}
}
// Phone already exists, fall back to SignIn
case Some(phone) ⇒
signIn(clientData.authId, phone.userId, countryCode, clientData)
}
)
case In ⇒
optPhone match {
case None ⇒ DBIO.successful(Error(AuthErrors.PhoneNumberUnoccupied))
case Some(phone) ⇒
persist.AuthSmsCodeObsolete.deleteByPhoneNumber(normPhoneNumber).andThen(
signIn(clientData.authId, phone.userId, countryCode, clientData)
)
}
}
}.flatMap {
case \\/-(user :: HNil) ⇒
val rnd = ThreadLocalRandom.current()
val authSession = models.AuthSession(
userId = user.id,
id = nextIntId(rnd),
authId = clientData.authId,
appId = appId,
appTitle = models.AuthSession.appTitleOf(appId),
deviceHash = deviceHash,
deviceTitle = deviceTitle,
authTime = DateTime.now,
authLocation = "",
latitude = None,
longitude = None
)
for {
prevSessions ← persist.AuthSession.findByDeviceHash(deviceHash)
_ ← DBIO.from(Future.sequence(prevSessions map UserOffice.logout))
_ ← persist.AuthSession.create(authSession)
userStruct ← DBIO.from(UserOffice.getApiStruct(user.id, user.id, clientData.authId))
} yield {
Ok(
ResponseAuth(
userStruct,
misc.ApiConfig(maxGroupSize)
)
)
}
case error @ -\\/(_) ⇒ DBIO.successful(error)
}
for {
result ← db.run(action)
} yield {
result match {
case Ok(r: ResponseAuth) ⇒
sessionRegion.ref ! SessionEnvelope(clientData.authId, clientData.sessionId).withAuthorizeUser(AuthorizeUser(r.user.id))
case _ ⇒
}
result
}
}
}
}
private def signIn(authId: Long, userId: Int, countryCode: String, clientData: ClientData) = {
persist.User.find(userId).headOption.flatMap {
case None ⇒ throw new Exception("Failed to retrieve user")
case Some(user) ⇒
for {
_ ← DBIO.from(UserOffice.changeCountryCode(userId, countryCode))
_ ← DBIO.from(UserOffice.auth(userId, clientData.authId))
} yield \\/-(user :: HNil)
}
}
}
| liruqi/actor-platform | actor-server/actor-rpc-api/src/main/scala/im/actor/server/api/rpc/service/auth/AuthServiceImpl.scala | Scala | mit | 22,439 |
package akka.stream
class TrieMap extends scala.collection.mutable.HashMap
| unicredit/akka.js | akka-js-actor-stream/js/src/main/scala/akka/stream/TrieMap.scala | Scala | bsd-3-clause | 76 |
/***********************************************************************
* Copyright (c) 2013-2019 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.fs.spark
import java.io.Serializable
import com.typesafe.scalalogging.LazyLogging
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.mapreduce.Job
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.geotools.data.{Query, Transaction}
import org.geotools.filter.text.ecql.ECQL
import org.locationtech.geomesa.fs.data.{FileSystemDataStore, FileSystemDataStoreFactory}
import org.locationtech.geomesa.fs.storage.api.StorageMetadata.{StorageFileAction, StorageFilePath}
import org.locationtech.geomesa.fs.storage.common.jobs.StorageConfiguration
import org.locationtech.geomesa.fs.storage.common.jobs.StorageConfiguration.SimpleFeatureAction
import org.locationtech.geomesa.fs.storage.orc.OrcFileSystemStorage
import org.locationtech.geomesa.fs.storage.orc.jobs.{OrcSimpleFeatureActionInputFormat, OrcSimpleFeatureInputFormat}
import org.locationtech.geomesa.parquet.ParquetFileSystemStorage
import org.locationtech.geomesa.parquet.jobs.{ParquetSimpleFeatureActionInputFormat, ParquetSimpleFeatureInputFormat}
import org.locationtech.geomesa.spark.{SpatialRDD, SpatialRDDProvider}
import org.locationtech.geomesa.utils.geotools.FeatureUtils
import org.locationtech.geomesa.utils.io.{WithClose, WithStore}
import org.opengis.feature.simple.SimpleFeature
import org.opengis.filter.Filter
import scala.collection.mutable.{ArrayBuffer, ListBuffer}
class FileSystemRDDProvider extends SpatialRDDProvider with LazyLogging {
override def canProcess(params: java.util.Map[String, _ <: Serializable]): Boolean =
FileSystemDataStoreFactory.canProcess(params)
override def rdd(
conf: Configuration,
sc: SparkContext,
params: Map[String, String],
query: Query): SpatialRDD = {
WithStore[FileSystemDataStore](params) { ds =>
val sft = ds.getSchema(query.getTypeName)
val storage = ds.storage(query.getTypeName)
def runQuery(filter: Filter, paths: Seq[StorageFilePath], modifications: Boolean): RDD[SimpleFeature] = {
// note: file input format requires a job object, but conf gets copied in job object creation,
// so we have to copy the file paths back out
val job = Job.getInstance(conf)
// note: we have to copy all the conf twice?
FileInputFormat.setInputPaths(job, paths.map(_.path): _*)
conf.set(FileInputFormat.INPUT_DIR, job.getConfiguration.get(FileInputFormat.INPUT_DIR))
// configure the input format for the storage type
// we have two input formats for each, depending if we need to do a reduce step or not
val (base, action) = if (storage.metadata.encoding == OrcFileSystemStorage.Encoding) {
OrcSimpleFeatureInputFormat.configure(conf, sft, query.getFilter, query.getPropertyNames)
(classOf[OrcSimpleFeatureInputFormat], classOf[OrcSimpleFeatureActionInputFormat])
} else if (storage.metadata.encoding == ParquetFileSystemStorage.Encoding) {
ParquetSimpleFeatureInputFormat.configure(conf, sft, query)
(classOf[ParquetSimpleFeatureInputFormat], classOf[ParquetSimpleFeatureActionInputFormat])
} else {
throw new NotImplementedError(s"Not implemented for encoding '${storage.metadata.encoding}'")
}
if (modifications) {
StorageConfiguration.setPathActions(conf, paths)
val rdd = sc.newAPIHadoopRDD(conf, action, classOf[SimpleFeatureAction], classOf[SimpleFeature])
// group updates by feature ID, then take the most recent
rdd.groupBy(_._1.id).flatMap { case (_, group) =>
val (action, sf) = group.minBy(_._1)
if (action.action == StorageFileAction.Delete) { None } else { Some(sf) }
}
} else {
sc.newAPIHadoopRDD(conf, base, classOf[Void], classOf[SimpleFeature]).map(_._2)
}
}
// split up the job by the filters required and partitions that require sequential reads
// if a partition has modifications, it must be read separately to ensure they are handled correctly
val partitioned = ArrayBuffer.empty[(String, Filter, Seq[StorageFilePath], Boolean)]
storage.getPartitionFilters(query.getFilter).foreach { fp =>
val defaults = ListBuffer.empty[StorageFilePath]
val defaultPartitions = ListBuffer.empty[String]
fp.partitions.foreach { p =>
val files = storage.getFilePaths(p)
if (files.nonEmpty) {
if (files.forall(_.file.action == StorageFileAction.Append)) {
defaults ++= files
defaultPartitions += p
} else {
logger.warn(s"Found modifications for partition '$p': " +
"compact the partition to improve read performance")
partitioned += ((p, fp.filter, files, true))
}
}
}
if (defaults.nonEmpty) {
partitioned += ((defaultPartitions.mkString("', '"), fp.filter, defaults, false))
}
}
val rdd = if (partitioned.isEmpty) {
logger.debug("Reading 0 partitions")
sc.emptyRDD[SimpleFeature]
} else {
val rdds = partitioned.map { case (names, filter, files, modifications) =>
logger.debug(s"Reading partitions '$names' with ${files.length} files with filter: ${ECQL.toCQL(filter)}")
runQuery(filter, files, modifications)
}
rdds.reduceLeft(_ union _)
}
SpatialRDD(rdd, sft)
}
}
override def save(rdd: RDD[SimpleFeature], params: Map[String, String], typeName: String): Unit = {
WithStore[FileSystemDataStore](params) {ds =>
require(ds.getSchema(typeName) != null,
"Feature type must exist before calling save. Call createSchema on the DataStore first.")
}
rdd.foreachPartition { iter =>
WithStore[FileSystemDataStore](params) { ds =>
WithClose(ds.getFeatureWriterAppend(typeName, Transaction.AUTO_COMMIT)) { writer =>
iter.foreach(FeatureUtils.write(writer, _, useProvidedFid = true))
}
}
}
}
}
| elahrvivaz/geomesa | geomesa-fs/geomesa-fs-spark/src/main/scala/org/locationtech/geomesa/fs/spark/FileSystemRDDProvider.scala | Scala | apache-2.0 | 6,613 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2016 Algolia
* http://www.algolia.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package algolia.responses
import algolia.objects.{EventsScoring, FacetsScoring}
case class SetStrategyResponse(status: Int, message: String)
case class GetStrategyResponse(
eventsScoring: Option[Seq[EventsScoring]],
facetsScoring: Option[Seq[FacetsScoring]],
personalizationImpact: Option[Int]
)
case class SetStrategyResult(updatedAt: String)
/**
* User profile built from Personalization strategy.
*
* @param userToken the user token representing the user and associated data
* @param lastEventAt the last processed event timestamp using the ISO 8601 format.
* @param scores The profile is structured by facet name used in the strategy. Each facet value is mapped to its score.
* Each score represents the user affinity for a specific facet value given the userToken past events and
* the Personalization strategy defined. Scores are bounded to 20.
*/
case class PersonalizationProfileResponse(
userToken: String,
lastEventAt: String,
scores: Map[String, Any]
)
/**
* Delete the user profile response.
*
* @param userToken the user token representing the user and associated data
* @param deletedUntil date until which the data can safely be considered as deleted for the given use
*/
case class DeletePersonalizationProfileResponse(
userToken: String,
deletedUntil: String
)
| algolia/algoliasearch-client-scala | src/main/scala/algolia/responses/Personalization.scala | Scala | mit | 2,538 |
/*
* Copyright 2015 LG CNS.
*
* 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 scouter.server.netio.service.net;
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.EOFException
import java.net.Socket
import java.net.SocketTimeoutException
import scouter.io.DataInputX
import scouter.io.DataOutputX
import scouter.net.NetCafe
import scouter.net.RequestCmd
import scouter.net.TcpFlag
import scouter.server.LoginManager
import scouter.server.logs.RequestLogger
import scouter.server.netio.service.ServiceHandlingProxy
import scouter.util.FileUtil
import scouter.util.Hexa32
import scouter.server.Configure
object ServiceWorker {
var workers = 0;
def inc() {
this.synchronized {
workers += 1;
}
}
def desc() {
this.synchronized {
workers -= 1;
}
}
def getActiveCount(): Int = {
workers;
}
}
class ServiceWorker(_socket: Socket) extends Runnable {
var socket = _socket;
val in = new DataInputX(new BufferedInputStream(socket.getInputStream()));
val out = new DataOutputX(new BufferedOutputStream(socket.getOutputStream()));
val conf = Configure.getInstance()
override def run() {
var remoteAddr = ""
try {
remoteAddr = "" + socket.getRemoteSocketAddress()
val cafe = in.readInt();
cafe match {
case NetCafe.TCP_AGENT | NetCafe.TCP_AGENT_V2 =>
val objHash = in.readInt()
val num = TcpAgentManager.add(objHash, new TcpAgentWorker(socket, in, out, cafe))
if (conf.debug_net) {
println("Agent : " + remoteAddr + " open [" + Hexa32.toString32(objHash) + "] #" + num);
}
return
case NetCafe.TCP_CLIENT =>
if (conf.debug_net) {
println("Client : " + remoteAddr + " open #" + (ServiceWorker.getActiveCount() + 1));
}
case _ =>
if (conf.debug_net) {
println("Unknown : " + remoteAddr + " drop");
}
FileUtil.close(in);
FileUtil.close(out);
FileUtil.close(socket);
return
}
} catch {
case _: Throwable =>
FileUtil.close(in);
FileUtil.close(out);
FileUtil.close(socket);
return
}
try {
ServiceWorker.inc();
while (true) {
val cmd = in.readText();
if (RequestCmd.CLOSE.equals(cmd)) {
return
}
val session = in.readLong();
val login = LoginManager.okSession(session);
RequestLogger.getInstance().add(cmd, session);
ServiceHandlingProxy.process(cmd, in, out, login);
out.writeByte(TcpFlag.NoNEXT);
out.flush();
}
} catch {
case ne: NullPointerException =>
if (conf.debug_net) {
println("Client : " + remoteAddr + " closed");
ne.printStackTrace();
}
case e: EOFException =>
if (conf.debug_net) {
println("Client : " + remoteAddr + " closed");
}
case se: SocketTimeoutException =>
if (conf.debug_net) {
println("Client : " + remoteAddr + " closed");
se.printStackTrace();
}
case e: Exception =>
if (conf.debug_net) {
println("Client : " + remoteAddr + " closed " + e + " workers=" + ServiceWorker.getActiveCount());
}
case t: Throwable => t.printStackTrace();
} finally {
FileUtil.close(in);
FileUtil.close(out);
FileUtil.close(socket);
ServiceWorker.desc();
}
}
} | sncap/scouter | scouter.server/src/scouter/server/netio/service/net/TcpServiceWorker.scala | Scala | apache-2.0 | 4,669 |
/**
* Copyright (C) 2014 Orbeon, Inc.
*
* This program 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 program 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.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.fb
import org.junit.Test
import org.orbeon.oxf.fr.DataMigration
import org.orbeon.oxf.resources.URLFactory
import org.orbeon.oxf.test.{XMLSupport, DocumentTestBase}
import org.orbeon.oxf.util.{ScalaUtils, XPath}
import org.orbeon.oxf.xml.TransformerUtils
import org.orbeon.saxon.om.NodeInfo
import org.scalatest.junit.AssertionsForJUnit
import org.orbeon.scaxon.XML._
class MigrationTest extends DocumentTestBase with FormBuilderSupport with XMLSupport with AssertionsForJUnit {
val MigrationJSON =
"""
|[
| {
| "path": "section-3/section-3-iteration/grid-4",
| "iteration-name": "grid-4-iteration"
| },
| {
| "path": "section-13/grid-6",
| "iteration-name": "grid-6-iteration"
| },
| {
| "path": "section-13/grid-14",
| "iteration-name": "grid-14-iteration"
| },
| {
| "path": "section-8/grid-3",
| "iteration-name": "my-custom-grid-3-iteration"
| },
| {
| "path": "section-23/grid-3",
| "iteration-name": "my-custom-grid-3-iteration"
| }
|]
""".stripMargin
@Test def buildGridMigrationMap(): Unit = {
def readTree(url: String) =
ScalaUtils.useAndClose(URLFactory.createURL(url).openStream()) { is ⇒
TransformerUtils.readTinyTree(XPath.GlobalConfiguration, is, null, false, false)
}
val form = readTree("oxf:/org/orbeon/oxf/fb/form-to-migrate.xhtml")
val toolbox = readTree("oxf:/org/orbeon/oxf/fb/form-to-migrate-library.xml")
val result =
MigrationOps.buildGridMigrationMap(form, Some(toolbox), legacyGridsOnly = false)
import spray.json._
assert(MigrationJSON.asJson === result.asJson)
}
val Data47: NodeInfo =
<form>
<section-1>
<control-1/>
</section-1>
<section-3>
<section-3-iteration>
<control-6/>
<grid-4>
<control-7/>
</grid-4>
<grid-4>
<control-7/>
</grid-4>
<grid-4>
<control-7/>
</grid-4>
</section-3-iteration>
<section-3-iteration>
<control-6/>
<grid-4>
<control-7/>
</grid-4>
<grid-4>
<control-7/>
</grid-4>
<grid-4>
<control-7/>
</grid-4>
</section-3-iteration>
</section-3>
<section-13>
<grid-6>
<control-10/>
<control-11/>
<control-12/>
<control-13/>
</grid-6>
<grid-6>
<control-10/>
<control-11/>
<control-12/>
<control-13/>
</grid-6>
<grid-6>
<control-10/>
<control-11/>
<control-12/>
<control-13/>
</grid-6>
<grid-14>
<control-16/>
</grid-14>
<grid-14>
<control-16/>
</grid-14>
<grid-14>
<control-16/>
</grid-14>
</section-13>
<section-8>
<control-1/>
<grid-3>
<control-8/>
<control-9/>
</grid-3>
<grid-3>
<control-8/>
<control-9/>
</grid-3>
<grid-3>
<control-8/>
<control-9/>
</grid-3>
</section-8>
<section-23>
<control-1/>
<grid-3>
<control-8/>
<control-9/>
</grid-3>
<grid-3>
<control-8/>
<control-9/>
</grid-3>
<grid-3>
<control-8/>
<control-9/>
</grid-3>
</section-23>
</form>
val Data48: NodeInfo =
<form>
<section-1>
<control-1/>
</section-1>
<section-3>
<section-3-iteration>
<control-6/>
<grid-4>
<grid-4-iteration>
<control-7/>
</grid-4-iteration>
<grid-4-iteration>
<control-7/>
</grid-4-iteration>
<grid-4-iteration>
<control-7/>
</grid-4-iteration>
</grid-4>
</section-3-iteration>
<section-3-iteration>
<control-6/>
<grid-4>
<grid-4-iteration>
<control-7/>
</grid-4-iteration>
<grid-4-iteration>
<control-7/>
</grid-4-iteration>
<grid-4-iteration>
<control-7/>
</grid-4-iteration>
</grid-4>
</section-3-iteration>
</section-3>
<section-13>
<grid-6>
<grid-6-iteration>
<control-10/>
<control-11/>
<control-12/>
<control-13/>
</grid-6-iteration>
<grid-6-iteration>
<control-10/>
<control-11/>
<control-12/>
<control-13/>
</grid-6-iteration>
<grid-6-iteration>
<control-10/>
<control-11/>
<control-12/>
<control-13/>
</grid-6-iteration>
</grid-6>
<grid-14>
<grid-14-iteration>
<control-16/>
</grid-14-iteration>
<grid-14-iteration>
<control-16/>
</grid-14-iteration>
<grid-14-iteration>
<control-16/>
</grid-14-iteration>
</grid-14>
</section-13>
<section-8>
<control-1/>
<grid-3>
<my-custom-grid-3-iteration>
<control-8/>
<control-9/>
</my-custom-grid-3-iteration>
<my-custom-grid-3-iteration>
<control-8/>
<control-9/>
</my-custom-grid-3-iteration>
<my-custom-grid-3-iteration>
<control-8/>
<control-9/>
</my-custom-grid-3-iteration>
</grid-3>
</section-8>
<section-23>
<control-1/>
<grid-3>
<my-custom-grid-3-iteration>
<control-8/>
<control-9/>
</my-custom-grid-3-iteration>
<my-custom-grid-3-iteration>
<control-8/>
<control-9/>
</my-custom-grid-3-iteration>
<my-custom-grid-3-iteration>
<control-8/>
<control-9/>
</my-custom-grid-3-iteration>
</grid-3>
</section-23>
</form>
@Test def migrateDataTo(): Unit =
assertXMLDocumentsIgnoreNamespacesInScope(
Data48.root,
DataMigration.migrateDataTo(Data47.root, MigrationJSON)
)
@Test def migrateDataFrom(): Unit =
assertXMLDocumentsIgnoreNamespacesInScope(
Data47.root,
DataMigration.migrateDataFrom(Data48.root, MigrationJSON)
)
@Test def roundTripData(): Unit =
assertXMLDocumentsIgnoreNamespacesInScope(
Data47.root,
DataMigration.migrateDataFrom(DataMigration.migrateDataTo(Data47.root, MigrationJSON), MigrationJSON)
)
// TODO: annotate.xpl migrations
}
| martinluther/orbeon-forms | src/test/scala/org/orbeon/oxf/fb/MigrationTest.scala | Scala | lgpl-2.1 | 9,742 |
package ch.wsl.box.rest.routes
import akka.actor.ActorSystem
import akka.http.scaladsl.marshalling.ToResponseMarshaller
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, MediaTypes, StatusCodes}
import akka.http.scaladsl.model.headers.{ContentDispositionTypes, `Content-Disposition`, `Content-Type`}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.stream.Materializer
import akka.util.ByteString
import ch.wsl.box.jdbc.Connection
import ch.wsl.box.model.shared._
import ch.wsl.box.rest.html.Html
import ch.wsl.box.rest.jdbc.JdbcConnect
import ch.wsl.box.rest.utils.{JSONSupport, UserProfile}
import io.circe.Json
import io.circe.parser.parse
import io.circe._
import io.circe.generic.auto._
import io.circe.syntax._
import scribe.Logging
import ch.wsl.box.jdbc.PostgresProfile.api._
import ch.wsl.box.model.shared.{DataResult, DataResultObject, DataResultTable}
import ch.wsl.box.rest.metadata.DataMetadataFactory
import ch.wsl.box.rest.io.pdf.Pdf
import ch.wsl.box.rest.io.shp.ShapeFileWriter
import ch.wsl.box.services.Services
import scala.concurrent.{ExecutionContext, Future}
case class DataContainer(result: DataResult, presenter: Option[String], mode: String) {
def asTable: DataResultTable = result.asInstanceOf[DataResultTable]
def asObj: Json = result match {
case t: DataResultTable => Map("data" -> t.json).asJson
case o: DataResultObject => Map("data" -> o.obj).asJson
}
}
trait Data extends Logging {
import ch.wsl.box.shared.utils.JSONUtils._
import JSONSupport._
import ch.wsl.box.shared.utils.Formatters._
import io.circe.generic.auto._
def metadataFactory(implicit up: UserProfile, mat: Materializer, ec: ExecutionContext, services: Services): DataMetadataFactory
def data(function: String, params: Json, lang: String)(implicit up: UserProfile, mat: Materializer, ec: ExecutionContext, system: ActorSystem, services: Services): Future[Option[DataContainer]]
def render(function: String, params: Json, lang: String)(implicit up: UserProfile, mat: Materializer, ec: ExecutionContext, system: ActorSystem, services: Services) = {
import ch.wsl.box.model.boxentities.BoxFunction._
onSuccess(data(function, params, lang)) {
case Some(dc) if dc.mode == FunctionKind.Modes.TABLE =>
respondWithHeaders(`Content-Disposition`(ContentDispositionTypes.attachment, Map("filename" -> s"$function.csv"))) {
{
import kantan.csv._
import kantan.csv.ops._
val csv = (Seq(dc.asTable.headers) ++ dc.asTable.rows.map(_.map(_.string))).asCsv(rfc)
complete(HttpEntity(ContentTypes.`text/csv(UTF-8)`, ByteString(csv)))
}
}
case Some(dc) if dc.mode == FunctionKind.Modes.HTML => {
complete(Html.render(dc.presenter.getOrElse(""), dc.asObj).map(html => HttpEntity(ContentTypes.`text/html(UTF-8)`, html)))
}
case Some(dc) if dc.mode == FunctionKind.Modes.PDF => {
val pdf = for {
html <- Html.render(dc.presenter.getOrElse(""), dc.asObj)
} yield Pdf.render(html)
respondWithHeaders(`Content-Disposition`(ContentDispositionTypes.attachment, Map("filename" -> s"$function.pdf"))) {
complete(pdf.map(p => HttpEntity(MediaTypes.`application/pdf`, p)))
}
}
case Some(dc) if dc.mode == FunctionKind.Modes.SHP => {
val shp: Future[Array[Byte]] = ShapeFileWriter.writeShapeFile(function,dc.asTable)
respondWithHeaders(`Content-Disposition`(ContentDispositionTypes.attachment, Map("filename" -> s"$function.zip"))) {
complete(shp.map(p => HttpEntity(MediaTypes.`application/zip`, p)))
}
}
case _ => complete(StatusCodes.BadRequest)
}
}
def route(implicit up: UserProfile, ec: ExecutionContext, mat: Materializer, system: ActorSystem, services: Services): Route = {
pathPrefix("list") {
// complete(JSONExportMetadataFactory().list)
path(Segment) { lang =>
get {
complete(metadataFactory.list(lang))
}
}
} ~
pathPrefix(Segment) { function =>
pathPrefix("def") {
// complete(JSONExportMetadataFactory().list)
path(Segment) { lang =>
get {
complete(metadataFactory.defOf(function, lang))
}
}
}
} ~
// pathPrefix("") {
pathPrefix(Segment) { function =>
pathPrefix("metadata") {
path(Segment) { lang =>
get {
complete(metadataFactory.of(services.connection.dbSchema, function, lang))
}
}
} ~
pathPrefix(Segment) { lang =>
path("raw") {
post {
entity(as[Json]) { params =>
import ch.wsl.box.model.shared.DataResultTable._
complete(data(function, params, lang).map(_.map(_.asTable.asJson)))
}
}
} ~
pathEnd {
get {
parameters('q) { q =>
val params = parse(q).right.get.as[Json].right.get
render(function, params, lang)
}
} ~
post {
entity(as[Json]) { params =>
render(function, params, lang)
}
}
}
}
}
// }
}
}
| Insubric/box | server/src/main/scala/ch/wsl/box/rest/routes/Data.scala | Scala | apache-2.0 | 5,472 |
package com.cddcore.carersblog.refactoringAtEnd
import scala.language.implicitConversions
import org.cddcore.engine.Engine
import org.joda.time.DateTime
import org.joda.time.Weeks
import org.junit.runner.RunWith
import org.cddcore.engine.tests.CddJunitRunner
case class TimeLineItem(events: List[(DateRange, TimeLineCalcs.ReasonsOrAmount)]) {
val startDate = events.head._1.from
val endDate = events.last._1.to
lazy val okDays = {
val x = TimeLineCalcs.daysInWhichIWasOk
x(this)
}
lazy val wasOk = okDays > 2
override def toString = s"TimeLineItem($startDate, $endDate, dateRange=\\n ${events.mkString("\\n ")})"
}
@RunWith(classOf[CddJunitRunner])
object TimeLineCalcs {
type ReasonsOrAmount = Either[Double, List[KeyAndParams]]
type TimeLine = List[TimeLineItem]
implicit def stringToDate(x: String) = Xmls.asDate(x)
implicit def toTliInt(x: List[(String, String, Any)]): TimeLineItem =
TimeLineItem(x.collect {
case (from, to, x) => x match {
case num: Int => (DateRange(from, to, "for test"), Left(num.toDouble))
case reason: String => (DateRange(from, to, "for test"), Right(List(KeyAndParams(reason))))
}
})
val daysInWhichIWasOk = Engine[TimeLineItem, Int]().title("Time line item: days in which I was OK").
scenario(List(("2010-3-1", "2010-3-3", 110))).expected(3).
code((tli: TimeLineItem) => tli.events.foldLeft[Int](0)((acc, tuple) => tuple match {
case (dr, Left(d: Double)) => dr.days
case (dr, Right(_)) => 0
})).
scenario(List(("2010-3-1", "2010-3-3", 110))).expected(3).
scenario(List(("2010-3-1", "2010-3-3", "failed"))).expected(0).
scenario(List(("2010-3-1", "2010-3-3", "failed"), ("2010-3-4", "2010-3-5", 0))).expected(2).
build
/** Returns a DatesToBeProcessedTogether and the days that the claim is valid for */
def findTimeLine(c: CarersXmlSituation): TimeLine = {
val dates = Carers.interestingDates(c)
val dayToSplit = DateRanges.sunday
val result = DateRanges.interestingDatesToDateRangesToBeProcessedTogether(dates, dayToSplit)
result.map((dateRangeToBeProcessedTogether: DateRangesToBeProcessedTogether) => {
TimeLineItem(dateRangeToBeProcessedTogether.dateRanges.map((dr) => {
val result = Carers.engine(dr.from, c)
(dr, result)
}))
})
}
case class SimplifiedTimeLineItem(startDate: DateTime, amount: Int, reasons: List[KeyAndParams])
implicit def toSimplifiedTlItem(x: (String, Int)) =
SimplifiedTimeLineItem(x._1, x._2, List())
implicit def toSimplifiedTlItemWithReason(x: (String, String)) =
SimplifiedTimeLineItem(x._1, 0, List(KeyAndParams(x._2)))
val simplifyTimeLineEngine = Engine[TimeLine, List[SimplifiedTimeLineItem]]().
useCase("single week").
scenario(List(List(("2010-3-1", "2010-3-3", 110)))).expected(List(("2010-3-1", 110))).
code((t: TimeLine) =>
t.flatMap((tli) => {
val weeks = Weeks.weeksBetween(tli.startDate, tli.endDate).getWeeks
(0 to weeks - 1).map((week) => {
val reasons = tli.events.foldLeft(List[KeyAndParams]())((acc, e) => {
val newList: List[KeyAndParams] = e._2 match {
case Left(num: Double) => List[KeyAndParams]()
case Right(list: List[KeyAndParams]) => list
}
newList ++ acc
})
SimplifiedTimeLineItem(tli.startDate.plusDays(week * 7), tli.wasOk match { case false => 0; case true => 110 }, reasons)
})
})).
scenario(List(List(("2010-3-1", "2010-3-3", 110), ("2010-3-4", "2010-3-6", 110)))).expected(List(("2010-3-1", 110))).
build
def simplifyTimeLine(t: TimeLine) = {
t.flatMap((tli) => {
val weeks = Weeks.weeksBetween(tli.startDate, tli.endDate).getWeeks
(0 to weeks - 1).map((week) => {
val reasons = tli.events.foldLeft(List[ReasonsOrAmount]())((acc, e) => e._2 :: acc)
(tli.startDate.plusDays(week * 7), tli.wasOk match { case false => 0; case true => 110 }, reasons)
})
})
}
} | phil-rice/Carers | src/main/scala/com/cddcore/carersblog/refactoringAtEnd/TimeLine.scala | Scala | bsd-2-clause | 4,037 |
/*
* FFT.scala
* (FScape)
*
* Copyright (c) 2001-2022 Hanns Holger Rutz. All rights reserved.
*
* This software is published under the GNU Affero General Public License v3+
*
*
* For further information, please contact Hanns Holger Rutz at
* contact@sciss.de
*/
package de.sciss.fscape.stream
import de.sciss.fscape.stream.impl.{Complex1FFTStageImpl, Complex1IFFTStageImpl, Real1FFTStageImpl, Real1FullFFTStageImpl, Real1FullIFFTStageImpl, Real1IFFTStageImpl}
/** Real (positive spectrum) forward Short Time Fourier Transform.
* The counter-part of it is `Real1IFFT`.
*
* Useful page: http://calculator.vhex.net/calculator/fast-fourier-transform-calculator-fft/1d-discrete-fourier-transform
*/
object Real1FFT {
def apply(in: OutD, size: OutI, padding: OutI, mode: OutI)(implicit b: Builder): OutD =
new Real1FFTStageImpl(b.layer).connect(in = in, size = size, padding = padding, mode = mode)
}
/** Real (positive spectrum) inverse Short Time Fourier Transform.
* The counter-part of `Real1FFT`.
*/
object Real1IFFT {
def apply(in: OutD, size: OutI, padding: OutI, mode: OutI)(implicit b: Builder): OutD =
new Real1IFFTStageImpl(b.layer).connect(in = in, size = size, padding = padding, mode = mode)
}
/** Real (full spectrum) forward Short Time Fourier Transform.
* This produces a symmetric spectrum (redundant) spectrum, whereas
* `Real1FFT` only produces half of the spectrum.
* The counter-part of it is `Real1FullIFFT`.
*/
object Real1FullFFT {
def apply(in: OutD, size: OutI, padding: OutI)(implicit b: Builder): OutD =
new Real1FullFFTStageImpl(b.layer).connect(in = in, size = size, padding = padding)
}
/** Real (full spectrum) inverse Short Time Fourier Transform.
* This is the counter-part to `Real1FullFFT`. It assumes
* the input is a complex spectrum of a real signal, and after the IFFT
* drops the imaginary part.
*/
object Real1FullIFFT {
def apply(in: OutD, size: OutI, padding: OutI)(implicit b: Builder): OutD =
new Real1FullIFFTStageImpl(b.layer).connect(in = in, size = size, padding = padding)
}
/** Complex forward Short Time Fourier Transform.
* The counter-part of it is `Complex1IFFT`.
*/
object Complex1FFT {
def apply(in: OutD, size: OutI, padding: OutI)(implicit b: Builder): OutD =
new Complex1FFTStageImpl(b.layer).connect(in = in, size = size, padding = padding)
}
/** Complex inverse Short Time Fourier Transform.
* The is the counter-part to `Complex1FFT`.
*/
object Complex1IFFT {
def apply(in: OutD, size: OutI, padding: OutI)(implicit b: Builder): OutD =
new Complex1IFFTStageImpl(b.layer).connect(in = in, size = size, padding = padding)
} | Sciss/FScape-next | core/shared/src/main/scala/de/sciss/fscape/stream/FFT.scala | Scala | agpl-3.0 | 2,677 |
package org.jai.search.actors
import scala.collection.mutable.Map
import org.apache.commons.lang.time.StopWatch
import org.jai.search.config.ElasticSearchIndexConfig
import org.jai.search.data.SampleDataGeneratorService
import org.jai.search.exception.IndexingException
import org.jai.search.index.IndexProductDataService
import org.jai.search.setup.SetupIndexService
import org.slf4j.LoggerFactory
import akka.actor.Actor
import akka.actor.Props
import akka.routing.FromConfig
class SetupIndexMasterActorScala(setupIndexService: SetupIndexService, sampleDataGeneratorService: SampleDataGeneratorService, indexProductDataService: IndexProductDataService) extends Actor {
val LOG = LoggerFactory.getLogger(classOf[SetupIndexMasterActorScala])
private val workerRouter = context.actorOf(Props.create(classOf[SetupIndexWorkerActorScala], setupIndexService, sampleDataGeneratorService, indexProductDataService).withDispatcher("setupIndexWorkerActorDispatcherScala").withRouter(new FromConfig()), "setupIndexWorkerActorScala")
private var allIndexingDone: Boolean = _
private var isRebuildInProgress: Boolean = _
private var startTime : Long = _
private val indexDone: Map[ElasticSearchIndexConfig, Boolean] = scala.collection.mutable.Map()
def receive = {
case message: AnyRef =>
LOG.debug("Master Actor message received is:" + message)
if (message.isInstanceOf[IndexingMessage]) {
handleIndexingMessage(message)
} else if (message.isInstanceOf[ElasticSearchIndexConfig]) {
handleIndexCompletionMessage(message)
} else if (message.isInstanceOf[Exception]) {
handleException(message)
} else {
unhandled(message)
}
}
private def handleIndexCompletionMessage(message: AnyRef) {
indexDone.put(message.asInstanceOf[ElasticSearchIndexConfig], true)
updateIndexDoneState()
}
private def handleException(message: AnyRef) {
val ex = message.asInstanceOf[Exception]
if (ex.isInstanceOf[IndexingException]) {
indexDone += ex.asInstanceOf[IndexingException].getIndexConfig -> true
updateIndexDoneState()
} else {
unhandled(message)
}
}
private def handleIndexingMessage(message: AnyRef) {
val indexingMessage = message.asInstanceOf[IndexingMessage]
if (IndexingMessage.REBUILD_ALL_INDICES == indexingMessage) {
handleIndexingRebuildMessage(message)
} else if (IndexingMessage.REBUILD_ALL_INDICES_DONE == indexingMessage) {
returnAllIndicesCurrentStateAndReset()
} else {
unhandled(message)
}
}
private def handleIndexingRebuildMessage(message: AnyRef) {
if (!isRebuildInProgress) {
startTime = compat.Platform.currentTime
}
if (allIndexingDone && isRebuildInProgress) {
if (compat.Platform.currentTime - startTime > 5 * 60 * 1000) {
isRebuildInProgress = false
startTime = 0
}
}
if (isRebuildInProgress) {
LOG.error("Rebuilding is already in progress, ignoring another rebuild message: {}", message)
} else {
isRebuildInProgress = true
setupIndicesForAll()
}
}
private def updateIndexDoneState() {
var isAllIndexDone = true
for ((key, value) <- indexDone) {
LOG.debug("Indexing setup current status is index: {} status: {}", Array(key, value))
if (!value) {
isAllIndexDone = false
}
}
if (isAllIndexDone) {
allIndexingDone = true
}
}
private def returnAllIndicesCurrentStateAndReset() {
LOG.debug("Master Actor message received for DONE check, status is:" + allIndexingDone)
sender.tell(allIndexingDone, self)
if (allIndexingDone) {
LOG.debug("Indexing setup finished for all indices!")
allIndexingDone = false
indexDone.clear()
isRebuildInProgress = false
// stopWatch.reset()
startTime =0
}
}
private def setupIndicesForAll() {
LOG.debug("Starting fresh Rebuilding of indices!")
for (config <- ElasticSearchIndexConfig.values) {
workerRouter.tell(config, self)
indexDone.put(config, false)
}
}
}
| jaibeermalik/elasticsearch-akka | src/main/scala/org/jai/search/actors/SetupIndexMasterActorScala.scala | Scala | mit | 4,103 |
package game
import play.api.libs.json._
import reactivemongo.bson.{BSONDocumentReader, BSONDocument, BSONDocumentWriter}
import play.api.libs.functional.syntax._
/**
* Created by tomas on 08-08-15.
*/
sealed abstract class Suit(val icon: String, val string: String)
case object Hearts extends Suit("♥", "H")
case object Diamonds extends Suit("♦", "R")
case object Clubs extends Suit("♣", "L")
case object Spades extends Suit("♠", "S")
object Suit {
val Suits = Seq(Hearts, Diamonds, Clubs, Spades)
def fromString(suit: String) = Suits.find(_.string.equalsIgnoreCase(suit))
implicit val suitReads = new Reads[Suit] {
override def reads(json: JsValue): JsResult[Suit] = {
fromString(json.as[String]) match {
case Some(suitUnwrap) => JsSuccess(suitUnwrap)
case None => JsError("Suit not valid")
}
}
}
}
sealed abstract class RankType(val string: String)
case object Normal extends RankType("Normal")
case object Joker extends RankType("Joker")
case object LowerThan extends RankType("LowerThan")
case object WillThrowAwayAllCards extends RankType("WillThrowAwayAllCards")
case object StartAgain extends RankType("StartAgain")
sealed abstract class Rank(val rank: Int, val abbr: String, val rankType: RankType)
case object Two extends Rank(2, "2", StartAgain)
case object Three extends Rank(3, "3", Joker)
case object Four extends Rank(4, "4", Normal)
case object Five extends Rank(5, "5", Normal)
case object Six extends Rank(6, "6", Normal)
case object Seven extends Rank(7, "7", LowerThan)
case object Eight extends Rank(8, "8", Normal)
case object Nine extends Rank(9, "9", Normal)
case object Ten extends Rank(10, "10", WillThrowAwayAllCards)
case object Jack extends Rank(11, "J", Normal)
case object Queen extends Rank(12, "Q", Normal)
case object King extends Rank(13, "K", Normal)
case object Ace extends Rank(14, "A", Normal)
object Rank {
val Ranks = Seq(Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace)
def fromString(rank: String) = Ranks.find(_.abbr.equalsIgnoreCase(rank))
implicit val rankReads = new Reads[Rank] {
override def reads(json: JsValue): JsResult[Rank] = {
fromString(json.as[String]) match {
case Some(suitUnwrap) => JsSuccess(suitUnwrap)
case None => JsError("Rank not valid")
}
}
}
}
case class Card(suit: Suit,
rank: Rank) {
def string = this.suit.icon + this.rank.abbr
def isEqual(otherCard: Card): Boolean = {
this.rank.rank == otherCard.rank.rank && this.suit.string.equals(otherCard.suit.string)
}
def comesAfter(otherCard: Card): Boolean = {
rank.rankType match {
case Normal =>
otherCard.rank.rank >= this.rank.rank
case StartAgain =>
otherCard.rank.rank >= this.rank.rank
case LowerThan =>
otherCard.rank.rank <= this.rank.rank
case _ =>
true
}
}
}
object Card {
def fromKV(kv: JsValue): Option[Card] = {
kv.asOpt[JsObject] match {
case Some(obj) =>
(Suit.fromString((obj \ "suit").as[String]), Rank.fromString((obj \ "rank").as[String])) match {
case (Some(suit), Some(rank)) => Some(Card(suit, rank))
case _ => None
}
case _ => None
}
}
implicit val writesCard: Writes[Card] = new Writes[Card] {
override def writes(card: Card): JsValue = {
Json.obj(
"string" -> card.string,
"suit" -> card.suit.string,
"suitIcon" -> card.suit.icon,
"rank" -> card.rank.abbr
)
}
}
implicit val readsCard: Reads[Card] = (
(JsPath \ "suit").read[Suit] and
(JsPath \ "rank").read[Rank]
)(Card.apply _)
implicit val writesCardBSON = new BSONDocumentWriter[Card] {
def write(card: Card) = BSONDocument(
"suit" -> card.suit.string,
"rank" -> card.rank.abbr
)
}
implicit val readsCardBSON = new BSONDocumentReader[Card] {
override def read(bson: BSONDocument): Card = Card(
Suit.fromString(bson.getAs[String]("suit").get).get,
Rank.fromString(bson.getAs[String]("rank").get).get
)
}
} | tomasharkema/Drie-en.Scala | app/game/Card.scala | Scala | mit | 4,118 |
/*
* Copyright (C) 2009-2018 Lightbend Inc. <https://www.lightbend.com>
*/
package scalaguide.advanced.routing
import org.specs2.mutable.Specification
import play.api.test.{FakeRequest, WithApplication}
class ScalaSirdRouter extends Specification {
//#imports
import play.api.mvc._
import play.api.routing._
import play.api.routing.sird._
//#imports
private def Action(block: => Result)(implicit app: play.api.Application) = app.injector.instanceOf[DefaultActionBuilder].apply(block)
"sird router" should {
"allow a simple match" in new WithApplication {
val Action = app.injector.instanceOf[DefaultActionBuilder]
//#simple
val router = Router.from {
case GET(p"/hello/$to") => Action {
Results.Ok(s"Hello $to")
}
}
//#simple
router.routes.lift(FakeRequest("GET", "/hello/world")) must beSome[Handler]
router.routes.lift(FakeRequest("GET", "/goodbye/world")) must beNone
}
"allow a full path match" in new WithApplication {
val Assets = app.injector.instanceOf[controllers.Assets]
//#full-path
val router = Router.from {
case GET(p"/assets/$file*") =>
Assets.versioned(path = "/public", file = file)
}
//#full-path
router.routes.lift(FakeRequest("GET", "/assets/javascripts/main.js")) must beSome[Handler]
router.routes.lift(FakeRequest("GET", "/foo/bar")) must beNone
}
"allow a regex match" in new WithApplication {
val Action = app.injector.instanceOf[DefaultActionBuilder]
//#regexp
val router = Router.from {
case GET(p"/items/$id<[0-9]+>") => Action {
Results.Ok(s"Item $id")
}
}
//#regexp
router.routes.lift(FakeRequest("GET", "/items/21")) must beSome[Handler]
router.routes.lift(FakeRequest("GET", "/items/foo")) must beNone
}
"allow extracting required query parameters" in new WithApplication {
val Action = app.injector.instanceOf[DefaultActionBuilder]
//#required
val router = Router.from {
case GET(p"/search" ? q"query=$query") => Action {
Results.Ok(s"Searching for $query")
}
}
//#required
router.routes.lift(FakeRequest("GET", "/search?query=foo")) must beSome[Handler]
router.routes.lift(FakeRequest("GET", "/search")) must beNone
}
"allow extracting optional query parameters" in new WithApplication {
val Action = app.injector.instanceOf[DefaultActionBuilder]
//#optional
val router = Router.from {
case GET(p"/items" ? q_o"page=$page") => Action {
val thisPage = page.getOrElse("1")
Results.Ok(s"Showing page $thisPage")
}
}
//#optional
router.routes.lift(FakeRequest("GET", "/items?page=10")) must beSome[Handler]
router.routes.lift(FakeRequest("GET", "/items")) must beSome[Handler]
}
"allow extracting multi value query parameters" in new WithApplication {
val Action = app.injector.instanceOf[DefaultActionBuilder]
//#many
val router = Router.from {
case GET(p"/items" ? q_s"tag=$tags") => Action {
val allTags = tags.mkString(", ")
Results.Ok(s"Showing items tagged: $allTags")
}
}
//#many
router.routes.lift(FakeRequest("GET", "/items?tag=a&tag=b")) must beSome[Handler]
router.routes.lift(FakeRequest("GET", "/items")) must beSome[Handler]
}
"allow extracting multiple query parameters" in new WithApplication {
val Action = app.injector.instanceOf[DefaultActionBuilder]
//#multiple
val router = Router.from {
case GET(p"/items" ? q_o"page=$page"
& q_o"per_page=$perPage") => Action {
val thisPage = page.getOrElse("1")
val pageLength = perPage.getOrElse("10")
Results.Ok(s"Showing page $thisPage of length $pageLength")
}
}
//#multiple
router.routes.lift(FakeRequest("GET", "/items?page=10&per_page=20")) must beSome[Handler]
router.routes.lift(FakeRequest("GET", "/items")) must beSome[Handler]
}
"allow sub extractor" in new WithApplication {
val Action = app.injector.instanceOf[DefaultActionBuilder]
//#int
val router = Router.from {
case GET(p"/items/${int(id)}") => Action {
Results.Ok(s"Item $id")
}
}
//#int
router.routes.lift(FakeRequest("GET", "/items/21")) must beSome[Handler]
router.routes.lift(FakeRequest("GET", "/items/foo")) must beNone
}
"allow sub extractor on a query parameter" in new WithApplication {
val Action = app.injector.instanceOf[DefaultActionBuilder]
//#query-int
val router = Router.from {
case GET(p"/items" ? q_o"page=${int(page)}") => Action {
val thePage = page.getOrElse(1)
Results.Ok(s"Items page $thePage")
}
}
//#query-int
router.routes.lift(FakeRequest("GET", "/items?page=21")) must beSome[Handler]
router.routes.lift(FakeRequest("GET", "/items?page=foo")) must beNone
router.routes.lift(FakeRequest("GET", "/items")) must beSome[Handler]
}
"allow complex extractors" in new WithApplication {
val Action = app.injector.instanceOf[DefaultActionBuilder]
//#complex
val router = Router.from {
case rh @ GET(p"/items/${idString @ int(id)}" ?
q"price=${int(price)}")
if price > 200 =>
Action {
Results.Ok(s"Expensive item $id")
}
}
//#complex
router.routes.lift(FakeRequest("GET", "/items/21?price=400")) must beSome[Handler]
router.routes.lift(FakeRequest("GET", "/items/21?price=foo")) must beNone
router.routes.lift(FakeRequest("GET", "/items/foo?price=400")) must beNone
}
}
}
| Shenker93/playframework | documentation/manual/working/scalaGuide/advanced/routing/code/ScalaSirdRouter.scala | Scala | apache-2.0 | 5,854 |
package io.getquill.context.cassandra
import java.util.{ Date, UUID }
import io.getquill.NamingStrategy
import io.getquill.context.Context
import io.getquill.context.cassandra.encoding.{ CassandraMapper, Encodings }
import java.time.{ Instant, LocalDate }
import scala.reflect.ClassTag
trait CassandraContext[N <: NamingStrategy]
extends Context[CqlIdiom, N]
with Encodings
with UdtMetaDsl
with Ops {
implicit def optionDecoder[T](implicit d: Decoder[T]): Decoder[Option[T]]
implicit def optionEncoder[T](implicit d: Encoder[T]): Encoder[Option[T]]
implicit val stringDecoder: Decoder[String]
implicit val bigDecimalDecoder: Decoder[BigDecimal]
implicit val booleanDecoder: Decoder[Boolean]
implicit val byteDecoder: Decoder[Byte]
implicit val shortDecoder: Decoder[Short]
implicit val intDecoder: Decoder[Int]
implicit val longDecoder: Decoder[Long]
implicit val floatDecoder: Decoder[Float]
implicit val doubleDecoder: Decoder[Double]
implicit val byteArrayDecoder: Decoder[Array[Byte]]
implicit val uuidDecoder: Decoder[UUID]
implicit val timestampDecoder: Decoder[Instant]
implicit val cassandraLocalDateDecoder: Decoder[LocalDate]
implicit val stringEncoder: Encoder[String]
implicit val bigDecimalEncoder: Encoder[BigDecimal]
implicit val booleanEncoder: Encoder[Boolean]
implicit val byteEncoder: Encoder[Byte]
implicit val shortEncoder: Encoder[Short]
implicit val intEncoder: Encoder[Int]
implicit val longEncoder: Encoder[Long]
implicit val floatEncoder: Encoder[Float]
implicit val doubleEncoder: Encoder[Double]
implicit val byteArrayEncoder: Encoder[Array[Byte]]
implicit val uuidEncoder: Encoder[UUID]
implicit val timestampEncoder: Encoder[Instant]
implicit val cassandraLocalDateEncoder: Encoder[LocalDate]
implicit def listDecoder[T, Cas: ClassTag](implicit mapper: CassandraMapper[Cas, T]): Decoder[List[T]]
implicit def setDecoder[T, Cas: ClassTag](implicit mapper: CassandraMapper[Cas, T]): Decoder[Set[T]]
implicit def mapDecoder[K, V, KCas: ClassTag, VCas: ClassTag](
implicit
keyMapper: CassandraMapper[KCas, K],
valMapper: CassandraMapper[VCas, V]
): Decoder[Map[K, V]]
implicit def listEncoder[T, Cas: ClassTag](implicit mapper: CassandraMapper[T, Cas]): Encoder[List[T]]
implicit def setEncoder[T, Cas: ClassTag](implicit mapper: CassandraMapper[T, Cas]): Encoder[Set[T]]
implicit def mapEncoder[K, V, KCas: ClassTag, VCas: ClassTag](
implicit
keyMapper: CassandraMapper[K, KCas],
valMapper: CassandraMapper[V, VCas]
): Encoder[Map[K, V]]
} | getquill/quill | quill-cassandra/src/main/scala/io/getquill/context/cassandra/CassandraContext.scala | Scala | apache-2.0 | 2,578 |
package com.codelab27.cards9.controllers
import com.codelab27.cards9.game.engines
import com.codelab27.cards9.models.common.Common.Color
import com.codelab27.cards9.models.matches.Match
import com.codelab27.cards9.models.matches.Match._
import com.codelab27.cards9.models.players.Player
import com.codelab27.cards9.repos.matches.MatchRepository
import io.kanaka.monadic.dsl._
import cats.Bimonad
import cats.arrow.FunctionK
import cats.data.OptionT
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}
import scala.concurrent.Future
class MatchMakerController[F[_] : Bimonad](
cc: ControllerComponents,
matchRepo: MatchRepository[F]
)(implicit fshandler: FunctionK[F, Future]) extends AbstractController(cc) {
implicit val ec = cc.executionContext
import com.codelab27.cards9.serdes.json.DefaultFormats._
import com.codelab27.cards9.utils.DefaultStepOps._
import cats.syntax.comonad._
import cats.syntax.functor._
private def playingOrWaitingMatches(playerId: Player.Id): F[Seq[Match]] = for {
foundMatches <- matchRepo.findMatchesForPlayer(playerId)
} yield {
foundMatches.filter(engines.matches.isPlayingOrWaiting)
}
def createMatch() = Action.async { implicit request =>
for {
matchId <- OptionT(matchRepo.storeMatch(engines.matches.freshMatch)).step ?| (_ => Conflict("Could not create a new match"))
} yield {
Ok(Json.toJson(matchId))
}
}
def retrieveMatch(matchId: Match.Id) = Action.async { implicit request =>
for {
theMatch <- OptionT(matchRepo.findMatch(matchId)).step ?| (_ => NotFound(s"Could not find match with id ${matchId.value}"))
} yield {
Ok(Json.toJson(theMatch))
}
}
def getMatchesForState(stateOrError: Either[String, MatchState]) = Action.async {
for {
state <- stateOrError ?| (err => BadRequest(err))
} yield {
val foundMatches = matchRepo.findMatches(state)
Ok(Json.toJson(foundMatches.extract))
}
}
private def updateMatch(id: Match.Id)(performUpdate: Match => Option[Match]) = {
Action.async { implicit request =>
for {
theMatch <- OptionT(matchRepo.findMatch(id)).step ?| (_ => NotFound(s"Match with identifier ${id.value} not found"))
updatedMatch <- OptionT.fromOption(performUpdate(theMatch)).step ?| (_ => Conflict(s"Could not perform action on match ${id.value}"))
_ <- OptionT(matchRepo.storeMatch(updatedMatch)).step ?| (_ => Conflict(s"Could not update the match"))
} yield {
Ok(Json.toJson(updatedMatch))
}
}
}
def addPlayer(id: Match.Id, color: Color, playerId: Player.Id) = {
updateMatch(id)(theMatch => engines.matches.addPlayerToMatch(theMatch, color, playerId))
}
def removePlayer(id: Match.Id, color: Color) = {
updateMatch(id)(theMatch => engines.matches.removePlayerFromMatch(theMatch, color))
}
def setReadiness(id: Match.Id, color: Color, isReady: IsReady) = {
updateMatch(id)(theMatch => engines.matches.switchPlayerReadiness(theMatch, color, isReady))
}
}
| Codelab27/cards9-server | app/com/codelab27/cards9/controllers/MatchMakerController.scala | Scala | gpl-2.0 | 3,113 |
package me.frmr.stripe
import net.liftweb.common._
import net.liftweb.json._
import net.liftweb.util._
import net.liftweb.util.Helpers._
import dispatch._, Defaults._
import org.asynchttpclient.Response
/**
* Case class describing a raw response from Stripe, including
* HTTP status code and JValue representation of the payload.
**/
case class StripeResponse(code: Int, json: JValue)
/**
* Response transformer for use with dispatch to turn a Response
* into an instance of StripeResponse.
**/
object AsStripeResponse extends (Response=>StripeResponse) {
def apply(res: Response) = {
StripeResponse(res.getStatusCode(), StripeHelpers.camelifyFieldNames(as.lift.Json(res)))
}
}
/**
* An executor that will talk to Stripe for you. You'll need to
* define an executor in your code that knows about your API key
* in order to talk to Stripe.
*
* StripeExecutors are designed to be used as implicits, so that they
* can be defined once in an application and automatically dropped in
* wherever they're needed. For example, for your application you might
* use the package prefix com.widgets. To put an executor in scope for all
* of your code you'd define a package object containing the executor.
*
* {{{
* package com
* package object widgets {
* implicit val stripeExecutor = new StripeExecutor(myApiKey)
* }
* }}}
**/
class StripeExecutor(
apiKey: String,
includeRaw: Boolean = false,
apiVersion: String = "2016-03-07"
) {
val httpExecutor = Http.default
val baseReq = url("https://api.stripe.com/v1").secure.as_!(apiKey, "") <:<
Map("Stripe-Version" -> apiVersion, "User-Agent" -> ("streifen/" + BuildInfo.version))
implicit val formats = DefaultFormats
/**
* Execute a request against Stripe and get a {{Full(StripeResponse)}} in reponse if things work
* (e.g. return a 200) and a {{Failure}} otherwise.
*
* In general, the primary consumer of this function will be the streifen library itself. External
* code shouldn't need to use this unless it's implementing functionality not supported by
* streifen for some reason.
**/
def execute(request: Req): Future[Box[StripeResponse]] = {
httpExecutor(request > AsStripeResponse).either.map {
case Left(throwable) =>
Failure("Error occured while talking to stripe.", Full(throwable), Empty)
case Right(stripeResponse) =>
Full(stripeResponse)
}
}
protected def handler[T](implicit mf: Manifest[T]): (StripeResponse)=>Box[T] = {
case StripeResponse(200, json) =>
tryo(json.extract[T])
case StripeResponse(code, json) =>
Failure(s"Unexpected $code") ~> json
}
/**
* Execute a request against Stripe and get a fully typed object out of the response if it was
* successful.
*
* In general, the primary consumer of this function will be the streifen library itself. External
* code shouldn't need to use this unless it's implementing functionality not supported by
* streifen for some reason.
**/
def executeFor[T <: StripeObject](request: Req)(implicit mf: Manifest[T]): Future[Box[T]] = {
execute(request).map { futureBox =>
for {
stripeResponse <- futureBox
concreteObject <- handler(mf)(stripeResponse)
} yield {
if (includeRaw) {
concreteObject.withRaw(stripeResponse.json).asInstanceOf[T]
} else {
concreteObject
}
}
}
}
}
| farmdawgnation/streifen | src/main/scala/me/frmr/stripe/StripeExecutor.scala | Scala | apache-2.0 | 3,425 |
package skuber
import java.util.Date
/**
* @author David O'Riordan
*/
case class Pod(
val kind: String ="Pod",
override val apiVersion: String = v1,
val metadata: ObjectMeta,
spec: Option[Pod.Spec] = None,
status: Option[Pod.Status] = None)
extends ObjectResource with Limitable
object Pod {
def named(name: String) = Pod(metadata=ObjectMeta(name=name))
def apply(name: String, spec: Pod.Spec) : Pod = Pod(metadata=ObjectMeta(name=name), spec = Some(spec))
import DNSPolicy._
case class Spec(
containers: List[Container] = List(), // should have at least one member
volumes: List[Volume] = Nil,
restartPolicy: RestartPolicy.RestartPolicy = RestartPolicy.Always,
terminationGracePeriodSeconds: Option[Int] = None,
activeDeadlineSeconds: Option[Int] = None,
dnsPolicy: DNSPolicy.DNSPolicy = Default,
nodeSelector: Map[String, String] = Map(),
serviceAccountName: String ="",
nodeName: String = "",
hostNetwork: Boolean = false,
imagePullSecrets: List[LocalObjectReference] = List()) {
// a few convenience methods for fluently building out a pod spec
def addContainer(c: Container) = { this.copy(containers = c :: containers) }
def addVolume(v: Volume) = { this.copy(volumes = v :: volumes) }
def addNodeSelector(kv: Tuple2[String,String]) = {
this.copy(nodeSelector = this.nodeSelector + kv)
}
def addImagePullSecretRef(ref: String) = {
val loref = LocalObjectReference(ref)
this.copy(imagePullSecrets = loref :: this.imagePullSecrets)
}
def withTerminationGracePeriodSeconds(gp: Int) =
this.copy(terminationGracePeriodSeconds = Some(gp))
def withActiveDeadlineSeconds(ad: Int) =
this.copy(activeDeadlineSeconds = Some(ad))
def withDnsPolicy(dp: DNSPolicy.DNSPolicy) =
this.copy(dnsPolicy=dp)
def withNodeName(nn: String) =
this.copy(nodeName = nn)
def withServiceAccountName(san: String) =
this.copy(serviceAccountName = san)
def withRestartPolicy(rp: RestartPolicy.RestartPolicy) =
this.copy(restartPolicy = rp)
def useHostNetwork = this.copy(hostNetwork=true)
}
object Phase extends Enumeration {
type Phase = Value
val Pending, Running, Succeeded, Failed, Unknown = Value
}
case class Status(
phase: Option[Phase.Phase] = None,
conditions: List[Condition] = Nil,
message: Option[String] = None,
reason: Option[String] = None,
hostIP: Option[String] = None,
podIP: Option[String] = None,
startTime: Option[Timestamp] = None,
containerStatuses: List[Container.Status] = Nil)
case class Condition(_type : String="Ready", status: String)
case class Template(
val kind: String ="PodTemplate",
override val apiVersion: String = v1,
val metadata: ObjectMeta = ObjectMeta(),
spec: Option[Template.Spec] = None)
extends ObjectResource
{
def withResourceVersion(version: String) = this.copy(metadata = metadata.copy(resourceVersion=version))
def addLabel(label: Tuple2[String, String]) : Template = this.copy(metadata = metadata.copy(labels = metadata.labels + label))
def addLabel(label: String) : Template = addLabel(label -> "")
def addLabels(newLabels: Map[String, String]) = this.copy(metadata=metadata.copy(labels = metadata.labels ++ newLabels))
def addAnnotation(anno: Tuple2[String, String]) : Template = this.copy(metadata = metadata.copy(annotations = metadata.annotations + anno))
def addAnnotation(anno: String) : Template = addAnnotation(anno -> "")
def addAnnotations(newAnnos: Map[String, String]) = this.copy(metadata=metadata.copy(annotations = metadata.annotations ++ newAnnos))
def withTemplateSpec(spec: Template.Spec) = this.copy(spec=Some(spec))
def withPodSpec(podSpec: Pod.Spec) = this.copy(spec=Some(Pod.Template.Spec(spec=Some(podSpec))))
}
object Template {
def named(name: String) : Pod.Template =Pod.Template(metadata=ObjectMeta(name=name))
case class Spec(
metadata: ObjectMeta = ObjectMeta(),
spec: Option[Pod.Spec] = None) {
def addLabel(label: Tuple2[String, String]) : Spec = this.copy(metadata = metadata.copy(labels = metadata.labels + label))
def addLabels(newLabels: Map[String, String]) = this.copy(metadata=metadata.copy(labels = metadata.labels ++ newLabels))
def addAnnotation(anno: Tuple2[String, String]) : Spec = this.copy(metadata = metadata.copy(annotations = metadata.annotations + anno))
def addAnnotations(newAnnos: Map[String, String]) = this.copy(metadata=metadata.copy(annotations = metadata.annotations ++ newAnnos))
def addContainer(container: Container) : Spec = {
val newPodSpec = this.spec.getOrElse(Pod.Spec(Nil)).addContainer(container)
this.copy(spec=Some(newPodSpec))
}
def withPodSpec(spec: Pod.Spec): Spec = this.copy(spec=Some(spec))
}
object Spec {
def named(name: String) : Spec = Spec(metadata=ObjectMeta(name=name))
}
}
} | coryfklein/skuber | client/src/main/scala/skuber/Pod.scala | Scala | apache-2.0 | 5,147 |
/*
* Copyright 2011-2018 GatlingCorp (http://gatling.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 io.gatling.http.cache
import com.typesafe.scalalogging.StrictLogging
import io.gatling.core.config.GatlingConfiguration
import io.gatling.core.session.{ Expression, Session }
import io.gatling.commons.validation.SuccessWrapper
class HttpCaches(val configuration: GatlingConfiguration)
extends HttpContentCacheSupport
with PermanentRedirectCacheSupport
with DnsCacheSupport
with LocalAddressSupport
with BaseUrlSupport
with StrictLogging {
val FlushCache: Expression[Session] = _.removeAll(
HttpContentCacheSupport.HttpContentCacheAttributeName,
DnsCacheSupport.DnsNameResolverAttributeName,
PermanentRedirectCacheSupport.HttpPermanentRedirectCacheAttributeName
).success
}
| wiacekm/gatling | gatling-http/src/main/scala/io/gatling/http/cache/HttpCaches.scala | Scala | apache-2.0 | 1,331 |
/*
* 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.hive.thriftserver
import java.security.PrivilegedExceptionAction
import java.util.{Arrays, Map => JMap}
import java.util.concurrent.{Executors, RejectedExecutionException, TimeUnit}
import scala.collection.JavaConverters._
import scala.collection.mutable.ArrayBuffer
import scala.util.control.NonFatal
import org.apache.hadoop.hive.metastore.api.FieldSchema
import org.apache.hadoop.hive.shims.Utils
import org.apache.hive.service.cli._
import org.apache.hive.service.cli.operation.ExecuteStatementOperation
import org.apache.hive.service.cli.session.HiveSession
import org.apache.spark.internal.Logging
import org.apache.spark.sql.{DataFrame, Row => SparkRow, SQLContext}
import org.apache.spark.sql.execution.HiveResult.{getTimeFormatters, toHiveString, TimeFormatters}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.internal.VariableSubstitution
import org.apache.spark.sql.types._
import org.apache.spark.unsafe.types.CalendarInterval
import org.apache.spark.util.{Utils => SparkUtils}
private[hive] class SparkExecuteStatementOperation(
val sqlContext: SQLContext,
parentSession: HiveSession,
statement: String,
confOverlay: JMap[String, String],
runInBackground: Boolean = true,
queryTimeout: Long)
extends ExecuteStatementOperation(parentSession, statement, confOverlay, runInBackground)
with SparkOperation
with Logging {
// If a timeout value `queryTimeout` is specified by users and it is smaller than
// a global timeout value, we use the user-specified value.
// This code follows the Hive timeout behaviour (See #29933 for details).
private val timeout = {
val globalTimeout = sqlContext.conf.getConf(SQLConf.THRIFTSERVER_QUERY_TIMEOUT)
if (globalTimeout > 0 && (queryTimeout <= 0 || globalTimeout < queryTimeout)) {
globalTimeout
} else {
queryTimeout
}
}
private val forceCancel = sqlContext.conf.getConf(SQLConf.THRIFTSERVER_FORCE_CANCEL)
private val substitutorStatement = SQLConf.withExistingConf(sqlContext.conf) {
new VariableSubstitution().substitute(statement)
}
private var result: DataFrame = _
private var iter: FetchIterator[SparkRow] = _
private var dataTypes: Array[DataType] = _
private lazy val resultSchema: TableSchema = {
if (result == null || result.schema.isEmpty) {
new TableSchema(Arrays.asList(new FieldSchema("Result", "string", "")))
} else {
logInfo(s"Result Schema: ${result.schema}")
SparkExecuteStatementOperation.getTableSchema(result.schema)
}
}
def addNonNullColumnValue(
from: SparkRow,
to: ArrayBuffer[Any],
ordinal: Int,
timeFormatters: TimeFormatters): Unit = {
dataTypes(ordinal) match {
case StringType =>
to += from.getString(ordinal)
case IntegerType =>
to += from.getInt(ordinal)
case BooleanType =>
to += from.getBoolean(ordinal)
case DoubleType =>
to += from.getDouble(ordinal)
case FloatType =>
to += from.getFloat(ordinal)
case DecimalType() =>
to += from.getDecimal(ordinal)
case LongType =>
to += from.getLong(ordinal)
case ByteType =>
to += from.getByte(ordinal)
case ShortType =>
to += from.getShort(ordinal)
case BinaryType =>
to += from.getAs[Array[Byte]](ordinal)
// SPARK-31859, SPARK-31861: Date and Timestamp need to be turned to String here to:
// - respect spark.sql.session.timeZone
// - work with spark.sql.datetime.java8API.enabled
// These types have always been sent over the wire as string, converted later.
case _: DateType | _: TimestampType =>
to += toHiveString((from.get(ordinal), dataTypes(ordinal)), false, timeFormatters)
case CalendarIntervalType =>
to += toHiveString(
(from.getAs[CalendarInterval](ordinal), CalendarIntervalType),
false,
timeFormatters)
case _: ArrayType | _: StructType | _: MapType | _: UserDefinedType[_] |
YearMonthIntervalType | _: DayTimeIntervalType =>
to += toHiveString((from.get(ordinal), dataTypes(ordinal)), false, timeFormatters)
}
}
def getNextRowSet(order: FetchOrientation, maxRowsL: Long): RowSet = withLocalProperties {
try {
sqlContext.sparkContext.setJobGroup(statementId, substitutorStatement, forceCancel)
getNextRowSetInternal(order, maxRowsL)
} finally {
sqlContext.sparkContext.clearJobGroup()
}
}
private def getNextRowSetInternal(
order: FetchOrientation,
maxRowsL: Long): RowSet = withLocalProperties {
log.info(s"Received getNextRowSet request order=${order} and maxRowsL=${maxRowsL} " +
s"with ${statementId}")
validateDefaultFetchOrientation(order)
assertState(OperationState.FINISHED)
setHasResultSet(true)
val resultRowSet: RowSet = RowSetFactory.create(getResultSetSchema, getProtocolVersion, false)
if (order.equals(FetchOrientation.FETCH_FIRST)) {
iter.fetchAbsolute(0)
} else if (order.equals(FetchOrientation.FETCH_PRIOR)) {
iter.fetchPrior(maxRowsL)
} else {
iter.fetchNext()
}
resultRowSet.setStartOffset(iter.getPosition)
if (!iter.hasNext) {
resultRowSet
} else {
val timeFormatters = getTimeFormatters
// maxRowsL here typically maps to java.sql.Statement.getFetchSize, which is an int
val maxRows = maxRowsL.toInt
var curRow = 0
while (curRow < maxRows && iter.hasNext) {
val sparkRow = iter.next()
val row = ArrayBuffer[Any]()
var curCol = 0
while (curCol < sparkRow.length) {
if (sparkRow.isNullAt(curCol)) {
row += null
} else {
addNonNullColumnValue(sparkRow, row, curCol, timeFormatters)
}
curCol += 1
}
resultRowSet.addRow(row.toArray.asInstanceOf[Array[Object]])
curRow += 1
}
log.info(s"Returning result set with ${curRow} rows from offsets " +
s"[${iter.getFetchStart}, ${iter.getPosition}) with $statementId")
resultRowSet
}
}
def getResultSetSchema: TableSchema = resultSchema
override def runInternal(): Unit = {
setState(OperationState.PENDING)
logInfo(s"Submitting query '$statement' with $statementId")
HiveThriftServer2.eventManager.onStatementStart(
statementId,
parentSession.getSessionHandle.getSessionId.toString,
statement,
statementId,
parentSession.getUsername)
setHasResultSet(true) // avoid no resultset for async run
if (timeout > 0) {
val timeoutExecutor = Executors.newSingleThreadScheduledExecutor()
timeoutExecutor.schedule(new Runnable {
override def run(): Unit = {
try {
timeoutCancel()
} catch {
case NonFatal(e) =>
setOperationException(new HiveSQLException(e))
logError(s"Error cancelling the query after timeout: $timeout seconds")
} finally {
timeoutExecutor.shutdown()
}
}
}, timeout, TimeUnit.SECONDS)
}
if (!runInBackground) {
execute()
} else {
val sparkServiceUGI = Utils.getUGI()
// Runnable impl to call runInternal asynchronously,
// from a different thread
val backgroundOperation = new Runnable() {
override def run(): Unit = {
val doAsAction = new PrivilegedExceptionAction[Unit]() {
override def run(): Unit = {
registerCurrentOperationLog()
try {
withLocalProperties {
execute()
}
} catch {
case e: HiveSQLException => setOperationException(e)
}
}
}
try {
sparkServiceUGI.doAs(doAsAction)
} catch {
case e: Exception =>
setOperationException(new HiveSQLException(e))
logError("Error running hive query as user : " +
sparkServiceUGI.getShortUserName(), e)
}
}
}
try {
// This submit blocks if no background threads are available to run this operation
val backgroundHandle =
parentSession.getSessionManager().submitBackgroundOperation(backgroundOperation)
setBackgroundHandle(backgroundHandle)
} catch {
case rejected: RejectedExecutionException =>
logError("Error submitting query in background, query rejected", rejected)
setState(OperationState.ERROR)
HiveThriftServer2.eventManager.onStatementError(
statementId, rejected.getMessage, SparkUtils.exceptionString(rejected))
throw HiveThriftServerErrors.taskExecutionRejectedError(rejected)
case NonFatal(e) =>
logError(s"Error executing query in background", e)
setState(OperationState.ERROR)
HiveThriftServer2.eventManager.onStatementError(
statementId, e.getMessage, SparkUtils.exceptionString(e))
throw new HiveSQLException(e)
}
}
}
private def execute(): Unit = {
try {
synchronized {
if (getStatus.getState.isTerminal) {
logInfo(s"Query with $statementId in terminal state before it started running")
return
} else {
logInfo(s"Running query with $statementId")
setState(OperationState.RUNNING)
}
}
// Always use the latest class loader provided by executionHive's state.
val executionHiveClassLoader = sqlContext.sharedState.jarClassLoader
Thread.currentThread().setContextClassLoader(executionHiveClassLoader)
// Always set the session state classloader to `executionHiveClassLoader` even for sync mode
if (!runInBackground) {
parentSession.getSessionState.getConf.setClassLoader(executionHiveClassLoader)
}
sqlContext.sparkContext.setJobGroup(statementId, substitutorStatement, forceCancel)
result = sqlContext.sql(statement)
logDebug(result.queryExecution.toString())
HiveThriftServer2.eventManager.onStatementParsed(statementId,
result.queryExecution.toString())
iter = if (sqlContext.getConf(SQLConf.THRIFTSERVER_INCREMENTAL_COLLECT.key).toBoolean) {
new IterableFetchIterator[SparkRow](new Iterable[SparkRow] {
override def iterator: Iterator[SparkRow] = result.toLocalIterator.asScala
})
} else {
new ArrayFetchIterator[SparkRow](result.collect())
}
dataTypes = result.schema.fields.map(_.dataType)
} catch {
// Actually do need to catch Throwable as some failures don't inherit from Exception and
// HiveServer will silently swallow them.
case e: Throwable =>
// When cancel() or close() is called very quickly after the query is started,
// then they may both call cleanup() before Spark Jobs are started. But before background
// task interrupted, it may have start some spark job, so we need to cancel again to
// make sure job was cancelled when background thread was interrupted
if (statementId != null) {
sqlContext.sparkContext.cancelJobGroup(statementId)
}
val currentState = getStatus().getState()
if (currentState.isTerminal) {
// This may happen if the execution was cancelled, and then closed from another thread.
logWarning(s"Ignore exception in terminal state with $statementId: $e")
} else {
logError(s"Error executing query with $statementId, currentState $currentState, ", e)
setState(OperationState.ERROR)
HiveThriftServer2.eventManager.onStatementError(
statementId, e.getMessage, SparkUtils.exceptionString(e))
e match {
case _: HiveSQLException => throw e
case _ => throw HiveThriftServerErrors.runningQueryError(e)
}
}
} finally {
synchronized {
if (!getStatus.getState.isTerminal) {
setState(OperationState.FINISHED)
HiveThriftServer2.eventManager.onStatementFinish(statementId)
}
}
sqlContext.sparkContext.clearJobGroup()
}
}
def timeoutCancel(): Unit = {
synchronized {
if (!getStatus.getState.isTerminal) {
logInfo(s"Query with $statementId timed out after $timeout seconds")
setState(OperationState.TIMEDOUT)
cleanup()
HiveThriftServer2.eventManager.onStatementTimeout(statementId)
}
}
}
override def cancel(): Unit = {
synchronized {
if (!getStatus.getState.isTerminal) {
logInfo(s"Cancel query with $statementId")
setState(OperationState.CANCELED)
cleanup()
HiveThriftServer2.eventManager.onStatementCanceled(statementId)
}
}
}
override protected def cleanup(): Unit = {
if (runInBackground) {
val backgroundHandle = getBackgroundHandle()
if (backgroundHandle != null) {
backgroundHandle.cancel(true)
}
}
// RDDs will be cleaned automatically upon garbage collection.
if (statementId != null) {
sqlContext.sparkContext.cancelJobGroup(statementId)
}
}
}
object SparkExecuteStatementOperation {
def getTableSchema(structType: StructType): TableSchema = {
val schema = structType.map { field =>
val attrTypeString = field.dataType match {
case NullType => "void"
case CalendarIntervalType => StringType.catalogString
case YearMonthIntervalType => "interval_year_month"
case _: DayTimeIntervalType => "interval_day_time"
case other => other.catalogString
}
new FieldSchema(field.name, attrTypeString, field.getComment.getOrElse(""))
}
new TableSchema(schema.asJava)
}
}
| cloud-fan/spark | sql/hive-thriftserver/src/main/scala/org/apache/spark/sql/hive/thriftserver/SparkExecuteStatementOperation.scala | Scala | apache-2.0 | 14,691 |
package reactivemongo.core.commands
import reactivemongo.bson._
/**
* Implements the "aggregation" command, otherwise known as the "Aggregation Framework."
* http://docs.mongodb.org/manual/applications/aggregation/
*
* @param collectionName Collection to aggregate against
* @param pipeline Sequence of MongoDB aggregation operations.
*/
@deprecated(
message = "Use [[reactivemongo.api.collections.GenericCollection.aggregateWith]]",
since = "0.12-RC5"
)
case class Aggregate(
collectionName: String,
pipeline: Seq[PipelineOperator]
) extends Command[Stream[BSONDocument]] {
override def makeDocuments =
BSONDocument(
"aggregate" -> BSONString(collectionName),
"pipeline" -> BSONArray(
{ for (pipe <- pipeline) yield pipe.makePipe }.toStream
)
)
val ResultMaker = Aggregate
}
object Aggregate extends BSONCommandResultMaker[Stream[BSONDocument]] {
def apply(document: BSONDocument) =
CommandError.checkOk(document, Some("aggregate")).toLeft(document.get("result").get.asInstanceOf[BSONArray].values.map(_.asInstanceOf[BSONDocument]))
}
/**
* One of MongoDBs pipeline operators for aggregation. Sealed as these are defined in
* the mongodb spec, and clients should not have custom operators.
*/
sealed trait PipelineOperator {
def makePipe: BSONValue
}
/**
* Reshapes a document stream by renaming, adding, or removing fields.
* Also use "Project" to create computed values or sub-objects.
* http://docs.mongodb.org/manual/reference/aggregation/project/#_S_project
* @param fields Fields to include. The resulting objects will contain only these fields
*/
case class Project(fields: (String, BSONValue)*) extends PipelineOperator {
override val makePipe = BSONDocument(f"$$project" -> BSONDocument(
{ for (field <- fields) yield field._1 -> field._2 }.toStream
))
}
/**
* Filters out documents from the stream that do not match the predicate.
* http://docs.mongodb.org/manual/reference/aggregation/match/#_S_match
* @param predicate Query that documents must satisfy to be in the stream.
*/
case class Match(predicate: BSONDocument) extends PipelineOperator {
override val makePipe = BSONDocument(f"$$match" -> predicate)
}
/**
* Limts the number of documents that pass through the stream.
* http://docs.mongodb.org/manual/reference/aggregation/limit/#_S_limit
* @param limit Number of documents to allow through.
*/
case class Limit(limit: Int) extends PipelineOperator {
override val makePipe = BSONDocument(f"$$limit" -> BSONInteger(limit))
}
/**
* Skips over a number of documents before passing all further documents along the stream.
* http://docs.mongodb.org/manual/reference/aggregation/skip/#_S_skip
* @param skip Number of documents to skip.
*/
case class Skip(skip: Int) extends PipelineOperator {
override val makePipe = BSONDocument(f"$$skip" -> BSONInteger(skip))
}
/**
* Turns a document with an array into multiple documents, one document for each
* element in the array.
* http://docs.mongodb.org/manual/reference/aggregation/unwind/#_S_unwind
* @param field Name of the array to unwind.
*/
case class Unwind(field: String) extends PipelineOperator {
override val makePipe = BSONDocument(f"$$unwind" -> BSONString("$" + field))
}
/**
* Groups documents together to calulate aggregates on document collections. This command
* aggregates on one field.
* http://docs.mongodb.org/manual/reference/aggregation/group/#_S_group
* @param idField Name of the field to aggregate on.
* @param ops Sequence of operators specifying aggregate calculation.
*/
case class GroupField(idField: String)(ops: (String, GroupFunction)*) extends PipelineOperator {
override val makePipe = Group(BSONString("$" + idField))(ops: _*).makePipe
}
/**
* Groups documents together to calulate aggregates on document collections. This command
* aggregates on multiple fields, and they must be named.
* http://docs.mongodb.org/manual/reference/aggregation/group/#_S_group
* @param idField Fields to aggregate on, and the names they should be aggregated under.
* @param ops Sequence of operators specifying aggregate calculation.
*/
case class GroupMulti(idField: (String, String)*)(ops: (String, GroupFunction)*) extends PipelineOperator {
override val makePipe = Group(BSONDocument(
idField.map {
case (alias, attribute) => alias -> BSONString("$" + attribute)
}.toStream
))(ops: _*).makePipe
}
/**
* Groups documents together to calulate aggregates on document collections. This command
* aggregates on arbitrary identifiers. Document fields identifier must be prefixed with `$`.
* http://docs.mongodb.org/manual/reference/aggregation/group/#_S_group
* @param identifiers Any BSON value acceptable by mongodb as identifier
* @param ops Sequence of operators specifying aggregate calculation.
*/
case class Group(identifiers: BSONValue)(ops: (String, GroupFunction)*) extends PipelineOperator {
override val makePipe = BSONDocument(
f"$$group" -> BSONDocument(
{
"_id" -> identifiers
} +:
{
ops.map {
case (field, operator) => field -> operator.makeFunction
}
}.toStream
)
)
}
/**
* Sorts the stream based on the given fields.
* http://docs.mongodb.org/manual/reference/aggregation/sort/#_S_sort
* @param fields Fields to sort by.
*/
case class Sort(fields: Seq[SortOrder]) extends PipelineOperator {
override val makePipe = BSONDocument(f"$$sort" -> BSONDocument(fields.map {
case Ascending(field) => field -> BSONInteger(1)
case Descending(field) => field -> BSONInteger(-1)
}.toStream))
}
/**
* Represents that a field should be sorted on, as well as whether it
* should be ascending or descending.
*/
sealed trait SortOrder
case class Ascending(field: String) extends SortOrder
case class Descending(field: String) extends SortOrder
/**
* Represents one of the group operators for the "Group" Operation. This class is sealed
* as these are defined in the MongoDB spec, and clients should not need to customise these.
*/
sealed trait GroupFunction {
def makeFunction: BSONValue
}
/** Factory to declare custom call to a group function. */
object GroupFunction {
/**
* Creates a call to specified group function with given argument.
*
* @param name The name of the group function (e.g. `\\$sum`)
* @param arg The group function argument
* @return A group function call defined as `{ name: arg }`
*/
def apply(name: String, arg: BSONValue): GroupFunction = new GroupFunction {
val makeFunction = BSONDocument(name -> arg)
}
}
case class AddToSet(field: String) extends GroupFunction {
val makeFunction = BSONDocument(f"$$addToSet" -> BSONString("$" + field))
}
case class First(field: String) extends GroupFunction {
val makeFunction = BSONDocument(f"$$first" -> BSONString("$" + field))
}
case class Last(field: String) extends GroupFunction {
val makeFunction = BSONDocument(f"$$last" -> BSONString("$" + field))
}
case class Max(field: String) extends GroupFunction {
val makeFunction = BSONDocument(f"$$max" -> BSONString("$" + field))
}
case class Min(field: String) extends GroupFunction {
val makeFunction = BSONDocument(f"$$min" -> BSONString("$" + field))
}
case class Avg(field: String) extends GroupFunction {
val makeFunction = BSONDocument(f"$$avg" -> BSONString("$" + field))
}
case class Push(field: String) extends GroupFunction {
val makeFunction = BSONDocument(f"$$push" -> BSONString("$" + field))
}
case class PushMulti(fields: (String, String)*) extends GroupFunction {
val makeFunction = BSONDocument(f"$$push" -> BSONDocument(
fields.map(field => field._1 -> BSONString("$" + field._2))
))
}
case class SumField(field: String) extends GroupFunction {
val makeFunction = BSONDocument(f"$$sum" -> BSONString("$" + field))
}
case class SumValue(value: Int) extends GroupFunction {
val makeFunction = BSONDocument(f"$$sum" -> BSONInteger(value))
}
| maxime-gautre/ReactiveMongo | driver/src/main/scala/core/commands/aggregation.scala | Scala | apache-2.0 | 7,977 |
package eu.brosbit.opos.snippet.page
import _root_.scala.xml.{NodeSeq, Unparsed}
import _root_.net.liftweb.util._
import _root_.net.liftweb.common._
import _root_.eu.brosbit.opos.model.page._
import _root_.eu.brosbit.opos.model._
import _root_.net.liftweb.mapper.{Descending, OrderBy, By}
import _root_.net.liftweb.http.{S, SHtml}
import Helpers._
import _root_.eu.brosbit.opos.lib.{Formater}
import java.util.Date
import _root_.net.liftweb.json.JsonDSL._
import _root_.net.liftweb.mongodb._
import org.bson.types.ObjectId
import com.mongodb.BasicDBObject
import eu.brosbit.opos.model.page._
class Test {
def test1() = {
val fth = ForumThreadHead.findAll.head
val format = """ id: %s, count: %d """
val text1 = format.format(fth._id.toString, fth.count)
val idObjStr = "ObjectId(\"" + fth._id.toString + "\")"
val o3 = (("$inc" -> ("count" -> 1)))
ForumThreadHead.update(("_id" -> fth._id.toString), o3)
val fth2 = ForumThreadHead.find(fth._id).get
val text2 = format.format(fth2._id.toString, fth2.count)
"#info" #> <p>Object:
{idObjStr}<br/>{text1}<br/>{text2}
</p>
}
def test2() = {
(new eu.brosbit.opos.lib.TestData).createData
"#info" #> <p>Data Created!</p>
}
} | mikolajs/osp | src/main/scala/eu/brosbit/opos/snippet/page/Test.scala | Scala | agpl-3.0 | 1,235 |
/*
*
* o o o o o
* | o | |\\ /| | /
* | o-o o--o o-o oo | | O | oo o-o OO o-o o o
* | | | | | | | | | | | | | | | | \\ | | \\ /
* O---oo-o o--O | o-o o-o-o o o o-o-o o o o-o o
* |
* o--o
* o--o o o--o o o
* | | | | o | |
* O-Oo oo o-o o-O o-o o-O-o O-o o-o | o-O o-o
* | \\ | | | | | | | | | | | | | |-' | | | \\
* o o o-o-o o o-o o-o o o o o | o-o o o-o o-o
*
* Logical Markov Random Fields (LoMRF).
*
*
*/
package lomrf.mln.model.builders
import org.scalatest.{ FunSpec, Matchers }
import scala.util.Random
/**
* A series of specification test for constants set builder.
*
* @see [[lomrf.mln.model.builders.ConstantsSetBuilder]]
*/
final class ConstantsSetBuilderSpecTest extends FunSpec with Matchers {
describe("An empty builder") {
val builder = ConstantsSetBuilder()
it ("should be empty") {
builder.isEmpty shouldEqual true
}
it ("should have zero size") {
builder.size shouldEqual 0
}
it("should have an empty iterator") {
builder.iterator.isEmpty shouldEqual true
}
it("should create copies of empty builders") {
builder.copy().isEmpty shouldEqual true
}
it ("should result in an empty constants set") {
builder.result().isEmpty shouldBe true
}
}
describe("A builder holding a single constant symbol") {
val builder = ConstantsSetBuilder("Symbol")
it ("should NOT be empty") {
builder.nonEmpty shouldEqual true
}
it ("should have size 1") {
builder.size shouldEqual 1
}
it("should have a NON empty iterator") {
builder.iterator.nonEmpty shouldEqual true
}
it("should create copies of NON empty builders") {
builder.copy().nonEmpty shouldEqual true
}
it ("should result in a constants set holding a single constant") {
val constantsSet = builder.result()
constantsSet.nonEmpty shouldEqual true
constantsSet.contains("Symbol") shouldEqual true
}
}
describe("A builder holding a more constant symbols") {
val constants =
for (idx <- 1 to 10) yield s"C${idx}" + Random.alphanumeric.take(5).toString()
val builder = ConstantsSetBuilder(constants)
it ("should NOT be empty") {
builder.nonEmpty shouldEqual true
}
it (s"should have size ${constants.size}") {
builder.size shouldEqual constants.size
}
it("should have a NON empty iterator") {
builder.iterator.nonEmpty shouldEqual true
}
it("should create copies of NON empty builders") {
builder.copy().nonEmpty shouldEqual true
}
it ("should result in a constants set holding all given constants") {
val constantsSet = builder.result()
constantsSet.nonEmpty shouldEqual true
constants.forall(constantsSet.contains)
}
it ("should be empty after clear function is called") {
builder.clear()
builder.isEmpty shouldEqual true
}
}
}
| anskarl/LoMRF | src/test/scala/lomrf/mln/model/builders/ConstantsSetBuilderSpecTest.scala | Scala | apache-2.0 | 3,175 |
package list
/**
* P07 (**) Flatten a nested list structure.
*/
object P07 {
def flatten(list: List[Any]): List[Any] = list flatMap {
case l: List[_] => flatten(l)
case e => List(e)
}
}
| zjt1114/scala99 | src/main/scala/list/P07.scala | Scala | apache-2.0 | 203 |
package hotpepper4s
/**
* @author ponkotuy
* date: 13/12/26.
*/
trait Results[T] {
def apiVersion: String
def resultsAvailable: Int
def resultsReturned: String
def resultsStart: Int
def data: List[T]
}
| ponkotuy/hotpepper4s | src/main/scala/hotpepper4s/Results.scala | Scala | mit | 216 |
/*
* 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.catalyst.analysis
import org.apache.spark.sql.catalyst.catalog.SessionCatalog
import org.apache.spark.sql.catalyst.expressions._
import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.errors.QueryCompilationErrors
import org.apache.spark.sql.types.DataType
/**
* Resolve a higher order functions from the catalog. This is different from regular function
* resolution because lambda functions can only be resolved after the function has been resolved;
* so we need to resolve higher order function when all children are either resolved or a lambda
* function.
*/
case class ResolveHigherOrderFunctions(catalog: SessionCatalog) extends Rule[LogicalPlan] {
override def apply(plan: LogicalPlan): LogicalPlan = plan.resolveExpressions {
case u @ UnresolvedFunction(fn, children, false, filter, ignoreNulls)
if hasLambdaAndResolvedArguments(children) =>
withPosition(u) {
catalog.lookupFunction(fn, children) match {
case func: HigherOrderFunction =>
filter.foreach(_.failAnalysis("FILTER predicate specified, " +
s"but ${func.prettyName} is not an aggregate function"))
if (ignoreNulls) {
throw QueryCompilationErrors.functionWithUnsupportedSyntaxError(
func.prettyName, "IGNORE NULLS")
}
func
case other => other.failAnalysis(
"A lambda function should only be used in a higher order function. However, " +
s"its class is ${other.getClass.getCanonicalName}, which is not a " +
s"higher order function.")
}
}
}
/**
* Check if the arguments of a function are either resolved or a lambda function.
*/
private def hasLambdaAndResolvedArguments(expressions: Seq[Expression]): Boolean = {
val (lambdas, others) = expressions.partition(_.isInstanceOf[LambdaFunction])
lambdas.nonEmpty && others.forall(_.resolved)
}
}
/**
* Resolve the lambda variables exposed by a higher order functions.
*
* This rule works in two steps:
* [1]. Bind the anonymous variables exposed by the higher order function to the lambda function's
* arguments; this creates named and typed lambda variables. The argument names are checked
* for duplicates and the number of arguments are checked during this step.
* [2]. Resolve the used lambda variables used in the lambda function's function expression tree.
* Note that we allow the use of variables from outside the current lambda, this can either
* be a lambda function defined in an outer scope, or a attribute in produced by the plan's
* child. If names are duplicate, the name defined in the most inner scope is used.
*/
object ResolveLambdaVariables extends Rule[LogicalPlan] {
type LambdaVariableMap = Map[String, NamedExpression]
private def canonicalizer = {
if (!conf.caseSensitiveAnalysis) {
// scalastyle:off caselocale
s: String => s.toLowerCase
// scalastyle:on caselocale
} else {
s: String => s
}
}
override def apply(plan: LogicalPlan): LogicalPlan = {
plan.resolveOperators {
case q: LogicalPlan =>
q.mapExpressions(resolve(_, Map.empty))
}
}
/**
* Create a bound lambda function by binding the arguments of a lambda function to the given
* partial arguments (dataType and nullability only). If the expression happens to be an already
* bound lambda function then we assume it has been bound to the correct arguments and do
* nothing. This function will produce a lambda function with hidden arguments when it is passed
* an arbitrary expression.
*/
private def createLambda(
e: Expression,
argInfo: Seq[(DataType, Boolean)]): LambdaFunction = e match {
case f: LambdaFunction if f.bound => f
case LambdaFunction(function, names, _) =>
if (names.size != argInfo.size) {
e.failAnalysis(
s"The number of lambda function arguments '${names.size}' does not " +
"match the number of arguments expected by the higher order function " +
s"'${argInfo.size}'.")
}
if (names.map(a => canonicalizer(a.name)).distinct.size < names.size) {
e.failAnalysis(
"Lambda function arguments should not have names that are semantically the same.")
}
val arguments = argInfo.zip(names).map {
case ((dataType, nullable), ne) =>
NamedLambdaVariable(ne.name, dataType, nullable)
}
LambdaFunction(function, arguments)
case _ =>
// This expression does not consume any of the lambda's arguments (it is independent). We do
// create a lambda function with default parameters because this is expected by the higher
// order function. Note that we hide the lambda variables produced by this function in order
// to prevent accidental naming collisions.
val arguments = argInfo.zipWithIndex.map {
case ((dataType, nullable), i) =>
NamedLambdaVariable(s"col$i", dataType, nullable)
}
LambdaFunction(e, arguments, hidden = true)
}
/**
* Resolve lambda variables in the expression subtree, using the passed lambda variable registry.
*/
private def resolve(e: Expression, parentLambdaMap: LambdaVariableMap): Expression = e match {
case _ if e.resolved => e
case h: HigherOrderFunction if h.argumentsResolved && h.checkArgumentDataTypes().isSuccess =>
h.bind(createLambda).mapChildren(resolve(_, parentLambdaMap))
case l: LambdaFunction if !l.bound =>
// Do not resolve an unbound lambda function. If we see such a lambda function this means
// that either the higher order function has yet to be resolved, or that we are seeing
// dangling lambda function.
l
case l: LambdaFunction if !l.hidden =>
val lambdaMap = l.arguments.map(v => canonicalizer(v.name) -> v).toMap
l.mapChildren(resolve(_, parentLambdaMap ++ lambdaMap))
case u @ UnresolvedNamedLambdaVariable(name +: nestedFields) =>
parentLambdaMap.get(canonicalizer(name)) match {
case Some(lambda) =>
nestedFields.foldLeft(lambda: Expression) { (expr, fieldName) =>
ExtractValue(expr, Literal(fieldName), conf.resolver)
}
case None =>
UnresolvedAttribute(u.nameParts)
}
case _ =>
e.mapChildren(resolve(_, parentLambdaMap))
}
}
| witgo/spark | sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/higherOrderFunctions.scala | Scala | apache-2.0 | 7,326 |
package org.jetbrains.plugins.scala
package lang
package psi
package impl
package statements
package params
import com.intellij.lang.ASTNode
import com.intellij.psi.{PsiClass, PsiElement}
import javax.swing.Icon
import org.jetbrains.plugins.scala.extensions.ifReadAllowed
import org.jetbrains.plugins.scala.icons.Icons
import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes
import org.jetbrains.plugins.scala.lang.parser.ScalaElementType
import org.jetbrains.plugins.scala.lang.psi.api.ScalaElementVisitor
import org.jetbrains.plugins.scala.lang.psi.api.statements.params._
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.ScClass
import org.jetbrains.plugins.scala.lang.psi.stubs.ScParameterStub
/**
* @author Alexander Podkhalyuzin
* Date: 22.02.2008
*/
final class ScClassParameterImpl private(stub: ScParameterStub, node: ASTNode)
extends ScParameterImpl(stub, ScalaElementType.CLASS_PARAM, node) with ScClassParameter {
def this(node: ASTNode) = this(null, node)
def this(stub: ScParameterStub) = this(stub, null)
override def toString: String = "ClassParameter: " + ifReadAllowed(name)("")
override def isVal: Boolean = byStubOrPsi(_.isVal)(findChildByType(ScalaTokenTypes.kVAL) != null)
override def isVar: Boolean = byStubOrPsi(_.isVar)(findChildByType(ScalaTokenTypes.kVAR) != null)
override def isImplicitParameter: Boolean = super.isImplicitParameter || getModifierList.isImplicit
override def isPrivateThis: Boolean = {
if (!isClassMember) return true
getModifierList.accessModifier match {
case Some(am) =>
am.isThis && am.isPrivate
case _ => false
}
}
override def isCaseClassVal: Boolean = containingClass match {
case c: ScClass if c.isCase =>
val isInPrimaryConstructorFirstParamSection = c.constructor
.exists(_.effectiveFirstParameterSection.contains(this))
isInPrimaryConstructorFirstParamSection
case _ => false
}
override def isStable: Boolean = byStubOrPsi(_.isStable)(findChildByType(ScalaTokenTypes.kVAR) == null)
override def getOriginalElement: PsiElement = {
val ccontainingClass = containingClass
if (ccontainingClass == null) return this
val originalClass: PsiClass = ccontainingClass.getOriginalElement.asInstanceOf[PsiClass]
if (ccontainingClass eq originalClass) return this
if (!originalClass.isInstanceOf[ScClass]) return this
val c = originalClass.asInstanceOf[ScClass]
val iterator = c.parameters.iterator
while (iterator.hasNext) {
val param = iterator.next()
if (param.name == name) return param
}
this
}
override protected def acceptScala(visitor: ScalaElementVisitor): Unit = {
visitor.visitClassParameter(this)
}
override protected def baseIcon: Icon =
if (isVar) Icons.FIELD_VAR
else if (isVal || isCaseClassVal) Icons.FIELD_VAL
else Icons.PARAMETER
}
| JetBrains/intellij-scala | scala/scala-impl/src/org/jetbrains/plugins/scala/lang/psi/impl/statements/params/ScClassParameterImpl.scala | Scala | apache-2.0 | 2,896 |
/*
* Copyright (c) 2014 - 2015 Contributor. All rights reserved.
*/
package org.scalaide.debug.internal.expression
package proxies.phases
import scala.reflect.runtime.universe
trait UnboundValuesSupport {
import universe._
/**
* Keeps track of all enclosing trees
* @param topLevelTree top level tree
*/
class ScopeManager(topLevelTree: Tree) {
private var treeStack: List[Tree] = Nil
final def popTree(): Unit = treeStack = treeStack.tail
final def pushTree(tree: Tree): Unit = treeStack = tree :: treeStack
final def insideImport: Boolean = treeStack.exists {
case Import(_, _) => true
case _ => false
}
/**
* @return tree defining enclosing scope e.g.: function, block, case def
* when no such tree is found the top level tree is returned
*/
final def findCurrentScopeTree(): Tree =
treeStack.find {
case _: Function | _: Block | _: CaseDef => true
case _ => false
}.getOrElse(topLevelTree)
}
/**
* Keeps track of bound and unbound variables (name and type if is accessible)
*/
private class VariableManager(extractType: Tree => Option[String]) {
/**
* Unbound names in a sense that a name is unbound if there exists at least one scope in which it is unbound.
* NOTE: In some other scopes in a processed code snippet the unbound name might be actually bound
*/
private var _unboundNames = Map.empty[UnboundVariable, Option[String]]
/**
* A map of names and corresponding trees which bind the name
*/
private var boundNames = Map.empty[Name, Seq[Tree]].withDefaultValue(Seq.empty)
/**
* @return collected unbound names
*/
final def unboundNames(): Map[UnboundVariable, Option[String]] = _unboundNames
/**
* @param name identifier
* @param boundingTree tree bounding the name
*/
final def registerNameBinding(name: Name, boundingTree: Tree): Unit = {
boundNames += name -> (boundNames(name) :+ boundingTree)
}
/**
* Checks whether name is unbound and if so registers it as such
* @param name an identifier
* @param tree tree representing the name usage
*/
final def registerUnboundName(name: TermName, tree: Tree, isLocal: Boolean): Unit = {
val isBound = boundingTreesOf(name).exists(parentOf(tree))
val isScalaSymbol = name == termNames.WILDCARD || name == Names.Scala.scalaPackageTermName
val isSymbolVisibleByDefault = isVisibleByDefault(name.toString)
if (!isScalaSymbol && !isSymbolVisibleByDefault && !isBound && name.isTermName) {
_unboundNames += UnboundVariable(name, isLocal) -> extractType(tree)
}
}
/** Checks if type is defined in `scala.Predef` or in `scala` package object. */
private def isVisibleByDefault(typeName: String): Boolean =
defaultSymbols.contains(typeName)
private lazy val defaultSymbols = {
val predefSymbols = {
val clazz = Predef.getClass
val methods = clazz.getMethods.map(_.getName)
val fields = clazz.getFields.map(_.getName)
methods ++ fields
}
val fromPackageObject = {
val clazz = getClass.getClassLoader.loadClass("scala.package$")
val methods = clazz.getMethods.map(_.getName)
val fields = clazz.getFields.map(_.getName)
methods ++ fields
}
(predefSymbols ++ fromPackageObject).toSet
}
/**
* @param child child searching for a parent
* @param node node checked for parenthood
* @return true if the node contains the child, i.e. the node is a parent of the child, false otherwise
*/
private def parentOf(child: Tree)(node: Tree): Boolean = node.exists(_ == child)
/**
* @param name identifier
* @return all trees which define the name
*/
private def boundingTreesOf(name: Name): Seq[Tree] = boundNames(name)
}
/**
* Collects unbound names in the tree.
*/
class VariableProxyTraverser(
tree: Tree,
extractType: Tree => Option[String] = _ => None,
localVariablesNames: => Set[String] = Set.empty) extends Traverser {
private val scopeManager = new ScopeManager(tree)
private val nameManager = new VariableManager(extractType)
/**
* Collects unbound variables in the tree.
*/
final def findUnboundVariables(): Set[UnboundVariable] =
findUnboundValues.keySet
/**
* Collects unbound values (name, type) in the tree.
*/
final def findUnboundValues(): Map[UnboundVariable, Option[String]] = {
this.traverse(tree)
nameManager.unboundNames()
}
private def isLocalVar(termName: TermName): Boolean =
localVariablesNames.contains(termName.encodedName.toString)
/**
* Collects unbound names in tree.
* Keeps track of all name bindings in order to collect unbound names.
*/
final override def traverse(tree: Tree): Unit = {
scopeManager.pushTree(tree)
tree match {
case Assign(Ident(name: TermName), value) =>
// suppressing value extraction from lhs if it's not local
if (isLocalVar(name)) nameManager.registerUnboundName(name, tree, isLocal = true)
super.traverse(value)
// all identifiers
case Ident(name: TermName) if !scopeManager.insideImport =>
nameManager.registerUnboundName(name, tree, isLocal = false)
// like: case ala: Ala =>
case CaseDef(Bind(name, _), _, _) =>
nameManager.registerNameBinding(name, tree)
super.traverse(tree)
// named args like: foo(ala = "ola")
case AssignOrNamedArg(Ident(name), _) =>
nameManager.registerNameBinding(name, scopeManager.findCurrentScopeTree())
super.traverse(tree)
// for binding in pattern matching like: ala @ Ala(name)
// and, apparently, for values in for-comprehension
case Bind(name, _) =>
nameManager.registerNameBinding(name, scopeManager.findCurrentScopeTree())
super.traverse(tree)
// value definition like: val ala = "Ala"
case ValDef(_, name, _, impl) =>
nameManager.registerNameBinding(name, scopeManager.findCurrentScopeTree())
super.traverse(impl)
//typed expression like x: Int
case Typed(impl, _) =>
super.traverse(impl)
case _ => super.traverse(tree)
}
scopeManager.popTree()
}
}
}
| scala-ide/scala-ide | org.scala-ide.sdt.debug.expression/src/org/scalaide/debug/internal/expression/proxies/phases/UnboundValuesSupport.scala | Scala | bsd-3-clause | 6,472 |
package org.slickz
import scala.slick.jdbc.JdbcBackend
import scalaz.concurrent.Task
trait Slickz {
outer =>
def withSessionPure[T](b: JdbcBackend#Database)(f: JdbcBackend#Session => Task[T]): Task[T] = for {
session <- Task.delay(b.createSession())
t <- f(session) onFinish {
case Some(fException) => Task.delay(session.close()).handle { case _: Throwable => throw fException }
case None => Task.delay(session.close())
}
} yield t
def withTransactionPure[T](b: JdbcBackend#Database)(f: JdbcBackend#Session => Task[T]): Task[T] =
withSessionPure(b)(s => Task.delay(s.withTransaction(f(s).run)))
def withTransactionPure[T](s: JdbcBackend#Session)(work: Task[T]): Task[T] =
Task.delay(s.withTransaction(work.run))
}
object Slickz extends Slickz
| 2chilled/slickz | src/main/scala/org/slickz/Slickz.scala | Scala | bsd-2-clause | 791 |
/*
* Copyright (C) 2005, The OpenURP Software.
*
* This program 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 3 of the License, or
* (at your option) any later version.
*
* This program 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 program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openurp.std.graduation.model
import java.time.LocalDate
import org.beangle.commons.collection.Collections
import org.beangle.data.model.LongId
import org.beangle.data.model.pojo.Updated
import org.openurp.code.edu.model.Degree
import org.openurp.base.edu.model.Student
import scala.collection.mutable
class DegreeResult extends LongId with Updated {
/** 所属的毕业审核批次 */
var session: GraduateSession = _
/** 学生 */
var std: Student = _
/** 学位审核详细结果 */
var items: mutable.Buffer[DegreeAuditItem] = Collections.newBuffer[DegreeAuditItem]
/** GPA */
var gpa: Float = _
/** 平均分 */
var ga: Float = _
/** 是否通过学位审核 */
var passed: Boolean = _
/** 锁定审核结果 */
var locked: Boolean = _
/** 是否已发布 */
var published: Boolean = _
/** 毕业备注 */
var comments: Option[String] = None
/** 学位 */
var degree: Option[Degree] = None
/** 外语通过年月 */
var foreignLangPassedOn: Option[LocalDate] = None
def deciplineCode: String = {
std.state.map(_.major.disciplineCode(session.beginOn)).getOrElse("")
}
}
| openurp/api | std/src/main/scala/org/openurp/std/graduation/model/DegreeResult.scala | Scala | lgpl-3.0 | 1,874 |
package com.tekacs.codegen
object Versions {
val nightly = "0.3.0-SNAPSHOT"
val stable = "0.3.0"
}
| tekacs/scala-db-codegen | src/main/scala/com/tekacs/codegen/Versions.scala | Scala | apache-2.0 | 104 |
package net.liftweb.util
import _root_.org.specs.Specification
import _root_.org.specs.runner._
import _root_.java.util._
import _root_.java.text._
import _root_.org.scalacheck.Gen._
import _root_.org.scalacheck.Prop._
import _root_.org.scalacheck.Arbitrary
import _root_.org.specs.Products._
import _root_.org.specs.mock.Mocker
import _root_.org.specs.ScalaCheck
class TimeHelpersTest extends JUnit4(TimeHelpersSpec)
object TimeHelpersSpec extends Specification with TimeHelpers with TimeAmountsGen with ScalaCheck with Mocker with LoggerDelegation with ControlHelpers with ClassHelpers {
"A TimeSpan" can {
"be created from a number of milliseconds" in {
TimeSpan(3000) must_== TimeSpan(3 * 1000)
}
"be created from a number of seconds" in {
3.seconds must_== TimeSpan(3 * 1000)
}
"be created from a number of minutes" in {
3.minutes must_== TimeSpan(3 * 60 * 1000)
}
"be created from a number of hours" in {
3.hours must_== TimeSpan(3 * 60 * 60 * 1000)
}
"be created from a number of days" in {
3.days must_== TimeSpan(3 * 24 * 60 * 60 * 1000)
}
"be created from a number of weeks" in {
3.weeks must_== TimeSpan(3 * 7 * 24 * 60 * 60 * 1000)
}
"be converted implicitly to a date starting from the epoch time" in {
3.seconds.after(new Date(0)) must beTrue
}
"be converted to a date starting from the epoch time, using the date method" in {
3.seconds.after(new Date(0)) must beTrue
}
"be implicitly converted to a Long" in {
3.seconds must_== 3000L
}
"be compared to an int" in {
3.seconds must_== 3000
3.seconds must_!= 2000
}
"be compared to a long" in {
3.seconds must_== 3000L
3.seconds must_!= 2000L
}
"be compared to another TimeSpan" in {
3.seconds must_== 3.seconds
3.seconds must_!= 2.seconds
}
"be compared to another object" in {
3.seconds must_!= "string"
}
}
"A TimeSpan" should {
"return a new TimeSpan representing the sum of the 2 times when added with another TimeSpan" in {
3.seconds + 3.seconds must_== 6.seconds
}
"return a new TimeSpan representing the difference of the 2 times when substracted with another TimeSpan" in {
3.seconds - 4.seconds must_== (-1).seconds
}
"have a later method returning a date relative to now plus the time span" in {
3.seconds.later.getTime must beCloseTo(new Date().getTime + 3.seconds.millis, 100L)
}
"have an ago method returning a date relative to now minus the time span" in {
3.seconds.ago.getTime must beCloseTo(new Date().getTime - 3.seconds.millis, 100L)
}
"have a toString method returning the relevant number of weeks, days, hours, minutes, seconds, millis" in {
val conversionIsOk = forAll(timeAmounts)((t: TimeAmounts) => { val (timeSpanToString, timeSpanAmounts) = t
timeSpanAmounts forall { case (amount, unit) =>
amount >= 1 &&
timeSpanToString.contains(amount.toString) || true }
})
val timeSpanStringIsPluralized = forAll(timeAmounts)((t: TimeAmounts) => { val (timeSpanToString, timeSpanAmounts) = t
timeSpanAmounts forall { case (amount, unit) =>
amount > 1 && timeSpanToString.contains(unit + "s") ||
amount == 1 && timeSpanToString.contains(unit) ||
amount == 0 && !timeSpanToString.contains(unit)
}
})
conversionIsOk && timeSpanStringIsPluralized must pass
}
}
"the TimeHelpers" should {
"provide a 'seconds' function transforming a number of seconds into millis" in {
seconds(3) must_== 3 * 1000
}
"provide a 'minutes' function transforming a number of minutes into millis" in {
minutes(3) must_== 3 * 60 * 1000
}
"provide a 'hours' function transforming a number of hours into milliss" in {
hours(3) must_== 3 * 60 * 60 * 1000
}
"provide a 'days' function transforming a number of days into millis" in {
days(3) must_== 3 * 24 * 60 * 60 * 1000
}
"provide a 'weeks' function transforming a number of weeks into millis" in {
weeks(3) must_== 3 * 7 * 24 * 60 * 60 * 1000
}
"provide a noTime function on Date objects to transform a date into a date at the same day but at 00:00" in {
hourFormat(timeNow.noTime) must_== "00:00:00"
}
"provide a day function returning the day of month corresponding to a given date (relative to UTC)" in {
day(today.setTimezone(utc).setDay(3).getTime) must_== 3
}
"provide a month function returning the month corresponding to a given date" in {
month(today.setTimezone(utc).setMonth(4).getTime) must_== 4
}
"provide a year function returning the year corresponding to a given date" in {
year(today.setTimezone(utc).setYear(2008).getTime) must_== 2008
}
"provide a millisToDays function returning the number of days since the epoch time" in {
millisToDays(new Date(0).getTime) must_== 0
millisToDays(today.setYear(1970).setMonth(0).setDay(1).getTime.getTime) must_== 0 // the epoch time
// on the 3rd day after the epoch time, 2 days are passed
millisToDays(today.setTimezone(utc).setYear(1970).setMonth(0).setDay(3).getTime.getTime) must_== 2
}
"provide a daysSinceEpoch function returning the number of days since the epoch time" in {
daysSinceEpoch must_== millisToDays(now.getTime)
}
"provide a time function creating a new Date object from a number of millis" in {
time(1000) must_== new Date(1000)
}
"provide a calcTime function returning the time taken to evaluate a block in millis and the block's result" in {
val (time, result) = calcTime((1 to 10).reduceLeft[Int](_ + _))
time.toInt must beCloseTo(0, 1000) // it should take less than 1 second!
result must_== 55
}
"provide a logTime function logging the time taken to do something and returning the result" in {
skip("this way of mock LiftLogger is not robust enough and has to be reworked")
val logMock = new LiftLogger {
override def info(a: => AnyRef) = record {
a.toString must beMatching("this test took \\\\d* Milliseconds")
}
}
expect {
logMock.info("this test took 10 Milliseconds")
}
withLogger(logMock) {
logTime("this test")((1 to 10).reduceLeft[Int](_ + _))
}
}
"provide a hourFormat function to format the time of a date object" in {
hourFormat(Calendar.getInstance(utc).noTime.getTime) must_== "00:00:00"
}
"provide a formattedDateNow function to format todays date" in {
formattedDateNow must beMatching("\\\\d\\\\d\\\\d\\\\d/\\\\d\\\\d/\\\\d\\\\d")
}
"provide a formattedTimeNow function to format now's time with the TimeZone" in {
formattedTimeNow must beMatching("\\\\d\\\\d:\\\\d\\\\d ...(\\\\+|\\\\-\\\\d\\\\d:00)?")
}
"provide a parseInternetDate function to parse a string formatted using the internet format" in {
parseInternetDate(internetDateFormatter.format(now)).getTime.toLong must beCloseTo(now.getTime.toLong, 1000L)
}
"provide a parseInternetDate function returning new Date(0) if the input date cant be parsed" in {
parseInternetDate("unparsable") must_== new Date(0)
}
"provide a toInternetDate function formatting a date to the internet format" in {
toInternetDate(now) must beMatching("..., \\\\d* ... \\\\d\\\\d\\\\d\\\\d \\\\d\\\\d:\\\\d\\\\d:\\\\d\\\\d .*")
}
"provide a toDate returning a Full(date) from many kinds of objects" in {
val d = now
(null, Nil, None, Failure("", Empty, Empty)).toList forall { toDate(_) must_== Empty }
(Full(d), Some(d), d :: d).toList forall { toDate(_) must_== Full(d) }
toDate(internetDateFormatter.format(d)).get.getTime.toLong must beCloseTo(d.getTime.toLong, 1000L)
}
}
"The Calendar class" should {
"have a setDay method setting the day of month and returning the updated Calendar" in {
day(today.setTimezone(utc).setDay(1).getTime) must_== 1
}
"have a setMonth method setting the month and returning the updated Calendar" in {
month(today.setTimezone(utc).setMonth(0).getTime) must_== 0
}
"have a setYear method setting the year and returning the updated Calendar" in {
year(today.setTimezone(utc).setYear(2008).getTime) must_== 2008
}
"have a setTimezone method to setting the time zone and returning the updated Calendar" in {
today.setTimezone(utc).getTimeZone must_== utc
}
"have a noTime method to setting the time to 00:00:00 and returning the updated Calendar" in {
hourFormat(today.noTime.getTime) must_== "00:00:00"
}
}
}
trait TimeAmountsGen { self: TimeHelpers =>
type TimeAmounts = Tuple2[String, Tuple6[(Int, String), (Int, String), (Int, String), (Int, String), (Int, String), (Int, String)]]
val timeAmounts = for {
w <- choose(0, 2)
d <- choose(0, 6)
h <- choose(0, 23)
m <- choose(0, 59)
s <- choose(0, 59)
ml <- choose(0, 999)
}
yield (TimeSpan(weeks(w) + days(d) + hours(h) + minutes(m) + seconds(s) + ml).toString,
((w, "week"), (d, "day"), (h, "hour"), (m, "minute"), (s, "second"), (ml, "milli")))
}
/**
* This trait allows to insert a Logger delegate inside the lift Logging framework and to use it to
* temporarily log with a mock logger
*/
trait LoggerDelegation {
def withLogger(logger: LiftLogger)(block: => Any) = {
setLogger(logger)
try {
block
} finally { unsetLogger }
}
private[this] def setLogger(logger: LiftLogger) {
LogBoot.loggerSetup = () => true
LogBoot.loggerByName = (s: String) => LoggerDelegate(logger)
}
private[this] def unsetLogger {
Log.rootLogger.asInstanceOf[LoggerDelegate].logger = NullLogger
}
case class LoggerDelegate(var logger: LiftLogger) extends LiftLogger {
override def isTraceEnabled: Boolean = logger.isTraceEnabled
override def trace(msg: => AnyRef): Unit = logger.trace(msg)
override def trace(msg: => AnyRef, t: => Throwable): Unit = logger.trace(msg, t)
override def isDebugEnabled: Boolean = logger.isDebugEnabled
override def debug(msg: => AnyRef): Unit = logger.debug(msg)
override def debug(msg: => AnyRef, t: => Throwable): Unit = logger.debug(msg, t)
override def isErrorEnabled: Boolean = logger.isErrorEnabled
override def error(msg: => AnyRef): Unit = logger.error(msg)
override def error(msg: => AnyRef, t: => Throwable): Unit = logger.error(msg, t)
override def fatal(msg: AnyRef): Unit = logger.fatal(msg)
override def fatal(msg: AnyRef, t: Throwable): Unit = logger.fatal(msg, t)
override def isInfoEnabled: Boolean = logger.isInfoEnabled
override def info(msg: => AnyRef): Unit = logger.info(msg)
override def info(msg: => AnyRef, t: => Throwable): Unit = logger.info(msg, t)
override def isWarnEnabled: Boolean = logger.isWarnEnabled
override def warn(msg: => AnyRef): Unit = logger.warn(msg)
override def warn(msg: => AnyRef, t: => Throwable): Unit = logger.warn(msg, t)
override def isEnabledFor(level: LiftLogLevels.Value): Boolean = logger.isEnabledFor(level)
override def level: LiftLogLevels.Value = LiftLogLevels.Off
override def level_=(level: LiftLogLevels.Value): Unit = logger.level = level
override def name: String = "LoggerDelegate"
override def assertLog(assertion: Boolean, msg: => String): Unit = ()
}
}
| beni55/liftweb | lift-util/src/test/scala/net/liftweb/util/TimeHelpersSpec.scala | Scala | apache-2.0 | 11,489 |
package main.scala.math.matrix
/**
*
*/
class MatrixCreator(val firstColNum:Int, val firstRowNum:Int, val firstMatrixValues:Array[Array[Int]],val secondColNum:Int, val secondRowNum:Int, val secondMatrixValues:Array[Array[Int]]){
/**
* A secondary constructor.
*/
def this(firstRowNum: Int, secondColNum:Int) {
this(0,firstRowNum, Array.empty,secondColNum, 0, Array.empty);
}
def this(firstMatrixValues:Array[Array[Int]],secondMatrixValues:Array[Array[Int]]) = this(0,0,firstMatrixValues,0,0,secondMatrixValues)
def A:Matrix = new Matrix(firstMatrixValues)
if(firstRowNum != secondColNum) throw new IllegalArgumentException("Please provide a second matrix column numbers equalling first matrix row number")
def B:Matrix = new Matrix(secondMatrixValues)
} | SaadE92/mathlibrary | maths-library/src/main/scala/math/matrix/MatrixCreator.scala | Scala | gpl-3.0 | 796 |
package typeformation.cf
import java.net.{InetAddress, URL}
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import typeformation.cf.CfExp._
import typeformation.cf.Parameter.{AwsParamType, CommaDelimited}
import typeformation.iam
import AwsParamType._
import io.circe.syntax._
import typeformation.cf.init._
import io.circe.{Encoder, Json, JsonObject}
import java.time.Duration
import enum.Enum
import ResourceAttributes._
import io.circe.generic.semiauto.deriveEncoder
import scala.util.Try
object Encoding {
implicit final val encodeDuration: Encoder[Duration] =
Encoder.instance(duration => Json.fromString(duration.toString))
implicit val encodeZonedDateTime: Encoder[ZonedDateTime] =
implicitly[Encoder[String]]
.contramap[ZonedDateTime](_.format(DateTimeFormatter.ISO_ZONED_DATE_TIME))
implicit val encodeTagExp: Encoder[Tag] =
Encoder.instance[Tag] { t =>
Json.obj(
"Key" -> Json.fromString(t.key),
"Value" -> Json.fromString(t.value)
)
}
implicit val encodeInetIp =
Encoder.instance[InetAddress](a => Json.fromString(a.toString))
implicit val encodeArn = Encoder.instance[Arn](a => Json.fromString(a.value))
implicit def encodeLit[T: IsLit: Encoder]: Encoder[Lit[T]] =
implicitly[Encoder[T]].contramap[Lit[T]](_.value)
implicit def encodeCfExp[T: IsLit: Encoder]: Encoder[CfExp[T]] =
Encoder.instance[CfExp[T]] {
case l: Lit[T] =>
l.asJson
case FnBase64(exp) =>
Json.obj("Fn::Base64" -> exp.asJson)
case FnAnd(cond1, cond2) =>
Json.obj("Fn::And" -> List(cond1, cond2).asJson)
case eq: FnEquals[T @unchecked] =>
Json.obj(
"Fn::Equals" -> Json.fromValues(
List(eq.left.asJson, eq.right.asJson)))
case FnIf(cond, ifTrue, ifFalse) =>
Json.obj(
"Fn::If" -> Json.fromValues(
List(cond.asJson, ifTrue.asJson, ifFalse.asJson)))
case FnNot(cond) =>
Json.obj("Fn::Not" -> List(cond).asJson) // weird but correct according to the doc
case FnJoin(delimiter, chunks) =>
Json.obj("Fn::Join" -> Json.arr(delimiter.asJson, chunks.asJson))
case FnOr(conds) =>
Json.obj("Fn::Or" -> conds.asJson)
case FnGetAZs(region) =>
Json.obj(
"Fn::GetAZs" ->
Json.fromString(region.getOrElse("")))
case FnSplit(separator, string) =>
Json.obj(
"Fn::Split" -> Json.arr(
Json.fromString(separator),
string.asJson
))
case FnFindInMap(m, key1, key2) =>
Json.obj(
"Fn::FindInMap" -> Json.arr(
m.logicalId.asJson,
key1.asJson,
key2.asJson
))
case FnSelect(index, values) =>
Json.obj(
"Fn::Select" -> Json.arr(
Json.fromInt(index),
values.asJson
))
case FnSub(str, mappings) =>
Json.obj(
"Fn::Sub" ->
mappings.fold(Json.fromString(str))(
m =>
Json.arr(
Json.fromString(str),
m.asJson
)))
case FnGetAtt(logicalId, attr) =>
Json.obj(
"Fn::GetAtt" -> Json.arr(Json.fromString(logicalId),
Json.fromString(attr)))
case ResourceRef(resource) =>
Json.obj("Ref" -> Json.fromString(resource.logicalId))
case ParameterRef(resource) =>
Json.obj("Ref" -> Json.fromString(resource.logicalId))
case PseudoParameterRef(param) =>
Json.obj("Ref" -> Json.fromString(param.toString))
case x =>
throw new Exception(s"Unexpected expression $x")
}
implicit def encodeEnum[T: Enum]: Encoder[T] = Encoder.instance[T] { t =>
Json.fromString(implicitly[Enum[T]].encode(t))
}
implicit def encodeEnumMap[K, V](
implicit
enum: Enum[K],
mapEnc: Encoder[Map[String, V]]
): Encoder[Map[K, V]] =
mapEnc.contramap[Map[K, V]](_.map { case (k, v) => enum.encode(k) -> v })
implicit val encodeParamDataType: Encoder[Parameter.DataType] = {
import Parameter.DataType._
val awsEnum = implicitly[Enum[Parameter.AwsParamType]]
Encoder.instance[Parameter.DataType] { dt =>
val s = dt match {
case String => "String"
case Number => "Number"
case `List<Number>` => "List<Number>"
case CommaDelimitedList => "CommaDelimitedList"
case t: AwsTypeList => s"List<${awsEnum.encode(t.tpe)}>"
case t: AwsType => awsEnum.encode(t.tpe)
}
Json.fromString(s)
}
}
implicit val encodeAutoscalingPolicy: Encoder[AutoscalingCreationPolicy] =
deriveEncoder[AutoscalingCreationPolicy]
implicit val encodeResourceSignal: Encoder[ResourceSignal] =
deriveEncoder[ResourceSignal]
implicit val encodeCreationPolicy: Encoder[CreationPolicy] =
deriveEncoder[CreationPolicy]
implicit val encodeAutoScalingReplacingUpdate
: Encoder[AutoScalingReplacingUpdate] =
deriveEncoder[AutoScalingReplacingUpdate]
implicit val encodeAutoScalingRollingUpdate
: Encoder[AutoScalingRollingUpdate] =
deriveEncoder[AutoScalingRollingUpdate]
implicit val encodeAutoScalingScheduledAction
: Encoder[AutoScalingScheduledAction] =
deriveEncoder[AutoScalingScheduledAction]
implicit val encodeUpdatePolicy: Encoder[UpdatePolicy] =
deriveEncoder[UpdatePolicy]
implicit val encodeParam: Encoder[Parameter] =
Encoder.instance[Parameter] { p =>
val common = Json.obj(
"Type" -> p.Type.asJson,
"Description" -> p.Description.asJson,
"NoEcho" -> p.NoEcho.asJson
)
val specific = p match {
case sp: Parameter.Str =>
Json.obj(
"MaxLength" -> sp.MaxLength.asJson,
"MinLength" -> sp.MinLength.asJson,
"AllowedPattern" -> sp.AllowedPattern.asJson,
"ConstraintDescription" -> sp.ConstraintDescription.asJson,
"AllowedValues" -> sp.AllowedValues.asJson,
"Default" -> sp.Default.asJson
)
case np: Parameter.Integer =>
Json.obj(
"MaxValue" -> np.MaxValue.asJson,
"MinValue" -> np.MinValue.asJson,
"Default" -> np.Default.asJson
)
case np: Parameter.Double =>
Json.obj(
"MaxValue" -> np.MaxValue.asJson,
"MinValue" -> np.MinValue.asJson,
"Default" -> np.Default.asJson
)
case p: CommaDelimited =>
Json.obj(
"AllowedValues" -> p.AllowedValues.map(_.mkString(",")).asJson,
"Default" -> p.Default.map(_.mkString(",")).asJson
)
case _ => Json.obj()
}
Json.obj(p.logicalId -> common.deepMerge(specific))
}
implicit val encodeCondition: Encoder[Condition] = deriveEncoder[Condition]
implicit val encodeOutput: Encoder[Output] = Encoder.instance { o =>
Json.obj(
o.logicalId -> Json
.obj(
"Description" -> o.Description.asJson,
"Value" -> o.Value.asJson,
"Condition" -> o.Condition.map(_.logicalId).asJson
)
.deepMerge(o.Export.fold(Json.obj()) { e =>
Json.obj("Export" -> Json.obj("Name" -> e.asJson))
}))
}
implicit val encodeMapping: Encoder[Template.Mapping] = Encoder.instance {
o =>
Json.obj(o.logicalId -> o.value.asJson)
}
implicit val encodeTemplate: Encoder[Template] = Encoder.instance { t =>
Json.obj(
"AWSTemplateFormatVersion" -> Json.fromString("2010-09-09"),
"Description" -> t.Description.asJson,
"Metadata" -> t.Metadata.asJson,
"Parameters" -> foldKeyVals(t.Parameters),
"Mappings" -> foldKeyVals(t.Mappings),
"Conditions" -> foldKeyVals(t.Conditions),
"Resources" -> foldKeyVals(t.Resources.map(_.jsonEncode)),
"Outputs" -> foldKeyVals(t.Outputs)
)
}
implicit val cfInitCommandEncoder: Encoder[Command] = {
val enc: Encoder[Command] = deriveEncoder[Command]
Encoder.instance { c =>
Json.obj(c.logicalId -> enc(c).withObject(_.remove("logicalId").asJson))
}
}
implicit def cfInitFileEncoder[T <: File]: Encoder[T] = {
lazy val encS: Encoder[File.FromString] = deriveEncoder[File.FromString]
lazy val encU: Encoder[File.FromUrl] = deriveEncoder[File.FromUrl]
Encoder.instance { f =>
val encoded = f match {
case fS: File.FromString => encS(fS)
case fU: File.FromUrl => encU(fU)
}
Json.obj(f.path -> encoded.withObject(_.remove("path").asJson))
}
}
implicit val cfInitGroupEnc: Encoder[Group] = Encoder.instance { g =>
Json.obj(
g.logicalId -> Json.obj(
"gid" -> g.gid.asJson
))
}
implicit val cfInitPackagesEncoder: Encoder[Package] = Encoder.instance { p =>
val version = p.version match {
case Nil => Json.arr()
case v :: Nil =>
//lists of one signle URLs should be encoded as string
if (Try { new URL(v) }.isSuccess)
Json.fromString(v)
else
p.version.asJson
case other => p.version.asJson
}
Json.obj(p.name -> version)
}
implicit val cfInitServiceEncoder: Encoder[Service] = Encoder.instance {
srv =>
val enc: Encoder[Service] = deriveEncoder[Service]
Json.obj(srv.name -> enc(srv).withObject(_.remove("name").asJson))
}
implicit val cfInitSource: Encoder[Source] = Encoder.instance { src =>
Json.obj(src.targetDir -> Json.fromString(src.url))
}
implicit val cfInitUser: Encoder[User] = Encoder.instance { u =>
Json.obj(
u.username -> Json.obj(
"groups" -> u.groups.asJson,
"uid" -> u.uid.asJson,
"homeDir" -> u.homeDir.asJson
))
}
implicit def cfnInitServiceListEncoder[S <: Service.Services]: Encoder[S] =
Encoder.instance { srvs =>
val obj = emptyToNull(foldKeyVals(srvs.toList))
srvs match {
case Service.Sysvinit(_) =>
Json.obj("sysvinit" -> obj)
case Service.Windows(_) =>
Json.obj("windows" -> obj)
}
}
implicit val cfnInitConfigEncoder: Encoder[Init.Config] = Encoder.instance {
c =>
val pkgsByFormat: Map[String, Json] =
c.packages
.groupBy(p => implicitly[Enum[PackageFormat]].encode(p.format))
.mapValues(foldKeyVals(_))
def f = emptyToNull _
Json.obj(
c.logicalId -> Json.obj(
"commands" -> f(foldKeyVals(c.commands)),
"files" -> f(foldKeyVals(c.files)),
"groups" -> f(foldKeyVals(c.groups)),
"packages" -> pkgsByFormat.asJson,
"services" -> c.services.asJson,
"sources" -> f(foldKeyVals(c.sources)),
"users" -> f(foldKeyVals(c.users))
)
)
}
implicit val cfnInitEncoder: Encoder[Init] = Encoder.instance { i =>
Json.obj(
"AWS::CloudFormation::Init" -> Json
.obj(
"configSets" -> i.configSets.asJson
)
.deepMerge(foldKeyVals(i.configs.toList))
)
}
implicit val iamActionEncoder: Encoder[iam.Action] =
implicitly[Encoder[Seq[String]]].contramap(_.value)
implicit val encodeIamPrincipal: Encoder[iam.Principal] = {
import iam.Principal._
Encoder.instance {
case Aws(arns @ _*) => Json.obj("AWS" -> unwrapSingleton(arns))
case Service(values @ _*) => Json.obj("Service" -> values.asJson)
case CanonicalUser(value) => Json.obj("CanonicalUser" -> value.asJson)
case Federated(value) => Json.obj("Federated" -> value.asJson)
}
}
implicit val encodeIamCondition: Encoder[iam.Condition] =
Encoder.instance { c =>
val suffix = if (c.hasIfExists) "IfExists" else ""
val labelWithModifiers =
c.quantifier.fold[String](c.label)(q => s"${q.id}:${c.label}") ++ suffix
Json.obj(
labelWithModifiers -> Json.obj(
c.key.value -> unwrapSingleton(c.expressionEncoder(c.expected)))
)
}
implicit val encodeStatement: Encoder[iam.Statement] =
Encoder.instance { s =>
def invertibleKV[A: Encoder](key: String,
inv: iam.Invertible[A]): (String, Json) =
(if (inv.isPositive) key else s"Not$key") -> unwrapSingleton(
inv.value.asJson)
Json.obj(
Seq(
"Sid" -> s.Sid.asJson,
"Effect" -> Json.fromString(iam.Effect.effectEnum.encode(s.Effect)),
invertibleKV("Resource", s.Resource),
invertibleKV("Action", s.Action),
"Condition" -> foldKeyVals(s.Condition)
) ++ s.Principal
.map(p => Seq(invertibleKV("Principal", p)))
.getOrElse(Nil): _*)
}
implicit val encodePolicy: Encoder[iam.Policy] = deriveEncoder[iam.Policy]
private[cf] def unwrapSingleton(j: Json): Json =
j.withArray(arr => if (arr.size == 1) arr.head else arr.asJson)
private[cf] def unwrapSingleton[A: Encoder](as: Traversable[A]): Json =
if (as.size == 1) as.head.asJson else as.asJson
private[cf] def emptyToNull(o: Json): Json = {
val onArray: Vector[Json] => Json = arr =>
if (arr.isEmpty) Json.Null else arr.map(emptyToNull).asJson
val onObject: JsonObject => Json = obj =>
if (obj.isEmpty)
Json.Null
else
Json.obj(obj.toList.map {
case (k, v) =>
k -> emptyToNull(v)
}: _*)
o.arrayOrObject(o, onArray, onObject)
}
private[cf] def dropNull(o: Json): Json = {
val onArray: Vector[Json] => Json = arr =>
arr.foldLeft(Json.arr()) { (arr, el) =>
if (el.isNull)
arr
else
arr.withArray(x => (x :+ dropNull(el)).asJson)
}
val onObject: JsonObject => Json = obj =>
if (obj.isEmpty)
o
else
obj.toList
.foldLeft(JsonObject.empty) {
case (o, (k, v)) =>
if (v.isNull) o else o.add(k, dropNull(v))
}
.asJson
o.arrayOrObject(o, onArray, onObject)
}
private def foldKeyVals[A: Encoder](objects: List[A]): Json =
if (objects.isEmpty)
Json.Null
else
objects.foldRight(Json.obj()) {
case (item, o) =>
o.deepMerge(item.asJson)
}
}
| typeformation/typeformation | cf/src/main/scala/typeformation/cf/Encoding.scala | Scala | mit | 14,324 |
// Copyright (C) 2017 Calin Cruceru <calin.cruceru@stud.acs.upb.ro>.
//
// See the LICENCE file distributed with this work for additional
// information regarding copyright ownership.
package org.symnet
package models.iptables
package extensions.nat
import org.change.v2.analysis.expression.concrete.{ConstantValue, SymbolicValue}
import org.change.v2.analysis.expression.concrete.nonprimitive.:@
import org.change.v2.analysis.processingmodels.Instruction
import org.change.v2.analysis.processingmodels.instructions._
import org.change.v2.util.canonicalnames.{IPSrc, TcpSrc}
import types.net.{Ipv4, Port}
import core._
import extensions.filter.ProtocolMatch
object MasqueradeTargetExtension extends TargetExtension {
val targetParser = MasqueradeTarget.parser
}
case class MasqueradeTarget(
lowerPort: Option[Port],
upperPort: Option[Port]) extends Target {
type Self = MasqueradeTarget
/** This target is only valid in the 'nat' table, in the 'POSTROUTING'
* chain.
*
* The '--to-ports' option is only valid if the rule also specifies
* '-p tcp' or '-p udp'.
*/
override protected def validateIf(context: ValidationContext): Boolean = {
val chain = context.chain.get
val table = context.table.get
val rule = context.rule.get
// Check the table/chain in which this target is valid.
table.name == "nat" && (chain match {
case _ @ BuiltinChain("POSTROUTING", _, _) => true
case _ @ UserChain(_, _) => true
case _ => false
}) &&
// The existance of the upper port implies the existance of the lower
// one.
//
// upperPort -> lowerPort <=> !upperPort or lowerPort
//
(upperPort.isEmpty || lowerPort.isDefined) &&
// Check that 'tcp' or 'udp' is specified when either of the lower/upper
// ports are given.
//
// The existance of any of the lower/upper ports implies that '-p
// tcp/udp' must have been specified.
//
// lowerPort or upperPort -> tcp/udp
// but upperPort -> lowerPort =>
// => lowerPort -> tcp/udp <=> !lowerPort or tcp/udp
//
(lowerPort.isEmpty || ProtocolMatch.ruleMatchesTcpOrUdp(rule))
}
// NOTE: This is almost identical to SNAT; it differs only in that it uses the
// saved ip of the output port, instead of a specified port (range).
override def seflCode(options: SeflGenOptions): Instruction = {
// Get the name of the metadata tags.
val fromIp = virtdev.snatFromIp(options.deviceId)
val fromPort = virtdev.snatFromPort(options.deviceId)
val toIp = virtdev.snatToIp(options.deviceId)
val toPort = virtdev.snatToPort(options.deviceId)
InstructionBlock(
// Save original addresses.
Assign(fromIp, :@(IPSrc)),
Assign(fromPort, :@(TcpSrc)),
// Mangle IP address to the one of the interface this packet is going to
// leave the device.
Assign(IPSrc, :@(virtdev.OutputIpTag)),
// Mangle TCP/UDP port address.
Assign(TcpSrc, SymbolicValue()),
if (lowerPort.isDefined) {
// Get the port range to constrain to.
val (lower, upper) = (lowerPort.get, upperPort.getOrElse(lowerPort.get))
Constrain(TcpSrc, :&:(:>=:(ConstantValue(lower)),
:<=:(ConstantValue(upper))))
} else {
// Otherwise (from docs):
//
// If no port range is specified, then source ports below 512 will be
// mapped to other ports below 512: those between 512 and 1023
// inclusive will be mapped to ports below 1024, and other ports will
// be mapped to 1024 or above. Where possible, no port alteration
// will occur.
If(Constrain(fromPort, :<:(ConstantValue(512))),
// then
Constrain(TcpSrc, :<:(ConstantValue(512))),
// else
If(Constrain(fromPort, :<:(ConstantValue(1024))),
// then
Constrain(TcpSrc, :&:(:>=:(ConstantValue(512)),
:<:(ConstantValue(1024)))),
// else
Constrain(TcpSrc, :>=:(ConstantValue(1024)))))
},
// Save the new addresses.
Assign(toIp, :@(IPSrc)),
Assign(toPort, :@(TcpSrc)),
// In the end, we accept the packet.
Forward(options.acceptPort)
)
}
}
object MasqueradeTarget extends BaseParsers {
import ParserMP.monadPlusSyntax._
def parser: Parser[Target] =
for {
_ <- iptParsers.jumpOptionParser
// Parse the actual target
targetName <- someSpacesParser >> identifierParser
if targetName == "MASQUERADE"
// Parse the optional '--to-ports' target option
// ([--to-ports port[-port]]).
lowerPort <- optional(someSpacesParser >> parseString("--to-ports") >>
someSpacesParser >> portParser)
// Try to parse the upper bound port only if the previous one succeeded.
upperPort <- conditional(optional(parseChar('-') >> portParser),
lowerPort.isDefined)
} yield MasqueradeTarget(lowerPort, upperPort.flatten)
}
| calincru/iptables-sefl | src/main/scala/org/symnet/models/iptables/extensions/nat/MasqueradeTargetExtension.scala | Scala | mit | 5,112 |
import scala.reflect.runtime.universe._
import scala.reflect.runtime.{universe => ru}
import scala.reflect.runtime.{currentMirror => cm}
import scala.tools.reflect.{ToolBox, mkSilentFrontEnd}
object Test extends dotty.runtime.LegacyApp {
val toolbox = cm.mkToolBox(options = "-deprecation", frontEnd = mkSilentFrontEnd())
toolbox.eval(reify{
object Utils {
@deprecated("test", "2.10.0")
def foo: Unit = { println("hello") }
}
Utils.foo
}.tree)
println("============compiler messages============")
toolbox.frontEnd.infos.foreach(println(_))
println("=========================================")
}
| folone/dotty | tests/disabled/macro/run/toolbox_silent_reporter.scala | Scala | bsd-3-clause | 633 |
/*
* 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 bootstrap.liftweb
import _root_.net.liftweb.sitemap._
import _root_.net.liftweb.sitemap.Loc._
import de.fuberlin.wiwiss.silk.plugins.Plugins
import scala.xml.Text
import de.fuberlin.wiwiss.silk.workspace.{FileUser, User}
import de.fuberlin.wiwiss.silk.plugins.jena.JenaPlugins
import net.liftweb.http._
import js.jquery.JQuery14Artifacts
import net.liftweb.util.NamedPF
import net.liftmodules.widgets.autocomplete.AutoComplete
/**
* Configures the Silk Workbench WebApp.
*/
class Boot {
object UserManager extends SessionVar[User](new FileUser) {
override protected def onShutdown(session : CleanUpParam) {
is.dispose()
}
}
def boot {
User.userManager = UserManager.is _
Plugins.register()
JenaPlugins.register()
LiftRules.jsArtifacts = JQuery14Artifacts
LiftRules.maxMimeSize = 1024L * 1024L * 1024L
LiftRules.maxMimeFileSize = 1024L * 1024L * 1024L
//Workaround to fix hardcoded resource paths
if(!LiftRules.context.path.isEmpty) {
LiftRules.resourceServerPath = LiftRules.context.path.stripPrefix("/") + "/classpath"
ResourceServer.allow({
case _ => true
})
LiftRules.statelessDispatchTable.prepend(NamedPF("Classpath service") {
case r@Req(mainPath :: subPath, suffx, _) if (mainPath == "classpath") =>
ResourceServer.findResourceInClasspath(r, r.path.wholePath.drop(1))
})
}
AutoComplete.init()
// where to search snippet
LiftRules.addToPackages("de.fuberlin.wiwiss.silk.workbench.lift")
// Build SiteMap
val ifLinkingTaskOpen = If(() => User().linkingTaskOpen, () => RedirectResponse("index"))
val workspaceText = LinkText[Unit](_ => Text(if(User().projectOpen) "Workspace: " + User().project.name else "Workspace"))
val linkSpecText = LinkText[Unit](_ => Text("Editor: " + User().linkingTask.name))
val entries =
Menu(Loc("Workspace", List("index"), workspaceText)) ::
Menu(Loc("Editor", List("editor"), linkSpecText, ifLinkingTaskOpen)) ::
Menu(Loc("Generate Links", List("generateLinks"), "Generate Links", ifLinkingTaskOpen)) ::
Menu(Loc("Learn", List("learn"), "Learn", ifLinkingTaskOpen)) ::
Menu(Loc("Reference Links", List("referenceLinks"), "Reference Links", ifLinkingTaskOpen)) ::
Menu(Loc("Population", List("population"), "Population", ifLinkingTaskOpen)) ::
Nil
LiftRules.setSiteMap(SiteMap(entries:_*))
LiftRules.dispatch.prepend(Api.dispatch)
}
}
| fusepoolP3/p3-silk | silk-workbench-outdated/src/main/scala/bootstrap/liftweb/Boot.scala | Scala | apache-2.0 | 3,072 |
/**
* Copyright 2011-2017 GatlingCorp (http://gatling.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 io.gatling.charts.stats
import scala.collection.mutable
import io.gatling.commons.stats.{ Group, KO, Status }
import io.gatling.core.stats.message.MessageEvent
import io.gatling.core.stats.writer.{ RawErrorRecord, RawGroupRecord, RawRequestRecord, RawUserRecord }
private[stats] object UserRecordParser {
def unapply(array: Array[String]) = RawUserRecord.unapply(array).map(parseUserRecord)
private def parseUserRecord(strings: Array[String]): UserRecord = {
val scenario = strings(1)
val userId = strings(2)
val event = MessageEvent(strings(3))
val start = strings(4).toLong
val end = strings(5).toLong
UserRecord(scenario, userId, event, start, end)
}
}
private[stats] class RequestRecordParser(bucketFunction: Long => Int) {
def unapply(array: Array[String]) = RawRequestRecord.unapply(array).map(parseRequestRecord)
private def parseRequestRecord(strings: Array[String]): RequestRecord = {
val group = {
val groupString = strings(3)
if (groupString.isEmpty) None else Some(GroupRecordParser.parseGroup(groupString))
}
val request = strings(4)
val start = strings(5).toLong
val end = strings(6).toLong
val status = Status.apply(strings(7))
val errorMessage = if (status == KO) Some(strings(8)) else None
if (end != Long.MinValue) {
// regular request
RequestRecord(group, request, status, start, bucketFunction(start), bucketFunction(end), (end - start).toInt, errorMessage, incoming = false)
} else {
// unmatched incoming event
RequestRecord(group, request, status, start, bucketFunction(start), bucketFunction(start), 0, errorMessage, incoming = true)
}
}
}
private[stats] object GroupRecordParser {
val GroupCache = mutable.Map.empty[String, Group]
def parseGroup(string: String) = GroupCache.getOrElseUpdate(string, Group(string.split(",").toList))
}
private[stats] class GroupRecordParser(bucketFunction: Long => Int) {
def unapply(array: Array[String]) = RawGroupRecord.unapply(array).map(parseGroupRecord)
private def parseGroupRecord(strings: Array[String]): GroupRecord = {
val group = GroupRecordParser.parseGroup(strings(3))
val start = strings(4).toLong
val end = strings(5).toLong
val cumulatedResponseTime = strings(6).toInt
val status = Status.apply(strings(7))
val duration = (end - start).toInt
GroupRecord(group, duration, cumulatedResponseTime, status, start, bucketFunction(start))
}
}
private[stats] object ErrorRecordParser {
def unapply(array: Array[String]) = RawErrorRecord.unapply(array).map(parseErrorRecord)
private def parseErrorRecord(strings: Array[String]): ErrorRecord = {
val message = strings(1)
val timestamp = strings(2).toLong
ErrorRecord(message, timestamp)
}
}
private[stats] case class RequestRecord(group: Option[Group], name: String, status: Status, start: Long, startBucket: Int, endBucket: Int, responseTime: Int, errorMessage: Option[String], incoming: Boolean)
private[stats] case class GroupRecord(group: Group, duration: Int, cumulatedResponseTime: Int, status: Status, start: Long, startBucket: Int)
private[stats] case class UserRecord(scenario: String, userId: String, event: MessageEvent, start: Long, end: Long)
private[stats] case class ErrorRecord(message: String, timestamp: Long)
| MykolaB/gatling | gatling-charts/src/main/scala/io/gatling/charts/stats/Records.scala | Scala | apache-2.0 | 3,963 |
/*
* 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.primj.names
import ch.usi.inf.l3.sana
import sana.tiny
import sana.calcj
import tiny.names.Name
trait StdNames extends calcj.names.StdNames {
/** The name of the {{{void}}} "type" */
val VOID_TYPE_NAME = Name("void")
}
object StdNames extends StdNames
| amanjpro/languages-a-la-carte | primj/src/main/scala/names/StdNames.scala | Scala | bsd-3-clause | 1,866 |
package com.negrisoli.algorithms.implementation
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FunSuite
import BiggerIsGreater._
import BiggerIsGreater._
@RunWith(classOf[JUnitRunner])
class BiggerIsGreaterTest extends FunSuite {
test("test 'ab'") {
assert(solve("ab") === "ba")
}
test("test 'bb'") {
assert(solve("bb") === "no answer")
}
test("test 'hefg'") {
assert(solve("hefg") === "hegf")
}
test("test 'dkhc'") {
assert(solve("dkhc") === "hcdk")
}
test("test 'dldmsym'") {
assert(solve("dldmsym") === "dldmyms")
}
}
| rbatista/algorithms | challenges/hacker-rank/scala/src/test/scala/com/negrisoli/algorithms/implementation/BiggerIsGreaterTest.scala | Scala | mit | 625 |
/*
* This file is part of Parallel Dynamic Programming Automation Plugin Prototype (PDPAPP).
*
* PDPAPP is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PDPAPP 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PDPAPP. If not, see <http://www.gnu.org/licenses/>.
*/
package de.unikl.reitzig.paralleldynprog.automation
/**
* Marker objects for recursive calls
* @author Raphael Reitzig, 2012
*/
sealed abstract class Area() {
def apply() {}
}
case object L extends Area
case object UL extends Area
case object U extends Area
case object UR extends Area
case object Other extends Area
object Area {
def apply(a : String) = {
a match {
case "L" => L
case "UL" => UL
case "U" => U
case "UR" => UR
case _ => Other
}
}
}
/**
* Values to be used with @link{DynamicProgramming}.
*/
sealed abstract class Case()
case object Case1 extends Case
case object Case2 extends Case
case object Case3 extends Case
case object Detect extends Case
object Case {
def apply(s : String) = {
s match {
case "Case1" => Case1
case "Case2" => Case2
case "Case3" => Case3
case "Detect" => Detect
}
}
}
/**
* Annotation that marks a method as dynamic programming recursion
*/
class DynamicProgramming(val use : Case = Detect) extends scala.annotation.StaticAnnotation
| reitzig/2012_auto-parallel-dynprog_compiler | src/de/unikl/reitzig/paralleldynprog/automation/package.scala | Scala | gpl-3.0 | 1,799 |
///*
// * DARWIN Genetic Algorithms Framework Project.
// * Copyright (c) 2003, 2005, 2007, 2009, 2011, 2016, 2017. Phasmid Software
// *
// * Originally, developed in Java by Rubecula Software, LLC and hosted by SourceForge.
// * Converted to Scala by Phasmid Software and hosted by github at https://github.com/rchillyard/Darwin
// *
// * This file is part of Darwin.
// *
// * Darwin is free software: you can redistribute it and/or modify
// * it under the terms of the GNU General Public License as published by
// * the Free Software Foundation, either version 3 of the License, or
// * (at your option) any later version.
// *
// * This program 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 General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program. If not, see <http://www.gnu.org/licenses/>.
// */
//
//package com.phasmid.darwin.evolution
//
//import com.phasmid.darwin.base._
//import com.phasmid.darwin.eco.{Ecology, Environment, Fitness}
//import com.phasmid.darwin.genetics._
//import com.phasmid.darwin.run.Species
//import com.phasmid.laScala.fp.{Named, Streamer}
//import com.phasmid.laScala.{Prefix, Version}
//
//import scala.util.Try
//
///**
// * Created by scalaprof on 7/27/16.
// *
// * Definition of an organism and its behaviors.
// * An organism belongs to a Species and is able to reproduce.
// * It's nucleus is considered fixed: there are no changes to the nucleus after the organism is born.
// *
// * @tparam B the Base type
// * @tparam G the Gene type
// * @tparam P the Ploidy type
// * @tparam T the Trait type
// * @tparam V the Version (Generation) type
// * @tparam X the Eco-type
// */
//trait OldOrganism[B, G, P, T, V, X] extends Reproductive[OldOrganism[B, G, P, T, V, X]] with Sexual[P] with Individual[T, X] {
//
// /**
// * @return the generation during which this organism was formed
// */
// def generation: Version[V]
//
// /**
// * @return the species to which this organism belongs
// */
// def species: Species[B, G, P, T, X]
//
// /**
// * @return the nucleus of this organism
// */
// def nucleus: Nucleus[B]
//
// /**
// * @return the genotype of this organism
// */
// def genotype: Genotype[G, P] = species.genome(nucleus)
//
// /**
// * @return the phenotype of this organism
// */
// def phenotype: Phenotype[T] = species.phenome(genotype)
//
// /**
// * @param environment the Environment
// * @return the Fitness of this OldOrganism in the environment, wrapped in Try
// */
// def fitness(environment: Environment[T, X]): Try[Fitness] = environment.ecology(phenotype).fitness(environment.habitat)
//
//}
//
///**
// * Definition of an adapted organism, one that is adapted to an Ecology.
// * It is not generally fixed to a particular Habitat, but it its Ecology, and therefore its Adaptatype, is fixed.
// *
// * Created by scalaprof on 7/27/16.
// *
// * @tparam B the Base type
// * @tparam G the Gene type
// * @tparam P the Ploidy type
// * @tparam T the Trait type
// * @tparam V the Version (Generation) type
// * @tparam X the Eco-type
// */
//trait AdaptedOldOrganism[B, G, P, T, V, X] extends OldOrganism[B, G, P, T, V, X] {
//
// /**
// * @return the Ecology to which this organism is adapted
// */
// def ecology: Ecology[T, X]
//
// /**
// * @return the adaptatype for this organism
// */
// def adaptatype: Adaptatype[X] = ecology(phenotype)
//
// /**
// * Method to build a new AdaptedOldOrganism
// *
// * @param id the id of the new instance
// * @param generation the natal generation (version) of the new instance
// * @param species the species of the new instance
// * @param nucleus the nucleus of the new instance
// * @param ecology the ecology of the new instance
// * @return the new instance
// */
// def build(id: Named, generation: Version[V], species: Species[B, G, P, T, X], nucleus: Nucleus[B], ecology: Ecology[T, X]): OldOrganism[B, G, P, T, V, X]
//}
//
///**
// * Concrete case class which implements AdaptedOldOrganism and is Sexual (i.e. diploid).
// *
// * @param id the Identifier
// * @param generation the generation
// * @param species the species
// * @param nucleus the nucleus
// * @param ecology the ecology
// * @tparam B the Base type
// * @tparam G the Gene type
// * @tparam T the Trait type
// * @tparam V the Version (Generation) type
// * @tparam X the Eco-type
// */
//case class SexualAdaptedOldOrganism[B, G, T, V, X](id: Named, generation: Version[V], species: Species[B, G, Boolean, T, X], nucleus: Nucleus[B], ecology: Ecology[T, X]) extends Identified(id) with Mating[B, G, T, V, X, OldOrganism[B, G, Boolean, T, V, X]] with AdaptedOldOrganism[B, G, Boolean, T, V, X] with SelfAuditing with Identifiable {
// def build(id: Named, generation: Version[V], species: Species[B, G, Boolean, T, X], nucleus: Nucleus[B], ecology: Ecology[T, X]): OldOrganism[B, G, Boolean, T, V, X] = SexualAdaptedOldOrganism(id, generation, species, nucleus, ecology)
//
// def mate(evolvable: Evolvable[OldOrganism[B, G, Boolean, T, V, X]]): Iterable[OldOrganism[B, G, Boolean, T, V, X]] = ??? // TODO
//
// def pool: Evolvable[OldOrganism[B, G, Boolean, T, V, X]] = ??? // TODO
//
// override def render(indent: Int)(implicit tab: (Int) => Prefix): String = CaseIdentifiable.renderAsCaseClass(this.asInstanceOf[SexualAdaptedOldOrganism[Any, Any, Any, Any, Any]])(indent)
//}
//
//object SexualAdaptedOldOrganism {
//
// def apply[B, G, T, V, X](generation: Version[V], species: Species[B, G, Boolean, T, X], nucleus: Nucleus[B], ecology: Ecology[T, X])(implicit streamer: Streamer[Long]): SexualAdaptedOldOrganism[B, G, T, V, X] = new SexualAdaptedOldOrganism[B, G, T, V, X](IdentifierStrVerUID("sso", generation, streamer), generation, species, nucleus, ecology)
//
//}
//
///**
// * Concrete case class which implements AdaptedOldOrganism and is ASexual (i.e. haploid).
// *
// * @param id the Identifier
// * @param generation the generation
// * @param species the species
// * @param nucleus the nucleus
// * @param ecology the ecology
// * @tparam B the Base type
// * @tparam G the Gene type
// * @tparam T the Trait type
// * @tparam V the Version (Generation) type
// * @tparam X the Eco-type
// */
//case class Bacterium[B, G, T, V, X](id: Named, generation: Version[V], species: Species[B, G, Unit, T, X], nucleus: Nucleus[B], ecology: Ecology[T, X]) extends Identified(id) with ASexual[B, G, T, V, X, OldOrganism[B, G, Unit, T, V, X]] with AdaptedOldOrganism[B, G, Unit, T, V, X] with SelfAuditing {
//
// def fission: Iterable[OldOrganism[B, G, Unit, T, V, X]] = ??? // TODO
//
// def build(id: Named, generation: Version[V], species: Species[B, G, Unit, T, X], nucleus: Nucleus[B], ecology: Ecology[T, X]) = Bacterium(id, generation, species, nucleus, ecology)
//
// override def render(indent: Int)(implicit tab: (Int) => Prefix): String = CaseIdentifiable.renderAsCaseClass(this.asInstanceOf[Bacterium[Any, Any, Any, Any, Any]])(indent)
//}
//
//object Bacterium {
//
// def apply[B, G, T, V, X](generation: Version[V], species: Species[B, G, Unit, T, X], nucleus: Nucleus[B], ecology: Ecology[T, X])(implicit streamer: Streamer[Long]): Bacterium[B, G, T, V, X] = new Bacterium[B, G, T, V, X](IdentifierStrVerUID("sso", generation, streamer), generation, species, nucleus, ecology)
//}
//
//trait OldOrganismBuilder[Z] {
//
// def build[B, G, P, T, V, X](generation: Version[V], species: Species[B, G, P, T, X], nucleus: Nucleus[B], environment: Environment[T, X]): Z
//}
//
| rchillyard/Darwin | src/main/scala/com/phasmid/darwin/evolution/OldOrganism.scala | Scala | gpl-3.0 | 7,842 |
package unfiltered.directives
import unfiltered.request._
import unfiltered.response._
import scala.language.implicitConversions
trait Syntax extends Directives {
class Ops[X](x:X){
import Directive.{Eq, Gt, Lt}
def ===[V, T, R, A](v:V)(implicit eq:Eq[X, V, T, R, A]) = eq.directive(x, v)
def in[V, T, R, A](vs:Seq[V])(implicit eq:Eq[X, V, T, R, A]) = vs.map(v => eq.directive(x,v)).reduce(_ | _)
def gt[V, T, R, A](v:V)(implicit gtd:Gt[X, V, T, R, A]) = gtd.directive(x, v)
def > [V, T, R, A](v:V)(implicit gtd:Gt[X, V, T, R, A]) = gt(v)
def lt[V, T, R, A](v:V)(implicit ltd:Lt[X, V, T, R, A]) = ltd.directive(x, v)
def <[V, T, R, A](v:V)(implicit ltd:Lt[X, V, T, R, A]) = lt(v)
def lte[V, T, R, A](v:V)(implicit lted:Lt[X, V, T, R, A], eqd:Eq[X, V, T, R, A]) =
lted.directive(x, v) orElse eqd.directive(x, v)
def <=[V, T, R, A](v:V)(implicit ltd:Lt[X, V, T, R, A], eqd:Eq[X, V, T, R, A]) =
lte(v)
def gte[V, T, R, A](v:V)(implicit gtd:Gt[X, V, T, R, A], eq:Eq[X, V, T, R, A]) =
gtd.directive(x, v) orElse eq.directive(x, v)
def >=[V, T, R, A](v:V)(implicit gtd:Gt[X, V, T, R, A], eq:Eq[X, V, T, R, A]) = gte(v)
}
implicit def ops[X](x:X) = new Ops[X](x)
implicit def defMethod(M:Method) =
when{ case M(_) => } orElse MethodNotAllowed
implicit def accepting(A:Accepts.Accepting) =
when{ case A(_) => } orElse NotAcceptable
implicit def defQueryParams(q:QueryParams.type) =
queryParams
implicit def defExtract[A](Ex:Params.Extract[Nothing, A]) =
when{ case Params(Ex(a)) => a } orElse BadRequest
implicit def defPathIntent(p:Path.type) = PathIntentions
object PathIntentions {
@deprecated("Use Directive.Intent.Path", since="0.7.0")
def Intent[T] = Directive.Intent.Path[T]
}
implicit def defInterpreterIdentity[T] = data.Interpreter.identity[T]
implicit def defInterpreterString = data.as.String
}
| benhutchison/unfiltered | directives/src/main/scala/directives/Syntax.scala | Scala | mit | 1,925 |
/*
* Parts of the source code in this file is based on or copied the source code from the book Functional Programming in
* Scala.
* The original source code from Functional Programming in Scala can be found at https://github.com/fpinscala/fpinscala.
* These code sections are copyrighted by Manning Publications, Co. with the following license:
*
*
* Copyright (c) 2012, Manning Publications, Co.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
* OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*
* All other code are copyrighted by Emil Nilsson with the following license:
*
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Emil Nilsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.enil.chapter06
/**
* From Functional Programming in Scala.
*/
trait RNG {
def nextInt: (Int, RNG)
}
/**
* From Functional Programming in Scala.
*/
object RNG {
type Rand[+A] = RNG => (A, RNG)
val int: Rand[Int] = _.nextInt
def unit[A](a: A): Rand[A] =
rng => (a, rng)
def map[A, B](s: Rand[A])(f: A => B): Rand[B] =
rng => {
val (a, rng2) = s(rng)
(f(a), rng2)
}
/**
* @author Emil Nilsson
*/
def map2[A, B, C](ra: Rand[A], rb: Rand[B])(f: (A, B) => C): Rand[C] =
rng => {
val (a, rng2) = ra(rng)
val (b, rng3) = rb(rng2)
(f(a, b), rng3)
}
/**
* @author Emil Nilsson
*/
def sequence[A](s: List[Rand[A]]): Rand[List[A]] = {
rng => s match {
case r :: rs =>
val (a, rng2) = r(rng)
val (as, rng3) = sequence(rs)(rng2)
(a :: as, rng3)
case _ => (List(), rng)
}
}
/**
* @author Emil Nilsson
*/
def flatMap[A, B](f: Rand[A])(g: A => Rand[B]): Rand[B] =
rng => {
val (a, rng2) = f(rng)
g(a)(rng2)
}
def both[A, B](ra: Rand[A], rb: Rand[B]): Rand[(A, B)] =
map2(ra, rb)((_, _))
/**
* @author Emil Nilsson
*/
def nonNegativeInt(rng: RNG): (Int, RNG) = {
val (n, rng2) = rng.nextInt
val nn = if (n < 0) -n -1 else n
(nn, rng2)
}
/**
* @author Emil Nilsson
*/
def double(rng: RNG): (Double, RNG) = {
val (n, rng2) = nonNegativeInt(rng)
val f = (n % (Int.MaxValue - 1)).toFloat / Int.MaxValue
(f, rng2)
}
/**
* @author Emil Nilsson
*/
def intDouble(rng: RNG): ((Int, Double), RNG) = {
val (n, rng1) = rng.nextInt
val (f, rng2) = double(rng1)
((n, f), rng2)
}
/**
* @author Emil Nilsson
*/
def doubleInt(rng: RNG): ((Double, Int), RNG) = {
val (f, rng1) = double(rng)
val (n, rng2) = rng1.nextInt
((f, n), rng2)
}
/**
* @author Emil Nilsson
*/
def double3(rng: RNG): ((Double, Double, Double), RNG) = {
val (f1, rng1) = double(rng)
val (f2, rng2) = double(rng1)
val (f3, rng3) = double(rng2)
((f1, f2, f3), rng3)
}
/**
* @author Emil Nilsson
*/
def ints(count: Int)(rng: RNG): (List[Int], RNG) = {
if (count <= 0)
(List(), rng)
else {
val (n1, rng1) = rng.nextInt
val (ns, rng2) = ints(count - 1)(rng1)
(n1 :: ns, rng2)
}
}
/**
* @author Emil Nilsson
*/
def double2: RNG.Rand[Double] =
RNG.map(nonNegativeInt) { n =>
(n % (Int.MaxValue - 1)).toFloat / Int.MaxValue
}
def randIntDouble: Rand[(Int, Double)] =
both(int, double)
def randDoubleInt: Rand[(Double, Int)] =
both(double, int)
def randInts(count: Int): Rand[List[Int]] =
sequence(List.fill(count)(int))
/**
* @author Emil Nilsson
*/
def nonNegativeIntLessThan(n: Int): Rand[Int] =
flatMap(nonNegativeInt) { i =>
val mod = i % n
if (i + (n-1) - mod >= 0) unit(mod) else nonNegativeIntLessThan(n)
}
}
/**
* From Functional Programming in Scala.
*/
case class SimpleRNG(seed: Long) extends RNG {
def nextInt: (Int, RNG) = {
val newSeed = (seed * 0x5DEECE66DL + 0xBL) & 0xFFFFFFFFFFFFL
val nextRNG = SimpleRNG(newSeed)
val n = (newSeed >>> 16).toInt
(n, nextRNG)
}
}
/**
* A mock random number generator yielding values from a predefined list of numbers.
*
* @author Emil Nilsson
*/
case class MockRNG(ints: Seq[Int]) extends RNG {
def nextInt: (Int, RNG) = ints match {
case h :: t => (h, MockRNG(t))
case _ => throw new RuntimeException("Exhausted mock ints")
}
}
/**
* From Functional Programming in Scala.
*/
case class State[S, +A](run: S => (A, S)) {
/**
* @author Emil Nilsson
*/
def apply(s: S): (A, S) = run(s)
/**
* @author Emil Nilsson
*/
def map[B](f: A => B): State[S, B] =
flatMap(a => State.unit(f(a)))
/**
* @author Emil Nilsson
*/
def flatMap[B](f: A => State[S, B]): State[S, B] =
State { s =>
val (a, s2) = run(s)
f(a)(s2)
}
/**
* @author Emil Nilsson
*/
def map2[B, C](rb: State[S, B])(f: (A, B) => C): State[S, C] =
flatMap(a => rb.flatMap(b => State.unit(f(a, b))))
}
/**
* @author Emil Nilsson
*/
object State {
def unit[S, A](a: A): State[S, A] =
State { s => (a, s) }
def sequence[S, A](fs: List[State[S, A]]): State[S, List[A]] =
State(s => fs match {
case r :: rs =>
val (a, s2) = r(s)
val (as, s3) = sequence(rs)(s2)
(a :: as, s3)
case _ => (List(), s)
})
/**
* From Functional Programming in Scala.
*/
def modify[S](f: S => S): State[S, Unit] = for {
s <- get
_ <- set(f(s))
} yield ()
/**
* From Functional Programming in Scala.
*/
def get[S]: State[S, S] = State(s => (s, s))
/**
* From Functional Programming in Scala.
*/
def set[S](s: S): State[S, Unit] = State(_ => ((), s))
}
/**
* @author Emil Nilsson
*/
object Util {
/**
* Extension to compare two doubles to determine if they are approximately equal.
*/
implicit class DoubleExtensions(val d: Double) {
val epsilon = 1e-7
def near(d2: Double): Boolean = Math.abs(d - d2) < epsilon
}
}
/**
* Exercise 6.1: implement nonNegativeInt using RNG.nextInt.
*
* @author Emil Nilsson
*/
object Exercise61 {
def main (args: Array[String]): Unit = {
import RNG._
val rng = MockRNG(List(-1, -2, 3, 4))
val (n1, rng1) = nonNegativeInt(rng)
val (n2, rng2) = nonNegativeInt(rng1)
val (n3, rng3) = nonNegativeInt(rng2)
// make sure the returned RNG is in the correct state
val (n4, _) = rng3.nextInt
assert(n1 == 0) // -(-1) - 1
assert(n2 == 1) // -(-2) - 1
assert(n3 == 3)
assert(n4 == 4)
}
}
/**
* Exercise 6.2: implement double.
*
* @author Emil Nilsson
*/
object Exercise62 {
def main(args: Array[String]): Unit = {
import RNG._
import Util.DoubleExtensions
val rng = MockRNG(List(10000000, -20000000, 30000000))
val (f1, rng1) = double(rng)
val (f2, rng2) = double(rng1)
// make sure the returned RNG is in the correct state
val (n, _) = rng2.nextInt
assert(f1 near 0.0046566129) // (100000000 % ((2^31)-2)) / ((2^31)-1)
assert(f2 near 0.0093132253) // ((-(-20000000) - 1) % ((2^31)-2)) / ((2^31)-1)
assert(n == 30000000)
}
}
/**
* Exercise 6.3: implement intDouble, doubleInt and double3.
*
* @author Emil Nilsson
*/
object Exercise63 {
import RNG._
import Util.DoubleExtensions
val rng = MockRNG(List(10000000, 20000000, 30000000, 40000000, 50000000, 60000000, 70000000))
def main(args: Array[String]): Unit = {
testIntDouble
testDoubleInt
testDouble3
}
def testIntDouble: Unit = {
val ((n1, f1), rng1) = intDouble(rng)
val ((n2, f2), rng2) = intDouble(rng1)
// make sure the returned RNG is in the correct state
val (n3, _) = rng2.nextInt
assert(n1 == 10000000)
assert(f1 near 0.0093132258) // (20000000 % ((2^31)-2)) / ((2^31)-1)
assert(n2 == 30000000)
assert(f2 near 0.0186264515) // (40000000 % ((2^31)-2)) / ((2^31)-1)
assert(n3 == 50000000)
}
def testDoubleInt: Unit = {
val ((f1, n1), rng1) = doubleInt(rng)
val ((f2, n2), rng2) = doubleInt(rng1)
// make sure the returned RNG is in the correct state
val (n3, _) = rng2.nextInt
assert(f1 near 0.0046566129) // (10000000 % ((2^31)-2)) / ((2^31)-1)
assert(n1 == 20000000)
assert(f2 near 0.0139698386) // (30000000 % ((2^31)-2)) / ((2^31)-1)
assert(n2 == 40000000)
assert(n3 == 50000000)
}
def testDouble3: Unit = {
val ((f1, f2, f3), rng1) = double3(rng)
val ((f4, f5, f6), rng2) = double3(rng1)
// make sure the returned RNG is in the correct state
val (n, _) = rng2.nextInt
assert(f1 near 0.0046566129) // (10000000 % ((2^31)-2)) / ((2^31)-1)
assert(f2 near 0.0093132258) // (20000000 % ((2^31)-2)) / ((2^31)-1)
assert(f3 near 0.0139698386) // (30000000 % ((2^31)-2)) / ((2^31)-1)
assert(f4 near 0.0186264515) // (40000000 % ((2^31)-2)) / ((2^31)-1)
assert(f5 near 0.0232830644) // (50000000 % ((2^31)-2)) / ((2^31)-1)
assert(f6 near 0.0279396773) // (60000000 % ((2^31)-2)) / ((2^31)-1)
assert(n == 70000000)
}
}
/**
* Exercise 6.4: implement ints.
*
* @author Emil Nilsson
*/
object Exercise64 {
def main(args: Array[String]): Unit = {
import RNG._
val rng = MockRNG(List(1, 2, 3, 4))
val (ns1, rng1) = ints(3)(rng)
// make sure the returned RNG is in the correct state
val (n1, _) = rng1.nextInt
assert(ns1 == List(1, 2, 3))
assert(n1 == 4)
val (ns2, rng2) = ints(0)(rng)
// make sure the returned RNG is in the correct state
val (n2, _) = rng2.nextInt
assert(ns2 == List())
assert(n2 == 1)
}
}
/**
* Exercise 6.5: implement double using map.
*
* @author Emil Nilsson
*/
object Exercise65 {
def main(args: Array[String]): Unit = {
import RNG._
import Util.DoubleExtensions
val rng = MockRNG(List(10000000, -20000000, 30000000))
val (f1, rng1) = double2(rng)
val (f2, rng2) = double2(rng1)
// make sure the returned RNG is in the correct state
val (n, _) = rng2.nextInt
assert(f1 near 0.0046566129) // (100000000 % ((2^31)-2)) / ((2^31)-1)
assert(f2 near 0.0093132253) // ((-(-20000000) - 1) % ((2^31)-2)) / ((2^31)-1)
assert(n == 30000000)
}
}
/**
* Exercise 6.6: implement map2.
*
* @author Emil Nilsson
*/
object Exercise66 {
import RNG._
import Util.DoubleExtensions
val rng = MockRNG(List(10000000, 20000000, 30000000, 40000000, 50000000))
def main(args: Array[String]): Unit = {
testIntDouble
testDoubleInt
}
def testIntDouble: Unit = {
val ((n1, f1), rng1) = randIntDouble(rng)
val ((n2, f2), rng2) = randIntDouble(rng1)
// make sure the returned RNG is in the correct state
val (n3, _) = rng2.nextInt
assert(n1 == 10000000)
assert(f1 near 0.0093132258) // (20000000 % ((2^31)-2)) / ((2^31)-1)
assert(n2 == 30000000)
assert(f2 near 0.0186264515) // (40000000 % ((2^31)-2)) / ((2^31)-1)
assert(n3 == 50000000)
}
def testDoubleInt: Unit = {
val ((f1, n1), rng1) = randDoubleInt(rng)
val ((f2, n2), rng2) = randDoubleInt(rng1)
// make sure the returned RNG is in the correct state
val (n3, _) = rng2.nextInt
assert(f1 near 0.0046566129) // (10000000 % ((2^31)-2)) / ((2^31)-1)
assert(n1 == 20000000)
assert(f2 near 0.0139698386) // (30000000 % ((2^31)-2)) / ((2^31)-1)
assert(n2 == 40000000)
assert(n3 == 50000000)
}
}
/**
* Exercise 6.7: implement ints using sequence.
*
* @author Emil Nilsson
*/
object Exercise67 {
import RNG._
def main(args: Array[String]): Unit = {
val rng = MockRNG(List(1, 2, 3, 4))
val (ns1, rng1) = randInts(3)(rng)
// make sure the returned RNG is in the correct state
val (n1, _) = rng1.nextInt
assert(ns1 == List(1, 2, 3))
assert(n1 == 4)
val (ns2, rng2) = randInts(0)(rng)
// make sure the returned RNG is in the correct state
val (n2, _) = rng2.nextInt
assert(ns2 == List())
assert(n2 == 1)
}
}
/**
* Exercise 6.8: implement flatMap and use it to implement nonNegativeIntLessThan.
*
* @author Emil Nilsson
*/
object Exercise68 {
import RNG._
def main(args: Array[String]): Unit = {
val rng = MockRNG(List(Int.MaxValue, 1, 2, 3))
// first value should be rejected
val (n1, rng1) = nonNegativeIntLessThan(1000)(rng)
val (n2, rng2) = nonNegativeIntLessThan(1000)(rng1)
val (n3, _) = rng2.nextInt
assert(n1 == 1)
assert(n2 == 2)
assert(n3 == 3)
}
}
/**
* Exercise 6.9: implement map and map2 using flatMap.
*
* @author Emil Nilsson
*/
object Exercise69 {
import RNG.{Rand, flatMap, unit, int}
def main(args: Array[String]): Unit = {
val rng = MockRNG(List(1, 2, 3, 4))
val (s1, rng1) = map(int)(-_)(rng)
val (s2, rng2) = map2(int, int)(_ + _)(rng1)
// make sure the returned RNG is in the correct state
val (n, _) = rng2.nextInt
assert(s1 == -1)
assert(s2 == 5)
assert(n == 4)
}
def map[A, B](s: Rand[A])(f: A => B): Rand[B] =
flatMap(s)(a => unit(f(a)))
def map2[A, B, C](ra: Rand[A], rb: Rand[B])(f: (A, B) => C): Rand[C] =
flatMap(ra)(a => flatMap(rb)(b => unit(f(a, b))))
}
/**
* Exercise 6.10: implement unit, map, map2, flatMap and sequence for State.
*
* Reimplementations of functions generating random numbers are reimplemented for the State class to test the
* implementations.
*
* @author Emil Nilsson
*/
object Exercise610 {
import Util.DoubleExtensions
def main(args: Array[String]): Unit = {
testNonNegativeInt
testDouble
testNonNegativeIntLessThan
testRandIntDouble
testInts
}
def testNonNegativeInt: Unit = {
val rng = MockRNG(List(-1, -2, 3, 4))
val (n1, rng1) = nonNegativeInt(rng)
val (n2, rng2) = nonNegativeInt(rng1)
val (n3, rng3) = nonNegativeInt(rng2)
// make sure the returned RNG is in the correct state
val (n4, _) = rng3.nextInt
assert(n1 == 0) // -(-1) - 1
assert(n2 == 1) // -(-2) - 1
assert(n3 == 3)
assert(n4 == 4)
}
def testDouble: Unit = {
val rng = MockRNG(List(10000000, -20000000, 30000000))
val (f1, rng1) = double(rng)
val (f2, rng2) = double(rng1)
// make sure the returned RNG is in the correct state
val (n, _) = rng2.nextInt
assert(f1 near 0.0046566129) // (100000000 % ((2^31)-2)) / ((2^31)-1)
assert(f2 near 0.0093132253) // ((-(-20000000) - 1) % ((2^31)-2)) / ((2^31)-1)
assert(n == 30000000)
}
def testNonNegativeIntLessThan: Unit = {
val rng = MockRNG(List(Int.MaxValue, 1, 2, 3))
// first value should be rejected
val (n1, rng1) = nonNegativeIntLessThan(1000)(rng)
val (n2, rng2) = nonNegativeIntLessThan(1000)(rng1)
val (n3, _) = rng2.nextInt
assert(n1 == 1)
assert(n2 == 2)
assert(n3 == 3)
}
def testRandIntDouble: Unit = {
val rng = MockRNG(List(10000000, 20000000, 30000000, 40000000, 50000000))
val ((n1, f1), rng1) = randIntDouble(rng)
val ((n2, f2), rng2) = randIntDouble(rng1)
// make sure the returned RNG is in the correct state
val (n3, _) = rng2.nextInt
assert(n1 == 10000000)
assert(f1 near 0.0093132258) // (20000000 % ((2^31)-2)) / ((2^31)-1)
assert(n2 == 30000000)
assert(f2 near 0.0186264515) // (40000000 % ((2^31)-2)) / ((2^31)-1)
assert(n3 == 50000000)
}
def testInts: Unit = {
val rng = MockRNG(List(1, 2, 3, 4))
val (ns1, rng1) = ints(3)(rng)
// make sure the returned RNG is in the correct state
val (n1, _) = rng1.nextInt
assert(ns1 == List(1, 2, 3))
assert(n1 == 4)
val (ns2, rng2) = ints(0)(rng)
// make sure the returned RNG is in the correct state
val (n2, _) = rng2.nextInt
assert(ns2 == List())
assert(n2 == 1)
}
type Rand[A] = State[RNG, A]
val int: Rand[Int] = State { _.nextInt }
def nonNegativeInt: Rand[Int] = int.map { i =>
if (i < 0) -i - 1 else i
}
def double: Rand[Double] = nonNegativeInt.map { i =>
(i % (Int.MaxValue - 1)).toFloat / Int.MaxValue
}
def nonNegativeIntLessThan(n: Int): Rand[Int] = nonNegativeInt.flatMap { i =>
val mod = i % n
if (i + (n-1) - mod >= 0) State.unit(mod) else nonNegativeIntLessThan(n)
}
def both[A, B](ra: Rand[A], rb: Rand[B]): Rand[(A, B)] = (ra map2 rb)((_, _))
def randIntDouble: Rand[(Int, Double)] = both(int, double)
def ints(count: Int): Rand[List[Int]] = State.sequence(List.fill(count)(int))
}
/**
* Exercise 6.11: implement candy dispenser FSM using State.
*
* @author Emil Nilsson
*/
object Exercise611 {
val machine = Machine(locked = true, candies = 5, coins = 0)
def main(args: Array[String]): Unit = {
testBuySome
testBuyAll
}
def testBuySome: Unit = {
// successfully buys 3 out of 5 candies
val input: List[Input] = List(Coin, Turn, Turn, Turn, Coin, Coin, Turn, Coin, Turn, Turn)
val machine = Machine(locked = true, candies = 5, coins = 0)
val ((candies: Int, coins: Int), _) = simulateMachine(input)(machine)
assert(candies == 2)
assert(coins == 3)
}
def testBuyAll: Unit = {
// successfully buys all 5 candies
val input: List[Input] = List(Coin, Turn, Coin, Turn, Coin, Turn, Coin, Turn, Coin, Turn, Coin, Turn)
val machine = Machine(locked = true, candies = 5, coins = 0)
val ((candies: Int, coins: Int), _) = simulateMachine(input)(machine)
assert(candies == 0)
assert(coins == 5)
}
def simulateMachine(inputs: List[Input]): State[Machine, (Int, Int)] =
for {
_ <- State.sequence(inputs.map(Machine.process))
s <- State.get
} yield (s.candies, s.coins)
/**
* From Functional Programming in Scala.
*/
sealed trait Input
/**
* From Functional Programming in Scala.
*/
case object Coin extends Input
/**
* From Functional Programming in Scala.
*/
case object Turn extends Input
/**
* From Functional Programming in Scala.
*/
case class Machine(locked: Boolean, candies: Int, coins: Int)
/**
* From Functional Programming in Scala.
*/
object Machine {
/**
* @author Emil Nilsson
*/
def process(input: Input): State[Machine, Unit] = input match {
case Coin => insertCoin
case Turn => turnKnob
}
/**
* @author Emil Nilsson
*/
def insertCoin: State[Machine, Unit] = State.modify(s => (s.locked, s.candies) match {
case (true, c) if c > 0 => Machine(locked = false, s.candies, coins = s.coins + 1)
case _ => s
})
/**
* @author Emil Nilsson
*/
def turnKnob: State[Machine, Unit] = State.modify(s => (s.locked, s.candies) match {
case (false, c) if c > 0 => Machine(locked = true, candies = s.candies - 1, s.coins)
case _ => s
})
}
}
| enil/fpis-exercises | src/main/scala/io/github/enil/chapter06/ch06.scala | Scala | mit | 20,598 |
package recfun
import common._
import scala.collection.immutable.Stack
object Main {
def main(args: Array[String]) {
println("Pascal's Triangle")
for (row <- 0 to 10) {
for (col <- 0 to row)
print(pascal(col, row) + " ")
println()
}
}
/**
* Exercise 1
* Given column and row number of element in pascal's triangle, returns
* the value of that element.
*/
def pascal(c: Int, r: Int): Int = {
if (c == 0 || r == 0 || c == r) 1
// c cannot be greater than r in pascal's triangle, so this handles the
// edge case that we are calculating the value of an entry on the right
// hand edge of the triangle
else if (c > r) 0
else pascal(c-1, r-1) + pascal(c, r-1)
}
/**
* Exercise 2
* Parentheses Balancing: write a recursive function which verifies the
* balancing of parentheses.
* Idea behind the solution:
* -> keep a stack of parentheses thus far seen
* ->
*/
def balance(chars: List[Char]): Boolean = {
def balanceHelper(chars: List[Char], stack: Stack[Char]): Boolean = {
if (chars.isEmpty) stack.isEmpty
else if (chars.head == '(') balanceHelper(chars.tail, stack :+ '(')
else if (chars.head == ')' && !stack.isEmpty)
balanceHelper(chars.tail, stack pop)
else if (chars.head == ')' && stack.isEmpty)
// Encountered a mismatched ')', return false immediately.
false
else
// Element at head of list is not '(' or ')', continue iteration
// over string
balanceHelper(chars.tail, stack)
}
balanceHelper(chars, new Stack())
}
/**
* Exercise 3
* Write a recursive function that counts how many different ways you can make
* change for an amount, given a list of coin denominations.
* Implementation idea:
* - We cannot make change for money < 0 or when we have no coins
* - There is exactly one way to make change for money == 0 which is to
* simply return no change
* - For money > 0, we can make change a number of ways as follows:
* (i) If we use the coin at the head of the list, then we count the
* number of ways we can make change using all the coins in the list
* for the amount of money left to make change for (money - value of
* coin that we used)
* (ii)We can alternatively choose not to use the coin at the head of the
* list. Then the number of ways that we can make change is equal to
* the number of ways we can make change for money with the rest
* of the coins in the list.
*/
def countChange(money: Int, coins: List[Int]): Int = {
if (money < 0 || coins.isEmpty) 0
else if (money == 0) 1
else if (coins.isEmpty) 0
else
countChange(money - coins.head, coins) + countChange(money, coins.tail)
}
}
| mbabic/progfun | recfun/src/main/scala/recfun/Main.scala | Scala | unlicense | 2,872 |
package org.ensime.debug
import org.ensime.util._
import org.ensime.util.RichFile._
import org.ensime.util.FileUtils._
import org.ensime.config.ProjectConfig
import scala.collection.mutable.{ HashMap, ArrayBuffer }
import java.io._
import org.objectweb.asm._
import org.objectweb.asm.commons.EmptyVisitor
import scala.math._
case class DebugSourceLinePairs(pairs: Iterable[(String, Int)])
class ProjectDebugInfo(projectConfig: ProjectConfig) {
private val target: File = projectConfig.target.getOrElse(new File("."))
/**
* For each (classname,line) pair, return the corresponding
* (sourcefile,line) pair.
*/
def debugClassLocsToSourceLocs(pairs: Iterable[(String, Int)]): DebugSourceLinePairs = {
DebugSourceLinePairs(pairs.map { ea =>
findSourceForClass(ea._1) match {
case Some(s) => (s, ea._2)
case None => ("", ea._2)
}
})
}
/**
*
* Returns the unit whose bytecodes correspond to the given
* source location.
*
* @param source The source filename, without path information.
* @param line The source line
* @param packPrefix A possibly incomplete prefix of the desired unit's package
* @return The desired unit
*/
def findUnit(source: String, line: Int, packPrefix: String): Option[DebugUnit] = {
val units = sourceNameToUnits(source)
units.find { u =>
u.startLine <= line &&
u.endLine >= line &&
u.packageName.startsWith(packPrefix)
}
}
def findSourceForClass(className: String): Option[String] = {
val paths = classNameToSourcePath(className)
// TODO: Loss of precision here!
paths.headOption
}
private val sourceNameToSourcePath = new HashMap[String, ArrayBuffer[String]] {
override def default(s: String) = new ArrayBuffer[String]
}
projectConfig.sources.foreach { f =>
val paths = sourceNameToSourcePath(f.getName)
paths += f.getAbsolutePath
sourceNameToSourcePath(f.getName) = paths
}
private val classNameToSourcePath = new HashMap[String, ArrayBuffer[String]] {
override def default(s: String) = new ArrayBuffer[String]
}
private val sourceNameToUnits = new HashMap[String, ArrayBuffer[DebugUnit]] {
override def default(s: String) = new ArrayBuffer[DebugUnit]
}
if (target.exists && target.isDirectory) {
val classFiles = target.andTree.toList.filter { f =>
!f.isHidden && f.getName.endsWith(".class")
}
classFiles.foreach { f =>
val fs = new FileInputStream(f)
try {
val reader = new ClassReader(fs)
reader.accept(new EmptyVisitor() {
var qualName: String = null
var packageName: String = null
var sourceName: String = null
var startLine = Int.MaxValue
var endLine = Int.MinValue
override def visit(version: Int, access: Int,
name: String, signature: String, superName: String,
interfaces: Array[String]) {
if (name != null) {
qualName = name.replace("/", ".")
packageName = qualName.split(".").lastOption.getOrElse("")
println("")
println("--------")
println(qualName)
}
}
override def visitAttribute(att: Attribute) {
println("Attribute:" + att.`type`)
}
override def visitAnnotation(desc: String,
visibleAtRuntime: Boolean): AnnotationVisitor = {
println("Annotation: " + desc)
new EmptyVisitor() {
override def visit(name: String, value: Object) {
println(name)
}
override def visitArray(name: String): AnnotationVisitor = {
println("Array:" + name)
null
}
override def visitEnum(name: String, desc: String, value: String) {
println("Enum:" + name)
}
}
}
override def visitField(i: Int, s1: String,
s2: String, s3: String, a: Any): FieldVisitor = null
override def visitMethod(access: Int, name: String,
desc: String, signature: String,
exceptions: Array[String]): MethodVisitor = {
println("Method: " + signature + " " + name)
new EmptyVisitor() {
override def visitLineNumber(line: Int, start: Label) {
println(" line: " + line + ", label=" + start)
startLine = min(startLine, line)
endLine = max(endLine, line)
}
override def visitAttribute(att: Attribute) {}
override def visitAnnotation(desc: String,
visibleAtRuntime: Boolean): AnnotationVisitor = null
override def visitAnnotationDefault(): AnnotationVisitor = null
override def visitParameterAnnotation(parameter: Int,
desc: String, visible: Boolean): AnnotationVisitor = null
}
}
override def visitSource(source: String, debug: String) {
sourceName = source
}
override def visitEnd() {
val possibleSourcePaths = sourceNameToSourcePath(sourceName)
possibleSourcePaths.foreach { p =>
val paths = classNameToSourcePath(qualName)
paths += p
classNameToSourcePath(qualName) = paths
}
// Notice that a single name may resolve to many units.
// This is either due to many classes/objects declared in one file,
// or the fact that the mapping from source name to source path is
// one to many.
val units = sourceNameToUnits(sourceName)
val newU = new DebugUnit(startLine, endLine, f,
sourceName, packageName, qualName)
units += newU
// Sort in descending order of startLine, so first unit found will also be
// the most deeply nested.
val sortedUnits = units.sortWith { (a, b) => a.startLine > b.startLine }
sourceNameToUnits(sourceName) = sortedUnits
}
}, 0)
} catch {
case e: Exception => {
System.err.println("Error reading classfile.")
e.printStackTrace(System.err)
}
}
finally {
fs.close()
}
}
println("Finished parsing " + classFiles.length + " class files.")
}
}
class DebugUnit(
val startLine: Int,
val endLine: Int,
val classFile: File,
val sourceName: String,
val packageName: String,
val classQualName: String) {
override def toString = Map(
"startLine" -> startLine,
"endLine" -> endLine,
"classFile" -> classFile,
"sourceName" -> sourceName,
"packageName" -> packageName,
"classQualName" -> classQualName
).toString
}
| non/ensime | src/main/scala/org/ensime/debug/ProjectDebugInfo.scala | Scala | gpl-3.0 | 6,880 |
/*
* Copyright (C) 2016 Nikos Katzouris
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package oled.non_blocking
import akka.actor.{Actor, Props}
import app.runutils.IOHandling.InputSource
import app.runutils.{Globals, RunningOptions}
import com.typesafe.scalalogging.LazyLogging
import logic.Examples.Example
import logic.{Clause, LogicUtils, Theory}
import oled.distributed.Structures.{FinalTheoryMessage, Initiated, Terminated}
import oled.functions.DistributedOLEDFunctions.crossVal
/**
* Created by nkatz on 3/14/17.
*
*
* This actor starts two top-level actors to coordinate learning
* the initiated and the terminated part of the theory respectively.
*
*/
class Dispatcher[T <: InputSource](
val dataOptions: List[(T, T => Iterator[Example])],
val inputParams: RunningOptions,
val tasksNumber: Int,
testingDataOptions: T,
testingDataFunction: T => Iterator[Example]) extends Actor with LazyLogging {
private var counter = tasksNumber
private var initTheory = List[Clause]()
private var termTheory = List[Clause]()
private var initTrainingTime = ""
private var termTrainingTime = ""
private var theory = List[Clause]() // this is for future use with single-predicate learning
private var theoryTrainingTime = ""
private var initTotalMsgNum = 0
private var initTotalMsgSize = 0L
private var termTotalMsgNum = 0
private var termTotalMsgSize = 0L
def updateMessages(m: FinalTheoryMessage, what: String) = {
what match {
case "init" =>
initTotalMsgNum = m.totalMsgNum
initTotalMsgSize = m.totalMsgSize
case "term" =>
termTotalMsgNum = m.totalMsgNum
termTotalMsgSize = m.totalMsgSize
case _ => logger.info("UNKNOWN MESSAGE!")
}
}
def receive = {
case "go" =>
context.actorOf(Props(new TopLevelActor(dataOptions, inputParams, new Initiated)), name = "InitTopLevelActor") ! "go"
context.actorOf(Props(new TopLevelActor(dataOptions, inputParams, new Terminated)), name = "TermTopLevelActor") ! "go"
/*---------------------------------------------------------------------------*/
// For debugging (trying to see if the sub-linear speed-up is due to blocking)
/*---------------------------------------------------------------------------*/
case "go-no-communication" =>
context.actorOf(Props(new TopLevelActor(dataOptions, inputParams, new Initiated)), name = "InitTopLevelActor") ! "go-no-communication"
context.actorOf(Props(new TopLevelActor(dataOptions, inputParams, new Terminated)), name = "TermTopLevelActor") ! "go-no-communication"
case msg: FinalTheoryMessage =>
msg.targetPredicate match {
case x: Initiated =>
this.initTheory = msg.theory
this.initTrainingTime = msg.trainingTime
updateMessages(msg, "init")
case x: Terminated =>
this.termTheory = msg.theory
this.termTrainingTime = msg.trainingTime
updateMessages(msg, "term")
case _ =>
this.theory = msg.theory
this.theoryTrainingTime = msg.trainingTime
//updateMessages(msg)
}
counter -= 1
if (counter == 0) {
logger.info(s"\\n\\nThe initiated part of the theory is\\n${Theory(this.initTheory).showWithStats}\\nTraining" +
s" time: $initTrainingTime\\nTotal messages: $initTotalMsgNum\\nTotal message size: $initTotalMsgSize")
logger.info(s"\\n\\nThe terminated part of the theory is\\n${Theory(this.termTheory).showWithStats}\\nTraining" +
s" time: $termTrainingTime\\nTotal messages: $termTotalMsgNum\\nTotal message size: $termTotalMsgSize")
/*
* Cross-validation...
* */
val merged_ = Theory(this.initTheory ++ this.termTheory)
val compressed = Theory(LogicUtils.compressTheory(merged_.clauses))
/*------------------*/
// DEBUGGING-TESTING
/*------------------*/
//val filtered = Theory(compressed.clauses.filter(x => x.tps > 50))
val filtered = compressed
val data = testingDataFunction(testingDataOptions)
val (tps, fps, fns, precision, recall, fscore) =
crossVal(filtered, data = data, handCraftedTheoryFile = inputParams.evalth, globals = inputParams.globals, inps = inputParams)
val time = Math.max(this.initTrainingTime.toDouble, this.termTrainingTime.toDouble)
val theorySize = filtered.clauses.foldLeft(0)((x, y) => x + y.body.length + 1)
logger.info(s"\\ntps: $tps\\nfps: $fps\\nfns: $fns\\nprecision:" +
s" $precision\\nrecall: $recall\\nf-score: $fscore\\ntraining time: " +
s"$time\\ntheory size: $theorySize\\n" +
s"Total number of messages: ${initTotalMsgNum + termTotalMsgNum}\\n" +
s"Total message size: ${initTotalMsgSize + termTotalMsgSize}")
logger.info(s"\\nDone. Theory found:\\n ${filtered.showWithStats}")
logger.info(s"Mean time per batch: ${Globals.timeDebug.sum / Globals.timeDebug.length}")
logger.info(s"Total batch time: ${Globals.timeDebug.sum}")
context.system.terminate()
}
}
def showTheory(t: Theory) = {
val showClause = (c: Clause) => {
s"score (${if (c.head.functor == "initiatedAt") "precision" else "recall"}):" +
s"${c.score}, tps: ${c.tps}, fps: ${c.fps}, fns: ${c.fns} Evaluated on: ${c.seenExmplsNum} examples\\n$$c.tostring}"
}
t.clauses.map(x => showClause(x)).mkString("\\n")
}
/*
def crossVal() = {
val merged_ = Theory(this.initTheory ++ this.termTheory)
val compressed = Theory(LogicUtils.compressTheory(merged_.clauses))
/*------------------*/
// DEBUGGING-TESTING
/*------------------*/
//val filtered = Theory(compressed.clauses.filter(x => x.tps > 50))
val filtered = compressed
val crossValJep = new Jep()
val data = testingDataFunction(testingDataOptions)
val (tps,fps,fns,precision,recall,fscore) = crossVal(filtered, crossValJep, data = data, handCraftedTheoryFile = inps.evalth, globals = inps.globals, inps = inps)
val time = Math.max(this.initTrainingTime.toDouble, this.termTrainingTime.toDouble)
val theorySize = filtered.clauses.foldLeft(0)((x,y) => x + y.body.length + 1)
logger.info(s"\\ntps: $tps\\nfps: $fps\\nfns: $fns\\nprecision:" +
s" $precision\\nrecall: $recall\\nf-score: $fscore\\ntraining time: " +
s"$time\\ntheory size: $theorySize\\n" +
s"Total number of messages: ${initTotalMsgNum+termTotalMsgNum}\\n" +
s"Total message size: ${initTotalMsgSize+termTotalMsgSize}")
logger.info(s"\\nDone. Theory found:\\n ${filtered.showWithStats}")
logger.info(s"Mean time per batch: ${Globals.timeDebug.sum/Globals.timeDebug.length}")
logger.info(s"Total batch time: ${Globals.timeDebug.sum}")
crossValJep.close()
}
*/
}
| nkatzz/OLED | src/main/scala/oled/non_blocking/Dispatcher.scala | Scala | gpl-3.0 | 7,433 |
package net.walend.shipit2017a
import net.walend.present.{IFrame, SimpleSlide, Table}
import net.walend.present.Shortcuts._
/**
*
*
* @author dwalend
* @since 10/20/206
*/
object MoreKapow {
val Cover = SimpleSlide ("Return of the Tech Talks",
t("Return of the Tech Talks"),
st("Tech Talks Once Per Month","https://open.med.harvard.edu/wiki/display/CATSAND/Tech+Talks"),
blank,
st("Jillian Dudek, David Walend"),
st("HMS Catalyst Shipit, June, 2017")
)
val TechTalks = SimpleSlide("Tech Talks",
t("Tech Talks"),
l1("Revival of Dev Club"),
l1("Once a month - planned through November"),
l1("All of Catalyst Informatics is Welcome"),
l1("Talks will drill deeply into technical details"),
l1("Come geek out with us")
)
val TechTalksAudience = SimpleSlide("Tech Talk Topics",
t("Tech Talk Topics"),
l1("Technology and Working with Technologists"),
l1("Technical Tools"),
l1("Coding Practices"),
l1("How We Work Together"),
l1("Expect to see code, stats, diagrams")
)
val WikiPage = SimpleSlide("Tech Talk Wiki Page",
t("Tech Talk Wiki Pages"),
l1("Upcoming and Past Talks","https://open.med.harvard.edu/wiki/display/CATSAND/Tech+Talks"),
l1("Ideas","https://open.med.harvard.edu/wiki/display/CATSAND/Tech+Talk+Topic+Ideas")
)
val MoreKapowCover = SimpleSlide ("More Kapow!",
t("More Kapow!"),
st("Outlines to Presentations in Scala.js"),
st("Now With More Features"),
blank,
st("David Walend, Ben Carmen, ..."),
st("HMS Catalyst Shipit, June, 2017")
// st("Slides Online", "https://dwalend.github.io/Kapow/Kapow.html") //todo how to get the javascript ap on line?
)
val TableSlide = SimpleSlide("Tables",
t("Tables"),
Table(Array(l2("Table header")),Array(Array(l2("Cell 1"),l2("Cell 2"))))
)
val ScalaJs = SimpleSlide("Scala.js",
t("Scala.JS","https://www.scala-js.org/"),
l1("Write in Scala, compile to JavaScript (instead of JVM bytecodes)"),
l1("Use the best language to reach the most viable platform"),
l1("Potentially very valuable for SHRINE"),
l2("Gives us the same logic in the front- and back-end code"),
l2("Reuses our skillset"),
l2("A better choice for low-frequency AWS Lambda serverless systems"),
l1(f("Li Hoyi's blog on "),f("why Scala.js","http://www.lihaoyi.com/")) //todo fix link
)
val LittleLanguage = SimpleSlide("Little Language",
t("A DSL for Presentations"),
l1("Kapow! supplies a little language to turn outlines into presentations"),
c("""
| val SinglePageApp = SimpleSlide("SinglePageApp",
| t("A Presentation is a Single-Page Application"),
| l1(f("Kapow! translates the outline into html tags via "),f("ScalaTags","http://www.lihaoyi.com/scalatags/#ScalaTags")),
| l1("jQuery picks up left- and right- arrow keys to navigage"),
| l1("Simple CSS to set the look"),
| l1(f("highlights.js","https://highlightjs.org/usage/"),f(" to color the code"))
| )
""".stripMargin)
)
val SinglePageApp = SimpleSlide("SinglePageApp",
t("A Presentation is a Single-Page Application"),
l1(f("Kapow! translates the outline into html tags via "),f("ScalaTags","http://www.lihaoyi.com/scalatags/#ScalaTags")),
l1("jQuery picks up left- and right- arrow keys to navigage"),
l1("Simple CSS to set the look"),
l1(f("highlights.js","https://highlightjs.org/usage/"),f(" to color the code"))
)
val JqueryInScala = SimpleSlide("JQuery From Scala",
t(""""Javascript is like assembly code. It needs a compiler." - Mark Waks"""),
c("""
| def keyPressed(event:JQueryEventObject) = {
| val BACKWARDS_KEY = 37
| val FORWARDS_KEY = 39
|
| val index = if(event.which == BACKWARDS_KEY) currentSlideIndex - 1
| else if(event.which == FORWARDS_KEY) currentSlideIndex + 1
| else currentSlideIndex
| changeToSlide(index)
| }
""".stripMargin)
)
val Thanks = SimpleSlide("Thanks To",
l2("Li Hoyi - Scala.JS, ScalaTags library, questions about abstracting text and tags"),
l2("Mark Waks - Local Scala.JS evangelist"),
l2("isagalaev - highlights.js"),
l2("Greg - Pointer to Processing.js"),
l2("""Ankit - "Just put the link tag there and it'll pull in the CSS""""),
l2("""Sherry - "That part is working fine... Read the docs""""),
l2("Ben - div tag, yes use jQuery, peer programming CSS")
)
val slides = Seq(Cover,TechTalks,TechTalksAudience,WikiPage)//MoreKapowCover,TableSlide,ScalaJs,JqueryInScala,SinglePageApp,LittleLanguage,Thanks)
}
//todo a slide about shrine and gage the room
| dwalend/ScalaJSPresent | src/main/scala/net/walend/shipit2017a/MoreKapow.scala | Scala | apache-2.0 | 4,776 |
/*
* Copyright (c) 2013-2014 Telefónica Investigación y Desarrollo S.A.U.
*
* 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 es.tid.cosmos.infinity.server.hadoop
import java.io.InputStream
import es.tid.cosmos.infinity.common.fs.Path
import es.tid.cosmos.infinity.server.util.ToClose
/** An abstraction for an HDFS Data node service. */
trait DataNode extends UserPrivileges {
/** Retrieve the file contents corresponding to the given path.
*
* @param path The path whose content is to be obtained
* @param offset The optional offset from where to start reading the content
* @param length The optional length of content to read from the given offset
* @return The content part as per offset and length.
* The content is provided as an autocloseable stream.
* Use [[ToClose.useAndClose]] to safely read the content part.
*/
@throws[HdfsException.IOError]
@throws[HdfsException.Unauthorized]
def open(path: Path, offset: Option[Long], length: Option[Long]): ToClose[InputStream]
/** Add content to the existing content of the file located at the given path.
*
* @param path The path of the file where the content is to be added
* @param contentStream The stream from where to read the content to be added.
* <b>Note:</b> It is left to the client's discretion to close the stream.
* e.g. You can use
* [[es.tid.cosmos.infinity.server.util.IoUtil.withAutoClose]]
* to automatically release the stream.
*/
@throws[HdfsException.IOError]
@throws[HdfsException.Unauthorized]
def append(path: Path, contentStream: InputStream): Unit
/** Overwrite the content of the file located at the given path.
*
* @param path The path of the file where the content is to be written
* @param contentStream The stream from where to read to content that will ovewrite the file.
* <b>Note:</b> It is left to the client's discretion to close the stream.
* e.g. You can use
* [[es.tid.cosmos.infinity.server.util.IoUtil.withAutoClose]]
* to automatically release the stream.
*/
@throws[HdfsException.IOError]
@throws[HdfsException.Unauthorized]
def overwrite(path: Path, contentStream: InputStream): Unit
}
| telefonicaid/fiware-cosmos-platform | infinity/server/src/main/scala/es/tid/cosmos/infinity/server/hadoop/DataNode.scala | Scala | apache-2.0 | 2,953 |
package rere.ql.rasterization
import java.nio.charset.Charset
import akka.util.ByteString
trait Renderer {
def ~~(string: String): this.type
def ~~(byteString: ByteString): this.type
def get: ByteString
}
class ByteStringRenderer(encoding: Charset) extends Renderer {
import akka.util._
val builder = new ByteStringBuilder
def ~~(str: String): this.type = {
builder.putBytes(str.getBytes(encoding))
this
}
def ~~(byteString: ByteString): this.type = {
builder ++= byteString
this
}
def get: ByteString = builder.result()
}
| pbaun/rere | modules/ql/src/main/scala/rere/ql/rasterization/Renderer.scala | Scala | apache-2.0 | 568 |
package bootstrap.liftweb
/* *\
(c) 2007-2008 WorldWide Conferencing, LLC
Distributed under an Apache License
http://www.apache.org/licenses/LICENSE-2.0
\* */
import _root_.net.liftweb.util.{Helpers, Box, Empty, Full, Failure, Log, NamedPF}
import _root_.net.liftweb.http._
import _root_.net.liftweb.mapper._
import Helpers._
import _root_.net.liftweb.mapper.{DB, ConnectionManager, Schemifier, DefaultConnectionIdentifier, ConnectionIdentifier}
import _root_.java.sql.{Connection, DriverManager}
import _root_.javax.servlet.http.{HttpServlet, HttpServletRequest , HttpServletResponse, HttpSession}
import _root_.com.skittr.model._
import _root_.com.skittr.actor._
/**
* A class that's instantiated early and run. It allows the application
* to modify lift's environment
*/
class Boot {
def modelList = List[BaseMetaMapper](User, Friend, MsgStore)
def boot {
if (!DB.jndiJdbcConnAvailable_?) DB.defineConnectionManager(DefaultConnectionIdentifier, DBVendor)
LiftRules.addToPackages("com.skittr")
// make sure the database is up to date
Schemifier.schemify(true, Log.infoF _, modelList :_*)
if ((System.getProperty("create_users") != null) && User.count < User.createdCount) User.createTestUsers
// map certain urls to the right place
val rewriter: LiftRules.RewritePF = NamedPF("User and Friend mapping") {
case RewriteRequest(ParsePath("user" :: user :: _, _, _,_), _, _) =>
RewriteResponse("user" :: Nil, Map("user" -> user))
case RewriteRequest(ParsePath("friend" :: user :: _, _, _,_), _, _) =>
RewriteResponse("friend" :: Nil, Map("user" -> user))
case RewriteRequest(ParsePath("unfriend" :: user :: _, _, _, _), _, _) =>
RewriteResponse("unfriend" :: Nil, Map("user" -> user))
}
LiftRules.rewrite.prepend(rewriter)
// load up the list of user actors
UserList.create
}
}
/**
* A singleton that vends a database connection to a Derby database
*/
object DBVendor extends ConnectionManager {
def newConnection(name: ConnectionIdentifier): Box[Connection] = {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver")
val dm = DriverManager.getConnection("jdbc:derby:skittr;create=true")
Full(dm)
} catch {
case e : Exception => e.printStackTrace; Empty
}
}
def releaseConnection(conn: Connection) {conn.close}
}
| andreum/liftweb | sites/skittr/src/main/scala/bootstrap/liftweb/Boot.scala | Scala | apache-2.0 | 2,456 |
/*
* Copyright (c) 2014-2019 Israel Herraiz <isra@herraiz.org>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// ---------------------
// Test for example 3.25
// ---------------------
package chap03
import adt._
import org.specs2.mutable._
object Ex25Spec extends Specification {
"The size function" should {
"works with a single leaf tree" in {
Ex25.size(Leaf(0)) mustEqual 1
}
"gives the right size for some simple trees" in {
val tree2 = Branch(Leaf(1.4),Leaf(2.5))
Ex25.size(tree2) mustEqual 2
val tree3 = Branch(tree2, Leaf(7.6))
Ex25.size(tree3) mustEqual 3
val tree5a = Branch(tree2, tree3)
val tree5b = Branch(tree2, tree3)
Ex25.size(tree5a) mustEqual 5
Ex25.size(tree5b) mustEqual 5
val tree4 = Branch(tree2, tree2)
Ex25.size(tree4) mustEqual 4
val tree9 = Branch(tree4, tree5b)
Ex25.size(tree9) mustEqual 9
}
}
}
| iht/fpinscala | src/test/scala/chap03/ex25Spec.scala | Scala | mit | 1,979 |
/*
* 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.parquet
import java.lang.{Boolean => JBoolean, Double => JDouble, Float => JFloat, Long => JLong}
import java.math.{BigDecimal => JBigDecimal}
import java.sql.{Date, Timestamp}
import java.time.{Instant, LocalDate}
import java.util.Locale
import scala.collection.JavaConverters.asScalaBufferConverter
import org.apache.parquet.filter2.predicate._
import org.apache.parquet.filter2.predicate.SparkFilterApi._
import org.apache.parquet.io.api.Binary
import org.apache.parquet.schema.{DecimalMetadata, GroupType, MessageType, OriginalType, PrimitiveComparator, PrimitiveType, Type}
import org.apache.parquet.schema.OriginalType._
import org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName
import org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName._
import org.apache.spark.sql.catalyst.util.{CaseInsensitiveMap, DateTimeUtils}
import org.apache.spark.sql.sources
import org.apache.spark.unsafe.types.UTF8String
/**
* Some utility function to convert Spark data source filters to Parquet filters.
*/
class ParquetFilters(
schema: MessageType,
pushDownDate: Boolean,
pushDownTimestamp: Boolean,
pushDownDecimal: Boolean,
pushDownStartWith: Boolean,
pushDownInFilterThreshold: Int,
caseSensitive: Boolean) {
// A map which contains parquet field name and data type, if predicate push down applies.
//
// Each key in `nameToParquetField` represents a column; `dots` are used as separators for
// nested columns. If any part of the names contains `dots`, it is quoted to avoid confusion.
// See `org.apache.spark.sql.connector.catalog.quote` for implementation details.
private val nameToParquetField : Map[String, ParquetPrimitiveField] = {
// Recursively traverse the parquet schema to get primitive fields that can be pushed-down.
// `parentFieldNames` is used to keep track of the current nested level when traversing.
def getPrimitiveFields(
fields: Seq[Type],
parentFieldNames: Array[String] = Array.empty): Seq[ParquetPrimitiveField] = {
fields.flatMap {
case p: PrimitiveType =>
Some(ParquetPrimitiveField(fieldNames = parentFieldNames :+ p.getName,
fieldType = ParquetSchemaType(p.getOriginalType,
p.getPrimitiveTypeName, p.getTypeLength, p.getDecimalMetadata)))
// Note that when g is a `Struct`, `g.getOriginalType` is `null`.
// When g is a `Map`, `g.getOriginalType` is `MAP`.
// When g is a `List`, `g.getOriginalType` is `LIST`.
case g: GroupType if g.getOriginalType == null =>
getPrimitiveFields(g.getFields.asScala.toSeq, parentFieldNames :+ g.getName)
// Parquet only supports push-down for primitive types; as a result, Map and List types
// are removed.
case _ => None
}
}
val primitiveFields = getPrimitiveFields(schema.getFields.asScala.toSeq).map { field =>
import org.apache.spark.sql.connector.catalog.CatalogV2Implicits.MultipartIdentifierHelper
(field.fieldNames.toSeq.quoted, field)
}
if (caseSensitive) {
primitiveFields.toMap
} else {
// Don't consider ambiguity here, i.e. more than one field is matched in case insensitive
// mode, just skip pushdown for these fields, they will trigger Exception when reading,
// See: SPARK-25132.
val dedupPrimitiveFields =
primitiveFields
.groupBy(_._1.toLowerCase(Locale.ROOT))
.filter(_._2.size == 1)
.mapValues(_.head._2)
CaseInsensitiveMap(dedupPrimitiveFields.toMap)
}
}
/**
* Holds a single primitive field information stored in the underlying parquet file.
*
* @param fieldNames a field name as an array of string multi-identifier in parquet file
* @param fieldType field type related info in parquet file
*/
private case class ParquetPrimitiveField(
fieldNames: Array[String],
fieldType: ParquetSchemaType)
private case class ParquetSchemaType(
originalType: OriginalType,
primitiveTypeName: PrimitiveTypeName,
length: Int,
decimalMetadata: DecimalMetadata)
private val ParquetBooleanType = ParquetSchemaType(null, BOOLEAN, 0, null)
private val ParquetByteType = ParquetSchemaType(INT_8, INT32, 0, null)
private val ParquetShortType = ParquetSchemaType(INT_16, INT32, 0, null)
private val ParquetIntegerType = ParquetSchemaType(null, INT32, 0, null)
private val ParquetLongType = ParquetSchemaType(null, INT64, 0, null)
private val ParquetFloatType = ParquetSchemaType(null, FLOAT, 0, null)
private val ParquetDoubleType = ParquetSchemaType(null, DOUBLE, 0, null)
private val ParquetStringType = ParquetSchemaType(UTF8, BINARY, 0, null)
private val ParquetBinaryType = ParquetSchemaType(null, BINARY, 0, null)
private val ParquetDateType = ParquetSchemaType(DATE, INT32, 0, null)
private val ParquetTimestampMicrosType = ParquetSchemaType(TIMESTAMP_MICROS, INT64, 0, null)
private val ParquetTimestampMillisType = ParquetSchemaType(TIMESTAMP_MILLIS, INT64, 0, null)
private def dateToDays(date: Any): Int = date match {
case d: Date => DateTimeUtils.fromJavaDate(d)
case ld: LocalDate => DateTimeUtils.localDateToDays(ld)
}
private def timestampToMicros(v: Any): JLong = v match {
case i: Instant => DateTimeUtils.instantToMicros(i)
case t: Timestamp => DateTimeUtils.fromJavaTimestamp(t)
}
private def decimalToInt32(decimal: JBigDecimal): Integer = decimal.unscaledValue().intValue()
private def decimalToInt64(decimal: JBigDecimal): JLong = decimal.unscaledValue().longValue()
private def decimalToByteArray(decimal: JBigDecimal, numBytes: Int): Binary = {
val decimalBuffer = new Array[Byte](numBytes)
val bytes = decimal.unscaledValue().toByteArray
val fixedLengthBytes = if (bytes.length == numBytes) {
bytes
} else {
val signByte = if (bytes.head < 0) -1: Byte else 0: Byte
java.util.Arrays.fill(decimalBuffer, 0, numBytes - bytes.length, signByte)
System.arraycopy(bytes, 0, decimalBuffer, numBytes - bytes.length, bytes.length)
decimalBuffer
}
Binary.fromConstantByteArray(fixedLengthBytes, 0, numBytes)
}
private def timestampToMillis(v: Any): JLong = {
val micros = timestampToMicros(v)
val millis = DateTimeUtils.microsToMillis(micros)
millis.asInstanceOf[JLong]
}
private val makeEq:
PartialFunction[ParquetSchemaType, (Array[String], Any) => FilterPredicate] = {
case ParquetBooleanType =>
(n: Array[String], v: Any) => FilterApi.eq(booleanColumn(n), v.asInstanceOf[JBoolean])
case ParquetByteType | ParquetShortType | ParquetIntegerType =>
(n: Array[String], v: Any) => FilterApi.eq(
intColumn(n),
Option(v).map(_.asInstanceOf[Number].intValue.asInstanceOf[Integer]).orNull)
case ParquetLongType =>
(n: Array[String], v: Any) => FilterApi.eq(longColumn(n), v.asInstanceOf[JLong])
case ParquetFloatType =>
(n: Array[String], v: Any) => FilterApi.eq(floatColumn(n), v.asInstanceOf[JFloat])
case ParquetDoubleType =>
(n: Array[String], v: Any) => FilterApi.eq(doubleColumn(n), v.asInstanceOf[JDouble])
// Binary.fromString and Binary.fromByteArray don't accept null values
case ParquetStringType =>
(n: Array[String], v: Any) => FilterApi.eq(
binaryColumn(n),
Option(v).map(s => Binary.fromString(s.asInstanceOf[String])).orNull)
case ParquetBinaryType =>
(n: Array[String], v: Any) => FilterApi.eq(
binaryColumn(n),
Option(v).map(b => Binary.fromReusedByteArray(v.asInstanceOf[Array[Byte]])).orNull)
case ParquetDateType if pushDownDate =>
(n: Array[String], v: Any) => FilterApi.eq(
intColumn(n),
Option(v).map(date => dateToDays(date).asInstanceOf[Integer]).orNull)
case ParquetTimestampMicrosType if pushDownTimestamp =>
(n: Array[String], v: Any) => FilterApi.eq(
longColumn(n),
Option(v).map(timestampToMicros).orNull)
case ParquetTimestampMillisType if pushDownTimestamp =>
(n: Array[String], v: Any) => FilterApi.eq(
longColumn(n),
Option(v).map(timestampToMillis).orNull)
case ParquetSchemaType(DECIMAL, INT32, _, _) if pushDownDecimal =>
(n: Array[String], v: Any) => FilterApi.eq(
intColumn(n),
Option(v).map(d => decimalToInt32(d.asInstanceOf[JBigDecimal])).orNull)
case ParquetSchemaType(DECIMAL, INT64, _, _) if pushDownDecimal =>
(n: Array[String], v: Any) => FilterApi.eq(
longColumn(n),
Option(v).map(d => decimalToInt64(d.asInstanceOf[JBigDecimal])).orNull)
case ParquetSchemaType(DECIMAL, FIXED_LEN_BYTE_ARRAY, length, _) if pushDownDecimal =>
(n: Array[String], v: Any) => FilterApi.eq(
binaryColumn(n),
Option(v).map(d => decimalToByteArray(d.asInstanceOf[JBigDecimal], length)).orNull)
}
private val makeNotEq:
PartialFunction[ParquetSchemaType, (Array[String], Any) => FilterPredicate] = {
case ParquetBooleanType =>
(n: Array[String], v: Any) => FilterApi.notEq(booleanColumn(n), v.asInstanceOf[JBoolean])
case ParquetByteType | ParquetShortType | ParquetIntegerType =>
(n: Array[String], v: Any) => FilterApi.notEq(
intColumn(n),
Option(v).map(_.asInstanceOf[Number].intValue.asInstanceOf[Integer]).orNull)
case ParquetLongType =>
(n: Array[String], v: Any) => FilterApi.notEq(longColumn(n), v.asInstanceOf[JLong])
case ParquetFloatType =>
(n: Array[String], v: Any) => FilterApi.notEq(floatColumn(n), v.asInstanceOf[JFloat])
case ParquetDoubleType =>
(n: Array[String], v: Any) => FilterApi.notEq(doubleColumn(n), v.asInstanceOf[JDouble])
case ParquetStringType =>
(n: Array[String], v: Any) => FilterApi.notEq(
binaryColumn(n),
Option(v).map(s => Binary.fromString(s.asInstanceOf[String])).orNull)
case ParquetBinaryType =>
(n: Array[String], v: Any) => FilterApi.notEq(
binaryColumn(n),
Option(v).map(b => Binary.fromReusedByteArray(v.asInstanceOf[Array[Byte]])).orNull)
case ParquetDateType if pushDownDate =>
(n: Array[String], v: Any) => FilterApi.notEq(
intColumn(n),
Option(v).map(date => dateToDays(date).asInstanceOf[Integer]).orNull)
case ParquetTimestampMicrosType if pushDownTimestamp =>
(n: Array[String], v: Any) => FilterApi.notEq(
longColumn(n),
Option(v).map(timestampToMicros).orNull)
case ParquetTimestampMillisType if pushDownTimestamp =>
(n: Array[String], v: Any) => FilterApi.notEq(
longColumn(n),
Option(v).map(timestampToMillis).orNull)
case ParquetSchemaType(DECIMAL, INT32, _, _) if pushDownDecimal =>
(n: Array[String], v: Any) => FilterApi.notEq(
intColumn(n),
Option(v).map(d => decimalToInt32(d.asInstanceOf[JBigDecimal])).orNull)
case ParquetSchemaType(DECIMAL, INT64, _, _) if pushDownDecimal =>
(n: Array[String], v: Any) => FilterApi.notEq(
longColumn(n),
Option(v).map(d => decimalToInt64(d.asInstanceOf[JBigDecimal])).orNull)
case ParquetSchemaType(DECIMAL, FIXED_LEN_BYTE_ARRAY, length, _) if pushDownDecimal =>
(n: Array[String], v: Any) => FilterApi.notEq(
binaryColumn(n),
Option(v).map(d => decimalToByteArray(d.asInstanceOf[JBigDecimal], length)).orNull)
}
private val makeLt:
PartialFunction[ParquetSchemaType, (Array[String], Any) => FilterPredicate] = {
case ParquetByteType | ParquetShortType | ParquetIntegerType =>
(n: Array[String], v: Any) =>
FilterApi.lt(intColumn(n), v.asInstanceOf[Number].intValue.asInstanceOf[Integer])
case ParquetLongType =>
(n: Array[String], v: Any) => FilterApi.lt(longColumn(n), v.asInstanceOf[JLong])
case ParquetFloatType =>
(n: Array[String], v: Any) => FilterApi.lt(floatColumn(n), v.asInstanceOf[JFloat])
case ParquetDoubleType =>
(n: Array[String], v: Any) => FilterApi.lt(doubleColumn(n), v.asInstanceOf[JDouble])
case ParquetStringType =>
(n: Array[String], v: Any) =>
FilterApi.lt(binaryColumn(n), Binary.fromString(v.asInstanceOf[String]))
case ParquetBinaryType =>
(n: Array[String], v: Any) =>
FilterApi.lt(binaryColumn(n), Binary.fromReusedByteArray(v.asInstanceOf[Array[Byte]]))
case ParquetDateType if pushDownDate =>
(n: Array[String], v: Any) =>
FilterApi.lt(intColumn(n), dateToDays(v).asInstanceOf[Integer])
case ParquetTimestampMicrosType if pushDownTimestamp =>
(n: Array[String], v: Any) => FilterApi.lt(longColumn(n), timestampToMicros(v))
case ParquetTimestampMillisType if pushDownTimestamp =>
(n: Array[String], v: Any) => FilterApi.lt(longColumn(n), timestampToMillis(v))
case ParquetSchemaType(DECIMAL, INT32, _, _) if pushDownDecimal =>
(n: Array[String], v: Any) =>
FilterApi.lt(intColumn(n), decimalToInt32(v.asInstanceOf[JBigDecimal]))
case ParquetSchemaType(DECIMAL, INT64, _, _) if pushDownDecimal =>
(n: Array[String], v: Any) =>
FilterApi.lt(longColumn(n), decimalToInt64(v.asInstanceOf[JBigDecimal]))
case ParquetSchemaType(DECIMAL, FIXED_LEN_BYTE_ARRAY, length, _) if pushDownDecimal =>
(n: Array[String], v: Any) =>
FilterApi.lt(binaryColumn(n), decimalToByteArray(v.asInstanceOf[JBigDecimal], length))
}
private val makeLtEq:
PartialFunction[ParquetSchemaType, (Array[String], Any) => FilterPredicate] = {
case ParquetByteType | ParquetShortType | ParquetIntegerType =>
(n: Array[String], v: Any) =>
FilterApi.ltEq(intColumn(n), v.asInstanceOf[Number].intValue.asInstanceOf[Integer])
case ParquetLongType =>
(n: Array[String], v: Any) => FilterApi.ltEq(longColumn(n), v.asInstanceOf[JLong])
case ParquetFloatType =>
(n: Array[String], v: Any) => FilterApi.ltEq(floatColumn(n), v.asInstanceOf[JFloat])
case ParquetDoubleType =>
(n: Array[String], v: Any) => FilterApi.ltEq(doubleColumn(n), v.asInstanceOf[JDouble])
case ParquetStringType =>
(n: Array[String], v: Any) =>
FilterApi.ltEq(binaryColumn(n), Binary.fromString(v.asInstanceOf[String]))
case ParquetBinaryType =>
(n: Array[String], v: Any) =>
FilterApi.ltEq(binaryColumn(n), Binary.fromReusedByteArray(v.asInstanceOf[Array[Byte]]))
case ParquetDateType if pushDownDate =>
(n: Array[String], v: Any) =>
FilterApi.ltEq(intColumn(n), dateToDays(v).asInstanceOf[Integer])
case ParquetTimestampMicrosType if pushDownTimestamp =>
(n: Array[String], v: Any) => FilterApi.ltEq(longColumn(n), timestampToMicros(v))
case ParquetTimestampMillisType if pushDownTimestamp =>
(n: Array[String], v: Any) => FilterApi.ltEq(longColumn(n), timestampToMillis(v))
case ParquetSchemaType(DECIMAL, INT32, _, _) if pushDownDecimal =>
(n: Array[String], v: Any) =>
FilterApi.ltEq(intColumn(n), decimalToInt32(v.asInstanceOf[JBigDecimal]))
case ParquetSchemaType(DECIMAL, INT64, _, _) if pushDownDecimal =>
(n: Array[String], v: Any) =>
FilterApi.ltEq(longColumn(n), decimalToInt64(v.asInstanceOf[JBigDecimal]))
case ParquetSchemaType(DECIMAL, FIXED_LEN_BYTE_ARRAY, length, _) if pushDownDecimal =>
(n: Array[String], v: Any) =>
FilterApi.ltEq(binaryColumn(n), decimalToByteArray(v.asInstanceOf[JBigDecimal], length))
}
private val makeGt:
PartialFunction[ParquetSchemaType, (Array[String], Any) => FilterPredicate] = {
case ParquetByteType | ParquetShortType | ParquetIntegerType =>
(n: Array[String], v: Any) =>
FilterApi.gt(intColumn(n), v.asInstanceOf[Number].intValue.asInstanceOf[Integer])
case ParquetLongType =>
(n: Array[String], v: Any) => FilterApi.gt(longColumn(n), v.asInstanceOf[JLong])
case ParquetFloatType =>
(n: Array[String], v: Any) => FilterApi.gt(floatColumn(n), v.asInstanceOf[JFloat])
case ParquetDoubleType =>
(n: Array[String], v: Any) => FilterApi.gt(doubleColumn(n), v.asInstanceOf[JDouble])
case ParquetStringType =>
(n: Array[String], v: Any) =>
FilterApi.gt(binaryColumn(n), Binary.fromString(v.asInstanceOf[String]))
case ParquetBinaryType =>
(n: Array[String], v: Any) =>
FilterApi.gt(binaryColumn(n), Binary.fromReusedByteArray(v.asInstanceOf[Array[Byte]]))
case ParquetDateType if pushDownDate =>
(n: Array[String], v: Any) =>
FilterApi.gt(intColumn(n), dateToDays(v).asInstanceOf[Integer])
case ParquetTimestampMicrosType if pushDownTimestamp =>
(n: Array[String], v: Any) => FilterApi.gt(longColumn(n), timestampToMicros(v))
case ParquetTimestampMillisType if pushDownTimestamp =>
(n: Array[String], v: Any) => FilterApi.gt(longColumn(n), timestampToMillis(v))
case ParquetSchemaType(DECIMAL, INT32, _, _) if pushDownDecimal =>
(n: Array[String], v: Any) =>
FilterApi.gt(intColumn(n), decimalToInt32(v.asInstanceOf[JBigDecimal]))
case ParquetSchemaType(DECIMAL, INT64, _, _) if pushDownDecimal =>
(n: Array[String], v: Any) =>
FilterApi.gt(longColumn(n), decimalToInt64(v.asInstanceOf[JBigDecimal]))
case ParquetSchemaType(DECIMAL, FIXED_LEN_BYTE_ARRAY, length, _) if pushDownDecimal =>
(n: Array[String], v: Any) =>
FilterApi.gt(binaryColumn(n), decimalToByteArray(v.asInstanceOf[JBigDecimal], length))
}
private val makeGtEq:
PartialFunction[ParquetSchemaType, (Array[String], Any) => FilterPredicate] = {
case ParquetByteType | ParquetShortType | ParquetIntegerType =>
(n: Array[String], v: Any) =>
FilterApi.gtEq(intColumn(n), v.asInstanceOf[Number].intValue.asInstanceOf[Integer])
case ParquetLongType =>
(n: Array[String], v: Any) => FilterApi.gtEq(longColumn(n), v.asInstanceOf[JLong])
case ParquetFloatType =>
(n: Array[String], v: Any) => FilterApi.gtEq(floatColumn(n), v.asInstanceOf[JFloat])
case ParquetDoubleType =>
(n: Array[String], v: Any) => FilterApi.gtEq(doubleColumn(n), v.asInstanceOf[JDouble])
case ParquetStringType =>
(n: Array[String], v: Any) =>
FilterApi.gtEq(binaryColumn(n), Binary.fromString(v.asInstanceOf[String]))
case ParquetBinaryType =>
(n: Array[String], v: Any) =>
FilterApi.gtEq(binaryColumn(n), Binary.fromReusedByteArray(v.asInstanceOf[Array[Byte]]))
case ParquetDateType if pushDownDate =>
(n: Array[String], v: Any) =>
FilterApi.gtEq(intColumn(n), dateToDays(v).asInstanceOf[Integer])
case ParquetTimestampMicrosType if pushDownTimestamp =>
(n: Array[String], v: Any) => FilterApi.gtEq(longColumn(n), timestampToMicros(v))
case ParquetTimestampMillisType if pushDownTimestamp =>
(n: Array[String], v: Any) => FilterApi.gtEq(longColumn(n), timestampToMillis(v))
case ParquetSchemaType(DECIMAL, INT32, _, _) if pushDownDecimal =>
(n: Array[String], v: Any) =>
FilterApi.gtEq(intColumn(n), decimalToInt32(v.asInstanceOf[JBigDecimal]))
case ParquetSchemaType(DECIMAL, INT64, _, _) if pushDownDecimal =>
(n: Array[String], v: Any) =>
FilterApi.gtEq(longColumn(n), decimalToInt64(v.asInstanceOf[JBigDecimal]))
case ParquetSchemaType(DECIMAL, FIXED_LEN_BYTE_ARRAY, length, _) if pushDownDecimal =>
(n: Array[String], v: Any) =>
FilterApi.gtEq(binaryColumn(n), decimalToByteArray(v.asInstanceOf[JBigDecimal], length))
}
// Returns filters that can be pushed down when reading Parquet files.
def convertibleFilters(filters: Seq[sources.Filter]): Seq[sources.Filter] = {
filters.flatMap(convertibleFiltersHelper(_, canPartialPushDown = true))
}
private def convertibleFiltersHelper(
predicate: sources.Filter,
canPartialPushDown: Boolean): Option[sources.Filter] = {
predicate match {
case sources.And(left, right) =>
val leftResultOptional = convertibleFiltersHelper(left, canPartialPushDown)
val rightResultOptional = convertibleFiltersHelper(right, canPartialPushDown)
(leftResultOptional, rightResultOptional) match {
case (Some(leftResult), Some(rightResult)) => Some(sources.And(leftResult, rightResult))
case (Some(leftResult), None) if canPartialPushDown => Some(leftResult)
case (None, Some(rightResult)) if canPartialPushDown => Some(rightResult)
case _ => None
}
case sources.Or(left, right) =>
val leftResultOptional = convertibleFiltersHelper(left, canPartialPushDown)
val rightResultOptional = convertibleFiltersHelper(right, canPartialPushDown)
if (leftResultOptional.isEmpty || rightResultOptional.isEmpty) {
None
} else {
Some(sources.Or(leftResultOptional.get, rightResultOptional.get))
}
case sources.Not(pred) =>
val resultOptional = convertibleFiltersHelper(pred, canPartialPushDown = false)
resultOptional.map(sources.Not)
case other =>
if (createFilter(other).isDefined) {
Some(other)
} else {
None
}
}
}
/**
* Converts data sources filters to Parquet filter predicates.
*/
def createFilter(predicate: sources.Filter): Option[FilterPredicate] = {
createFilterHelper(predicate, canPartialPushDownConjuncts = true)
}
// Parquet's type in the given file should be matched to the value's type
// in the pushed filter in order to push down the filter to Parquet.
private def valueCanMakeFilterOn(name: String, value: Any): Boolean = {
value == null || (nameToParquetField(name).fieldType match {
case ParquetBooleanType => value.isInstanceOf[JBoolean]
case ParquetByteType | ParquetShortType | ParquetIntegerType => value.isInstanceOf[Number]
case ParquetLongType => value.isInstanceOf[JLong]
case ParquetFloatType => value.isInstanceOf[JFloat]
case ParquetDoubleType => value.isInstanceOf[JDouble]
case ParquetStringType => value.isInstanceOf[String]
case ParquetBinaryType => value.isInstanceOf[Array[Byte]]
case ParquetDateType =>
value.isInstanceOf[Date] || value.isInstanceOf[LocalDate]
case ParquetTimestampMicrosType | ParquetTimestampMillisType =>
value.isInstanceOf[Timestamp] || value.isInstanceOf[Instant]
case ParquetSchemaType(DECIMAL, INT32, _, decimalMeta) =>
isDecimalMatched(value, decimalMeta)
case ParquetSchemaType(DECIMAL, INT64, _, decimalMeta) =>
isDecimalMatched(value, decimalMeta)
case ParquetSchemaType(DECIMAL, FIXED_LEN_BYTE_ARRAY, _, decimalMeta) =>
isDecimalMatched(value, decimalMeta)
case _ => false
})
}
// Decimal type must make sure that filter value's scale matched the file.
// If doesn't matched, which would cause data corruption.
private def isDecimalMatched(value: Any, decimalMeta: DecimalMetadata): Boolean = value match {
case decimal: JBigDecimal =>
decimal.scale == decimalMeta.getScale
case _ => false
}
private def canMakeFilterOn(name: String, value: Any): Boolean = {
nameToParquetField.contains(name) && valueCanMakeFilterOn(name, value)
}
/**
* @param predicate the input filter predicates. Not all the predicates can be pushed down.
* @param canPartialPushDownConjuncts whether a subset of conjuncts of predicates can be pushed
* down safely. Pushing ONLY one side of AND down is safe to
* do at the top level or none of its ancestors is NOT and OR.
* @return the Parquet-native filter predicates that are eligible for pushdown.
*/
private def createFilterHelper(
predicate: sources.Filter,
canPartialPushDownConjuncts: Boolean): Option[FilterPredicate] = {
// NOTE:
//
// For any comparison operator `cmp`, both `a cmp NULL` and `NULL cmp a` evaluate to `NULL`,
// which can be casted to `false` implicitly. Please refer to the `eval` method of these
// operators and the `PruneFilters` rule for details.
// Hyukjin:
// I added [[EqualNullSafe]] with [[org.apache.parquet.filter2.predicate.Operators.Eq]].
// So, it performs equality comparison identically when given [[sources.Filter]] is [[EqualTo]].
// The reason why I did this is, that the actual Parquet filter checks null-safe equality
// comparison.
// So I added this and maybe [[EqualTo]] should be changed. It still seems fine though, because
// physical planning does not set `NULL` to [[EqualTo]] but changes it to [[IsNull]] and etc.
// Probably I missed something and obviously this should be changed.
predicate match {
case sources.IsNull(name) if canMakeFilterOn(name, null) =>
makeEq.lift(nameToParquetField(name).fieldType)
.map(_(nameToParquetField(name).fieldNames, null))
case sources.IsNotNull(name) if canMakeFilterOn(name, null) =>
makeNotEq.lift(nameToParquetField(name).fieldType)
.map(_(nameToParquetField(name).fieldNames, null))
case sources.EqualTo(name, value) if canMakeFilterOn(name, value) =>
makeEq.lift(nameToParquetField(name).fieldType)
.map(_(nameToParquetField(name).fieldNames, value))
case sources.Not(sources.EqualTo(name, value)) if canMakeFilterOn(name, value) =>
makeNotEq.lift(nameToParquetField(name).fieldType)
.map(_(nameToParquetField(name).fieldNames, value))
case sources.EqualNullSafe(name, value) if canMakeFilterOn(name, value) =>
makeEq.lift(nameToParquetField(name).fieldType)
.map(_(nameToParquetField(name).fieldNames, value))
case sources.Not(sources.EqualNullSafe(name, value)) if canMakeFilterOn(name, value) =>
makeNotEq.lift(nameToParquetField(name).fieldType)
.map(_(nameToParquetField(name).fieldNames, value))
case sources.LessThan(name, value) if canMakeFilterOn(name, value) =>
makeLt.lift(nameToParquetField(name).fieldType)
.map(_(nameToParquetField(name).fieldNames, value))
case sources.LessThanOrEqual(name, value) if canMakeFilterOn(name, value) =>
makeLtEq.lift(nameToParquetField(name).fieldType)
.map(_(nameToParquetField(name).fieldNames, value))
case sources.GreaterThan(name, value) if canMakeFilterOn(name, value) =>
makeGt.lift(nameToParquetField(name).fieldType)
.map(_(nameToParquetField(name).fieldNames, value))
case sources.GreaterThanOrEqual(name, value) if canMakeFilterOn(name, value) =>
makeGtEq.lift(nameToParquetField(name).fieldType)
.map(_(nameToParquetField(name).fieldNames, value))
case sources.And(lhs, rhs) =>
// At here, it is not safe to just convert one side and remove the other side
// if we do not understand what the parent filters are.
//
// Here is an example used to explain the reason.
// Let's say we have NOT(a = 2 AND b in ('1')) and we do not understand how to
// convert b in ('1'). If we only convert a = 2, we will end up with a filter
// NOT(a = 2), which will generate wrong results.
//
// Pushing one side of AND down is only safe to do at the top level or in the child
// AND before hitting NOT or OR conditions, and in this case, the unsupported predicate
// can be safely removed.
val lhsFilterOption =
createFilterHelper(lhs, canPartialPushDownConjuncts)
val rhsFilterOption =
createFilterHelper(rhs, canPartialPushDownConjuncts)
(lhsFilterOption, rhsFilterOption) match {
case (Some(lhsFilter), Some(rhsFilter)) => Some(FilterApi.and(lhsFilter, rhsFilter))
case (Some(lhsFilter), None) if canPartialPushDownConjuncts => Some(lhsFilter)
case (None, Some(rhsFilter)) if canPartialPushDownConjuncts => Some(rhsFilter)
case _ => None
}
case sources.Or(lhs, rhs) =>
// The Or predicate is convertible when both of its children can be pushed down.
// That is to say, if one/both of the children can be partially pushed down, the Or
// predicate can be partially pushed down as well.
//
// Here is an example used to explain the reason.
// Let's say we have
// (a1 AND a2) OR (b1 AND b2),
// a1 and b1 is convertible, while a2 and b2 is not.
// The predicate can be converted as
// (a1 OR b1) AND (a1 OR b2) AND (a2 OR b1) AND (a2 OR b2)
// As per the logical in And predicate, we can push down (a1 OR b1).
for {
lhsFilter <- createFilterHelper(lhs, canPartialPushDownConjuncts)
rhsFilter <- createFilterHelper(rhs, canPartialPushDownConjuncts)
} yield FilterApi.or(lhsFilter, rhsFilter)
case sources.Not(pred) =>
createFilterHelper(pred, canPartialPushDownConjuncts = false)
.map(FilterApi.not)
case sources.In(name, values) if canMakeFilterOn(name, values.head)
&& values.distinct.length <= pushDownInFilterThreshold =>
values.distinct.flatMap { v =>
makeEq.lift(nameToParquetField(name).fieldType)
.map(_(nameToParquetField(name).fieldNames, v))
}.reduceLeftOption(FilterApi.or)
case sources.StringStartsWith(name, prefix)
if pushDownStartWith && canMakeFilterOn(name, prefix) =>
Option(prefix).map { v =>
FilterApi.userDefined(binaryColumn(nameToParquetField(name).fieldNames),
new UserDefinedPredicate[Binary] with Serializable {
private val strToBinary = Binary.fromReusedByteArray(v.getBytes)
private val size = strToBinary.length
override def canDrop(statistics: Statistics[Binary]): Boolean = {
val comparator = PrimitiveComparator.UNSIGNED_LEXICOGRAPHICAL_BINARY_COMPARATOR
val max = statistics.getMax
val min = statistics.getMin
comparator.compare(max.slice(0, math.min(size, max.length)), strToBinary) < 0 ||
comparator.compare(min.slice(0, math.min(size, min.length)), strToBinary) > 0
}
override def inverseCanDrop(statistics: Statistics[Binary]): Boolean = {
val comparator = PrimitiveComparator.UNSIGNED_LEXICOGRAPHICAL_BINARY_COMPARATOR
val max = statistics.getMax
val min = statistics.getMin
comparator.compare(max.slice(0, math.min(size, max.length)), strToBinary) == 0 &&
comparator.compare(min.slice(0, math.min(size, min.length)), strToBinary) == 0
}
override def keep(value: Binary): Boolean = {
value != null && UTF8String.fromBytes(value.getBytes).startsWith(
UTF8String.fromBytes(strToBinary.getBytes))
}
}
)
}
case _ => None
}
}
}
| witgo/spark | sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/parquet/ParquetFilters.scala | Scala | apache-2.0 | 31,860 |
/*
* Open Korean Text - Scala library to process Korean text
*
* Copyright 2015 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 org.openkoreantext.processor.tokenizer
import org.openkoreantext.processor.TestBase
import org.openkoreantext.processor.tokenizer.KoreanDetokenizer._
class KoreanDetokenizerTest extends TestBase {
test("detokenizer should correctly detokenize the input text") {
assert(
detokenize(List("연세", "대학교", "보건", "대학원","에","오신","것","을","환영","합니다", "!"))
=== "연세대학교 보건 대학원에 오신것을 환영합니다!"
)
assert(
detokenize(List("와", "!!!", "iPhone", "6+", "가",",", "드디어","나왔다", "!"))
=== "와!!! iPhone 6+ 가, 드디어 나왔다!"
)
assert(
detokenize(List("뭐", "완벽", "하진", "않", "지만", "그럭저럭", "쓸", "만", "하군", "..."))
=== "뭐 완벽하진 않지만 그럭저럭 쓸 만하군..."
)
}
test("detokenizer should correctly detokenize the edge cases") {
assert(
detokenize(List(""))
=== ""
)
assert(
detokenize(List())
=== ""
)
assert(
detokenize(List("완벽"))
=== "완벽"
)
assert(
detokenize(List("이"))
=== "이"
)
assert(
detokenize(List("이", "제품을", "사용하겠습니다"))
=== "이 제품을 사용하겠습니다"
)
}
} | open-korean-text/open-korean-text | src/test/scala/org/openkoreantext/processor/tokenizer/KoreanDetokenizerTest.scala | Scala | apache-2.0 | 2,015 |
package dotty.tools.dotc.quoted
import dotty.tools.dotc.ast.Trees._
import dotty.tools.dotc.ast.{TreeTypeMap, tpd}
import dotty.tools.dotc.config.Printers._
import dotty.tools.dotc.core.Contexts._
import dotty.tools.dotc.core.Decorators._
import dotty.tools.dotc.core.Mode
import dotty.tools.dotc.core.Symbols._
import dotty.tools.dotc.core.Types._
import dotty.tools.dotc.core.tasty.{ PositionPickler, TastyPickler, TastyPrinter }
import dotty.tools.dotc.core.tasty.DottyUnpickler
import dotty.tools.dotc.core.tasty.TreeUnpickler.UnpickleMode
import dotty.tools.dotc.report
import scala.quoted.Quotes
import scala.quoted.runtime.impl._
import scala.collection.mutable
import QuoteUtils._
object PickledQuotes {
import tpd._
/** Pickle the tree of the quote into strings */
def pickleQuote(tree: Tree)(using Context): List[String] =
if (ctx.reporter.hasErrors) Nil
else {
assert(!tree.isInstanceOf[Hole]) // Should not be pickled as it represents `'{$x}` which should be optimized to `x`
val pickled = pickle(tree)
TastyString.pickle(pickled)
}
/** Transform the expression into its fully spliced Tree */
def quotedExprToTree[T](expr: quoted.Expr[T])(using Context): Tree = {
val expr1 = expr.asInstanceOf[ExprImpl]
ScopeException.checkInCorrectScope(expr1.scope, SpliceScope.getCurrent, expr1.tree, "Expr")
changeOwnerOfTree(expr1.tree, ctx.owner)
}
/** Transform the expression into its fully spliced TypeTree */
def quotedTypeToTree(tpe: quoted.Type[?])(using Context): Tree = {
val tpe1 = tpe.asInstanceOf[TypeImpl]
ScopeException.checkInCorrectScope(tpe1.scope, SpliceScope.getCurrent, tpe1.typeTree, "Type")
changeOwnerOfTree(tpe1.typeTree, ctx.owner)
}
/** Unpickle the tree contained in the TastyExpr */
def unpickleTerm(pickled: String | List[String], typeHole: (Int, Seq[Any]) => scala.quoted.Type[?], termHole: (Int, Seq[Any], scala.quoted.Quotes) => scala.quoted.Expr[?])(using Context): Tree = {
val unpickled = withMode(Mode.ReadPositions)(unpickle(pickled, isType = false))
val Inlined(call, Nil, expnasion) = unpickled
val inlineCtx = inlineContext(call)
val expansion1 = spliceTypes(expnasion, typeHole, termHole)(using inlineCtx)
val expansion2 = spliceTerms(expansion1, typeHole, termHole)(using inlineCtx)
cpy.Inlined(unpickled)(call, Nil, expansion2)
}
/** Unpickle the tree contained in the TastyType */
def unpickleTypeTree(pickled: String | List[String], typeHole: (Int, Seq[Any]) => scala.quoted.Type[?], termHole: (Int, Seq[Any], scala.quoted.Quotes) => scala.quoted.Expr[?])(using Context): Tree = {
val unpickled = withMode(Mode.ReadPositions)(unpickle(pickled, isType = true))
spliceTypes(unpickled, typeHole, termHole)
}
/** Replace all term holes with the spliced terms */
private def spliceTerms(tree: Tree, typeHole: (Int, Seq[Any]) => scala.quoted.Type[?], termHole: (Int, Seq[Any], scala.quoted.Quotes) => scala.quoted.Expr[?])(using Context): Tree = {
val evaluateHoles = new TreeMap {
override def transform(tree: tpd.Tree)(using Context): tpd.Tree = tree match {
case Hole(isTerm, idx, args) =>
inContext(SpliceScope.contextWithNewSpliceScope(tree.sourcePos)) {
val reifiedArgs = args.map { arg =>
if (arg.isTerm) (q: Quotes) ?=> new ExprImpl(arg, SpliceScope.getCurrent)
else new TypeImpl(arg, SpliceScope.getCurrent)
}
if isTerm then
val quotedExpr = termHole(idx, reifiedArgs, QuotesImpl())
val filled = PickledQuotes.quotedExprToTree(quotedExpr)
// We need to make sure a hole is created with the source file of the surrounding context, even if
// it filled with contents a different source file.
if filled.source == ctx.source then filled
else filled.cloneIn(ctx.source).withSpan(tree.span)
else
// Replaces type holes generated by PickleQuotes (non-spliced types).
// These are types defined in a quote and used at the same level in a nested quote.
val quotedType = typeHole(idx, reifiedArgs)
PickledQuotes.quotedTypeToTree(quotedType)
}
case tree =>
if tree.isDef then
tree.symbol.annotations = tree.symbol.annotations.map {
annot => annot.derivedAnnotation(transform(annot.tree))
}
end if
val tree1 = super.transform(tree)
tree1.withType(mapAnnots(tree1.tpe))
}
// Evaluate holes in type annotations
private val mapAnnots = new TypeMap {
override def apply(tp: Type): Type = {
tp match
case tp @ AnnotatedType(underlying, annot) =>
val underlying1 = this(underlying)
derivedAnnotatedType(tp, underlying1, annot.derivedAnnotation(transform(annot.tree)))
case _ => mapOver(tp)
}
}
}
val tree1 = evaluateHoles.transform(tree)
quotePickling.println(i"**** evaluated quote\\n$tree1")
tree1
}
/** Replace all type holes generated with the spliced types */
private def spliceTypes(tree: Tree, typeHole: (Int, Seq[Any]) => scala.quoted.Type[?], termHole: (Int, Seq[Int], scala.quoted.Quotes) => Any)(using Context): Tree = {
tree match
case Block(stat :: rest, expr1) if stat.symbol.hasAnnotation(defn.QuotedRuntime_SplicedTypeAnnot) =>
val typeSpliceMap = (stat :: rest).iterator.map {
case tdef: TypeDef =>
assert(tdef.symbol.hasAnnotation(defn.QuotedRuntime_SplicedTypeAnnot))
val tree = tdef.rhs match
case TypeBoundsTree(_, Hole(_, idx, args), _) =>
val quotedType = typeHole(idx, args)
PickledQuotes.quotedTypeToTree(quotedType)
case TypeBoundsTree(_, tpt, _) =>
tpt
(tdef.symbol, tree.tpe)
}.toMap
class ReplaceSplicedTyped extends TypeMap() {
override def apply(tp: Type): Type = tp match {
case tp: ClassInfo =>
tp.derivedClassInfo(declaredParents = tp.declaredParents.map(apply))
case tp: TypeRef =>
typeSpliceMap.get(tp.symbol) match
case Some(t) if tp.typeSymbol.hasAnnotation(defn.QuotedRuntime_SplicedTypeAnnot) => mapOver(t)
case _ => mapOver(tp)
case _ =>
mapOver(tp)
}
}
val expansion2 = new TreeTypeMap(new ReplaceSplicedTyped).transform(expr1)
quotePickling.println(i"**** typed quote\\n${expansion2.show}")
expansion2
case _ =>
tree
}
// TASTY picklingtests/pos/quoteTest.scala
/** Pickle tree into it's TASTY bytes s*/
private def pickle(tree: Tree)(using Context): Array[Byte] = {
quotePickling.println(i"**** pickling quote of\\n$tree")
val pickler = new TastyPickler(defn.RootClass)
val treePkl = pickler.treePkl
treePkl.pickle(tree :: Nil)
treePkl.compactify()
if tree.span.exists then
val positionWarnings = new mutable.ListBuffer[String]()
val reference = ctx.settings.sourceroot.value
new PositionPickler(pickler, treePkl.buf.addrOfTree, treePkl.treeAnnots, reference)
.picklePositions(ctx.compilationUnit.source, tree :: Nil, positionWarnings)
positionWarnings.foreach(report.warning(_))
val pickled = pickler.assembleParts()
quotePickling.println(s"**** pickled quote\\n${TastyPrinter.showContents(pickled, ctx.settings.color.value == "never")}")
pickled
}
/** Unpickle TASTY bytes into it's tree */
private def unpickle(pickled: String | List[String], isType: Boolean)(using Context): Tree = {
QuotesCache.getTree(pickled) match
case Some(tree) =>
quotePickling.println(s"**** Using cached quote for TASTY\\n$tree")
treeOwner(tree) match
case Some(owner) =>
// Copy the cached tree to make sure the all definitions are unique.
TreeTypeMap(oldOwners = List(owner), newOwners = List(owner)).apply(tree)
case _ =>
tree
case _ =>
val bytes = pickled match
case pickled: String => TastyString.unpickle(pickled)
case pickled: List[String] => TastyString.unpickle(pickled)
quotePickling.println(s"**** unpickling quote from TASTY\\n${TastyPrinter.showContents(bytes, ctx.settings.color.value == "never")}")
val mode = if (isType) UnpickleMode.TypeTree else UnpickleMode.Term
val unpickler = new DottyUnpickler(bytes, ctx.tastyVersion, mode)
unpickler.enter(Set.empty)
val tree = unpickler.tree
QuotesCache(pickled) = tree
// Make sure trees and positions are fully loaded
new TreeTraverser {
def traverse(tree: Tree)(using Context): Unit = traverseChildren(tree)
}.traverse(tree)
quotePickling.println(i"**** unpickled quote\\n$tree")
tree
}
}
| dotty-staging/dotty | compiler/src/dotty/tools/dotc/quoted/PickledQuotes.scala | Scala | apache-2.0 | 9,049 |
package org.http4s
package server
package middleware
import cats.effect._
import cats.implicits._
import fs2._
import fs2.Stream._
import java.nio.charset.StandardCharsets
import org.http4s.server.middleware.EntityLimiter.EntityTooLarge
import org.http4s.Method._
import org.http4s.Status._
import org.http4s.Uri.uri
class EntityLimiterSpec extends Http4sSpec {
val routes = HttpRoutes.of[IO] {
case r if r.uri.path == "/echo" => r.decode[String](Response[IO](Ok).withEntity(_).pure[IO])
}
val b = chunk(Chunk.bytes("hello".getBytes(StandardCharsets.UTF_8)))
"EntityLimiter" should {
"Allow reasonable entities" in {
EntityLimiter(routes, 100)
.apply(Request[IO](POST, uri("/echo"), body = b))
.map(_ => -1)
.value must returnValue(Some(-1))
}
"Limit the maximum size of an EntityBody" in {
EntityLimiter(routes, 3)
.apply(Request[IO](POST, uri("/echo"), body = b))
.map(_ => -1L)
.value
.handleError { case EntityTooLarge(i) => Some(i) } must returnValue(Some(3))
}
"Chain correctly with other HttpRoutes" in {
val routes2 = HttpRoutes.of[IO] {
case r if r.uri.path == "/echo2" =>
r.decode[String](Response[IO](Ok).withEntity(_).pure[IO])
}
val st = EntityLimiter(routes, 3) <+> routes2
st.apply(Request[IO](POST, uri("/echo2"), body = b))
.map(_ => -1)
.value must returnValue(Some(-1))
st.apply(Request[IO](POST, uri("/echo"), body = b))
.map(_ => -1L)
.value
.handleError { case EntityTooLarge(i) => Some(i) } must returnValue(Some(3L))
}
}
}
| aeons/http4s | server/src/test/scala/org/http4s/server/middleware/EntityLimiterSpec.scala | Scala | apache-2.0 | 1,653 |
/*
* Copyright (C) 2014 - 2016 Softwaremill <http://softwaremill.com>
* Copyright (C) 2016 - 2019 Lightbend Inc. <http://www.lightbend.com>
*/
package akka.kafka.benchmarks
import java.lang.management.{BufferPoolMXBean, ManagementFactory, MemoryType}
import akka.NotUsed
import akka.actor.Cancellable
import akka.kafka.scaladsl.Consumer.Control
import akka.stream.Materializer
import akka.stream.scaladsl.{Keep, Sink, Source}
import com.codahale.metrics.{Histogram, MetricRegistry}
import javax.management.remote.{JMXConnectorFactory, JMXServiceURL}
import javax.management.{Attribute, MBeanServerConnection, ObjectName}
import scala.concurrent.duration.{FiniteDuration, _}
import scala.concurrent.{ExecutionContext, Future}
import scala.jdk.CollectionConverters._
private[benchmarks] trait InflightMetrics {
import InflightMetrics._
private val registry = new MetricRegistry()
private val gcBeans = ManagementFactory.getGarbageCollectorMXBeans.asScala
private val memoryPoolBeans = ManagementFactory.getMemoryPoolMXBeans.asScala
private val directBufferPoolBeans = ManagementFactory.getPlatformMXBeans(classOf[BufferPoolMXBean]).asScala
private val compatibleGcNames = List("ConcurrentMarkSweep", "PS MarkSweep")
private val timeMsHeader = "time-ms"
private val (gcCountHeader, gcTimeMsHeader, heapBytesHeader, nonHeapBytesHeader, directBytesHeader) =
("gc-count", "gc-time-ms", "heap-bytes:mean", "non-heap-bytes:mean", "direct-bytes:mean")
private val jvmHeaders =
List(gcCountHeader, gcTimeMsHeader, heapBytesHeader, nonHeapBytesHeader, directBytesHeader).map("jvm:" + _)
private val consumerHeaderPrefix = "kafka-consumer:"
private val brokerHeaderPrefix = "broker:"
/**
* Every poll interval collect JVM and specified Kafka Consumer & Broker metrics.
*/
def pollForMetrics(
interval: FiniteDuration,
control: Control,
consumerMetricNames: List[ConsumerMetricRequest],
brokerMetricNames: List[BrokerMetricRequest],
brokerJmxUrls: List[String]
)(implicit mat: Materializer): (Cancellable, Future[List[List[String]]]) = {
implicit val ec: ExecutionContext = mat.executionContext
val consumerMetricNamesSorted = consumerMetricNames.sortBy(_.name)
val brokerMetricNamesSorted = brokerMetricNames.sortBy(_.name)
val accStart = (0.seconds, None.asInstanceOf[Option[List[Metric]]])
val brokersJmx = jmxConnections(brokerJmxUrls)
val (metricsControl, metricsFuture) = Source
.tick(0.seconds, interval, NotUsed)
.scanAsync(accStart)({
case ((timeMs, accLastMetrics), _) =>
getAllMetrics(control, consumerMetricNamesSorted, brokerMetricNamesSorted, brokersJmx) map {
case jvmMetrics :: consumerMetrics :: brokerMetrics :: Nil =>
val timeMsMeasurement = Measurement(timeMsHeader, timeMs.toMillis.toDouble, GaugeMetricType)
val newMetrics = timeMsMeasurement +: (jvmMetrics ++ consumerMetrics ++ brokerMetrics)
val nextInterval = interval + timeMs
val nextAcc = accLastMetrics match {
case None => InflightMetrics.reset(newMetrics, registry)
case Some(lastMetrics) => InflightMetrics.update(lastMetrics, newMetrics)
}
(nextInterval, Some(nextAcc))
case _ => throw new IllegalStateException("The wrong number of Future results were returned.")
}
})
.mapConcat { case (_, results: Option[List[Metric]]) => results.toList }
.toMat(Sink.seq)(Keep.both)
.run()
val metricsWithHeaderAndFooter: Future[List[List[String]]] = metricsFuture.map { metrics =>
val header = timeMsHeader +: metricHeaders(consumerMetricNamesSorted, brokerMetricNamesSorted)
val metricsStrings = metrics.map(_.map(_.value.toString)).toList
val summaryLine = metrics.last.map {
case hg: HistogramGauge => hg.summaryValue.toString
case metric => metric.value.toString
}
header +: metricsStrings :+ summaryLine
}
(metricsControl, metricsWithHeaderAndFooter)
}
private def metricHeaders(consumerMetricNamesSorted: List[ConsumerMetricRequest],
brokerMetricNamesSorted: List[BrokerMetricRequest]): List[String] = {
jvmHeaders ++
consumerMetricNamesSorted.map(consumerHeaderPrefix + _.name) ++
brokerMetricNamesSorted.map(brokerHeaderPrefix + _.name.replace(",", ":"))
}
/**
* Asynchronously retrieve all metrics
*/
private def getAllMetrics(control: Control,
consumerMetricNamesSorted: List[ConsumerMetricRequest],
brokerMetricNamesSorted: List[BrokerMetricRequest],
brokersJmx: List[MBeanServerConnection])(implicit ec: ExecutionContext) = {
Future.sequence(
List(
jvm(),
consumer(control, consumerMetricNamesSorted),
broker(brokersJmx, brokerMetricNamesSorted)
)
)
}
/**
* Get all JVM metrics
*/
private def jvm()(implicit ec: ExecutionContext) = Future {
val (gcCount, gcTimeMs) = gc()
val (heapBytes, nonHeapBytes, directBytes) = memoryUsage()
val getMeanSummary: Option[com.codahale.metrics.Sampling => Long] = Some(_.getSnapshot.getMean.toLong)
List(
Measurement(gcCountHeader, gcCount, CounterMetricType),
Measurement(gcTimeMsHeader, gcTimeMs, CounterMetricType),
Measurement(heapBytesHeader, heapBytes, GaugeMetricType, getMeanSummary),
Measurement(nonHeapBytesHeader, nonHeapBytes, GaugeMetricType, getMeanSummary),
Measurement(directBytesHeader, directBytes, GaugeMetricType, getMeanSummary)
)
}
/**
* Use first GC pool that matches compatible GC names and return total GC count and last collection time length in ms.
*/
private def gc() = {
gcBeans
.find(bean => compatibleGcNames.contains(bean.getName))
.map(bean => (bean.getCollectionCount.toDouble, bean.getCollectionTime.toDouble))
.getOrElse(
throw new Exception(
s"Compatible GC not found. Need one of: ${compatibleGcNames.mkString(",")}. Found ${gcBeans.map(_.getName()).mkString(",")}."
)
)
}
/**
* Return JVM memory usage for on heap, JVM-managed off heap (code cache, metaspace, compressed class space), and
* direct memory usages by end-users and NIO threadlocal BufferCache.
*/
private def memoryUsage() = {
val heapBytes = memoryPoolBeans.filter(_.getType == MemoryType.HEAP).map(_.getUsage.getUsed).sum.toDouble
val nonHeapBytes = memoryPoolBeans.filter(_.getType == MemoryType.NON_HEAP).map(_.getUsage.getUsed).sum.toDouble
val directBytes = directBufferPoolBeans.map(_.getMemoryUsed).sum.toDouble
(heapBytes, nonHeapBytes, directBytes)
}
/**
* Return specified consumer-level metrics using Alpakka Kafka's [[Control]] metrics API.
*/
private def consumer[T](control: Control, requests: List[ConsumerMetricRequest])(
implicit ec: ExecutionContext
): Future[List[Measurement]] = {
control.metrics.map { consumerMetrics =>
val metricValues = consumerMetrics
.filter { case (name, _) => requests.map(_.name).contains(name.name()) }
.filterNot { case (name, _) => name.tags.containsKey("topic") || name.tags.containsKey("partition") }
.toList
.sortBy { case (name, _) => name.name() }
.map { case (_, value) => value.metricValue().asInstanceOf[Any] }
.map(parseNumeric)
require(metricValues.size == requests.size,
"Number of returned metric values DNE number of requested consumer metrics")
val results: List[Measurement] = requests
.zip(metricValues)
.map {
case (ConsumerMetricRequest(name, metricType), value) => Measurement(name, value, metricType)
}
results
}
}
/**
* Return specified broker metrics using a remote JMX connection.
*/
private def broker(
brokersJmx: Seq[MBeanServerConnection],
brokerMetricNames: List[BrokerMetricRequest]
)(implicit ec: ExecutionContext): Future[List[Measurement]] = Future {
brokerMetricNames
.sortBy(_.name)
.map {
case bmr @ BrokerMetricRequest(name, _, attrName, _) =>
val sum = brokersJmx
.map(conn => getRemoteJmxValue(bmr.topicMetricName, attrName, conn))
.sum
Measurement(name, parseNumeric(sum), CounterMetricType)
}
}
private def jmxConnections(brokerJmxUrls: List[String]): List[MBeanServerConnection] = {
brokerJmxUrls.map { url =>
val jmxUrl = new JMXServiceURL(url)
val conn = JMXConnectorFactory.connect(jmxUrl)
conn.getMBeanServerConnection
}
}
private def getRemoteJmxValue(objectName: String, attrName: String, conn: MBeanServerConnection): Double = {
val bytesInPerSec: ObjectName = new ObjectName(objectName)
val attributes = Array(attrName)
// to list all available objects and attributes you can: `conn.queryNames(null, null)`
val attributeValues = conn.getAttributes(bytesInPerSec, attributes)
val attr = attributeValues.stream.findFirst.get.asInstanceOf[Attribute]
parseNumeric(attr.getValue)
}
}
private[benchmarks] object InflightMetrics {
sealed trait MetricType
case object GaugeMetricType extends MetricType
case object CounterMetricType extends MetricType
final case class ConsumerMetricRequest(name: String, metricType: MetricType)
final case class BrokerMetricRequest(name: String, topic: String, attribute: String, metricType: MetricType) {
val topicMetricName: String = s"$name,topic=$topic"
}
/**
* Optional summary value HoF lets you choose how to calculate the summary value of the gauge. Choosing [[None]]
* will return the last gauge value. Providing a HoF allows you to extract a statistical calculation from a
* dropwizard [[Sampling]].
*/
final case class Measurement(name: String,
value: Double,
metricType: MetricType,
summaryValueF: Option[com.codahale.metrics.Sampling => Long] = None)
sealed trait Metric {
def measurement: Measurement
def value: Double = measurement.value
def update(measurement: Measurement): Metric
override def toString: String = measurement.value.toString
}
private final case class HistogramGauge(measurement: Measurement, histogram: Histogram) extends Metric {
histogram.update(measurement.value.toLong)
def summaryValue: Double = measurement.summaryValueF.map(f => f(histogram).toDouble).getOrElse(value)
def update(measurement: Measurement): HistogramGauge = HistogramGauge(measurement, histogram)
}
private final case class BaseCounter(base: Measurement, measurement: Measurement) extends Metric {
override val value: Double = measurement.value - base.value
def update(measurement: Measurement): Metric = BaseCounter(base, measurement)
}
def reset(measurements: List[Measurement], registry: MetricRegistry): List[Metric] = measurements.map {
case measurement @ Measurement(_, _, CounterMetricType, _) => BaseCounter(measurement, measurement)
case measurement @ Measurement(_, _, GaugeMetricType, _) =>
HistogramGauge(measurement, registry.histogram(measurement.name))
}
def update(lastMetrics: List[Metric], measurements: List[Measurement]): List[Metric] =
measurements.zip(lastMetrics).map {
case (measurement, lastMetric) => lastMetric.update(measurement)
}
def parseNumeric(n: Any): Double = n match {
case n: Double => n
case n: Long => n.toDouble
case o => java.lang.Double.parseDouble(o.toString)
}
}
| softwaremill/reactive-kafka | benchmarks/src/main/scala/akka/kafka/benchmarks/InflightMetrics.scala | Scala | apache-2.0 | 11,722 |
package genericFunctionRDD.impl
import com.newbrightidea.util.RTree
import org.apache.spark.Partitioner
import org.apache.spark.rdd.RDD
import scala.reflect.ClassTag
/**
* Created by merlin on 2/9/16.
*/
class RTreePartitioner [K: ClassTag,V:ClassTag](partitions:Int, fraction:Float,
rdd: RDD[_ <: Product2[K, V]]) extends Partitioner{
// We allow partitions = 0, which happens when sorting an empty RDD under the default settings.
require(partitions >= 0, s"Number of partitions cannot be negative but found $partitions.")
val rtreeForPartition={
//sample data from big data set
val sampledata=rdd.map(_._1).sample(false,fraction).collect()
val numDimensions: Int = Util.input_data_dimensions
val minNum: Int = Util.rtree_minimum_number
val maxNum: Int = sampledata.length/partitions
val rt: RTree[Int] = new RTree[Int](minNum, maxNum, numDimensions, RTree.SeedPicker.QUADRATIC)
sampledata.foreach
{
case coords: Array[Float] =>
rt.insert(coords,1)
}
rt
}
def numPartitions: Int = {
partitions
}
/**
* get the related partition for each input data point
* @param key
* @return
*/
def getPartition(key: Any): Int ={
key match
{
case k:Array[Float]=>
(this.rtreeForPartition.getPartitionID(k))%this.numPartitions
case _=>
1
//Array(k)
}
}
override def hashCode: Int = rtreeForPartition.size()
}
| merlintang/genericFunctionOverSpark | src/main/scala/genericFunctionRDD/impl/SpatialPartitioner.scala | Scala | apache-2.0 | 1,494 |
package com.datawizards.sparklocal.dataset
import com.datawizards.sparklocal.SparkLocalBaseTest
import com.datawizards.sparklocal.implicits._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
@RunWith(classOf[JUnitRunner])
class RepartitionTest extends SparkLocalBaseTest {
test("repartition result") {
val ds = DataSetAPI(Seq(1,2,3))
assert(ds.repartition(2) == ds)
}
test("repartition equal") {
assertDatasetOperationReturnsSameResultWithSorted(Seq(1,2,3)) {
ds => ds.repartition(2)
}
}
} | piotr-kalanski/spark-local | src/test/scala/com/datawizards/sparklocal/dataset/RepartitionTest.scala | Scala | apache-2.0 | 550 |
/*
* 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.scalactic
import org.scalatest._
import scala.collection.GenSeq
import scala.collection.GenMap
import scala.collection.GenSet
import scala.collection.GenIterable
import scala.collection.GenTraversable
import scala.collection.GenTraversableOnce
import scala.collection.{mutable,immutable}
class ConversionCheckedSetEqualityConstraintsSpec extends FunSpec with NonImplicitAssertions with ConversionCheckedTripleEquals with SetEqualityConstraints {
case class Super(size: Int)
class Sub(sz: Int) extends Super(sz)
val super1: Super = new Super(1)
val sub1: Sub = new Sub(1)
val super2: Super = new Super(2)
val sub2: Sub = new Sub(2)
val nullSuper: Super = null
case class Fruit(name: String)
class Apple extends Fruit("apple")
class Orange extends Fruit("orange")
describe("the SetEqualityConstraints trait") {
it("should allow any Set to be compared with any other Set, so long as the element types of the two Sets adhere to the equality constraint in force for those types") {
assert(mutable.HashSet(1, 2, 3) === immutable.HashSet(1, 2, 3))
assert(mutable.HashSet(1, 2, 3) === immutable.HashSet(1L, 2L, 3L))
assert(mutable.HashSet(1L, 2L, 3L) === immutable.HashSet(1, 2, 3))
assert(immutable.HashSet(1, 2, 3) === mutable.HashSet(1L, 2L, 3L))
assert(immutable.HashSet(1L, 2L, 3L) === mutable.HashSet(1, 2, 3))
assert(mutable.HashSet(new Apple, new Apple) === immutable.HashSet(new Fruit("apple"), new Fruit("apple")))
assert(immutable.HashSet(new Fruit("apple"), new Fruit("apple")) === mutable.HashSet(new Apple, new Apple))
assertTypeError("mutable.HashSet(new Apple, new Apple) === immutable.HashSet(new Orange, new Orange)")
assertTypeError("immutable.HashSet(new Apple, new Apple) === mutable.HashSet(new Orange, new Orange)")
assertTypeError("immutable.HashSet(new Orange, new Orange) === mutable.HashSet(new Apple, new Apple)")
assertTypeError("mutable.HashSet(new Orange, new Orange) === immutable.HashSet(new Apple, new Apple)")
}
}
}
| SRGOM/scalatest | scalactic-test/src/test/scala/org/scalactic/ConversionCheckedSetEqualityConstraintsSpec.scala | Scala | apache-2.0 | 2,662 |
/*
* @author Philip Stutz
*
* Copyright 2015 iHealth Technologies
*
* 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.signalcollect.triplerush.sparql
import org.scalatest.{ Finders, FlatSpec, Matchers }
import com.signalcollect.triplerush.TripleRush
import com.signalcollect.util.TestAnnouncements
class FilterSpec extends FlatSpec with Matchers with TestAnnouncements {
"ARQ FILTER" should "return the correct result even when all variables are bound during an existence check" in {
val sparql = """
SELECT ?r {
?r <http://p> <http://r2>
FILTER EXISTS { ?r <http://p> <http://r3> }
}
"""
val tr = TripleRush()
val graph = TripleRushGraph(tr)
implicit val model = graph.getModel
try {
tr.addStringTriple("http://r1", "http://p", "r2")
tr.prepareExecution
val results = Sparql(sparql)
assert(!results.hasNext)
} finally {
tr.shutdown
}
}
}
| hicolour/triplerush | src/test/scala/com/signalcollect/triplerush/sparql/FilterSpec.scala | Scala | apache-2.0 | 1,453 |
// Copyright (c) 2013-2020 Rob Norris and Contributors
// This software is licensed under the MIT License (MIT).
// For more information see LICENSE or https://opensource.org/licenses/MIT
// relies on streaming, so no cats for now
package example
import cats.Show
import cats.syntax.all._
import cats.effect.{ IO, IOApp }
import fs2.Stream
import doobie._, doobie.implicits._
// Example lifted from slick
object FirstExample extends IOApp.Simple {
// Our data model
final case class Supplier(id: Int, name: String, street: String, city: String, state: String, zip: String)
final case class Coffee(name: String, supId: Int, price: Double, sales: Int, total: Int)
object Coffee {
implicit val show: Show[Coffee] = Show.fromToString
}
// Some suppliers
val suppliers = List(
Supplier(101, "Acme, Inc.", "99 Market Street", "Groundsville", "CA", "95199"),
Supplier( 49, "Superior Coffee", "1 Party Place", "Mendocino", "CA", "95460"),
Supplier(150, "The High Ground", "100 Coffee Lane", "Meadows", "CA", "93966")
)
// Some coffees
val coffees = List(
Coffee("Colombian", 101, 7.99, 0, 0),
Coffee("French_Roast", 49, 8.99, 0, 0),
Coffee("Espresso", 150, 9.99, 0, 0),
Coffee("Colombian_Decaf", 101, 8.99, 0, 0),
Coffee("French_Roast_Decaf", 49, 9.99, 0, 0)
)
// Our example database action
def examples: ConnectionIO[String] =
for {
// Create and populate
_ <- DAO.create
ns <- DAO.insertSuppliers(suppliers)
nc <- DAO.insertCoffees(coffees)
_ <- putStrLn(show"Inserted $ns suppliers and $nc coffees.")
// Select and stream the coffees to stdout
_ <- DAO.allCoffees.evalMap(c => putStrLn(show"$c")).compile.drain
// Get the names and supplier names for all coffees costing less than $9.00,
// again streamed directly to stdout
_ <- DAO.coffeesLessThan(9.0).evalMap(p => putStrLn(show"$p")).compile.drain
// Same thing, but read into a list this time
l <- DAO.coffeesLessThan(9.0).compile.toList
_ <- putStrLn(l.toString)
// Read into a vector this time, with some stream processing
v <- DAO.coffeesLessThan(9.0).take(2).map(p => p._1 + "*" + p._2).compile.toVector
_ <- putStrLn(v.toString)
} yield "All done!"
// Entry point.
def run: IO[Unit] = {
val db = Transactor.fromDriverManager[IO](
"org.h2.Driver", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "sa", ""
)
for {
a <- examples.transact(db).attempt
_ <- IO(println(a))
} yield ()
}
/** DAO module provides ConnectionIO constructors for end users. */
object DAO {
def coffeesLessThan(price: Double): Stream[ConnectionIO, (String, String)] =
Queries.coffeesLessThan(price).stream
def insertSuppliers(ss: List[Supplier]): ConnectionIO[Int] =
Queries.insertSupplier.updateMany(ss) // bulk insert (!)
def insertCoffees(cs: List[Coffee]): ConnectionIO[Int] =
Queries.insertCoffee.updateMany(cs)
def allCoffees: Stream[ConnectionIO, Coffee] =
Queries.allCoffees.stream
def create: ConnectionIO[Unit] =
Queries.create.run.void
}
/** Queries module contains "raw" Query/Update values. */
object Queries {
def coffeesLessThan(price: Double): Query0[(String, String)] =
sql"""
SELECT cof_name, sup_name
FROM coffees JOIN suppliers ON coffees.sup_id = suppliers.sup_id
WHERE price < $price
""".query[(String, String)]
val insertSupplier: Update[Supplier] =
Update[Supplier]("INSERT INTO suppliers VALUES (?, ?, ?, ?, ?, ?)", None)
val insertCoffee: Update[Coffee] =
Update[Coffee]("INSERT INTO coffees VALUES (?, ?, ?, ?, ?)", None)
def allCoffees[A]: Query0[Coffee] =
sql"SELECT cof_name, sup_id, price, sales, total FROM coffees".query[Coffee]
def create: Update0 =
sql"""
CREATE TABLE suppliers (
sup_id INT NOT NULL PRIMARY KEY,
sup_name VARCHAR NOT NULL,
street VARCHAR NOT NULL,
city VARCHAR NOT NULL,
state VARCHAR NOT NULL,
zip VARCHAR NOT NULL
);
CREATE TABLE coffees (
cof_name VARCHAR NOT NULL,
sup_id INT NOT NULL,
price DOUBLE NOT NULL,
sales INT NOT NULL,
total INT NOT NULL
);
ALTER TABLE coffees
ADD CONSTRAINT coffees_suppliers_fk FOREIGN KEY (sup_id) REFERENCES suppliers(sup_id);
""".update
}
// Lifted println
def putStrLn(s: => String): ConnectionIO[Unit] =
FC.delay(println(s))
}
| tpolecat/doobie | modules/example/src/main/scala/example/FirstExample.scala | Scala | mit | 4,670 |
/*
* Copyright 2016 The BigDL Authors.
*
* 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.intel.analytics.bigdl.dllib.nn
import com.intel.analytics.bigdl.dllib.tensor.Tensor
import com.intel.analytics.bigdl._
import com.intel.analytics.bigdl.dllib.nn.tf.TanhGrad
import com.intel.analytics.bigdl.dllib.utils.T
import com.intel.analytics.bigdl.dllib.utils.serializer.ModuleSerializationTest
import org.scalatest.{FlatSpec, Matchers}
import scala.math.abs
@com.intel.analytics.bigdl.tags.Parallel
class TanhSpec extends FlatSpec with Matchers {
"A Tanh Module " should "generate correct output and grad" in {
val module = new Tanh[Double]()
val input = Tensor[Double](2, 2, 2)
input(Array(1, 1, 1)) = -0.17020166106522
input(Array(1, 1, 2)) = 0.57785657607019
input(Array(1, 2, 1)) = -1.3404131438583
input(Array(1, 2, 2)) = 1.0938102817163
input(Array(2, 1, 1)) = 1.120370157063
input(Array(2, 1, 2)) = -1.5014141565189
input(Array(2, 2, 1)) = 0.3380249235779
input(Array(2, 2, 2)) = -0.625677742064
val gradOutput = Tensor[Double](2, 2, 2)
gradOutput(Array(1, 1, 1)) = 0.79903302760795
gradOutput(Array(1, 1, 2)) = 0.019753993256018
gradOutput(Array(1, 2, 1)) = 0.63136631483212
gradOutput(Array(1, 2, 2)) = 0.29849314852618
gradOutput(Array(2, 1, 1)) = 0.94380705454387
gradOutput(Array(2, 1, 2)) = 0.030344664584845
gradOutput(Array(2, 2, 1)) = 0.33804601291195
gradOutput(Array(2, 2, 2)) = 0.8807330634445
val expectedOutput = Tensor[Double](2, 2, 2)
expectedOutput(Array(1, 1, 1)) = -0.16857698275003
expectedOutput(Array(1, 1, 2)) = 0.52110579963112
expectedOutput(Array(1, 2, 1)) = -0.87177144344863
expectedOutput(Array(1, 2, 2)) = 0.79826462420686
expectedOutput(Array(2, 1, 1)) = 0.80769763073281
expectedOutput(Array(2, 1, 2)) = -0.90540347425835
expectedOutput(Array(2, 2, 1)) = 0.32571298952384
expectedOutput(Array(2, 2, 2)) = -0.55506882753488
val expectedGrad = Tensor[Double](2, 2, 2)
expectedGrad(Array(1, 1, 1)) = 0.77632594793144
expectedGrad(Array(1, 1, 2)) = 0.014389771607755
expectedGrad(Array(1, 2, 1)) = 0.15153710218424
expectedGrad(Array(1, 2, 2)) = 0.1082854310036
expectedGrad(Array(2, 1, 1)) = 0.32809049064441
expectedGrad(Array(2, 1, 2)) = 0.0054694603766104
expectedGrad(Array(2, 2, 1)) = 0.3021830658283
expectedGrad(Array(2, 2, 2)) = 0.6093779706637
val inputOrg = input.clone()
val gradOutputOrg = gradOutput.clone()
val output = module.forward(input)
val gradInput = module.backward(input, gradOutput)
expectedOutput.map(output, (v1, v2) => {
assert(abs(v1 - v2) < 1e-6);
v1
})
expectedGrad.map(gradInput, (v1, v2) => {
assert(abs(v1 - v2) < 1e-6);
v1
})
assert(input == inputOrg)
assert(gradOutput == gradOutputOrg)
}
"A Tanh Module " should "be good in gradient check" in {
val module = new Tanh[Double]()
val input = Tensor[Double](2, 2, 2).rand()
val checker = new GradientChecker(1e-4, 1e-2)
checker.checkLayer[Double](module, input) should be(true)
}
}
class TanhSerialTest extends ModuleSerializationTest {
override def test(): Unit = {
val module = TanhGrad[Float, Float]()
val input = T(Tensor[Float](1, 5, 3, 4).rand(), Tensor[Float](1, 5, 3, 4).rand())
runSerializationTest(module, input)
}
}
| intel-analytics/BigDL | scala/dllib/src/test/scala/com/intel/analytics/bigdl/dllib/nn/TanhSpec.scala | Scala | apache-2.0 | 3,926 |
/*
* Copyright 2015 the original author or authors.
* @https://github.com/scouter-project/scouter
*
* 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 scouter.server.account;
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream
import java.util.ArrayList
import java.util.Enumeration
import java.util.List
import java.util.Properties;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import scouter.server.Configure
import scouter.server.Logger
import scouter.lang.Account
import scouter.lang.pack.MapPack
import scouter.lang.value.MapValue
import scouter.lang.value.Value
import scouter.util.CipherUtil
import scouter.util.FileUtil
import scouter.util.StringKeyLinkedMap
import scouter.util.ThreadUtil
import scouter.server.util.ThreadScala
import scouter.server.core.CoreRun
object AccountManager {
val ACCOUNT_FILENAME = "account.xml";
val GROUP_FILENAME = "account_group.xml";
var accountMap = new StringKeyLinkedMap[Account]();
var groupPolicyMap = new StringKeyLinkedMap[MapValue]();
val confPath = Configure.CONF_DIR;
var conf = Configure.getInstance();
FileUtil.mkdirs(confPath);
val groupFile = new File(confPath + GROUP_FILENAME);
val accountFile = new File(confPath + ACCOUNT_FILENAME);
loadGroupFile();
loadAccountFile();
var lastModifiedAccountFile = 0L
var lastModifiedGroupFile = 0L
ThreadScala.startDaemon("scouter.server.account.AccountManager", { CoreRun.running }, 5000) {
if (groupFile.lastModified() != lastModifiedGroupFile) {
loadGroupFile();
}
if (accountFile.lastModified() != lastModifiedAccountFile) {
loadAccountFile();
}
}
private def loadGroupFile() {
this.synchronized {
try {
Logger.println("Load Account Group File");
if (groupFile.canRead() == false) {
var in: InputStream = null;
var fos: FileOutputStream = null;
var copyFailed = true;
var tryCnt = 0;
while (copyFailed) {
try {
tryCnt += 1;
in = AccountManager.getClass().getResourceAsStream("/scouter/server/account/" + GROUP_FILENAME);
fos = new FileOutputStream(groupFile);
fos.write(FileUtil.readAll(in));
copyFailed = false;
} catch {
case e: Exception =>
e.printStackTrace();
if (tryCnt > 3) {
throw new RuntimeException("Cannot copy account_group.xml");
}
ThreadUtil.sleep(2000);
} finally {
FileUtil.close(fos);
FileUtil.close(in);
}
}
}
groupPolicyMap = GroupFileHandler.parse(groupFile);
lastModifiedGroupFile = groupFile.lastModified();
} catch {
case e: Exception => e.printStackTrace();
}
}
}
private def loadAccountFile() {
this.synchronized {
try {
Logger.println("Load Account File");
if (accountFile.canRead() == false) {
var in: InputStream = null;
var fos: FileOutputStream = null;
var copyFailed = true;
var tryCnt = 0;
while (copyFailed) {
try {
tryCnt += 1;
in = AccountManager.getClass().getResourceAsStream("/scouter/server/account/" + ACCOUNT_FILENAME);
fos = new FileOutputStream(accountFile);
fos.write(FileUtil.readAll(in));
copyFailed = false;
} catch {
case e: Exception =>
e.printStackTrace();
if (tryCnt > 3) {
throw new RuntimeException("Cannot copy account.xml");
}
ThreadUtil.sleep(2000);
} finally {
FileUtil.close(fos);
FileUtil.close(in);
}
}
}
accountMap = AccountFileHandler.parse(accountFile);
lastModifiedAccountFile = accountFile.lastModified();
} catch {
case e: Exception => e.printStackTrace();
}
}
}
def authorizeAccount(id: String, pass: String): Account = {
if(conf.getBoolean("account_use_ldap",false)){
var ctx : DirContext = null;
var props : Properties = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.setProperty(Context.PROVIDER_URL, conf.getValue("account_ldap_provider_url"));
props.setProperty(Context.SECURITY_AUTHENTICATION, conf.getValue("account_ldap_auth=","simple"));
props.setProperty(Context.SECURITY_PRINCIPAL, id+conf.getValue("account_ldap_principal_domain"));
props.setProperty(Context.SECURITY_CREDENTIALS, pass);
try{
ctx = new InitialDirContext(props);
var cons : SearchControls = new SearchControls();
cons.setSearchScope(SearchControls.SUBTREE_SCOPE);
var searchFilter : String = "(cn="+id+")";
if(conf.getBoolean("account_ldap_debug", false)){
Logger.println("ldap id : "+id);
Logger.println("ldap pass : "+pass);
Logger.println("ldap properties : "+props.toString());
}
var result = ctx.search(conf.getValue("account_ldap_basedn"), searchFilter, cons);
var nextEntry : SearchResult = null;
if(result.hasMore()){
var attrs = result.next().getAttributes();
var nmEnum = attrs.getIDs();
while(nmEnum.hasMore()){
var _id = nmEnum.next();
if( id.equals( attrs.get(_id).get().toString()) ){
var account : Account = new Account();
account.id = id
try{
account.email = attrs.get(conf.getValue("account_ldap_email_id","")).get().toString();
account.group = attrs.get(conf.getValue("account_ldap_group_id","")).get().toString();
}catch{
case ne : NullPointerException => ne.printStackTrace()
}
return account;
}
}
}
}catch{
case e: Exception => Logger.println("Ldap Account Error : "+e.toString()); e.printStackTrace();
}finally{
if(null != ctx) ctx.close();
}
}else{
val account = accountMap.get(id);
if (account == null) {
return null;
}
if (account.password.equals(pass)) {
return account;
}
}
return null;
}
def getAccountList(): List[Account] = {
val list = new ArrayList[Account]();
val accEnu = accountMap.values();
while (accEnu.hasMoreElements()) {
list.add(accEnu.nextElement());
}
return list;
}
def getGroupList(): Array[String] = {
return groupPolicyMap.keyArray();
}
def addAccount(account: Account): Boolean = {
this.synchronized {
if (accountMap.get(account.id) != null) {
return false;
}
try {
AccountFileHandler.addAccount(accountFile, account);
accountMap.put(account.id, account);
lastModifiedAccountFile = accountFile.lastModified();
return true;
} catch {
case e: Exception => e.printStackTrace();
}
return false;
}
}
def editAccount(account: Account): Boolean = {
this.synchronized {
if (accountMap.get(account.id) == null) {
return false;
}
try {
AccountFileHandler.editAccount(accountFile, account);
accountMap.put(account.id, account);
lastModifiedAccountFile = accountFile.lastModified();
return true;
} catch {
case e: Exception => e.printStackTrace();
}
return false;
}
}
def addAccountGroup(pack: MapPack): Boolean = {
this.synchronized {
val name = pack.getText("name");
val v = pack.get("policy");
if (name == null || v == null) {
return false;
}
val result = GroupFileHandler.addAccountGroup(groupFile, name, v.asInstanceOf[MapValue]);
if (result) {
groupPolicyMap.put(name, v.asInstanceOf[MapValue]);
lastModifiedGroupFile = groupFile.lastModified();
}
return result;
}
}
def editGroupPolicy(pack: MapPack): Boolean = {
this.synchronized {
val result = GroupFileHandler.editGroupPolicy(groupFile, pack);
if (result) {
loadGroupFile();
}
return result;
}
}
def avaliableId(id: String): Boolean = {
return accountMap.containsKey(id) == false;
}
def getAccount(id: String): Account = {
return accountMap.get(id);
}
def getGroupPolicy(groupName: String): MapValue = {
return groupPolicyMap.get(groupName);
}
def readAccountGroup(): Array[Byte] = {
return FileUtil.readAll(groupFile);
}
}
| yuyupapa/OpenSource | scouter.server/src/scouter/server/account/AccountManager.scala | Scala | apache-2.0 | 11,219 |
object BinaryBar {
val binary = "2.12"
}
| densh/sbt-cross-project | sbt-crossproject-test/src/sbt-test/new-api/shared-cross-sources/foo/shared/src/main/scala-2.13/BinaryBar.scala | Scala | bsd-3-clause | 43 |
package project
import sbt._
import Keys._
import sbtassembly.AssemblyPlugin.autoImport._
import sbtassembly.{MergeStrategy, PathList}
object BuildSettings {
// Basic settings for our app
lazy val basicSettings = Seq[Setting[_]](
name := "SparkTestLab",
organization := "com.diegomagalhaes",
version := "1.0",
description := "Simple job for the Spark cluster computing platform, ready for Amazon EMR",
scalaVersion := "2.10.4",
scalacOptions := Seq("-deprecation", "-encoding", "utf8"),
javacOptions ++= Seq("-source", "1.7", "-target", "1.7"),
resolvers ++= Seq(
DefaultMavenRepository,
"Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/",
"Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots"
),
libraryDependencies ++= Seq(
"com.diegomagalhaes" %% "scalanginxaccesslogparser" % "1.3-SNAPSHOT",
"org.apache.spark" % "spark-core_2.10" % "1.5.2" % "provided",
"org.apache.spark" % "spark-sql_2.10" % "1.5.2" % "provided",
"com.databricks" % "spark-csv_2.10" % "1.2.0",
"com.github.tototoshi" % "scala-csv_2.10" % "1.2.2",
"org.specs2" % "specs2_2.10" % "1.12.3" % "test"
)
)
// sbt-assembly settings for building a fat jar
lazy val sbtAssemblySettings = baseAssemblySettings ++ Seq(
// Slightly cleaner jar name
assemblyJarName in assembly := {
name.value + "-" + version.value + ".jar"
},
// Drop these jars
assemblyExcludedJars in assembly <<= (fullClasspath in assembly) map { cp =>
val excludes = Set(
"jsp-api-2.1-6.1.14.jar",
"jsp-2.1-6.1.14.jar",
"jasper-compiler-5.5.12.jar",
"commons-beanutils-core-1.8.0.jar",
"commons-beanutils-1.7.0.jar",
"servlet-api-2.5-20081211.jar",
"servlet-api-2.5.jar"
)
cp filter { jar => excludes(jar.data.getName) }
},
assemblyMergeStrategy in assembly := {
case x if x.endsWith(".html") => MergeStrategy.discard
case PathList("META-INF", xs@_*) => MergeStrategy.discard
case x => MergeStrategy.first
}
)
lazy val buildSettings = basicSettings ++ sbtAssemblySettings
} | dgomesbr/SparkTestLab | project/project/BuildSettings.scala | Scala | apache-2.0 | 2,212 |
Subsets and Splits
Filtered Scala Code Snippets
The query filters and retrieves a sample of code snippets that meet specific criteria, providing a basic overview of the dataset's content without revealing deeper insights.