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 (c) 2013-2018 Commonwealth Computer Research, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution and is available at
* http://www.opensource.org/licenses/apache2.0.php.
***********************************************************************/
package org.locationtech.geomesa.fs.storage.converter
import java.util.Optional
import java.util.regex.Pattern
import com.typesafe.scalalogging.LazyLogging
import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FileContext, Path}
import org.locationtech.geomesa.convert.{ConfArgs, ConverterConfigResolver, SimpleFeatureConverters}
import org.locationtech.geomesa.fs.storage.api.{FileSystemStorage, FileSystemStorageFactory}
import org.locationtech.geomesa.fs.storage.common.{FileMetadata, PartitionScheme}
import org.locationtech.geomesa.utils.geotools.{SftArgResolver, SftArgs}
import org.opengis.feature.simple.SimpleFeatureType
class ConverterStorageFactory extends FileSystemStorageFactory with LazyLogging {
import ConverterStorageFactory._
import scala.collection.JavaConverters._
override def getEncoding: String = "converter"
override def load(fc: FileContext,
conf: Configuration,
root: Path): Optional[FileSystemStorage] = {
if (Option(conf.get(ConverterPathParam)).exists(_ != root.getName) || FileMetadata.load(fc, root).isDefined) {
Optional.empty()
} else {
try {
val sft = {
val sftArg = Option(conf.get(SftConfigParam))
.orElse(Option(conf.get(SftNameParam)))
.getOrElse(throw new IllegalArgumentException(s"Must provide either simple feature type config or name"))
SftArgResolver.getArg(SftArgs(sftArg, null)) match {
case Left(e) => throw new IllegalArgumentException("Could not load SimpleFeatureType with provided parameters", e)
case Right(schema) => schema
}
}
val converter = {
val convertArg = Option(conf.get(ConverterConfigParam))
.orElse(Option(conf.get(ConverterNameParam)))
.getOrElse(throw new IllegalArgumentException(s"Must provide either converter config or name"))
val converterConfig = ConverterConfigResolver.getArg(ConfArgs(convertArg)) match {
case Left(e) => throw new IllegalArgumentException("Could not load Converter with provided parameters", e)
case Right(c) => c
}
SimpleFeatureConverters.build(sft, converterConfig)
}
val partitionScheme = {
val partitionSchemeName =
Option(conf.get(PartitionSchemeParam))
.getOrElse(throw new IllegalArgumentException(s"Must provide partition scheme name"))
val partitionSchemeOpts =
conf.getValByRegex(Pattern.quote(PartitionOptsPrefix) + ".*").asScala.map {
case (k, v) => k.substring(PartitionOptsPrefix.length) -> v
}
PartitionScheme(sft, partitionSchemeName, partitionSchemeOpts.asJava)
}
Optional.of(new ConverterStorage(fc, root, sft, converter, partitionScheme))
} catch {
case e: IllegalArgumentException => logger.warn(s"Couldn't create converter storage: $e", e); Optional.empty()
}
}
}
override def create(fc: FileContext,
conf: Configuration,
root: Path,
sft: SimpleFeatureType): FileSystemStorage = {
throw new NotImplementedError("Converter FS is read only")
}
}
object ConverterStorageFactory {
val ConverterNameParam = "fs.options.converter.name"
val ConverterConfigParam = "fs.options.converter.conf"
val ConverterPathParam = "fs.options.converter.path"
val SftNameParam = "fs.options.sft.name"
val SftConfigParam = "fs.options.sft.conf"
val PartitionSchemeParam = "fs.partition-scheme.name"
val PartitionOptsPrefix = "fs.partition-scheme.opts."
}
|
jahhulbert-ccri/geomesa
|
geomesa-fs/geomesa-fs-storage/geomesa-fs-storage-convert/src/main/scala/org/locationtech/geomesa/fs/storage/converter/ConverterStorageFactory.scala
|
Scala
|
apache-2.0
| 4,170 |
import engine.WorkflowDefinition
package object definitions {
val availableWorkflowDefinitions: List[WorkflowDefinition] = List(Demo, ExampleWorkflow, RandomWorkflow)
}
|
mpod/scala-workflow
|
backend/src/main/scala/definitions/package.scala
|
Scala
|
gpl-3.0
| 174 |
package com.dt.scala.dataset
/**
* Author: Wang Jialin
* Contact Information:
* WeChat: 18610086859
* QQ: 1740415547
* Email: [email protected]
* Tel: 18610086859
*/
object HelloList {
def main(args: Array[String]) {
val bigData = List("Hadoop", "Spark")
val data = List(1, 2, 3)
val bigData_Core = "Hadoop" :: ("Spark" :: Nil)
val data_Int = 1 :: 2 :: 3 :: Nil
println(data.isEmpty)
println(data.head)
println(data.tail.head)
val List(a, b) = bigData
println("a : " + a + " === " + " b: " + b)
val x :: y :: rest = data
println("x : " + x + " === " + " y: " + y + " === " + rest)
val shuffledData = List(6, 3, 5, 6, 2, 9, 1)
println(sortList(shuffledData))
def sortList(list: List[Int]): List[Int] = list match {
case List() => List()
case head :: tail => compute(head, sortList(tail))
}
def compute(data: Int, dataSet: List[Int]): List[Int] = dataSet match {
case List() => List(data)
case head :: tail => if (data <= head) data :: dataSet
else head :: compute(data, tail)
}
}
}
|
slieer/scala-tutorials
|
src/main/scala/com/dt/scala/dataset/HelloList.scala
|
Scala
|
apache-2.0
| 1,151 |
package com.github.agourlay.cornichon.core
case class FeatureDef(name: String, scenarios: List[Scenario], ignored: Option[String] = None) {
require(
scenarios.map(s => s.name).distinct.length == scenarios.length,
s"Scenarios name must be unique within a Feature - error caused by duplicated declaration of scenarios '${scenarios.map(s => s.name).diff(scenarios.map(s => s.name).distinct).mkString(", ")}'"
)
val focusedScenarios: Set[String] = scenarios.iterator.collect { case s if s.focused => s.name }.toSet
}
case class Scenario(
name: String,
steps: List[Step],
ignored: Option[String] = None,
pending: Boolean = false,
focused: Boolean = false)
|
agourlay/cornichon
|
cornichon-core/src/main/scala/com/github/agourlay/cornichon/core/Models.scala
|
Scala
|
apache-2.0
| 687 |
package org.opencompare.experimental.io.wikipedia.parser
import java.io.StringReader
import de.fau.cs.osr.ptk.common.AstVisitor
import org.ccil.cowan.tagsoup.jaxp.SAXFactoryImpl
import org.xml.sax.InputSource
import scala.xml.Node
import scala.xml.parsing.NoBindingFactoryAdapter
import scalaj.http.{Http, HttpOptions}
import org.sweble.wikitext.parser.nodes._
class PreprocessVisitor extends AstVisitor[WtNode] with CompleteWikitextVisitorNoReturn {
val code = new StringBuilder
var isInTemplateName = false
var templateName = new StringBuilder
var isInTemplateArg = false
var templateArg = new StringBuilder
val templateCache: collection.mutable.Map[String, String] = collection.mutable.Map()
def getPreprocessedCode(): String = {
code.toString
}
/**
* Expand template in WikiCode with the special page on English version of Wikipedia
*/
def expandTemplate(template: String): String = {
val cachedTemplate = templateCache.get(template)
if (cachedTemplate.isDefined) {
cachedTemplate.get
} else {
// Ask expanded template
val expandTemplatesPage = Http.post("https://en.wikipedia.org/wiki/Special:ExpandTemplates")
.params("wpInput" -> template, "wpRemoveComments" -> "1", "wpRemoveNowiki" -> "1")
.option(HttpOptions.connTimeout(1000))
.option(HttpOptions.readTimeout(30000))
.asString
// Filter the returned page
val xml = parseHTMLAsXML(expandTemplatesPage)
val textareas = xml \\\\ "textarea"
var expandedTemplate = textareas.filter(_.attribute("id") exists (_.text == "output")).text
// Remove line breaks
if (expandedTemplate.length >= 2) {
expandedTemplate = expandedTemplate.substring(1, expandedTemplate.length - 1)
}
// Add template to cache
templateCache += template -> expandedTemplate
expandedTemplate
}
}
/**
* Clean HTML to get strict XML
*/
private def parseHTMLAsXML(htmlCode: String): Node = {
val adapter = new NoBindingFactoryAdapter
val htmlParser = (new SAXFactoryImpl).newSAXParser()
val xml = adapter.loadXML(new InputSource(new StringReader(htmlCode)), htmlParser)
xml
}
def visit(e: WtPreproWikitextPage) {
iterate(e)
}
def visit(e: WtNodeList) {
iterate(e)
}
def visit(e: WtXmlComment) {
}
def visit(e: WtText) {
if (isInTemplateName) {
templateName ++= e.getContent()
} else if (isInTemplateArg) {
templateArg ++= e.getContent()
} else {
code ++= e.getContent()
}
}
def visit(e: WtTemplate) {
val template = new StringBuilder
template ++= "{{"
// Parse name of the template
isInTemplateName = true
dispatch(e.getName())
template ++= templateName
templateName = new StringBuilder
isInTemplateName = false
// Parse arguments of the template
isInTemplateArg = true
val argIterator = e.getArgs().iterator()
while (argIterator.hasNext()) {
template ++= "|"
val arg = argIterator.next()
templateArg = new StringBuilder
dispatch(arg)
template ++= templateArg
}
isInTemplateArg = false
template ++= "}}"
// Call special page on wikipedia to expand the template
val expandedTemplate = expandTemplate(template.toString())
// println("-----")
// println(e)
// println(template.toString)
// println(expandedTemplate)
// println("-----")
code ++= expandedTemplate
}
def visit(e: WtTemplateArgument) {
if (!e.getName().isEmpty()) {
dispatch(e.getName())
templateArg ++= "="
}
dispatch(e.getValue())
}
def visit(e: WtIgnored) {
}
def visit(e: WtTagExtension) {
// a TagExtension is a reference which may contain usefull information
}
def visit(e: WtRedirect) {
}
override def visit(e: WtTableImplicitTableBody): Unit = iterate(e)
override def visit(e: WtLinkOptionLinkTarget): Unit = iterate(e)
override def visit(e: WtTableHeader): Unit = iterate(e)
override def visit(e: WtTableRow): Unit = iterate(e)
override def visit(e: WtTemplateArguments): Unit = iterate(e)
override def visit(e: WtUnorderedList): Unit = iterate(e)
override def visit(e: WtValue): Unit = iterate(e)
override def visit(e: WtWhitespace): Unit = iterate(e)
override def visit(e: WtXmlAttributes): Unit = iterate(e)
override def visit(e: WtLinkOptionGarbage): Unit = iterate(e)
override def visit(e: WtNewline): Unit = iterate(e)
override def visit(e: WtPageName): Unit = iterate(e)
override def visit(e: WtXmlElement): Unit = iterate(e)
override def visit(e: WtImageLink): Unit = iterate(e)
override def visit(e: WtTemplateParameter): Unit = iterate(e)
override def visit(e: WtHorizontalRule): Unit = iterate(e)
override def visit(e: WtIllegalCodePoint): Unit = iterate(e)
override def visit(e: WtLinkOptionKeyword): Unit = iterate(e)
override def visit(e: WtLinkOptionResize): Unit = iterate(e)
override def visit(e: WtXmlAttribute): Unit = iterate(e)
override def visit(e: WtXmlEmptyTag): Unit = iterate(e)
override def visit(e: WtXmlStartTag): Unit = iterate(e)
override def visit(e: WtImStartTag): Unit = iterate(e)
override def visit(e: WtImEndTag): Unit = iterate(e)
override def visit(e: WtXmlEndTag): Unit = iterate(e)
override def visit(e: WtXmlCharRef): Unit = iterate(e)
override def visit(e: WtUrl): Unit = iterate(e)
override def visit(e: WtTicks): Unit = iterate(e)
override def visit(e: WtSignature): Unit = iterate(e)
override def visit(e: WtPageSwitch): Unit = iterate(e)
override def visit(e: WtTableCell): Unit = iterate(e)
override def visit(e: WtTableCaption): Unit = iterate(e)
override def visit(e: WtTable): Unit = iterate(e)
override def visit(e: WtSection): Unit = iterate(e)
override def visit(e: WtInternalLink): Unit = iterate(e)
override def visit(e: WtExternalLink): Unit = iterate(e)
override def visit(e: WtXmlEntityRef): Unit = iterate(e)
override def visit(e: WtBody): Unit = iterate(e)
override def visit(e: WtBold): Unit = iterate(e)
override def visit(e: WtParsedWikitextPage): Unit = iterate(e)
override def visit(e: WtOrderedList): Unit = iterate(e)
override def visit(e: WtOnlyInclude): Unit = iterate(e)
override def visit(e: WtName): Unit = iterate(e)
override def visit(e: WtListItem): Unit = iterate(e)
override def visit(e: WtLinkTitle): Unit = iterate(e)
override def visit(e: WtLinkOptions): Unit = iterate(e)
override def visit(e: WtLinkOptionAltText): Unit = iterate(e)
override def visit(e: WtItalics): Unit = iterate(e)
override def visit(e: WtHeading): Unit = iterate(e)
override def visit(e: WtDefinitionListTerm): Unit = iterate(e)
override def visit(e: WtDefinitionListDef): Unit = iterate(e)
override def visit(e: WtDefinitionList): Unit = iterate(e)
override def visit(e: WtParagraph): Unit = iterate(e)
override def visit(e: WtSemiPre): Unit = iterate(e)
override def visit(e: WtSemiPreLine): Unit = iterate(e)
override def visit(e: WtXmlAttributeGarbage): Unit = iterate(e)
override def visit(e: WtTagExtensionBody): Unit = iterate(e)
}
|
OpenCompare/sandbox
|
experimental/src/main/scala/org/opencompare/experimental/io/wikipedia/parser/PreprocessVisitor.scala
|
Scala
|
apache-2.0
| 7,220 |
package de.hpi.asg.breezetestgen
import baseclasses.UnitTest
import de.hpi.asg.breezetestgen.domain.{Constant, DataAcknowledge, Request, Signal}
import de.hpi.asg.breezetestgen.fixtures.GCDTest
import de.hpi.asg.breezetestgen.testing.{IOEvent, JsonFromTo}
class TestJsonSpec extends UnitTest {
private val (ain, bin, o) = (12, 8, 4)
private val gcdTest = GCDTest(ain, bin, o)
def isDefinedIn(signal: Signal, test: testing.Test) = {
test.nodes.map(_.value).collectFirst{case IOEvent(_, `signal`) => true}.isDefined
}
"JSON export and import" should "produce the same test again" in {
val gcdJson = JsonFromTo.testToJsonString(gcdTest)
val gcdAgainO = JsonFromTo.testFromJson(gcdJson)
assert(gcdAgainO.isDefined)
val gcdAgain = gcdAgainO.get
// okay, this could be tested better
assert(isDefinedIn(Request(2), gcdAgain))
assert(isDefinedIn(DataAcknowledge(2, Constant(ain)), gcdAgain))
}
}
|
0x203/BreezeTestGen
|
src/test/scala/de/hpi/asg/breezetestgen/TestJsonSpec.scala
|
Scala
|
mit
| 937 |
package com.keba.scala.bank.transactions
import java.util.Date
import com.keba.scala.bank.money.Money
/**
* Entry in transaction history of a bank account that describes a
* deposit of foreign currency to the bank account.
*
* @author alexp
*/
class ForeignCurrencyDepositTransactionHistoryEntry(override val timeStamp: Date,
override val bankAccountNumber: String,
val foreignCurrencyAmount: Money,
override val amount: Money,
val exchangeRate: BigDecimal)
extends DepositTransactionHistoryEntry(timeStamp, bankAccountNumber, amount) {
}
|
alexp82/ddd-banking-system
|
src/main/scala/com/keba/scala/bank/transactions/ForeignCurrencyDepositTransactionHistoryEntry.scala
|
Scala
|
apache-2.0
| 762 |
/**
* Copyright (C) 2009-2011 Scalable Solutions AB <http://scalablesolutions.se>
*/
package akka.util
import java.util.concurrent.locks.{ ReentrantReadWriteLock, ReentrantLock }
import java.util.concurrent.atomic.{ AtomicBoolean }
import akka.event.EventHandler
/**
* @author <a href="http://jonasboner.com">Jonas Bonér</a>
*/
final class ReentrantGuard {
val lock = new ReentrantLock
final def withGuard[T](body: => T): T = {
lock.lock
try {
body
} finally {
lock.unlock
}
}
final def tryWithGuard[T](body: => T): T = {
while (!lock.tryLock) { Thread.sleep(10) } // wait on the monitor to be unlocked
try {
body
} finally {
lock.unlock
}
}
}
/**
* @author <a href="http://jonasboner.com">Jonas Bonér</a>
*/
class ReadWriteGuard {
private val rwl = new ReentrantReadWriteLock
val readLock = rwl.readLock
val writeLock = rwl.writeLock
def withWriteGuard[T](body: => T): T = {
writeLock.lock
try {
body
} finally {
writeLock.unlock
}
}
def withReadGuard[T](body: => T): T = {
readLock.lock
try {
body
} finally {
readLock.unlock
}
}
}
/**
* A very simple lock that uses CCAS (Compare Compare-And-Swap)
* Does not keep track of the owner and isn't Reentrant, so don't nest and try to stick to the if*-methods
*/
class SimpleLock {
val acquired = new AtomicBoolean(false)
def ifPossible(perform: () => Unit): Boolean = {
if (tryLock()) {
try {
perform
} finally {
unlock()
}
true
} else false
}
def ifPossibleYield[T](perform: () => T): Option[T] = {
if (tryLock()) {
try {
Some(perform())
} finally {
unlock()
}
} else None
}
def ifPossibleApply[T, R](value: T)(function: (T) => R): Option[R] = {
if (tryLock()) {
try {
Some(function(value))
} finally {
unlock()
}
} else None
}
def tryLock() = {
if (acquired.get) false
else acquired.compareAndSet(false, true)
}
def tryUnlock() = {
acquired.compareAndSet(true, false)
}
def locked = acquired.get
def unlock() {
acquired.set(false)
}
}
/**
* An atomic switch that can be either on or off
*/
class Switch(startAsOn: Boolean = false) {
private val switch = new AtomicBoolean(startAsOn)
protected def transcend(from: Boolean, action: => Unit): Boolean = synchronized {
if (switch.compareAndSet(from, !from)) {
try {
action
} catch {
case e: Throwable =>
EventHandler.error(e, this, e.getMessage)
switch.compareAndSet(!from, from) // revert status
throw e
}
true
} else false
}
def switchOff(action: => Unit): Boolean = transcend(from = true, action)
def switchOn(action: => Unit): Boolean = transcend(from = false, action)
def switchOff: Boolean = synchronized { switch.compareAndSet(true, false) }
def switchOn: Boolean = synchronized { switch.compareAndSet(false, true) }
def ifOnYield[T](action: => T): Option[T] = {
if (switch.get) Some(action)
else None
}
def ifOffYield[T](action: => T): Option[T] = {
if (!switch.get) Some(action)
else None
}
def ifOn(action: => Unit): Boolean = {
if (switch.get) {
action
true
} else false
}
def ifOff(action: => Unit): Boolean = {
if (!switch.get) {
action
true
} else false
}
def whileOnYield[T](action: => T): Option[T] = synchronized {
if (switch.get) Some(action)
else None
}
def whileOffYield[T](action: => T): Option[T] = synchronized {
if (!switch.get) Some(action)
else None
}
def whileOn(action: => Unit): Boolean = synchronized {
if (switch.get) {
action
true
} else false
}
def whileOff(action: => Unit): Boolean = synchronized {
if (switch.get) {
action
true
} else false
}
def ifElseYield[T](on: => T)(off: => T) = synchronized {
if (switch.get) on else off
}
def isOn = switch.get
def isOff = !isOn
}
|
felixmulder/scala
|
test/disabled/presentation/akka/src/akka/util/LockUtil.scala
|
Scala
|
bsd-3-clause
| 4,115 |
package com.twitter.finagle.netty4
import com.twitter.io.Buf
import com.twitter.io.Buf.ByteArray
import io.netty.buffer._
private[finagle] object ByteBufAsBuf {
object Owned {
/**
* Construct a [[Buf]] wrapper for ``ByteBuf``.
*
* @note this wrapper does not support ref-counting and therefore should either
* be used with unpooled and non-leak detecting allocators or managed
* via the ref-counting methods of the wrapped `buf`. Non-empty buffers
* are `retain`ed.
*/
def apply(buf: ByteBuf): Buf =
if (buf.readableBytes == 0)
Buf.Empty
else
new ByteBufAsBuf(buf)
/**
* Extract a [[ByteBufAsBuf]]'s underlying ByteBuf without copying.
*/
def unapply(wrapped: ByteBufAsBuf): Option[ByteBuf] = Some(wrapped.underlying)
/**
* Extract a read-only `ByteBuf` from [[Buf]] potentially without copying.
*/
def extract(buf: Buf): ByteBuf = BufAsByteBuf.Owned(buf)
}
object Shared {
/**
* Construct a [[Buf]] by copying `ByteBuf`.
*/
def apply(buf: ByteBuf): Buf =
if (buf.readableBytes == 0)
Buf.Empty
else
new ByteBufAsBuf(buf.copy())
/**
* Extract a copy of the [[ByteBufAsBuf]]'s underlying ByteBuf.
*/
def unapply(wrapped: ByteBufAsBuf): Option[ByteBuf] = Some(wrapped.underlying.copy())
/**
* Extract a read-only `ByteBuf` copy from [[Buf]].
*/
def extract(buf: Buf): ByteBuf = BufAsByteBuf.Shared(buf)
}
}
/**
* a [[Buf]] wrapper for Netty `ByteBuf`s.
*/
private[finagle] class ByteBufAsBuf(private val underlying: ByteBuf) extends Buf {
def write(bytes: Array[Byte], off: Int): Unit = {
val dup = underlying.duplicate()
dup.readBytes(bytes, off, dup.readableBytes)
}
protected def unsafeByteArrayBuf: Option[ByteArray] =
if (underlying.hasArray) {
val bytes = underlying.array
val begin = underlying.arrayOffset + underlying.readerIndex
val end = begin + underlying.readableBytes
Some(new Buf.ByteArray(bytes, begin, end))
} else None
def length: Int = underlying.readableBytes
def slice(from: Int, until: Int): Buf = {
if (from < 0 || until < 0)
throw new IndexOutOfBoundsException(s"slice indexes must be >= 0, saw from: $from until: $until")
if (until <= from || from >= length) Buf.Empty
else if (from == 0 && until >= length) this
else new ByteBufAsBuf(underlying.slice(from, Math.min((until-from), (length-from))))
}
override def equals(other: Any): Boolean = other match {
case ByteBufAsBuf.Owned(otherBB) => underlying.equals(otherBB)
case other: Buf => Buf.equals(this, other)
case _ => false
}
}
|
sveinnfannar/finagle
|
finagle-netty4/src/main/scala/com/twitter/finagle/netty4/ByteBufAsBuf.scala
|
Scala
|
apache-2.0
| 2,726 |
package foo
object Compile {
def main(args: Array[String]): Unit = {
println("hello world")
}
}
|
xuwei-k/xsbt
|
sbt-app/src/sbt-test/project/semanticdb/src/main/scala/foo/Compile.scala
|
Scala
|
apache-2.0
| 105 |
package ml.combust.mleap.bundle.ops.feature
import ml.combust.bundle.BundleContext
import ml.combust.bundle.dsl._
import ml.combust.bundle.op.OpModel
import ml.combust.mleap.bundle.ops.MleapOp
import ml.combust.mleap.core.feature.BucketedRandomProjectionLSHModel
import ml.combust.mleap.runtime.MleapContext
import ml.combust.mleap.runtime.transformer.feature.BucketedRandomProjectionLSH
import ml.combust.mleap.tensor.Tensor
import org.apache.spark.ml.linalg.Vectors
/**
* Created by hollinwilkins on 12/28/16.
*/
class BucketedRandomProjectionLSHOp extends MleapOp[BucketedRandomProjectionLSH, BucketedRandomProjectionLSHModel] {
override val Model: OpModel[MleapContext, BucketedRandomProjectionLSHModel] = new OpModel[MleapContext, BucketedRandomProjectionLSHModel] {
override val klazz: Class[BucketedRandomProjectionLSHModel] = classOf[BucketedRandomProjectionLSHModel]
override def opName: String = Bundle.BuiltinOps.feature.bucketed_random_projection_lsh
override def store(model: Model, obj: BucketedRandomProjectionLSHModel)
(implicit context: BundleContext[MleapContext]): Model = {
model.withValue("random_unit_vectors", Value.tensorList[Double](obj.randomUnitVectors.map(v => Tensor.denseVector(v.toArray)))).
withValue("bucket_length", Value.double(obj.bucketLength)).
withValue("input_size", Value.int(obj.inputSize))
}
override def load(model: Model)
(implicit context: BundleContext[MleapContext]): BucketedRandomProjectionLSHModel = {
val ruv = model.value("random_unit_vectors").getTensorList[Double].map(_.toArray).map(Vectors.dense)
BucketedRandomProjectionLSHModel(randomUnitVectors = ruv,
bucketLength = model.value("bucket_length").getDouble,
inputSize = model.value("input_size").getInt)
}
}
override def model(node: BucketedRandomProjectionLSH): BucketedRandomProjectionLSHModel = node.model
}
|
combust/mleap
|
mleap-runtime/src/main/scala/ml/combust/mleap/bundle/ops/feature/BucketedRandomProjectionLSHOp.scala
|
Scala
|
apache-2.0
| 1,953 |
package com.example.tictactoe.baseboard
import com.example.tictactoe.InvalidPositionException
import com.example.tictactoe.player.PlayerMark
import com.example.tictactoe.baseboard.Board.Position
/**
* @author s.a.ramamuniappa
*/
case class Square (val position: Position, marking: PlayerMark) {
require(isValidPosition(position))
}
|
ayyappanramamuniappa/tic-tac-toe
|
src/com/example/tictactoe/baseboard/Square.scala
|
Scala
|
apache-2.0
| 339 |
/*
* 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 wvlet.airframe.codec
import wvlet.airframe.surface.Surface
import wvlet.airframe.surface.reflect.ReflectSurfaceFactory
trait CompatBase {
inline def codecOf[A]: MessageCodec[A] = ${ CompatBase.codecOf[A] }
// TODO Implementation
def surfaceOfClass(cl: Class[_]): Surface = ReflectSurfaceFactory.ofClass(cl)
}
private[codec] object CompatBase {
import scala.quoted._
def codecOf[A](using t: Type[A], quotes: Quotes): Expr[MessageCodec[A]] = {
import quotes._
'{ MessageCodecFactory.defaultFactory.of[A] }
}
}
|
wvlet/airframe
|
airframe-codec/.jvm/src/main/scala-3/wvlet/airframe/codec/CompatBase.scala
|
Scala
|
apache-2.0
| 1,101 |
/**
*
*/
package helpers.common
import play.api.templates.Html
/**
* @author Stefan Illgen
*
*/
object repeatWithIndex {
import play.api.data.Field
def apply(field: play.api.data.Field, min: Int = 1)(f: (Field,Int) => Html) = {
(0 until math.max(if (field.indexes.isEmpty) 0 else field.indexes.max + 1, min)).map(i => f(field("[" + i + "]"),i))
}
}
|
stefanil/play2-prototypen
|
forms/repeatWithIndex.scala
|
Scala
|
apache-2.0
| 373 |
/*
* Copyright 2013 http4s.org
*
* 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.http4s
package object syntax {
object all extends AllSyntax
@deprecated("import is no longer needed", "0.22.3")
object kleisli extends KleisliSyntax
object literals extends LiteralsSyntax
object string extends StringSyntax
object header extends HeaderSyntax
}
|
rossabaker/http4s
|
core/shared/src/main/scala/org/http4s/syntax/package.scala
|
Scala
|
apache-2.0
| 880 |
package `object`.foo
class SourceObjectPackage
|
ilinum/intellij-scala
|
testdata/autoImport/all/object/foo/SourceObjectPackage.scala
|
Scala
|
apache-2.0
| 47 |
/**
* 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.camel.scala.dsl
import builder.RouteBuilder
import org.apache.camel.model.InterceptSendToEndpointDefinition
/**
* Scala enrichment for Camel's InterceptSendToEndpointDefinition
*/
case class SInterceptSendToEndpointDefinition(override val target: InterceptSendToEndpointDefinition)(implicit val builder: RouteBuilder) extends SAbstractDefinition[InterceptSendToEndpointDefinition] {
def skipSendToOriginalEndpoint = {
target.skipSendToOriginalEndpoint
this
}
override def apply(block: => Unit) : SInterceptSendToEndpointDefinition = {
builder.build(this, block)
this
}
}
|
jmandawg/camel
|
components/camel-scala/src/main/scala/org/apache/camel/scala/dsl/SInterceptSendToEndpointDefinition.scala
|
Scala
|
apache-2.0
| 1,425 |
/*
* Copyright (c) 2012-2014 Snowplow Analytics Ltd. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.snowplowanalytics.snowplow.enrich
package hadoop
package good
// Scala
import scala.collection.mutable.Buffer
// Specs2
import org.specs2.mutable.Specification
// Scalding
import com.twitter.scalding._
// Cascading
import cascading.tuple.TupleEntry
// This project
import JobSpecHelpers._
/**
* Holds the input and expected data
* for the test.
*/
object StructEventCfLineSpec {
val lines = Lines(
"2012-05-27 11:35:53 DFW3 3343 128.232.0.0 GET d3gs014xn8p70.cloudfront.net /ice.png 200 http://www.psychicbazaar.com/oracles/internal/_session/119-psycards-book-and-deck-starter-pack.html?view=print#detail Mozilla/5.0%20(Windows%20NT%206.1;%20WOW64;%20rv:12.0)%20Gecko/20100101%20Firefox/12.0 &e=se&se_ca=ecomm&se_ac=add-to-basket&se_la=PBZ00110&se_pr=1&se_va=35708.23&dtm=1364230969450&tid=598951&evn=com.snowplowanalytics&vp=2560x934&ds=2543x1420&vid=43&duid=9795bd0203804cd1&p=web&tv=js-0.11.1&fp=2876815413&aid=pbzsite&lang=en-GB&cs=UTF-8&tz=Europe%2FLondon&refr=http%3A%2F%2Fwww.psychicbazaar.com%2F&f_pdf=1&f_qt=0&f_realp=0&f_wma=0&f_dir=0&f_fla=1&f_java=1&f_gears=0&f_ag=1&res=2560x1440&cd=32&cookie=1&url=http%3A%2F%2Fwww.psychicbazaar.com%2Foracles%2F119-psycards-book-and-deck-starter-pack.html%3Fview%3Dprint%23detail"
)
val expected = List(
"pbzsite",
"web",
"2012-05-27 11:35:53.000",
"2013-03-25 17:02:49.450",
"struct",
"com.snowplowanalytics",
null, // We can't predict the event_id
"598951",
null, // No tracker namespace
"js-0.11.1",
"cloudfront",
EtlVersion,
null, // No user_id set
"128.232.0.0",
"2876815413",
"9795bd0203804cd1",
"43",
null, // No network_userid set
"GB", // UK geo-location
"C3",
"Cambridge",
null,
"52.199997",
"0.11669922",
"http://www.psychicbazaar.com/oracles/119-psycards-book-and-deck-starter-pack.html?view=print#detail",
null, // No page title for events
"http://www.psychicbazaar.com/",
"http",
"www.psychicbazaar.com",
"80",
"/oracles/119-psycards-book-and-deck-starter-pack.html",
"view=print",
"detail",
"http",
"www.psychicbazaar.com",
"80",
"/",
null,
null,
"internal", // Internal referer
null,
null,
null, // No marketing campaign info
null, //
null, //
null, //
null, //
null, // No custom contexts
"ecomm", // Structured event fields are set
"add-to-basket", //
"PBZ00110", //
"1", //
"35708.23", //
null, // Unstructured event fields empty
null, //
null, // Transaction fields empty
null, //
null, //
null, //
null, //
null, //
null, //
null, //
null, // Transaction item fields empty
null, //
null, //
null, //
null, //
null, //
null, // Page ping fields are empty
null, //
null, //
null, //
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0",
"Firefox 12",
"Firefox",
"12.0",
"Browser",
"GECKO",
"en-GB",
"1",
"1",
"1",
"0",
"0",
"0",
"0",
"0",
"1",
"1",
"32",
"2560",
"934",
"Windows",
"Windows",
"Microsoft Corporation",
"Europe/London",
"Computer",
"0",
"2560",
"1440",
"UTF-8",
"2543",
"1420"
)
}
/**
* Integration test for the EtlJob:
*
* Check that all tuples in a custom structured event
* (CloudFront format) are successfully extracted.
*/
class StructEventCfLineSpec extends Specification {
"A job which processes a CloudFront file containing 1 valid custom structured event" should {
EtlJobSpec("cloudfront", "0").
source(MultipleTextLineFiles("inputFolder"), StructEventCfLineSpec.lines).
sink[TupleEntry](Tsv("outputFolder")){ buf : Buffer[TupleEntry] =>
"correctly output 1 custom structured event" in {
buf.size must_== 1
val actual = buf.head
for (idx <- StructEventCfLineSpec.expected.indices) {
actual.getString(idx) must beFieldEqualTo(StructEventCfLineSpec.expected(idx), withIndex = idx)
}
}
}.
sink[TupleEntry](Tsv("exceptionsFolder")){ trap =>
"not trap any exceptions" in {
trap must beEmpty
}
}.
sink[String](JsonLine("badFolder")){ error =>
"not write any bad rows" in {
error must beEmpty
}
}.
run.
finish
}
}
|
pkallos/snowplow
|
3-enrich/scala-hadoop-enrich/src/test/scala/com.snowplowanalytics.snowplow.enrich.hadoop/good/StructEventCfLineSpec.scala
|
Scala
|
apache-2.0
| 5,205 |
package euler
package til110
import euler.Utils.withResource
import scala.collection.BitSet
/**
*
* Let S(A) represent the sum of elements in set A of size n. We shall call it a special sum set if
* for any two non-empty disjoint subsets, B and C, the following properties are true:
* S(B) ≠ S(C); that is, sums of subsets cannot be equal.
* If B contains more elements than C then S(B) > S(C).
*
* For example, {81, 88, 75, 42, 87, 84, 86, 65} is not a special sum set because 65 + 87 + 88 = 75 + 81 + 84,
* whereas {157, 150, 164, 119, 79, 159, 161, 139, 158} satisfies both rules
* for all possible subset pair combinations and S(A) = 1286.
*
* Using sets.txt (right click and "Save Link/Target As..."), a 4K text file with one-hundred sets
* containing seven to twelve elements (the two examples given above are the first two sets in the file),
* identify all the special sum sets, A1, A2, ..., Ak, and find the value of S(A1) + S(A2) + ... + S(Ak).
*
*/
object Euler105 extends EulerProblem {
/**
* p1: S(B) ≠ S(C); that is, sums of subsets cannot be equal.
* p2: If B contains more elements than C then S(B) > S(C).
*/
def isSpecialSumSet(xs: Set[Int]) = {
val checks = for {
b <- xs.subsets()
c <- (xs -- b).subsets()
bSum = b.sum
cSum = c.sum
p1 = bSum == 0 || cSum == 0 || bSum != cSum
p2 = (b.size == c.size) || (b.size > c.size && bSum > cSum) || (cSum > bSum)
} yield p1 && p2
checks forall (_ == true)
}
override def result = {
parseSets().par.filter(isSpecialSumSet).map(_.sum).sum
}
def parseSets() = withResource("p105_sets.txt") { src =>
src.getLines().map { line =>
Set(line.split(",").map(_.toInt): _*)
}.toList
}
}
|
TrustNoOne/Euler
|
scala/src/main/scala/euler/til110/Euler105.scala
|
Scala
|
mit
| 1,772 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package scaps.eclipse.ui.search
import org.eclipse.core.runtime.IProgressMonitor
import org.eclipse.core.runtime.IStatus
import org.eclipse.core.runtime.Status
import org.eclipse.search.ui.ISearchQuery
import org.eclipse.search.ui.ISearchResult
import scaps.api.Result
import scaps.api.ValueDef
class ScapsSearchQuery(query: String, searchFunction: (String) => Seq[Result[ValueDef]]) extends ISearchQuery {
val result: ScapsSearchResult = new ScapsSearchResult(this)
def canRerun(): Boolean = false
def canRunInBackground(): Boolean = true
def getLabel(): String = "Scaps Search: \\"" + query + "\\""
def getSearchResult(): ISearchResult = result
def run(monitor: IProgressMonitor): IStatus = {
result.setData(searchFunction(query))
Status.OK_STATUS
}
}
|
flomerz/scala-ide-scaps
|
scala-ide-scaps-plugin/src/main/scala/scaps/eclipse/ui/search/ScapsSearchQuery.scala
|
Scala
|
mpl-2.0
| 990 |
package wow.auth
import wow.auth.protocol.RealmFlags
import wow.auth.protocol.packets.ServerRealmlistEntry
import wow.realm.RealmServerConfiguration
/**
* Information about realm (from the point of view of the authserver)
*/
case class RealmInfo(
id: Int,
realmConfig: RealmServerConfiguration,
var flags: RealmFlags.ValueSet = RealmFlags.ValueSet(RealmFlags.Offline),
private var _population : Float = 0.0f
) {
require(id > 0)
def population: Float = _population
def population_=(newPopulation: Float): Unit = {
require(newPopulation >= 0)
_population = Math.min(1.0f, newPopulation)
if (population >= 0.90f) {
flags = flags + RealmFlags.Full
} else {
flags = flags - RealmFlags.Full
}
}
/**
* Get the ServerRealmlist packet entry for this realm
* @param charactersCount number of characters
* @return ServerRealmlistEntry for this realm
*/
def toEntry(charactersCount: Int): ServerRealmlistEntry = ServerRealmlistEntry(realmConfig.tpe,
lock = realmConfig.lock,
realmConfig.flags ++ flags,
realmConfig.name,
s"${realmConfig.host}:${realmConfig.port}",
// from experiment in client: 0.9 shows as low, 1.0 as medium, 1.1 as high, thus:
0.8f + Math.ceil(_population * 3).toFloat * 0.1f,
charactersCount,
realmConfig.timeZone,
id)
}
|
SKNZ/SpinaciCore
|
wow/core/src/main/scala/wow/auth/RealmInfo.scala
|
Scala
|
mit
| 1,346 |
package sangria.execution.deferred
import java.util.concurrent.atomic.AtomicInteger
import sangria.ast
import sangria.execution.Executor
import sangria.macros._
import sangria.schema._
import sangria.util.{FutureResultSupport, Pos}
import sangria.util.SimpleGraphQlSupport._
import scala.concurrent.{ExecutionContext, Future}
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec
class FetcherSpec extends AnyWordSpec with Matchers with FutureResultSupport {
case class Product(id: Int, name: String, inCategories: Vector[String])
case class Category(
id: String,
name: String,
children: Seq[String],
products: Vector[Int] = Vector.empty)
case class ColorDeferred(id: String) extends Deferred[String]
object Category {
implicit val hasId = HasId[Category, String](_.id)
}
object Product {
implicit val hasId = HasId[Product, Int](_.id)
}
val prodCat = Relation[Product, String]("product-category", _.inCategories)
val prodComplexCat =
Relation[Product, (Seq[String], Product), String]("product-category-complex", _._1, _._2)
val catProd = Relation[Category, Int]("category-product", _.products)
class Repo {
private val categories = Vector(
Category("1", "Root", Vector("2", "3", "4")),
Category("2", "Cat 2", Vector("5", "6")),
Category("3", "Cat 3", Vector("7", "5", "6")),
Category("4", "Cat 4", Vector.empty, Vector(1, 2, 3)),
Category("5", "Cat 5", Vector.empty, Vector(2, 4)),
Category("6", "Cat 6", Vector.empty, Vector(5, 6, 1)),
Category("7", "Cat 7", Vector.empty, Vector(2, 3)),
Category("8", "Cat 8", Vector("4", "5", "foo!")),
Category("20", "Cat 8", (1 to 8).map(_.toString))
)
private val products = Vector(
Product(1, "Rusty sword", Vector("4", "6")),
Product(2, "Magic belt", Vector("4", "5", "7")),
Product(3, "Health potion", Vector("4", "7")),
Product(4, "Unidentified potion", Vector("5")),
Product(5, "Common boots", Vector("6")),
Product(6, "Golden ring", Vector("6"))
)
def loadCategories(ids: Seq[String])(implicit ec: ExecutionContext): Future[Seq[Category]] =
Future(ids.flatMap(id => categories.find(_.id == id)))
def loadProducts(ids: Seq[Int])(implicit ec: ExecutionContext): Future[Seq[Product]] =
Future(ids.flatMap(id => products.find(_.id == id)))
def loadProductsByCategory(categoryIds: Seq[String])(implicit
ec: ExecutionContext): Future[Seq[Product]] =
Future(products.filter(p => categoryIds.exists(p.inCategories contains _)))
def loadCategoriesByProduct(productIds: Seq[Int])(implicit
ec: ExecutionContext): Future[Seq[Category]] =
Future(categories.filter(c => productIds.exists(c.products contains _)))
def getCategory(id: String)(implicit ec: ExecutionContext) =
Future(categories.find(_.id == id))
def getProduct(id: Int)(implicit ec: ExecutionContext) =
Future(products.find(_.id == id))
}
def properFetcher(implicit ec: ExecutionContext) = {
val defaultCatFetcher = Fetcher.relCaching[Repo, Category, Category, String](
(repo, ids) => repo.loadCategories(ids),
(repo, ids) => repo.loadCategoriesByProduct(ids(catProd)))
val defaultProdFetcher = Fetcher.relCaching[Repo, Product, Product, Int](
(repo, ids) => repo.loadProducts(ids),
(repo, ids) => repo.loadProductsByCategory(ids(prodCat)),
FetcherConfig.caching.maxBatchSize(2))
val complexProdFetcher = Fetcher.relCaching[Repo, Product, (Seq[String], Product), Int](
(repo, ids) => repo.loadProducts(ids),
(repo, ids) =>
repo.loadProductsByCategory(ids(prodComplexCat)).map(_.map(p => p.inCategories -> p)))
val defaultResolver = DeferredResolver.fetchers(defaultProdFetcher, defaultCatFetcher)
def schema(
fetcherCat: Fetcher[Repo, Category, Category, String] = defaultCatFetcher,
fetcherProd: Fetcher[Repo, Product, Product, Int] = defaultProdFetcher) = {
lazy val ProductType: ObjectType[Repo, Product] = ObjectType(
"Product",
() =>
fields(
Field("id", IntType, resolve = c => c.value.id),
Field("name", StringType, resolve = c => c.value.name),
Field(
"categories",
ListType(CategoryType),
resolve = c => fetcherCat.deferSeqOpt(c.value.inCategories)),
Field(
"categoryRel",
CategoryType,
resolve = c => fetcherCat.deferRel(catProd, c.value.id)),
Field(
"categoryRelOpt",
OptionType(CategoryType),
resolve = c => fetcherCat.deferRelOpt(catProd, c.value.id)),
Field(
"categoryRelSeq",
ListType(CategoryType),
resolve = c => fetcherCat.deferRelSeq(catProd, c.value.id))
)
)
lazy val CategoryType: ObjectType[Repo, Category] = ObjectType(
"Category",
() =>
fields(
Field("id", StringType, resolve = c => c.value.id),
Field("name", StringType, resolve = c => c.value.name),
Field("color", StringType, resolve = c => ColorDeferred("red")),
Field("self", CategoryType, resolve = c => c.value),
Field("selfOpt", OptionType(CategoryType), resolve = c => Some(c.value)),
Field("selfFut", CategoryType, resolve = c => Future(c.value)),
Field(
"products",
ListType(ProductType),
resolve = c => fetcherProd.deferSeqOpt(c.value.products)),
Field(
"productRel",
ProductType,
resolve = c => fetcherProd.deferRel(prodCat, c.value.id)),
Field(
"productComplexRel",
ListType(ProductType),
resolve = c => complexProdFetcher.deferRelSeq(prodComplexCat, c.value.id)),
Field(
"productRelOpt",
OptionType(ProductType),
resolve = c => fetcherProd.deferRelOpt(prodCat, c.value.id)),
Field(
"productRelSeq",
ListType(ProductType),
resolve = c => fetcherProd.deferRelSeq(prodCat, c.value.id)),
Field(
"categoryNonOpt",
CategoryType,
arguments = Argument("id", StringType) :: Nil,
resolve = c => fetcherCat.defer(c.arg[String]("id"))),
Field(
"childrenSeq",
ListType(CategoryType),
resolve = c => fetcherCat.deferSeq(c.value.children)),
Field(
"childrenSeqOpt",
ListType(CategoryType),
resolve = c => fetcherCat.deferSeqOpt(c.value.children)),
Field(
"childrenFut",
ListType(CategoryType),
resolve = c => Future.successful(fetcherCat.deferSeq(c.value.children)))
)
)
val QueryType = ObjectType(
"Query",
fields[Repo, Unit](
Field(
"category",
OptionType(CategoryType),
arguments = Argument("id", StringType) :: Nil,
resolve = c => fetcherCat.deferOpt(c.arg[String]("id"))),
Field(
"categoryEager",
OptionType(CategoryType),
arguments = Argument("id", StringType) :: Nil,
resolve = c => c.ctx.getCategory(c.arg[String]("id"))),
Field(
"categoryNonOpt",
CategoryType,
arguments = Argument("id", StringType) :: Nil,
resolve = c => fetcherCat.defer(c.arg[String]("id"))),
Field(
"products",
ListType(ProductType),
arguments = Argument("categoryIds", ListInputType(StringType)) :: Nil,
resolve = c => fetcherProd.deferRelSeqMany(prodCat, c.arg[Seq[String]]("categoryIds"))
),
Field(
"productOpt",
OptionType(ProductType),
arguments = Argument("id", OptionInputType(IntType)) :: Nil,
resolve = c => fetcherProd.deferOpt(c.argOpt[Int]("id"))),
Field(
"productsOptExplicit",
ListType(OptionType(ProductType)),
arguments = Argument("ids", ListInputType(IntType)) :: Nil,
resolve = c => fetcherProd.deferSeqOptExplicit(c.arg[Seq[Int]]("ids"))
),
Field("root", CategoryType, resolve = _ => fetcherCat.defer("1")),
Field("rootFut", CategoryType, resolve = _ => Future.successful(fetcherCat.defer("1")))
)
)
Schema(QueryType)
}
"fetch results in batches and cache results if necessary" in {
val query =
graphql"""
{
c1: category(id: "non-existing") {name}
c3: category(id: "8") {name childrenSeqOpt {id}}
rootFut {
id
name
childrenSeq {
id
name
childrenSeq {
id
name
childrenSeq {
id
name
childrenSeq {
id
name
}
}
}
}
}
}
"""
var fetchedIds = Vector.empty[Seq[String]]
val fetcher =
Fetcher { (repo: Repo, ids: Seq[String]) =>
fetchedIds = fetchedIds :+ ids
repo.loadCategories(ids)
}
var fetchedIdsCached = Vector.empty[Seq[String]]
val fetcherCached =
Fetcher.caching { (repo: Repo, ids: Seq[String]) =>
fetchedIdsCached = fetchedIdsCached :+ ids
repo.loadCategories(ids)
}
val res = Executor
.execute(
schema(fetcher),
query,
new Repo,
deferredResolver = DeferredResolver.fetchers(fetcher))
.await
val resCached = Executor
.execute(
schema(fetcherCached),
query,
new Repo,
deferredResolver = DeferredResolver.fetchers(fetcherCached))
.await
fetchedIds.map(_.sorted) should be(
Vector(
Vector("1", "8", "non-existing"),
Vector("2", "3", "4", "5", "foo!"),
Vector("5", "6", "7")))
fetchedIdsCached.map(_.sorted) should be(
Vector(
Vector("1", "8", "non-existing"),
Vector("2", "3", "4", "5", "foo!"),
Vector("6", "7")))
List(res, resCached).foreach(
_ should be(Map("data" -> Map(
"c1" -> null,
"c3" -> Map(
"name" -> "Cat 8",
"childrenSeqOpt" -> Vector(Map("id" -> "4"), Map("id" -> "5"))),
"rootFut" -> Map(
"id" -> "1",
"name" -> "Root",
"childrenSeq" -> Vector(
Map(
"id" -> "2",
"name" -> "Cat 2",
"childrenSeq" -> Vector(
Map("id" -> "5", "name" -> "Cat 5", "childrenSeq" -> Vector.empty),
Map("id" -> "6", "name" -> "Cat 6", "childrenSeq" -> Vector.empty))
),
Map(
"id" -> "3",
"name" -> "Cat 3",
"childrenSeq" -> Vector(
Map("id" -> "7", "name" -> "Cat 7", "childrenSeq" -> Vector.empty),
Map("id" -> "5", "name" -> "Cat 5", "childrenSeq" -> Vector.empty),
Map("id" -> "6", "name" -> "Cat 6", "childrenSeq" -> Vector.empty)
)
),
Map("id" -> "4", "name" -> "Cat 4", "childrenSeq" -> Vector.empty)
)
)
))))
}
"fetch results with `deferOpt` and option argument" in {
val query =
graphql"""
{
p1: productOpt(id: 1) {id, name}
p2: productOpt {id, name}
p3: productOpt(id: 12345) {id, name}
}
"""
val res =
Executor.execute(schema(), query, new Repo, deferredResolver = defaultResolver).await
res should be(Map(
"data" -> Map("p1" -> Map("id" -> 1, "name" -> "Rusty sword"), "p2" -> null, "p3" -> null)))
}
"fetch results with `deferSeqOptExplicit`" in {
val query =
graphql"""
{
productsOptExplicit(ids: [1, 1001, 2, 3, 3001]) {id, name}
}
"""
Executor
.execute(schema(), query, new Repo, deferredResolver = defaultResolver)
.await should be(
Map(
"data" -> Map(
"productsOptExplicit" -> Vector(
Map("id" -> 1, "name" -> "Rusty sword"),
null,
Map("id" -> 2, "name" -> "Magic belt"),
Map("id" -> 3, "name" -> "Health potion"),
null))))
}
"cache relation results" in {
val query =
graphql"""
{
p1: products(categoryIds: ["4", "7"]) {
categoryRel {
name
products {
categoryRel {
name
products {
categoryRel {
name
}
}
}
}
}
}
}
"""
var fetchedIds = Vector.empty[Seq[String]]
var fetchedRels = Vector.empty[RelationIds[Category]]
val fetcher =
Fetcher.rel(
(repo: Repo, ids: Seq[String]) => {
fetchedIds = fetchedIds :+ ids
repo.loadCategories(ids)
},
(repo: Repo, ids: RelationIds[Category]) => {
fetchedRels = fetchedRels :+ ids
repo.loadCategoriesByProduct(ids(catProd))
}
)
var fetchedIdsCached = Vector.empty[Seq[String]]
var fetchedRelsCached = Vector.empty[RelationIds[Category]]
val fetcherCached =
Fetcher.relCaching(
(repo: Repo, ids: Seq[String]) => {
fetchedIdsCached = fetchedIdsCached :+ ids
repo.loadCategories(ids)
},
(repo: Repo, ids: RelationIds[Category]) => {
fetchedRelsCached = fetchedRelsCached :+ ids
repo.loadCategoriesByProduct(ids(catProd))
}
)
var fetchedRelsOnly = Vector.empty[RelationIds[Category]]
val fetcherRelsOnly =
Fetcher.relOnly { (repo: Repo, ids: RelationIds[Category]) =>
fetchedRelsOnly = fetchedRelsOnly :+ ids
repo.loadCategoriesByProduct(ids(catProd))
}
var fetchedRelsOnlyCached = Vector.empty[RelationIds[Category]]
val fetcherRelsOnlyCached =
Fetcher.relOnlyCaching { (repo: Repo, ids: RelationIds[Category]) =>
fetchedRelsOnlyCached = fetchedRelsOnlyCached :+ ids
repo.loadCategoriesByProduct(ids(catProd))
}
val res = Executor
.execute(
schema(fetcher),
query,
new Repo,
deferredResolver = DeferredResolver.fetchers(fetcher, defaultProdFetcher))
.await
val resCached = Executor
.execute(
schema(fetcherCached),
query,
new Repo,
deferredResolver = DeferredResolver.fetchers(fetcherCached, defaultProdFetcher))
.await
val resRelsOnly = Executor
.execute(
schema(fetcherRelsOnly),
query,
new Repo,
deferredResolver = DeferredResolver.fetchers(fetcherRelsOnly, defaultProdFetcher))
.await
val resRelsOnlyCached = Executor
.execute(
schema(fetcherRelsOnlyCached),
query,
new Repo,
deferredResolver = DeferredResolver.fetchers(fetcherRelsOnlyCached, defaultProdFetcher))
.await
fetchedIds should have size 0
fetchedIdsCached should have size 0
val relsOut = Vector(
RelationIds[Category](Map(catProd -> Vector(1, 2, 3))),
RelationIds[Category](Map(catProd -> Vector(1, 2, 3))),
RelationIds[Category](Map(catProd -> Vector(1, 2, 3)))
)
val relsCachedOut = Vector(RelationIds[Category](Map(catProd -> Vector(1, 2, 3))))
fetchedRels should be(relsOut)
fetchedRelsCached should be(relsCachedOut)
fetchedRelsOnly should be(relsOut)
fetchedRelsOnlyCached should be(relsCachedOut)
res should be(resCached)
resRelsOnly should be(resRelsOnlyCached)
}
"handle complex relations" in {
val query =
graphql"""
{
c1: category(id: "5") {
productComplexRel {
id
}
}
c2: category(id: "6") {
productComplexRel {
name
}
}
}
"""
val res = Executor
.execute(
schema(),
query,
new Repo,
deferredResolver =
DeferredResolver.fetchers(complexProdFetcher, defaultProdFetcher, defaultCatFetcher))
.await
res should be(
Map("data" -> Map(
"c1" -> Map("productComplexRel" -> Vector(Map("id" -> 2), Map("id" -> 4))),
"c2" -> Map("productComplexRel" -> Vector(
Map("name" -> "Rusty sword"),
Map("name" -> "Common boots"),
Map("name" -> "Golden ring")))
)))
}
"should result in error for missing non-optional values" in {
var fetchedIds = Vector.empty[Seq[String]]
val fetcher =
Fetcher { (repo: Repo, ids: Seq[String]) =>
fetchedIds = fetchedIds :+ ids
repo.loadCategories(ids)
}
checkContainsErrors(
schema(fetcher),
(),
"""
{
c1: category(id: "8") {name childrenSeq {id}}
c2: categoryEager(id: "1") {
name
selfOpt {
categoryNonOpt(id: "qwe") {name}
}
}
}
""",
Map("c1" -> null, "c2" -> Map("name" -> "Root", "selfOpt" -> null)),
List(
"Fetcher has not resolved non-optional ID 'foo!'." -> List(Pos(3, 41)),
"Fetcher has not resolved non-optional ID 'qwe'." -> List(Pos(7, 17))),
resolver = DeferredResolver.fetchers(fetcher),
userContext = new Repo
)
fetchedIds should be(Vector(Vector("8", "qwe"), Vector("4", "5", "foo!")))
}
"use fallback `DeferredResolver`" in {
class MyDeferredResolver extends DeferredResolver[Any] {
val callsCount = new AtomicInteger(0)
val valueCount = new AtomicInteger(0)
override val includeDeferredFromField
: Option[(Field[_, _], Vector[ast.Field], Args, Double) => Boolean] =
Some((_, _, _, _) => false)
def resolve(deferred: Vector[Deferred[Any]], ctx: Any, queryState: Any)(implicit
ec: ExecutionContext) = {
callsCount.getAndIncrement()
valueCount.addAndGet(deferred.size)
deferred.map { case ColorDeferred(id) =>
Future.successful(id + "Color")
}
}
}
check(
schema(),
(),
"""
{
c1: category(id: "1") {name childrenSeq {id}}
c2: categoryEager(id: "2") {
color
childrenSeq {name}
}
}
""",
Map(
"data" -> Map(
"c1" -> Map(
"name" -> "Root",
"childrenSeq" -> Vector(Map("id" -> "2"), Map("id" -> "3"), Map("id" -> "4"))),
"c2" -> Map(
"color" -> "redColor",
"childrenSeq" -> Vector(Map("name" -> "Cat 5"), Map("name" -> "Cat 6")))
)),
resolver = DeferredResolver.fetchersWithFallback(
new MyDeferredResolver,
defaultCatFetcher,
defaultProdFetcher),
userContext = new Repo
)
}
"explicit cache should be used in consequent executions" in {
var fetchedIds = Vector.empty[Seq[String]]
val cache = FetcherCache.simple
(1 to 3).foreach { _ =>
val fetcher = Fetcher.caching(
config = FetcherConfig.caching(cache),
fetch = (repo: Repo, ids: Seq[String]) => {
fetchedIds = fetchedIds :+ ids
repo.loadCategories(ids)
})
check(
schema(fetcher),
(),
"""
{
root {
childrenSeq {
childrenSeq {
childrenSeq {
childrenSeq {
name
}
}
}
}
}
}
""",
Map(
"data" -> Map("root" -> Map("childrenSeq" -> Vector(
Map("childrenSeq" -> Vector(
Map("childrenSeq" -> Vector.empty),
Map("childrenSeq" -> Vector.empty))),
Map("childrenSeq" -> Vector(
Map("childrenSeq" -> Vector.empty),
Map("childrenSeq" -> Vector.empty),
Map("childrenSeq" -> Vector.empty))),
Map("childrenSeq" -> Vector.empty)
)))),
resolver = DeferredResolver.fetchers(fetcher),
userContext = new Repo
)
}
fetchedIds.map(_.sorted) should be(
Vector(Vector("1"), Vector("2", "3", "4"), Vector("5", "6", "7")))
}
"clearId should remove entry from cache" in {
val cache = new SimpleFetcherCache() {
override def cacheKey(id: Any): Any = id.toString
}
cache.update(1, "one")
cache.get(1) should be(Some("one"))
cache.clearId(1)
cache.get(1) should be(None)
}
"support multiple fetchers" in {
var fetchedCatIds = Vector.empty[Seq[String]]
val fetcherCat =
Fetcher { (repo: Repo, ids: Seq[String]) =>
fetchedCatIds = fetchedCatIds :+ ids
repo.loadCategories(ids)
}
var fetchedProdIds = Vector.empty[Seq[Int]]
val fetcherProd =
Fetcher { (repo: Repo, ids: Seq[Int]) =>
fetchedProdIds = fetchedProdIds :+ ids
repo.loadProducts(ids)
}
check(
schema(fetcherCat, fetcherProd),
(),
"""
{
root {
...Cat
childrenSeq {
...Cat
childrenSeq {
...Cat
}
}
}
}
fragment Cat on Category {
name
products {
name
categories {
name
}
}
}
""",
Map(
"data" -> Map("root" -> Map(
"name" -> "Root",
"products" -> Vector.empty,
"childrenSeq" -> Vector(
Map(
"name" -> "Cat 2",
"products" -> Vector.empty,
"childrenSeq" -> Vector(
Map(
"name" -> "Cat 5",
"products" -> Vector(
Map(
"name" -> "Magic belt",
"categories" -> Vector(
Map("name" -> "Cat 4"),
Map("name" -> "Cat 5"),
Map("name" -> "Cat 7"))),
Map(
"name" -> "Unidentified potion",
"categories" -> Vector(Map("name" -> "Cat 5")))
)
),
Map(
"name" -> "Cat 6",
"products" -> Vector(
Map("name" -> "Common boots", "categories" -> Vector(Map("name" -> "Cat 6"))),
Map("name" -> "Golden ring", "categories" -> Vector(Map("name" -> "Cat 6"))),
Map(
"name" -> "Rusty sword",
"categories" -> Vector(Map("name" -> "Cat 4"), Map("name" -> "Cat 6")))
)
)
)
),
Map(
"name" -> "Cat 3",
"products" -> Vector.empty,
"childrenSeq" -> Vector(
Map(
"name" -> "Cat 7",
"products" -> Vector(
Map(
"name" -> "Magic belt",
"categories" -> Vector(
Map("name" -> "Cat 4"),
Map("name" -> "Cat 5"),
Map("name" -> "Cat 7"))),
Map(
"name" -> "Health potion",
"categories" -> Vector(Map("name" -> "Cat 4"), Map("name" -> "Cat 7")))
)
),
Map(
"name" -> "Cat 5",
"products" -> Vector(
Map(
"name" -> "Magic belt",
"categories" -> Vector(
Map("name" -> "Cat 4"),
Map("name" -> "Cat 5"),
Map("name" -> "Cat 7"))),
Map(
"name" -> "Unidentified potion",
"categories" -> Vector(Map("name" -> "Cat 5")))
)
),
Map(
"name" -> "Cat 6",
"products" -> Vector(
Map("name" -> "Common boots", "categories" -> Vector(Map("name" -> "Cat 6"))),
Map("name" -> "Golden ring", "categories" -> Vector(Map("name" -> "Cat 6"))),
Map(
"name" -> "Rusty sword",
"categories" -> Vector(Map("name" -> "Cat 4"), Map("name" -> "Cat 6")))
)
)
)
),
Map(
"name" -> "Cat 4",
"products" -> Vector(
Map(
"name" -> "Rusty sword",
"categories" -> Vector(Map("name" -> "Cat 4"), Map("name" -> "Cat 6"))),
Map(
"name" -> "Magic belt",
"categories" -> Vector(
Map("name" -> "Cat 4"),
Map("name" -> "Cat 5"),
Map("name" -> "Cat 7"))),
Map(
"name" -> "Health potion",
"categories" -> Vector(Map("name" -> "Cat 4"), Map("name" -> "Cat 7")))
),
"childrenSeq" -> Vector.empty
)
)
))),
resolver = DeferredResolver.fetchers(fetcherCat, fetcherProd),
userContext = new Repo
)
fetchedCatIds.map(_.sorted) should be(
Vector(
Vector("1"),
Vector("2", "3", "4"),
Vector("5", "6", "7"),
Vector("4", "5", "6", "7"),
Vector("4", "5", "6", "7")))
fetchedProdIds.map(_.sorted) should be(Vector(Vector(1, 2, 3), Vector(1, 2, 3, 4, 5, 6)))
}
"support a single relation" in check(
schema(),
(),
"""
{
category(id: "4") {
productRel {
name
categoryRel {
name
}
}
}
}
""",
Map(
"data" -> Map("category" -> Map(
"productRel" -> Map("name" -> "Rusty sword", "categoryRel" -> Map("name" -> "Cat 4"))))),
resolver = defaultResolver,
userContext = new Repo
)
"single relation should produce an error if value is not resolved" in checkContainsErrors(
schema(),
(),
"""
{
category(id: "1") {
productRel {
name
}
}
}
""",
Map("category" -> null),
List(
"Fetcher has not resolved non-optional relation ID '1' for relation 'SimpleRelation(product-category)'." -> List(
Pos(4, 13))),
resolver = defaultResolver,
userContext = new Repo
)
"support a optional and list relations" in check(
schema(),
(),
"""
{
c1: category(id: "1") {
productRelOpt {
name
}
productRelSeq {
name
}
}
c2: category(id: "4") {
productRelOpt {
name
categoryRelOpt {
name
}
}
productRelSeq {
name
categoryRelSeq {
name
}
}
}
}
""",
Map(
"data" -> Map(
"c1" -> Map("productRelOpt" -> null, "productRelSeq" -> Vector.empty),
"c2" -> Map(
"productRelOpt" -> Map(
"name" -> "Rusty sword",
"categoryRelOpt" -> Map("name" -> "Cat 4")),
"productRelSeq" -> Vector(
Map(
"name" -> "Rusty sword",
"categoryRelSeq" -> Vector(Map("name" -> "Cat 4"), Map("name" -> "Cat 6"))),
Map(
"name" -> "Magic belt",
"categoryRelSeq" -> Vector(
Map("name" -> "Cat 4"),
Map("name" -> "Cat 5"),
Map("name" -> "Cat 7"))),
Map(
"name" -> "Health potion",
"categoryRelSeq" -> Vector(Map("name" -> "Cat 4"), Map("name" -> "Cat 7")))
)
)
)),
resolver = defaultResolver,
userContext = new Repo
)
"support multiple relations" in check(
schema(),
(),
"""
{
products(categoryIds: ["1", "2", "5", "6", "4"]) {
id, name
}
}
""",
Map(
"data" -> Map("products" -> Vector(
Map("id" -> 2, "name" -> "Magic belt"),
Map("id" -> 4, "name" -> "Unidentified potion"),
Map("id" -> 1, "name" -> "Rusty sword"),
Map("id" -> 5, "name" -> "Common boots"),
Map("id" -> 6, "name" -> "Golden ring"),
Map("id" -> 3, "name" -> "Health potion")
))),
resolver = defaultResolver,
userContext = new Repo
)
"support manual cache updates" in {
var fetchedProdIds = Vector.empty[Seq[Int]]
val fetcherProd =
Fetcher.cachingWithContext[Repo, Product, Int] { (c, ids) =>
fetchedProdIds = fetchedProdIds :+ ids
c.ctx.loadProducts(ids)
}
val fetcherCat =
Fetcher.cachingWithContext[Repo, Category, String] { (c, ids) =>
c.ctx.loadCategories(ids).map { categories =>
c.cacheFor(fetcherProd).foreach { productCache =>
productCache.update(4, Product(4, "Manually Cached", categories.map(_.id).toVector))
}
categories
}
}
check(
schema(fetcherCat, fetcherProd),
(),
"""
{
category(id: "5") {
name
products {
name
}
}
}
""",
Map(
"data" -> Map("category" -> Map(
"name" -> "Cat 5",
"products" -> Vector(Map("name" -> "Magic belt"), Map("name" -> "Manually Cached"))))),
resolver = DeferredResolver.fetchers(fetcherCat, fetcherProd),
userContext = new Repo
)
fetchedProdIds.map(_.sorted) should be(Vector(Vector(2)))
}
}
"Fetcher" when {
"using standard execution context" should {
behave.like(properFetcher(ExecutionContext.Implicits.global))
}
"using sync execution context" should {
behave.like(properFetcher(sync.executionContext))
}
}
}
|
sangria-graphql/sangria
|
modules/core/src/test/scala/sangria/execution/deferred/FetcherSpec.scala
|
Scala
|
apache-2.0
| 32,218 |
package kafka.common
import kafka.cluster.{Partition, Replica}
import kafka.utils.Json
import org.apache.kafka.common.TopicPartition
/**
* 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.
*/
/**
* Convenience case class since (topic, partition) pairs are ubiquitous.
*/
case class TopicAndPartition(topic: String, partition: Int) {
def this(tuple: (String, Int)) = this(tuple._1, tuple._2)
def this(partition: Partition) = this(partition.topic, partition.partitionId)
def this(topicPartition: TopicPartition) = this(topicPartition.topic, topicPartition.partition)
def this(replica: Replica) = this(replica.topicPartition)
def asTuple = (topic, partition)
override def toString = "[%s,%d]".format(topic, partition)
}
|
wangcy6/storm_app
|
frame/kafka-0.11.0/kafka-0.11.0.1-src/core/src/main/scala/kafka/common/TopicAndPartition.scala
|
Scala
|
apache-2.0
| 1,483 |
/*
* 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.plan.rules.logical
import org.apache.flink.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.planner.plan.optimize.program.{BatchOptimizeContext, FlinkChainedProgram, FlinkHepRuleSetProgramBuilder, HEP_RULES_EXECUTION_TYPE}
import org.apache.flink.table.planner.utils.TableTestBase
import org.apache.calcite.plan.hep.HepMatchOrder
import org.apache.calcite.tools.RuleSets
import org.junit.{Before, Test}
/**
* Test for [[RewriteMinusAllRule]].
*/
class RewriteMinusAllRuleTest extends TableTestBase {
private val util = batchTestUtil()
@Before
def setup(): Unit = {
val programs = new FlinkChainedProgram[BatchOptimizeContext]()
programs.addLast(
"rules",
FlinkHepRuleSetProgramBuilder.newBuilder
.setHepRulesExecutionType(HEP_RULES_EXECUTION_TYPE.RULE_SEQUENCE)
.setHepMatchOrder(HepMatchOrder.BOTTOM_UP)
.add(RuleSets.ofList(RewriteMinusAllRule.INSTANCE))
.build()
)
util.replaceBatchProgram(programs)
util.addTableSource[(Int, Long, String)]("T1", 'a, 'b, 'c)
util.addTableSource[(Int, Long, String)]("T2", 'd, 'e, 'f)
}
@Test
def testExceptAll(): Unit = {
util.verifyRelPlan("SELECT c FROM T1 EXCEPT ALL SELECT f FROM T2")
}
@Test
def testExceptAllWithFilter(): Unit = {
util.verifyRelPlan("SELECT c FROM (SELECT * FROM T1 EXCEPT ALL (SELECT * FROM T2)) WHERE b < 2")
}
@Test
def testExceptAllLeftIsEmpty(): Unit = {
util.verifyRelPlan("SELECT c FROM T1 WHERE 1=0 EXCEPT ALL SELECT f FROM T2")
}
@Test
def testExceptAllRightIsEmpty(): Unit = {
util.verifyRelPlan("SELECT c FROM T1 EXCEPT ALL SELECT f FROM T2 WHERE 1=0")
}
}
|
apache/flink
|
flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/planner/plan/rules/logical/RewriteMinusAllRuleTest.scala
|
Scala
|
apache-2.0
| 2,533 |
package com.hyenawarrior.OldNorseGrammar.grammar.adjectival
import com.hyenawarrior.OldNorseGrammar.grammar.adjectival.enums.AdjectiveType
import com.hyenawarrior.OldNorseGrammar.grammar.adjectival.enums.AdjectiveType._
import com.hyenawarrior.OldNorseGrammar.grammar.enums.Case._
import com.hyenawarrior.OldNorseGrammar.grammar.enums.GNumber._
import com.hyenawarrior.OldNorseGrammar.grammar.enums.Gender._
import com.hyenawarrior.OldNorseGrammar.grammar.enums.{Case, GNumber, Gender}
import scala.language.implicitConversions
/**
* Created by HyenaWarrior on 2018.06.11..
*/
object core {
case class AdjectiveFormType(adjType: AdjectiveType, number: GNumber, gender: Gender, caze: Case) {
override def toString: String = Seq(number, caze, gender, adjType)
.map(e => ABBREVATIONS_OF.getOrElse(e, s"ERROR:${e.toString}"))
.mkString(" ")
}
implicit def toTuple(adjForm: AdjectiveFormType): (AdjectiveType, GNumber, Gender, Case) = (adjForm.adjType, adjForm.number, adjForm.gender, adjForm.caze)
implicit def fromTuple(tuple: (AdjectiveType, GNumber, Gender, Case)): AdjectiveFormType = AdjectiveFormType(tuple._1, tuple._2, tuple._3, tuple._4)
private val ABBREVATIONS_OF = Map[Any, String](
//
POSITIVE_INDEFINITE -> "INDF",
POSITIVE_DEFINITE -> "DEF",
COMPARATIVE -> "COMP",
SUPERLATIVE_INDEFINITE -> "SUPL INDEF",
SUPERLATIVE_DEFINITE -> "SUPL DEF",
DETERMINERS -> "DET",
// numbers
SINGULAR -> "SG",
PLURAL -> "PL",
// genders
MASCULINE -> "M",
FEMININE -> "F",
NEUTER -> "N",
// cases
NOMINATIVE -> "NOM",
ACCUSATIVE -> "ACC",
DATIVE -> "DAT",
GENITIVE -> "GEN"
)
}
|
HyenaSoftware/IG-Dictionary
|
OldNorseGrammarEngine/src/main/scala/com/hyenawarrior/OldNorseGrammar/grammar/adjectival/core.scala
|
Scala
|
lgpl-3.0
| 1,697 |
/*
* Copyright 2001-2014 Artima, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scalatest
import scala.xml.{Node, Text, NodeSeq}
class StreamlinedXmlNormMethodsSpec extends FunSpec with Matchers with StreamlinedXmlNormMethods {
describe("Xml Normalization of Elems") {
it("should leave already-normalized XML alone") {
<summer></summer>.norm == <summer></summer> shouldBe true
}
it("should zap text that is only whitespace") {
<summer> </summer>.norm == <summer></summer> shouldBe true
<summer>
</summer>.norm == <summer></summer> shouldBe true
<summer>
<day></day>
</summer>.norm == <summer><day></day></summer> shouldBe true
<summer><day></day></summer> ==
<summer>
<day></day>
</summer>.norm shouldBe true
<summer><day>Dude!</day></summer> ==
<summer>
<day>
Dude!
</day>
</summer>.norm shouldBe true
<div>{Text("My name is ")}{Text("Harry")}</div>.norm shouldBe <div>My name is Harry</div>
}
}
describe("Xml Normalization of Nodes") {
it("should leave already-normalized XML alone") {
(<summer></summer>: Node).norm == <summer></summer> shouldBe true
(Text("Bla"): Node).norm shouldBe Text("Bla")
}
it("should zap text that is only whitespace, unless it is already a Text") {
(<summer> </summer>.norm: Node) == <summer></summer> shouldBe true
(<summer>
</summer>.norm: Node) == <summer></summer> shouldBe true
(<summer>
<day></day>
</summer>.norm: Node) == <summer><day></day></summer> shouldBe true
<summer><day></day></summer> ==
(<summer>
<day></day>
</summer>.norm: Node) shouldBe true
<summer><day>Dude!</day></summer> ==
(<summer>
<day>
Dude!
</day>
</summer>.norm: Node) shouldBe true
(Text(" "): Node).norm shouldBe Text(" ")
(<div>{Text("My name is ")}{Text("Harry")}</div>: Node).norm shouldBe <div>My name is Harry</div>
}
}
describe("Xml Normalization of NodeSeq") {
it("should leave already-normalized XML alone") {
(<summer></summer>: NodeSeq).norm == <summer></summer> shouldBe true
(Text("Bla"): NodeSeq).norm shouldBe Text("Bla")
}
it("should zap text that is only whitespace, unless it is already a Text") {
(<summer> </summer>.norm: NodeSeq) == <summer></summer> shouldBe true
(<summer>
</summer>.norm: NodeSeq) == <summer></summer> shouldBe true
(<summer>
<day></day>
</summer>.norm: NodeSeq) == <summer><day></day></summer> shouldBe true
<summer><day></day></summer> ==
(<summer>
<day></day>
</summer>.norm: NodeSeq) shouldBe true
<summer><day>Dude!</day></summer> ==
(<summer>
<day>
Dude!
</day>
</summer>.norm: NodeSeq) shouldBe true
(Text(" "): NodeSeq).norm shouldBe Text(" ")
(<div>{Text("My name is ")}{Text("Harry")}</div>: NodeSeq).norm shouldBe <div>My name is Harry</div>
}
}
}
|
dotty-staging/scalatest
|
scalatest-test/src/test/scala/org/scalatest/StreamlinedXmlNormMethodsSpec.scala
|
Scala
|
apache-2.0
| 3,657 |
package org.holmesprocessing.totem.types
import org.holmesprocessing.totem.util.DownloadSettings
/**
* Create() case class. Used between the ConsumerActor and the WorkGroup.
* @param config: DownloadSettings => The configuration options for downloading an object
* @param key: Long => The message key associated with this work.
* @param primaryURI: String => The primary URL for downloading the target resource
* @param secondaryURI: String => The secondary URL for downloading the target resource
* @param value: WorkState => The state of the Job, and component work at time of creation
*
* @constructor Generate a Create message. This is used to initiate the creation of a WorkActor
*
*/
case class Create(key: Long, download: Boolean, primaryURI: String, secondaryURI: String, tags: List[String], value: WorkState, config: DownloadSettings)
/**
* Result case class. Used between the WorkActor and the ProducerActor
* @param filename: String => The filename representing the target of this Job
* @param result: WorkResult => The WorkResult representing the end state of the Job
*
* @constructor Generate a Result message. This is used to transmit results to the Producer and from there, to the queueing backbone
*
*/
case class Result(filename: String, result: WorkResult)
/**
* ResultPackage case class. A package of results for transmission. The various filehashes are used for secondary aggregation against
* the target processing file, that information is lost due to the UUID usage in the temporary filestore.
* @param filename: String => The filename representing the target of this Job
* @param results: Iterable[WorkResult] => An Iterable representing the WorkResults to be transmitted
* @param tags: List[String] => A list of tags for the results
* @param MD5: String => MD5 hash of the target file.
* @param SHA1: String => SHA1 hash of the target file.
* @param SHA256: String => SHA256 hash of the target file.
*
* @constructor Generate a ResultPackage message. This is for multiple WorkResult transfers.
*
*/
case class ResultPackage(filename: String, results: Iterable[WorkResult], tags: List[String], MD5: String, SHA1: String, SHA256: String)
object WorkState {
def create(filename: String, hashfilename: String, workToDo: List[TaskedWork], results: List[WorkResult] = List[WorkResult](), attempts: Int): WorkState = {
WorkState(filename, hashfilename, workToDo, 0, 0, results, attempts)
}
}
/**
* WorkState case class. A representation of the current state of a given Job. This can be used to merge Jobs, or transfer overall Job state.
* @param filename: String => The filename representing the target of this Job.
* @param hashfilename: String => The hashed filename representing the target of the Job.
* @param workToDo: List[TaskedWork] => A list of all TaskedWork elements, which are the component Work elements
* @param created: Int => The time this work was created.
* @param lastEdited: Int => The last time this work had an altered state.
* @param results: List[WorkResult] => A list of the WorkResults that have been generated.
* @param attempts: Int => The number of times this Job has been attempted across all executors.
* @constructor Generate a WorkState message.
*
*/
case class WorkState(
filename: String,
hashfilename: String,
workToDo: List[TaskedWork],
created: Int = 0,
lastEdited: Int = 0,
results: List[WorkResult] = List[WorkResult](),
attempts: Int = 0
) {
def isComplete: Boolean = {
workToDo.size == results.size
}
def +(that: WorkResult): WorkState = {
new WorkState(
filename = this.filename,
hashfilename = this.hashfilename,
workToDo = this.workToDo,
created = this.created,
lastEdited = 1,
results = this.results :+ that,
attempts = this.attempts
)
}
}
|
webstergd/Holmes-Totem
|
src/main/scala/org/holmesprocessing/totem/types/CommandTypes.scala
|
Scala
|
apache-2.0
| 3,997 |
package battle.classes
object Fighter extends GladiatorClass {
attack + 1
hitpoints + 5
}
|
bbalser/gladiator-actors
|
src/main/scala/battle/classes/Fighter.scala
|
Scala
|
cc0-1.0
| 97 |
package com.github.gdefacci.raz
import shapeless._
trait ToPathCodec[H, TD, TE, S <: PathPosition, E <: PathPosition] {
def apply(h: H): PathCodec[TD, TE, S, E]
}
object ToPathCodec {
implicit def fromDecoderAndEncoder[H <: HList, TD, TE, S <: PathPosition, E <: PathPosition](
implicit topd: ToPathDecoder[H, TD, S, E],
tope: ToPathEncoder[H, TE, S, E]) =
new ToPathCodec[H, TD, TE, S, E] {
def apply(h: H) = PathCodec(topd(h), tope(h))
}
implicit def pathCodecIdentity[TD, TE, S <: PathPosition, E <: PathPosition] =
new ToPathCodec[PathCodec[TD, TE, S, E], TD, TE, S, E] {
def apply(h: PathCodec[TD, TE, S, E]): PathCodec[TD, TE, S, E] = h
}
implicit def fromPathConverter[TD, TE, TU, S <: PathPosition, E <: PathPosition] =
new ToPathCodec[PathConverter[TD, TE, TU, S, E], TD, TE, S, E] {
def apply(h: PathConverter[TD, TE, TU, S, E]): PathCodec[TD, TE, S, E] = h.toCodec
}
}
|
gdefacci/raz
|
raz/src/main/scala/com/github/gdefacci/raz/ToPathCodec.scala
|
Scala
|
mit
| 946 |
class Foo(a: Foo#A) {
type A = Int
}
|
som-snytt/dotty
|
tests/pos/i2949.scala
|
Scala
|
apache-2.0
| 39 |
/*
* Copyright (c) 2014 Roberto Tyley
*
* This file is part of 'scala-textmatching'.
*
* scala-textmatching 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.
*
* scala-textmatching 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.madgag.textmatching
import util.matching.Regex
import com.madgag.globs.openjdk.Globs
import java.util.regex.Pattern
object TextMatcher {
private val allPrefixes = TextMatcherTypes.all.keys mkString ("|")
val prefixedExpression = s"($allPrefixes):(.*)".r
def apply(possiblyPrefixedExpr: String, defaultType: TextMatcherType = Literal): TextMatcher = possiblyPrefixedExpr match {
case prefixedExpression(typ, expr) => TextMatcher(TextMatcherTypes.all(typ), expr)
case unprefixedExpression => TextMatcher(defaultType, unprefixedExpression)
}
}
case class TextMatcher(typ: TextMatcherType, expression: String) extends (String => Boolean) {
lazy val r = typ.regexFor(expression)
override def apply(s: String) = r.matches(s)
lazy override val toString = s"${typ.expressionPrefix}:<$expression>"
}
object TextMatcherTypes {
val all = Seq(Glob, Literal, Reg).map(rs => rs.expressionPrefix -> rs).toMap
}
sealed trait TextMatcherType {
val expressionPrefix: String
def apply(expression: String) = TextMatcher(this, expression)
def regexFor(expression: String): Regex
def implicitReplacementTextEscaping(replacementText: String) = replacementText
}
object Glob extends TextMatcherType {
val expressionPrefix = "glob"
def regexFor(expression: String) = Globs.toUnixRegexPattern(expression).r
}
object Literal extends TextMatcherType {
val expressionPrefix = "literal"
def regexFor(expression: String) = Pattern.quote(expression).r
override def implicitReplacementTextEscaping(replacementText: String) = Regex.quoteReplacement(replacementText)
}
object Reg extends TextMatcherType {
val expressionPrefix = "regex"
def regexFor(expression: String) = expression.r
}
|
rtyley/scala-textmatching
|
src/main/scala/com/madgag/textmatching/TextMatcherType.scala
|
Scala
|
gpl-3.0
| 2,486 |
package com.twitter.finatra.thrift.tests
import com.twitter.converter.thriftscala.Converter
import com.twitter.converter.thriftscala.Converter.Uppercase
import com.twitter.finagle.{Filter, Service}
import com.twitter.finatra.thrift.{Controller, _}
import com.twitter.finatra.thrift.filters.{AccessLoggingFilter, ExceptionMappingFilter, StatsFilter}
import com.twitter.finatra.thrift.routing.ThriftRouter
import com.twitter.finatra.thrift.tests.EmbeddedThriftServerControllerFeatureTest._
import com.twitter.inject.server.FeatureTest
import com.twitter.io.Buf
import com.twitter.scrooge
import com.twitter.util.Future
object EmbeddedThriftServerControllerFeatureTest {
class ConverterControllerServer extends ThriftServer {
override def configureThrift(router: ThriftRouter): Unit = {
router
.filter(classOf[AccessLoggingFilter])
.filter[StatsFilter]
.filter[ExceptionMappingFilter]
.add[ConverterController]
}
}
class ConverterController extends Controller with Converter.BaseServiceIface {
import com.twitter.converter.thriftscala.Converter._
val uppercase = handle(Uppercase) { args: Uppercase.Args =>
if (args.msg == "fail")
Future.exception(new Exception("oops"))
else
Future.value(args.msg.toUpperCase)
}
val moreThanTwentyTwoArgs = handle(MoreThanTwentyTwoArgs) { _: MoreThanTwentyTwoArgs.Args =>
Future.value("foo")
}
}
}
class EmbeddedThriftServerControllerFeatureTest extends FeatureTest {
override val server =
new EmbeddedThriftServer(new ConverterControllerServer, disableTestLogging = true)
/* Higher-kinded interface type */
val client123: Converter.MethodPerEndpoint =
server.thriftClient[Converter.MethodPerEndpoint](clientId = "client123")
/* Method-Per-Endpoint type: https://twitter.github.io/scrooge/Finagle.html#id1 */
val methodPerEndpointClient123: Converter.MethodPerEndpoint =
server.thriftClient[Converter.MethodPerEndpoint](clientId = "client123")
/* Service-Per-Endpoint type: https://twitter.github.io/scrooge/Finagle.html#id2 */
val servicePerEndpoint123: Converter.ServicePerEndpoint =
server.servicePerEndpoint[Converter.ServicePerEndpoint](clientId = "client123")
/* Req/Rep Service-Per-Endpoint type: https://twitter.github.io/scrooge/Finagle.html#id3 */
val reqRepServicePerEndpoint123: Converter.ReqRepServicePerEndpoint =
server.servicePerEndpoint[Converter.ReqRepServicePerEndpoint](clientId = "client123")
test("success") {
await(client123.uppercase("Hi")) should equal("HI")
await(methodPerEndpointClient123.uppercase("Hi")) should equal("HI")
val filter = new Filter[
Converter.Uppercase.Args,
Converter.Uppercase.SuccessType,
Converter.Uppercase.Args,
Converter.Uppercase.SuccessType
] {
override def apply(
request: Uppercase.Args,
service: Service[Uppercase.Args, String]
): Future[String] = {
if (request.msg == "hello") {
service(Converter.Uppercase.Args("goodbye"))
} else service(request)
}
}
val service = filter.andThen(servicePerEndpoint123.uppercase)
await(service(Converter.Uppercase.Args("hello"))) should equal("GOODBYE")
val filter2 =
new Filter[scrooge.Request[Converter.Uppercase.Args], scrooge.Response[
Converter.Uppercase.SuccessType
], scrooge.Request[Converter.Uppercase.Args], scrooge.Response[
Converter.Uppercase.SuccessType
]] {
override def apply(
request: scrooge.Request[Converter.Uppercase.Args],
service: Service[scrooge.Request[Converter.Uppercase.Args], scrooge.Response[
Converter.Uppercase.SuccessType
]]
): Future[scrooge.Response[Converter.Uppercase.SuccessType]] = {
val filteredRequest: scrooge.Request[Converter.Uppercase.Args] =
scrooge.Request(Map("com.twitter.test.header" -> Seq(Buf.Utf8("foo"))), request.args)
service(filteredRequest)
}
}
val service2 = filter2.andThen(reqRepServicePerEndpoint123.uppercase)
await(service2(scrooge.Request(Converter.Uppercase.Args("hello")))).value should equal("HELLO")
}
test("failure") {
val e = assertFailedFuture[Exception] {
client123.uppercase("fail")
}
e.getMessage should include("oops")
}
test("more than 22 args") {
await(
client123.moreThanTwentyTwoArgs(
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
"eleven",
"twelve",
"thirteen",
"fourteen",
"fifteen",
"sixteen",
"seventeen",
"eighteen",
"nineteen",
"twenty",
"twentyone",
"twentytwo",
"twentythree"
)
) should equal("foo")
}
}
|
twitter/finatra
|
thrift/src/test/scala/com/twitter/finatra/thrift/tests/EmbeddedThriftServerControllerFeatureTest.scala
|
Scala
|
apache-2.0
| 4,904 |
package org.scalatest.examples.wordspec.oneargtest
import org.scalatest.fixture
import java.io._
class ExampleSpec extends fixture.WordSpec {
case class FixtureParam(file: File, writer: FileWriter)
def withFixture(test: OneArgTest) = {
// create the fixture
val file = File.createTempFile("hello", "world")
val writer = new FileWriter(file)
val theFixture = FixtureParam(file, writer)
try {
writer.write("ScalaTest is ") // set up the fixture
withFixture(test.toNoArgTest(theFixture)) // "loan" the fixture to the test
}
finally writer.close() // clean up the fixture
}
"Testing" should {
"be easy" in { f =>
f.writer.write("easy!")
f.writer.flush()
assert(f.file.length === 18)
}
"be fun" in { f =>
f.writer.write("fun!")
f.writer.flush()
assert(f.file.length === 17)
}
}
}
|
svn2github/scalatest
|
examples/src/main/scala/org/scalatest/examples/wordspec/oneargtest/ExampleSpec.scala
|
Scala
|
apache-2.0
| 886 |
/*
* 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 org.apache.spark.{SparkConf, SparkFunSuite}
import org.apache.spark.sql.catalyst.expressions.{GenericInternalRow, SpecificInternalRow}
import org.apache.spark.sql.test.SharedSparkSession
import org.apache.spark.sql.types._
import org.apache.spark.unsafe.types.UTF8String
class RowSuite extends SparkFunSuite with SharedSparkSession {
import testImplicits._
override def sparkConf: SparkConf =
super.sparkConf
.setAppName("test")
.set("spark.sql.parquet.columnarReaderBatchSize", "4096")
.set("spark.sql.sources.useV1SourceList", "avro")
.set("spark.sql.extensions", "com.intel.oap.ColumnarPlugin")
.set("spark.sql.execution.arrow.maxRecordsPerBatch", "4096")
//.set("spark.shuffle.manager", "org.apache.spark.shuffle.sort.ColumnarShuffleManager")
.set("spark.memory.offHeap.enabled", "true")
.set("spark.memory.offHeap.size", "50m")
.set("spark.sql.join.preferSortMergeJoin", "false")
.set("spark.sql.columnar.codegen.hashAggregate", "false")
.set("spark.oap.sql.columnar.wholestagecodegen", "false")
.set("spark.sql.columnar.window", "false")
.set("spark.unsafe.exceptionOnMemoryLeak", "false")
//.set("spark.sql.columnar.tmp_dir", "/codegen/nativesql/")
.set("spark.sql.columnar.sort.broadcastJoin", "true")
.set("spark.oap.sql.columnar.preferColumnar", "true")
test("create row") {
val expected = new GenericInternalRow(4)
expected.setInt(0, 2147483647)
expected.update(1, UTF8String.fromString("this is a string"))
expected.setBoolean(2, false)
expected.setNullAt(3)
val actual1 = Row(2147483647, "this is a string", false, null)
assert(expected.numFields === actual1.size)
assert(expected.getInt(0) === actual1.getInt(0))
assert(expected.getString(1) === actual1.getString(1))
assert(expected.getBoolean(2) === actual1.getBoolean(2))
assert(expected.isNullAt(3) === actual1.isNullAt(3))
val actual2 = Row.fromSeq(Seq(2147483647, "this is a string", false, null))
assert(expected.numFields === actual2.size)
assert(expected.getInt(0) === actual2.getInt(0))
assert(expected.getString(1) === actual2.getString(1))
assert(expected.getBoolean(2) === actual2.getBoolean(2))
assert(expected.isNullAt(3) === actual2.isNullAt(3))
}
test("SpecificMutableRow.update with null") {
val row = new SpecificInternalRow(Seq(IntegerType))
row(0) = null
assert(row.isNullAt(0))
}
ignore("get values by field name on Row created via .toDF") {
val row = Seq((1, Seq(1))).toDF("a", "b").first()
assert(row.getAs[Int]("a") === 1)
assert(row.getAs[Seq[Int]]("b") === Seq(1))
intercept[IllegalArgumentException]{
row.getAs[Int]("c")
}
}
test("float NaN == NaN") {
val r1 = Row(Float.NaN)
val r2 = Row(Float.NaN)
assert(r1 === r2)
}
test("double NaN == NaN") {
val r1 = Row(Double.NaN)
val r2 = Row(Double.NaN)
assert(r1 === r2)
}
test("equals and hashCode") {
val r1 = Row("Hello")
val r2 = Row("Hello")
assert(r1 === r2)
assert(r1.hashCode() === r2.hashCode())
val r3 = Row("World")
assert(r3.hashCode() != r1.hashCode())
}
test("toString") {
val r1 = Row(2147483647, 21474.8364, (-5).toShort, "this is a string", true, null)
assert(r1.toString == "[2147483647,21474.8364,-5,this is a string,true,null]")
val r2 = Row(null, Int.MinValue, Double.NaN, Short.MaxValue, "", false)
assert(r2.toString == "[null,-2147483648,NaN,32767,,false]")
val tsString = "2019-05-01 17:30:12.0"
val dtString = "2019-05-01"
val r3 = Row(
r1,
Seq(1, 2, 3),
Map(1 -> "a", 2 -> "b"),
java.sql.Timestamp.valueOf(tsString),
java.sql.Date.valueOf(dtString),
BigDecimal("1234567890.1234567890"),
(-1).toByte)
assert(r3.toString == "[[2147483647,21474.8364,-5,this is a string,true,null],List(1, 2, 3)," +
s"Map(1 -> a, 2 -> b),$tsString,$dtString,1234567890.1234567890,-1]")
val empty = Row()
assert(empty.toString == "[]")
}
}
|
Intel-bigdata/OAP
|
oap-native-sql/core/src/test/scala/org/apache/spark/sql/RowSuite.scala
|
Scala
|
apache-2.0
| 4,908 |
import sbt._
import Keys._
object MultiPublishTest extends Build
{
override lazy val settings = super.settings ++ Seq(
organization := "A",
version := "1.0",
ivyPaths <<= baseDirectory( dir => new IvyPaths(dir, Some(dir / "ivy" / "cache")) ),
externalResolvers <<= baseDirectory map { base => Resolver.file("local", base / "ivy" / "local" asFile)(Resolver.ivyStylePatterns) :: Nil }
)
lazy val root = Project("root", file(".")) settings(
name := "Retrieve Test",
mavenStyle,
libraryDependencies <<= publishMavenStyle { style => if(style) mavenStyleDependencies else ivyStyleDependencies }
)
lazy val mavenStyle = publishMavenStyle <<= baseDirectory { base => (base / "mavenStyle") exists }
def ivyStyleDependencies = parentDep("A") :: subDep("A") :: subDep("B") ::parentDep("D") :: Nil
def mavenStyleDependencies = parentDep("B") :: parentDep("C") :: subDep("C") :: subDep("D") :: Nil
def parentDep(org: String) = org %% "publish-test" % "1.0"
def subDep(org: String) = org %% "sub-project" % "1.0"
}
|
niktrop/sbt
|
sbt/src/sbt-test/dependency-management/publish-local/changes/RetrieveTest.scala
|
Scala
|
bsd-3-clause
| 1,032 |
package org.jetbrains.plugins.scala.lang.resolve
import org.jetbrains.plugins.scala.base.ScalaLightCodeInsightFixtureTestAdapter
/**
* @author Roman.Shein
* @since 28.03.2016.
*/
class TypeVisibilityTest extends ScalaLightCodeInsightFixtureTestAdapter {
def testSCL13138(): Unit = {
val text =
"""
|trait A[T] {
| type T
| def f(x : T) : Unit
|}
""".stripMargin
checkTextHasNoErrors(text)
}
}
|
JetBrains/intellij-scala
|
scala/scala-impl/test/org/jetbrains/plugins/scala/lang/resolve/TypeVisibilityTest.scala
|
Scala
|
apache-2.0
| 460 |
/*
* Copyright 2015-2016 IBM Corporation
*
* 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 whisk.core.container.test
import scala.concurrent.Future
import scala.concurrent.duration._
import org.junit.runner.RunWith
import org.scalatest.BeforeAndAfter
import org.scalatest.BeforeAndAfterAll
import org.scalatest.FlatSpec
import org.scalatest.junit.JUnitRunner
import akka.event.Logging.ErrorLevel
import whisk.common.TransactionId
import whisk.core.WhiskConfig
import whisk.core.WhiskConfig.dockerEndpoint
import whisk.core.WhiskConfig.edgeHostName
import whisk.core.WhiskConfig.selfDockerEndpoint
import whisk.core.WhiskConfig.invokerSerializeDockerOp
import whisk.core.WhiskConfig.invokerSerializeDockerPull
import whisk.core.container.Container
import whisk.core.container.ContainerPool
import whisk.core.entity.AuthKey
import whisk.core.entity.EntityName
import whisk.core.entity.Exec
import whisk.core.entity.EntityPath
import whisk.core.entity.WhiskAction
import whisk.core.entity.WhiskAuthStore
import whisk.core.entity.WhiskEntityStore
import scala.language.postfixOps
import common.WskActorSystem
/**
* Unit tests for ContainerPool and, by association, Container and WhiskContainer.
*
*/
@RunWith(classOf[JUnitRunner])
class ContainerPoolTests extends FlatSpec
with BeforeAndAfter
with BeforeAndAfterAll
with WskActorSystem {
implicit val transid = TransactionId.testing
val config = new WhiskConfig(
WhiskEntityStore.requiredProperties ++
WhiskAuthStore.requiredProperties ++
ContainerPool.requiredProperties ++
Map(selfDockerEndpoint -> "localhost",
dockerEndpoint -> null,
edgeHostName -> "localhost",
invokerSerializeDockerOp -> "true",
invokerSerializeDockerPull -> "true"))
assert(config.isValid)
val pool = new ContainerPool(config, 0, ErrorLevel, true, true)
pool.logDir = "/tmp"
val datastore = WhiskEntityStore.datastore(config)
override def afterAll() {
println("Shutting down store connections")
datastore.shutdown()
super.afterAll()
}
/**
* Starts (and returns) a container running ubuntu image running echo on the given test word.
* Also checks that the test word shows up in the docker logs.
*/
def getEcho(word: String): Container = {
val conOpt = pool.getByImageName("ubuntu", Array("/bin/echo", word))
assert(conOpt isDefined) // we must be able to start the container
val con = conOpt.getOrElse(null)
Thread.sleep(1000) // docker run has no guarantee how far along the process is
assert(con.getLogs().contains(word)) // the word must be in the docker logs
con
}
/*
* Start a new container that stays around via sleep.
*/
def getSleep(duration: Int): Container = {
val conOpt = pool.getByImageName("ubuntu", Array("/bin/sleep", duration.toString()))
assert(conOpt isDefined) // we must be able to start the container
conOpt.getOrElse(null)
}
/*
* Ensure pool is empty/clean.
*/
def ensureClean() = {
pool.enableGC()
pool.forceGC()
Thread.sleep(2 * pool.gcFrequency.toMillis + 1500L) // GC should collect this by now
assert(pool.idleCount() == 0)
assert(pool.activeCount() == 0)
}
/*
* Does a container with the given prefix exist?
*/
def poolHasContainerIdPrefix(containerIdPrefix: String) = {
val states = pool.listAll()
states.find { _.id.hash.contains(containerIdPrefix) }.isDefined
}
behavior of "ContainerPool"
after {
ensureClean()
}
it should "be empty when it starts" in {
assert(pool.idleCount() == 0)
assert(pool.activeCount() == 0)
}
it should "allow getting container by image name, run it, retrieve logs, return it, force GC, check via docker ps" in {
pool.disableGC()
val startIdleCount = pool.idleCount()
val container = getEcho("abracadabra")
val containerIdPrefix = container.containerIdPrefix
assert(poolHasContainerIdPrefix(containerIdPrefix)) // container must be around
pool.putBack(container) // contractually, user must let go of con at this point
assert(pool.idleCount() == startIdleCount + 1)
pool.enableGC()
pool.forceGC() // force all containers in pool to be freed
Thread.sleep(2 * pool.gcFrequency.toMillis + 1500L) // GC should collect this by now
assert(!poolHasContainerIdPrefix(containerIdPrefix)) // container must be gone by now
assert(pool.idleCount() == 0)
}
it should "respect maxIdle by shooting a container on a putBack that could exceed it" in {
ensureClean()
pool.maxIdle = 1
val c1 = getEcho("quasar")
val c2 = getEcho("pulsar")
val p1 = c1.containerIdPrefix
val p2 = c2.containerIdPrefix
assert(pool.activeCount() == 2)
assert(pool.idleCount() == 0)
pool.putBack(c1)
assert(pool.activeCount() == 1)
assert(pool.idleCount() == 1)
pool.putBack(c2)
assert(pool.activeCount() == 0)
assert(pool.idleCount() == 1) // because c1 got shot
pool.resetMaxIdle()
}
it should "respect activeIdle by blocking a getContainer until another is returned" in {
ensureClean()
pool.maxActive = 1
val c1 = getEcho("hocus")
var c1Back = false
val f = Future { Thread.sleep(3000); c1Back = true; pool.putBack(c1) }
val c2 = getEcho("pocus")
assert(c1Back) // make sure c2 is not available before c1 is put back
pool.putBack(c2)
pool.resetMaxActive()
}
it should "also perform automatic GC with a settable threshold, invoke same action afterwards, another GC" in {
ensureClean();
pool.gcThreshold = 1.seconds
val container = getEcho("hocus pocus")
val containerIdPrefix = container.containerIdPrefix
assert(poolHasContainerIdPrefix(containerIdPrefix)) // container must be around
pool.putBack(container); // contractually, user must let go of con at this point
// TODO: replace this with GC count so we don't break abstraction by knowing the GC check freq. (!= threshold)
Thread.sleep(2 * pool.gcFrequency.toMillis + 4000L) // GC should collect this by now
assert(!poolHasContainerIdPrefix(containerIdPrefix)) // container must be gone by now
// Do it again now
val container2 = getEcho("hocus pocus")
val containerIdPrefix2 = container2.containerIdPrefix
assert(poolHasContainerIdPrefix(containerIdPrefix2)) // container must be around
pool.putBack(container2)
pool.resetGCThreshold()
}
// Lower it some more by parameterizing GC thresholds
it should "be able to go through 15 containers without thrashing the system" in {
ensureClean()
val max = 15
for (i <- List.range(0, max)) {
val name = "foobar" + i
val action = makeHelloAction(name, i)
pool.getAction(action, defaultAuth) match {
case (con, initResult) => {
val str = "QWERTY" + i.toString()
con.run(str, (20000 + i).toString()) // payload + activationId
if (i == max - 1) {
Thread.sleep(1000)
assert(con.getLogs().contains(str))
}
pool.putBack(con)
}
} // match
} // for
}
private val defaultNamespace = EntityPath("container pool test")
private val defaultAuth = AuthKey()
/*
* Create an action with the given name that print hello_N payload !
* where N is specified.
*/
private def makeHelloAction(name: String, index: Integer): WhiskAction = {
val code = """console.log('ABCXYZ'); function main(msg) { console.log('hello_${index}', msg.payload+'!');} """
WhiskAction(defaultNamespace, EntityName(name), Exec.js(code))
}
it should "be able to start a nodejs action with init, do a run, return to pool, do another get testing reuse, another run" in {
ensureClean()
val action = makeHelloAction("foobar", 0)
// Make a whisk container and test init and a push
val (con, initRes) = pool.getAction(action, defaultAuth)
Thread.sleep(1000)
assert(con.getLogs().contains("ABCXYZ"))
con.run("QWERTY", "55555") // payload + activationId
Thread.sleep(1000)
assert(con.getLogs().contains("QWERTY"))
pool.putBack(con)
// Test container reuse
val (con2, _) = pool.getAction(action, defaultAuth)
assert(con == con2) // check re-use
con.run("ASDFGH", "4444") // payload + activationId
Thread.sleep(1000)
assert(con.getLogs().contains("ASDFGH"))
pool.putBack(con)
}
}
|
nwspeete-ibm/openwhisk
|
tests/src/whisk/core/container/test/ContainerPoolTests.scala
|
Scala
|
apache-2.0
| 9,528 |
package models.provider
import org.specs2.mutable._
import models.provider._
import play.api.test._
import play.api.test.Helpers._
import java.net.URI
object ProviderSpecs extends Specification {
"PathProvider" should {
"deconstruct simple path" in {
val testPath = "/AMDA-NG/data/WSRESULT/getObsDataTree_LocalParams.xml"
val folderName = "AMDA"
val result = PathProvider.getPath("trees", folderName, testPath)
val expectedResult = "trees/AMDA/getObsDataTree_LocalParams.xml"
result must be equalTo expectedResult
}
"deconstruct GET path" in {
val testPath = "AMDA_METHODS_WSDL.php?wsdl"
val folderName = "AMDA"
val result = PathProvider.getPath("methods", folderName, testPath)
val expectedResult = "methods/AMDA/AMDA_methods.wsdl"
result must be equalTo expectedResult
}
}
"UrlProvider" should {
"provide URL" in {
val testPath = Seq("/AMDA-NG/data/WSRESULT/getObsDataTree_LocalParams.xml")
val dnsName = "cdpp1.cesr.fr"
val protocol = "http"
val result = UrlProvider.getUrls(protocol, dnsName, testPath)
val expectedResult = Seq(new URI("http://cdpp1.cesr.fr/AMDA-NG/data/WSRESULT/getObsDataTree_LocalParams.xml"))
result must be equalTo expectedResult
}
"encode URI" in {
val uri = new URI("impex://FMI")
val expected = "impex___FMI"
UrlProvider.encodeURI(uri) must be equalTo expected
}
"decode URI" in {
val string = "impex___SINP_PMM"
val expected = new URI("impex://SINP/PMM")
UrlProvider.decodeURI(string) must be equalTo expected
}
}
"TimeProvider" should {
"return ISO date for String" in {
val date = "2012-03-08T14:06:00"
val isoDate = TimeProvider.getISODate(date)
isoDate.toString must be equalTo "2012-03-08T14:06:00.000+01:00"
}
}
}
|
FlorianTopf/impex-portal
|
test/models/provider/ProviderSpecs.scala
|
Scala
|
gpl-2.0
| 1,957 |
package org.skycastle.core.design
/**
* A part that maps directly to an entity.
*/
class ConcretePart extends Part {
def anchorPos = null
def occupiedCells = null
def outerBounds = null
def gridSize = null
}
|
zzorn/skycastle
|
src/main/scala/org/skycastle/core/design/ConcretePart.scala
|
Scala
|
gpl-2.0
| 218 |
package at.logic.gapt.proofs.drup
import at.logic.gapt.expr.{ Formula, Polarity }
import at.logic.gapt.proofs._
import at.logic.gapt.proofs.resolution._
import cats.{ Eval, Later, Now }
import scala.collection.mutable
sealed abstract class DrupProofLine extends Product {
def clause: HOLClause
override def toString = s"[${productPrefix.stripPrefix( "Drup" ).toLowerCase}] $clause"
}
/** Input clause in a DRUP proof. */
case class DrupInput( clause: HOLClause ) extends DrupProofLine
/**
* Derived clause in a DRUP proof.
*
* The clause is not only required to be a consequence of the previous
* clauses in the proof, but also RUP (a strictly stronger requirement):
*
* Given a set of clauses Γ and a clause C, then C has the property RUP with regard to Γ iff
* Γ, ¬C can be refuted with only unit propagation.
*/
case class DrupDerive( clause: HOLClause ) extends DrupProofLine
/**
* Forgets a clause in a DRUP proof.
*
* This inference is not necessary for completeness, it is mainly a
* performance optimization since it speeds up the unit propagation in [[DrupDerive]].
*/
case class DrupForget( clause: HOLClause ) extends DrupProofLine
/**
* DRUP proof.
*
* A DRUP proof consists of a sequence of clauses. Each clause is either a [[DrupInput]], a [[DrupDerive]], or a [[DrupForget]].
*/
case class DrupProof( refutation: Seq[DrupProofLine] ) {
override def toString = refutation.reverse.mkString( "\\n" )
}
object DrupProof {
def apply( cnf: Iterable[HOLClause], refutation: Seq[DrupProofLine] ): DrupProof =
DrupProof( cnf.map( DrupInput ).toSeq ++ refutation )
}
object DrupToResolutionProof {
// We operate on pairs of clauses and resolution proofs.
// - Proofs are computed only when needed (Eval[_] does lazy evaluation)
// - The clauses can be smaller than the conclusion of the proof,
// e.g. we can have a pair (:- a, Taut(a))
private type ResProofThunk = ( HOLSequent, Eval[ResolutionProof] )
private def unitPropagationProver( cnf: Iterable[ResProofThunk] ): ResolutionProof = {
// An atom together with a polarity
type Literal = ( Formula, Polarity )
var emptyClause: Option[ResProofThunk] = None
// All unit clauses that we have found so far, indexed by their one literal
val unitIndex = mutable.Map[Literal, ResProofThunk]()
// All non-unit clauses that we have found so far, indexed by the first two literals
val nonUnitIndex = mutable.Map[Literal, Map[HOLSequent, Eval[ResolutionProof]]]().withDefaultValue( Map() )
def negate( lit: Literal ) = ( lit._1, !lit._2 )
def resolve( p: ResProofThunk, unit: ResProofThunk, lit: Literal ): ResProofThunk =
if ( lit._2.inSuc ) ( p._1.removeFromSuccedent( lit._1 ), Later( Factor( Resolution( p._2.value, unit._2.value, lit._1 ) ) ) )
else ( p._1.removeFromAntecedent( lit._1 ), Later( Factor( Resolution( unit._2.value, p._2.value, lit._1 ) ) ) )
// Handle a new clause, and fully interreduce it with the clauses we have found so far
def add( p: ResProofThunk ): Unit =
if ( emptyClause.isDefined ) {
// already found empty clause somewhere else
} else if ( p._1.isEmpty ) {
emptyClause = Some( p )
} else {
val lits = p._1.polarizedElements
if ( lits.exists( unitIndex.contains ) ) {
// subsumed by unit clause
} else {
lits.find( l => unitIndex.contains( negate( l ) ) ) match {
case Some( lit ) =>
val q = unitIndex( negate( lit ) )
add( resolve( p, q, lit ) )
case None =>
if ( lits.size == 1 ) { // found unit clause
val lit = lits.head
unitIndex( lit ) = p
// propagate
val negLit = negate( lit )
val qs = nonUnitIndex( negLit )
nonUnitIndex.remove( negLit )
for {
q <- qs.keys
lit_ <- q.polarizedElements.view.take( 2 )
if lit_ != negLit
} nonUnitIndex( lit_ ) -= q
// .map removes duplicate clauses
qs.map( resolve( _, p, negLit ) ).foreach( add )
} else {
val watched = lits.view.take( 2 )
for ( lit <- watched ) nonUnitIndex( lit ) += p
}
}
}
}
cnf.toSeq.sortBy( _._1.size ).foreach( add )
emptyClause.get._2.value
}
def unitPropagationReplay( cnf: Iterable[ResolutionProof], toDerive: HOLClause ): ResolutionProof = {
val inputClauses = for ( p <- cnf ) yield p.conclusion -> Now( p )
val negatedUnitClauses =
for {
( a, i ) <- toDerive.zipWithIndex.elements
concl = if ( i.isSuc ) Seq( a ) :- Seq() else Seq() :- Seq( a )
} yield concl -> Later( Taut( a ) )
unitPropagationProver( inputClauses ++ negatedUnitClauses )
}
def apply( drup: DrupProof ): ResolutionProof = {
val cnf = mutable.Set[ResolutionProof]()
drup.refutation foreach {
case DrupInput( clause ) =>
cnf += Input( clause )
case DrupDerive( clause ) =>
cnf += unitPropagationReplay( cnf, clause )
case DrupForget( clause ) =>
cnf.retain( !_.conclusion.multiSetEquals( clause ) )
}
simplifyResolutionProof( cnf.find( _.conclusion.isEmpty ).get )
}
}
|
gebner/gapt
|
core/src/main/scala/at/logic/gapt/proofs/drup/DrupProof.scala
|
Scala
|
gpl-3.0
| 5,372 |
/*
* Copyright (c) 2014 Alvaro Agea.
*
* 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.rogerfs.core.api
import org.rogerfs.common.store.IStore
import org.rogerfs.common.store.Path
import org.rogerfs.test.store.TestStore
import org.scalatest.WordSpec
class RogerInputStreamSpec extends WordSpec {
val store: IStore = new TestStore
val file = Path.getPath("/a/b/c")
store.createFile(file)
val block1 = store.openBlock(file)
store.addData(file, block1,
Array[Byte](0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), 0)
store.addData(file, block1,
Array[Byte](16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31), 1)
val block2 = store.openBlock(file)
store.closeBlock(file, block1, block2)
store.addData(file, block2,
Array[Byte](0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), 0)
store.addData(file, block2,
Array[Byte](16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31), 1)
store.closeBlock(file, block2, null)
val fileSystem = FileSystem.mount(store)
val inputStream = fileSystem.readFile(file)
val data = new Array[Byte](8)
"A RogerInputStream" when {
"read Sequential bytes in multiples blocks" must {
"not fail" in {
inputStream.read(data)
assertResult(7)(data(7))
inputStream.read(data)
assertResult(15)(data(7))
inputStream.read(data)
assertResult(23)(data(7))
inputStream.read(data)
assertResult(31)(data(7))
inputStream.read(data)
assertResult(7)(data(7))
inputStream.read(data)
assertResult(15)(data(7))
inputStream.read(data)
assertResult(23)(data(7))
inputStream.read(data)
assertResult(31)(data(7))
}
}
}
}
|
aagea/rogerfs
|
rogerfs-core/src/test/scala/org/rogerfs/core/api/RogerInputStreamSpec.scala
|
Scala
|
apache-2.0
| 2,289 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.spark.deploy
import java.io.{File, FileInputStream, FileOutputStream}
import java.util.jar.{JarEntry, JarOutputStream}
import com.google.common.io.{Files, ByteStreams}
import org.apache.commons.io.FileUtils
import org.apache.ivy.core.settings.IvySettings
import org.apache.spark.TestUtils.{createCompiledClass, JavaSourceFromString}
import org.apache.spark.deploy.SparkSubmitUtils.MavenCoordinate
private[deploy] object IvyTestUtils {
/**
* Create the path for the jar and pom from the maven coordinate. Extension should be `jar`
* or `pom`.
*/
private def pathFromCoordinate(
artifact: MavenCoordinate,
prefix: File,
ext: String,
useIvyLayout: Boolean): File = {
val groupDirs = artifact.groupId.replace(".", File.separator)
val artifactDirs = artifact.artifactId
val artifactPath =
if (!useIvyLayout) {
Seq(groupDirs, artifactDirs, artifact.version).mkString(File.separator)
} else {
Seq(artifact.groupId, artifactDirs, artifact.version, ext + "s").mkString(File.separator)
}
new File(prefix, artifactPath)
}
/** Returns the artifact naming based on standard ivy or maven format. */
private def artifactName(
artifact: MavenCoordinate,
useIvyLayout: Boolean,
ext: String = ".jar"): String = {
if (!useIvyLayout) {
s"${artifact.artifactId}-${artifact.version}$ext"
} else {
s"${artifact.artifactId}$ext"
}
}
/** Returns the directory for the given groupId based on standard ivy or maven format. */
private def getBaseGroupDirectory(artifact: MavenCoordinate, useIvyLayout: Boolean): String = {
if (!useIvyLayout) {
artifact.groupId.replace(".", File.separator)
} else {
artifact.groupId
}
}
/** Write the contents to a file to the supplied directory. */
private def writeFile(dir: File, fileName: String, contents: String): File = {
val outputFile = new File(dir, fileName)
val outputStream = new FileOutputStream(outputFile)
outputStream.write(contents.toCharArray.map(_.toByte))
outputStream.close()
outputFile
}
/** Create an example Python file. */
private def createPythonFile(dir: File): File = {
val contents =
"""def myfunc(x):
| return x + 1
""".stripMargin
writeFile(dir, "mylib.py", contents)
}
/** Create a simple testable Class. */
private def createJavaClass(dir: File, className: String, packageName: String): File = {
val contents =
s"""package $packageName;
|
|import java.lang.Integer;
|
|class $className implements java.io.Serializable {
|
| public $className() {}
|
| public Integer myFunc(Integer x) {
| return x + 1;
| }
|}
""".stripMargin
val sourceFile =
new JavaSourceFromString(new File(dir, className + ".java").getAbsolutePath, contents)
createCompiledClass(className, dir, sourceFile, Seq.empty)
}
private def createDescriptor(
tempPath: File,
artifact: MavenCoordinate,
dependencies: Option[Seq[MavenCoordinate]],
useIvyLayout: Boolean): File = {
if (useIvyLayout) {
val ivyXmlPath = pathFromCoordinate(artifact, tempPath, "ivy", true)
Files.createParentDirs(new File(ivyXmlPath, "dummy"))
createIvyDescriptor(ivyXmlPath, artifact, dependencies)
} else {
val pomPath = pathFromCoordinate(artifact, tempPath, "pom", useIvyLayout)
Files.createParentDirs(new File(pomPath, "dummy"))
createPom(pomPath, artifact, dependencies)
}
}
/** Helper method to write artifact information in the pom. */
private def pomArtifactWriter(artifact: MavenCoordinate, tabCount: Int = 1): String = {
var result = "\\n" + " " * tabCount + s"<groupId>${artifact.groupId}</groupId>"
result += "\\n" + " " * tabCount + s"<artifactId>${artifact.artifactId}</artifactId>"
result += "\\n" + " " * tabCount + s"<version>${artifact.version}</version>"
result
}
/** Create a pom file for this artifact. */
private def createPom(
dir: File,
artifact: MavenCoordinate,
dependencies: Option[Seq[MavenCoordinate]]): File = {
var content = """
|<?xml version="1.0" encoding="UTF-8"?>
|<project xmlns="http://maven.apache.org/POM/4.0.0"
| xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
| xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
| http://maven.apache.org/xsd/maven-4.0.0.xsd">
| <modelVersion>4.0.0</modelVersion>
""".stripMargin.trim
content += pomArtifactWriter(artifact)
content += dependencies.map { deps =>
val inside = deps.map { dep =>
"\\t<dependency>" + pomArtifactWriter(dep, 3) + "\\n\\t</dependency>"
}.mkString("\\n")
"\\n <dependencies>\\n" + inside + "\\n </dependencies>"
}.getOrElse("")
content += "\\n</project>"
writeFile(dir, artifactName(artifact, false, ".pom"), content.trim)
}
/** Helper method to write artifact information in the ivy.xml. */
private def ivyArtifactWriter(artifact: MavenCoordinate): String = {
s"""<dependency org="${artifact.groupId}" name="${artifact.artifactId}"
| rev="${artifact.version}" force="true"
| conf="compile->compile(*),master(*);runtime->runtime(*)"/>""".stripMargin
}
/** Create a pom file for this artifact. */
private def createIvyDescriptor(
dir: File,
artifact: MavenCoordinate,
dependencies: Option[Seq[MavenCoordinate]]): File = {
var content = s"""
|<?xml version="1.0" encoding="UTF-8"?>
|<ivy-module version="2.0" xmlns:m="http://ant.apache.org/ivy/maven">
| <info organisation="${artifact.groupId}"
| module="${artifact.artifactId}"
| revision="${artifact.version}"
| status="release" publication="20150405222456" />
| <configurations>
| <conf name="default" visibility="public" description="" extends="runtime,master"/>
| <conf name="compile" visibility="public" description=""/>
| <conf name="master" visibility="public" description=""/>
| <conf name="runtime" visibility="public" description="" extends="compile"/>
| <conf name="pom" visibility="public" description=""/>
| </configurations>
| <publications>
| <artifact name="${artifactName(artifact, true, "")}" type="jar" ext="jar"
| conf="master"/>
| </publications>
""".stripMargin.trim
content += dependencies.map { deps =>
val inside = deps.map(ivyArtifactWriter).mkString("\\n")
"\\n <dependencies>\\n" + inside + "\\n </dependencies>"
}.getOrElse("")
content += "\\n</ivy-module>"
writeFile(dir, "ivy.xml", content.trim)
}
/** Create the jar for the given maven coordinate, using the supplied files. */
private def packJar(
dir: File,
artifact: MavenCoordinate,
files: Seq[(String, File)],
useIvyLayout: Boolean): File = {
val jarFile = new File(dir, artifactName(artifact, useIvyLayout))
val jarFileStream = new FileOutputStream(jarFile)
val jarStream = new JarOutputStream(jarFileStream, new java.util.jar.Manifest())
for (file <- files) {
val jarEntry = new JarEntry(file._1)
jarStream.putNextEntry(jarEntry)
val in = new FileInputStream(file._2)
ByteStreams.copy(in, jarStream)
in.close()
}
jarStream.close()
jarFileStream.close()
jarFile
}
/**
* Creates a jar and pom file, mocking a Maven repository. The root path can be supplied with
* `tempDir`, dependencies can be created into the same repo, and python files can also be packed
* inside the jar.
*
* @param artifact The maven coordinate to generate the jar and pom for.
* @param dependencies List of dependencies this artifact might have to also create jars and poms.
* @param tempDir The root folder of the repository
* @param useIvyLayout whether to mock the Ivy layout for local repository testing
* @param withPython Whether to pack python files inside the jar for extensive testing.
* @return Root path of the repository
*/
private def createLocalRepository(
artifact: MavenCoordinate,
dependencies: Option[Seq[MavenCoordinate]] = None,
tempDir: Option[File] = None,
useIvyLayout: Boolean = false,
withPython: Boolean = false): File = {
// Where the root of the repository exists, and what Ivy will search in
val tempPath = tempDir.getOrElse(Files.createTempDir())
// Create directory if it doesn't exist
Files.createParentDirs(tempPath)
// Where to create temporary class files and such
val root = new File(tempPath, tempPath.hashCode().toString)
Files.createParentDirs(new File(root, "dummy"))
try {
val jarPath = pathFromCoordinate(artifact, tempPath, "jar", useIvyLayout)
Files.createParentDirs(new File(jarPath, "dummy"))
val className = "MyLib"
val javaClass = createJavaClass(root, className, artifact.groupId)
// A tuple of files representation in the jar, and the file
val javaFile = (artifact.groupId.replace(".", "/") + "/" + javaClass.getName, javaClass)
val allFiles =
if (withPython) {
val pythonFile = createPythonFile(root)
Seq(javaFile, (pythonFile.getName, pythonFile))
} else {
Seq(javaFile)
}
val jarFile = packJar(jarPath, artifact, allFiles, useIvyLayout)
assert(jarFile.exists(), "Problem creating Jar file")
val descriptor = createDescriptor(tempPath, artifact, dependencies, useIvyLayout)
assert(descriptor.exists(), "Problem creating Pom file")
} finally {
FileUtils.deleteDirectory(root)
}
tempPath
}
/**
* Creates a suite of jars and poms, with or without dependencies, mocking a maven repository.
* @param artifact The main maven coordinate to generate the jar and pom for.
* @param dependencies List of dependencies this artifact might have to also create jars and poms.
* @param rootDir The root folder of the repository (like `~/.m2/repositories`)
* @param useIvyLayout whether to mock the Ivy layout for local repository testing
* @param withPython Whether to pack python files inside the jar for extensive testing.
* @return Root path of the repository. Will be `rootDir` if supplied.
*/
private[deploy] def createLocalRepositoryForTests(
artifact: MavenCoordinate,
dependencies: Option[String],
rootDir: Option[File],
useIvyLayout: Boolean = false,
withPython: Boolean = false): File = {
val deps = dependencies.map(SparkSubmitUtils.extractMavenCoordinates)
val mainRepo = createLocalRepository(artifact, deps, rootDir, useIvyLayout, withPython)
deps.foreach { seq => seq.foreach { dep =>
createLocalRepository(dep, None, Some(mainRepo), useIvyLayout, withPython = false)
}}
mainRepo
}
/**
* Creates a repository for a test, and cleans it up afterwards.
*
* @param artifact The main maven coordinate to generate the jar and pom for.
* @param dependencies List of dependencies this artifact might have to also create jars and poms.
* @param rootDir The root folder of the repository (like `~/.m2/repositories`)
* @param useIvyLayout whether to mock the Ivy layout for local repository testing
* @param withPython Whether to pack python files inside the jar for extensive testing.
* @return Root path of the repository. Will be `rootDir` if supplied.
*/
private[deploy] def withRepository(
artifact: MavenCoordinate,
dependencies: Option[String],
rootDir: Option[File],
useIvyLayout: Boolean = false,
withPython: Boolean = false,
ivySettings: IvySettings = new IvySettings)(f: String => Unit): Unit = {
val deps = dependencies.map(SparkSubmitUtils.extractMavenCoordinates)
purgeLocalIvyCache(artifact, deps, ivySettings)
val repo = createLocalRepositoryForTests(artifact, dependencies, rootDir, useIvyLayout,
withPython)
try {
f(repo.toURI.toString)
} finally {
// Clean up
if (repo.toString.contains(".m2") || repo.toString.contains(".ivy2")) {
val groupDir = getBaseGroupDirectory(artifact, useIvyLayout)
FileUtils.deleteDirectory(new File(repo, groupDir + File.separator + artifact.artifactId))
deps.foreach { _.foreach { dep =>
FileUtils.deleteDirectory(new File(repo, getBaseGroupDirectory(dep, useIvyLayout)))
}
}
} else {
FileUtils.deleteDirectory(repo)
}
purgeLocalIvyCache(artifact, deps, ivySettings)
}
}
/** Deletes the test packages from the ivy cache */
private def purgeLocalIvyCache(
artifact: MavenCoordinate,
dependencies: Option[Seq[MavenCoordinate]],
ivySettings: IvySettings): Unit = {
// delete the artifact from the cache as well if it already exists
FileUtils.deleteDirectory(new File(ivySettings.getDefaultCache, artifact.groupId))
dependencies.foreach { _.foreach { dep =>
FileUtils.deleteDirectory(new File(ivySettings.getDefaultCache, dep.groupId))
}
}
}
}
|
andrewor14/iolap
|
core/src/test/scala/org/apache/spark/deploy/IvyTestUtils.scala
|
Scala
|
apache-2.0
| 14,222 |
package s3.website
import s3.website.ErrorReport._
import s3.website.model.{FileUpdate, Config}
import com.amazonaws.services.cloudfront.{AmazonCloudFrontClient, AmazonCloudFront}
import com.amazonaws.services.cloudfront.model.{TooManyInvalidationsInProgressException, Paths, InvalidationBatch, CreateInvalidationRequest}
import scala.collection.JavaConversions._
import scala.concurrent.duration._
import s3.website.S3.{SuccessfulDelete, PushSuccessReport, SuccessfulUpload}
import com.amazonaws.auth.BasicAWSCredentials
import java.net.{URLEncoder, URI}
import scala.concurrent.{ExecutionContextExecutor, Future}
import s3.website.model.Config.awsCredentials
object CloudFront {
def invalidate(invalidationBatch: InvalidationBatch, distributionId: String, attempt: Attempt = 1)
(implicit ec: ExecutionContextExecutor, cloudFrontSettings: CloudFrontSetting, config: Config, logger: Logger, pushOptions: PushOptions): InvalidationResult =
Future {
if (!pushOptions.dryRun) cloudFront createInvalidation new CreateInvalidationRequest(distributionId, invalidationBatch)
val result = SuccessfulInvalidation(invalidationBatch.getPaths.getItems.size())
logger.debug(invalidationBatch.getPaths.getItems.map(item => s"${Invalidated.renderVerb} $item") mkString "\\n")
logger.info(result)
Right(result)
} recoverWith (tooManyInvalidationsRetry(invalidationBatch, distributionId, attempt) orElse retry(attempt)(
createFailureReport = error => FailedInvalidation(error),
retryAction = nextAttempt => invalidate(invalidationBatch, distributionId, nextAttempt)
))
def tooManyInvalidationsRetry(invalidationBatch: InvalidationBatch, distributionId: String, attempt: Attempt)
(implicit ec: ExecutionContextExecutor, logger: Logger, cloudFrontSettings: CloudFrontSetting, config: Config, pushOptions: PushOptions):
PartialFunction[Throwable, InvalidationResult] = {
case e: TooManyInvalidationsInProgressException =>
val duration: Duration = Duration(
(fibs drop attempt).head min 15, /* CloudFront invalidations complete within 15 minutes */
cloudFrontSettings.retryTimeUnit
)
logger.pending(maxInvalidationsExceededInfo(duration, attempt))
Thread.sleep(duration.toMillis)
invalidate(invalidationBatch, distributionId, attempt + 1)
}
def maxInvalidationsExceededInfo(sleepDuration: Duration, attempt: Int) = {
val basicInfo = s"The maximum amount of CloudFront invalidations has exceeded. Trying again in $sleepDuration, please wait."
val extendedInfo =
s"""|$basicInfo
|For more information, see http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html#InvalidationLimits"""
.stripMargin
if (attempt == 1)
extendedInfo
else
basicInfo
}
def cloudFront(implicit config: Config, cloudFrontSettings: CloudFrontSetting) = cloudFrontSettings.cfClient(config)
type InvalidationResult = Future[Either[FailedInvalidation, SuccessfulInvalidation]]
type CloudFrontClientProvider = (Config) => AmazonCloudFront
case class SuccessfulInvalidation(invalidatedItemsCount: Int)(implicit pushOptions: PushOptions) extends SuccessReport {
def reportMessage = s"${Invalidated.renderVerb} ${invalidatedItemsCount ofType "item"} on CloudFront"
}
case class FailedInvalidation(error: Throwable)(implicit logger: Logger) extends ErrorReport {
def reportMessage = errorMessage(s"Failed to invalidate the CloudFront distribution", error)
}
def awsCloudFrontClient(config: Config) = new AmazonCloudFrontClient(awsCredentials(config))
def toInvalidationBatches(pushSuccessReports: Seq[PushSuccessReport])(implicit config: Config): Seq[InvalidationBatch] = {
def defaultPath(paths: Seq[String]): Option[String] = {
// This is how we support the Default Root Object @ CloudFront (http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/DefaultRootObject.html)
// We could do this more accurately by fetching the distribution config (http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/GetConfig.html)
// and reading the Default Root Object from there.
val containsPotentialDefaultRootObject = paths
.exists(
_
.replaceFirst("^/", "") // S3 keys do not begin with a slash
.contains("/") == false // See if the S3 key is a top-level key (i.e., it is not within a directory)
)
if (containsPotentialDefaultRootObject) Some("/") else None
}
val indexPath = config.cloudfront_invalidate_root collect {
case true if pushSuccessReports.nonEmpty => config.s3_key_prefix.map(prefix => s"/$prefix").getOrElse("") + "/index.html"
}
val invalidationPaths: Seq[String] = {
val paths = pushSuccessReports
.filter(needsInvalidation)
.map(toInvalidationPath)
.map(encodeUnsafeChars)
.map(applyInvalidateRootSetting)
val extraPathItems = defaultPath(paths) :: indexPath :: Nil collect {
case Some(path) => path
}
paths ++ extraPathItems
}
invalidationPaths
.grouped(1000) // CloudFront supports max 1000 invalidations in one request (http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html#InvalidationLimits)
.map { batchKeys =>
new InvalidationBatch() withPaths
(new Paths() withItems batchKeys withQuantity batchKeys.size) withCallerReference
s"s3_website gem ${System.currentTimeMillis()}"
}
.toSeq
}
def applyInvalidateRootSetting(path: String)(implicit config: Config) =
if (config.cloudfront_invalidate_root.contains(true))
path.replaceFirst("/index.html$", "/")
else
path
def toInvalidationPath(report: PushSuccessReport) = "/" + report.s3Key
def encodeUnsafeChars(invalidationPath: String) =
new URI("http", "cloudfront", invalidationPath, "")
.toURL
.getPath
.replaceAll("'", URLEncoder.encode("'", "UTF-8")) // CloudFront does not accept ' in invalidation path
.flatMap(chr => {
if (("[^\\\\x00-\\\\x7F]".r findFirstIn chr.toString).isDefined)
URLEncoder.encode(chr.toString, "UTF-8")
else
chr.toString
})
def needsInvalidation: PartialFunction[PushSuccessReport, Boolean] = {
case succ: SuccessfulUpload => succ.details.fold(_.uploadType, _.uploadType) == FileUpdate
case SuccessfulDelete(_) => true
case _ => false
}
case class CloudFrontSetting(
cfClient: CloudFrontClientProvider = CloudFront.awsCloudFrontClient,
retryTimeUnit: TimeUnit = MINUTES
) extends RetrySetting
}
|
pathawks/s3_website
|
src/main/scala/s3/website/CloudFront.scala
|
Scala
|
mit
| 6,716 |
/*
* Copyright (C) 2009-2013 Typesafe Inc. <http://www.typesafe.com>
*/
package play.it.http
import java.io.IOException
import play.api.mvc._
import play.api.test._
import play.api.libs.ws._
import play.api.libs.iteratee._
import play.it._
import scala.util.{ Failure, Success, Try }
import play.api.libs.concurrent.Execution.{ defaultContext => ec }
object NettyScalaResultsHandlingSpec extends ScalaResultsHandlingSpec with NettyIntegrationSpecification
object AkkaHttpScalaResultsHandlingSpec extends ScalaResultsHandlingSpec with AkkaHttpIntegrationSpecification
trait ScalaResultsHandlingSpec extends PlaySpecification with WsTestClient with ServerIntegrationSpecification {
"scala body handling" should {
def tryRequest[T](result: Result)(block: Try[WSResponse] => T) = withServer(result) { implicit port =>
val response = Try(await(wsUrl("/").get()))
block(response)
}
def makeRequest[T](result: Result)(block: WSResponse => T) = {
tryRequest(result)(tryResult => block(tryResult.get))
}
def withServer[T](result: Result)(block: Port => T) = {
val port = testServerPort
running(TestServer(port, FakeApplication(
withRoutes = {
case _ => Action(result)
}
))) {
block(port)
}
}
"add Content-Length when enumerator contains a single item" in makeRequest(Results.Ok("Hello world")) { response =>
response.header(CONTENT_LENGTH) must beSome("11")
response.body must_== "Hello world"
}
"revert to chunked encoding when enumerator contains more than one item" in makeRequest(
Result(ResponseHeader(200, Map()), Enumerator("abc", "def", "ghi") &> Enumeratee.map[String](_.getBytes)(ec))
) { response =>
response.header(CONTENT_LENGTH) must beNone
response.header(TRANSFER_ENCODING) must beSome("chunked")
response.body must_== "abcdefghi"
}
"truncate result body or close connection when body is larger than Content-Length" in tryRequest(Results.Ok("Hello world")
.withHeaders(CONTENT_LENGTH -> "5")) { tryResponse =>
tryResponse must beLike {
case Success(response) =>
response.header(CONTENT_LENGTH) must_== Some("5")
response.body must_== "Hello"
case Failure(t) =>
t must haveClass[IOException]
t.getMessage must_== "Remotely Closed"
}
}
"chunk results for chunked streaming strategy" in makeRequest(
Results.Ok.chunked(Enumerator("a", "b", "c"))
) { response =>
response.header(TRANSFER_ENCODING) must beSome("chunked")
response.header(CONTENT_LENGTH) must beNone
response.body must_== "abc"
}
"close the connection for feed results" in withServer(
Results.Ok.feed(Enumerator("a", "b", "c"))
) { port =>
val response = BasicHttpClient.makeRequests(port, checkClosed = true)(
BasicRequest("GET", "/", "HTTP/1.1", Map(), "")
)(0)
response.status must_== 200
response.headers.get(TRANSFER_ENCODING) must beNone
response.headers.get(CONTENT_LENGTH) must beNone
response.headers.get(CONNECTION) must beSome("close")
response.body must beLeft("abc")
}
"close the HTTP 1.1 connection when requested" in withServer(
Results.Ok.copy(connection = HttpConnection.Close)
) { port =>
val response = BasicHttpClient.makeRequests(port, checkClosed = true)(
BasicRequest("GET", "/", "HTTP/1.1", Map(), "")
)(0)
response.status must_== 200
response.headers.get(CONNECTION) must beSome("close")
}
"close the HTTP 1.0 connection when requested" in withServer(
Results.Ok.copy(connection = HttpConnection.Close)
) { port =>
val response = BasicHttpClient.makeRequests(port, checkClosed = true)(
BasicRequest("GET", "/", "HTTP/1.0", Map("Connection" -> "keep-alive"), "")
)(0)
response.status must_== 200
response.headers.get(CONNECTION) must beNone
}
"close the connection when the connection close header is present" in withServer(
Results.Ok
) { port =>
BasicHttpClient.makeRequests(port, checkClosed = true)(
BasicRequest("GET", "/", "HTTP/1.1", Map("Connection" -> "close"), "")
)(0).status must_== 200
}
"close the connection when the connection when protocol is HTTP 1.0" in withServer(
Results.Ok
) { port =>
BasicHttpClient.makeRequests(port, checkClosed = true)(
BasicRequest("GET", "/", "HTTP/1.0", Map(), "")
)(0).status must_== 200
}
"honour the keep alive header for HTTP 1.0" in withServer(
Results.Ok
) { port =>
val responses = BasicHttpClient.makeRequests(port)(
BasicRequest("GET", "/", "HTTP/1.0", Map("Connection" -> "keep-alive"), ""),
BasicRequest("GET", "/", "HTTP/1.0", Map(), "")
)
responses(0).status must_== 200
responses(0).headers.get(CONNECTION) must beSome.like {
case s => s.toLowerCase must_== "keep-alive"
}
responses(1).status must_== 200
}
"keep alive HTTP 1.1 connections" in withServer(
Results.Ok
) { port =>
val responses = BasicHttpClient.makeRequests(port)(
BasicRequest("GET", "/", "HTTP/1.1", Map(), ""),
BasicRequest("GET", "/", "HTTP/1.1", Map(), "")
)
responses(0).status must_== 200
responses(1).status must_== 200
}
"close chunked connections when requested" in withServer(
Results.Ok.chunked(Enumerator("a", "b", "c"))
) { port =>
// will timeout if not closed
BasicHttpClient.makeRequests(port, checkClosed = true)(
BasicRequest("GET", "/", "HTTP/1.1", Map("Connection" -> "close"), "")
)(0).status must_== 200
}
"keep chunked connections alive by default" in withServer(
Results.Ok.chunked(Enumerator("a", "b", "c"))
) { port =>
val responses = BasicHttpClient.makeRequests(port)(
BasicRequest("GET", "/", "HTTP/1.1", Map(), ""),
BasicRequest("GET", "/", "HTTP/1.1", Map(), "")
)
responses(0).status must_== 200
responses(1).status must_== 200
}
"allow sending trailers" in withServer(
Result(ResponseHeader(200, Map(TRANSFER_ENCODING -> CHUNKED, TRAILER -> "Chunks")),
Enumerator("aa", "bb", "cc") &> Enumeratee.map[String](_.getBytes)(ec) &> Results.chunk(Some(
Iteratee.fold[Array[Byte], Int](0)((count, in) => count + 1)(ec)
.map(count => Seq("Chunks" -> count.toString))(ec)
)))
) { port =>
val response = BasicHttpClient.makeRequests(port)(
BasicRequest("GET", "/", "HTTP/1.1", Map(), "")
)(0)
response.status must_== 200
response.body must beRight
val (chunks, trailers) = response.body.right.get
chunks must containAllOf(Seq("aa", "bb", "cc")).inOrder
trailers.get("Chunks") must beSome("3")
}.pendingUntilAkkaHttpFixed
"fall back to simple streaming when more than one chunk is sent and protocol is HTTP 1.0" in withServer(
Result(ResponseHeader(200, Map()), Enumerator("abc", "def", "ghi") &> Enumeratee.map[String](_.getBytes)(ec))
) { port =>
val response = BasicHttpClient.makeRequests(port)(
BasicRequest("GET", "/", "HTTP/1.0", Map(), "")
)(0)
response.headers.keySet must not contain TRANSFER_ENCODING
response.headers.keySet must not contain CONTENT_LENGTH
response.body must beLeft("abcdefghi")
}
"Strip malformed cookies" in withServer(
Results.Ok
) { port =>
val response = BasicHttpClient.makeRequests(port)(
BasicRequest("GET", "/", "HTTP/1.1", Map("Cookie" -> """£"""), "")
)(0)
response.status must_== 200
response.body must beLeft
}
"reject HTTP 1.0 requests for chunked results" in withServer(
Results.Ok.chunked(Enumerator("a", "b", "c"))
) { port =>
val response = BasicHttpClient.makeRequests(port)(
BasicRequest("GET", "/", "HTTP/1.0", Map(), "")
)(0)
response.status must_== HTTP_VERSION_NOT_SUPPORTED
response.body must beLeft("The response to this request is chunked and hence requires HTTP 1.1 to be sent, but this is a HTTP 1.0 request.")
}
"return a 500 error on response with null header" in withServer(
Results.Ok("some body").withHeaders("X-Null" -> null)
) { port =>
val response = BasicHttpClient.makeRequests(port)(
BasicRequest("GET", "/", "HTTP/1.1", Map(), "")
)(0)
response.status must_== 500
response.body must beLeft("")
}
"return a 400 error on invalid URI" in withServer(
Results.Ok
) { port =>
val response = BasicHttpClient.makeRequests(port)(
BasicRequest("GET", "/[", "HTTP/1.1", Map(), "")
)(0)
response.status must_== 400
response.body must beLeft
}
"not send empty chunks before the end of the enumerator stream" in makeRequest(
Results.Ok.chunked(Enumerator("foo", "", "bar"))
) { response =>
response.header(TRANSFER_ENCODING) must beSome("chunked")
response.header(CONTENT_LENGTH) must beNone
response.body must_== "foobar"
}
"return a 400 error on Header value contains a prohibited character" in withServer(
Results.Ok
) { port =>
forall(List(
"aaa" -> "bbb\\fccc",
"ddd" -> "eee\\u000bfff"
)) { header =>
val response = BasicHttpClient.makeRequests(port)(
BasicRequest("GET", "/", "HTTP/1.1", Map(header), "")
)(0)
response.status must_== 400
response.body must beLeft
}
}
"split Set-Cookie headers" in {
import play.api.mvc.Cookie
val aCookie = Cookie("a", "1")
val bCookie = Cookie("b", "2")
val cCookie = Cookie("c", "3")
makeRequest {
Results.Ok.withCookies(aCookie, bCookie, cCookie)
} { response =>
response.allHeaders.get(SET_COOKIE) must beSome.like {
case rawCookieHeaders =>
val decodedCookieHeaders: Set[Set[Cookie]] = rawCookieHeaders.map { headerValue =>
Cookies.decode(headerValue).to[Set]
}.to[Set]
decodedCookieHeaders must_== (Set(Set(aCookie), Set(bCookie), Set(cCookie)))
}
}
}
}
}
|
jyotikamboj/container
|
pf-framework/src/play-integration-test/src/test/scala/play/it/http/ScalaResultsHandlingSpec.scala
|
Scala
|
mit
| 10,568 |
package lila.relay
import akka.actor.{ Actor, ActorRef, Props }
import akka.io.{ IO, Tcp }
import akka.util.ByteString
import java.net.InetSocketAddress
private[relay] final class Telnet(
remote: InetSocketAddress,
listener: ActorRef) extends Actor {
import Tcp._
import context.system
IO(Tcp) ! Connect(remote, options = List(
SO.TcpNoDelay(false)
))
var bufferUntil = none[String]
val buffer = new collection.mutable.StringBuilder
def receive = {
case CommandFailed(_: Connect) =>
listener ! "connect failed"
context stop self
case Connected(remote, local) =>
val connection = sender()
connection ! Register(self)
listener ! Telnet.Connection({ str =>
// println(s"TELNET> $str")
connection ! Write(ByteString(s"$str\\n"))
})
context become {
case CommandFailed(w: Write) =>
// O/S buffer was full
listener ! Telnet.WriteFailed
case Received(data) =>
val chunk = data decodeString "UTF-8"
bufferUntil match {
case None => listener ! Telnet.In(chunk)
case Some(eom) =>
buffer append chunk
if (buffer endsWith eom) {
listener ! Telnet.In(buffer.toString)
buffer.clear()
}
}
case Telnet.BufferUntil(str) =>
buffer.clear()
bufferUntil = str
case "close" =>
connection ! Close
case _: ConnectionClosed =>
listener ! Telnet.Close
context stop self
}
}
}
object Telnet {
case class In(data: String) {
lazy val lines: List[String] = data.split(Array('\\r', '\\n')).toList.map(_.trim).filter(_.nonEmpty)
def last: Option[String] = lines.lastOption
}
case class Connection(send: String => Unit)
case class BufferUntil(str: Option[String])
case object ConnectFailed
case object WriteFailed
case object Close
}
|
Enigmahack/lila
|
modules/relay/src/main/Telnet.scala
|
Scala
|
mit
| 1,967 |
package uk.gov.dvla.vehicles.presentation.common.models
import play.api.data.Forms.{mapping, nonEmptyText}
case class ValtechInputDigitsModel(mileage: String)
object ValtechInputDigitsModel {
object Form {
final val MileageId = "mileage"
final val Mapping = mapping(
MileageId -> nonEmptyText()
)(ValtechInputDigitsModel.apply)(ValtechInputDigitsModel.unapply)
}
}
|
dvla/vehicles-presentation-common
|
common-test/app/uk/gov/dvla/vehicles/presentation/common/models/ValtechInputDigitsModel.scala
|
Scala
|
mit
| 393 |
package sampler.aggr.emp
import delta.util.ReflectiveDecoder
import sampler._
import scuff.Codec
import scuff.json._, JsVal._
trait JsonCodec
extends EmpEventHandler {
this: ReflectiveDecoder[_, String] =>
type Return = JSON
private val IsoDate = """(\\d{4})-(\\d{2})-(\\d{2})""".r
private val EmployeeRegisteredCodecV1 = new Codec[EmployeeRegistered, JSON] {
def encode(evt: EmployeeRegistered): String = s"""{
"name": "${evt.name}",
"dob": "${evt.dob.toString}",
"ssn": "${evt.soch}",
"title": "${evt.title}",
"salary": ${evt.annualSalary}
}"""
def decode(json: String): EmployeeRegistered = {
val jsObj = JsVal.parse(json).asObj
val IsoDate(year, month, day) = jsObj.dob.asStr.value
new EmployeeRegistered(
name = jsObj.name.asStr,
dob = new MyDate(year.toShort, month.toByte, day.toByte),
soch = jsObj.ssn.asStr,
title = jsObj.title.asStr,
annualSalary = jsObj.salary.asNum)
}
}
def on(evt: EmployeeRegistered): String = EmployeeRegisteredCodecV1.encode(evt)
def onEmployeeRegistered(encoded: Encoded): EmployeeRegistered = encoded.version match {
case 1 => EmployeeRegisteredCodecV1.decode(encoded.data)
}
def on(evt: EmployeeSalaryChange): String = evt.newSalary.toString
def onEmployeeSalaryChange(encoded: Encoded): EmployeeSalaryChange = encoded.version match {
case 1 => new EmployeeSalaryChange(newSalary = encoded.data.toInt)
}
def on(evt: EmployeeTitleChange): String = JsStr(evt.newTitle).toJson
def onEmployeeTitleChange(encoded: Encoded): EmployeeTitleChange = encoded.version match {
case 1 => new EmployeeTitleChange(newTitle = JsVal.parse(encoded.data).asStr)
}
}
|
nilskp/delta
|
src/test/scala/sampler/aggr/emp/JsonCodec.scala
|
Scala
|
mit
| 1,734 |
import sbt._
import sbt.Keys._
import bintray.Plugin._
import bintray.Keys._
object Build extends Build {
val customBintraySettings = bintrayPublishSettings ++ Seq(
packageLabels in bintray := Seq("json"),
bintrayOrganization in bintray := Some("blackboxsociety"),
repository in bintray := "releases"
)
val root = Project("root", file("."))
.settings(customBintraySettings: _*)
.settings(
name := "blackbox-json",
organization := "com.blackboxsociety",
version := "0.2.0",
scalaVersion := "2.11.0",
licenses += ("MIT", url("http://opensource.org/licenses/MIT")),
scalacOptions in Test ++= Seq("-Yrangepos"),
resolvers ++= Seq("snapshots", "releases").map(Resolver.sonatypeRepo),
libraryDependencies += "org.scala-lang.modules" %% "scala-parser-combinators" % "1.0.1",
libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.0.6",
libraryDependencies += "org.specs2" %% "specs2" % "2.3.11" % "test"
)
}
|
blackboxsociety/blackbox-json
|
project/Build.scala
|
Scala
|
mit
| 1,094 |
package scwilio
import op._
import xml._
import dispatch._
object Twilio {
var accountSid = System.getenv("SCWILIO_ACCOUNT_SID")
var authToken = System.getenv("SCWILIO_AUTH_TOKEN")
val API_VERSION = "2010-04-01"
lazy val restClient = new RestClient(accountSid, authToken)
lazy val client = new TwilioClient(restClient)
def apply() = client
def apply(accountSid: String, authToken: String) = new TwilioClient(new RestClient(accountSid, authToken))
}
/**
* Holds configuration data for the Twilio API.
*/
trait HttpConfig {
val accountSid: String
val authToken: String
lazy val TWILIO_BASE = :/("api.twilio.com").secure as (accountSid, authToken)
lazy val API_BASE = TWILIO_BASE / Twilio.API_VERSION / "Accounts" / accountSid
val http = new Http
}
/**
* Low level client for the Twilio API. Works with TwilioOperation instances.
*/
class RestClient(val accountSid: String, val authToken: String) extends HttpConfig with util.Logging {
import scala.xml._
def execute[R](op: TwilioOperation[R]) : R = {
val req = op.request(this)
log.debug("Sending req {}", req)
try {
http(req <> { res =>
log.debug("Twilio response:\\n{}", res)
op.parser.apply(res)
})
} catch {
case e : dispatch.StatusCode =>
val res: Elem = XML.loadString(e.contents)
if (!(res \\ "RestException").isEmpty) {
throw RestClient.parseException(res)
} else {
throw e
}
}
}
}
object RestClient {
def parseException(res: NodeSeq) = {
val error = res \\ "RestException"
new TwilioException((error \\ "Code").text, (error \\ "Message").text)
}
}
/**
* Client service interface hiding REST operation details.
*/
class TwilioClient(private val restClient: RestClient) {
def dial(from: Phonenumber,
to: Phonenumber,
onConnect: Option[String],
onEnd: Option[String] = None,
timeout: Int = 30,
machineDetection: Boolean = false
) : CallInfo = restClient.execute(DialOperation(from, to, onConnect, onEnd, timeout, machineDetection))
def sendSms(from: Phonenumber,
to: Phonenumber,
body: String) : SmsInfo = restClient.execute(SendSms(from, to, body))
/**
* List all purchased incoming numbers.
*/
def listIncomingNumbers() = restClient.execute(ListIncomingNumbers)
/**
* List incoming numbers available for purchase.
*/
def listAvailableNumbers(countryCode: String) = restClient.execute(ListAvailableNumbers(countryCode))
def updateIncomingNumberConfig(sid: String, config: IncomingNumberConfig) = restClient.execute(UpdateIncomingNumberConfig(sid, config))
def getConferenceState(cid: String) = {
val (state, uris) = restClient.execute(GetConferenceParticipantURIs(cid))
val participants = uris.map ( uri => restClient.execute(GetConferenceParticipantInfo(uri)) )
ConferenceState(cid, state, participants)
}
}
class TwilioException(val code: String, val message: String) extends RuntimeException("Error code " + code + ". " + message)
|
daggerrz/Scwilio
|
core/src/main/scala/scwilio/twilio.scala
|
Scala
|
mit
| 3,093 |
package scala.actors.io
import org.testng.annotations.{Test, BeforeMethod}
import org.scalatest.testng.TestNGSuite
import org.scalatest.prop.Checkers
import org.scalacheck.Arbitrary
import org.scalacheck.Arbitrary._
import org.scalacheck.Gen
import org.scalacheck.Prop._
import org.scalatest._
import scala.actors.controlflow._
import scala.actors.controlflow.ControlFlow._
import scala.binary._
import java.net.InetSocketAddress
import java.nio.channels._
import java.nio.ByteBuffer
/**
* Tests for io classes.
*
* @author <a href="http://www.richdougherty.com/">Rich Dougherty</a>
*/
class IoSuite extends TestNGSuite with Checkers {
implicit def arbBinary: Arbitrary[Binary] = Arbitrary {
for (bytes <- Arbitrary.arbitrary[Array[Byte]]) yield Binary.fromSeq(bytes)
}
@Test
def testSocket = {
val binary = Binary.fromString("Hello ") ++ Binary.fromString("world!")
val address = new InetSocketAddress("localhost", 12345)
val result = { fc: FC[Binary] =>
import fc.implicitThr
val selector = new AsyncSelector
val ssc = ServerSocketChannel.open
ssc.configureBlocking(false)
val ss = ssc.socket
ss.setReuseAddress(true)
ss.bind(address)
val rssc = new AsyncServerSocketChannel(ssc, selector)
Actor.actor {
println("Accepting")
rssc.asyncAccept { sc1: SocketChannel =>
sc1.configureBlocking(false)
val rsc1 = new AsyncSocketChannel(sc1, selector)
println("Sending: " + new String(binary.toArray))
rsc1.asyncWrite(binary) { () => println("Closing socket") ; sc1.close }
println("Closing server socket")
ssc.close
}
}
Actor.actor {
val sc2: SocketChannel = SocketChannel.open
sc2.configureBlocking(false)
val rsc2 = new AsyncSocketChannel(sc2, selector)
println("Connecting")
rsc2.asyncConnect(address) { () => println("Receiving") ; rsc2.asyncReadAll(fc) }
}
Actor.exit
}.toFunction.apply
println("Received: " + new String(result.toArray))
assert(result == binary)
}
}
|
bingoyang/scala-otp
|
io/src/test/scala/scala/actors/io/IoSuite.scala
|
Scala
|
bsd-3-clause
| 2,122 |
/* *\\
** Squants **
** **
** Scala Quantities and Units of Measure Library and DSL **
** (c) 2013-2015, Gary Keorkunian **
** **
\\* */
package squants
/**
* Base class for creating objects to manage quantities as Numeric.
*
* One limitation is the `times` operation which is not supported by every quantity type
*
* @tparam A Quantity type
*/
abstract class AbstractQuantityNumeric[A <: Quantity[A]](val unit: UnitOfMeasure[A] with PrimaryUnit) extends Numeric[A] {
def plus(x: A, y: A) = x + y
def minus(x: A, y: A) = x - y
/**
* `times` is not a supported Numeric operation for Quantities.
* It is not possible to multiply a dimensional quantity by a like quantity and get another like quantity.
* Applying this class in a way that uses this method will result in an UnsupportedOperationException being thrown.
*
* @param x Quantity[A]
* @param y Quantity[A]
* @return
* @throws scala.UnsupportedOperationException for most types
*/
def times(x: A, y: A): A = throw new UnsupportedOperationException("Numeric.times not supported for Quantities")
def negate(x: A) = -x
def fromInt(x: Int) = unit(x)
def toInt(x: A) = x.to(unit).toInt
def toLong(x: A) = x.to(unit).toLong
def toFloat(x: A) = x.to(unit).toFloat
def toDouble(x: A) = x.to(unit)
def compare(x: A, y: A) = if (x.to(unit) > y.to(unit)) 1 else if (x.to(unit) < y.to(unit)) -1 else 0
// As there's no direct access to the Dimension (which has parseString) from a UnitOfMeasure,
// we create a dummy instance here and access its dimension member
def parseString(str: String): Option[A] = unit(0).dimension.parseString(str).toOption
}
|
garyKeorkunian/squants
|
shared/src/main/scala/squants/AbstractQuantityNumeric.scala
|
Scala
|
apache-2.0
| 2,047 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.plan.nodes.datastream
import org.apache.calcite.plan.{RelOptCluster, RelTraitSet}
import org.apache.calcite.rel.RelNode
import org.apache.calcite.rel.core.Calc
import org.apache.calcite.rex.{RexCall, RexInputRef, RexLocalRef, RexNode, RexProgram}
import org.apache.flink.api.java.typeutils.RowTypeInfo
import org.apache.flink.streaming.api.datastream.DataStream
import org.apache.flink.streaming.api.functions.ProcessFunction
import org.apache.flink.streaming.api.operators.OneInputStreamOperator
import org.apache.flink.table.api.StreamQueryConfig
import org.apache.flink.table.calcite.FlinkTypeFactory
import org.apache.flink.table.codegen.FunctionCodeGenerator
import org.apache.flink.table.functions.python.PythonFunctionInfo
import org.apache.flink.table.plan.nodes.CommonPythonCalc
import org.apache.flink.table.plan.nodes.datastream.DataStreamPythonCalc.PYTHON_SCALAR_FUNCTION_OPERATOR_NAME
import org.apache.flink.table.plan.schema.RowSchema
import org.apache.flink.table.planner.StreamPlanner
import org.apache.flink.table.runtime.CRowProcessRunner
import org.apache.flink.table.runtime.types.{CRow, CRowTypeInfo}
import org.apache.flink.table.types.logical.RowType
import org.apache.flink.table.types.utils.TypeConversions
import scala.collection.JavaConversions._
/**
* RelNode for Python ScalarFunctions.
*/
class DataStreamPythonCalc(
cluster: RelOptCluster,
traitSet: RelTraitSet,
input: RelNode,
inputSchema: RowSchema,
schema: RowSchema,
calcProgram: RexProgram,
ruleDescription: String)
extends DataStreamCalcBase(
cluster,
traitSet,
input,
inputSchema,
schema,
calcProgram,
ruleDescription)
with CommonPythonCalc {
override def copy(traitSet: RelTraitSet, child: RelNode, program: RexProgram): Calc = {
new DataStreamPythonCalc(
cluster,
traitSet,
child,
inputSchema,
schema,
program,
ruleDescription)
}
private lazy val pythonRexCalls = calcProgram.getProjectList
.map(calcProgram.expandLocalRef)
.filter(_.isInstanceOf[RexCall])
.map(_.asInstanceOf[RexCall])
.toArray
private lazy val forwardedFields: Array[Int] = calcProgram.getProjectList
.map(calcProgram.expandLocalRef)
.filter(_.isInstanceOf[RexInputRef])
.map(_.asInstanceOf[RexInputRef].getIndex)
.toArray
private lazy val (pythonUdfInputOffsets, pythonFunctionInfos) =
extractPythonScalarFunctionInfos(pythonRexCalls)
private lazy val resultProjectList: Array[RexNode] = {
var idx = 0
calcProgram.getProjectList
.map(calcProgram.expandLocalRef)
.map {
case pythonCall: RexCall =>
val inputRef = new RexInputRef(forwardedFields.length + idx, pythonCall.getType)
idx += 1
inputRef
case node => node
}
.toArray
}
override def translateToPlan(
planner: StreamPlanner,
queryConfig: StreamQueryConfig): DataStream[CRow] = {
val config = planner.getConfig
val inputDataStream =
getInput.asInstanceOf[DataStreamRel].translateToPlan(planner, queryConfig)
val inputParallelism = inputDataStream.getParallelism
val pythonOperatorResultTypeInfo = new RowTypeInfo(
forwardedFields.map(inputSchema.fieldTypeInfos.get(_)) ++
pythonRexCalls.map(node => FlinkTypeFactory.toTypeInfo(node.getType)): _*)
// Constructs the Python operator
val pythonOperatorInputRowType = TypeConversions.fromLegacyInfoToDataType(
inputSchema.typeInfo).getLogicalType.asInstanceOf[RowType]
val pythonOperatorOutputRowType = TypeConversions.fromLegacyInfoToDataType(
pythonOperatorResultTypeInfo).getLogicalType.asInstanceOf[RowType]
val pythonOperator = getPythonScalarFunctionOperator(
pythonOperatorInputRowType, pythonOperatorOutputRowType, pythonUdfInputOffsets)
val pythonDataStream = inputDataStream
.transform(
calcOpName(calcProgram, getExpressionString),
CRowTypeInfo(pythonOperatorResultTypeInfo),
pythonOperator)
// keep parallelism to ensure order of accumulate and retract messages
.setParallelism(inputParallelism)
val generator = new FunctionCodeGenerator(
config, false, pythonOperatorResultTypeInfo)
val genFunction = generateFunction(
generator,
ruleDescription,
schema,
resultProjectList,
None,
config,
classOf[ProcessFunction[CRow, CRow]])
val processFunc = new CRowProcessRunner(
genFunction.name,
genFunction.code,
CRowTypeInfo(schema.typeInfo))
pythonDataStream
.process(processFunc)
.name(calcOpName(calcProgram, getExpressionString))
// keep parallelism to ensure order of accumulate and retract messages
.setParallelism(inputParallelism)
}
private[flink] def getPythonScalarFunctionOperator(
inputRowType: RowType,
outputRowType: RowType,
udfInputOffsets: Array[Int]) = {
val clazz = Class.forName(PYTHON_SCALAR_FUNCTION_OPERATOR_NAME)
val ctor = clazz.getConstructor(
classOf[Array[PythonFunctionInfo]],
classOf[RowType],
classOf[RowType],
classOf[Array[Int]],
classOf[Array[Int]])
ctor.newInstance(
pythonFunctionInfos,
inputRowType,
outputRowType,
udfInputOffsets,
forwardedFields)
.asInstanceOf[OneInputStreamOperator[CRow, CRow]]
}
}
object DataStreamPythonCalc {
val PYTHON_SCALAR_FUNCTION_OPERATOR_NAME =
"org.apache.flink.table.runtime.operators.python.PythonScalarFunctionOperator"
}
|
mbode/flink
|
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/plan/nodes/datastream/DataStreamPythonCalc.scala
|
Scala
|
apache-2.0
| 6,401 |
sealed trait JState
trait Start extends JState
trait Complete extends JState
trait OpenArray[E <: JState] extends JState
trait OpenObject[E <: JState] extends JState
|
arnolddevos/phantom_types
|
json1.scala
|
Scala
|
mit
| 167 |
package leo
package datastructures
package blackboard.scheduler
import leo.datastructures.blackboard._
import leo.datastructures.context.Context
import leo.modules.output.{SZS_Theorem, StatusSZS}
import scala.collection.mutable
import java.util.concurrent.Executors
/**
* Singleton Scheduler
*/
object Scheduler {
private[scheduler] var s : Scheduler = null
private var n : Int = 5
/**
* Defines a scheduler with numberOfThreads Threads or
* a simple get for the singleton.
*
* @param numberOfThreads - Number of Threads
* @return Singleton Scheduler
*/
def apply(numberOfThreads : Int) : Scheduler = {
n = numberOfThreads
if (s == null) {
s = new SchedulerImpl(numberOfThreads)
s.start()
}
return s
}
/**
* Creates a Scheduler for 5 Threads or a get for the singleton,
* if the scheduler already exists.
* @return
*/
def apply() : Scheduler = {
apply(n)
}
def working() : Boolean = {
if (s == null) return false
// s exists
s.working()
}
}
/**
* Scheduler Interface
*/
trait Scheduler {
def isTerminated() : Boolean
/**
* Terminate all working processes.
*/
def killAll() : Unit
/**
* Tells the Scheduler to continue to Work
*/
def signal() : Unit
/**
* Pauses the execution of the scheduler.
*/
def pause() : Unit
/**
* Performs one round of auction
*/
def step() : Unit
def clear() : Unit
protected[scheduler] def start()
def working() : Boolean
}
// TODO IF GROWS MOVE TO IMPL PACKAGE
/**
* <p>
* Central Object for coordinating the ThreadPool responsible for
* executing the Agents
* </p>
* @author Max Wisniewski
* @since 5/15/14
*/
protected[scheduler] class SchedulerImpl (numberOfThreads : Int) extends Scheduler {
import leo.agents._
private var exe = Executors.newFixedThreadPool(numberOfThreads)
private val s : SchedulerRun = new SchedulerRun()
private val w : Writer = new Writer()
private var sT : Thread = null
private var sW : Thread = null
protected val curExec : mutable.Set[Task] = new mutable.HashSet[Task] with mutable.SynchronizedSet[Task]
def working() : Boolean = {
this.synchronized(
return w.work || curExec.nonEmpty
)
}
override def isTerminated() : Boolean = endFlag
def signal() : Unit = s.synchronized{
pauseFlag = false
s.notifyAll()
}
def step() : Unit = s.synchronized{s.notifyAll()}
// def toWork(a : Agent) : Unit = exe.submit(new Runnable {
// override def run(): Unit = if (a.guard()) a.apply()
// })
def killAll() : Unit = s.synchronized{
endFlag = true
pauseFlag = false
ExecTask.put(ExitResult,ExitTask) // For the writer to exit, if he is waiting for a result
exe.shutdownNow()
curExec.clear()
AgentWork.executingAgents() foreach(_.kill())
AgentWork.clear()
sT.interrupt()
s.notifyAll()
curExec.clear()
// Scheduler.s = null
}
var pauseFlag = true
var endFlag = false
def pause() : Unit = {s.synchronized(pauseFlag = true);
// println("Scheduler paused.")
}
def clear() : Unit = {
pause()
curExec.clear()
AgentWork.executingAgents() foreach(_.kill())
AgentWork.clear()
}
protected[scheduler] def start() {
// println("Scheduler started.")
sT = new Thread(s)
sT.start() // Start Scheduler
sW = new Thread(w)
sW.start() // Start writer
}
/**
* Takes Tasks from the Queue and Executes it.
*/
private class SchedulerRun extends Runnable {
override def run(): Unit = while (true) {
// Check Status TODO Try catch
this.synchronized {
if (pauseFlag) {
// If is paused wait
Out.trace("Scheduler paused.")
this.wait()
Out.trace("Scheduler is commencing.")
}
if (endFlag) return // If is ended quit
}
// Blocks until a task is available
val tasks = Blackboard().getTask
try {
for ((a, t) <- tasks) {
this.synchronized {
curExec.add(t)
if (endFlag) return // Savely exit
if (pauseFlag) {
Out.trace("Scheduler paused.")
this.wait()
Out.trace("Scheduler is commencing.")
} // Check again, if waiting took to long
// Execute task
if (!exe.isShutdown) exe.submit(new GenAgent(a, t))
}
}
} catch {
case e : InterruptedException => Out.info("Scheduler interrupted. Quiting now"); return
}
}
}
/**
* Writes a result back to the blackboard
*/
private class Writer extends Runnable{
var work : Boolean = false
override def run(): Unit = while(!endFlag) {
val (result,task) = ExecTask.get()
if(endFlag) return // Savely exit
if(curExec.contains(task)) {
work = true
// Update blackboard
var newF : Set[FormulaStore] = Set()
var closed : List[(Context,StatusSZS)] = List()
result.newFormula().foreach { f =>
val up = f.newOrigin(task.writeSet().union(task.readSet()).toList, task.name)
val ins = Blackboard().addNewFormula(up)
if (ins) {
// Keep track of new Formulas
newF = newF + up
//Out.trace(s"[Writer]:\\n [$task =>]:\\n Füge Formel $up ein.")
}
}
result.removeFormula().foreach(Blackboard().removeFormula(_))
result.updateFormula().foreach { case (oF, nF) =>
Blackboard().removeFormula(oF)
val up = nF.newOrigin(task.writeSet().union(task.readSet()).toList, task.name)
val ins = Blackboard().addNewFormula(up)
if (ins) {
newF = newF + up // Keep track of new formulas
//Out.trace(s"[Writer]:\\n [$task =>]:\\n Füge Formel $up ein.")
}
}
result.updateStatus().foreach{ case (c,s) =>
Blackboard().forceStatus(c)(s)
}
// Removing Task from Taskset (Therefor remove locks)
curExec.remove(task)
Blackboard().finishTask(task)
// Notify changes
// ATM only New and Updated Formulas
Blackboard().filterAll({a =>
newF.foreach{ f => a.filter(FormulaEvent(f)) // If the result was new, everyone has to be informed
}
result.updateStatus.foreach{case (c,s) => a.filter(StatusEvent(c,s))}
result.updatedContext().foreach{c => a.filter(ContextEvent(c))}
//task.writeSet().filter{t => !newF.exists(_.cong(t))}.foreach{f => a.filter(FormulaEvent(f))}
(task.contextWriteSet() ++ result.updatedContext()).foreach{c => a.filter(ContextEvent(c))}
})
}
work = false
Blackboard().forceCheck()
}
}
/**
* The Generic Agent runs an agent on a task and writes the Result Back, such that it can be updated to the blackboard.
* @param a - Agent that will be executed
* @param t - Task on which the agent runs.
*/
private class GenAgent(a : Agent, t : Task) extends Runnable{
override def run() {
AgentWork.inc(a)
ExecTask.put(a.run(t),t)
AgentWork.dec(a)
//Out.trace("Executed :\\n "+t.toString+"\\n Agent: "+a.name)
}
}
/**
* Producer Consumer Implementation for the solutions of the current executing Threads (Agents)
* and the Task responsible for writing the changes to the Blackboard.
*
* // TODO Use of Java Monitors might work with ONE Writer
*/
private object ExecTask {
private val results : mutable.Set[(Result,Task)] = new mutable.HashSet[(Result,Task)] with mutable.SynchronizedSet[(Result,Task)]
def get() : (Result,Task) = this.synchronized {
while (true) {
try {
while(results.isEmpty) this.wait()
val r = results.head
results.remove(r)
return r
} catch {
// If got interrupted exception, restore status and continue
case e: InterruptedException => Thread.currentThread().interrupt()
// Any other exception will be rethrown
case e : Exception => throw e
}
}
null // Should never be reached
}
def put(r : Result, t : Task) {
this.synchronized{
results.add((r,t)) // Must not be synchronized, but maybe it should
this.notifyAll()
}
}
}
private object AgentWork {
protected val agentWork : mutable.Map[Agent, Int] = new mutable.HashMap[Agent, Int]()
/**
* Increases the amount of work of an agent by 1.
*
* @param a - Agent that executes a task
* @return the updated number of task of the agent.
*/
def inc(a : Agent) : Int = synchronized(agentWork.get(a) match {
case Some(v) => agentWork.update(a,v+1); return v+1
case None => agentWork.put(a,1); return 1
})
def dec(a : Agent) : Int = synchronized(agentWork.get(a) match {
case Some(v) if v > 2 => agentWork.update(a,v-1); return v-1
case Some(v) if v == 1 => agentWork.remove(a); return 0
case _ => return 0 // Possibly error, but occurs on regular termination, so no output.
})
def executingAgents() : Iterable[Agent] = synchronized(agentWork.keys)
def clear() = synchronized(agentWork.clear())
}
/**
* Marker for the writer to end itself
*/
private object ExitResult extends Result {
override def newFormula(): Set[FormulaStore] = ???
override def updateFormula(): Map[FormulaStore, FormulaStore] = ???
override def removeFormula(): Set[FormulaStore] = ???
override def updatedContext(): Set[Context] = ???
override def updateStatus(): List[(Context, StatusSZS)] = ???
}
/**
* Empty marker for the Writer to end itself
*/
private object ExitTask extends Task {
override def readSet(): Set[FormulaStore] = Set.empty
override def writeSet(): Set[FormulaStore] = Set.empty
override def bid(budget : Double) : Double = 1
override def name: String = ???
override def pretty: String = ???
}
}
|
cbenzmueller/LeoPARD
|
src/main/scala/leo/datastructures/blackboard/scheduler/Scheduler.scala
|
Scala
|
bsd-3-clause
| 10,103 |
// Copyright (C) 2014 - 2016 ENSIME Contributors
// Licence: Apache-2.0
package org.ensime
import scala.util.Properties.{versionNumberString => sbtScalaVersion}
import CoursierHelper._
import EnsimeCoursierKeys._
import EnsimeKeys._
import sbt._
import sbt.Keys._
object EnsimeCoursierKeys {
// can't include Coursier keys in our public API because it is shaded
val ensimeRepositoryUrls = settingKey[Seq[String]](
"The maven repositories to download the scala compiler, ensime-server and ensime-plugins jars"
)
def addEnsimeScalaPlugin(module: ModuleID, args: String = ""): Seq[Setting[_]] = {
ensimeScalacOptions += {
val jar = resolveSingleJar(module, ensimeScalaVersion.value, ensimeRepositoryUrls.value)
s"-Xplugin:${jar.getCanonicalFile}${args}"
}
}
}
/**
* Defines the tasks that resolve all the jars needed to start the
* ensime-server.
*
* Intentionally separated from EnsimePlugin to allow corporate users
* to avoid a dependency on coursier and provide hard coded jar paths.
*/
object EnsimeCoursierPlugin extends AutoPlugin {
override def requires = EnsimePlugin
override def trigger = allRequirements
val autoImport = EnsimeCoursierKeys
import EnsimeKeys._
override lazy val buildSettings = Seq(
ensimeRepositoryUrls := Seq(
// intentionally not using the ivy cache because it's very unreliable
"https://repo1.maven.org/maven2/"
),
ensimeScalaJars := resolveScalaJars(scalaOrganization.value, ensimeScalaVersion.value, ensimeRepositoryUrls.value),
ensimeScalaProjectJars := resolveScalaJars("org.scala-lang", sbtScalaVersion, ensimeRepositoryUrls.value),
ensimeServerJars := resolveEnsimeJars(scalaOrganization.value, ensimeScalaVersion.value, ensimeServerVersion.value, ensimeRepositoryUrls.value),
ensimeServerProjectJars := resolveEnsimeJars("org.scala-lang", sbtScalaVersion, ensimeProjectServerVersion.value, ensimeRepositoryUrls.value)
)
}
|
ensime/ensime-sbt
|
src/main/scala/EnsimeCoursierPlugin.scala
|
Scala
|
apache-2.0
| 1,956 |
package br.unb.cic.tp1.mh.ast
import org.scalatest._
import br.unb.cic.tp1.exceptions.VariavelNaoDeclaradaException
class TesteExpLambda extends FlatSpec with Matchers {
behavior of "a lambda expression"
it should "be evaluated to Closure(x, x+1) when (x) -> x + 1" in {
val inc = new ExpLambda("x", TInt(),
ExpMatSoma(ExpRef("x"), ValorInteiro(1)))
val closure = inc.avaliar().asInstanceOf[Closure]
closure.id should be ("x")
closure.corpo should be (ExpMatSoma(ExpRef("x"), ValorInteiro(1)))
}
}
|
PeterTowers/TP1-022017
|
mhs/src/test/scala/br/unb/cic/tp1/mh/ast/TesteExpLambda.scala
|
Scala
|
mit
| 533 |
/*
* Copyright 2014 IBM Corp.
*
* 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.ibm.spark.kernel.protocol.v5.content
import com.ibm.spark.kernel.protocol.v5.KernelMessageContent
import play.api.libs.json.Json
case class HistoryReply(
// TODO: This is really (String, String, String | (String, String)), look
// TODO: into writing implicits to handle tuples
// NOTE: Currently, only handle (String, String, String)
history: List[String]
) extends KernelMessageContent {
override def content : String =
Json.toJson(this)(HistoryReply.historyReplyWrites).toString
}
object HistoryReply {
implicit val historyReplyReads = Json.reads[HistoryReply]
implicit val historyReplyWrites = Json.writes[HistoryReply]
}
|
bpburns/spark-kernel
|
protocol/src/main/scala/com/ibm/spark/kernel/protocol/v5/content/HistoryReply.scala
|
Scala
|
apache-2.0
| 1,254 |
/*
* The block under qual$1 must be owned by it.
* In the sample bug, the first default arg generates x$4,
* the second default arg generates qual$1, hence the maximal
* minimization.
*
<method> <triedcooking> def model: C.this.M = {
val qual$1: C.this.M = scala.Option.apply[C.this.M]({
val x$1: lang.this.String("foo") = "foo";
val x$2: String = C.this.M.apply$default$2("foo");
C.this.M.apply("foo")(x$2)
}).getOrElse[C.this.M]({
val x$3: lang.this.String("bar") = "bar";
val x$4: String = C.this.M.apply$default$2("bar");
C.this.M.apply("bar")(x$4)
});
val x$5: lang.this.String("baz") = "baz";
val x$6: String = qual$1.copy$default$2("baz");
qual$1.copy("baz")(x$6)
}
*/
class C {
case class M(currentUser: String = "anon")(val message: String = "empty")
val m = M("foo")()
// reported
//def model = Option(M("foo")()).getOrElse(M("bar")()).copy(currentUser = "")()
// the bug
def model = Option(m).getOrElse(M("bar")()).copy("baz")("empty")
// style points for this version
def modish = ((null: Option[M]) getOrElse new M()()).copy()("empty")
// various simplifications are too simple
case class N(currentUser: String = "anon")
val n = N("fun")
def nudel = Option(n).getOrElse(N()).copy()
}
object Test {
def main(args: Array[String]) {
val c = new C
println(c.model.currentUser)
println(c.model.message)
}
}
/*
symbol value x$4$1 does not exist in badcopy.C.model
at scala.reflect.internal.SymbolTable.abort(SymbolTable.scala:45)
at scala.tools.nsc.Global.abort(Global.scala:202)
at scala.tools.nsc.backend.icode.GenICode$ICodePhase.liftedTree2$1(GenICode.scala:998)
at scala.tools.nsc.backend.icode.GenICode$ICodePhase.scala$tools$nsc$backend$icode$GenICode$ICodePhase$$genLoad(GenICode.scala:992)
*/
|
loskutov/intellij-scala
|
testdata/scalacTests/pos/t5720-ownerous.scala
|
Scala
|
apache-2.0
| 1,830 |
package GUI
import GUIAbstractComponent._
abstract class GUIAbstractGeneratorToolkit {
type ImplFrame
var mainFrame : ImplFrame
protected def init(frame : Frame)
final def generateFrame(frame : Frame) : ImplFrame = {
init(frame)
return mainFrame
}
}
|
DoumbiaAmadou/FrameworkVote
|
src/GUI/GUIAbstractGeneratorToolkit.scala
|
Scala
|
mit
| 275 |
import sbt._
import com.typesafe.config._
object BuildConf extends Plugin {
lazy val conf = ConfigFactory.parseFile(new File("conf/application.conf"))
def getString(key: String) = conf.getString(key)
}
|
moatra/playground
|
project/BuildConf.scala
|
Scala
|
mit
| 208 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kafka.log
import org.junit.Assert._
import java.util.concurrent.atomic._
import org.junit.{Test, After}
import kafka.utils.TestUtils
import kafka.message._
import kafka.utils.SystemTime
import scala.collection._
class LogSegmentTest {
val segments = mutable.ArrayBuffer[LogSegment]()
/* create a segment with the given base offset */
def createSegment(offset: Long): LogSegment = {
val msFile = TestUtils.tempFile()
val ms = new FileMessageSet(msFile)
val idxFile = TestUtils.tempFile()
idxFile.delete()
val idx = new OffsetIndex(idxFile, offset, 1000)
val seg = new LogSegment(ms, idx, offset, 10, 0, SystemTime)
segments += seg
seg
}
/* create a ByteBufferMessageSet for the given messages starting from the given offset */
def messages(offset: Long, messages: String*): ByteBufferMessageSet = {
new ByteBufferMessageSet(compressionCodec = NoCompressionCodec,
offsetCounter = new AtomicLong(offset),
messages = messages.map(s => new Message(s.getBytes)):_*)
}
@After
def teardown() {
for(seg <- segments) {
seg.index.delete()
seg.log.delete()
}
}
/**
* A read on an empty log segment should return null
*/
@Test
def testReadOnEmptySegment() {
val seg = createSegment(40)
val read = seg.read(startOffset = 40, maxSize = 300, maxOffset = None)
assertNull("Read beyond the last offset in the segment should be null", read)
}
/**
* Reading from before the first offset in the segment should return messages
* beginning with the first message in the segment
*/
@Test
def testReadBeforeFirstOffset() {
val seg = createSegment(40)
val ms = messages(50, "hello", "there", "little", "bee")
seg.append(50, ms)
val read = seg.read(startOffset = 41, maxSize = 300, maxOffset = None).messageSet
assertEquals(ms.toList, read.toList)
}
/**
* If we set the startOffset and maxOffset for the read to be the same value
* we should get only the first message in the log
*/
@Test
def testMaxOffset() {
val baseOffset = 50
val seg = createSegment(baseOffset)
val ms = messages(baseOffset, "hello", "there", "beautiful")
seg.append(baseOffset, ms)
def validate(offset: Long) =
assertEquals(ms.filter(_.offset == offset).toList,
seg.read(startOffset = offset, maxSize = 1024, maxOffset = Some(offset+1)).messageSet.toList)
validate(50)
validate(51)
validate(52)
}
/**
* If we read from an offset beyond the last offset in the segment we should get null
*/
@Test
def testReadAfterLast() {
val seg = createSegment(40)
val ms = messages(50, "hello", "there")
seg.append(50, ms)
val read = seg.read(startOffset = 52, maxSize = 200, maxOffset = None)
assertNull("Read beyond the last offset in the segment should give null", read)
}
/**
* If we read from an offset which doesn't exist we should get a message set beginning
* with the least offset greater than the given startOffset.
*/
@Test
def testReadFromGap() {
val seg = createSegment(40)
val ms = messages(50, "hello", "there")
seg.append(50, ms)
val ms2 = messages(60, "alpha", "beta")
seg.append(60, ms2)
val read = seg.read(startOffset = 55, maxSize = 200, maxOffset = None)
assertEquals(ms2.toList, read.messageSet.toList)
}
/**
* In a loop append two messages then truncate off the second of those messages and check that we can read
* the first but not the second message.
*/
@Test
def testTruncate() {
val seg = createSegment(40)
var offset = 40
for(i <- 0 until 30) {
val ms1 = messages(offset, "hello")
seg.append(offset, ms1)
val ms2 = messages(offset+1, "hello")
seg.append(offset+1, ms2)
// check that we can read back both messages
val read = seg.read(offset, None, 10000)
assertEquals(List(ms1.head, ms2.head), read.messageSet.toList)
// now truncate off the last message
seg.truncateTo(offset + 1)
val read2 = seg.read(offset, None, 10000)
assertEquals(1, read2.messageSet.size)
assertEquals(ms1.head, read2.messageSet.head)
offset += 1
}
}
/**
* Test truncating the whole segment, and check that we can reappend with the original offset.
*/
@Test
def testTruncateFull() {
// test the case where we fully truncate the log
val seg = createSegment(40)
seg.append(40, messages(40, "hello", "there"))
seg.truncateTo(0)
assertNull("Segment should be empty.", seg.read(0, None, 1024))
seg.append(40, messages(40, "hello", "there"))
}
/**
* Test that offsets are assigned sequentially and that the nextOffset variable is incremented
*/
@Test
def testNextOffsetCalculation() {
val seg = createSegment(40)
assertEquals(40, seg.nextOffset)
seg.append(50, messages(50, "hello", "there", "you"))
assertEquals(53, seg.nextOffset())
}
/**
* Test that we can change the file suffixes for the log and index files
*/
@Test
def testChangeFileSuffixes() {
val seg = createSegment(40)
val logFile = seg.log.file
val indexFile = seg.index.file
seg.changeFileSuffixes("", ".deleted")
assertEquals(logFile.getAbsolutePath + ".deleted", seg.log.file.getAbsolutePath)
assertEquals(indexFile.getAbsolutePath + ".deleted", seg.index.file.getAbsolutePath)
assertTrue(seg.log.file.exists)
assertTrue(seg.index.file.exists)
}
/**
* Create a segment with some data and an index. Then corrupt the index,
* and recover the segment, the entries should all be readable.
*/
@Test
def testRecoveryFixesCorruptIndex() {
val seg = createSegment(0)
for(i <- 0 until 100)
seg.append(i, messages(i, i.toString))
val indexFile = seg.index.file
TestUtils.writeNonsenseToFile(indexFile, 5, indexFile.length.toInt)
seg.recover(64*1024)
for(i <- 0 until 100)
assertEquals(i, seg.read(i, Some(i+1), 1024).messageSet.head.offset)
}
/**
* Randomly corrupt a log a number of times and attempt recovery.
*/
@Test
def testRecoveryWithCorruptMessage() {
val messagesAppended = 20
for(iteration <- 0 until 10) {
val seg = createSegment(0)
for(i <- 0 until messagesAppended)
seg.append(i, messages(i, i.toString))
val offsetToBeginCorruption = TestUtils.random.nextInt(messagesAppended)
// start corrupting somewhere in the middle of the chosen record all the way to the end
val position = seg.log.searchFor(offsetToBeginCorruption, 0).position + TestUtils.random.nextInt(15)
TestUtils.writeNonsenseToFile(seg.log.file, position, seg.log.file.length.toInt - position)
seg.recover(64*1024)
assertEquals("Should have truncated off bad messages.", (0 until offsetToBeginCorruption).toList, seg.log.map(_.offset).toList)
seg.delete()
}
}
/* create a segment with pre allocate */
def createSegment(offset: Long, fileAlreadyExists: Boolean = false, initFileSize: Int = 0, preallocate: Boolean = false): LogSegment = {
val tempDir = TestUtils.tempDir()
val seg = new LogSegment(tempDir, offset, 10, 1000, 0, SystemTime, fileAlreadyExists = fileAlreadyExists, initFileSize = initFileSize, preallocate = preallocate)
segments += seg
seg
}
/* create a segment with pre allocate, put message to it and verify */
@Test
def testCreateWithInitFileSizeAppendMessage() {
val seg = createSegment(40, false, 512*1024*1024, true)
val ms = messages(50, "hello", "there")
seg.append(50, ms)
val ms2 = messages(60, "alpha", "beta")
seg.append(60, ms2)
val read = seg.read(startOffset = 55, maxSize = 200, maxOffset = None)
assertEquals(ms2.toList, read.messageSet.toList)
}
/* create a segment with pre allocate and clearly shut down*/
@Test
def testCreateWithInitFileSizeClearShutdown() {
val tempDir = TestUtils.tempDir()
val seg = new LogSegment(tempDir, 40, 10, 1000, 0, SystemTime, false, 512*1024*1024, true)
val ms = messages(50, "hello", "there")
seg.append(50, ms)
val ms2 = messages(60, "alpha", "beta")
seg.append(60, ms2)
val read = seg.read(startOffset = 55, maxSize = 200, maxOffset = None)
assertEquals(ms2.toList, read.messageSet.toList)
val oldSize = seg.log.sizeInBytes()
val oldPosition = seg.log.channel.position
val oldFileSize = seg.log.file.length
assertEquals(512*1024*1024, oldFileSize)
seg.close()
//After close, file should be trimed
assertEquals(oldSize, seg.log.file.length)
val segReopen = new LogSegment(tempDir, 40, 10, 1000, 0, SystemTime, true, 512*1024*1024, true)
segments += segReopen
val readAgain = segReopen.read(startOffset = 55, maxSize = 200, maxOffset = None)
assertEquals(ms2.toList, readAgain.messageSet.toList)
val size = segReopen.log.sizeInBytes()
val position = segReopen.log.channel.position
val fileSize = segReopen.log.file.length
assertEquals(oldPosition, position)
assertEquals(oldSize, size)
assertEquals(size, fileSize)
}
}
|
winlinvip/kafka
|
core/src/test/scala/unit/kafka/log/LogSegmentTest.scala
|
Scala
|
apache-2.0
| 10,008 |
/*
* Copyright 2013 Maurício Linhares
*
* Maurício Linhares licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.github.mauricio.async.db
import scala.collection.IndexedSeq
/**
* Represents the collection of rows that is returned from a statement inside a {@link QueryResult}. It's basically
* a collection of Array[Any]. Mutating fields in this array will not affect the database in any way
*/
trait ResultSet extends IndexedSeq[RowData] {
/**
* The names of the columns returned by the statement.
*
* @return
*/
def columnNames: IndexedSeq[String]
}
|
dripower/postgresql-async
|
db-async-common/src/main/scala/com/github/mauricio/async/db/ResultSet.scala
|
Scala
|
apache-2.0
| 1,112 |
/***********************************************************************
* Copyright (c) 2013-2020 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.index.api
import org.geotools.util.factory.Hints
import org.locationtech.geomesa.index.geotools.GeoMesaDataStoreFactory.GeoMesaDataStoreConfig
import org.locationtech.geomesa.index.utils.Explainer
import org.opengis.feature.simple.SimpleFeatureType
import org.opengis.filter.Filter
/**
* Conversions to/from index keys
*
* @tparam T values extracted from a filter and used for creating ranges - extracted geometries, z-ranges, etc
* @tparam U a single key space index value, e.g. Long for a z-value, etc
*/
trait IndexKeySpace[T, U] {
/**
* Simple feature type being indexed
*
* @return
*/
def sft: SimpleFeatureType
/**
* The attributes used to create the index keys
*
* @return
*/
def attributes: Seq[String]
/**
* Length of an index key. If static (general case), will return a Right with the length. If dynamic,
* will return Left with a function to determine the length from a given (row, offset, length)
*
* @return
*/
def indexKeyByteLength: Either[(Array[Byte], Int, Int) => Int, Int]
/**
* Table sharing
*
* @return
*/
def sharing: Array[Byte]
/**
* Strategy for sharding
*
* @return
*/
def sharding: ShardStrategy
/**
* Index key from the attributes of a simple feature
*
* @param feature simple feature with cached values
* @param tier tier bytes
* @param id feature id bytes
* @param lenient if input values should be strictly checked, or normalized instead
* @return
*/
def toIndexKey(feature: WritableFeature, tier: Array[Byte], id: Array[Byte], lenient: Boolean = false): RowKeyValue[U]
/**
* Extracts values out of the filter used for range and push-down predicate creation
*
* @param filter query filter
* @param explain explainer
* @return
*/
def getIndexValues(filter: Filter, explain: Explainer): T
/**
* Creates ranges over the index keys
*
* @param values index values @see getIndexValues
* @param multiplier hint for how many times the ranges will be multiplied. can be used to
* inform the number of ranges generated
* @return
*/
def getRanges(values: T, multiplier: Int = 1): Iterator[ScanRange[U]]
/**
* Creates bytes from ranges
*
* @param ranges typed scan ranges. @see `getRanges`
* @param tier will the ranges have tiered ranges appended, or not
* @return
*/
def getRangeBytes(ranges: Iterator[ScanRange[U]], tier: Boolean = false): Iterator[ByteRange]
/**
* Determines if the ranges generated by `getRanges` are sufficient to fulfill the query,
* or if additional filtering needs to be done
*
* @param config data store config
* @param values index values @see getIndexValues
* @param hints query hints
* @return
*/
def useFullFilter(values: Option[T], config: Option[GeoMesaDataStoreConfig], hints: Hints): Boolean
}
object IndexKeySpace {
/**
* Factory for creating key spaces
*
* @tparam T values extracted from a filter and used for creating ranges - extracted geometries, z-ranges, etc
* @tparam U a single key space index value, e.g. Long for a z-value, etc
*/
trait IndexKeySpaceFactory[T, U] {
def supports(sft: SimpleFeatureType, attributes: Seq[String]): Boolean
def apply(sft: SimpleFeatureType, attributes: Seq[String], tier: Boolean): IndexKeySpace[T, U]
}
}
|
aheyne/geomesa
|
geomesa-index-api/src/main/scala/org/locationtech/geomesa/index/api/IndexKeySpace.scala
|
Scala
|
apache-2.0
| 3,941 |
package org.json4s.scalaz
import scalaz._
import scalaz.syntax.apply0._
import scalaz.syntax.bind0._
import scalaz.syntax.traverse._
import scalaz.std.list._
import scalaz.syntax.validation._
import JsonScalaz._
import org.json4s._
import org.scalatest.wordspec.AnyWordSpec
class ValidationExample extends AnyWordSpec {
case class Person(name: String, age: Int)
object Person extends ((String, Int) => Person)
"Validation" should {
def min(x: Int): Int => Result[Int] = (y: Int) => if (y < x) Fail("min", s"$y < $x") else y.success
def max(x: Int): Int => Result[Int] = (y: Int) => if (y > x) Fail("max", s"$y > $x") else y.success
val json = native.JsonParser.parse(""" {"name":"joe","age":17} """)
// Note 'apply _' is not needed on Scala 2.8.1 >=
"fail when age is less than min age" in {
// Age must be between 18 an 60
val person = Person.applyJSON(field[String]("name"), validate[Int]("age") >==> min(18) >==> max(60))
assert(person(json) == Failure(NonEmptyList(UncategorizedError("min", "17 < 18", Nil))))
}
"pass when age within limits" in {
val person = Person.applyJSON(field[String]("name"), validate[Int]("age") >==> min(16) >==> max(60))
assert(person(json) == Success(Person("joe", 17)))
}
}
case class Range(start: Int, end: Int)
object Range extends ((Int, Int) => Range)
// This example shows:
// * a validation where result depends on more than one value
// * parse a List with invalid values
"Range filtering" should {
val json = native.JsonParser.parse(""" [{"s":10,"e":17},{"s":12,"e":13},{"s":11,"e":8}] """)
val ascending: (Int, Int) => (NonEmptyList[Error] \\/ (Int, Int)) = (x1, x2) =>
{
if (x1 > x2) Fail[(Int, Int)]("asc", s"${x1} > ${x2}") else (x1, x2).successNel[Error]
}.toDisjunction
// Valid range is a range having start <= end
implicit def rangeJSON: JSONR[Range] = new JSONR[Range] {
def read(json: JValue) =
((field[Int]("s")(json) |@| field[Int]("e")(json))(ascending).toDisjunction.join map Range.tupled).toValidation
}
"fail if lists contains invalid ranges" in {
val r = fromJSON[List[Range]](json)
assert(r.swap.toOption.get.list == IList(UncategorizedError("asc", "11 > 8", Nil)))
}
"optionally return only valid ranges" in {
val ranges = json.children.map(fromJSON[Range]).filter(_.isSuccess).sequenceU
assert(ranges == Success(List(Range(10, 17), Range(12, 13))))
}
}
}
|
json4s/json4s
|
scalaz/shared/src/test/scala/org/json4s/scalaz/ValidationExample.scala
|
Scala
|
apache-2.0
| 2,508 |
package me.breidenbach
import akka.actor.ActorRef
import me.breidenbach.footrade.OrderType.OrderType
import me.breidenbach.footrade.TradeDirection.TradeDirection
import java.time.Instant
/**
* Date: 3/11/15
* Time: 10:13 PM
* Copyright 2015 Kevin E. Breidenbach
* @author Kevin E. Breidenbach
*/
package object footrade {
object OrderType extends Enumeration {
type OrderType = Value
val Market, Limit = Value
}
object TradeDirection extends Enumeration {
type TradeDirection = Value
val Buy, Sell = Value
}
object IdCounter {
var initial = 0
def next: Int = {
initial = initial + 1
initial
}
}
sealed trait TradeMessage
sealed trait MatchingMessage
case class Trade(ticker: String, qty: Int, tradeDirection: TradeDirection, orderType: OrderType,
partial: Boolean = false, price: BigDecimal = 0, id: Int = 0, tradeTime: Instant = null)
case class TradeRequest(trade: Trade) extends TradeMessage
case class TradeRequestAck(trade: Trade) extends TradeMessage
case class TradeConfirm(trade: Trade) extends TradeMessage
case class Match(trade: Trade, tradeRequestor: ActorRef) extends MatchingMessage
case class Matched(trade: Trade, tradeRequestor: ActorRef) extends MatchingMessage
}
|
kbreidenbach/fooexchange
|
src/main/scala/me/breidenbach/footrade/package.scala
|
Scala
|
mit
| 1,285 |
package org.jetbrains.plugins.scala
package lang.psi.api.expr
import com.intellij.openapi.util.Key
import com.intellij.psi.{PsiElement, PsiNamedElement}
import org.jetbrains.plugins.scala.extensions._
import org.jetbrains.plugins.scala.lang.psi.ScalaPsiUtil._
import org.jetbrains.plugins.scala.lang.psi.api.InferUtil
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.imports.usages.ImportUsed
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.ScTrait
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiManager
import org.jetbrains.plugins.scala.lang.psi.types.Compatibility.Expression
import org.jetbrains.plugins.scala.lang.psi.types._
import org.jetbrains.plugins.scala.lang.psi.types.nonvalue.{Parameter, ScMethodType, ScTypePolymorphicType, TypeParameter}
import org.jetbrains.plugins.scala.lang.psi.types.result.{Success, TypeResult, TypingContext}
import org.jetbrains.plugins.scala.lang.psi.{ScalaPsiElement, ScalaPsiUtil, types}
import org.jetbrains.plugins.scala.lang.resolve.{ResolvableReferenceExpression, ScalaResolveResult}
import org.jetbrains.plugins.scala.project.ScalaLanguageLevel.Scala_2_10
import org.jetbrains.plugins.scala.project._
/**
* Pavel Fatin, Alexander Podkhalyuzin.
*/
// A common trait for Infix, Postfix and Prefix expressions
// and Method calls to handle them uniformly
trait MethodInvocation extends ScExpression with ScalaPsiElement {
/**
* For Infix, Postfix and Prefix expressions
* it's refernce expression for operation
* @return method reference or invoked expression for calls
*/
def getInvokedExpr: ScExpression
/**
* @return call arguments
*/
def argumentExpressions: Seq[ScExpression]
/**
* Unwraps parenthesised expression for method calls
* @return unwrapped invoked expression
*/
def getEffectiveInvokedExpr: ScExpression = getInvokedExpr
/**
* Important method for method calls like: foo(expr) = assign.
* Usually this is same as argumentExpressions
* @return arguments with additional argument if call in update position
*/
def argumentExpressionsIncludeUpdateCall: Seq[ScExpression] = argumentExpressions
/**
* Seq of application problems like type mismatch.
* @return seq of application problems
*/
def applicationProblems: Seq[ApplicabilityProblem] = {
getUpdatableUserData(MethodInvocation.APPLICABILITY_PROBLEMS_VAR_KEY)(Seq.empty)
}
/**
* @return map of expressions and parameters
*/
def matchedParameters: Seq[(ScExpression, Parameter)] = {
matchedParametersInner.map(a => a.swap).filter(a => a._1 != null) //todo: catch when expression is null
}
/**
* @return map of expressions and parameters
*/
def matchedParametersMap: Map[Parameter, Seq[ScExpression]] = {
matchedParametersInner.groupBy(_._1).map(t => t.copy(_2 = t._2.map(_._2)))
}
private def matchedParametersInner: Seq[(Parameter, ScExpression)] = {
getUpdatableUserData(MethodInvocation.MATCHED_PARAMETERS_VAR_KEY)(Seq.empty)
}
/**
* In case if invoked expression converted implicitly to invoke apply or update method
* @return imports used for implicit conversion
*/
def getImportsUsed: collection.Set[ImportUsed] = {
getUpdatableUserData(MethodInvocation.IMPORTS_USED_KEY)(collection.Set.empty[ImportUsed])
}
/**
* In case if invoked expression converted implicitly to invoke apply or update method
* @return actual conversion element
*/
def getImplicitFunction: Option[PsiNamedElement] = {
getUpdatableUserData(MethodInvocation.IMPLICIT_FUNCTION_KEY)(None)
}
/**
* true if this call is syntactic sugar for apply or update method.
*/
def isApplyOrUpdateCall: Boolean = applyOrUpdateElement.isDefined
def applyOrUpdateElement: Option[ScalaResolveResult] = {
getUpdatableUserData(MethodInvocation.APPLY_OR_UPDATE_KEY)(None)
}
/**
* It's arguments for method and infix call.
* For prefix and postfix call it's just operation.
* @return Element, which reflects arguments
*/
def argsElement: PsiElement
/**
* This method useful in case if you want to update some polymorphic type
* according to method call expected type
*/
def updateAccordingToExpectedType(nonValueType: TypeResult[ScType],
check: Boolean = false): TypeResult[ScType] = {
InferUtil.updateAccordingToExpectedType(nonValueType, fromImplicitParameters = false, filterTypeParams = false,
expectedType = expectedType(), expr = this, check = check)
}
/**
* @return Is this method invocation in 'update' syntax sugar position.
*/
def isUpdateCall: Boolean = false
protected override def innerType(ctx: TypingContext): TypeResult[ScType] = {
try {
tryToGetInnerType(ctx, useExpectedType = true)
} catch {
case _: SafeCheckException =>
tryToGetInnerType(ctx, useExpectedType = false)
}
}
private def tryToGetInnerType(ctx: TypingContext, useExpectedType: Boolean): TypeResult[ScType] = {
var nonValueType: TypeResult[ScType] = getEffectiveInvokedExpr.getNonValueType(TypingContext.empty)
this match {
case _: ScPrefixExpr => return nonValueType //no arg exprs, just reference expression type
case _: ScPostfixExpr => return nonValueType //no arg exprs, just reference expression type
case _ =>
}
val withExpectedType = useExpectedType && expectedType().isDefined //optimization to avoid except
if (useExpectedType) nonValueType = updateAccordingToExpectedType(nonValueType, check = true)
def checkConformance(retType: ScType, psiExprs: Seq[Expression], parameters: Seq[Parameter]) = {
tuplizyCase(psiExprs) { t =>
val result = Compatibility.checkConformanceExt(checkNames = true, parameters = parameters, exprs = t,
checkWithImplicits = true, isShapesResolve = false)
(retType, result.problems, result.matchedArgs, result.matchedTypes)
}
}
def checkConformanceWithInference(retType: ScType, psiExprs: Seq[Expression],
typeParams: Seq[TypeParameter], parameters: Seq[Parameter]) = {
tuplizyCase(psiExprs) { t =>
localTypeInferenceWithApplicabilityExt(retType, parameters, t, typeParams, safeCheck = withExpectedType)
}
}
def tuplizyCase(exprs: Seq[Expression])
(fun: (Seq[Expression]) => (ScType, scala.Seq[ApplicabilityProblem],
Seq[(Parameter, ScExpression)], Seq[(Parameter, ScType)])): ScType = {
val c = fun(exprs)
def tail: ScType = {
setApplicabilityProblemsVar(c._2)
setMatchedParametersVar(c._3)
val dependentSubst = new ScSubstitutor(() => {
this.scalaLanguageLevel match {
case Some(level) if level < Scala_2_10 => Map.empty
case _ => c._4.toMap
}
})
dependentSubst.subst(c._1)
}
if (c._2.nonEmpty) {
ScalaPsiUtil.tuplizy(exprs, getResolveScope, getManager, ScalaPsiUtil.firstLeaf(this)).map {e =>
val cd = fun(e)
if (cd._2.nonEmpty) tail
else {
setApplicabilityProblemsVar(cd._2)
setMatchedParametersVar(cd._3)
val dependentSubst = new ScSubstitutor(() => {
this.scalaLanguageLevel match {
case Some(level) if level < Scala_2_10 => Map.empty
case _ => cd._4.toMap
}
})
dependentSubst.subst(cd._1)
}
}.getOrElse(tail)
} else tail
}
def functionParams(params: Seq[ScType]): Seq[Parameter] = {
val functionName = "scala.Function" + params.length
val functionClass = Option(ScalaPsiManager.instance(getProject).getCachedClass(functionName, getResolveScope,
ScalaPsiManager.ClassCategory.TYPE)).flatMap {case t: ScTrait => Option(t) case _ => None}
val applyFunction = functionClass.flatMap(_.functions.find(_.name == "apply"))
params.mapWithIndex {
case (tp, i) =>
new Parameter("v" + (i + 1), None, tp, tp, false, false, false, i, applyFunction.map(_.parameters.apply(i)))
}
}
def checkApplication(tpe: ScType, args: Seq[Expression]): Option[ScType] = tpe match {
case ScFunctionType(retType: ScType, params: Seq[ScType]) =>
Some(checkConformance(retType, args, functionParams(params)))
case ScMethodType(retType, params, _) =>
Some(checkConformance(retType, args, params))
case ScTypePolymorphicType(ScMethodType(retType, params, _), typeParams) =>
Some(checkConformanceWithInference(retType, args, typeParams, params))
case ScTypePolymorphicType(ScFunctionType(retType, params), typeParams) =>
Some(checkConformanceWithInference(retType, args, typeParams, functionParams(params)))
case any if ScalaPsiUtil.isSAMEnabled(this) =>
ScalaPsiUtil.toSAMType(any, getResolveScope) match {
case Some(ScFunctionType(retType: ScType, params: Seq[ScType])) =>
Some(checkConformance(retType, args, functionParams(params)))
case _ => None
}
case _ => None
}
val invokedType: ScType = nonValueType.getOrElse(return nonValueType)
def args(includeUpdateCall: Boolean = false, isNamedDynamic: Boolean = false): Seq[Expression] = {
def default: Seq[ScExpression] =
if (includeUpdateCall) argumentExpressionsIncludeUpdateCall
else argumentExpressions
if (isNamedDynamic) {
default.map {
expr =>
val actualExpr = expr match {
case a: ScAssignStmt =>
a.getLExpression match {
case ref: ScReferenceExpression if ref.qualifier.isEmpty => a.getRExpression.getOrElse(expr)
case _ => expr
}
case _ => expr
}
new Expression(actualExpr) {
override def getTypeAfterImplicitConversion(checkImplicits: Boolean, isShape: Boolean,
_expectedOption: Option[ScType]): (TypeResult[ScType], collection.Set[ImportUsed]) = {
val expectedOption = _expectedOption.map {
case ScTupleType(comps) if comps.length == 2 => comps(1)
case t => t
}
val (res, imports) = super.getTypeAfterImplicitConversion(checkImplicits, isShape, expectedOption)
val str = ScalaPsiManager.instance(getProject).getCachedClass(getResolveScope, "java.lang.String")
val stringType = str.map(ScType.designator(_)).getOrElse(types.Any)
(res.map(tp => ScTupleType(Seq(stringType, tp))(getProject, getResolveScope)), imports)
}
}
}
} else default
}
def isApplyDynamicNamed: Boolean = {
getEffectiveInvokedExpr match {
case ref: ScReferenceExpression =>
ref.bind().exists(result => result.isDynamic && result.name == ResolvableReferenceExpression.APPLY_DYNAMIC_NAMED)
case _ => false
}
}
var res: ScType = checkApplication(invokedType, args(isNamedDynamic = isApplyDynamicNamed)).getOrElse {
var (processedType, importsUsed, implicitFunction, applyOrUpdateResult) =
ScalaPsiUtil.processTypeForUpdateOrApply(invokedType, this, isShape = false).getOrElse {
(types.Nothing, Set.empty[ImportUsed], None, this.applyOrUpdateElement)
}
if (useExpectedType) {
updateAccordingToExpectedType(Success(processedType, None)).foreach(x => processedType = x)
}
setApplyOrUpdate(applyOrUpdateResult)
setImportsUsed(importsUsed)
setImplicitFunction(implicitFunction)
val isNamedDynamic: Boolean =
applyOrUpdateResult.exists(result => result.isDynamic &&
result.name == ResolvableReferenceExpression.APPLY_DYNAMIC_NAMED)
checkApplication(processedType, args(includeUpdateCall = true, isNamedDynamic)).getOrElse {
setApplyOrUpdate(None)
setApplicabilityProblemsVar(Seq(new DoesNotTakeParameters))
setMatchedParametersVar(Seq())
processedType
}
}
//Implicit parameters
val checkImplicitParameters = withEtaExpansion(this)
if (checkImplicitParameters) {
val tuple = InferUtil.updateTypeWithImplicitParameters(res, this, None, useExpectedType, fullInfo = false)
res = tuple._1
implicitParameters = tuple._2
}
Success(res, Some(this))
}
def setApplicabilityProblemsVar(seq: Seq[ApplicabilityProblem]) {
val modCount: Long = getManager.getModificationTracker.getModificationCount
putUserData(MethodInvocation.APPLICABILITY_PROBLEMS_VAR_KEY, (modCount, seq))
}
private def setMatchedParametersVar(seq: Seq[(Parameter, ScExpression)]) {
val modCount: Long = getManager.getModificationTracker.getModificationCount
putUserData(MethodInvocation.MATCHED_PARAMETERS_VAR_KEY, (modCount, seq))
}
def setImportsUsed(set: collection.Set[ImportUsed]) {
val modCount: Long = getManager.getModificationTracker.getModificationCount
putUserData(MethodInvocation.IMPORTS_USED_KEY, (modCount, set))
}
def setImplicitFunction(opt: Option[PsiNamedElement]) {
val modCount: Long = getManager.getModificationTracker.getModificationCount
putUserData(MethodInvocation.IMPLICIT_FUNCTION_KEY, (modCount, opt))
}
def setApplyOrUpdate(opt: Option[ScalaResolveResult]) {
val modCount: Long = getManager.getModificationTracker.getModificationCount
putUserData(MethodInvocation.APPLY_OR_UPDATE_KEY, (modCount, opt))
}
private def getUpdatableUserData[Res](key: Key[(Long, Res)])(default: => Res): Res = {
val modCount = getManager.getModificationTracker.getModificationCount
def getData = Option(getUserData(key)).getOrElse(-1L, default)
getData match {
case (`modCount`, res) => res
case _ =>
getType(TypingContext.empty) //update if needed
getData match {
case (`modCount`, res) => res
case _ => default //todo: should we throw an exception in this case?
}
}
}
}
object MethodInvocation {
def unapply(invocation: MethodInvocation) =
Some(invocation.getInvokedExpr, invocation.argumentExpressions)
private val APPLICABILITY_PROBLEMS_VAR_KEY: Key[(Long, Seq[ApplicabilityProblem])] = Key.create("applicability.problems.var.key")
private val MATCHED_PARAMETERS_VAR_KEY: Key[(Long, Seq[(Parameter, ScExpression)])] = Key.create("matched.parameter.var.key")
private val IMPORTS_USED_KEY: Key[(Long, collection.Set[ImportUsed])] = Key.create("imports.used.method.invocation.key")
private val IMPLICIT_FUNCTION_KEY: Key[(Long, Option[PsiNamedElement])] = Key.create("implicit.function.method.invocation.key")
private val APPLY_OR_UPDATE_KEY: Key[(Long, Option[ScalaResolveResult])] = Key.create("apply.or.update.key")
}
|
LPTK/intellij-scala
|
src/org/jetbrains/plugins/scala/lang/psi/api/expr/MethodInvocation.scala
|
Scala
|
apache-2.0
| 14,937 |
/*
* SimpleFOLParser.scala
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package at.logic.gapt.formats.language.simple
import at.logic.gapt.formats.simple.SimpleFOLParser
import org.specs2.mutable._
import at.logic.gapt.expr._
import at.logic.gapt.language.fol._
import at.logic.gapt.expr.StringSymbol
import at.logic.gapt.formats.readers.StringReader
class SimpleFOLParserTest extends Specification {
private class MyParser( input: String ) extends StringReader( input ) with SimpleFOLParser
val var1 = FOLVar( "x1" )
val const1 = FOLConst( "c1" )
val var2 = FOLVar( "x2" )
val atom1 = FOLAtom( "A", var1 :: var2 :: const1 :: Nil )
val var3 = FOLAtom( "X3", Nil )
val func1 = FOLFunction( "f", var1 :: var2 :: const1 :: Nil )
val and1 = And( atom1, var3 )
val or1 = Or( atom1, var3 )
val imp1 = Imp( atom1, var3 )
val neg1 = Neg( atom1 )
val ex1 = Ex( var1, atom1 )
val all1 = All( var1, atom1 )
val npx = Neg( FOLAtom( "p", FOLVar( "x" ) :: Nil ) )
"SimpleFOLParser" should {
"parse correctly a variable" in {
( new MyParser( "x1" ).getTerm() ) must beEqualTo( var1 )
}
"parse correctly an constant" in {
( new MyParser( "c1" ).getTerm() ) must beEqualTo( const1 )
}
"parse correctly an atom" in {
( new MyParser( "A(x1, x2, c1)" ).getTerm() ) must beEqualTo( atom1 )
}
"parse correctly a formula" in {
( new MyParser( "X3" ).getTerm() ) must beLike { case x: FOLFormula => ok }
( new MyParser( "X3" ).getTerm() ) must beEqualTo( var3 )
}
"parse correctly a function 1" in {
( new MyParser( "f(x1)" ).getTerm() ) must beEqualTo( FOLFunction( "f", var1 :: Nil ) )
}
"parse correctly a function 2" in {
( new MyParser( "f(x1, x2, c1)" ).getTerm() ) must beEqualTo( func1 )
}
"parse correctly an and" in {
( new MyParser( "And A(x1, x2, c1) X3" ).getTerm() ) must beEqualTo( and1 )
}
"parse correctly an or" in {
( new MyParser( "Or A(x1, x2, c1) X3" ).getTerm() ) must beEqualTo( or1 )
}
"parse correctly an imp" in {
( new MyParser( "Imp A(x1, x2, c1) X3" ).getTerm() ) must beEqualTo( imp1 )
}
"parse correctly an neg" in {
( new MyParser( "Neg A(x1, x2, c1)" ).getTerm() ) must beEqualTo( neg1 )
}
"parse correctly an exists" in {
( new MyParser( "Exists x1 A(x1, x2, c1)" ).getTerm() ) must beEqualTo( ex1 )
}
"parse correctly a forall" in {
( new MyParser( "Forall x1 A(x1, x2, c1)" ).getTerm() ) must beEqualTo( all1 )
}
"reject the empty string" in {
( new MyParser( "" ).getTerm() ) must throwAn[Exception]
}
"reject the string p(X)" in {
( new MyParser( "p(X)" ).getTerm() ) must throwAn[Exception]
}
}
}
|
gisellemnr/gapt
|
src/test/scala/at/logic/gapt/formats/language/simple/SimpleFOLParserTest.scala
|
Scala
|
gpl-3.0
| 2,815 |
/*
* Copyright (C) 2015 Holmes Team at HUAWEI Noah's Ark Lab.
*
* 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.apache.spark.streamdm.classifiers.trees
import scala.math.{ max,min }
import org.apache.spark.streamdm.utils.Utils.{log2}
trait SplitCriterionType
case class InfoGainSplitCriterionType() extends SplitCriterionType
case class GiniSplitCriterionType() extends SplitCriterionType
case class VarianceReductionSplitCriterionType() extends SplitCriterionType
/**
* Trait for computing splitting criteria with respect to distributions of class values.
* The split criterion is used as a parameter on decision trees and decision stumps.
* The two split criteria most used are Information Gain and Gini.
*/
trait SplitCriterion extends Serializable {
/**
* Computes the merit of splitting for a given distribution before and after the split.
*
* @param pre the class distribution before the split
* @param post the class distribution after the split
* @return value of the merit of splitting
*/
def merit(pre: Array[Double], post: Array[Array[Double]]): Double
/**
* Computes the range of splitting merit
*
* @param pre the class distribution before the split
* @return value of the range of splitting merit
*/
def rangeMerit(pre: Array[Double]): Double
}
/**
* Class for computing splitting criteria using information gain with respect to
* distributions of class values.
*/
class InfoGainSplitCriterion extends SplitCriterion with Serializable {
var minBranch: Double = 0.01
def this(minBranch: Double) {
this()
this.minBranch = minBranch
}
/**
* Computes the merit of splitting for a given distribution before and after the split.
*
* @param pre the class distribution before the split
* @param post the class distribution after the split
* @return value of the merit of splitting
*/
override def merit(pre: Array[Double], post: Array[Array[Double]]): Double = {
val num = numGTFrac(post, minBranch)
if (numGTFrac(post, minBranch) < 2) Double.NegativeInfinity
else {
val merit = entropy(pre) - entropy(post)
merit
}
}
/**
* Computes the range of splitting merit
*
* @param pre the class distribution before the split
* @return value of the range of splitting merit
*/
override def rangeMerit(pre: Array[Double]): Double = log2(max(pre.length, 2))
/**
* Returns the entropy of a distribution
*
* @param pre an Array containing the distribution
* @return the entropy
*/
def entropy(pre: Array[Double]): Double = {
if (pre == null || pre.sum <= 0 || hasNegative(pre)) 0.0
log2(pre.sum) - pre.filter(_ > 0).map(x => x * log2(x)).sum / pre.sum
}
/**
* Computes the entropy of an matrix
*
* @param post the matrix as an Array of Array
* @return the entropy
*/
def entropy(post: Array[Array[Double]]): Double = {
if (post == null || post.length == 0 || post(0).length == 0) 0
else {
post.map { row => (row.sum * entropy(row)) }.sum / post.map(_.sum).sum
}
}
/**
* Returns number of subsets which have values greater than minFrac
*
* @param post he matrix as an Array of Array
* @param minFrac the min threshold
* @return number of subsets
*/
def numGTFrac(post: Array[Array[Double]], minFrac: Double): Int = {
if (post == null || post.length == 0) {
0
} else {
val sums = post.map { _.sum }
sums.filter(_ > sums.sum * minFrac).length
}
}
/**
* Returns whether a array has negative value
*
* @param pre an Array to be valued
* @return whether a array has negative value
*/
private[trees] def hasNegative(pre: Array[Double]): Boolean = pre.filter(x => x < 0).length > 0
}
/**
* Class for computing splitting criteria using Gini with respect to
* distributions of class values.
*/
class GiniSplitCriterion extends SplitCriterion with Serializable {
/**
* Computes the merit of splitting for a given distribution before and after the split.
*
* @param pre the class distribution before the split
* @param post the class distribution after the split
* @return value of the merit of splitting
*/
override def merit(pre: Array[Double], post: Array[Array[Double]]): Double = {
val sums = post.map(_.sum)
val totalWeight = sums.sum
val ginis: Array[Double] = post.zip(sums).map {
case (x, y) => computeGini(x, y) * y / totalWeight
}
1.0 - ginis.sum
}
/**
* Computes the range of splitting merit
*
* @param pre the class distribution before the split
* @return value of the range of splitting merit
*/
override def rangeMerit(pre: Array[Double]): Double = 1.0
/**
* Computes the gini of an array
*
* @param dist an array to be computed
* @param sum the sum of the array
* @return the gini of an array
*/
private[trees] def computeGini(dist: Array[Double], sum: Double): Double =
1.0 - dist.map { x => x * x / sum / sum }.sum
}
/**
* Class for computing splitting criteria using variance reduction with respect
* to distributions of class values.
*/
class VarianceReductionSplitCriterion extends SplitCriterion with Serializable {
val magicNumber = 5.0
/**
* Computes the merit of splitting for a given distribution before and after the split.
*
* @param pre the class distribution before the split
* @param post the class distribution after the split
* @return value of the merit of splitting
*/
override def merit(pre: Array[Double], post: Array[Array[Double]]): Double = {
val count = post.map { row => if (row(0) >= magicNumber) 1 else 0 }.sum
if (count != post.length) 0
else {
var sdr = computeSD(pre)
post.foreach { row => sdr -= (row(0) / pre(0)) * computeSD(row) }
sdr
}
}
/**
* Computes the range of splitting merit
*
* @param pre the class distribution before the split
* @return value of the range of splitting merit
*/
override def rangeMerit(pre: Array[Double]): Double = 1.0
/**
* Computes the standard deviation of a distribution
*
* @param pre an Array containing the distribution
* @return the standard deviation
*/
private[trees] def computeSD(pre: Array[Double]): Double = {
val n = pre(0).toInt
val sum = pre(1)
val sumSq = pre(2)
(sumSq - ((sum * sum) / n)) / n
}
}
object SplitCriterion {
/**
* Return a new SplitCriterion, by default InfoGainSplitCriterion.
* @param scType the type of the split criterion
* @param minBranch branch parameter
* @return the new SplitCriterion
*/
def createSplitCriterion(
scType: SplitCriterionType, minBranch: Double = 0.01): SplitCriterion = scType match {
case infoGrain: InfoGainSplitCriterionType => new InfoGainSplitCriterion(minBranch)
case gini: GiniSplitCriterionType => new GiniSplitCriterion()
case vr: VarianceReductionSplitCriterionType => new VarianceReductionSplitCriterion()
case _ => new InfoGainSplitCriterion(minBranch)
}
}
|
gosubpl/akka-online
|
src/main/scala/org/apache/spark/streamdm/classifiers/trees/SplitCriterion.scala
|
Scala
|
apache-2.0
| 7,631 |
package org.igye.learnpl2
import java.util.Random
import scala.collection.mutable.ListBuffer
class Rnd {
private val rnd = new Random()
private val buf = ListBuffer[Int]()
private var lastBound = -1
def nextInt(bound: Int) = {
// val pr = println(_:Any)
// pr(s"buf.size = ${buf.size}, bound = $bound, lastBound = $lastBound")
if (buf.isEmpty || lastBound != bound) {
lastBound = bound
buf.clear()
buf ++= 0 until bound
for (i <- 1 to bound*5) {
buf += buf.remove(rnd.nextInt(buf.size))
}
}
val res = buf.remove(rnd.nextInt(buf.size)) % bound
// pr(s"nextInt.res = $res")
res
}
def removeFromBuffer(nums: List[Int]): Unit = {
if (buf.nonEmpty) {
buf --= nums
}
}
def getBuffer = buf.toList
def refresh() = lastBound = -1
}
|
Igorocky/learnpl2
|
src/main/scala/org/igye/learnpl2/Rnd.scala
|
Scala
|
mit
| 922 |
/* Copyright 2009-2016 EPFL, Lausanne */
object Nested5 {
def foo(a: Int): Int = {
require(a >= 0)
def bar(b: Int): Int = {
require(b > 0)
b + 3
} ensuring(a >= 0 && _ == b + 3)
bar(2)
} ensuring(a >= 0 && _ == 5)
}
|
regb/leon
|
src/test/resources/regression/verification/purescala/valid/Nested5.scala
|
Scala
|
gpl-3.0
| 251 |
package email
import models.{BusinessDetailsModel, ConfirmFormModel, EligibilityModel}
import play.api.i18n.Lang
import play.twirl.api.HtmlFormat
import uk.gov.dvla.vehicles.presentation.common.clientsidesession.TrackingId
import uk.gov.dvla.vehicles.presentation.common.model.VehicleAndKeeperDetailsModel
import uk.gov.dvla.vehicles.presentation.common.webserviceclients.emailservice.EmailServiceSendRequest
trait RetainEmailService {
def emailRequest(emailAddress: String,
vehicleAndKeeperDetailsModel: VehicleAndKeeperDetailsModel,
eligibilityModel: EligibilityModel,
emailData: EmailData,
confirmFormModel: Option[ConfirmFormModel],
businessDetailsModel: Option[BusinessDetailsModel],
emailFlags: EmailFlags,
trackingId: TrackingId)(implicit lang: Lang): Option[EmailServiceSendRequest]
def htmlMessage(vehicleAndKeeperDetailsModel: VehicleAndKeeperDetailsModel,
eligibilityModel: EligibilityModel,
emailData: EmailData,
confirmFormModel: Option[ConfirmFormModel],
businessDetailsModel: Option[BusinessDetailsModel],
emailFlags: EmailFlags)(implicit lang: Lang): HtmlFormat.Appendable
}
case class EmailFlags(sendPdf: Boolean, isKeeper: Boolean)
case class EmailData(certificateNumber: String, transactionTimestamp: String, transactionId: String)
|
dvla/vrm-retention-online
|
app/email/RetainEmailService.scala
|
Scala
|
mit
| 1,482 |
/**
* Copyright 2015 Thomson Reuters
*
* 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 cmwell.it
import cmwell.util.concurrent.FutureTimeout
import cmwell.util.concurrent.SimpleScheduler.scheduleFuture
import cmwell.util.http.SimpleResponse
import com.typesafe.scalalogging.LazyLogging
import org.scalatest.enablers.Size
import play.api.libs.json._
import scala.concurrent.Future
import scala.concurrent.duration._
import org.scalatest.{AsyncFunSpec, Inspectors, Matchers}
class OWTests extends AsyncFunSpec with Matchers with Inspectors with Helpers with fixture.NSHashesAndPrefixes with LazyLogging {
//Assertions
val firstIngest = {
val h1 = scala.io.Source.fromURL(this.getClass.getResource(s"/feed/history.feed.tms.1.nq")).mkString
Http.post(_ow, h1, Some("text/nquads;charset=UTF-8"), List("format" -> "nquads"), tokenHeader).map { res =>
withClue(res){
res.status should be(200)
jsonSuccessPruner(Json.parse(res.payload)) should be(jsonSuccess)
}
}
}
def futureToWaitFor(httpReq: =>Future[SimpleResponse[Array[Byte]]], expectedTotal: Int) = {
val startTime = System.currentTimeMillis()
def recurse(): Future[SimpleResponse[Array[Byte]]] = {
httpReq.flatMap { res =>
Json.parse(res.payload) \\ "results" \\ "total" match { //make sure parents are created as well.
case JsDefined(JsNumber(n)) if n.intValue() == expectedTotal => Future.successful(res)
case _ if System.currentTimeMillis() - startTime > 60000L => Future.failed(new IllegalStateException(s"timed out with last response: $res"))
case _ => scheduleFuture(990.millis)(recurse())
}
}
}
recurse()
}
val parent = cmw / "feed.tms"
val path = parent / "1.0"
lazy val waitForIngest = futureToWaitFor(Http.get(path, List("op" -> "search", "recursive" -> "", "length" -> "1", "format" -> "json")),83)
lazy val waitForParent = waitForIngest.flatMap(_ => futureToWaitFor(Http.get(parent, List("op" -> "search", "length" -> "1", "format" -> "json")),1))
def executeAfterIngest[T](body: =>Future[T]): Future[T] = waitForIngest.flatMap(_ => body)
implicit val jsValueArrSize = new Size[JsArray] {
def sizeOf(obj: JsArray): Long = obj.value.size
}
val childrenIndexed = executeAfterIngest {
Http.get(path, List("op" -> "search", "recursive" -> "", "length" -> "1", "format" -> "json")).map { res =>
withClue(res) {
res.status should be(200)
Json.parse(res.payload) \\ "results" \\ "total" match { //make sure parents are created as well.
case JsDefined(JsNumber(n)) => n should be(83)
case JsDefined(j) => fail(s"got something else: ${Json.stringify(j)}")
case u:JsUndefined => fail(s"failed to parse json, error: ${u.error}, original json: ${new String(res.payload, "UTF-8")}")
}
}
}
}
val makeSureParentDirsWereNotCreated = executeAfterIngest {
Http.get(path,List("length" -> "100","format"->"json")).map { res =>
withClue(res) {
res.status should be(404)
}
}
}
val makeSureGrandParentDirsWereNotCreated = makeSureParentDirsWereNotCreated.flatMap { _ =>
Http.get(cmw / "feed.tms").map { res =>
withClue(res) {
res.status should be(404)
}
}
}
val ingestFeedTMS = makeSureGrandParentDirsWereNotCreated.flatMap{ _ =>
val payload =
"""
|<http://feed.tms> <cmwell://meta/sys#indexTime> "1489414332875"^^<http://www.w3.org/2001/XMLSchema#long> .
|<http://feed.tms> <cmwell://meta/sys#dataCenter> "vg" .
|<http://feed.tms> <cmwell://meta/sys#lastModified> "1970-01-01T00:00:00.000Z"^^<http://www.w3.org/2001/XMLSchema#dateTime> .
|<http://feed.tms> <cmwell://meta/sys#type> "ObjectInfoton" .
|<http://feed.tms/1.0> <cmwell://meta/sys#indexTime> "1489414332875"^^<http://www.w3.org/2001/XMLSchema#long> .
|<http://feed.tms/1.0> <cmwell://meta/sys#dataCenter> "vg" .
|<http://feed.tms/1.0> <cmwell://meta/sys#lastModified> "1970-01-01T00:00:00.000Z"^^<http://www.w3.org/2001/XMLSchema#dateTime> .
|<http://feed.tms/1.0> <cmwell://meta/sys#type> "ObjectInfoton" .
""".stripMargin
Http.post(_ow, payload, Some("text/nquads;charset=UTF-8"), List("format" -> "nquads"), tokenHeader).map{ res =>
withClue(res) {
res.status should be(200)
Json.parse(res.payload) should be(jsonSuccess)
}
}
}
val waitForParents = ingestFeedTMS.flatMap { _ =>
val waitForParentIngest1 = futureToWaitFor(Http.get(parent, List("op" -> "search", "length" -> "1", "format" -> "json")),1)
val waitForParentIngest2 = futureToWaitFor(Http.get(cmw, List("op" -> "search", "qp" -> "system.path::/feed.tms", "length" -> "1", "format" -> "json")),1)
for {
r1 <- waitForParentIngest1
r2 <- waitForParentIngest2
} yield withClue(r1 -> r2)(succeed)
}
val emptyFile = {
val payload =
// scalastyle:off
"""
|<http://la.grading.dev.thomsonreuters.com/badfile> <cmwell://meta/sys#indexTime> "1489414332875"^^<http://www.w3.org/2001/XMLSchema#long> .
|<http://la.grading.dev.thomsonreuters.com/badfile> <cmwell://meta/sys#dataCenter> "blahlah" .
|<http://la.grading.dev.thomsonreuters.com/badfile> <cmwell://meta/sys#lastModified> "1970-01-01T00:00:00.000Z"^^<http://www.w3.org/2001/XMLSchema#dateTime> .
|<http://la.grading.dev.thomsonreuters.com/badfile> <cmwell://meta/sys#type> "FileInfoton" .
""".stripMargin
// scalastyle:on
Http.post(_ow, payload, Some("text/nquads;charset=UTF-8"), List("format" -> "nquads"), tokenHeader).map{ res =>
withClue(res) {
res.status should be(400)
}
}
}
describe("_ow API should") {
it("reject empty file infoton")(emptyFile)
it("ingest first version correctly")(firstIngest)
it("make sure all children were indexed in ES")(childrenIndexed)
it("make sure parent was NOT created with all children")(makeSureParentDirsWereNotCreated)
it("make sure grand parent was NOT created")(makeSureGrandParentDirsWereNotCreated)
it("succeed to ingest empty \\"parent\\" infotons")(ingestFeedTMS)
it("verify parents were ingeseted")(waitForParents)
//TODO: ingest all currents, make sure history is aligned
//TODO: ingest a historic version, make sure all is good
}
}
|
hochgi/CM-Well
|
server/cmwell-it/src/it/scala/cmwell/it/OWTests.scala
|
Scala
|
apache-2.0
| 6,930 |
package scala.in.programming.function_and_closure
/**
* @author loustler
* @since 02/04/2017 11:34
*/
object SimpleFunctionLiteral extends App {
val someNumbers = List(-11, -10, -5, 0, 5, 10)
println("--------- example 1 -------------")
// This method use method reference.
someNumbers.foreach(println)
println("--------- example 1 -------------")
println("--------- example 2 -------------")
// Parameter of filter function is Predicate
someNumbers.filter(x => x > 0).foreach(println)
println("--------- example 2 -------------")
println("--------- example 3 -------------")
// It works such example 2.
someNumbers.filter(_ > 0).foreach(println)
println("--------- example 3 -------------")
println("--------- example 4 -------------")
// It works such example 1.
someNumbers.foreach(println _)
println("--------- example 4 -------------")
println("--------- example 5 -------------")
// Partially applied function
def sum(a: Int, b: Int, c: Int) = a + b + c
// Show how to partially applied
/**
* Step 1
*
* It is example for first partially applied function,
* cuz provide any values as parameter.
*
*/
val partially1 = sum _
println(partially1(1, 2, 3))
/**
* Step 2
*
* It is example for second partially applied function,
* cuz provide 2 values as parameter out of 3 parameters.
*
*/
val partially2 = sum(1, _: Int, 3)
println(partially2(2))
println("--------- example 5 -------------")
}
|
loustler/scala
|
src/main/scala/scala/in/programming/function_and_closure/SimpleFunctionLiteral.scala
|
Scala
|
mit
| 1,527 |
package org.jetbrains.plugins.scala
package lang
package psi
package api
package base
package patterns
import org.jetbrains.plugins.scala.lang.psi.ScalaPsiElement
/**
* @author Alexander Podkhalyuzin
* Date: 28.02.2008
*/
trait ScCaseClauses extends ScalaPsiElement {
def caseClause = findChildByClassScala(classOf[ScCaseClause])
def caseClauses: Seq[ScCaseClause] = collection.immutable.Seq(findChildrenByClassScala(classOf[ScCaseClause]).toSeq: _*)
}
|
consulo/consulo-scala
|
src/org/jetbrains/plugins/scala/lang/psi/api/base/patterns/ScCaseClauses.scala
|
Scala
|
apache-2.0
| 460 |
/**
* 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.activemq.apollo.broker.transport
import java.io.IOException
import java.net.URI
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import org.apache.activemq.apollo.broker._
import scala.collection.JavaConversions._
import org.fusesource.hawtdispatch.transport._
import org.apache.activemq.apollo.util._
import java.lang.String
import org.apache.activemq.apollo.dto.AcceptingConnectorDTO
import org.fusesource.hawtdispatch._
/**
* @author <a href="http://hiramchirino.com">Hiram Chirino</a>
*/
object VMTransportFactory extends Log {
val DEFAULT_PIPE_NAME = "default"
}
/**
* Implements the vm transport which behaves like the pipe transport except that
* it can start embedded brokers up on demand.
*
* @author <a href="http://hiramchirino.com">Hiram Chirino</a>
*/
class VMTransportFactory extends Logging with TransportFactory.Provider {
import PipeTransportRegistry._
import VMTransportFactory._
override protected def log = VMTransportFactory
/**
* This extension of the PipeTransportServer shuts down the broker
* when all the connections are disconnected.
*
* @author chirino
*/
class VmTransportServer extends PipeTransportServer {
val refs = new AtomicInteger()
var broker: Broker = null
override def createClientTransport(): PipeTransport = {
refs.incrementAndGet();
new PipeTransport(this) {
val stopped = new AtomicBoolean()
override def stop(onComplete:Task) = {
if (stopped.compareAndSet(false, true)) {
super.stop(onComplete);
if (refs.decrementAndGet() == 0) {
stopBroker();
}
}
}
};
}
def setBroker(broker: Broker) = {
this.broker = broker;
}
def stopBroker() = {
try {
this.broker.stop(NOOP);
unbind(this);
} catch {
case e: Exception =>
error("Failed to stop the broker gracefully: " + e);
debug("Failed to stop the broker gracefully: ", e);
}
}
}
override def bind(location: String):TransportServer = {
if( !location.startsWith("vm:") ) {
return null;
}
PipeTransportRegistry.bind(location)
}
override def connect(location: String): Transport = {
if( !location.startsWith("vm:") ) {
return null;
}
try {
var uri = new URI(location)
var brokerURI: String = null;
var create = true;
var name = uri.getHost();
if (name == null) {
name = DEFAULT_PIPE_NAME;
}
var options = URISupport.parseParamters(uri);
var config = options.remove("broker").asInstanceOf[String]
if (config != null) {
brokerURI = config;
}
if ("false".equals(options.remove("create"))) {
create = false;
}
var server = servers.get(name);
if (server == null && create) {
// This is the connector that the broker needs.
val connector = new AcceptingConnectorDTO
connector.id = "vm"
connector.bind = "vm://" + name
// Create the broker on demand.
var broker: Broker = null
if (brokerURI == null) {
// Lets create and configure it...
broker = new Broker()
broker.config.connectors.clear
broker.config.connectors.add(connector)
} else {
// Use the user specified config
broker = BrokerFactory.createBroker(brokerURI);
// we need to add in the connector if it was not in the config...
val found = broker.config.connectors.toList.find { _ match {
case dto:AcceptingConnectorDTO=> dto.bind == connector.bind
case _ => false
}}
if (found.isEmpty) {
broker.config.connectors.add(connector)
}
}
// TODO: get rid of this blocking wait.
val tracker = new LoggingTracker("vm broker startup")
tracker.start(broker)
tracker.await
server = servers.get(name)
}
if (server == null) {
throw new IOException("Server is not bound: " + name)
}
var transport = server.connect()
import TransportFactorySupport._
verify(configure(transport, options), options)
} catch {
case e:IllegalArgumentException=>
throw e
case e: Exception =>
throw IOExceptionSupport.create(e)
}
}
}
|
chirino/activemq-apollo
|
apollo-broker/src/main/scala/org/apache/activemq/apollo/broker/transport/VMTransport.scala
|
Scala
|
apache-2.0
| 5,268 |
package com.alexitc.coinalerts.core
import com.alexitc.playsonify.models.WrappedString
case class FilterQuery(string: String) extends AnyVal with WrappedString
|
AlexITC/crypto-coin-alerts
|
alerts-server/app/com/alexitc/coinalerts/core/FilterQuery.scala
|
Scala
|
gpl-3.0
| 162 |
package controllers.conservation
import com.google.inject.{Inject, Singleton}
import no.uio.musit.security.Authenticator
import no.uio.musit.service.MusitController
import play.api.Logger
import play.api.mvc.ControllerComponents
import services.conservation.HseRiskAssessmentService
@Singleton
class HseRiskAssessmentController @Inject()(
val controllerComponents: ControllerComponents,
val authService: Authenticator,
val service: HseRiskAssessmentService
) extends MusitController {
val logger = Logger(classOf[HseRiskAssessmentController])
}
|
MUSIT-Norway/musit
|
service_backend/app/controllers/conservation/HseRiskAssessmentController.scala
|
Scala
|
gpl-2.0
| 561 |
package wvlet.airframe.surface.reflect
import wvlet.log.LogSupport
import wvlet.airframe.surface.AirSpecBridge
case class Person(id: Int, name: String) {
def hello: String = "hello"
}
class TastySurfaceFactoryTest extends munit.FunSuite with AirSpecBridge with LogSupport {
test("of[A]") {
val s = TastySurfaceFactory.of[Person]
debug(s.params.mkString(", "))
}
test("ofClass") {
val s = ReflectSurfaceFactory.ofClass(classOf[Person])
debug(s)
val s2 = ReflectSurfaceFactory.ofClass(classOf[Person])
debug(s2)
}
test("methodsOf") {
pending("runtime error is shown")
val m = TastySurfaceFactory.methodsOfClass(classOf[Person])
debug(m.mkString(", "))
}
}
|
wvlet/airframe
|
airframe-surface/.jvm/src/test/scala-3/wvlet/airframe/surface/reflect/TastySurfaceFactoryTest.scala
|
Scala
|
apache-2.0
| 711 |
package service
import model._
import scala.slick.driver.H2Driver.simple._
import Database.threadLocalSession
trait SshKeyService {
def addPublicKey(userName: String, title: String, publicKey: String): Unit =
SshKeys.ins insert (userName, title, publicKey)
def getPublicKeys(userName: String): List[SshKey] =
Query(SshKeys).filter(_.userName is userName.bind).sortBy(_.sshKeyId).list
def deletePublicKey(userName: String, sshKeyId: Int): Unit =
SshKeys filter (_.byPrimaryKey(userName, sshKeyId)) delete
}
|
Muscipular/gitbucket
|
src/main/scala/service/SshKeyService.scala
|
Scala
|
apache-2.0
| 531 |
/*
* 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.v2
import scala.collection.JavaConverters._
import scala.collection.mutable
import org.apache.spark.sql.{AnalysisException, Strategy}
import org.apache.spark.sql.catalyst.expressions.{And, AttributeReference, AttributeSet, Expression, PredicateHelper, SubqueryExpression}
import org.apache.spark.sql.catalyst.planning.PhysicalOperation
import org.apache.spark.sql.catalyst.plans.logical.{AlterTable, AppendData, CreateTableAsSelect, CreateV2Table, DeleteFromTable, DescribeTable, DropTable, LogicalPlan, OverwriteByExpression, OverwritePartitionsDynamic, Repartition, ReplaceTable, ReplaceTableAsSelect, ShowNamespaces, ShowTables}
import org.apache.spark.sql.connector.catalog.{StagingTableCatalog, TableCapability}
import org.apache.spark.sql.connector.read.{Scan, ScanBuilder, SupportsPushDownFilters, SupportsPushDownRequiredColumns}
import org.apache.spark.sql.connector.read.streaming.{ContinuousStream, MicroBatchStream}
import org.apache.spark.sql.execution.{FilterExec, ProjectExec, SparkPlan}
import org.apache.spark.sql.execution.datasources.DataSourceStrategy
import org.apache.spark.sql.execution.streaming.continuous.{ContinuousCoalesceExec, WriteToContinuousDataSource, WriteToContinuousDataSourceExec}
import org.apache.spark.sql.sources
import org.apache.spark.sql.util.CaseInsensitiveStringMap
object DataSourceV2Strategy extends Strategy with PredicateHelper {
/**
* Pushes down filters to the data source reader
*
* @return pushed filter and post-scan filters.
*/
private def pushFilters(
scanBuilder: ScanBuilder,
filters: Seq[Expression]): (Seq[Expression], Seq[Expression]) = {
scanBuilder match {
case r: SupportsPushDownFilters =>
// A map from translated data source leaf node filters to original catalyst filter
// expressions. For a `And`/`Or` predicate, it is possible that the predicate is partially
// pushed down. This map can be used to construct a catalyst filter expression from the
// input filter, or a superset(partial push down filter) of the input filter.
val translatedFilterToExpr = mutable.HashMap.empty[sources.Filter, Expression]
val translatedFilters = mutable.ArrayBuffer.empty[sources.Filter]
// Catalyst filter expression that can't be translated to data source filters.
val untranslatableExprs = mutable.ArrayBuffer.empty[Expression]
for (filterExpr <- filters) {
val translated =
DataSourceStrategy.translateFilterWithMapping(filterExpr, Some(translatedFilterToExpr))
if (translated.isEmpty) {
untranslatableExprs += filterExpr
} else {
translatedFilters += translated.get
}
}
// Data source filters that need to be evaluated again after scanning. which means
// the data source cannot guarantee the rows returned can pass these filters.
// As a result we must return it so Spark can plan an extra filter operator.
val postScanFilters = r.pushFilters(translatedFilters.toArray).map { filter =>
DataSourceStrategy.rebuildExpressionFromFilter(filter, translatedFilterToExpr)
}
// The filters which are marked as pushed to this data source
val pushedFilters = r.pushedFilters().map { filter =>
DataSourceStrategy.rebuildExpressionFromFilter(filter, translatedFilterToExpr)
}
(pushedFilters, untranslatableExprs ++ postScanFilters)
case _ => (Nil, filters)
}
}
/**
* Applies column pruning to the data source, w.r.t. the references of the given expressions.
*
* @return the created `ScanConfig`(since column pruning is the last step of operator pushdown),
* and new output attributes after column pruning.
*/
// TODO: nested column pruning.
private def pruneColumns(
scanBuilder: ScanBuilder,
relation: DataSourceV2Relation,
exprs: Seq[Expression]): (Scan, Seq[AttributeReference]) = {
scanBuilder match {
case r: SupportsPushDownRequiredColumns =>
val requiredColumns = AttributeSet(exprs.flatMap(_.references))
val neededOutput = relation.output.filter(requiredColumns.contains)
if (neededOutput != relation.output) {
r.pruneColumns(neededOutput.toStructType)
val scan = r.build()
val nameToAttr = relation.output.map(_.name).zip(relation.output).toMap
scan -> scan.readSchema().toAttributes.map {
// We have to keep the attribute id during transformation.
a => a.withExprId(nameToAttr(a.name).exprId)
}
} else {
r.build() -> relation.output
}
case _ => scanBuilder.build() -> relation.output
}
}
import DataSourceV2Implicits._
override def apply(plan: LogicalPlan): Seq[SparkPlan] = plan match {
case PhysicalOperation(project, filters, relation: DataSourceV2Relation) =>
val scanBuilder = relation.newScanBuilder()
val (withSubquery, withoutSubquery) = filters.partition(SubqueryExpression.hasSubquery)
val normalizedFilters = DataSourceStrategy.normalizeFilters(
withoutSubquery, relation.output)
// `pushedFilters` will be pushed down and evaluated in the underlying data sources.
// `postScanFilters` need to be evaluated after the scan.
// `postScanFilters` and `pushedFilters` can overlap, e.g. the parquet row group filter.
val (pushedFilters, postScanFiltersWithoutSubquery) =
pushFilters(scanBuilder, normalizedFilters)
val postScanFilters = postScanFiltersWithoutSubquery ++ withSubquery
val (scan, output) = pruneColumns(scanBuilder, relation, project ++ postScanFilters)
logInfo(
s"""
|Pushing operators to ${relation.name}
|Pushed Filters: ${pushedFilters.mkString(", ")}
|Post-Scan Filters: ${postScanFilters.mkString(",")}
|Output: ${output.mkString(", ")}
""".stripMargin)
val batchExec = BatchScanExec(output, scan)
val filterCondition = postScanFilters.reduceLeftOption(And)
val withFilter = filterCondition.map(FilterExec(_, batchExec)).getOrElse(batchExec)
val withProjection = if (withFilter.output != project || !batchExec.supportsColumnar) {
ProjectExec(project, withFilter)
} else {
withFilter
}
withProjection :: Nil
case r: StreamingDataSourceV2Relation if r.startOffset.isDefined && r.endOffset.isDefined =>
val microBatchStream = r.stream.asInstanceOf[MicroBatchStream]
val scanExec = MicroBatchScanExec(
r.output, r.scan, microBatchStream, r.startOffset.get, r.endOffset.get)
val withProjection = if (scanExec.supportsColumnar) {
scanExec
} else {
// Add a Project here to make sure we produce unsafe rows.
ProjectExec(r.output, scanExec)
}
withProjection :: Nil
case r: StreamingDataSourceV2Relation if r.startOffset.isDefined && r.endOffset.isEmpty =>
val continuousStream = r.stream.asInstanceOf[ContinuousStream]
val scanExec = ContinuousScanExec(r.output, r.scan, continuousStream, r.startOffset.get)
val withProjection = if (scanExec.supportsColumnar) {
scanExec
} else {
// Add a Project here to make sure we produce unsafe rows.
ProjectExec(r.output, scanExec)
}
withProjection :: Nil
case WriteToDataSourceV2(writer, query) =>
WriteToDataSourceV2Exec(writer, planLater(query)) :: Nil
case CreateV2Table(catalog, ident, schema, parts, props, ifNotExists) =>
CreateTableExec(catalog, ident, schema, parts, props, ifNotExists) :: Nil
case CreateTableAsSelect(catalog, ident, parts, query, props, options, ifNotExists) =>
val writeOptions = new CaseInsensitiveStringMap(options.asJava)
catalog match {
case staging: StagingTableCatalog =>
AtomicCreateTableAsSelectExec(
staging, ident, parts, query, planLater(query), props, writeOptions, ifNotExists) :: Nil
case _ =>
CreateTableAsSelectExec(
catalog, ident, parts, query, planLater(query), props, writeOptions, ifNotExists) :: Nil
}
case ReplaceTable(catalog, ident, schema, parts, props, orCreate) =>
catalog match {
case staging: StagingTableCatalog =>
AtomicReplaceTableExec(staging, ident, schema, parts, props, orCreate = orCreate) :: Nil
case _ =>
ReplaceTableExec(catalog, ident, schema, parts, props, orCreate = orCreate) :: Nil
}
case ReplaceTableAsSelect(catalog, ident, parts, query, props, options, orCreate) =>
val writeOptions = new CaseInsensitiveStringMap(options.asJava)
catalog match {
case staging: StagingTableCatalog =>
AtomicReplaceTableAsSelectExec(
staging,
ident,
parts,
query,
planLater(query),
props,
writeOptions,
orCreate = orCreate) :: Nil
case _ =>
ReplaceTableAsSelectExec(
catalog,
ident,
parts,
query,
planLater(query),
props,
writeOptions,
orCreate = orCreate) :: Nil
}
case AppendData(r: DataSourceV2Relation, query, writeOptions, _) =>
r.table.asWritable match {
case v1 if v1.supports(TableCapability.V1_BATCH_WRITE) =>
AppendDataExecV1(v1, writeOptions.asOptions, query) :: Nil
case v2 =>
AppendDataExec(v2, writeOptions.asOptions, planLater(query)) :: Nil
}
case OverwriteByExpression(r: DataSourceV2Relation, deleteExpr, query, writeOptions, _) =>
// fail if any filter cannot be converted. correctness depends on removing all matching data.
val filters = splitConjunctivePredicates(deleteExpr).map {
filter => DataSourceStrategy.translateFilter(deleteExpr).getOrElse(
throw new AnalysisException(s"Cannot translate expression to source filter: $filter"))
}.toArray
r.table.asWritable match {
case v1 if v1.supports(TableCapability.V1_BATCH_WRITE) =>
OverwriteByExpressionExecV1(v1, filters, writeOptions.asOptions, query) :: Nil
case v2 =>
OverwriteByExpressionExec(v2, filters, writeOptions.asOptions, planLater(query)) :: Nil
}
case OverwritePartitionsDynamic(r: DataSourceV2Relation, query, writeOptions, _) =>
OverwritePartitionsDynamicExec(
r.table.asWritable, writeOptions.asOptions, planLater(query)) :: Nil
case DeleteFromTable(r: DataSourceV2Relation, condition) =>
if (condition.exists(SubqueryExpression.hasSubquery)) {
throw new AnalysisException(
s"Delete by condition with subquery is not supported: $condition")
}
// fail if any filter cannot be converted. correctness depends on removing all matching data.
val filters = DataSourceStrategy.normalizeFilters(condition.toSeq, r.output)
.flatMap(splitConjunctivePredicates(_).map {
f => DataSourceStrategy.translateFilter(f).getOrElse(
throw new AnalysisException(s"Exec update failed:" +
s" cannot translate expression to source filter: $f"))
}).toArray
DeleteFromTableExec(r.table.asDeletable, filters) :: Nil
case WriteToContinuousDataSource(writer, query) =>
WriteToContinuousDataSourceExec(writer, planLater(query)) :: Nil
case Repartition(1, false, child) =>
val isContinuous = child.find {
case r: StreamingDataSourceV2Relation => r.stream.isInstanceOf[ContinuousStream]
case _ => false
}.isDefined
if (isContinuous) {
ContinuousCoalesceExec(1, planLater(child)) :: Nil
} else {
Nil
}
case desc @ DescribeTable(r: DataSourceV2Relation, isExtended) =>
DescribeTableExec(desc.output, r.table, isExtended) :: Nil
case DropTable(catalog, ident, ifExists) =>
DropTableExec(catalog, ident, ifExists) :: Nil
case AlterTable(catalog, ident, _, changes) =>
AlterTableExec(catalog, ident, changes) :: Nil
case r: ShowNamespaces =>
ShowNamespacesExec(r.output, r.catalog, r.namespace, r.pattern) :: Nil
case r : ShowTables =>
ShowTablesExec(r.output, r.catalog, r.namespace, r.pattern) :: Nil
case _ => Nil
}
}
|
bdrillard/spark
|
sql/core/src/main/scala/org/apache/spark/sql/execution/datasources/v2/DataSourceV2Strategy.scala
|
Scala
|
apache-2.0
| 13,282 |
/*
* 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.expressions
import java.sql.{Date, Timestamp}
import org.apache.spark.SparkFunSuite
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.analysis.TypeCheckResult.TypeCheckFailure
import org.apache.spark.sql.catalyst.dsl.expressions._
import org.apache.spark.sql.catalyst.expressions.codegen.CodegenContext
import org.apache.spark.sql.types._
class ArithmeticExpressionSuite extends SparkFunSuite with ExpressionEvalHelper {
import IntegralLiteralTestUtils._
/**
* Runs through the testFunc for all numeric data types.
*
* @param testFunc a test function that accepts a conversion function to convert an integer
* into another data type.
*/
private def testNumericDataTypes(testFunc: (Int => Any) => Unit): Unit = {
testFunc(_.toByte)
testFunc(_.toShort)
testFunc(identity)
testFunc(_.toLong)
testFunc(_.toFloat)
testFunc(_.toDouble)
testFunc(Decimal(_))
}
test("+ (Add)") {
testNumericDataTypes { convert =>
val left = Literal(convert(1))
val right = Literal(convert(2))
checkEvaluation(Add(left, right), convert(3))
checkEvaluation(Add(Literal.create(null, left.dataType), right), null)
checkEvaluation(Add(left, Literal.create(null, right.dataType)), null)
}
checkEvaluation(Add(positiveShortLit, negativeShortLit), -1.toShort)
checkEvaluation(Add(positiveIntLit, negativeIntLit), -1)
checkEvaluation(Add(positiveLongLit, negativeLongLit), -1L)
DataTypeTestUtils.numericAndInterval.foreach { tpe =>
checkConsistencyBetweenInterpretedAndCodegen(Add, tpe, tpe)
}
}
test("- (UnaryMinus)") {
testNumericDataTypes { convert =>
val input = Literal(convert(1))
val dataType = input.dataType
checkEvaluation(UnaryMinus(input), convert(-1))
checkEvaluation(UnaryMinus(Literal.create(null, dataType)), null)
}
checkEvaluation(UnaryMinus(Literal(Long.MinValue)), Long.MinValue)
checkEvaluation(UnaryMinus(Literal(Int.MinValue)), Int.MinValue)
checkEvaluation(UnaryMinus(Literal(Short.MinValue)), Short.MinValue)
checkEvaluation(UnaryMinus(Literal(Byte.MinValue)), Byte.MinValue)
checkEvaluation(UnaryMinus(positiveShortLit), (- positiveShort).toShort)
checkEvaluation(UnaryMinus(negativeShortLit), (- negativeShort).toShort)
checkEvaluation(UnaryMinus(positiveIntLit), - positiveInt)
checkEvaluation(UnaryMinus(negativeIntLit), - negativeInt)
checkEvaluation(UnaryMinus(positiveLongLit), - positiveLong)
checkEvaluation(UnaryMinus(negativeLongLit), - negativeLong)
DataTypeTestUtils.numericAndInterval.foreach { tpe =>
checkConsistencyBetweenInterpretedAndCodegen(UnaryMinus, tpe)
}
}
test("- (Minus)") {
testNumericDataTypes { convert =>
val left = Literal(convert(1))
val right = Literal(convert(2))
checkEvaluation(Subtract(left, right), convert(-1))
checkEvaluation(Subtract(Literal.create(null, left.dataType), right), null)
checkEvaluation(Subtract(left, Literal.create(null, right.dataType)), null)
}
checkEvaluation(Subtract(positiveShortLit, negativeShortLit),
(positiveShort - negativeShort).toShort)
checkEvaluation(Subtract(positiveIntLit, negativeIntLit), positiveInt - negativeInt)
checkEvaluation(Subtract(positiveLongLit, negativeLongLit), positiveLong - negativeLong)
DataTypeTestUtils.numericAndInterval.foreach { tpe =>
checkConsistencyBetweenInterpretedAndCodegen(Subtract, tpe, tpe)
}
}
test("* (Multiply)") {
testNumericDataTypes { convert =>
val left = Literal(convert(1))
val right = Literal(convert(2))
checkEvaluation(Multiply(left, right), convert(2))
checkEvaluation(Multiply(Literal.create(null, left.dataType), right), null)
checkEvaluation(Multiply(left, Literal.create(null, right.dataType)), null)
}
checkEvaluation(Multiply(positiveShortLit, negativeShortLit),
(positiveShort * negativeShort).toShort)
checkEvaluation(Multiply(positiveIntLit, negativeIntLit), positiveInt * negativeInt)
checkEvaluation(Multiply(positiveLongLit, negativeLongLit), positiveLong * negativeLong)
DataTypeTestUtils.numericTypeWithoutDecimal.foreach { tpe =>
checkConsistencyBetweenInterpretedAndCodegen(Multiply, tpe, tpe)
}
}
private def testDecimalAndDoubleType(testFunc: (Int => Any) => Unit): Unit = {
testFunc(_.toDouble)
testFunc(Decimal(_))
}
test("/ (Divide) basic") {
testDecimalAndDoubleType { convert =>
val left = Literal(convert(2))
val right = Literal(convert(1))
val dataType = left.dataType
checkEvaluation(Divide(left, right), convert(2))
checkEvaluation(Divide(Literal.create(null, dataType), right), null)
checkEvaluation(Divide(left, Literal.create(null, right.dataType)), null)
checkEvaluation(Divide(left, Literal(convert(0))), null) // divide by zero
}
Seq(DoubleType, DecimalType.SYSTEM_DEFAULT).foreach { tpe =>
checkConsistencyBetweenInterpretedAndCodegen(Divide, tpe, tpe)
}
}
// By fixing SPARK-15776, Divide's inputType is required to be DoubleType of DecimalType.
// TODO: in future release, we should add a IntegerDivide to support integral types.
ignore("/ (Divide) for integral type") {
checkEvaluation(Divide(Literal(1.toByte), Literal(2.toByte)), 0.toByte)
checkEvaluation(Divide(Literal(1.toShort), Literal(2.toShort)), 0.toShort)
checkEvaluation(Divide(Literal(1), Literal(2)), 0)
checkEvaluation(Divide(Literal(1.toLong), Literal(2.toLong)), 0.toLong)
checkEvaluation(Divide(positiveShortLit, negativeShortLit), 0.toShort)
checkEvaluation(Divide(positiveIntLit, negativeIntLit), 0)
checkEvaluation(Divide(positiveLongLit, negativeLongLit), 0L)
}
test("% (Remainder)") {
testNumericDataTypes { convert =>
val left = Literal(convert(1))
val right = Literal(convert(2))
checkEvaluation(Remainder(left, right), convert(1))
checkEvaluation(Remainder(Literal.create(null, left.dataType), right), null)
checkEvaluation(Remainder(left, Literal.create(null, right.dataType)), null)
checkEvaluation(Remainder(left, Literal(convert(0))), null) // mod by 0
}
checkEvaluation(Remainder(positiveShortLit, positiveShortLit), 0.toShort)
checkEvaluation(Remainder(negativeShortLit, negativeShortLit), 0.toShort)
checkEvaluation(Remainder(positiveIntLit, positiveIntLit), 0)
checkEvaluation(Remainder(negativeIntLit, negativeIntLit), 0)
checkEvaluation(Remainder(positiveLongLit, positiveLongLit), 0L)
checkEvaluation(Remainder(negativeLongLit, negativeLongLit), 0L)
DataTypeTestUtils.numericTypeWithoutDecimal.foreach { tpe =>
checkConsistencyBetweenInterpretedAndCodegen(Remainder, tpe, tpe)
}
}
test("SPARK-17617: % (Remainder) double % double on super big double") {
val leftDouble = Literal(-5083676433652386516D)
val rightDouble = Literal(10D)
checkEvaluation(Remainder(leftDouble, rightDouble), -6.0D)
// Float has smaller precision
val leftFloat = Literal(-5083676433652386516F)
val rightFloat = Literal(10F)
checkEvaluation(Remainder(leftFloat, rightFloat), -2.0F)
}
test("Abs") {
testNumericDataTypes { convert =>
val input = Literal(convert(1))
val dataType = input.dataType
checkEvaluation(Abs(Literal(convert(0))), convert(0))
checkEvaluation(Abs(Literal(convert(1))), convert(1))
checkEvaluation(Abs(Literal(convert(-1))), convert(1))
checkEvaluation(Abs(Literal.create(null, dataType)), null)
}
checkEvaluation(Abs(positiveShortLit), positiveShort)
checkEvaluation(Abs(negativeShortLit), (- negativeShort).toShort)
checkEvaluation(Abs(positiveIntLit), positiveInt)
checkEvaluation(Abs(negativeIntLit), - negativeInt)
checkEvaluation(Abs(positiveLongLit), positiveLong)
checkEvaluation(Abs(negativeLongLit), - negativeLong)
DataTypeTestUtils.numericTypeWithoutDecimal.foreach { tpe =>
checkConsistencyBetweenInterpretedAndCodegen(Abs, tpe)
}
}
test("pmod") {
testNumericDataTypes { convert =>
val left = Literal(convert(7))
val right = Literal(convert(3))
checkEvaluation(Pmod(left, right), convert(1))
checkEvaluation(Pmod(Literal.create(null, left.dataType), right), null)
checkEvaluation(Pmod(left, Literal.create(null, right.dataType)), null)
checkEvaluation(Pmod(left, Literal(convert(0))), null) // mod by 0
}
checkEvaluation(Pmod(Literal(-7), Literal(3)), 2)
checkEvaluation(Pmod(Literal(7.2D), Literal(4.1D)), 3.1000000000000005)
checkEvaluation(Pmod(Literal(Decimal(0.7)), Literal(Decimal(0.2))), Decimal(0.1))
checkEvaluation(Pmod(Literal(2L), Literal(Long.MaxValue)), 2L)
checkEvaluation(Pmod(positiveShort, negativeShort), positiveShort.toShort)
checkEvaluation(Pmod(positiveInt, negativeInt), positiveInt)
checkEvaluation(Pmod(positiveLong, negativeLong), positiveLong)
// mod by 0
checkEvaluation(Pmod(Literal(-7), Literal(0)), null)
checkEvaluation(Pmod(Literal(7.2D), Literal(0D)), null)
checkEvaluation(Pmod(Literal(7.2F), Literal(0F)), null)
checkEvaluation(Pmod(Literal(2.toByte), Literal(0.toByte)), null)
checkEvaluation(Pmod(positiveShort, 0.toShort), null)
}
test("function least") {
val row = create_row(1, 2, "a", "b", "c")
val c1 = 'a.int.at(0)
val c2 = 'a.int.at(1)
val c3 = 'a.string.at(2)
val c4 = 'a.string.at(3)
val c5 = 'a.string.at(4)
checkEvaluation(Least(Seq(c4, c3, c5)), "a", row)
checkEvaluation(Least(Seq(c1, c2)), 1, row)
checkEvaluation(Least(Seq(c1, c2, Literal(-1))), -1, row)
checkEvaluation(Least(Seq(c4, c5, c3, c3, Literal("a"))), "a", row)
val nullLiteral = Literal.create(null, IntegerType)
checkEvaluation(Least(Seq(nullLiteral, nullLiteral)), null)
checkEvaluation(Least(Seq(Literal(null), Literal(null))), null, InternalRow.empty)
checkEvaluation(Least(Seq(Literal(-1.0), Literal(2.5))), -1.0, InternalRow.empty)
checkEvaluation(Least(Seq(Literal(-1), Literal(2))), -1, InternalRow.empty)
checkEvaluation(
Least(Seq(Literal((-1.0).toFloat), Literal(2.5.toFloat))), (-1.0).toFloat, InternalRow.empty)
checkEvaluation(
Least(Seq(Literal(Long.MaxValue), Literal(Long.MinValue))), Long.MinValue, InternalRow.empty)
checkEvaluation(Least(Seq(Literal(1.toByte), Literal(2.toByte))), 1.toByte, InternalRow.empty)
checkEvaluation(
Least(Seq(Literal(1.toShort), Literal(2.toByte.toShort))), 1.toShort, InternalRow.empty)
checkEvaluation(Least(Seq(Literal("abc"), Literal("aaaa"))), "aaaa", InternalRow.empty)
checkEvaluation(Least(Seq(Literal(true), Literal(false))), false, InternalRow.empty)
checkEvaluation(
Least(Seq(
Literal(BigDecimal("1234567890987654321123456")),
Literal(BigDecimal("1234567890987654321123458")))),
BigDecimal("1234567890987654321123456"), InternalRow.empty)
checkEvaluation(
Least(Seq(Literal(Date.valueOf("2015-01-01")), Literal(Date.valueOf("2015-07-01")))),
Date.valueOf("2015-01-01"), InternalRow.empty)
checkEvaluation(
Least(Seq(
Literal(Timestamp.valueOf("2015-07-01 08:00:00")),
Literal(Timestamp.valueOf("2015-07-01 10:00:00")))),
Timestamp.valueOf("2015-07-01 08:00:00"), InternalRow.empty)
// Type checking error
assert(
Least(Seq(Literal(1), Literal("1"))).checkInputDataTypes() ==
TypeCheckFailure("The expressions should all have the same type, " +
"got LEAST(int, string)."))
DataTypeTestUtils.ordered.foreach { dt =>
checkConsistencyBetweenInterpretedAndCodegen(Least, dt, 2)
}
val least = Least(Seq(
Literal.create(Seq(1, 2), ArrayType(IntegerType, containsNull = false)),
Literal.create(Seq(1, 3, null), ArrayType(IntegerType, containsNull = true))))
assert(least.dataType === ArrayType(IntegerType, containsNull = true))
checkEvaluation(least, Seq(1, 2))
}
test("function greatest") {
val row = create_row(1, 2, "a", "b", "c")
val c1 = 'a.int.at(0)
val c2 = 'a.int.at(1)
val c3 = 'a.string.at(2)
val c4 = 'a.string.at(3)
val c5 = 'a.string.at(4)
checkEvaluation(Greatest(Seq(c4, c5, c3)), "c", row)
checkEvaluation(Greatest(Seq(c2, c1)), 2, row)
checkEvaluation(Greatest(Seq(c1, c2, Literal(2))), 2, row)
checkEvaluation(Greatest(Seq(c4, c5, c3, Literal("ccc"))), "ccc", row)
val nullLiteral = Literal.create(null, IntegerType)
checkEvaluation(Greatest(Seq(nullLiteral, nullLiteral)), null)
checkEvaluation(Greatest(Seq(Literal(null), Literal(null))), null, InternalRow.empty)
checkEvaluation(Greatest(Seq(Literal(-1.0), Literal(2.5))), 2.5, InternalRow.empty)
checkEvaluation(Greatest(Seq(Literal(-1), Literal(2))), 2, InternalRow.empty)
checkEvaluation(
Greatest(Seq(Literal((-1.0).toFloat), Literal(2.5.toFloat))), 2.5.toFloat, InternalRow.empty)
checkEvaluation(Greatest(
Seq(Literal(Long.MaxValue), Literal(Long.MinValue))), Long.MaxValue, InternalRow.empty)
checkEvaluation(
Greatest(Seq(Literal(1.toByte), Literal(2.toByte))), 2.toByte, InternalRow.empty)
checkEvaluation(
Greatest(Seq(Literal(1.toShort), Literal(2.toByte.toShort))), 2.toShort, InternalRow.empty)
checkEvaluation(Greatest(Seq(Literal("abc"), Literal("aaaa"))), "abc", InternalRow.empty)
checkEvaluation(Greatest(Seq(Literal(true), Literal(false))), true, InternalRow.empty)
checkEvaluation(
Greatest(Seq(
Literal(BigDecimal("1234567890987654321123456")),
Literal(BigDecimal("1234567890987654321123458")))),
BigDecimal("1234567890987654321123458"), InternalRow.empty)
checkEvaluation(Greatest(
Seq(Literal(Date.valueOf("2015-01-01")), Literal(Date.valueOf("2015-07-01")))),
Date.valueOf("2015-07-01"), InternalRow.empty)
checkEvaluation(
Greatest(Seq(
Literal(Timestamp.valueOf("2015-07-01 08:00:00")),
Literal(Timestamp.valueOf("2015-07-01 10:00:00")))),
Timestamp.valueOf("2015-07-01 10:00:00"), InternalRow.empty)
// Type checking error
assert(
Greatest(Seq(Literal(1), Literal("1"))).checkInputDataTypes() ==
TypeCheckFailure("The expressions should all have the same type, " +
"got GREATEST(int, string)."))
DataTypeTestUtils.ordered.foreach { dt =>
checkConsistencyBetweenInterpretedAndCodegen(Greatest, dt, 2)
}
val greatest = Greatest(Seq(
Literal.create(Seq(1, 2), ArrayType(IntegerType, containsNull = false)),
Literal.create(Seq(1, 3, null), ArrayType(IntegerType, containsNull = true))))
assert(greatest.dataType === ArrayType(IntegerType, containsNull = true))
checkEvaluation(greatest, Seq(1, 3, null))
}
test("SPARK-22499: Least and greatest should not generate codes beyond 64KB") {
val N = 3000
val strings = (1 to N).map(x => "s" * x)
val inputsExpr = strings.map(Literal.create(_, StringType))
checkEvaluation(Least(inputsExpr), "s" * 1, EmptyRow)
checkEvaluation(Greatest(inputsExpr), "s" * N, EmptyRow)
}
test("SPARK-22704: Least and greatest use less global variables") {
val ctx1 = new CodegenContext()
Least(Seq(Literal(1), Literal(1))).genCode(ctx1)
assert(ctx1.inlinedMutableStates.size == 1)
val ctx2 = new CodegenContext()
Greatest(Seq(Literal(1), Literal(1))).genCode(ctx2)
assert(ctx2.inlinedMutableStates.size == 1)
}
}
|
tejasapatil/spark
|
sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/ArithmeticExpressionSuite.scala
|
Scala
|
apache-2.0
| 16,429 |
/*
* 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.carbondata.integration.spark.testsuite.dataload
import java.io.File
import org.apache.spark.SparkContext
import org.apache.spark.sql.Row
import org.apache.spark.sql.test.util.QueryTest
import org.apache.spark.util.SparkUtil4Test
import org.scalatest.BeforeAndAfterAll
import org.apache.carbondata.core.constants.CarbonCommonConstants
import org.apache.carbondata.core.util.{CarbonProperties, CarbonUtil}
/**
* Test Class for data loading using multiple temp yarn dirs.
* It would be better to test with massive data,
* since small amount of data will generate few (or none) temp files,
* which will not fully utilize all the temp dirs configured.
*/
class TestLoadDataWithYarnLocalDirs extends QueryTest with BeforeAndAfterAll {
override def beforeAll {
sql("drop table if exists carbontable_yarnLocalDirs")
sql("CREATE TABLE carbontable_yarnLocalDirs (id int, name string, city string, age int) " +
"STORED BY 'org.apache.carbondata.format'")
}
private def getMockedYarnLocalDirs = {
val multi_dir_root = System.getProperty("java.io.tmpdir") + File.separator +
"yarn_local_multiple_dir" + File.separator
(1 to 3).map(multi_dir_root + "multiple" + _).mkString(",")
}
private def initYarnLocalDir = {
//set all the possible env for yarn local dirs in case of various deploy environment
val sparkConf = SparkContext.getOrCreate().getConf
sparkConf.set("SPARK_EXECUTOR_DIRS", getMockedYarnLocalDirs)
sparkConf.set("SPARK_LOCAL_DIRS", getMockedYarnLocalDirs)
sparkConf.set("MESOS_DIRECTORY", getMockedYarnLocalDirs)
sparkConf.set("spark.local.dir", getMockedYarnLocalDirs)
sparkConf.set("LOCAL_DIRS", getMockedYarnLocalDirs)
SparkUtil4Test.getOrCreateLocalRootDirs(sparkConf)
}
private def cleanUpYarnLocalDir = {
initYarnLocalDir
.foreach(dir => CarbonUtil.deleteFoldersAndFiles(new File(dir)))
}
private def enableMultipleDir = {
CarbonProperties.getInstance().addProperty("carbon.use.local.dir", "true")
CarbonProperties.getInstance().addProperty(
CarbonCommonConstants.CARBON_USE_MULTI_TEMP_DIR, "true")
}
private def disableMultipleDir = {
CarbonProperties.getInstance().addProperty("carbon.use.local.dir", "false")
CarbonProperties.getInstance().addProperty(CarbonCommonConstants.CARBON_USE_MULTI_TEMP_DIR,
CarbonCommonConstants.CARBON_USE_MULTI_TEMP_DIR_DEFAULT)
}
test("test carbon table data loading for multiple temp dir") {
initYarnLocalDir
enableMultipleDir
sql(s"LOAD DATA LOCAL INPATH '${resourcesPath}/sample.csv' INTO TABLE " +
"carbontable_yarnLocalDirs OPTIONS('DELIMITER'= ',')")
disableMultipleDir
checkAnswer(sql("select id from carbontable_yarnLocalDirs"),
Seq(Row(1), Row(2), Row(3), Row(3)))
cleanUpYarnLocalDir
}
override def afterAll {
sql("drop table if exists carbontable_yarnLocalDirs")
cleanUpYarnLocalDir
}
}
|
aniketadnaik/carbondataStreamIngest
|
integration/spark-common-test/src/test/scala/org/apache/carbondata/integration/spark/testsuite/dataload/TestLoadDataWithYarnLocalDirs.scala
|
Scala
|
apache-2.0
| 3,770 |
package cgta.otest
package runner
import sbt.testing.{Fingerprint, Selector, TaskDef, Status, OptionalThrowable}
//////////////////////////////////////////////////////////////
// Copyright (c) 2014 Ben Jackman, Jeff Gomberg
// All Rights Reserved
// please contact [email protected] or [email protected]
// for licensing inquiries
// Created by bjackman @ 5/28/14 10:46 AM
//////////////////////////////////////////////////////////////
sealed trait TestResult extends sbt.testing.Event {
val taskDef: TaskDef
override def selector(): Selector = taskDef.selectors().head
override def fingerprint(): Fingerprint = taskDef.fingerprint()
override def fullyQualifiedName(): String = taskDef.fullyQualifiedName()
def name: String
def isPassed: Boolean = false
def isFailed: Boolean = false
def isAborted: Boolean = false
def isIgnored: Boolean = false
def isIgnoredOnly: Boolean = false
}
object TestResults {
case class Passed(name: String, duration: Long)(implicit val taskDef: TaskDef) extends TestResult {
override val isPassed = true
override def throwable(): OptionalThrowable = new OptionalThrowable()
override def status(): Status = Status.Success
}
case class Ignored(name: String, becauseOnly : Boolean)(implicit val taskDef: TaskDef) extends TestResult {
val duration = 0L
override val isIgnored = true
override val isIgnoredOnly = becauseOnly
override def throwable(): OptionalThrowable = new OptionalThrowable()
override def status(): Status = Status.Ignored
}
sealed trait Failed extends TestResult
case class FailedBad(name: String, duration: Long)(implicit val taskDef: TaskDef) extends Failed {
override val isFailed = true
override def throwable(): OptionalThrowable = new OptionalThrowable()
override def status(): Status = Status.Failure
}
case class FailedAssertion(
name: String, e: AssertionFailureException, duration: Long)(implicit val taskDef: TaskDef) extends Failed {
override val isFailed = true
override def throwable(): OptionalThrowable = new OptionalThrowable(e)
override def status(): Status = Status.Failure
}
case class FailedUnexpectedException(
name: String, e: Throwable, duration: Long)(implicit val taskDef: TaskDef) extends Failed {
override val isFailed = true
override def throwable(): OptionalThrowable = new OptionalThrowable(e)
override def status(): Status = Status.Failure
}
case class FailedFatalException(
name: String, e: Throwable, duration: Long)(implicit val taskDef: TaskDef) extends Failed {
override val isAborted = true
override def throwable(): OptionalThrowable = new OptionalThrowable(e)
override def status(): Status = Status.Error
}
case class FailedWithEitherTrace(
name: String,
trace: Seq[Either[String, StackTraceElement]],
duration: Long,
failed: Boolean = false,
aborted: Boolean = false)(implicit val taskDef: TaskDef) extends Failed {
override val isFailed = failed
override val isAborted = aborted
override def throwable(): OptionalThrowable = new OptionalThrowable()
override def status(): Status = Status.Error
}
}
|
cgta/otest
|
otest/shared/src/main/scala/cgta/otest/runner/TestResults.scala
|
Scala
|
mit
| 3,170 |
package justin.db.replica.write
import justin.db.Data
import justin.db.actors.protocol.{StorageNodeConflictedWrite, StorageNodeFailedWrite, StorageNodeSuccessfulWrite, StorageNodeWriteResponse}
import justin.db.replica.IsPrimaryOrReplica
import justin.db.storage.PluggableStorageProtocol.StorageGetData
import justin.db.storage.{GetStorageProtocol, PutStorageProtocol}
import justin.db.vectorclocks.VectorClockComparator
import justin.db.vectorclocks.VectorClockComparator.VectorClockRelation
import scala.concurrent.{ExecutionContext, Future}
class ReplicaLocalWriter(storage: GetStorageProtocol with PutStorageProtocol)(implicit ec: ExecutionContext) {
def apply(newData: Data, isPrimaryOrReplica: IsPrimaryOrReplica): Future[StorageNodeWriteResponse] = {
storage.get(newData.id)(isPrimaryOrReplica).flatMap {
case StorageGetData.None => putSingleSuccessfulWrite(newData, isPrimaryOrReplica)
case StorageGetData.Single(oldData) => handleExistedSingleData(oldData, newData, isPrimaryOrReplica)
} recover { case _ => StorageNodeFailedWrite(newData.id) }
}
private def handleExistedSingleData(oldData: Data, newData: Data, isPrimaryOrReplica: IsPrimaryOrReplica) = {
new VectorClockComparator().apply(oldData.vclock, newData.vclock) match {
case VectorClockRelation.Predecessor => Future.successful(StorageNodeFailedWrite(newData.id))
case VectorClockRelation.Conflict => Future.successful(StorageNodeConflictedWrite(oldData, newData))
case VectorClockRelation.Consequent => putSingleSuccessfulWrite(newData, isPrimaryOrReplica)
}
}
private def putSingleSuccessfulWrite(newData: Data, resolveDataOriginality: IsPrimaryOrReplica) = {
storage.put(newData)(resolveDataOriginality).map(_ => StorageNodeSuccessfulWrite(newData.id))
}
}
|
speedcom/JustinDB
|
justin-core/src/main/scala/justin/db/replica/write/ReplicaLocalWriter.scala
|
Scala
|
apache-2.0
| 1,832 |
package akashic.storage.admin
import akashic.storage.server
import akka.http.scaladsl.model.{HttpEntity, StatusCodes}
import akka.http.scaladsl.server.Directives._
import scala.util.{Failure, Success, Try}
import scala.xml.XML
object Update {
val matcher =
put &
path("admin" / "user" / Segment) &
entity(as[String])
val route = matcher { (id: String, xmlString: String) =>
authenticate {
val status = Try {
run(server.users, id, xmlString)
} match {
case Success(_) => StatusCodes.OK
case Failure(_) => StatusCodes.ServerError // FIXME
}
complete(HttpEntity.Empty)
}
}
case class Result()
def run(users: UserDB, id: String, body: String): Result = {
val xml = XML.loadString(body)
val user = users.find(id) match {
case Some(a) => a
case None => Error.failWith(Error.NotFound())
}
val newUser = user.modifyWith(xml)
users.update(id, newUser)
Result()
}
}
|
akiradeveloper/fss3
|
src/main/scala/akashic/storage/admin/Update.scala
|
Scala
|
apache-2.0
| 977 |
package dotty.tools
package dotc
package core
import annotation.tailrec
import Symbols._
import Contexts._, Names._, Phases._, printing.Texts._, printing.Printer
import util.Spans.Span, util.SourcePosition
import collection.mutable.ListBuffer
import dotty.tools.dotc.transform.MegaPhase
import ast.tpd._
import scala.language.implicitConversions
import printing.Formatting._
/** This object provides useful implicit decorators for types defined elsewhere */
object Decorators {
/** Turns Strings into PreNames, adding toType/TermName methods */
implicit class PreNamedString(val s: String) extends AnyVal with PreName {
def toTypeName: TypeName = typeName(s)
def toTermName: TermName = termName(s)
def toText(printer: Printer): Text = Str(s)
}
implicit class StringDecorator(val s: String) extends AnyVal {
def splitWhere(f: Char => Boolean, doDropIndex: Boolean): Option[(String, String)] = {
def splitAt(idx: Int, doDropIndex: Boolean): Option[(String, String)] =
if (idx == -1) None
else Some((s.take(idx), s.drop(if (doDropIndex) idx + 1 else idx)))
splitAt(s.indexWhere(f), doDropIndex)
}
}
/** Implements a findSymbol method on iterators of Symbols that
* works like find but avoids Option, replacing None with NoSymbol.
*/
implicit class SymbolIteratorDecorator(val it: Iterator[Symbol]) extends AnyVal {
final def findSymbol(p: Symbol => Boolean): Symbol = {
while (it.hasNext) {
val sym = it.next()
if (p(sym)) return sym
}
NoSymbol
}
}
final val MaxFilterRecursions = 1000
/** Implements filterConserve, zipWithConserve methods
* on lists that avoid duplication of list nodes where feasible.
*/
implicit class ListDecorator[T](val xs: List[T]) extends AnyVal {
final def mapconserve[U](f: T => U): List[U] = {
@tailrec
def loop(mapped: ListBuffer[U], unchanged: List[U], pending: List[T]): List[U] =
if (pending.isEmpty)
if (mapped eq null) unchanged
else mapped.prependToList(unchanged)
else {
val head0 = pending.head
val head1 = f(head0)
if (head1.asInstanceOf[AnyRef] eq head0.asInstanceOf[AnyRef])
loop(mapped, unchanged, pending.tail)
else {
val b = if (mapped eq null) new ListBuffer[U] else mapped
var xc = unchanged
while (xc ne pending) {
b += xc.head
xc = xc.tail
}
b += head1
val tail0 = pending.tail
loop(b, tail0.asInstanceOf[List[U]], tail0)
}
}
loop(null, xs.asInstanceOf[List[U]], xs)
}
/** Like `xs filter p` but returns list `xs` itself - instead of a copy -
* if `p` is true for all elements and `xs` is not longer
* than `MaxFilterRecursions`.
*/
def filterConserve(p: T => Boolean): List[T] = {
def loop(xs: List[T], nrec: Int): List[T] = xs match {
case Nil => xs
case x :: xs1 =>
if (nrec < MaxFilterRecursions) {
val ys1 = loop(xs1, nrec + 1)
if (p(x))
if (ys1 eq xs1) xs else x :: ys1
else
ys1
}
else xs filter p
}
loop(xs, 0)
}
/** Like `xs.lazyZip(ys).map(f)`, but returns list `xs` itself
* - instead of a copy - if function `f` maps all elements of
* `xs` to themselves. Also, it is required that `ys` is at least
* as long as `xs`.
*/
def zipWithConserve[U](ys: List[U])(f: (T, U) => T): List[T] =
if (xs.isEmpty || ys.isEmpty) Nil
else {
val x1 = f(xs.head, ys.head)
val xs1 = xs.tail.zipWithConserve(ys.tail)(f)
if ((x1.asInstanceOf[AnyRef] eq xs.head.asInstanceOf[AnyRef]) &&
(xs1 eq xs.tail)) xs
else x1 :: xs1
}
/** Like `xs.lazyZip(xs.indices).map(f)`, but returns list `xs` itself
* - instead of a copy - if function `f` maps all elements of
* `xs` to themselves.
*/
def mapWithIndexConserve[U <: T](f: (T, Int) => U): List[U] =
def recur(xs: List[T], idx: Int): List[U] =
if xs.isEmpty then Nil
else
val x1 = f(xs.head, idx)
val xs1 = recur(xs.tail, idx + 1)
if (x1.asInstanceOf[AnyRef] eq xs.head.asInstanceOf[AnyRef])
&& (xs1 eq xs.tail)
then xs.asInstanceOf[List[U]]
else x1 :: xs1
recur(xs, 0)
final def hasSameLengthAs[U](ys: List[U]): Boolean = {
@tailrec def loop(xs: List[T], ys: List[U]): Boolean =
if (xs.isEmpty) ys.isEmpty
else ys.nonEmpty && loop(xs.tail, ys.tail)
loop(xs, ys)
}
@tailrec final def eqElements(ys: List[AnyRef]): Boolean = xs match {
case x :: _ =>
ys match {
case y :: _ =>
x.asInstanceOf[AnyRef].eq(y) &&
xs.tail.eqElements(ys.tail)
case _ => false
}
case nil => ys.isEmpty
}
/** Union on lists seen as sets */
def | (ys: List[T]): List[T] = xs ::: (ys filterNot (xs contains _))
/** Intersection on lists seen as sets */
def & (ys: List[T]): List[T] = xs filter (ys contains _)
}
extension ListOfListDecorator on [T, U](xss: List[List[T]]):
def nestedMap(f: T => U): List[List[U]] =
xss.map(_.map(f))
def nestedMapConserve(f: T => U): List[List[U]] =
xss.mapconserve(_.mapconserve(f))
def nestedZipWithConserve(yss: List[List[U]])(f: (T, U) => T): List[List[T]] =
xss.zipWithConserve(yss)((xs, ys) => xs.zipWithConserve(ys)(f))
implicit class TextToString(val text: Text) extends AnyVal {
def show(implicit ctx: Context): String = text.mkString(ctx.settings.pageWidth.value, ctx.settings.printLines.value)
}
/** Test whether a list of strings representing phases contains
* a given phase. See [[config.CompilerCommand#explainAdvanced]] for the
* exact meaning of "contains" here.
*/
implicit class PhaseListDecorator(val names: List[String]) extends AnyVal {
def containsPhase(phase: Phase): Boolean =
names.nonEmpty && {
phase match {
case phase: MegaPhase => phase.miniPhases.exists(containsPhase)
case _ =>
names exists { name =>
name == "all" || {
val strippedName = name.stripSuffix("+")
val logNextPhase = name != strippedName
phase.phaseName.startsWith(strippedName) ||
(logNextPhase && phase.prev.phaseName.startsWith(strippedName))
}
}
}
}
}
implicit class reportDeco[T](x: T) extends AnyVal {
def reporting(
op: WrappedResult[T] ?=> String,
printer: config.Printers.Printer = config.Printers.default): T = {
printer.println(op(using WrappedResult(x)))
x
}
}
implicit class genericDeco[T](val x: T) extends AnyVal {
def assertingErrorsReported(implicit ctx: Context): T = {
assert(ctx.reporter.errorsReported)
x
}
def assertingErrorsReported(msg: => String)(implicit ctx: Context): T = {
assert(ctx.reporter.errorsReported, msg)
x
}
}
implicit class StringInterpolators(val sc: StringContext) extends AnyVal {
/** General purpose string formatting */
def i(args: Any*)(implicit ctx: Context): String =
new StringFormatter(sc).assemble(args)
/** Formatting for error messages: Like `i` but suppress follow-on
* error messages after the first one if some of their arguments are "non-sensical".
*/
def em(args: Any*)(implicit ctx: Context): String =
new ErrorMessageFormatter(sc).assemble(args)
/** Formatting with added explanations: Like `em`, but add explanations to
* give more info about type variables and to disambiguate where needed.
*/
def ex(args: Any*)(implicit ctx: Context): String =
explained(em(args: _*))
}
implicit class ArrayInterpolator[T <: AnyRef](val arr: Array[T]) extends AnyVal {
def binarySearch(x: T): Int = java.util.Arrays.binarySearch(arr.asInstanceOf[Array[Object]], x)
}
}
|
som-snytt/dotty
|
compiler/src/dotty/tools/dotc/core/Decorators.scala
|
Scala
|
apache-2.0
| 8,177 |
package chrome.downloads.bindings
sealed trait DangerType
object DangerType {
val file: DangerType = "file".asInstanceOf[DangerType]
val url: DangerType = "url".asInstanceOf[DangerType]
val content: DangerType = "content".asInstanceOf[DangerType]
val uncommon: DangerType = "uncommon".asInstanceOf[DangerType]
val host: DangerType = "host".asInstanceOf[DangerType]
val unwanted: DangerType = "unwanted".asInstanceOf[DangerType]
val safe: DangerType = "safe".asInstanceOf[DangerType]
val accepted: DangerType = "accepted".asInstanceOf[DangerType]
}
|
lucidd/scala-js-chrome
|
bindings/src/main/scala/chrome/downloads/bindings/DangerType.scala
|
Scala
|
mit
| 565 |
/***********************************************************************
* 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.spark
import org.apache.spark.sql.{SQLContext, SparkSession}
import org.locationtech.geomesa.spark.jts.encoders.SpatialEncoders
/**
* User-facing module imports, sufficient for accessing the standard Spark-JTS functionality.
*/
package object jts extends DataFrameFunctions.Library with SpatialEncoders {
/**
* Initialization function that must be called before any JTS functionality
* is accessed. This function can be called directly, or one of the `initJTS`
* enrichment methods on [[SQLContext]] or [[SparkSession]] can be used instead.
*/
def initJTS(sqlContext: SQLContext): Unit = {
org.apache.spark.sql.jts.registerTypes()
udf.registerFunctions(sqlContext)
rules.registerOptimizations(sqlContext)
}
/** Enrichment over [[SQLContext]] to add `withJTS` "literate" method. */
implicit class SQLContextWithJTS(val sqlContext: SQLContext) extends AnyVal {
def withJTS: SQLContext = {
initJTS(sqlContext)
sqlContext
}
}
/** Enrichment over [[SparkSession]] to add `withJTS` "literate" method. */
implicit class SparkSessionWithJTS(val spark: SparkSession) extends AnyVal {
def withJTS: SparkSession = {
initJTS(spark.sqlContext)
spark
}
}
}
|
elahrvivaz/geomesa
|
geomesa-spark/geomesa-spark-jts/src/main/scala/org/locationtech/geomesa/spark/jts/package.scala
|
Scala
|
apache-2.0
| 1,729 |
package dotty.tools.backend.jvm
import dotty.tools.dotc.ast.tpd
import dotty.tools.dotc.core.Contexts._
import dotty.tools.dotc.core.Phases._
import dotty.tools.dotc.core.Symbols._
import dotty.tools.dotc.core.Flags.Trait
import dotty.tools.dotc.transform.MegaPhase.MiniPhase
/** Collect all super calls to trait members.
*
* For each super reference to trait member, register a call from the current class to the
* owner of the referenced member.
*
* This information is used to know if it is safe to remove a redundant mixin class.
* A redundant mixin class is one that is implemented by another mixin class. As the
* methods in a redundant mixin class could be implemented with a default abstract method,
* the redundant mixin class could be required as a parent by the JVM.
*/
class CollectSuperCalls extends MiniPhase {
import tpd._
override def phaseName: String = CollectSuperCalls.name
override def description: String = CollectSuperCalls.description
override def transformSelect(tree: Select)(using Context): Tree = {
tree.qualifier match {
case sup: Super =>
if (tree.symbol.owner.is(Trait))
registerSuperCall(ctx.owner.enclosingClass.asClass, tree.symbol.owner.asClass)
case _ =>
}
tree
}
private def registerSuperCall(sym: ClassSymbol, calls: ClassSymbol)(using Context) = {
genBCodePhase match {
case genBCodePhase: GenBCode =>
genBCodePhase.registerSuperCall(sym, calls)
case _ =>
}
}
}
object CollectSuperCalls:
val name: String = "collectSuperCalls"
val description: String = "find classes that are called with super"
|
dotty-staging/dotty
|
compiler/src/dotty/tools/backend/jvm/CollectSuperCalls.scala
|
Scala
|
apache-2.0
| 1,644 |
/*
Copyright 2012 Twitter, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.twitter.algebird
// Represents a decayed value that is decayed of the form:
// \\sum_i e^{-(t_i - t)} v_i
// 2^{-(t/th)} = exp(ln(2)(-t/th)) = exp(-t * (ln(2)/th))
// So time is measured in units of (half-life/ln(2)), so.
// t in seconds, 1 day half life means: t => t * ln(2)/(86400.0)
object DecayedValue extends java.io.Serializable {
def build[V <% Double](value: V, time: Double, halfLife: Double) = {
DecayedValue(value, time * math.log(2.0) / halfLife)
}
val zero = DecayedValue(0.0, Double.NegativeInfinity)
def scale(newv: DecayedValue, oldv: DecayedValue, eps: Double) = {
val newValue = newv.value +
math.exp(oldv.scaledTime - newv.scaledTime) * oldv.value
if (math.abs(newValue) > eps) {
DecayedValue(newValue, newv.scaledTime)
} else {
zero
}
}
def monoidWithEpsilon(eps: Double): Monoid[DecayedValue] = new DecayedValueMonoid(eps)
}
case class DecayedValueMonoid(eps: Double) extends Monoid[DecayedValue] {
override val zero = DecayedValue(0.0, Double.NegativeInfinity)
override def plus(left: DecayedValue, right: DecayedValue) =
if (left < right) {
// left is older:
DecayedValue.scale(right, left, eps)
} else {
// right is older
DecayedValue.scale(left, right, eps)
}
// Returns value if timestamp is less than value's timestamp
def valueAsOf(value: DecayedValue, halfLife: Double, timestamp: Double): Double = {
plus(DecayedValue.build(0, timestamp, halfLife), value).value
}
}
case class DecayedValue(value: Double, scaledTime: Double) extends Ordered[DecayedValue] {
def compare(that: DecayedValue): Int = {
scaledTime.compareTo(that.scaledTime)
}
// A DecayedValue can be translated to a moving average with the window size of its half-life.
// It is EXACTLY a sample of the Laplace transform of the signal of values.
// Therefore, we can get the moving average by normalizing a decayed value with halflife/ln(2),
// which is the integral of exp(-t(ln(2))/halflife) from 0 to infinity.
//
// See: https://github.com/twitter/algebird/wiki/Using-DecayedValue-as-moving-average
def average(halfLife: Double) = {
val normalization = halfLife / math.log(2)
value / normalization
}
/*
* Moving average assuming the signal started at zero a fixed point in the past.
* This normalizes by the integral of exp(-t(ln(2))/halflife) from 0 to (endTime - startTime).
*/
def averageFrom(halfLife: Double, startTime: Double, endTime: Double) = {
if (endTime > startTime) {
val asOfEndTime = DecayedValue.scale(DecayedValue.build(0, endTime, halfLife), this, 0.0)
val timeDelta = startTime - endTime
val normalization = halfLife * (1 - math.pow(2, timeDelta / halfLife)) / math.log(2)
asOfEndTime.value / normalization
} else {
0.0
}
}
/*
* Moving average assuming a discrete view of time - in other words,
* where the halfLife is a small multiple of the resolution of the timestamps.
* Works best when the timestamp resolution is 1.0
*/
def discreteAverage(halfLife: Double) = {
val normalization = 1.0 - math.pow(2, -1.0 / halfLife)
value * normalization
}
}
|
nkhuyu/algebird
|
algebird-core/src/main/scala/com/twitter/algebird/DecayedValue.scala
|
Scala
|
apache-2.0
| 3,761 |
package tmp
import java.io.FileInputStream
import java.io.IOException
import java.util.Properties
import jadeutils.xmpp.model._
import jadeutils.xmpp.utils._
object chatter {
// val prop: Properties = new Properties()
// prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("connect.properties"))
//
// val server = prop.getProperty("conn.server")
// val port = Integer.valueOf(prop.getProperty("conn.port"))
// val username = prop.getProperty("conn.username")
// val password = prop.getProperty("conn.password")
//
// val conn = new XMPPConnection(server)
//
// def connect() { conn.connect() }
}
|
Jade-Shan/Jade-XMPP
|
src/main/scala/tmp.scala
|
Scala
|
gpl-3.0
| 628 |
import org.scalatest._
import Matchers._
import com.jeffharwell.commoncrawl.warcparser.WARCRecord
import com.jeffharwell.commoncrawl.warcparser.WARCInfo
import com.jeffharwell.commoncrawl.warcparser.WARCRecordTypeException
import com.jeffharwell.commoncrawl.warcparser.WARCConversion
import com.jeffharwell.commoncrawl.warcparser.MyWARCCategorizer
//import scala.collection.mutable.Map
class WARCConversionSpec extends FlatSpec {
// Default warcinfo type required fields and values
val warcinforequired = Map[String,String](
"WARC-Type" -> "warcinfo"
,"WARC-Date" -> "2016-12-13T03:22:59Z"
,"WARC-Filename" -> "CC-MAIN-20161202170900-00009-ip-10-31-129-80.ec2.internal.warc.wet.gz"
,"WARC-Record-ID" -> "<urn:uuid:600aac89-8012-4390-8be6-2d81979f88cc>"
,"Content-Type" -> "application/warc-fields"
,"Content-Length" -> "259")
"WARCInfo Object" should "have these 7 specific required fields" in {
val requiredfields: List[String] = List[String](
"WARC-Type",
"WARC-Date",
"WARC-Filename",
"WARC-Record-ID",
"Content-Type",
"Content-Length",
"Content")
val warcinfo = new WARCInfo()
assert(requiredfields.toSet == warcinfo.requiredfields.toSet)
}
"WARCConversion Object" should "have these 9 specific required fields" in {
val requiredfields: List[String] = List[String](
"WARC-Type",
"WARC-Target-URI",
"WARC-Date",
"WARC-Record-ID",
"WARC-Refers-To",
"WARC-Block-Digest",
"Content-Type",
"Content-Length",
"Content")
val warc = WARCConversion()
assert(requiredfields.toSet == warc.requiredfields.toSet)
}
"WARCConversion Object" should "report that it has 9 required fields at initialization" in {
val warc = WARCConversion()
assert(warc.numberRequiredFields == 9)
}
"WARCConversion" should "throw WARCRecordTypeException if WARC-Type is not 'conversion'" in {
val w = WARCConversion()
assertThrows[WARCRecordTypeException] { w.addFields(Map("WARC-Type" -> "warcinfo")) }
}
"WARCConversion" should "be incomplete without a WARCInfo object" in {
val w: WARCConversion = WARCConversion()
val requiredfields: Map[String,String] = Map[String,String](
"WARC-Type" -> "conversion",
"WARC-Target-URI" -> "my uri",
"WARC-Date" -> "2016-12-13T03:22:59Z",
"WARC-Record-ID" -> "<urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb>",
"WARC-Refers-To" -> "my refers to",
"WARC-Block-Digest" -> "my block digest",
"Content-Type" -> "my content type",
"Content-Length" -> "my content length")
w.addFields(requiredfields)
w.addContent("This is my content")
assert(w.isComplete() === false)
}
"WARCConversion" should "be complete with these fields and content" in {
// First create the WARCInfo we need
val winfo = new WARCInfo()
winfo.addFields(warcinforequired)
winfo.addContent("This is my content")
val w: WARCConversion = WARCConversion()
val requiredfields: Map[String,String] = Map[String,String](
"WARC-Type" -> "conversion",
"WARC-Target-URI" -> "my uri",
"WARC-Date" -> "2016-12-13T03:22:59Z",
"WARC-Record-ID" -> "<urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb>",
"WARC-Refers-To" -> "my refers to",
"WARC-Block-Digest" -> "my block digest",
"Content-Type" -> "my content type",
"Content-Length" -> "my content length")
w.addFields(requiredfields)
w.addContent("This is my content")
w.addWARCInfo(winfo)
assert(w.isComplete() === true)
}
"WARCConversion" should "return the top level domain of the record if the WARC-URI field is populated" in {
// First create the WARCInfo we need
val winfo = new WARCInfo()
winfo.addFields(warcinforequired)
winfo.addContent("This is my content")
val w: WARCConversion = WARCConversion()
val requiredfields: Map[String,String] = Map[String,String](
"WARC-Type" -> "conversion",
"WARC-Target-URI" -> "http://003.su/search_results.php?letter=%D0%9C&offset=580",
"WARC-Date" -> "2016-12-13T03:22:59Z",
"WARC-Record-ID" -> "<urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb>",
"WARC-Refers-To" -> "my refers to",
"WARC-Block-Digest" -> "my block digest",
"Content-Type" -> "my content type",
"Content-Length" -> "my content length")
w.addFields(requiredfields)
w.addContent("This is my content")
w.addWARCInfo(winfo)
assert(w.get("Top-Level-Domain") == Some("su"))
assert(w.isComplete() === true)
}
"WARCConversion" should "return None for the top level domain of the record if the WARC-URI field is garbage" in {
// First create the WARCInfo we need
val winfo = new WARCInfo()
winfo.addFields(warcinforequired)
winfo.addContent("This is my content")
val w: WARCConversion = WARCConversion()
val requiredfields: Map[String,String] = Map[String,String](
"WARC-Type" -> "conversion",
"WARC-Target-URI" -> "blahblahblah",
"WARC-Date" -> "2016-12-13T03:22:59Z",
"WARC-Record-ID" -> "<urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb>",
"WARC-Refers-To" -> "my refers to",
"WARC-Block-Digest" -> "my block digest",
"Content-Type" -> "my content type",
"Content-Length" -> "my content length")
w.addFields(requiredfields)
w.addContent("This is my content")
w.addWARCInfo(winfo)
assert(w.get("Top-Level-Domain") == None)
assert(w.isComplete() === true)
}
"WARCConversion" should "headersComplete returns true when all headers are populated but no content" in {
// First create the WARCInfo we need
val winfo = new WARCInfo()
winfo.addFields(warcinforequired)
winfo.addContent("This is my content")
val w: WARCConversion = WARCConversion()
val requiredfields: Map[String,String] = Map[String,String](
"WARC-Type" -> "conversion",
"WARC-Target-URI" -> "my uri",
"WARC-Date" -> "2016-12-13T03:22:59Z",
"WARC-Record-ID" -> "<urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb>",
"WARC-Refers-To" -> "my refers to",
"WARC-Block-Digest" -> "my block digest",
"Content-Type" -> "my content type",
"Content-Length" -> "my content length")
assert(w.headersComplete() === false)
w.addFields(requiredfields)
assert(w.headersComplete() === true)
}
"WARCConversion" should "should know content length once headers are complete" in {
// First create the WARCInfo we need
val winfo = new WARCInfo()
winfo.addFields(warcinforequired)
winfo.addContent("This is my content")
val w: WARCConversion = WARCConversion()
val requiredfields: Map[String,String] = Map[String,String](
"WARC-Type" -> "conversion",
"WARC-Target-URI" -> "my uri",
"WARC-Date" -> "2016-12-13T03:22:59Z",
"WARC-Record-ID" -> "<urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb>",
"WARC-Refers-To" -> "my refers to",
"WARC-Block-Digest" -> "my block digest",
"Content-Type" -> "my content type",
"Content-Length" -> "35")
w.addFields(requiredfields)
assert(w.headersComplete() === true)
assert(w.getContentSizeInBytes() == 35)
}
"WARCConversion" should "should return the fields it has been populated with" in {
// First create the WARCInfo we need
val winfo = new WARCInfo()
winfo.addFields(warcinforequired)
winfo.addContent("This is my content")
val w: WARCConversion = WARCConversion()
val requiredfields: Map[String,String] = Map[String,String](
"WARC-Type" -> "conversion",
"WARC-Target-URI" -> "my uri",
"WARC-Date" -> "2016-12-13T03:22:59Z",
"WARC-Record-ID" -> "<urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb>",
"WARC-Refers-To" -> "my refers to",
"WARC-Block-Digest" -> "my block digest",
"Content-Type" -> "my content type",
"Content-Length" -> "35")
w.addFields(requiredfields)
w.addContent("This is my WARCConversion content")
assert(w.headersComplete() === true)
assert(w.getContentSizeInBytes() == 35)
assert(w.get("Content-Type") == Some("my content type"))
assert(w.get("WARC-Date") == Some("2016-12-13T03:22:59Z"))
assert(w.get("WARC-Type") == Some("conversion"))
assert(w.getContent() == Some("This is my WARCConversion content"))
}
"WARCConversion" should "should return the fields from WARCInfo using the get method" in {
// First create the WARCInfo we need
val winfo = new WARCInfo()
winfo.addFields(warcinforequired)
winfo.addContent("This is my content")
val w: WARCConversion = WARCConversion()
val requiredfields: Map[String,String] = Map[String,String](
"WARC-Type" -> "conversion",
"WARC-Target-URI" -> "my uri",
"WARC-Date" -> "2016-12-13T03:22:59Z",
"WARC-Record-ID" -> "<urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb>",
"WARC-Refers-To" -> "my refers to",
"WARC-Block-Digest" -> "my block digest",
"Content-Type" -> "my content type",
"Content-Length" -> "35")
w.addFields(requiredfields)
w.addContent("This is my WARCConversion content")
w.addWARCInfo(winfo)
// The WARC-Filename field is in the WARCInfo object, not directly in the wARCConversion object's fields.
assert(w.get("WARC-Filename") == Some("CC-MAIN-20161202170900-00009-ip-10-31-129-80.ec2.internal.warc.wet.gz"))
}
"WARCConversion" should "should return None for non-existent field even in the absence of a WARCInfo object" in {
val w: WARCConversion = WARCConversion()
val requiredfields: Map[String,String] = Map[String,String](
"WARC-Type" -> "conversion",
"WARC-Target-URI" -> "my uri",
"WARC-Date" -> "2016-12-13T03:22:59Z",
"WARC-Record-ID" -> "<urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb>",
"WARC-Refers-To" -> "my refers to",
"WARC-Block-Digest" -> "my block digest",
"Content-Type" -> "my content type",
"Content-Length" -> "35")
w.addFields(requiredfields)
w.addContent("This is my WARCConversion content")
// The WARC-Filename field is in the WARCInfo object, not directly in the wARCConversion object's fields.
w.get("WARC-Filename") should be (None)
}
"WARCConversion" should "Fields from WARCConversion should mask fields from WARCInfo if they have the same name" in {
// First create the WARCInfo we need
val winfo = new WARCInfo()
winfo.addFields(warcinforequired)
winfo.addContent("This is my content")
val w: WARCConversion = WARCConversion()
val requiredfields: Map[String,String] = Map[String,String](
"WARC-Type" -> "conversion",
"WARC-Target-URI" -> "my uri",
"WARC-Date" -> "2016-12-13T03:22:59Z",
"WARC-Record-ID" -> "<urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb>",
"WARC-Refers-To" -> "my refers to",
"WARC-Block-Digest" -> "my block digest",
"Content-Type" -> "my content type",
"Content-Length" -> "35")
w.addFields(requiredfields)
w.addContent("This is my WARCConversion content")
w.addWARCInfo(winfo)
// The WARCConversion record has a WARC-Record-ID and so does the WARCInfo object that
// we passed. <urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb> is the WARC conversion ID
// while <urn:uuid:600aac89-8012-4390-8be6-2d81979f88cc> is the WARC info ID
assert(w.get("WARC-Record-ID") == Some("<urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb>"))
}
"WARCConversion" should "should throw an exception if content size is requested before headers are complete" in {
val w: WARCConversion = WARCConversion()
assertThrows[RuntimeException] { w.getContentSizeInBytes() }
}
"WARCConversion" should "warcInfoComplete returns true after a completed WARCInfo object is added, false otherwise" in {
// First create the WARCInfo we need
val winfo = new WARCInfo()
winfo.addFields(warcinforequired)
winfo.addContent("This is my content")
val w: WARCConversion = WARCConversion()
assert(w.warcInfoComplete() === false)
w.addWARCInfo(winfo)
assert(w.warcInfoComplete() === true)
}
/*
* Testing Categorizers
*/
"WARCConversion" should "should categorize this content as asthma with MyWARCCategorizer" in {
// First create the WARCInfo we need
val winfo = new WARCInfo()
winfo.addFields(warcinforequired)
winfo.addContent("This is my content")
val c: MyWARCCategorizer = new MyWARCCategorizer(4)
val w: WARCConversion = WARCConversion(c)
val content = "Asthma asthma asthma this should match the asthma category."
val length = content.getBytes("UTF-8").size.toString()
val requiredfields: Map[String,String] = Map[String,String](
"WARC-Type" -> "conversion",
"WARC-Target-URI" -> "my uri",
"WARC-Date" -> "2016-12-13T03:22:59Z",
"WARC-Record-ID" -> "<urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb>",
"WARC-Refers-To" -> "my refers to",
"WARC-Block-Digest" -> "my block digest",
"Content-Type" -> "my content type",
"Content-Length" -> length)
w.addFields(requiredfields)
w.addContent(content)
assert(w.hasCategories)
assert(w.getCategories == Some(Set[String]("asthma")))
}
"WARCConversion" should "should categorize this content as asthma and politics with MyWARCCategorizer" in {
// First create the WARCInfo we need
val winfo = new WARCInfo()
winfo.addFields(warcinforequired)
winfo.addContent("This is my content")
val c: MyWARCCategorizer = new MyWARCCategorizer(4)
val w: WARCConversion = WARCConversion(c)
val content = "Asthma trump asthma trump asthma trump this should match the asthma and trump politics category."
val length = content.getBytes("UTF-8").size.toString()
val requiredfields: Map[String,String] = Map[String,String](
"WARC-Type" -> "conversion",
"WARC-Target-URI" -> "my uri",
"WARC-Date" -> "2016-12-13T03:22:59Z",
"WARC-Record-ID" -> "<urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb>",
"WARC-Refers-To" -> "my refers to",
"WARC-Block-Digest" -> "my block digest",
"Content-Type" -> "my content type",
"Content-Length" -> length)
w.addFields(requiredfields)
w.addContent(content)
assert(w.hasCategories)
w.getCategories() shouldBe defined
//w.getCategories() should contain "asthma"
//w.getCategories() should contain "politics"
assert(w.getCategories().get.size == 2)
//assert(w.getCategories.contains("asthma") && w.getCategories.contains("politics") && w.getCategories.size == 2)
}
"WARCConversion" should "should not be able to categorize this content with MyWARCCategorizer" in {
// First create the WARCInfo we need
val winfo = new WARCInfo()
winfo.addFields(warcinforequired)
winfo.addContent("This is my content")
val c: MyWARCCategorizer = new MyWARCCategorizer(4)
val w: WARCConversion = WARCConversion(c)
val content = "This sentence should not match any content categories."
val length = content.getBytes("UTF-8").size.toString()
val requiredfields: Map[String,String] = Map[String,String](
"WARC-Type" -> "conversion",
"WARC-Target-URI" -> "my uri",
"WARC-Date" -> "2016-12-13T03:22:59Z",
"WARC-Record-ID" -> "<urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb>",
"WARC-Refers-To" -> "my refers to",
"WARC-Block-Digest" -> "my block digest",
"Content-Type" -> "my content type",
"Content-Length" -> length)
w.addFields(requiredfields)
w.addContent(content)
assert(!w.hasCategories)
w.getCategories() should be (None)
}
"WARCConversion" should "should not categorize this content with default categorizer" in {
// First create the WARCInfo we need
val winfo = new WARCInfo()
winfo.addFields(warcinforequired)
winfo.addContent("This is my content")
val w: WARCConversion = WARCConversion()
val content = "Asthma trump asthma trump asthma trump this should match the asthma and trump politics category."
val length = content.getBytes("UTF-8").size.toString()
val requiredfields: Map[String,String] = Map[String,String](
"WARC-Type" -> "conversion",
"WARC-Target-URI" -> "my uri",
"WARC-Date" -> "2016-12-13T03:22:59Z",
"WARC-Record-ID" -> "<urn:uuid:519aac89-8012-4390-8be6-2d81979f88cb>",
"WARC-Refers-To" -> "my refers to",
"WARC-Block-Digest" -> "my block digest",
"Content-Type" -> "my content type",
"Content-Length" -> length)
w.addFields(requiredfields)
w.addContent(content)
assert(!w.hasCategories)
w.getCategories() should be (None)
}
}
|
jeffharwell/CommonCrawlScalaTools
|
warcparser/src/test/scala/WARCConversionSpec.scala
|
Scala
|
mit
| 17,239 |
/*
* Copyright 2013 Marek Radonsky
*
* 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 models
import anorm.Pk
trait ModelEntity {
val id: Pk[Long]
}
|
radonsky/Taurus
|
app/models/ModelEntity.scala
|
Scala
|
apache-2.0
| 675 |
package scredis.commands
import scala.language.postfixOps
import scredis.io.NonBlockingConnection
import scredis.protocol.AuthConfig
import scredis.protocol.requests.KeyRequests._
import scredis.serialization.{Reader, Writer}
import scala.concurrent.Future
import scala.concurrent.duration._
/**
* This trait implements key commands.
*
* @define e [[scredis.exceptions.RedisErrorResponseException]]
* @define none `None`
* @define true '''true'''
* @define false '''false'''
*/
trait KeyCommands { self: NonBlockingConnection =>
/**
* Deletes one or multiple keys.
*
* @note a key is ignored if it does not exist
*
* @param keys key(s) to delete
* @return the number of keys that were deleted
*
* @since 1.0.0
*/
def del(keys: String*): Future[Long] = send(Del(keys: _*))
/**
* Returns a serialized version of the value stored at the specified key.
*
* @param key key to dump
* @return the serialized value or $none if the key does not exist
*
* @since 2.6.0
*/
def dump(key: String): Future[Option[Array[Byte]]] = send(Dump(key))
/**
* Determines if a key exists.
*
* @param key key to check for existence
* @return $true if the key exists, $false otherwise
*
* @since 1.0.0
*/
def exists(key: String): Future[Boolean] = send(Exists(key))
/**
* Sets a key's time to live in seconds.
*
* @param key key to expire
* @param ttlSeconds time-to-live in seconds
* @return $true if the ttl was set, $false if key does not exist or
* the timeout could not be set
*
* @since 1.0.0
*/
def expire(key: String, ttlSeconds: Int): Future[Boolean] = send(Expire(key, ttlSeconds))
/**
* Sets the expiration for a key as a UNIX timestamp.
*
* @param key key to expire
* @param timestamp UNIX timestamp at which the key should expire
* @return $true if the ttl was set, $false if key does not exist or
* the timeout could not be set
*
* @since 1.2.0
*/
def expireAt(key: String, timestamp: Long): Future[Boolean] = send(ExpireAt(key, timestamp))
/**
* Finds all keys matching the given pattern.
*
* @param pattern pattern to search for
* @return the matched keys, or the empty set if no keys match the given pattern
*
* @since 1.0.0
*/
def keys(pattern: String): Future[Set[String]] = send(Keys[Set](pattern))
/**
* Atomically transfers a key from a Redis instance to another one.
*
* @param key key to transfer
* @param host destination host
* @param port destination port
* @param database destination database
* @param authOpt destination server authorization credentials
* @param timeout timeout duration, up to milliseconds precision
* @param copy if $true, do not remove the key from the local instance
* @param replace if $true, replace existing key on the remote instance
* @throws $e if an error occurs
*
* @since 2.6.0
*/
def migrate(
key: String,
host: String,
port: Int = 6379,
database: Int = 0,
authOpt: Option[AuthConfig] = None,
timeout: FiniteDuration = 2.seconds,
copy: Boolean = false,
replace: Boolean = false
): Future[Unit] = send(
Migrate(
key = key,
host = host,
port = port,
database = database,
authOpt = authOpt,
timeout = timeout,
copy = copy,
replace = replace
)
)
/**
* Moves a key to another database.
*
* @param key key to move
* @param database destination database
* @return true if key was moved, false otherwise
*
* @since 1.0.0
*/
def move(key: String, database: Int): Future[Boolean] = send(Move(key, database))
/**
* Returns the number of references of the value associated with the specified key.
*
* @param key the key
* @return the number of references or $none if the key does not exist
*
* @since 2.2.3
*/
def objectRefCount(key: String): Future[Option[Long]] = send(ObjectRefCount(key))
/**
* Returns the kind of internal representation used in order to store the value associated with
* a key.
*
* @note Objects can be encoded in different ways:
* Strings can be encoded as `raw` or `int`
* Lists can be encoded as `ziplist` or `linkedlist`
* Sets can be encoded as `intset` or `hashtable`
* Hashes can be encoded as `zipmap` or `hashtable`
* SortedSets can be encoded as `ziplist` or `skiplist`
*
* @param key the key
* @return the object encoding or $none if the key does not exist
*
* @since 2.2.3
*/
def objectEncoding(key: String): Future[Option[String]] = send(ObjectEncoding(key))
/**
* Returns the number of seconds since the object stored at the specified key is idle (not
* requested by read or write operations).
*
* @note While the value is returned in seconds the actual resolution of this timer is
* 10 seconds, but may vary in future implementations.
*
* @param key the key
* @return the number of seconds since the object is idle or $none if the key does not exist
*
* @since 2.2.3
*/
def objectIdleTime(key: String): Future[Option[Long]] = send(ObjectIdleTime(key))
/**
* Removes the expiration from a key.
*
* @param key key to persist
* @return $true if key was persisted, $false if key does not exist or does not have an
* associated timeout
*
* @since 2.2.0
*/
def persist(key: String): Future[Boolean] = send(Persist(key))
/**
* Sets a key's time to live in milliseconds.
*
* @param key key to expire
* @param ttlMillis time-to-live in milliseconds
* @return $true if the ttl was set, $false if key does not exist or
* the timeout could not be set
*
* @since 2.6.0
*/
def pExpire(key: String, ttlMillis: Long): Future[Boolean] = send(PExpire(key, ttlMillis))
/**
* Sets the expiration for a key as a UNIX timestamp specified in milliseconds.
*
* @param key key to expire
* @param timestampMillis UNIX milliseconds-timestamp at which the key should expire
* @return $true if the ttl was set, $false if key does not exist or
* the timeout could not be set
*
* @since 2.6.0
*/
def pExpireAt(key: String, timestampMillis: Long): Future[Boolean] = send(
PExpireAt(key, timestampMillis)
)
/**
* Gets the time to live for a key in milliseconds.
*
* {{{
* result match {
* case Left(false) => // key does not exist
* case Left(true) => // key exists but has no associated expire
* case Right(ttl) =>
* }
* }}}
*
* @note For `Redis` version <= 2.8.x, `Left(false)` will be returned when the key does not
* exists and when it exists but has no associated expire (`Redis` returns the same error code
* for both cases). In other words, you can simply check the following
*
* {{{
* result match {
* case Left(_) =>
* case Right(ttl) =>
* }
* }}}
*
* @param key the target key
* @return `Right(ttl)` where ttl is the time-to-live in milliseconds for specified key,
* `Left(false)` if key does not exist or `Left(true)` if key exists but has no associated
* expire
*
* @since 2.6.0
*/
def pTtl(key: String): Future[Either[Boolean, Long]] = send(PTTL(key))
/**
* Returns a random key from the keyspace.
*
* @return the random key or $none when the database is empty
*
* @since 1.0.0
*/
def randomKey(): Future[Option[String]] = send(RandomKey())
/**
* Renames a key.
*
* @note if newKey already exists, it is overwritten
* @param key source key
* @param newKey destination key
* @throws $e if the source and destination keys are the same, or when key
* does not exist
*
* @since 1.0.0
*/
def rename(key: String, newKey: String): Future[Unit] = send(Rename(key, newKey))
/**
* Renames a key, only if the new key does not exist.
*
* @param key source key
* @param newKey destination key
* @return $true if key was renamed to newKey, $false if newKey already exists
* @throws $e if the source and destination keys are the same, or when key does not exist
*
* @since 1.0.0
*/
def renameNX(key: String, newKey: String): Future[Boolean] = send(RenameNX(key, newKey))
/**
* Creates a key using the provided serialized value, previously obtained using DUMP.
*
* @param key destination key
* @param serializedValue serialized value, previously obtained using DUMP
* @param ttlOpt optional time-to-live duration of newly created key (expire)
* @throws $e if the value could not be restored
*
* @since 2.6.0
*/
def restore[W: Writer](
key: String,
serializedValue: W,
ttlOpt: Option[FiniteDuration] = None
): Future[Unit] = send(
Restore(
key = key,
value = serializedValue,
ttlOpt = ttlOpt
)
)
/**
* Incrementally iterates the set of keys in the currently selected Redis database.
*
* @param cursor the offset
* @param matchOpt when defined, the command only returns elements matching the pattern
* @param countOpt when defined, provides a hint of how many elements should be returned
* @return a pair containing the next cursor as its first element and the set of keys
* as its second element
*
* @since 2.8.0
*/
def scan(
cursor: Long,
matchOpt: Option[String] = None,
countOpt: Option[Int] = None
): Future[(Long, Set[String])] = send(
Scan(
cursor = cursor,
matchOpt = matchOpt,
countOpt = countOpt
)
)
/**
* Sorts the elements of a list, set or sorted set.
*
* @param key key of list, set or sorted set to be sorted
* @param byOpt optional pattern for sorting by external values, can also be "nosort" if
* the sorting operation should be skipped (useful when only sorting to retrieve objects
* with get). The * gets replaced by the values of the elements in the collection
* @param limitOpt optional pair of numbers (offset, count) where offset specified the number of
* elements to skip and count specifies the number of elements to return starting from offset
* @param get list of patterns for retrieving objects stored in external keys. The * gets
* replaced by the values of the elements in the collection
* @param desc indicates whether elements should be sorted descendingly
* @param alpha indicates whether elements should be sorted lexicographically
* @return the sorted list of elements, or the empty list if the key does not exist
* @throws $e whenever an error occurs
*
* @since 1.0.0
*/
def sort[R: Reader](
key: String,
byOpt: Option[String] = None,
limitOpt: Option[(Long, Long)] = None,
get: Iterable[String] = Nil,
desc: Boolean = false,
alpha: Boolean = false
): Future[List[Option[R]]] = send(
Sort[R](
key = key,
byOpt = byOpt,
limitOpt = limitOpt,
get = get,
desc = desc,
alpha = alpha
)
)
/**
* Sorts the elements of a list, set or sorted set and then store the result.
*
* @param key key of list, set or sorted set to be sorted
* @param targetKey key of list, set or sorted set to be sorted
* @param byOpt optional pattern for sorting by external values, can also be "nosort" if
* the sorting operation should be skipped (useful when only sorting to retrieve objects
* with get). The * gets replaced by the values of the elements in the collection
* @param limitOpt optional pair of numbers (offset, count) where offset specified the
* number of elements to skip and count specifies the number of elements to return starting
* from offset
* @param get list of patterns for retrieving objects stored in external keys. The * gets
* replaced by the values of the elements in the collection
* @param desc indicates whether elements should be sorted descendingly
* @param alpha indicates whether elements should be sorted lexicographically
* @return the number of elements in the newly stored sorted collection
* @throws $e whenever an error occurs
*
* @since 1.0.0
*/
def sortAndStore(
key: String,
targetKey: String,
byOpt: Option[String] = None,
limitOpt: Option[(Long, Long)] = None,
get: Iterable[String] = Nil,
desc: Boolean = false,
alpha: Boolean = false
): Future[Long] = send(
SortAndStore(
key = key,
targetKey = targetKey,
byOpt = byOpt,
limitOpt = limitOpt,
get = get,
desc = desc,
alpha = alpha
)
)
/**
* Gets the time to live for a key in seconds.
*
* {{{
* result match {
* case Left(false) => // key does not exist
* case Left(true) => // key exists but has no associated expire
* case Right(ttl) =>
* }
* }}}
*
* @note For `Redis` version <= 2.8.x, `Left(false)` will be returned when the key does not
* exists and when it exists but has no associated expire (`Redis` returns the same error code
* for both cases). In other words, you can simply check the following
*
* {{{
* result match {
* case Left(_) =>
* case Right(ttl) =>
* }
* }}}
*
* @param key the target key
* @return `Right(ttl)` where ttl is the time-to-live in seconds for specified key,
* `Left(false)` if key does not exist or `Left(true)` if key exists but has no associated
* expire
*
* @since 1.0.0
*/
def ttl(key: String): Future[Either[Boolean, Int]] = send(TTL(key))
/**
* Determine the type stored at key.
*
* @note This method needs to be called as follows:
* {{{
* client.`type`(key)
* }}}
*
* @param key key for which the type should be returned
* @return type of key, or $none if key does not exist
*
* @since 1.0.0
*/
def `type`(key: String): Future[Option[scredis.Type]] = send(Type(key))
}
|
scredis/scredis
|
src/main/scala/scredis/commands/KeyCommands.scala
|
Scala
|
apache-2.0
| 13,912 |
/*
* Scala (https://www.scala-lang.org)
*
* Copyright EPFL and Lightbend, Inc.
*
* Licensed under Apache License 2.0
* (http://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package scala.reflect.macros
package contexts
import scala.reflect.{ClassTag, classTag}
trait Enclosures {
self: Context =>
import universe._
private lazy val site = callsiteTyper.context
private def lenientEnclosure[T <: Tree : ClassTag]: Tree = site.nextEnclosing(c => classTag[T].runtimeClass.isInstance(c.tree)).tree
@deprecated("c.enclosingTree-style APIs are now deprecated; consult the scaladoc for more information", "2.13.4")
private def strictEnclosure[T <: Tree : ClassTag]: T = site.nextEnclosing(c => classTag[T].runtimeClass.isInstance(c.tree)) match {
case analyzer.NoContext => throw EnclosureException(classTag[T].runtimeClass, site.enclosingContextChain map (_.tree))
case cx => cx.tree.asInstanceOf[T]
}
val macroApplication: Tree = expandee
def enclosingPackage: PackageDef = site.nextEnclosing(_.tree.isInstanceOf[PackageDef]).tree.asInstanceOf[PackageDef]
lazy val enclosingClass: Tree = lenientEnclosure[ImplDef]
@deprecated("c.enclosingTree-style APIs are now deprecated; consult the scaladoc for more information", "2.13.4")
def enclosingImpl: ImplDef = strictEnclosure[ImplDef]
@deprecated("c.enclosingTree-style APIs are now deprecated; consult the scaladoc for more information", "2.13.4")
def enclosingTemplate: Template = strictEnclosure[Template]
lazy val enclosingImplicits: List[ImplicitCandidate] = site.openImplicits.map(_.toImplicitCandidate)
private val analyzerOpenMacros = universe.analyzer.openMacros
val enclosingMacros: List[Context] = this :: analyzerOpenMacros // include self
lazy val enclosingMethod: Tree = lenientEnclosure[DefDef]
@deprecated("c.enclosingTree-style APIs are now deprecated; consult the scaladoc for more information", "2.13.4")
def enclosingDef: DefDef = strictEnclosure[DefDef]
lazy val enclosingPosition: Position = if (this.macroApplication.pos ne NoPosition) this.macroApplication.pos else {
analyzerOpenMacros.collectFirst {
case x if x.macroApplication.pos ne NoPosition => x.macroApplication.pos
}.getOrElse(NoPosition)
}
@deprecated("c.enclosingTree-style APIs are now deprecated; consult the scaladoc for more information", "2.13.4")
val enclosingUnit: CompilationUnit = universe.currentRun.currentUnit
@deprecated("c.enclosingTree-style APIs are now deprecated; consult the scaladoc for more information", "2.13.4")
val enclosingRun: Run = universe.currentRun
}
|
scala/scala
|
src/compiler/scala/reflect/macros/contexts/Enclosures.scala
|
Scala
|
apache-2.0
| 2,929 |
/*
* Copyright 2014-2022 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.atlas.druid
import com.netflix.atlas.core.model.Query
import com.netflix.atlas.core.model.Query.KeyQuery
import com.netflix.spectator.impl.AsciiSet
trait DruidFilter
object DruidFilter {
private val allowedChars = AsciiSet.fromPattern("-._A-Za-z0-9^~ ")
def sanitize(v: String): String = allowedChars.replaceNonMembers(v, '_')
def forQuery(query: Query): Option[DruidFilter] = {
val q = removeDatasourceAndName(query)
if (q == Query.True) None else Some(toFilter(q))
}
def toFilter(query: Query): DruidFilter = {
query match {
case Query.True => throw new UnsupportedOperationException(":true")
case Query.False => throw new UnsupportedOperationException(":false")
case Query.Equal(k, v) => Equal(k, v)
case Query.In(k, vs) => In(k, vs)
case Query.GreaterThan(k, v) => js(k, ">", v)
case Query.GreaterThanEqual(k, v) => js(k, ">=", v)
case Query.LessThan(k, v) => js(k, "<", v)
case Query.LessThanEqual(k, v) => js(k, "<=", v)
case Query.HasKey(k) => Not(Equal(k, "")) // druid: empty string is same as null
case Query.Regex(k, v) => Regex(k, s"^$v")
case Query.RegexIgnoreCase(k, v) => Regex(k, s"(?i)^$v")
case Query.And(q1, q2) => And(List(toFilter(q1), toFilter(q2)))
case Query.Or(q1, q2) => Or(List(toFilter(q1), toFilter(q2)))
case Query.Not(q) => Not(toFilter(q))
}
}
/**
* The `nf.datasource` and `name` values should have already been confirmed before trying
* to create a filter. Those values must be listed as `dataSource` and `searchDimensions`
* respectively. This removes them by rewriting the query so that they are presumed
* to be true.
*/
private def removeDatasourceAndName(query: Query): Query = {
val newQuery = query.rewrite {
case kq: KeyQuery if kq.k == "nf.datasource" => Query.True
case kq: KeyQuery if kq.k == "name" => Query.True
}
Query.simplify(newQuery.asInstanceOf[Query])
}
private def js(k: String, op: String, v: String): JavaScript = {
val sanitizedV = sanitize(v)
JavaScript(k, s"function(x) { return x $op '$sanitizedV'; }")
}
case class Equal(dimension: String, value: String) extends DruidFilter {
val `type`: String = "selector"
}
case class Regex(dimension: String, pattern: String) extends DruidFilter {
val `type`: String = "regex"
}
case class In(dimension: String, values: List[String]) extends DruidFilter {
val `type`: String = "in"
}
case class JavaScript(dimension: String, function: String) extends DruidFilter {
val `type`: String = "javascript"
}
case class And(fields: List[DruidFilter]) extends DruidFilter {
val `type`: String = "and"
}
case class Or(fields: List[DruidFilter]) extends DruidFilter {
val `type`: String = "or"
}
case class Not(field: DruidFilter) extends DruidFilter {
val `type`: String = "not"
}
}
|
Netflix-Skunkworks/iep-apps
|
atlas-druid/src/main/scala/com/netflix/atlas/druid/DruidFilter.scala
|
Scala
|
apache-2.0
| 3,689 |
package com.cds.learnscala.chapter.chap13
import scala.collection.immutable.SortedSet
import scala.collection.mutable
object Main {
def mapStringIndex(str: String) = {
var indexMap = new mutable.HashMap[Char, SortedSet[Int]]()
var i = 0
str.toCharArray.foreach {
c => indexMap.get(c) match {
case Some(result) => indexMap(c) = result + i
case None => indexMap += (c -> SortedSet {
i
})
}
i += 1
}
indexMap
}
def removeZero(list: List[Int]) = {
list.filter(_ != 0)
}
def filterMap(array: Array[String], map: Map[String, Int]): Array[Int] = {
array.flatMap(map.get)
}
def divArr(arr: Array[Double], i: Int) = {
}
def main(args: Array[String]) {
println(mapStringIndex("Mississippi"))
println(removeZero(List(0, 0, 1)))
println(filterMap(Array("Tom", "Fred", "Harry"), Map("Tom" -> 3, "Dick" -> 4, "Harry" -> 5))
.mkString(","))
val lst = List(1, 2, 3, 4, 5)
println((lst :\\ List[Int]()) (_ :: _))
println((List[Int]() /: lst) (_ :+ _))
println((List[Int]() /: lst) ((a, b) => b :: a))
}
}
|
anancds/scala-project
|
learn-scala/src/main/scala/com/cds/learnscala/chapter/chap13/Main.scala
|
Scala
|
mit
| 1,139 |
package de.fosd.typechef.typesystem.linker
import de.fosd.typechef.typesystem.CType
import de.fosd.typechef.featureexpr.FeatureExpr
import de.fosd.typechef.error.Position
/**
* signature with name type and condition. the position is only stored for debugging purposes and has no further
* relevance.
* its also not necessarily de/serialized
*
* extraflags can refer to special features for signatures, such as weak exports; see CFlags.scala
*
* TODO types should be selfcontained (i.e. not reference to structures or type names defined elsewhere,
* but resolved to anonymous structs, etc.)
*/
case class CSignature(name: String, ctype: CType, fexpr: FeatureExpr, pos: Seq[Position], extraFlags: Set[CFlag] = Set()) {
override def toString =
name + ": " + ctype.toText + " " + extraFlags.mkString("+") + "\\t\\tif " + fexpr + "\\t\\tat " + pos.mkString(", ")
override def hashCode = name.hashCode
override def equals(that: Any) = that match {
case CSignature(thatName, thatCType, thatFexpr, thatPos, thatExtraFlags) => name == thatName && CType.isLinkCompatible(ctype, thatCType) && fexpr.equivalentTo(thatFexpr) && pos == thatPos && extraFlags == thatExtraFlags
case _ => false
}
def and(f: FeatureExpr) = CSignature(name, ctype, fexpr and f, pos, extraFlags)
}
|
ckaestne/TypeChef
|
CTypeChecker/src/main/scala/de/fosd/typechef/typesystem/linker/CSignature.scala
|
Scala
|
lgpl-3.0
| 1,353 |
package frdomain.ch5
package domain
package service
package interpreter
import java.util.{ Date, Calendar }
import scalaz._
import Scalaz._
import \\/._
import Kleisli._
import model.{ Account, Balance }
import model.common._
import repository.AccountRepository
class AccountServiceInterpreter extends AccountService[Account, Amount, Balance] {
def open(no: String,
name: String,
rate: Option[BigDecimal],
openingDate: Option[Date],
accountType: AccountType) = kleisli[Valid, AccountRepository, Account] { (repo: AccountRepository) =>
repo.query(no) match {
case \\/-(Some(a)) => NonEmptyList(s"Already existing account with no $no").left[Account]
case \\/-(None) => accountType match {
case Checking => Account.checkingAccount(no, name, openingDate, None, Balance()).flatMap(repo.store)
case Savings => rate map { r =>
Account.savingsAccount(no, name, r, openingDate, None, Balance()).flatMap(repo.store)
} getOrElse {
NonEmptyList(s"Rate needs to be given for savings account").left[Account]
}
}
case a @ -\\/(_) => a
}
}
def close(no: String, closeDate: Option[Date]) = kleisli[Valid, AccountRepository, Account] { (repo: AccountRepository) =>
repo.query(no) match {
case \\/-(None) => NonEmptyList(s"Account $no does not exist").left[Account]
case \\/-(Some(a)) =>
val cd = closeDate.getOrElse(today)
Account.close(a, cd).flatMap(repo.store)
case a @ -\\/(_) => a
}
}
def debit(no: String, amount: Amount) = up(no, amount, D)
def credit(no: String, amount: Amount) = up(no, amount, C)
private trait DC
private case object D extends DC
private case object C extends DC
private def up(no: String, amount: Amount, dc: DC): AccountOperation[Account] = kleisli[Valid, AccountRepository, Account] { (repo: AccountRepository) =>
repo.query(no) match {
case \\/-(None) => NonEmptyList(s"Account $no does not exist").left[Account]
case \\/-(Some(a)) => dc match {
case D => Account.updateBalance(a, -amount).flatMap(repo.store)
case C => Account.updateBalance(a, amount).flatMap(repo.store)
}
case a @ -\\/(_) => a
}
}
def balance(no: String) = kleisli[Valid, AccountRepository, Balance] { (repo: AccountRepository) => repo.balance(no) }
}
object AccountService extends AccountServiceInterpreter
|
debasishg/frdomain
|
src/main/scala/frdomain/ch5/domain/service/interpreter/AccountService.scala
|
Scala
|
apache-2.0
| 2,444 |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kafka.metrics
import java.util.concurrent.TimeUnit
import com.yammer.metrics.Metrics
import com.yammer.metrics.core.{Gauge, MetricName}
import kafka.consumer.{ConsumerTopicStatsRegistry, FetchRequestAndResponseStatsRegistry}
import kafka.producer.{ProducerRequestStatsRegistry, ProducerStatsRegistry, ProducerTopicStatsRegistry}
import kafka.utils.Logging
import scala.collection.immutable
trait KafkaMetricsGroup extends Logging {
/**
* Creates a new MetricName object for gauges, meters, etc. created for this
* metrics group.
* @param name Descriptive name of the metric.
* @param tags Additional attributes which mBean will have.
* @return Sanitized metric name object.
*/
private def metricName(name: String, tags: scala.collection.Map[String, String] = Map.empty) = {
val klass = this.getClass
val pkg = if (klass.getPackage == null) "" else klass.getPackage.getName
val simpleName = klass.getSimpleName.replaceAll("\\$$", "")
explicitMetricName(pkg, simpleName, name, tags)
}
private def explicitMetricName(group: String, typeName: String, name: String, tags: scala.collection.Map[String, String] = Map.empty) = {
val nameBuilder: StringBuilder = new StringBuilder
nameBuilder.append(group)
nameBuilder.append(":type=")
nameBuilder.append(typeName)
if (name.length > 0) {
nameBuilder.append(",name=")
nameBuilder.append(name)
}
val scope: String = KafkaMetricsGroup.toScope(tags).getOrElse(null)
val tagsName = KafkaMetricsGroup.toMBeanName(tags)
tagsName match {
case Some(tn) =>
nameBuilder.append(",").append(tn)
case None =>
}
new MetricName(group, typeName, name, scope, nameBuilder.toString())
}
def newGauge[T](name: String, metric: Gauge[T], tags: scala.collection.Map[String, String] = Map.empty) =
Metrics.defaultRegistry().newGauge(metricName(name, tags), metric)
def newMeter(name: String, eventType: String, timeUnit: TimeUnit, tags: scala.collection.Map[String, String] = Map.empty) =
Metrics.defaultRegistry().newMeter(metricName(name, tags), eventType, timeUnit)
def newHistogram(name: String, biased: Boolean = true, tags: scala.collection.Map[String, String] = Map.empty) =
Metrics.defaultRegistry().newHistogram(metricName(name, tags), biased)
def newTimer(name: String, durationUnit: TimeUnit, rateUnit: TimeUnit, tags: scala.collection.Map[String, String] = Map.empty) =
Metrics.defaultRegistry().newTimer(metricName(name, tags), durationUnit, rateUnit)
def removeMetric(name: String, tags: scala.collection.Map[String, String] = Map.empty) =
Metrics.defaultRegistry().removeMetric(metricName(name, tags))
}
object KafkaMetricsGroup extends KafkaMetricsGroup with Logging {
/**
* To make sure all the metrics be de-registered after consumer/producer close, the metric names should be
* put into the metric name set.
*/
private val consumerMetricNameList: immutable.List[MetricName] = immutable.List[MetricName](
// kafka.consumer.ZookeeperConsumerConnector
new MetricName("kafka.consumer", "ZookeeperConsumerConnector", "FetchQueueSize"),
new MetricName("kafka.consumer", "ZookeeperConsumerConnector", "KafkaCommitsPerSec"),
new MetricName("kafka.consumer", "ZookeeperConsumerConnector", "ZooKeeperCommitsPerSec"),
new MetricName("kafka.consumer", "ZookeeperConsumerConnector", "RebalanceRateAndTime"),
new MetricName("kafka.consumer", "ZookeeperConsumerConnector", "OwnedPartitionsCount"),
// kafka.consumer.ConsumerFetcherManager
new MetricName("kafka.consumer", "ConsumerFetcherManager", "MaxLag"),
new MetricName("kafka.consumer", "ConsumerFetcherManager", "MinFetchRate"),
// kafka.server.AbstractFetcherThread <-- kafka.consumer.ConsumerFetcherThread
new MetricName("kafka.server", "FetcherLagMetrics", "ConsumerLag"),
// kafka.consumer.ConsumerTopicStats <-- kafka.consumer.{ConsumerIterator, PartitionTopicInfo}
new MetricName("kafka.consumer", "ConsumerTopicMetrics", "MessagesPerSec"),
// kafka.consumer.ConsumerTopicStats
new MetricName("kafka.consumer", "ConsumerTopicMetrics", "BytesPerSec"),
// kafka.server.AbstractFetcherThread <-- kafka.consumer.ConsumerFetcherThread
new MetricName("kafka.server", "FetcherStats", "BytesPerSec"),
new MetricName("kafka.server", "FetcherStats", "RequestsPerSec"),
// kafka.consumer.FetchRequestAndResponseStats <-- kafka.consumer.SimpleConsumer
new MetricName("kafka.consumer", "FetchRequestAndResponseMetrics", "FetchResponseSize"),
new MetricName("kafka.consumer", "FetchRequestAndResponseMetrics", "FetchRequestRateAndTimeMs"),
/**
* ProducerRequestStats <-- SyncProducer
* metric for SyncProducer in fetchTopicMetaData() needs to be removed when consumer is closed.
*/
new MetricName("kafka.producer", "ProducerRequestMetrics", "ProducerRequestRateAndTimeMs"),
new MetricName("kafka.producer", "ProducerRequestMetrics", "ProducerRequestSize")
)
private val producerMetricNameList: immutable.List[MetricName] = immutable.List[MetricName](
// kafka.producer.ProducerStats <-- DefaultEventHandler <-- Producer
new MetricName("kafka.producer", "ProducerStats", "SerializationErrorsPerSec"),
new MetricName("kafka.producer", "ProducerStats", "ResendsPerSec"),
new MetricName("kafka.producer", "ProducerStats", "FailedSendsPerSec"),
// kafka.producer.ProducerSendThread
new MetricName("kafka.producer.async", "ProducerSendThread", "ProducerQueueSize"),
// kafka.producer.ProducerTopicStats <-- kafka.producer.{Producer, async.DefaultEventHandler}
new MetricName("kafka.producer", "ProducerTopicMetrics", "MessagesPerSec"),
new MetricName("kafka.producer", "ProducerTopicMetrics", "DroppedMessagesPerSec"),
new MetricName("kafka.producer", "ProducerTopicMetrics", "BytesPerSec"),
// kafka.producer.ProducerRequestStats <-- SyncProducer
new MetricName("kafka.producer", "ProducerRequestMetrics", "ProducerRequestRateAndTimeMs"),
new MetricName("kafka.producer", "ProducerRequestMetrics", "ProducerRequestSize")
)
private def toMBeanName(tags: collection.Map[String, String]): Option[String] = {
val filteredTags = tags
.filter { case (tagKey, tagValue) => tagValue != ""}
if (filteredTags.nonEmpty) {
val tagsString = filteredTags
.map { case (key, value) => "%s=%s".format(key, value)}
.mkString(",")
Some(tagsString)
}
else {
None
}
}
private def toScope(tags: collection.Map[String, String]): Option[String] = {
val filteredTags = tags
.filter { case (tagKey, tagValue) => tagValue != ""}
if (filteredTags.nonEmpty) {
// convert dot to _ since reporters like Graphite typically use dot to represent hierarchy
val tagsString = filteredTags
.toList.sortWith((t1, t2) => t1._1 < t2._1)
.map { case (key, value) => "%s.%s".format(key, value.replaceAll("\\.", "_"))}
.mkString(".")
Some(tagsString)
}
else {
None
}
}
def removeAllConsumerMetrics(clientId: String) {
FetchRequestAndResponseStatsRegistry.removeConsumerFetchRequestAndResponseStats(clientId)
ConsumerTopicStatsRegistry.removeConsumerTopicStat(clientId)
ProducerRequestStatsRegistry.removeProducerRequestStats(clientId)
removeAllMetricsInList(KafkaMetricsGroup.consumerMetricNameList, clientId)
}
def removeAllProducerMetrics(clientId: String) {
ProducerRequestStatsRegistry.removeProducerRequestStats(clientId)
ProducerTopicStatsRegistry.removeProducerTopicStats(clientId)
ProducerStatsRegistry.removeProducerStats(clientId)
removeAllMetricsInList(KafkaMetricsGroup.producerMetricNameList, clientId)
}
private def removeAllMetricsInList(metricNameList: immutable.List[MetricName], clientId: String) {
metricNameList.foreach(metric => {
val pattern = (".*clientId=" + clientId + ".*").r
val registeredMetrics = scala.collection.JavaConversions.asScalaSet(Metrics.defaultRegistry().allMetrics().keySet())
for (registeredMetric <- registeredMetrics) {
if (registeredMetric.getGroup == metric.getGroup &&
registeredMetric.getName == metric.getName &&
registeredMetric.getType == metric.getType) {
pattern.findFirstIn(registeredMetric.getMBeanName) match {
case Some(_) => {
val beforeRemovalSize = Metrics.defaultRegistry().allMetrics().keySet().size
Metrics.defaultRegistry().removeMetric(registeredMetric)
val afterRemovalSize = Metrics.defaultRegistry().allMetrics().keySet().size
trace("Removing metric %s. Metrics registry size reduced from %d to %d".format(
registeredMetric, beforeRemovalSize, afterRemovalSize))
}
case _ =>
}
}
}
})
}
}
|
cran/rkafkajars
|
java/kafka/metrics/KafkaMetricsGroup.scala
|
Scala
|
apache-2.0
| 9,741 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.