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
/* * 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.ml.stat import org.apache.spark.annotation.Since /** * Trait for selection test results. */ @Since("3.1.0") trait SelectionTestResult { /** * The probability of obtaining a test statistic result at least as extreme as the one that was * actually observed, assuming that the null hypothesis is true. */ @Since("3.1.0") def pValue: Double /** * Test statistic. * In ChiSqSelector, this is chi square statistic * In ANOVASelector and FValueSelector, this is F Value */ @Since("3.1.0") def statistic: Double /** * Returns the degrees of freedom of the hypothesis test. */ @Since("3.1.0") def degreesOfFreedom: Long /** * String explaining the hypothesis test result. * Specific classes implementing this trait should override this method to output test-specific * information. */ override def toString: String = { // String explaining what the p-value indicates. val pValueExplain = if (pValue <= 0.01) { s"Very strong presumption against null hypothesis." } else if (0.01 < pValue && pValue <= 0.05) { s"Strong presumption against null hypothesis." } else if (0.05 < pValue && pValue <= 0.1) { s"Low presumption against null hypothesis." } else { s"No presumption against null hypothesis." } s"degrees of freedom = ${degreesOfFreedom.toString} \\n" + s"pValue = $pValue \\n" + pValueExplain } } /** * Object containing the test results for the chi-squared hypothesis test. */ @Since("3.1.0") class ChiSqTestResult private[stat] ( override val pValue: Double, override val degreesOfFreedom: Long, override val statistic: Double) extends SelectionTestResult { override def toString: String = { "Chi square test summary:\\n" + super.toString + s"Chi square statistic = $statistic \\n" } } /** * Object containing the test results for the FValue regression test. */ @Since("3.1.0") class FValueTestResult private[stat] ( override val pValue: Double, override val degreesOfFreedom: Long, override val statistic: Double) extends SelectionTestResult { override def toString: String = { "FValue Regression test summary:\\n" + super.toString + s"F Value = $statistic \\n" } }
goldmedal/spark
mllib/src/main/scala/org/apache/spark/ml/stat/SelectionTestResult.scala
Scala
apache-2.0
3,082
package com.mogproject.mogami.core.io.kif import com.mogproject.mogami.core.io.{IOFactoryLike, Lines, NonEmptyLines} import com.mogproject.mogami.core.state.StateCache object KifFactory { /** * @note do not ignore comments (* or #) here */ def normalizeString(s: Seq[String]): Lines = for { (ln, n) <- s.zipWithIndex // set line numbers if ln.nonEmpty } yield { (ln, n + 1) } } trait KifFactory[T <: KifLike] extends IOFactoryLike { final def parseKifString(s: String): T = parseKifString(toLines(s, KifFactory.normalizeString)) final def parseKifString(lines: Lines): T = parseKifString(toNonEmptyLines(lines)) def parseKifString(lines: NonEmptyLines): T } trait KifGameFactory[T <: KifLike] extends IOFactoryLike { final def parseKifString(s: String)(implicit stateCache: StateCache): T = parseKifString(s, isFreeMode = false) final def parseKifString(s: String, isFreeMode: Boolean)(implicit stateCache: StateCache): T = parseKifString(toLines(s, KifFactory.normalizeString), isFreeMode) final def parseKifString(lines: Lines, isFreeMode: Boolean)(implicit stateCache: StateCache): T = parseKifString(toNonEmptyLines(lines), isFreeMode) def parseKifString(lines: NonEmptyLines, isFreeMode: Boolean)(implicit stateCache: StateCache): T }
mogproject/mog-core-scala
shared/src/main/scala/com/mogproject/mogami/core/io/kif/KifFactory.scala
Scala
apache-2.0
1,295
package com.andre_cruz.utils import com.andre_cruz.utils.OptionUtils.optionIf object TraversableOnceUtils { implicit class RichTraversableOnce[+A](underlying: TraversableOnce[A]) { def minOption[B >: A](implicit cmp: Ordering[B]): Option[A] = optionIf(underlying.nonEmpty) { underlying.min(cmp) } def maxOption[B >: A](implicit cmp: Ordering[B]): Option[A] = optionIf(underlying.nonEmpty) { underlying.max(cmp) } def minByOption[B](f: A => B)(implicit cmp: Ordering[B]): Option[A] = optionIf(underlying.nonEmpty) { underlying.minBy(f) } def maxByOption[B](f: A => B)(implicit cmp: Ordering[B]): Option[A] = optionIf(underlying.nonEmpty) { underlying.maxBy(f) } } }
codecruzer/scala-caching
src/main/scala/com/andre_cruz/utils/TraversableOnceUtils.scala
Scala
apache-2.0
735
package com.scripts import org.apache.spark.sql.DataFrame import org.apache.spark.sql.SparkSession import org.apache.spark.sql.functions.array import org.apache.spark.sql.functions.col import org.apache.spark.sql.functions.explode import org.apache.spark.sql.functions.lit import org.apache.spark.sql.functions.struct import org.joda.time.DateTime object Excel_read { val sc = SparkSession.builder .master("local") .appName("kmeans") .config("spark.sql.warehouse.dir", "file:///C:/Users/sumeet.agrawal/workspace/Sumeet_Spark") .enableHiveSupport() .getOrCreate() import sc.sqlContext.implicits._ def main(args: Array[String]) = { val df_dollars = sc.sqlContext.read .format("com.databricks.spark.csv") .option("header", "true") .option("parserLib", "UNIVOCITY") .load("C:/Users/sumeet.agrawal/Desktop/Files/CDS.ZPHX.DOLLARS.CLI132.R45.W42.csv").toDF() val df_productList = sc.sqlContext.read .format("com.databricks.spark.csv") .option("header", "true") .option("parserLib", "UNIVOCITY") .load("C:/Users/sumeet.agrawal/Desktop/Files/Immunology-Product_List_2843.csv").toDF().select("Product Group ID", "Product Name") var a = df_dollars.select("Dt").distinct().collect()(0).getString(0).toString() println(a) println(df_dollars.columns.length) val list = df_dollars.columns.map(x => x.toString()).toList println(list) var dm = List[String]() var int = 0 for ((s, i) <- list.zipWithIndex) { if (i < 10) { dm = s :: dm } else { val format = new java.text.SimpleDateFormat("yyMMdd") var date1 = format.parse(a) val dateTime = new DateTime(date1); // println("dateTime : " + dateTime) dm = a :: dm val newdt = dateTime.minusDays(7) // println("newdt: " + newdt.toString()) a = newdt.toString().slice(2, 4).concat(newdt.toString().slice(5, 7)).concat(newdt.toString().slice(8, 10)) } } val newlst = dm.reverse.toSeq println(newlst) val df_Dollars_Renamed = df_dollars.toDF(newlst: _*) df_Dollars_Renamed.show() val df_Dollars_Transpose = toLong(df_Dollars_Renamed, newlst.slice(0, 10)) df_Dollars_Transpose.show() println("Join Started") val final_df_Joined = df_Dollars_Transpose .join(df_productList, df_Dollars_Transpose("PGN") === df_productList("Product Group ID"), "left_outer") final_df_Joined.show(300) println("Finished") } def toLong(df: DataFrame, by: Seq[String]): DataFrame = { val (cols, types) = df.dtypes.filter { case (c, _) => !by.contains(c) }.unzip require(types.distinct.size == 1) val kvs = explode(array( cols.map(c => struct(lit(c).alias("key"), col(c).alias("val"))): _*)) val byExprs = by.map(col(_)) df.select(byExprs :+ kvs.alias("_kvs"): _*) .select(byExprs ++ Seq(kvs.getField("_kvs.key"),kvs.getField("_kvs.val")): _*) } }
sum-coderepo/spark-scala
src/main/scala/com/scripts/Excel_read.scala
Scala
apache-2.0
2,992
/* * Copyright 2001-2013 Artima, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.scalatest import org.scalactic._ import Matchers._ import exceptions.TestFailedException class ShouldEqualNullSpec extends Spec { case class Super(size: Int) class Sub(sz: Int) extends Super(sz) val super1: Super = new Super(1) val sub1: Sub = new Sub(1) val super2: Super = new Super(2) val sub2: Sub = new Sub(2) val nullSuper: Super = null object `The should equal syntax` { def `should work sensibly if null is passed on the left or right hand side` { val caught1 = intercept[TestFailedException] { super1 should equal (null) } caught1.getMessage should be ("Super(1) did not equal null") val caught2 = intercept[TestFailedException] { super1 should (equal (null)) } caught2.getMessage should be ("Super(1) did not equal null") val caught1b = intercept[TestFailedException] { super1 shouldEqual null } caught1b.getMessage should be ("Super(1) did not equal null") super1 should not equal (null) super1 should not (equal (null)) super1 should (not (equal (null))) super1 should (not equal (null)) nullSuper should equal (null) nullSuper shouldEqual null nullSuper should (equal (null)) nullSuper should not equal (super1) nullSuper should not (equal (super1)) nullSuper should (not equal (super1)) nullSuper should (not (equal (super1))) val caught3 = intercept[TestFailedException] { nullSuper should not equal (null) } caught3.getMessage should be ("The reference equaled null") val caught4 = intercept[TestFailedException] { nullSuper should not (equal (null)) } caught4.getMessage should be ("The reference equaled null") val caught5 = intercept[TestFailedException] { nullSuper should (not equal (null)) } caught5.getMessage should be ("The reference equaled null") val caught6 = intercept[TestFailedException] { nullSuper should (not (equal (null))) } caught6.getMessage should be ("The reference equaled null") val caught7 = intercept[TestFailedException] { nullSuper should equal (super1) } caught7.getMessage should be ("null did not equal Super(1)") val caught8 = intercept[TestFailedException] { nullSuper should (equal (super1)) } caught8.getMessage should be ("null did not equal Super(1)") } def `should work sensibly if null is passed on the left or right hand side, when used with logical and` { val caught1 = intercept[TestFailedException] { super1 should (equal (null) and equal (null)) } caught1.getMessage should be ("Super(1) did not equal null") val caught2 = intercept[TestFailedException] { super1 should (equal (super1) and equal (null)) } caught2.getMessage should be ("Super(1) equaled Super(1), but Super(1) did not equal null") super1 should not (equal (null) and equal (null)) val caught3 = intercept[TestFailedException] { nullSuper should (not equal (null)) } caught3.getMessage should be ("The reference equaled null") val caught4 = intercept[TestFailedException] { nullSuper should (equal (null) and not (equal (null))) } caught4.getMessage should be ("The reference equaled null, but the reference equaled null") val caught5 = intercept[TestFailedException] { nullSuper should (equal (null) and not equal (null)) } caught5.getMessage should be ("The reference equaled null, but the reference equaled null") } def `should work sensibly if null is passed on the left or right hand side, when used with logical or` { val caught1 = intercept[TestFailedException] { super1 should (equal (null) or equal (null)) } caught1.getMessage should be ("Super(1) did not equal null, and Super(1) did not equal null") val caught2 = intercept[TestFailedException] { super1 should (equal (null) or (equal (null))) } caught2.getMessage should be ("Super(1) did not equal null, and Super(1) did not equal null") super1 should not (equal (null) or equal (null)) super1 should not (equal (null) or (equal (null))) super1 should (equal (null) or equal (super1)) super1 should (equal (super1) or equal (null)) super1 should (equal (null) or (equal (super1))) super1 should (equal (super1) or (equal (null))) val caught3 = intercept[TestFailedException] { nullSuper should (not equal (null) or not (equal (null))) } caught3.getMessage should be ("The reference equaled null, and the reference equaled null") val caught4 = intercept[TestFailedException] { nullSuper should (not equal (null) or not (equal (null))) } caught4.getMessage should be ("The reference equaled null, and the reference equaled null") val caught5 = intercept[TestFailedException] { nullSuper should (not equal (null) or (not equal (null))) } caught5.getMessage should be ("The reference equaled null, and the reference equaled null") val caught6 = intercept[TestFailedException] { nullSuper should (not equal (null) or (not (equal (null)))) } caught6.getMessage should be ("The reference equaled null, and the reference equaled null") val caught7 = intercept[TestFailedException] { nullSuper should (not equal (null) or not equal (null)) } caught7.getMessage should be ("The reference equaled null, and the reference equaled null") } } }
cheeseng/scalatest
scalatest-test/src/test/scala/org/scalatest/ShouldEqualNullSpec.scala
Scala
apache-2.0
5,956
package net.fehmicansaglam.tepkin import akka.stream.ActorMaterializer import akka.util.Timeout import net.fehmicansaglam.bson.BsonDocument import org.scalatest._ import org.scalatest.concurrent.ScalaFutures import scala.concurrent.duration._ class MongoDatabaseSpec extends FlatSpec with Matchers with ScalaFutures with OptionValues with BeforeAndAfter with BeforeAndAfterAll { override implicit val patienceConfig = PatienceConfig(timeout = 30.seconds, interval = 1.seconds) val client = MongoClient("mongodb://localhost") val db = client("tepkin") import client.{context, ec} implicit val timeout: Timeout = 30.seconds override protected def afterAll() = client.shutdown() "A MongoDatabase" should "list collections" in { implicit val mat = ActorMaterializer() val result = for { source <- db.listCollections() collections <- source.runFold(List.empty[BsonDocument])(_ ++ _) } yield collections whenReady(result) { collections => Logger.debug(s"$collections") } } }
fehmicansaglam/tepkin
tepkin/src/test/scala/net/fehmicansaglam/tepkin/MongoDatabaseSpec.scala
Scala
apache-2.0
1,047
package aia.stream import java.nio.file.{ Path, Paths } object FileArg { def shellExpanded(path: String): Path = { if(path.startsWith("~/")) { Paths.get(System.getProperty("user.home"), path.drop(2)) } else { Paths.get(path) } } }
RayRoestenburg/akka-in-action
chapter-stream/src/main/scala/aia/stream/FileArg.scala
Scala
mit
266
package dotty.tools package dotc package ast import dotty.tools.dotc.transform.ExplicitOuter import dotty.tools.dotc.typer.ProtoTypes.FunProtoTyped import transform.SymUtils._ import core._ import util.Positions._, Types._, Contexts._, Constants._, Names._, Flags._ import SymDenotations._, Symbols._, StdNames._, Annotations._, Trees._, Symbols._ import Denotations._, Decorators._, DenotTransformers._ import config.Printers._ import typer.Mode import collection.mutable import typer.ErrorReporting._ import scala.annotation.tailrec /** Some creators for typed trees */ object tpd extends Trees.Instance[Type] with TypedTreeInfo { private def ta(implicit ctx: Context) = ctx.typeAssigner def Modifiers(sym: Symbol)(implicit ctx: Context): Modifiers = Modifiers( sym.flags & ModifierFlags, if (sym.privateWithin.exists) sym.privateWithin.asType.name else tpnme.EMPTY, sym.annotations map (_.tree)) def Ident(tp: NamedType)(implicit ctx: Context): Ident = ta.assignType(untpd.Ident(tp.name), tp) def Select(qualifier: Tree, name: Name)(implicit ctx: Context): Select = ta.assignType(untpd.Select(qualifier, name), qualifier) def SelectFromTypeTree(qualifier: Tree, name: Name)(implicit ctx: Context): SelectFromTypeTree = ta.assignType(untpd.SelectFromTypeTree(qualifier, name), qualifier) def SelectFromTypeTree(qualifier: Tree, tp: NamedType)(implicit ctx: Context): SelectFromTypeTree = untpd.SelectFromTypeTree(qualifier, tp.name).withType(tp) def This(cls: ClassSymbol)(implicit ctx: Context): This = untpd.This(cls.name).withType(cls.thisType) def Super(qual: Tree, mix: TypeName, inConstrCall: Boolean, mixinClass: Symbol = NoSymbol)(implicit ctx: Context): Super = ta.assignType(untpd.Super(qual, mix), qual, inConstrCall, mixinClass) def Apply(fn: Tree, args: List[Tree])(implicit ctx: Context): Apply = ta.assignType(untpd.Apply(fn, args), fn, args) def TypeApply(fn: Tree, args: List[Tree])(implicit ctx: Context): TypeApply = ta.assignType(untpd.TypeApply(fn, args), fn, args) def Literal(const: Constant)(implicit ctx: Context): Literal = ta.assignType(untpd.Literal(const)) def unitLiteral(implicit ctx: Context): Literal = Literal(Constant(())) def New(tpt: Tree)(implicit ctx: Context): New = ta.assignType(untpd.New(tpt), tpt) def New(tp: Type)(implicit ctx: Context): New = New(TypeTree(tp)) def Pair(left: Tree, right: Tree)(implicit ctx: Context): Pair = ta.assignType(untpd.Pair(left, right), left, right) def Typed(expr: Tree, tpt: Tree)(implicit ctx: Context): Typed = ta.assignType(untpd.Typed(expr, tpt), tpt) def NamedArg(name: Name, arg: Tree)(implicit ctx: Context) = ta.assignType(untpd.NamedArg(name, arg), arg) def Assign(lhs: Tree, rhs: Tree)(implicit ctx: Context): Assign = ta.assignType(untpd.Assign(lhs, rhs)) def Block(stats: List[Tree], expr: Tree)(implicit ctx: Context): Block = ta.assignType(untpd.Block(stats, expr), stats, expr) /** Join `stats` in front of `expr` creating a new block if necessary */ def seq(stats: List[Tree], expr: Tree)(implicit ctx: Context): Tree = if (stats.isEmpty) expr else expr match { case Block(estats, eexpr) => cpy.Block(expr)(stats ::: estats, eexpr) case _ => Block(stats, expr) } def If(cond: Tree, thenp: Tree, elsep: Tree)(implicit ctx: Context): If = ta.assignType(untpd.If(cond, thenp, elsep), thenp, elsep) def Closure(env: List[Tree], meth: Tree, tpt: Tree)(implicit ctx: Context): Closure = ta.assignType(untpd.Closure(env, meth, tpt), meth, tpt) /** A function def * * vparams => expr * * gets expanded to * * { def $anonfun(vparams) = expr; Closure($anonfun) } * * where the closure's type is the target type of the expression (FunctionN, unless * otherwise specified). */ def Closure(meth: TermSymbol, rhsFn: List[List[Tree]] => Tree, targs: List[Tree] = Nil, targetType: Type = NoType)(implicit ctx: Context): Block = { val targetTpt = if (targetType.exists) TypeTree(targetType) else EmptyTree val call = if (targs.isEmpty) Ident(TermRef(NoPrefix, meth)) else TypeApply(Ident(TermRef(NoPrefix, meth)), targs) Block( DefDef(meth, rhsFn) :: Nil, Closure(Nil, call, targetTpt)) } def CaseDef(pat: Tree, guard: Tree, body: Tree)(implicit ctx: Context): CaseDef = ta.assignType(untpd.CaseDef(pat, guard, body), body) def Match(selector: Tree, cases: List[CaseDef])(implicit ctx: Context): Match = ta.assignType(untpd.Match(selector, cases), cases) def Return(expr: Tree, from: Tree)(implicit ctx: Context): Return = ta.assignType(untpd.Return(expr, from)) def Try(block: Tree, cases: List[CaseDef], finalizer: Tree)(implicit ctx: Context): Try = ta.assignType(untpd.Try(block, cases, finalizer), block, cases) def SeqLiteral(elems: List[Tree])(implicit ctx: Context): SeqLiteral = ta.assignType(untpd.SeqLiteral(elems), elems) def SeqLiteral(tpe: Type, elems: List[Tree])(implicit ctx: Context): SeqLiteral = if (tpe derivesFrom defn.SeqClass) SeqLiteral(elems) else JavaSeqLiteral(elems) def JavaSeqLiteral(elems: List[Tree])(implicit ctx: Context): SeqLiteral = ta.assignType(new untpd.JavaSeqLiteral(elems), elems) def TypeTree(original: Tree)(implicit ctx: Context): TypeTree = TypeTree(original.tpe, original) def TypeTree(tp: Type, original: Tree = EmptyTree)(implicit ctx: Context): TypeTree = untpd.TypeTree(original).withType(tp) def SingletonTypeTree(ref: Tree)(implicit ctx: Context): SingletonTypeTree = ta.assignType(untpd.SingletonTypeTree(ref), ref) def AndTypeTree(left: Tree, right: Tree)(implicit ctx: Context): AndTypeTree = ta.assignType(untpd.AndTypeTree(left, right), left, right) def OrTypeTree(left: Tree, right: Tree)(implicit ctx: Context): OrTypeTree = ta.assignType(untpd.OrTypeTree(left, right), left, right) // RefinedTypeTree is missing, handled specially in Typer and Unpickler. def AppliedTypeTree(tycon: Tree, args: List[Tree])(implicit ctx: Context): AppliedTypeTree = ta.assignType(untpd.AppliedTypeTree(tycon, args), tycon, args) def ByNameTypeTree(result: Tree)(implicit ctx: Context): ByNameTypeTree = ta.assignType(untpd.ByNameTypeTree(result), result) def TypeBoundsTree(lo: Tree, hi: Tree)(implicit ctx: Context): TypeBoundsTree = ta.assignType(untpd.TypeBoundsTree(lo, hi), lo, hi) def Bind(sym: TermSymbol, body: Tree)(implicit ctx: Context): Bind = ta.assignType(untpd.Bind(sym.name, body), sym) def Alternative(trees: List[Tree])(implicit ctx: Context): Alternative = ta.assignType(untpd.Alternative(trees), trees) def UnApply(fun: Tree, implicits: List[Tree], patterns: List[Tree], proto: Type)(implicit ctx: Context): UnApply = ta.assignType(untpd.UnApply(fun, implicits, patterns), proto) def ValDef(sym: TermSymbol, rhs: LazyTree = EmptyTree)(implicit ctx: Context): ValDef = ta.assignType(untpd.ValDef(sym.name, TypeTree(sym.info), rhs), sym) def SyntheticValDef(name: TermName, rhs: Tree)(implicit ctx: Context): ValDef = ValDef(ctx.newSymbol(ctx.owner, name, Synthetic, rhs.tpe.widen, coord = rhs.pos), rhs) def DefDef(sym: TermSymbol, rhs: Tree = EmptyTree)(implicit ctx: Context): DefDef = ta.assignType(DefDef(sym, Function.const(rhs) _), sym) def DefDef(sym: TermSymbol, rhsFn: List[List[Tree]] => Tree)(implicit ctx: Context): DefDef = polyDefDef(sym, Function.const(rhsFn)) def polyDefDef(sym: TermSymbol, rhsFn: List[Type] => List[List[Tree]] => Tree)(implicit ctx: Context): DefDef = { val (tparams, mtp) = sym.info match { case tp: PolyType => val tparams = ctx.newTypeParams(sym, tp.paramNames, EmptyFlags, tp.instantiateBounds) (tparams, tp.instantiate(tparams map (_.typeRef))) case tp => (Nil, tp) } def valueParamss(tp: Type): (List[List[TermSymbol]], Type) = tp match { case tp @ MethodType(paramNames, paramTypes) => def valueParam(name: TermName, info: Type): TermSymbol = { val maybeImplicit = if (tp.isInstanceOf[ImplicitMethodType]) Implicit else EmptyFlags ctx.newSymbol(sym, name, TermParam | maybeImplicit, info) } val params = (paramNames, paramTypes).zipped.map(valueParam) val (paramss, rtp) = valueParamss(tp.instantiate(params map (_.termRef))) (params :: paramss, rtp) case tp => (Nil, tp.widenExpr) } val (vparamss, rtp) = valueParamss(mtp) val targs = tparams map (_.typeRef) val argss = vparamss.nestedMap(vparam => Ident(vparam.termRef)) ta.assignType( untpd.DefDef( sym.name, tparams map TypeDef, vparamss.nestedMap(ValDef(_)), TypeTree(rtp), rhsFn(targs)(argss)), sym) } def TypeDef(sym: TypeSymbol)(implicit ctx: Context): TypeDef = ta.assignType(untpd.TypeDef(sym.name, TypeTree(sym.info)), sym) def ClassDef(cls: ClassSymbol, constr: DefDef, body: List[Tree], superArgs: List[Tree] = Nil)(implicit ctx: Context): TypeDef = { val firstParentRef :: otherParentRefs = cls.info.parents val firstParent = cls.typeRef.baseTypeWithArgs(firstParentRef.symbol) val superRef = if (cls is Trait) TypeTree(firstParent) else { def isApplicable(ctpe: Type): Boolean = ctpe match { case ctpe: PolyType => isApplicable(ctpe.instantiate(firstParent.argTypes)) case ctpe: MethodType => (superArgs corresponds ctpe.paramTypes)(_.tpe <:< _) case _ => false } val constr = firstParent.decl(nme.CONSTRUCTOR).suchThat(constr => isApplicable(constr.info)) New(firstParent, constr.symbol.asTerm, superArgs) } val parents = superRef :: otherParentRefs.map(TypeTree(_)) val selfType = if (cls.classInfo.selfInfo ne NoType) ValDef(ctx.newSelfSym(cls)) else EmptyValDef def isOwnTypeParam(stat: Tree) = (stat.symbol is TypeParam) && stat.symbol.owner == cls val bodyTypeParams = body filter isOwnTypeParam map (_.symbol) val newTypeParams = for (tparam <- cls.typeParams if !(bodyTypeParams contains tparam)) yield TypeDef(tparam) val findLocalDummy = new FindLocalDummyAccumulator(cls) val localDummy = ((NoSymbol: Symbol) /: body)(findLocalDummy.apply) .orElse(ctx.newLocalDummy(cls)) val impl = untpd.Template(constr, parents, selfType, newTypeParams ++ body) .withType(localDummy.nonMemberTermRef) ta.assignType(untpd.TypeDef(cls.name, impl), cls) } /** An anonymous class * * new parents { forwarders } * * where `forwarders` contains forwarders for all functions in `fns`. * @param parents a non-empty list of class types * @param fns a non-empty of functions for which forwarders should be defined in the class. * The class has the same owner as the first function in `fns`. * Its position is the union of all functions in `fns`. */ def AnonClass(parents: List[Type], fns: List[TermSymbol], methNames: List[TermName])(implicit ctx: Context): Block = { val owner = fns.head.owner val parents1 = if (parents.head.classSymbol.is(Trait)) defn.ObjectClass.typeRef :: parents else parents val cls = ctx.newNormalizedClassSymbol(owner, tpnme.ANON_FUN, Synthetic, parents1, coord = fns.map(_.pos).reduceLeft(_ union _)) val constr = ctx.newConstructor(cls, Synthetic, Nil, Nil).entered def forwarder(fn: TermSymbol, name: TermName) = { val fwdMeth = fn.copy(cls, name, Synthetic | Method).entered.asTerm DefDef(fwdMeth, prefss => ref(fn).appliedToArgss(prefss)) } val forwarders = (fns, methNames).zipped.map(forwarder) val cdef = ClassDef(cls, DefDef(constr), forwarders) Block(cdef :: Nil, New(cls.typeRef, Nil)) } // { <label> def while$(): Unit = if (cond) { body; while$() } ; while$() } def WhileDo(owner: Symbol, cond: Tree, body: List[Tree])(implicit ctx: Context): Tree = { val sym = ctx.newSymbol(owner, nme.WHILE_PREFIX, Flags.Label | Flags.Synthetic, MethodType(Nil, defn.UnitType), coord = cond.pos) val call = Apply(ref(sym), Nil) val rhs = If(cond, Block(body, call), unitLiteral) Block(List(DefDef(sym, rhs)), call) } def Import(expr: Tree, selectors: List[untpd.Tree])(implicit ctx: Context): Import = ta.assignType(untpd.Import(expr, selectors), ctx.newImportSymbol(ctx.owner, expr)) def PackageDef(pid: RefTree, stats: List[Tree])(implicit ctx: Context): PackageDef = ta.assignType(untpd.PackageDef(pid, stats), pid) def Annotated(annot: Tree, arg: Tree)(implicit ctx: Context): Annotated = ta.assignType(untpd.Annotated(annot, arg), annot, arg) def Throw(expr: Tree)(implicit ctx: Context): Tree = ref(defn.throwMethod).appliedTo(expr) // ------ Making references ------------------------------------------------------ def prefixIsElidable(tp: NamedType)(implicit ctx: Context) = { def test(implicit ctx: Context) = tp.prefix match { case NoPrefix => true case pre: ThisType => pre.cls.isStaticOwner || tp.symbol.is(ParamOrAccessor) && !pre.cls.is(Trait) && ctx.owner.enclosingClass == pre.cls // was ctx.owner.enclosingClass.derivesFrom(pre.cls) which was not tight enough // and was spuriously triggered in case inner class would inherit from outer one // eg anonymous TypeMap inside TypeMap.andThen case pre: TermRef => pre.symbol.is(Module) && pre.symbol.isStatic case _ => false } try test || tp.symbol.is(JavaStatic) catch { // See remark in SymDenotations#accessWithin case ex: NotDefinedHere => test(ctx.addMode(Mode.FutureDefsOK)) } } def needsSelect(tp: Type)(implicit ctx: Context) = tp match { case tp: TermRef => !prefixIsElidable(tp) case _ => false } /** A tree representing the same reference as the given type */ def ref(tp: NamedType)(implicit ctx: Context): Tree = if (tp.isType) TypeTree(tp) else if (prefixIsElidable(tp)) Ident(tp) else if (tp.symbol.is(Module) && ctx.owner.isContainedIn(tp.symbol.moduleClass)) followOuterLinks(This(tp.symbol.moduleClass.asClass)) else tp.prefix match { case pre: SingletonType => followOuterLinks(singleton(pre)).select(tp) case pre => SelectFromTypeTree(TypeTree(pre), tp) } // no checks necessary def ref(sym: Symbol)(implicit ctx: Context): Tree = ref(NamedType(sym.owner.thisType, sym.name, sym.denot)) private def followOuterLinks(t: Tree)(implicit ctx: Context) = t match { case t: This if ctx.erasedTypes && !(t.symbol == ctx.owner.enclosingClass || t.symbol.isStaticOwner) => // after erasure outer paths should be respected new ExplicitOuter.OuterOps(ctx).path(t.tpe.widen.classSymbol) case t => t } def singleton(tp: Type)(implicit ctx: Context): Tree = tp match { case tp: TermRef => ref(tp) case tp: ThisType => This(tp.cls) case SuperType(qual, _) => singleton(qual) case ConstantType(value) => Literal(value) } /** A tree representing a `newXYZArray` operation of the right * kind for the given element type in `typeArg`. No type arguments or * `length` arguments are given. */ def newArray(typeArg: Tree, pos: Position)(implicit ctx: Context): Tree = { val elemType = typeArg.tpe val elemClass = elemType.classSymbol def newArr(kind: String) = ref(defn.DottyArraysModule).select(s"new${kind}Array".toTermName).withPos(pos) if (TypeErasure.isUnboundedGeneric(elemType)) newArr("Generic").appliedToTypeTrees(typeArg :: Nil) else if (elemClass.isPrimitiveValueClass) newArr(elemClass.name.toString) else newArr("Ref").appliedToTypeTrees( TypeTree(defn.ArrayType(elemType)).withPos(typeArg.pos) :: Nil) } // ------ Creating typed equivalents of trees that exist only in untyped form ------- /** new C(args), calling the primary constructor of C */ def New(tp: Type, args: List[Tree])(implicit ctx: Context): Apply = New(tp, tp.typeSymbol.primaryConstructor.asTerm, args) /** new C(args), calling given constructor `constr` of C */ def New(tp: Type, constr: TermSymbol, args: List[Tree])(implicit ctx: Context): Apply = { val targs = tp.argTypes New(tp withoutArgs targs) .select(TermRef.withSig(tp.normalizedPrefix, constr)) .appliedToTypes(targs) .appliedToArgs(args) } /** An object def * * object obs extends parents { decls } * * gets expanded to * * <module> val obj = new obj$ * <module> class obj$ extends parents { this: obj.type => decls } * * (The following no longer applies: * What's interesting here is that the block is well typed * (because class obj$ is hoistable), but the type of the `obj` val is * not expressible. What needs to happen in general when * inferring the type of a val from its RHS, is: if the type contains * a class that has the val itself as owner, then that class * is remapped to have the val's owner as owner. Remapping could be * done by cloning the class with the new owner and substituting * everywhere in the tree. We know that remapping is safe * because the only way a local class can appear in the RHS of a val is * by being hoisted outside of a block, and the necessary checks are * done at this point already. * * On the other hand, for method result type inference, if the type of * the RHS of a method contains a class owned by the method, this would be * an error.) */ def ModuleDef(sym: TermSymbol, body: List[Tree])(implicit ctx: Context): tpd.Thicket = { val modcls = sym.moduleClass.asClass val constrSym = modcls.primaryConstructor orElse ctx.newDefaultConstructor(modcls).entered val constr = DefDef(constrSym.asTerm, EmptyTree) val clsdef = ClassDef(modcls, constr, body) val valdef = ValDef(sym, New(modcls.typeRef).select(constrSym).appliedToNone) Thicket(valdef, clsdef) } /** A `_' with given type */ def Underscore(tp: Type)(implicit ctx: Context) = untpd.Ident(nme.WILDCARD).withType(tp) def defaultValue(tpe: Types.Type)(implicit ctx: Context) = { val tpw = tpe.widen if (tpw isRef defn.IntClass) Literal(Constant(0)) else if (tpw isRef defn.LongClass) Literal(Constant(0L)) else if (tpw isRef defn.BooleanClass) Literal(Constant(false)) else if (tpw isRef defn.CharClass) Literal(Constant('\\u0000')) else if (tpw isRef defn.FloatClass) Literal(Constant(0f)) else if (tpw isRef defn.DoubleClass) Literal(Constant(0d)) else if (tpw isRef defn.ByteClass) Literal(Constant(0.toByte)) else if (tpw isRef defn.ShortClass) Literal(Constant(0.toShort)) else Literal(Constant(null)).select(defn.Any_asInstanceOf).appliedToType(tpe) } private class FindLocalDummyAccumulator(cls: ClassSymbol)(implicit ctx: Context) extends TreeAccumulator[Symbol] { def apply(sym: Symbol, tree: Tree)(implicit ctx: Context) = if (sym.exists) sym else if (tree.isDef) { val owner = tree.symbol.owner if (owner.isLocalDummy && owner.owner == cls) owner else if (owner == cls) foldOver(sym, tree) else sym } else foldOver(sym, tree) } implicit class modsDeco(mdef: MemberDef)(implicit ctx: Context) extends ModsDeco { def mods = if (mdef.hasType) Modifiers(mdef.symbol) else mdef.rawMods } override val cpy = new TypedTreeCopier class TypedTreeCopier extends TreeCopier { def postProcess(tree: Tree, copied: untpd.Tree): copied.ThisTree[Type] = copied.withTypeUnchecked(tree.tpe) def postProcess(tree: Tree, copied: untpd.MemberDef): copied.ThisTree[Type] = copied.withTypeUnchecked(tree.tpe) override def Select(tree: Tree)(qualifier: Tree, name: Name)(implicit ctx: Context): Select = { val tree1 = untpd.cpy.Select(tree)(qualifier, name) tree match { case tree: Select if qualifier.tpe eq tree.qualifier.tpe => tree1.withTypeUnchecked(tree.tpe) case _ => tree.tpe match { case tpe: NamedType => tree1.withType(tpe.derivedSelect(qualifier.tpe)) case _ => tree1.withTypeUnchecked(tree.tpe) } } } override def Apply(tree: Tree)(fun: Tree, args: List[Tree])(implicit ctx: Context): Apply = ta.assignType(untpd.cpy.Apply(tree)(fun, args), fun, args) // Note: Reassigning the original type if `fun` and `args` have the same types as before // does not work here: The computed type depends on the widened function type, not // the function type itself. A treetransform may keep the function type the // same but its widened type might change. override def TypeApply(tree: Tree)(fun: Tree, args: List[Tree])(implicit ctx: Context): TypeApply = ta.assignType(untpd.cpy.TypeApply(tree)(fun, args), fun, args) // Same remark as for Apply override def Literal(tree: Tree)(const: Constant)(implicit ctx: Context): Literal = ta.assignType(untpd.cpy.Literal(tree)(const)) override def New(tree: Tree)(tpt: Tree)(implicit ctx: Context): New = ta.assignType(untpd.cpy.New(tree)(tpt), tpt) override def Pair(tree: Tree)(left: Tree, right: Tree)(implicit ctx: Context): Pair = { val tree1 = untpd.cpy.Pair(tree)(left, right) tree match { case tree: Pair if (left.tpe eq tree.left.tpe) && (right.tpe eq tree.right.tpe) => tree1.withTypeUnchecked(tree.tpe) case _ => ta.assignType(tree1, left, right) } } override def Typed(tree: Tree)(expr: Tree, tpt: Tree)(implicit ctx: Context): Typed = ta.assignType(untpd.cpy.Typed(tree)(expr, tpt), tpt) override def NamedArg(tree: Tree)(name: Name, arg: Tree)(implicit ctx: Context): NamedArg = ta.assignType(untpd.cpy.NamedArg(tree)(name, arg), arg) override def Assign(tree: Tree)(lhs: Tree, rhs: Tree)(implicit ctx: Context): Assign = ta.assignType(untpd.cpy.Assign(tree)(lhs, rhs)) override def Block(tree: Tree)(stats: List[Tree], expr: Tree)(implicit ctx: Context): Block = { val tree1 = untpd.cpy.Block(tree)(stats, expr) tree match { case tree: Block if expr.tpe eq tree.expr.tpe => tree1.withTypeUnchecked(tree.tpe) case _ => ta.assignType(tree1, stats, expr) } } override def If(tree: Tree)(cond: Tree, thenp: Tree, elsep: Tree)(implicit ctx: Context): If = { val tree1 = untpd.cpy.If(tree)(cond, thenp, elsep) tree match { case tree: If if (thenp.tpe eq tree.thenp.tpe) && (elsep.tpe eq tree.elsep.tpe) => tree1.withTypeUnchecked(tree.tpe) case _ => ta.assignType(tree1, thenp, elsep) } } override def Closure(tree: Tree)(env: List[Tree], meth: Tree, tpt: Tree)(implicit ctx: Context): Closure = ta.assignType(untpd.cpy.Closure(tree)(env, meth, tpt), meth, tpt) // Same remark as for Apply override def Match(tree: Tree)(selector: Tree, cases: List[CaseDef])(implicit ctx: Context): Match = { val tree1 = untpd.cpy.Match(tree)(selector, cases) tree match { case tree: Match if sameTypes(cases, tree.cases) => tree1.withTypeUnchecked(tree.tpe) case _ => ta.assignType(tree1, cases) } } override def CaseDef(tree: Tree)(pat: Tree, guard: Tree, body: Tree)(implicit ctx: Context): CaseDef = { val tree1 = untpd.cpy.CaseDef(tree)(pat, guard, body) tree match { case tree: CaseDef if body.tpe eq tree.body.tpe => tree1.withTypeUnchecked(tree.tpe) case _ => ta.assignType(tree1, body) } } override def Return(tree: Tree)(expr: Tree, from: Tree)(implicit ctx: Context): Return = ta.assignType(untpd.cpy.Return(tree)(expr, from)) override def Try(tree: Tree)(expr: Tree, cases: List[CaseDef], finalizer: Tree)(implicit ctx: Context): Try = { val tree1 = untpd.cpy.Try(tree)(expr, cases, finalizer) tree match { case tree: Try if (expr.tpe eq tree.expr.tpe) && sameTypes(cases, tree.cases) => tree1.withTypeUnchecked(tree.tpe) case _ => ta.assignType(tree1, expr, cases) } } override def SeqLiteral(tree: Tree)(elems: List[Tree])(implicit ctx: Context): SeqLiteral = { val tree1 = untpd.cpy.SeqLiteral(tree)(elems) tree match { case tree: SeqLiteral if sameTypes(elems, tree.elems) => tree1.withTypeUnchecked(tree.tpe) case _ => ta.assignType(tree1, elems) } } override def Annotated(tree: Tree)(annot: Tree, arg: Tree)(implicit ctx: Context): Annotated = { val tree1 = untpd.cpy.Annotated(tree)(annot, arg) tree match { case tree: Annotated if (arg.tpe eq tree.arg.tpe) && (annot eq tree.annot) => tree1.withTypeUnchecked(tree.tpe) case _ => ta.assignType(tree1, annot, arg) } } override def If(tree: If)(cond: Tree = tree.cond, thenp: Tree = tree.thenp, elsep: Tree = tree.elsep)(implicit ctx: Context): If = If(tree: Tree)(cond, thenp, elsep) override def Closure(tree: Closure)(env: List[Tree] = tree.env, meth: Tree = tree.meth, tpt: Tree = tree.tpt)(implicit ctx: Context): Closure = Closure(tree: Tree)(env, meth, tpt) override def CaseDef(tree: CaseDef)(pat: Tree = tree.pat, guard: Tree = tree.guard, body: Tree = tree.body)(implicit ctx: Context): CaseDef = CaseDef(tree: Tree)(pat, guard, body) override def Try(tree: Try)(expr: Tree = tree.expr, cases: List[CaseDef] = tree.cases, finalizer: Tree = tree.finalizer)(implicit ctx: Context): Try = Try(tree: Tree)(expr, cases, finalizer) } implicit class TreeOps[ThisTree <: tpd.Tree](val tree: ThisTree) extends AnyVal { def isValue(implicit ctx: Context): Boolean = tree.isTerm && tree.tpe.widen.isValueType def isValueOrPattern(implicit ctx: Context) = tree.isValue || tree.isPattern def isValueType: Boolean = tree.isType && tree.tpe.isValueType def isInstantiation: Boolean = tree match { case Apply(Select(New(_), nme.CONSTRUCTOR), _) => true case _ => false } def shallowFold[T](z: T)(op: (T, tpd.Tree) => T)(implicit ctx: Context) = new ShallowFolder(op).apply(z, tree) def deepFold[T](z: T)(op: (T, tpd.Tree) => T)(implicit ctx: Context) = new DeepFolder(op).apply(z, tree) def find[T](pred: (tpd.Tree) => Boolean)(implicit ctx: Context): Option[tpd.Tree] = shallowFold[Option[tpd.Tree]](None)((accum, tree) => if (pred(tree)) Some(tree) else accum) def subst(from: List[Symbol], to: List[Symbol])(implicit ctx: Context): ThisTree = new TreeTypeMap(substFrom = from, substTo = to).apply(tree) /** Change owner from `from` to `to`. If `from` is a weak owner, also change its * owner to `to`, and continue until a non-weak owner is reached. */ def changeOwner(from: Symbol, to: Symbol)(implicit ctx: Context): ThisTree = { def loop(from: Symbol, froms: List[Symbol], tos: List[Symbol]): ThisTree = { if (from.isWeakOwner && !from.owner.isClass) loop(from.owner, from :: froms, to :: tos) else { //println(i"change owner ${from :: froms}%, % ==> $tos of $tree") new TreeTypeMap(oldOwners = from :: froms, newOwners = tos)(ctx.withMode(Mode.FutureDefsOK)).apply(tree) } } loop(from, Nil, to :: Nil) } /** After phase `trans`, set the owner of every definition in this tree that was formerly * owner by `from` to `to`. */ def changeOwnerAfter(from: Symbol, to: Symbol, trans: DenotTransformer)(implicit ctx: Context): ThisTree = { assert(ctx.phase == trans.next) val traverser = new TreeTraverser { def traverse(tree: Tree)(implicit ctx: Context) = tree match { case tree: DefTree => val sym = tree.symbol if (sym.denot(ctx.withPhase(trans)).owner == from) { val d = sym.copySymDenotation(owner = to) d.installAfter(trans) d.transformAfter(trans, d => if (d.owner eq from) d.copySymDenotation(owner = to) else d) } if (sym.isWeakOwner) traverseChildren(tree) case _ => traverseChildren(tree) } } traverser.traverse(tree) tree } /** A select node with the given selector name and a computed type */ def select(name: Name)(implicit ctx: Context): Select = Select(tree, name) /** A select node with the given type */ def select(tp: NamedType)(implicit ctx: Context): Select = untpd.Select(tree, tp.name).withType(tp) /** A select node that selects the given symbol. Note: Need to make sure this * is in fact the symbol you would get when you select with the symbol's name, * otherwise a data race may occur which would be flagged by -Yno-double-bindings. */ def select(sym: Symbol)(implicit ctx: Context): Select = untpd.Select(tree, sym.name).withType( TermRef.withSigAndDenot(tree.tpe, sym.name.asTermName, sym.signature, sym.denot.asSeenFrom(tree.tpe))) /** A select node with the given selector name and signature and a computed type */ def selectWithSig(name: Name, sig: Signature)(implicit ctx: Context): Tree = untpd.SelectWithSig(tree, name, sig) .withType(TermRef.withSig(tree.tpe, name.asTermName, sig)) /** A select node with selector name and signature taken from `sym`. * Note: Use this method instead of select(sym) if the referenced symbol * might be overridden in the type of the qualifier prefix. See note * on select(sym: Symbol). */ def selectWithSig(sym: Symbol)(implicit ctx: Context): Tree = selectWithSig(sym.name, sym.signature) /** A unary apply node with given argument: `tree(arg)` */ def appliedTo(arg: Tree)(implicit ctx: Context): Tree = appliedToArgs(arg :: Nil) /** An apply node with given arguments: `tree(arg, args0, ..., argsN)` */ def appliedTo(arg: Tree, args: Tree*)(implicit ctx: Context): Tree = appliedToArgs(arg :: args.toList) /** An apply node with given argument list `tree(args(0), ..., args(args.length - 1))` */ def appliedToArgs(args: List[Tree])(implicit ctx: Context): Apply = Apply(tree, args) /** The current tree applied to given argument lists: * `tree (argss(0)) ... (argss(argss.length -1))` */ def appliedToArgss(argss: List[List[Tree]])(implicit ctx: Context): Tree = ((tree: Tree) /: argss)(Apply(_, _)) /** The current tree applied to (): `tree()` */ def appliedToNone(implicit ctx: Context): Apply = appliedToArgs(Nil) /** The current tree applied to given type argument: `tree[targ]` */ def appliedToType(targ: Type)(implicit ctx: Context): Tree = appliedToTypes(targ :: Nil) /** The current tree applied to given type arguments: `tree[targ0, ..., targN]` */ def appliedToTypes(targs: List[Type])(implicit ctx: Context): Tree = appliedToTypeTrees(targs map (TypeTree(_))) /** The current tree applied to given type argument list: `tree[targs(0), ..., targs(targs.length - 1)]` */ def appliedToTypeTrees(targs: List[Tree])(implicit ctx: Context): Tree = if (targs.isEmpty) tree else TypeApply(tree, targs) /** Apply to `()` unless tree's widened type is parameterless */ def ensureApplied(implicit ctx: Context): Tree = if (tree.tpe.widen.isParameterless) tree else tree.appliedToNone /** `tree.isInstanceOf[tp]` */ def isInstance(tp: Type)(implicit ctx: Context): Tree = tree.select(defn.Any_isInstanceOf).appliedToType(tp) /** tree.asInstanceOf[`tp`] */ def asInstance(tp: Type)(implicit ctx: Context): Tree = { assert(tp.isValueType, i"bad cast: $tree.asInstanceOf[$tp]") tree.select(defn.Any_asInstanceOf).appliedToType(tp) } /** `tree.asInstanceOf[tp]` unless tree's type already conforms to `tp` */ def ensureConforms(tp: Type)(implicit ctx: Context): Tree = if (tree.tpe <:< tp) tree else asInstance(tp) /** If inititializer tree is `_', the default value of its type, * otherwise the tree itself. */ def wildcardToDefault(implicit ctx: Context) = if (isWildcardArg(tree)) defaultValue(tree.tpe) else tree /** `this && that`, for boolean trees `this`, `that` */ def and(that: Tree)(implicit ctx: Context): Tree = tree.select(defn.Boolean_&&).appliedTo(that) /** `this || that`, for boolean trees `this`, `that` */ def or(that: Tree)(implicit ctx: Context): Tree = tree.select(defn.Boolean_||).appliedTo(that) /** The translation of `tree = rhs`. * This is either the tree as an assignment, to a setter call. */ def becomes(rhs: Tree)(implicit ctx: Context): Tree = if (tree.symbol is Method) { val setr = tree match { case Ident(_) => val setter = tree.symbol.setter assert(setter.exists, tree.symbol.showLocated) ref(tree.symbol.setter) case Select(qual, _) => qual.select(tree.symbol.setter) } setr.appliedTo(rhs) } else Assign(tree, rhs) // --- Higher order traversal methods ------------------------------- /** Apply `f` to each subtree of this tree */ def foreachSubTree(f: Tree => Unit)(implicit ctx: Context): Unit = { val traverser = new TreeTraverser { def traverse(tree: Tree)(implicit ctx: Context) = foldOver(f(tree), tree) } traverser.traverse(tree) } /** Is there a subtree of this tree that satisfies predicate `p`? */ def existsSubTree(p: Tree => Boolean)(implicit ctx: Context): Boolean = { val acc = new TreeAccumulator[Boolean] { def apply(x: Boolean, t: Tree)(implicit ctx: Context) = x || p(t) || foldOver(x, t) } acc(false, tree) } /** All subtrees of this tree that satisfy predicate `p`. */ def filterSubTrees(f: Tree => Boolean)(implicit ctx: Context): List[Tree] = { val buf = new mutable.ListBuffer[Tree] foreachSubTree { tree => if (f(tree)) buf += tree } buf.toList } } implicit class ListOfTreeDecorator(val xs: List[tpd.Tree]) extends AnyVal { def tpes: List[Type] = xs map (_.tpe) } // convert a numeric with a toXXX method def primitiveConversion(tree: Tree, numericCls: Symbol)(implicit ctx: Context): Tree = { val mname = ("to" + numericCls.name).toTermName val conversion = tree.tpe member mname if (conversion.symbol.exists) tree.select(conversion.symbol.termRef).ensureApplied else if (tree.tpe.widen isRef numericCls) tree else { ctx.warning(i"conversion from ${tree.tpe.widen} to ${numericCls.typeRef} will always fail at runtime.") Throw(New(defn.ClassCastExceptionClass.typeRef, Nil)) withPos tree.pos } } def applyOverloaded(receiver: Tree, method: TermName, args: List[Tree], targs: List[Type], expectedType: Type, isAnnotConstructor: Boolean = false)(implicit ctx: Context): Tree = { val typer = ctx.typer val proto = new FunProtoTyped(args, expectedType, typer) val alts = receiver.tpe.member(method).alternatives.map(_.termRef) val alternatives = ctx.typer.resolveOverloaded(alts, proto, Nil) assert(alternatives.size == 1) // this is parsed from bytecode tree. there's nothing user can do about it val prefixTpe = if (method eq nme.CONSTRUCTOR) receiver.tpe.normalizedPrefix // <init> methods are part of the enclosing scope else receiver.tpe val selected = alternatives.head val fun = receiver .select(TermRef.withSig(prefixTpe, selected.termSymbol.asTerm)) .appliedToTypes(targs) def adaptLastArg(lastParam: Tree, expectedType: Type) = { if (isAnnotConstructor && !(lastParam.tpe <:< expectedType)) { val defn = ctx.definitions val prefix = args.take(selected.widen.paramTypess.head.size - 1) expectedType match { case defn.ArrayType(el) => lastParam.tpe match { case defn.ArrayType(el2) if el2 <:< el => // we have a JavaSeqLiteral with a more precise type // we cannot construct a tree as JavaSeqLiteral infered to precise type // if we add typed than it would be both type-correct and // will pass Ycheck prefix ::: List(tpd.Typed(lastParam, TypeTree(defn.ArrayType(el)))) case _ => ??? } case _ => args } } else args } val callArgs: List[Tree] = if (args.isEmpty) Nil else { val expectedType = selected.widen.paramTypess.head.last val lastParam = args.last adaptLastArg(lastParam, expectedType) } val apply = untpd.Apply(fun, callArgs) new typer.ApplyToTyped(apply, fun, selected, callArgs, expectedType).result.asInstanceOf[Tree] // needed to handle varargs } @tailrec def sameTypes(trees: List[tpd.Tree], trees1: List[tpd.Tree]): Boolean = { if (trees.isEmpty) trees.isEmpty else if (trees1.isEmpty) trees.isEmpty else (trees.head.tpe eq trees1.head.tpe) && sameTypes(trees.tail, trees1.tail) } def evalOnce(tree: Tree)(within: Tree => Tree)(implicit ctx: Context) = { if (isIdempotentExpr(tree)) within(tree) else { val vdef = SyntheticValDef(ctx.freshName("ev$").toTermName, tree) Block(vdef :: Nil, within(Ident(vdef.namedType))) } } def runtimeCall(name: TermName, args: List[Tree])(implicit ctx: Context): Tree = { Ident(defn.ScalaRuntimeModule.requiredMethod(name).termRef).appliedToArgs(args) } /** An extractor that pulls out type arguments */ object MaybePoly { def unapply(tree: Tree): Option[(Tree, List[Tree])] = tree match { case TypeApply(tree, targs) => Some(tree, targs) case _ => Some(tree, Nil) } } /** A traverser that passes the enclosing class or method as an argument * to the traverse method. */ abstract class EnclosingMethodTraverser extends TreeAccumulator[Symbol] { def traverse(enclMeth: Symbol, tree: Tree)(implicit ctx: Context): Unit def apply(enclMeth: Symbol, tree: Tree)(implicit ctx: Context) = { tree match { case _: DefTree if tree.symbol.exists => traverse(tree.symbol.enclosingMethod, tree) case _ => traverse(enclMeth, tree) } enclMeth } } // ensure that constructors are fully applied? // ensure that normal methods are fully applied? }
spetz911/dotty
src/dotty/tools/dotc/ast/tpd.scala
Scala
bsd-3-clause
38,695
//package org.aja.tantra.examples.concurrency.akka // ///** // * Created by mdhandapani on 29/10/15. // */ //import akka.actor._ //import akka.routing.RoundRobinRouter //import scala.concurrent.duration._ // //object Pi extends App { // // calculate(nrOfWorkers = 4, nrOfElements = 10000, nrOfMessages = 10000) // // sealed trait PiMessage // case object Calculate extends PiMessage // case class Work(start: Int, nrOfElements: Int) extends PiMessage // case class Result(value: Double) extends PiMessage // case class PiApproximation(pi: Double, duration: Duration) // // class Worker extends Actor { // def calculatePiFor(start: Int, nrOfElements: Int): Double = { // var acc = 0.0 // for (i <- start until (start + nrOfElements)) // acc += 4.0 * (1 - (i % 2) * 2) / (2 * i + 1) // acc // } // // def receive = { // case Work(start, nrOfElements) => // sender ! Result(calculatePiFor(start, nrOfElements)) // perform the work // } // } // // class Master(nrOfWorkers: Int, // nrOfMessages: Int, // nrOfElements: Int, // listener: ActorRef) extends Actor { // var pi: Double = _ // var nrOfResults: Int = _ // val start: Long = System.currentTimeMillis // // val workerRouter = context.actorOf( // Props[Worker].withRouter(RoundRobinRouter(nrOfWorkers)), name = "workerRouter") // // def receive = { // case Calculate ⇒ // for (i <- 0 until nrOfMessages) // workerRouter ! Work(i * nrOfElements, nrOfElements) // case Result(value) => // pi += value // nrOfResults += 1 // if (nrOfResults == nrOfMessages) { // // Send the result to the listener // listener ! PiApproximation(pi, duration = (System.currentTimeMillis - start).millis) // // Stops this actor and all its supervised children // context.stop(self) // } // } // } // // class Listener extends Actor { // def receive = { // case PiApproximation(pi, duration) => // println("\\n\\tPi approximation: \\t\\t%s\\n\\tCalculation time: \\t%s" // .format(pi, duration)) // context.system.shutdown() // } // } // // def calculate(nrOfWorkers: Int, nrOfElements: Int, nrOfMessages: Int) { // // Create an Akka system // val system = ActorSystem("PiSystem") // // // create the result listener, which will print the result and // // shutdown the system // val listener = system.actorOf(Props[Listener], name = "listener") // // // create the master // val master = system.actorOf(Props(new Master( // nrOfWorkers, nrOfMessages, nrOfElements, listener)), // name = "master") // // // start the calculation // master ! Calculate // } //}
Mageswaran1989/aja
src/examples/scala/org/aja/tantra/examples/concurrency/akka/PI.scala
Scala
apache-2.0
2,769
class CrashTest { def foo = () trait CrashTestTable { def cols = foo } // This was leading to a class between the mixed in // outer accessor and the outer accessor of this object. object CrashTestTable extends CrashTestTable { foo cols } } class CrashTest1 { def foo = () class CrashTestTable { def cols = foo } object CrashTestTable extends CrashTestTable { foo cols } } class CrashTest2 { def foo = () trait CrashTestTable { def cols = foo } object Obj extends CrashTestTable { foo cols } } class CrashTest3 { def foo = () def meth() { trait CrashTestTable { def cols = foo } object Obj extends CrashTestTable { foo cols } Obj } } object Test extends App { { val c = new CrashTest c.CrashTestTable } { val c = new CrashTest1 c.CrashTestTable } { val c = new CrashTest2 c.Obj } { val c = new CrashTest3 c.meth() } }
felixmulder/scala
test/files/run/t7242.scala
Scala
bsd-3-clause
987
package scalaguide.ws.scalaopenid import play.api.test._ //#dependency import javax.inject.Inject import scala.concurrent.Future import play.api._ import play.api.mvc._ import play.api.data._ import play.api.data.Forms._ import play.api.libs.openid._ class Application @Inject() (openIdClient: OpenIdClient) extends Controller { } //#dependency object ScalaOpenIdSpec extends PlaySpecification { "Scala OpenId" should { "be injectable" in new WithApplication() { app.injector.instanceOf[Application] must beAnInstanceOf[Application] } } def openIdClient: OpenIdClient = null import play.api.mvc.Results._ //#flow def login = Action { Ok(views.html.login()) } def loginPost = Action.async { implicit request => Form(single( "openid" -> nonEmptyText )).bindFromRequest.fold({ error => Logger.info("bad request " + error.toString) Future.successful(BadRequest(error.toString)) }, { openId => openIdClient.redirectURL(openId, routes.Application.openIdCallback.absoluteURL()) .map(url => Redirect(url)) .recover { case t: Throwable => Redirect(routes.Application.login)} }) } def openIdCallback = Action.async { implicit request => openIdClient.verifiedId(request).map(info => Ok(info.id + "\\n" + info.attributes)) .recover { case t: Throwable => // Here you should look at the error, and give feedback to the user Redirect(routes.Application.login) } } //#flow def extended(openId: String)(implicit request: RequestHeader) = { //#extended openIdClient.redirectURL( openId, routes.Application.openIdCallback.absoluteURL(), Seq("email" -> "http://schema.openid.net/contact/email") ) //#extended } } object routes { object Application { val login = Call("GET", "login") val openIdCallback = Call("GET", "callback") } } package views { object html { def login() = "loginpage" } }
jyotikamboj/container
pf-documentation/manual/working/scalaGuide/main/ws/code/ScalaOpenIdSpec.scala
Scala
mit
1,973
package tut import java.io.File import tut.Zed._ object TutMain { def main(args: Array[String]): Unit = runl(args.toList).unsafePerformIO() def runl(args: List[String]): IO[Unit] = { val (in, out) = (args(0), args(1)).umap(new File(_)) val filter = args(2).r val opts = args.drop(3) for { fa <- if (in.isFile) IO(List(in)) else FileIO.ls(in) ss <- fa.traverse(f => FileIO.walk(f, out, filter, opts)).map(_.flatten) _ <- if (ss.exists(_.err)) IO.fail(TutException("Tut execution failed.")) else IO(()) } yield () } }
tpolecat/tut
modules/core/src/main/scala/tut/TutMain.scala
Scala
mit
567
package org.openurp.edu.eams.teach.grade.transcript.service.impl import org.beangle.commons.collection.Collections import org.beangle.commons.dao.impl.BaseServiceImpl import org.openurp.edu.base.Student import org.openurp.edu.eams.teach.grade.transcript.service.TranscriptDataProvider import org.openurp.edu.teach.plan.CourseGroup import org.openurp.edu.teach.plan.CoursePlan import org.openurp.edu.teach.plan.PlanCourse import org.openurp.edu.eams.teach.program.service.CoursePlanProvider class TranscriptPlanCourse extends BaseServiceImpl with TranscriptDataProvider { private var coursePlanProvider: CoursePlanProvider = _ def getDataName(): String = "planCourses" def getData[T](std: Student, options: Map[String, String]): T = { val planCourses = getPlanCourses(std) if (Collections.isNotEmpty(planCourses)) { return planCourses.get(0).asInstanceOf[T] } null.asInstanceOf[T] } def getDatas[T](stds: List[Student], options: Map[String, String]): Map[Student, T] = { val datas = Collections.newMap[Any] for (std <- stds) { val planCourses = getPlanCourses(std) datas.put(std, planCourses.asInstanceOf[T]) } datas } private def getPlanCourses(std: Student): List[PlanCourse] = { val planCourses = new ArrayList[PlanCourse]() val coursePlan = coursePlanProvider.majorPlan(std) if (coursePlan != null) { for (courseGroup <- coursePlan.getGroups) { planCourses.addAll(courseGroup.getPlanCourses) } } planCourses } def setCoursePlanProvider(coursePlanProvider: CoursePlanProvider) { this.coursePlanProvider = coursePlanProvider } }
openurp/edu-eams-webapp
grade/src/main/scala/org/openurp/edu/eams/teach/grade/transcript/service/impl/TranscriptPlanCourse.scala
Scala
gpl-3.0
1,657
object Test extends dotty.runtime.LegacyApp { def test[T](t1 : T, t2 : T)(implicit ord : Ordering[T]) = { val cmp = ord.compare(t1, t2); val cmp2 = ord.compare(t2, t1); assert((cmp == 0) == (cmp2 == 0)) assert((cmp > 0) == (cmp2 < 0)) assert((cmp < 0) == (cmp2 > 0)) } def testAll[T](t1 : T, t2 : T)(implicit ord : Ordering[T]) = { assert(ord.compare(t1, t2) < 0) test(t1, t2); test(t1, t1); test(t2, t2); } assert(Ordering[String].compare("australopithecus", "brontausaurus") < 0) // assert(Ordering[Unit].compare((), ()) == 0) testAll("bar", "foo"); testAll[Byte](0, 1); testAll(false, true) testAll(1, 2); testAll(1.0, 2.0); testAll(None, Some(1)); testAll[Iterable[Int]](List(1), List(1, 2)); testAll[Iterable[Int]](List(1, 2), List(2)); testAll((1, "bar"), (1, "foo")) testAll((1, "foo"), (2, "bar")) // sortBy val words = "The quick brown fox jumped over the lazy dog".split(' ') val result = words.sortBy(x => (x.length, x.head)) assert(result sameElements Array[String]("The", "dog", "fox", "the", "lazy", "over", "brown", "quick", "jumped")) }
yusuke2255/dotty
tests/run/OrderingTest.scala
Scala
bsd-3-clause
1,134
/* * Copyright 2001-2013 Artima, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.scalatest.time import org.scalatest.Resources /** * Defines a family of singleton objects representing units of time. * * <p> * The singleton objects that extend this abstract class may be passed * to the constructor of <a href="Span.html"><code>Span</code></a> to specify * units of time. For example: * </p> * * <pre class="stHighlight"> * Span(1, Second) * </pre> */ sealed abstract class Units extends Product with Serializable { private[scalatest] def singularMessageFun(lengthString: String): String private[scalatest] def pluralMessageFun(lengthString: String): String } /** * Indicates units for a single nanosecond. * * <p> * This singleton object may be passed to the constructor of <a href="Span.html"><code>Span</code></a> to * specify nanosecond units of time, so long as the value passed to <code>Span</code> is 1. For example: * </p> * * <pre class="stHighlight"> * Span(1, Nanosecond) * </pre> */ case object Nanosecond extends Units { private[scalatest] def singularMessageFun(lengthString: String): String = Resources.singularNanosecondUnits(lengthString) private[scalatest] def pluralMessageFun(lengthString: String): String = Resources.pluralNanosecondUnits(lengthString) } /** * Indicates nanosecond units. * * <p> * This singleton object may be passed to the constructor of <a href="Span.html"><code>Span</code></a> to * specify nanosecond units of time. For example: * </p> * * <pre class="stHighlight"> * Span(10, Nanoseconds) * </pre> */ case object Nanoseconds extends Units { private[scalatest] def singularMessageFun(lengthString: String): String = Resources.singularNanosecondUnits(lengthString) private[scalatest] def pluralMessageFun(lengthString: String): String = Resources.pluralNanosecondUnits(lengthString) } /** * Indicates units for a single microsecond. * * <p> * This singleton object may be passed to the constructor of <a href="Span.html"><code>Span</code></a> to * specify microsecond units of time, so long as the value passed to <code>Span</code> is 1. For example: * </p> * * <pre class="stHighlight"> * Span(1, Microsecond) * </pre> */ case object Microsecond extends Units { private[scalatest] def singularMessageFun(lengthString: String): String = Resources.singularMicrosecondUnits(lengthString) private[scalatest] def pluralMessageFun(lengthString: String): String = Resources.pluralMicrosecondUnits(lengthString) } /** * Indicates microsecond units. * * <p> * This singleton object may be passed to the constructor of <a href="Span.html"><code>Span</code></a> to * specify microsecond units of time. For example: * </p> * * <pre class="stHighlight"> * Span(10, Microseconds) * </pre> */ case object Microseconds extends Units { private[scalatest] def singularMessageFun(lengthString: String): String = Resources.singularMicrosecondUnits(lengthString) private[scalatest] def pluralMessageFun(lengthString: String): String = Resources.pluralMicrosecondUnits(lengthString) } /** * Indicates units for a single millisecond. * * <p> * This singleton object may be passed to the constructor of <a href="Span.html"><code>Span</code></a> to * specify millisecond units of time, so long as the value passed to <code>Span</code> is 1. For example: * </p> * * <pre class="stHighlight"> * Span(1, Millisecond) * </pre> */ case object Millisecond extends Units { private[scalatest] def singularMessageFun(lengthString: String): String = Resources.singularMillisecondUnits(lengthString) private[scalatest] def pluralMessageFun(lengthString: String): String = Resources.pluralMillisecondUnits(lengthString) } /** * Indicates millisecond units. * * <p> * This singleton object may be passed to the constructor of <a href="Span.html"><code>Span</code></a> to * specify millisecond units of time. For example: * </p> * * <pre class="stHighlight"> * Span(10, Milliseconds) * </pre> */ case object Milliseconds extends Units { private[scalatest] def singularMessageFun(lengthString: String): String = Resources.singularMillisecondUnits(lengthString) private[scalatest] def pluralMessageFun(lengthString: String): String = Resources.pluralMillisecondUnits(lengthString) } /** * Indicates millisecond units (shorthand form). * * <p> * This singleton object may be passed to the constructor of <a href="Span.html"><code>Span</code></a> to * specify millisecond units of time. For example: * </p> * * <pre class="stHighlight"> * Span(10, Millis) * </pre> * * <p> * <em>Note: <code>Millis</code> is merely a shorthand for <a href="Milliseconds$.html"><code>Milliseconds</code></a>. * When passed to <code>Span</code>, <code>Millis</code> means exactly the same thing as * <code>Milliseconds</code>.</em> * </p> */ case object Millis extends Units { private[scalatest] def singularMessageFun(lengthString: String): String = Resources.singularMillisecondUnits(lengthString) private[scalatest] def pluralMessageFun(lengthString: String): String = Resources.pluralMillisecondUnits(lengthString) } /** * Indicates units for a single second. * * <p> * This singleton object may be passed to the constructor of <a href="Span.html"><code>Span</code></a> to * specify second units of time, so long as the value passed to <code>Span</code> is 1. For example: * </p> * * <pre class="stHighlight"> * Span(1, Second) * </pre> */ case object Second extends Units { private[scalatest] def singularMessageFun(lengthString: String): String = Resources.singularSecondUnits(lengthString) private[scalatest] def pluralMessageFun(lengthString: String): String = Resources.pluralSecondUnits(lengthString) } /** * Indicates second units. * * <p> * This singleton object may be passed to the constructor of <a href="Span.html"><code>Span</code></a> to * specify second units of time. For example: * </p> * * <pre class="stHighlight"> * Span(10, Seconds) * </pre> */ case object Seconds extends Units { private[scalatest] def singularMessageFun(lengthString: String): String = Resources.singularSecondUnits(lengthString) private[scalatest] def pluralMessageFun(lengthString: String): String = Resources.pluralSecondUnits(lengthString) } /** * Indicates units for a single minute. * * <p> * This singleton object may be passed to the constructor of <a href="Span.html"><code>Span</code></a> to * specify minute units of time, so long as the value passed to <code>Span</code> is 1. For example: * </p> * * <pre class="stHighlight"> * Span(1, Minute) * </pre> */ case object Minute extends Units { private[scalatest] def singularMessageFun(lengthString: String): String = Resources.singularMinuteUnits(lengthString) private[scalatest] def pluralMessageFun(lengthString: String): String = Resources.pluralMinuteUnits(lengthString) } /** * Indicates minute units. * * <p> * This singleton object may be passed to the constructor of <a href="Span.html"><code>Span</code></a> to * specify minute units of time. For example: * </p> * * <pre class="stHighlight"> * Span(10, Minutes) * </pre> */ case object Minutes extends Units { private[scalatest] def singularMessageFun(lengthString: String): String = Resources.singularMinuteUnits(lengthString) private[scalatest] def pluralMessageFun(lengthString: String): String = Resources.pluralMinuteUnits(lengthString) } /** * Indicates units for a single hour. * * <p> * This singleton object may be passed to the constructor of <a href="Span.html"><code>Span</code></a> to * specify hour units of time, so long as the value passed to <code>Span</code> is 1. For example: * </p> * * <pre class="stHighlight"> * Span(1, Hour) * </pre> */ case object Hour extends Units { private[scalatest] def singularMessageFun(lengthString: String): String = Resources.singularHourUnits(lengthString) private[scalatest] def pluralMessageFun(lengthString: String): String = Resources.pluralHourUnits(lengthString) } /** * Indicates hour units. * * <p> * This singleton object may be passed to the constructor of <a href="Span.html"><code>Span</code></a> to * specify hour units of time. For example: * </p> * * <pre class="stHighlight"> * Span(10, Hours) * </pre> */ case object Hours extends Units { private[scalatest] def singularMessageFun(lengthString: String): String = Resources.singularHourUnits(lengthString) private[scalatest] def pluralMessageFun(lengthString: String): String = Resources.pluralHourUnits(lengthString) } /** * Indicates units for a single day. * * <p> * This singleton object may be passed to the constructor of <a href="Span.html"><code>Span</code></a> to * specify day units of time, so long as the value passed to <code>Span</code> is 1. For example: * </p> * * <pre class="stHighlight"> * Span(1, Day) * </pre> */ case object Day extends Units { private[scalatest] def singularMessageFun(lengthString: String): String = Resources.singularDayUnits(lengthString) private[scalatest] def pluralMessageFun(lengthString: String): String = Resources.pluralDayUnits(lengthString) } /** * Indicates day units. * * <p> * This singleton object may be passed to the constructor of <a href="Span.html"><code>Span</code></a> to * specify day units of time. For example: * </p> * * <pre class="stHighlight"> * Span(10, Days) * </pre> */ case object Days extends Units { private[scalatest] def singularMessageFun(lengthString: String): String = Resources.singularDayUnits(lengthString) private[scalatest] def pluralMessageFun(lengthString: String): String = Resources.pluralDayUnits(lengthString) }
dotty-staging/scalatest
scalatest/src/main/scala/org/scalatest/time/Units.scala
Scala
apache-2.0
10,213
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark import java.io.{IOException, ObjectInputStream, ObjectOutputStream} import scala.collection.mutable import scala.collection.mutable.ArrayBuffer import scala.reflect.{ClassTag, classTag} import scala.util.hashing.byteswap32 import org.apache.spark.rdd.{PartitionPruningRDD, RDD} import org.apache.spark.serializer.JavaSerializer import org.apache.spark.util.{CollectionsUtils, Utils} import org.apache.spark.util.random.{XORShiftRandom, SamplingUtils} /** * An object that defines how the elements in a key-value pair RDD are partitioned by key. * Maps each key to a partition ID, from 0 to `numPartitions - 1`. */ abstract class Partitioner extends Serializable { def numPartitions: Int def getPartition(key: Any): Int } object Partitioner { /** * Choose a partitioner to use for a cogroup-like operation between a number of RDDs. * * If any of the RDDs already has a partitioner, choose that one. * * Otherwise, we use a default HashPartitioner. For the number of partitions, if * spark.default.parallelism is set, then we'll use the value from SparkContext * defaultParallelism, otherwise we'll use the max number of upstream partitions. * * Unless spark.default.parallelism is set, the number of partitions will be the * same as the number of partitions in the largest upstream RDD, as this should * be least likely to cause out-of-memory errors. * * We use two method parameters (rdd, others) to enforce callers passing at least 1 RDD. */ def defaultPartitioner(rdd: RDD[_], others: RDD[_]*): Partitioner = { val bySize = (Seq(rdd) ++ others).sortBy(_.partitions.size).reverse for (r <- bySize if r.partitioner.isDefined && r.partitioner.get.numPartitions > 0) { return r.partitioner.get } if (rdd.context.conf.contains("spark.default.parallelism")) { new HashPartitioner(rdd.context.defaultParallelism) } else { new HashPartitioner(bySize.head.partitions.size) } } } /** * A [[org.apache.spark.Partitioner]] that implements hash-based partitioning using * Java's `Object.hashCode`. * * Java arrays have hashCodes that are based on the arrays' identities rather than their contents, * so attempting to partition an RDD[Array[_]] or RDD[(Array[_], _)] using a HashPartitioner will * produce an unexpected or incorrect result. */ class HashPartitioner(partitions: Int) extends Partitioner { def numPartitions: Int = partitions def getPartition(key: Any): Int = key match { case null => 0 case _ => Utils.nonNegativeMod(key.hashCode, numPartitions) } override def equals(other: Any): Boolean = other match { case h: HashPartitioner => h.numPartitions == numPartitions case _ => false } override def hashCode: Int = numPartitions } /** * A [[org.apache.spark.Partitioner]] that partitions sortable records by range into roughly * equal ranges. The ranges are determined by sampling the content of the RDD passed in. * * Note that the actual number of partitions created by the RangePartitioner might not be the same * as the `partitions` parameter, in the case where the number of sampled records is less than * the value of `partitions`. */ class RangePartitioner[K : Ordering : ClassTag, V]( @transient partitions: Int, @transient rdd: RDD[_ <: Product2[K, V]], private var ascending: Boolean = true) extends Partitioner { // We allow partitions = 0, which happens when sorting an empty RDD under the default settings. require(partitions >= 0, s"Number of partitions cannot be negative but found $partitions.") private var ordering = implicitly[Ordering[K]] // An array of upper bounds for the first (partitions - 1) partitions private var rangeBounds: Array[K] = { if (partitions <= 1) { Array.empty } else { // This is the sample size we need to have roughly balanced output partitions, capped at 1M. val sampleSize = math.min(20.0 * partitions, 1e6) // Assume the input partitions are roughly balanced and over-sample a little bit. val sampleSizePerPartition = math.ceil(3.0 * sampleSize / rdd.partitions.size).toInt val (numItems, sketched) = RangePartitioner.sketch(rdd.map(_._1), sampleSizePerPartition) if (numItems == 0L) { Array.empty } else { // If a partition contains much more than the average number of items, we re-sample from it // to ensure that enough items are collected from that partition. val fraction = math.min(sampleSize / math.max(numItems, 1L), 1.0) val candidates = ArrayBuffer.empty[(K, Float)] val imbalancedPartitions = mutable.Set.empty[Int] sketched.foreach { case (idx, n, sample) => if (fraction * n > sampleSizePerPartition) { imbalancedPartitions += idx } else { // The weight is 1 over the sampling probability. val weight = (n.toDouble / sample.size).toFloat for (key <- sample) { candidates += ((key, weight)) } } } if (imbalancedPartitions.nonEmpty) { // Re-sample imbalanced partitions with the desired sampling probability. val imbalanced = new PartitionPruningRDD(rdd.map(_._1), imbalancedPartitions.contains) val seed = byteswap32(-rdd.id - 1) val reSampled = imbalanced.sample(withReplacement = false, fraction, seed).collect() val weight = (1.0 / fraction).toFloat candidates ++= reSampled.map(x => (x, weight)) } RangePartitioner.determineBounds(candidates, partitions) } } } def numPartitions: Int = rangeBounds.length + 1 private var binarySearch: ((Array[K], K) => Int) = CollectionsUtils.makeBinarySearch[K] def getPartition(key: Any): Int = { val k = key.asInstanceOf[K] var partition = 0 if (rangeBounds.length <= 128) { // If we have less than 128 partitions naive search while (partition < rangeBounds.length && ordering.gt(k, rangeBounds(partition))) { partition += 1 } } else { // Determine which binary search method to use only once. partition = binarySearch(rangeBounds, k) // binarySearch either returns the match location or -[insertion point]-1 if (partition < 0) { partition = -partition-1 } if (partition > rangeBounds.length) { partition = rangeBounds.length } } if (ascending) { partition } else { rangeBounds.length - partition } } override def equals(other: Any): Boolean = other match { case r: RangePartitioner[_, _] => r.rangeBounds.sameElements(rangeBounds) && r.ascending == ascending case _ => false } override def hashCode(): Int = { val prime = 31 var result = 1 var i = 0 while (i < rangeBounds.length) { result = prime * result + rangeBounds(i).hashCode i += 1 } result = prime * result + ascending.hashCode result } @throws(classOf[IOException]) private def writeObject(out: ObjectOutputStream): Unit = Utils.tryOrIOException { val sfactory = SparkEnv.get.serializer sfactory match { case js: JavaSerializer => out.defaultWriteObject() case _ => out.writeBoolean(ascending) out.writeObject(ordering) out.writeObject(binarySearch) val ser = sfactory.newInstance() Utils.serializeViaNestedStream(out, ser) { stream => stream.writeObject(scala.reflect.classTag[Array[K]]) stream.writeObject(rangeBounds) } } } @throws(classOf[IOException]) private def readObject(in: ObjectInputStream): Unit = Utils.tryOrIOException { val sfactory = SparkEnv.get.serializer sfactory match { case js: JavaSerializer => in.defaultReadObject() case _ => ascending = in.readBoolean() ordering = in.readObject().asInstanceOf[Ordering[K]] binarySearch = in.readObject().asInstanceOf[(Array[K], K) => Int] val ser = sfactory.newInstance() Utils.deserializeViaNestedStream(in, ser) { ds => implicit val classTag = ds.readObject[ClassTag[Array[K]]]() rangeBounds = ds.readObject[Array[K]]() } } } } private[spark] object RangePartitioner { /** * Sketches the input RDD via reservoir sampling on each partition. * * @param rdd the input RDD to sketch * @param sampleSizePerPartition max sample size per partition * @return (total number of items, an array of (partitionId, number of items, sample)) */ def sketch[K : ClassTag]( rdd: RDD[K], sampleSizePerPartition: Int): (Long, Array[(Int, Int, Array[K])]) = { val shift = rdd.id // val classTagK = classTag[K] // to avoid serializing the entire partitioner object val sketched = rdd.mapPartitionsWithIndex { (idx, iter) => val seed = byteswap32(idx ^ (shift << 16)) val (sample, n) = SamplingUtils.reservoirSampleAndCount( iter, sampleSizePerPartition, seed) Iterator((idx, n, sample)) }.collect() val numItems = sketched.map(_._2.toLong).sum (numItems, sketched) } /** * Determines the bounds for range partitioning from candidates with weights indicating how many * items each represents. Usually this is 1 over the probability used to sample this candidate. * * @param candidates unordered candidates with weights * @param partitions number of partitions * @return selected bounds */ def determineBounds[K : Ordering : ClassTag]( candidates: ArrayBuffer[(K, Float)], partitions: Int): Array[K] = { val ordering = implicitly[Ordering[K]] val ordered = candidates.sortBy(_._1) val numCandidates = ordered.size val sumWeights = ordered.map(_._2.toDouble).sum val step = sumWeights / partitions var cumWeight = 0.0 var target = step val bounds = ArrayBuffer.empty[K] var i = 0 var j = 0 var previousBound = Option.empty[K] while ((i < numCandidates) && (j < partitions - 1)) { val (key, weight) = ordered(i) cumWeight += weight if (cumWeight > target) { // Skip duplicate values. if (previousBound.isEmpty || ordering.gt(key, previousBound.get)) { bounds += key target += step j += 1 previousBound = Some(key) } } i += 1 } bounds.toArray } }
andrewor14/iolap
core/src/main/scala/org/apache/spark/Partitioner.scala
Scala
apache-2.0
11,268
package com.nthportal.shell.async import scala.concurrent.Future /** * Something which provides input (asynchronously) for an [[AsyncShell]]. */ trait InputProvider { /** * Returns a [[Future]] which will contain the next [[InputAction action]] * to be executed (by an [[AsyncShell]]). * * Successive invocations of this method MUST NOT return Futures which will * be completed with the same action; they MUST return Futures which will be * completed with successive requested actions. * * @return a Future which will contain the next action to be executed */ def nextAction: Future[InputAction[_]] }
NthPortal/app-shell
src/main/scala/com/nthportal/shell/async/InputProvider.scala
Scala
apache-2.0
647
/* * Copyright 2015 MongoDB, 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.mongodb.scala.model import com.mongodb.client.model.{ PushOptions => JPushOptions } /** * The options to apply to a `\\$push` update operator. * * @since 1.0 */ object PushOptions { def apply(): JPushOptions = new JPushOptions() }
anand-singh/mongo-scala-driver
driver/src/main/scala/org/mongodb/scala/model/PushOptions.scala
Scala
apache-2.0
846
package HackerRank.Training.DataStructures.Arrays import java.io.{ByteArrayInputStream, IOException, InputStream, PrintWriter} import java.util.InputMismatchException import scala.collection.generic.CanBuildFrom import scala.collection.mutable.ListBuffer import scala.language.higherKinds /** * Copyright (c) 2017 A. Roberto Fischer * * @author A. Roberto Fischer <[email protected]> on 6/7/2017 */ private[this] object DynamicArray { import Reader._ import Writer._ private[this] val TEST_INPUT: Option[String] = None //------------------------------------------------------------------------------------------// // Solution //------------------------------------------------------------------------------------------// private[this] def solve(): Unit = { val n = nextInt() val q = nextInt() val seqList = Array.fill(n)(ListBuffer.empty[Int]) val queries = next[(Int, Int, Int), Vector]((nextInt(), nextInt(), nextInt()), q) var lastAnswer = 0 queries.foreach { case (1, x, y) => seqList((x ^ lastAnswer) % n) = seqList((x ^ lastAnswer) % n) += y case (2, x, y) => lastAnswer = seqList((x ^ lastAnswer) % n)(y % seqList((x ^ lastAnswer) % n).size) println(lastAnswer) case _ => throw new RuntimeException } } //------------------------------------------------------------------------------------------// // Run //------------------------------------------------------------------------------------------// @throws[Exception] def main(args: Array[String]): Unit = { val s = System.currentTimeMillis solve() flush() if (TEST_INPUT.isDefined) System.out.println(System.currentTimeMillis - s + "ms") } //------------------------------------------------------------------------------------------// // Input //------------------------------------------------------------------------------------------// private[this] final object Reader { private[this] implicit val in: InputStream = TEST_INPUT.fold(System.in)(s => new ByteArrayInputStream(s.getBytes)) def nextSeq[T, Coll[_]](reader: => Seq[T], n: Int) (implicit cbf: CanBuildFrom[Coll[T], T, Coll[T]]): Coll[T] = { val builder = cbf() builder.sizeHint(n) for (_ <- 0 until n) { builder ++= reader } builder.result() } def next[T, Coll[_]](reader: => T, n: Int) (implicit cbf: CanBuildFrom[Coll[T], T, Coll[T]]): Coll[T] = { val builder = cbf() builder.sizeHint(n) for (_ <- 0 until n) { builder += reader } builder.result() } def nextWithIndex[T, Coll[_]](reader: => T, n: Int) (implicit cbf: CanBuildFrom[Coll[(T, Int)], (T, Int), Coll[(T, Int)]]): Coll[(T, Int)] = { val builder = cbf() builder.sizeHint(n) for (i <- 0 until n) { builder += ((reader, i)) } builder.result() } def nextDouble[Coll[_]] (n: Int)(implicit cbf: CanBuildFrom[Coll[Double], Double, Coll[Double]]): Coll[Double] = { val builder = cbf() builder.sizeHint(n) for (_ <- 0 until n) { builder += nextDouble() } builder.result() } def nextDoubleWithIndex[Coll[_]] (n: Int)(implicit cbf: CanBuildFrom[Coll[(Double, Int)], (Double, Int), Coll[(Double, Int)]]): Coll[(Double, Int)] = { val builder = cbf() builder.sizeHint(n) for (i <- 0 until n) { builder += ((nextDouble(), i)) } builder.result() } def nextChar[Coll[_]] (n: Int)(implicit cbf: CanBuildFrom[Coll[Char], Char, Coll[Char]]): Coll[Char] = { val builder = cbf() builder.sizeHint(n) var b = skip var p = 0 while (p < n && !isSpaceChar(b)) { builder += b.toChar p += 1 b = readByte().toInt } builder.result() } def nextCharWithIndex[Coll[_]] (n: Int)(implicit cbf: CanBuildFrom[Coll[(Char, Int)], (Char, Int), Coll[(Char, Int)]]): Coll[(Char, Int)] = { val builder = cbf() builder.sizeHint(n) var b = skip var p = 0 while (p < n && !isSpaceChar(b)) { builder += ((b.toChar, p)) p += 1 b = readByte().toInt } builder.result() } def nextInt[Coll[_]] (n: Int)(implicit cbf: CanBuildFrom[Coll[Int], Int, Coll[Int]]): Coll[Int] = { val builder = cbf() builder.sizeHint(n) for (_ <- 0 until n) { builder += nextInt() } builder.result() } def nextIntWithIndex[Coll[_]] (n: Int)(implicit cbf: CanBuildFrom[Coll[(Int, Int)], (Int, Int), Coll[(Int, Int)]]): Coll[(Int, Int)] = { val builder = cbf() builder.sizeHint(n) for (i <- 0 until n) { builder += ((nextInt(), i)) } builder.result() } def nextLong[Coll[_]] (n: Int)(implicit cbf: CanBuildFrom[Coll[Long], Long, Coll[Long]]): Coll[Long] = { val builder = cbf() builder.sizeHint(n) for (_ <- 0 until n) { builder += nextLong() } builder.result() } def nextLongWithIndex[Coll[_]] (n: Int)(implicit cbf: CanBuildFrom[Coll[(Long, Int)], (Long, Int), Coll[(Long, Int)]]): Coll[(Long, Int)] = { val builder = cbf() builder.sizeHint(n) for (i <- 0 until n) { builder += ((nextLong(), i)) } builder.result() } def nextString[Coll[_]] (n: Int)(implicit cbf: CanBuildFrom[Coll[String], String, Coll[String]]): Coll[String] = { val builder = cbf() builder.sizeHint(n) for (_ <- 0 until n) { builder += nextString() } builder.result() } def nextStringWithIndex[Coll[_]] (n: Int)(implicit cbf: CanBuildFrom[Coll[(String, Int)], (String, Int), Coll[(String, Int)]]): Coll[(String, Int)] = { val builder = cbf() builder.sizeHint(n) for (i <- 0 until n) { builder += ((nextString(), i)) } builder.result() } def nextMultiLine(n: Int, m: Int): Array[Array[Char]] = { val map = new Array[Array[Char]](n) var i = 0 while (i < n) { map(i) = nextChar[Array](m) i += 1 } map } def nextDouble(): Double = nextString().toDouble def nextChar(): Char = skip.toChar def nextString(): String = { var b = skip val sb = new java.lang.StringBuilder while (!isSpaceChar(b)) { sb.appendCodePoint(b) b = readByte().toInt } sb.toString } def nextInt(): Int = { var num = 0 var b = 0 var minus = false while ( { b = readByte().toInt b != -1 && !((b >= '0' && b <= '9') || b == '-') }) {} if (b == '-') { minus = true b = readByte().toInt } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0') } else { if (minus) return -num else return num } b = readByte().toInt } throw new IOException("Read Int") } def nextLong(): Long = { var num = 0L var b = 0 var minus = false while ( { b = readByte().toInt b != -1 && !((b >= '0' && b <= '9') || b == '-') }) {} if (b == '-') { minus = true b = readByte().toInt } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0') } else { if (minus) return -num else return num } b = readByte().toInt } throw new IOException("Read Long") } private[this] val inputBuffer = new Array[Byte](1024) private[this] var lenBuffer = 0 private[this] var ptrBuffer = 0 private[this] def readByte()(implicit in: java.io.InputStream): Byte = { if (lenBuffer == -1) throw new InputMismatchException if (ptrBuffer >= lenBuffer) { ptrBuffer = 0 try { lenBuffer = in.read(inputBuffer) } catch { case _: IOException => throw new InputMismatchException } if (lenBuffer <= 0) return -1 } inputBuffer({ ptrBuffer += 1 ptrBuffer - 1 }) } private[this] def isSpaceChar(c: Int) = !(c >= 33 && c <= 126) private[this] def skip = { var b = 0 while ( { b = readByte().toInt b != -1 && isSpaceChar(b) }) {} b } } //------------------------------------------------------------------------------------------// // Output //------------------------------------------------------------------------------------------// private[this] final object Writer { private[this] val out = new PrintWriter(System.out) def flush(): Unit = out.flush() def println(x: Any): Unit = out.println(x) def print(x: Any): Unit = out.print(x) } }
robertoFischer/hackerrank
src/main/scala/HackerRank/Training/DataStructures/Arrays/DynamicArray.scala
Scala
mit
8,999
class Yiibai(xc: Int, yc: Int){ var x: Int = xc var y: Int = yc def move(dx: Int, dy: Int){ x = x + dx y = y + dy println("Yiibai x location : " + x) println("Yiibai y location : " + y) } }
cmonkey/scala-school
src/main/scala/Yiibai.scala
Scala
gpl-3.0
216
import scala.math.pow object ExactlyAthrid { def main(arg: Array[String]) { val digits = List(1, 2, 3, 4, 5, 6, 7, 8, 9); for (c <- digits.combinations(4)) { for(d <- c.permutations) { // Get the numerator var numerator = 0; for((digit, place) <- d.zipWithIndex) { numerator += digit * pow(10, place).toInt; } // Get the denominator var denominator = 3 * numerator; // Check if all digits appear // exactly once var cdigits = numerator.toString + denominator.toString; var cdigits_list = cdigits.toCharArray. distinct; // Print solution if (cdigits_list.length == 9 && !cdigits_list.contains('0')){ println("%d / %d = 1/3". format(numerator, denominator)); } } } } }
MartinThoma/LaTeX-examples
documents/Programmierparadigmen/scripts/scala/04-ExactlyAThird.scala
Scala
mit
917
/* * Copyright (c) 2017 Clement Trosa <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package io.trosa.avian.network import io.trosa.avian.Types.Pivot trait Request { /* Request implementation * Process one request, an parse * connection to scraper actor that * will build Index sequence and process * pivot balancing to message broker consumer. * @param pivot request targets * */ def process(pivot: Pivot): Unit }
iomonad/avian
src/main/scala/io/trosa/avian/network/Request.scala
Scala
mit
1,481
package com.chriswk.bnet.wow.model /** * A Wow Character */ case class Spec(name: Option[String], role: String, backgroundImage: String, icon: String, description: String, order: Int) case class Character(name: String, achievementPoints: Int, battlegroup: String, `class`: Int, level: Int, race: Int, realm: String, thumbnail: String, guild: String, spec: Option[Spec] )
chriswk/sbnetapi
src/main/scala/com/chriswk/bnet/wow/model/Character.scala
Scala
mit
584
package lila object log { def apply(name: String): Logger = new Logger(name) val boot = apply("boot") val sameThread = apply("same-thread") final class Logger(name: String) extends play.api.LoggerLike { val logger = org.slf4j.LoggerFactory getLogger name def branch(childName: String) = new Logger(name = s"$name.$childName") } }
clarkerubber/lila
modules/common/src/main/log.scala
Scala
agpl-3.0
355
/* * Copyright 2001-2013 Artima, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.scalatest import org.scalatest.prop.Checkers import org.scalacheck._ import Arbitrary._ import Prop._ import org.scalatest.exceptions.TestFailedException import SharedHelpers._ import Matchers._ class ShouldStartWithRegexSpec extends Spec with Checkers with ReturnsNormallyThrowsAssertion { /* s should include substring t s should include regex t s should startWith substring t s should startWith regex t s should endWith substring t s should endWith regex t s should fullyMatch regex t */ object `The startWith regex syntax` { val decimal = """(-)?(\\d+)(\\.\\d*)?""" val decimalRegex = """(-)?(\\d+)(\\.\\d*)?""".r object `(when the regex is specified by a string)` { def `should do nothing if the string starts with substring that matched the regular expression specified as a string` { "1.78" should startWith regex ("1.7") "1.7" should startWith regex (decimal) "21.7" should startWith regex (decimal) "1.78" should startWith regex (decimal) "8x" should startWith regex (decimal) "1.x" should startWith regex (decimal) // The remaining are full matches, which should also work with "startWith" "1.7" should startWith regex ("1.7") "1.7" should startWith regex (decimal) "-1.8" should startWith regex (decimal) "8" should startWith regex (decimal) "1." should startWith regex (decimal) } def `should do nothing if the string starts with substring that matched the regular expression specified as a string and withGroup` { "abbc" should startWith regex ("a(b*)c" withGroup "bb") "aabbc" should startWith regex ("aa(b*)c" withGroup "bb") "abbcc" should startWith regex ("a(b*)cc" withGroup "bb") } def `should do nothing if the string starts with substring that matched the regular expression specified as a string and withGroups` { "abbcc" should startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) "aabbcc" should startWith regex ("aa(b*)(c*)" withGroups ("bb", "cc")) "abbccd" should startWith regex ("a(b*)(c*)d" withGroups ("bb", "cc")) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string when used with not` { "eight" should not { startWith regex (decimal) } "one.eight" should not { startWith regex (decimal) } "eight" should not startWith regex (decimal) "one.eight" should not startWith regex (decimal) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroup when used with not` { "abcdef" should not { startWith regex ("a(b*)c" withGroup "bb") } "abcdef" should not startWith regex ("a(b*)c" withGroup "bb") } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroups when used with not` { "abbcdef" should not { startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) } "abbcdef" should not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string when used in a logical-and expression` { "1.7b" should (startWith regex (decimal) and (startWith regex (decimal))) "1.7b" should ((startWith regex (decimal)) and (startWith regex (decimal))) "1.7b" should (startWith regex (decimal) and startWith regex (decimal)) "1.7" should (startWith regex (decimal) and (startWith regex (decimal))) "1.7" should ((startWith regex (decimal)) and (startWith regex (decimal))) "1.7" should (startWith regex (decimal) and startWith regex (decimal)) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroup when used in a logical-and expression` { "abbcdef" should (startWith regex ("a(b*)c" withGroup "bb") and (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should ((startWith regex ("a(b*)c" withGroup "bb")) and (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should (startWith regex ("a(b*)c" withGroup "bb") and startWith regex ("a(b*)c" withGroup "bb")) "abbcdef" should (startWith regex ("a(b*)c" withGroup "bb") and (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should ((startWith regex ("a(b*)c" withGroup "bb")) and (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should (startWith regex ("a(b*)c" withGroup "bb") and startWith regex ("a(b*)c" withGroup "bb")) "abbcdef" should (equal ("abbcdef") and (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should ((equal ("abbcdef")) and (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should (equal ("abbcdef") and startWith regex ("a(b*)c" withGroup "bb")) "abbcdef" should (equal ("abbcdef") and (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should ((equal ("abbcdef")) and (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should (equal ("abbcdef") and startWith regex ("a(b*)c" withGroup "bb")) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroups when used in a logical-and expression` { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should ((startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) and startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should ((startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) and startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) "abbccdef" should (equal ("abbccdef") and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should ((equal ("abbccdef")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should (equal ("abbccdef") and startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) "abbccdef" should (equal ("abbccdef") and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should ((equal ("abbccdef")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should (equal ("abbccdef") and startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string when used in a logical-or expression` { "1.7b" should (startWith regex ("hello") or (startWith regex (decimal))) "1.7b" should ((startWith regex ("hello")) or (startWith regex (decimal))) "1.7b" should (startWith regex ("hello") or startWith regex (decimal)) "1.7" should (startWith regex ("hello") or (startWith regex (decimal))) "1.7" should ((startWith regex ("hello")) or (startWith regex (decimal))) "1.7" should (startWith regex ("hello") or startWith regex (decimal)) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroup when used in a logical-or expression` { "abbcdef" should (startWith regex ("a(b*)c" withGroup "bbb") or (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should ((startWith regex ("a(b*)c" withGroup "bbb")) or (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should (startWith regex ("a(b*)c" withGroup "bbb") or startWith regex ("a(b*)c" withGroup "bb")) "abbcdef" should (startWith regex ("a(b*)c" withGroup "bbb") or (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should ((startWith regex ("a(b*)c" withGroup "bbb")) or (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should (startWith regex ("a(b*)c" withGroup "bbb") or startWith regex ("a(b*)c" withGroup "bb")) "abbcdef" should (equal ("abbbcdef") or (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should ((equal ("abbbcdef")) or (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should (equal ("abbbcdef") or startWith regex ("a(b*)c" withGroup "bb")) "abbcdef" should (equal ("abbbcdef") or (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should ((equal ("abbbcdef")) or (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should (equal ("abbbcdef") or startWith regex ("a(b*)c" withGroup "bb")) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroups when used in a logical-or expression` { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) or (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should ((startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) or (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) or startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) "abbccdef" should (equal ("abbcccdef") or (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should ((equal ("abbcccdef")) or (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should (equal ("abbcccdef") or startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string when used in a logical-and expression with not` { "fred" should (not (startWith regex ("bob")) and not (startWith regex (decimal))) "fred" should ((not startWith regex ("bob")) and (not startWith regex (decimal))) "fred" should (not startWith regex ("bob") and not startWith regex (decimal)) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroup when used in a logical-and expression with not` { "abbbcdef" should (not (startWith regex ("a(b*)c" withGroup "b")) and not (startWith regex ("a(b*)c" withGroup "bb"))) "abbbcdef" should ((not startWith regex ("a(b*)c" withGroup "b")) and (not startWith regex ("a(b*)c" withGroup "bb"))) "abbbcdef" should (not startWith regex ("a(b*)c" withGroup "b") and not startWith regex ("a(b*)c" withGroup "bb")) "abbbcdef" should (not (equal ("abcdef")) and not (startWith regex ("a(b*)c" withGroup "bb"))) "abbbcdef" should ((not equal ("abcdef")) and (not startWith regex ("a(b*)c" withGroup "bb"))) "abbbcdef" should (not equal ("abcdef") and not startWith regex ("a(b*)c" withGroup "bb")) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroups when used in a logical-and expression with not` { "abbccdef" should (not (startWith regex ("a(b*)(c*)" withGroups ("bb", "c"))) and not (startWith regex ("a(b*)(c*)" withGroups ("bb", "c")))) "abbccdef" should ((not startWith regex ("a(b*)(c*)" withGroups ("bb", "c"))) and (not startWith regex ("a(b*)(c*)" withGroups ("bb", "c")))) "abbccdef" should (not startWith regex ("a(b*)(c*)" withGroups ("bb", "c")) and not startWith regex ("a(b*)(c*)" withGroups ("bb", "c"))) "abbccdef" should (not (equal ("abbcdef")) and not (startWith regex ("a(b*)(c*)" withGroups ("bb", "c")))) "abbccdef" should ((not equal ("abbcdef")) and (not startWith regex ("a(b*)(c*)" withGroups ("bb", "c")))) "abbccdef" should (not equal ("abbcdef") and not startWith regex ("a(b*)(c*)" withGroups ("bb", "c"))) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string when used in a logical-or expression with not` { "fred" should (not (startWith regex ("fred")) or not (startWith regex (decimal))) "fred" should ((not startWith regex ("fred")) or (not startWith regex (decimal))) "fred" should (not startWith regex ("fred") or not startWith regex (decimal)) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroup when used in a logical-or expression with not` { "abbcdef" should (not (startWith regex ("a(b*)c" withGroup "bb")) or not (startWith regex ("a(b*)c" withGroup "bbb"))) "abbcdef" should ((not startWith regex ("a(b*)c" withGroup "bb")) or (not startWith regex ("a(b*)c" withGroup "bbb"))) "abbcdef" should (not startWith regex ("a(b*)c" withGroup "bb") or not startWith regex ("a(b*)c" withGroup "bbb")) "abbcdef" should (not (equal ("abbcdef")) or not (startWith regex ("a(b*)c" withGroup "bbb"))) "abbcdef" should ((not equal ("abbcdef")) or (not startWith regex ("a(b*)c" withGroup "bbb"))) "abbcdef" should (not equal ("abbcdef") or not startWith regex ("a(b*)c" withGroup "bbb")) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroups when used in a logical-or expression with not` { "abbccdef" should (not (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) or not (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) "abbccdef" should ((not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) or (not startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) "abbccdef" should (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) or not startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) "abbccdef" should (not (equal ("abbccdef")) or not (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) "abbccdef" should ((not equal ("abbccdef")) or (not startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) "abbccdef" should (not equal ("abbccdef") or not startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) } def `should throw TestFailedException if the string does not match substring that matched the regular expression specified as a string` { val caught1 = intercept[TestFailedException] { "1.7" should startWith regex ("1.78") } assert(caught1.getMessage === "\\"1.7\\" did not start with a substring that matched the regular expression 1.78") val caught2 = intercept[TestFailedException] { "1.7" should startWith regex ("21.7") } assert(caught2.getMessage === "\\"1.7\\" did not start with a substring that matched the regular expression 21.7") val caught3 = intercept[TestFailedException] { "-one.eight" should startWith regex (decimal) } assert(caught3.getMessage === "\\"-one.eight\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught6 = intercept[TestFailedException] { "eight" should startWith regex (decimal) } assert(caught6.getMessage === "\\"eight\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught7 = intercept[TestFailedException] { "one.8" should startWith regex (decimal) } assert(caught7.getMessage === "\\"one.8\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught8 = intercept[TestFailedException] { "onedoteight" should startWith regex (decimal) } assert(caught8.getMessage === "\\"onedoteight\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught9 = intercept[TestFailedException] { "***" should startWith regex (decimal) } assert(caught9.getMessage === "\\"***\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string does not match substring that matched the regular expression specified as a string and withGroup` { val caught1 = intercept[TestFailedException] { "abbcdef" should startWith regex ("a(b*)c" withGroup "b") } assert(caught1.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group b") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string does not match substring that matched the regular expression specified as a string and withGroups` { val caught1 = intercept[TestFailedException] { "abbccdef" should startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) } assert(caught1.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string does matches substring that matched the regular expression specified as a string when used with not` { val caught1 = intercept[TestFailedException] { "1.7" should not { startWith regex ("1.7") } } assert(caught1.getMessage === "\\"1.7\\" started with a substring that matched the regular expression 1.7") val caught2 = intercept[TestFailedException] { "1.7" should not { startWith regex (decimal) } } assert(caught2.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught3 = intercept[TestFailedException] { "-1.8" should not { startWith regex (decimal) } } assert(caught3.getMessage === "\\"-1.8\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught4 = intercept[TestFailedException] { "8" should not { startWith regex (decimal) } } assert(caught4.getMessage === "\\"8\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught5 = intercept[TestFailedException] { "1." should not { startWith regex (decimal) } } assert(caught5.getMessage === "\\"1.\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught11 = intercept[TestFailedException] { "1.7" should not startWith regex ("1.7") } assert(caught11.getMessage === "\\"1.7\\" started with a substring that matched the regular expression 1.7") val caught12 = intercept[TestFailedException] { "1.7" should not startWith regex (decimal) } assert(caught12.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught13 = intercept[TestFailedException] { "-1.8" should not startWith regex (decimal) } assert(caught13.getMessage === "\\"-1.8\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught14 = intercept[TestFailedException] { "8" should not startWith regex (decimal) } assert(caught14.getMessage === "\\"8\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught15 = intercept[TestFailedException] { "1." should not startWith regex (decimal) } assert(caught15.getMessage === "\\"1.\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") // The rest are non-exact matches val caught21 = intercept[TestFailedException] { "1.7a" should not { startWith regex ("1.7") } } assert(caught21.getMessage === "\\"1.7a\\" started with a substring that matched the regular expression 1.7") val caught22 = intercept[TestFailedException] { "1.7b" should not { startWith regex (decimal) } } assert(caught22.getMessage === "\\"1.7b\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught23 = intercept[TestFailedException] { "-1.8b" should not { startWith regex (decimal) } } assert(caught23.getMessage === "\\"-1.8b\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string does matches substring that matched the regular expression specified as a string and withGroup when used with not` { val caught1 = intercept[TestFailedException] { "abbcdef" should not { startWith regex ("a(b*)c" withGroup "bb") } } assert(caught1.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbcdef" should not startWith regex ("a(b*)c" withGroup "bb") } assert(caught2.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string does matches substring that matched the regular expression specified as a string and withGroups when used with not` { val caught1 = intercept[TestFailedException] { "abbccdef" should not { startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) } } assert(caught1.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbccdef" should not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) } assert(caught2.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "1.7" should (startWith regex (decimal) and (startWith regex ("1.8"))) } assert(caught1.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, but \\"1.7\\" did not start with a substring that matched the regular expression 1.8") val caught2 = intercept[TestFailedException] { "1.7" should ((startWith regex (decimal)) and (startWith regex ("1.8"))) } assert(caught2.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, but \\"1.7\\" did not start with a substring that matched the regular expression 1.8") val caught3 = intercept[TestFailedException] { "1.7" should (startWith regex (decimal) and startWith regex ("1.8")) } assert(caught3.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, but \\"1.7\\" did not start with a substring that matched the regular expression 1.8") // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "one.eight" should (startWith regex (decimal) and (startWith regex ("1.8"))) } assert(caught4.getMessage === "\\"one.eight\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught5 = intercept[TestFailedException] { "one.eight" should ((startWith regex (decimal)) and (startWith regex ("1.8"))) } assert(caught5.getMessage === "\\"one.eight\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught6 = intercept[TestFailedException] { "one.eight" should (startWith regex (decimal) and startWith regex ("1.8")) } assert(caught6.getMessage === "\\"one.eight\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string and withGroup when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "abbcdef" should (startWith regex ("a(b*)c" withGroup "bb") and (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught1.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb, but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbcdef" should ((startWith regex ("a(b*)c" withGroup "bb")) and (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught2.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb, but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbcdef" should (startWith regex ("a(b*)c" withGroup "bb") and startWith regex ("a(b*)c" withGroup "bbb")) } assert(caught3.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb, but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "abbcdef" should (startWith regex ("a(b*)c" withGroup "bbb") and (startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught4.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbcdef" should ((startWith regex ("a(b*)c" withGroup "bbb")) and (startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught5.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught5.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbcdef" should (startWith regex ("a(b*)c" withGroup "bbb") and startWith regex ("a(b*)c" withGroup "bb")) } assert(caught6.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught6.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abbcdef" should (equal ("abbcdef") and (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught7.getMessage === "\\"abbcdef\\" equaled \\"abbcdef\\", but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught7.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abbcdef" should ((equal ("abbcdef")) and (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught8.getMessage === "\\"abbcdef\\" equaled \\"abbcdef\\", but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught8.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "abbcdef" should (equal ("abbcdef") and startWith regex ("a(b*)c" withGroup "bbb")) } assert(caught9.getMessage === "\\"abbcdef\\" equaled \\"abbcdef\\", but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught9.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught10 = intercept[TestFailedException] { "abbcdef" should (equal ("abbbcdef") and (startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught10.getMessage === "\\"abb[]cdef\\" did not equal \\"abb[b]cdef\\"") assert(caught10.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "abbcdef" should ((equal ("abbbcdef")) and (startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught11.getMessage === "\\"abb[]cdef\\" did not equal \\"abb[b]cdef\\"") assert(caught11.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "abbcdef" should (equal ("abbbcdef") and startWith regex ("a(b*)c" withGroup "bb")) } assert(caught12.getMessage === "\\"abb[]cdef\\" did not equal \\"abb[b]cdef\\"") assert(caught12.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string and withGroups when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught1.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc, but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbccdef" should ((startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught2.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc, but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) and startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) } assert(caught3.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc, but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught4.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbccdef" should ((startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught5.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught5.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught6.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught6.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abbccdef" should (equal ("abbccdef") and (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught7.getMessage === "\\"abbccdef\\" equaled \\"abbccdef\\", but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught7.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abbccdef" should ((equal ("abbccdef")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught8.getMessage === "\\"abbccdef\\" equaled \\"abbccdef\\", but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught8.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "abbccdef" should (equal ("abbccdef") and startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) } assert(caught9.getMessage === "\\"abbccdef\\" equaled \\"abbccdef\\", but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught9.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught10 = intercept[TestFailedException] { "abbccdef" should (equal ("abbcccdef") and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught10.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\"") assert(caught10.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "abbccdef" should ((equal ("abbcccdef")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught11.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\"") assert(caught11.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "abbccdef" should (equal ("abbcccdef") and startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught12.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\"") assert(caught12.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "one.seven" should (startWith regex (decimal) or (startWith regex ("1.8"))) } assert(caught1.getMessage === "\\"one.seven\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"one.seven\\" did not start with a substring that matched the regular expression 1.8") val caught2 = intercept[TestFailedException] { "one.seven" should ((startWith regex (decimal)) or (startWith regex ("1.8"))) } assert(caught2.getMessage === "\\"one.seven\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"one.seven\\" did not start with a substring that matched the regular expression 1.8") val caught3 = intercept[TestFailedException] { "one.seven" should (startWith regex (decimal) or startWith regex ("1.8")) } assert(caught3.getMessage === "\\"one.seven\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"one.seven\\" did not start with a substring that matched the regular expression 1.8") } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string and withGroup when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "abbcdef" should (startWith regex ("a(b*)c" withGroup "b") or (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught1.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group b, and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbcdef" should ((startWith regex ("a(b*)c" withGroup "b")) or (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught2.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group b, and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbcdef" should (startWith regex ("a(b*)c" withGroup "b") or startWith regex ("a(b*)c" withGroup "bbb")) } assert(caught3.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group b, and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbcdef" should (equal ("abcdef") or (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught4.getMessage === "\\"ab[b]cdef\\" did not equal \\"ab[]cdef\\", and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbcdef" should ((equal ("abcdef")) or (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught5.getMessage === "\\"ab[b]cdef\\" did not equal \\"ab[]cdef\\", and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught5.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbcdef" should (equal ("abcdef") or startWith regex ("a(b*)c" withGroup "bbb")) } assert(caught6.getMessage === "\\"ab[b]cdef\\" did not equal \\"ab[]cdef\\", and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught6.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string and withGroups when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "c")) or (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught1.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group c at index 1, and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbccdef" should ((startWith regex ("a(b*)(c*)" withGroups ("bb", "c"))) or (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught2.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group c at index 1, and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "c")) or startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) } assert(caught3.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group c at index 1, and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbccdef" should (equal ("abbcdef") or (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught4.getMessage === "\\"abbc[c]def\\" did not equal \\"abbc[]def\\", and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbccdef" should ((equal ("abbcdef")) or (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught5.getMessage === "\\"abbc[c]def\\" did not equal \\"abbc[]def\\", and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught5.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbccdef" should (equal ("abbcdef") or startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) } assert(caught6.getMessage === "\\"abbc[c]def\\" did not equal \\"abbc[]def\\", and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught6.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not startWith regex ("1.8") and (not startWith regex (decimal))) } assert(caught1.getMessage === "\\"1.7\\" did not start with a substring that matched the regular expression 1.8, but \\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught2 = intercept[TestFailedException] { "1.7" should ((not startWith regex ("1.8")) and (not startWith regex (decimal))) } assert(caught2.getMessage === "\\"1.7\\" did not start with a substring that matched the regular expression 1.8, but \\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught3 = intercept[TestFailedException] { "1.7" should (not startWith regex ("1.8") and not startWith regex (decimal)) } assert(caught3.getMessage === "\\"1.7\\" did not start with a substring that matched the regular expression 1.8, but \\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught4 = intercept[TestFailedException] { "1.7a" should (not startWith regex ("1.8") and (not startWith regex (decimal))) } assert(caught4.getMessage === "\\"1.7a\\" did not start with a substring that matched the regular expression 1.8, but \\"1.7a\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught5 = intercept[TestFailedException] { "1.7" should ((not startWith regex ("1.8")) and (not startWith regex (decimal))) } assert(caught5.getMessage === "\\"1.7\\" did not start with a substring that matched the regular expression 1.8, but \\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string and withGroup when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "abbcdef" should (not startWith regex ("a(b*)c" withGroup "bbb") and (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught1.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb, but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbcdef" should ((not startWith regex ("a(b*)c" withGroup "bbb")) and (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught2.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb, but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbcdef" should (not startWith regex ("a(b*)c" withGroup "bbb") and not startWith regex ("a(b*)c" withGroup "bb")) } assert(caught3.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb, but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbcdef" should (not equal ("abbbcdef") and (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught4.getMessage === "\\"abb[]cdef\\" did not equal \\"abb[b]cdef\\", but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbcdef" should ((not equal ("abbbcdef")) and (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught5.getMessage === "\\"abb[]cdef\\" did not equal \\"abb[b]cdef\\", but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught5.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbcdef" should (not equal ("abbbcdef") and not startWith regex ("a(b*)c" withGroup "bb")) } assert(caught6.getMessage === "\\"abb[]cdef\\" did not equal \\"abb[b]cdef\\", but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught6.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string and withGroups when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "abbccdef" should (not startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught1.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1, but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbccdef" should ((not startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) and (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught2.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1, but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbccdef" should (not startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught3.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1, but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbccdef" should (not equal ("abbcccdef") and (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught4.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\", but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbccdef" should ((not equal ("abbcccdef")) and (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught5.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\", but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught5.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbccdef" should (not equal ("abbcccdef") and not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught6.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\", but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught6.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not startWith regex (decimal) or (not startWith regex ("1.7"))) } assert(caught1.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" started with a substring that matched the regular expression 1.7") val caught2 = intercept[TestFailedException] { "1.7" should ((not startWith regex (decimal)) or (not startWith regex ("1.7"))) } assert(caught2.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" started with a substring that matched the regular expression 1.7") val caught3 = intercept[TestFailedException] { "1.7" should (not startWith regex (decimal) or not startWith regex ("1.7")) } assert(caught3.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" started with a substring that matched the regular expression 1.7") val caught4 = intercept[TestFailedException] { "1.7" should (not (startWith regex (decimal)) or not (startWith regex ("1.7"))) } assert(caught4.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" started with a substring that matched the regular expression 1.7") val caught5 = intercept[TestFailedException] { "1.7a" should (not startWith regex (decimal) or (not startWith regex ("1.7"))) } assert(caught5.getMessage === "\\"1.7a\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7a\\" started with a substring that matched the regular expression 1.7") } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string and withGroup when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "abbcdef" should (not startWith regex ("a(b*)c" withGroup "bb") or (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught1.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb, and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbcdef" should ((not startWith regex ("a(b*)c" withGroup "bb")) or (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught2.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb, and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbcdef" should (not startWith regex ("a(b*)c" withGroup "bb") or not startWith regex ("a(b*)c" withGroup "bb")) } assert(caught3.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb, and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbcdef" should (not (startWith regex ("a(b*)c" withGroup "bb")) or not (startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught4.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb, and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbcdef" should (not equal ("abbcdef") or (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught5.getMessage === "\\"abbcdef\\" equaled \\"abbcdef\\", and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught5.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbcdef" should ((not equal ("abbcdef")) or (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught6.getMessage === "\\"abbcdef\\" equaled \\"abbcdef\\", and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught6.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abbcdef" should (not equal ("abbcdef") or not startWith regex ("a(b*)c" withGroup "bb")) } assert(caught7.getMessage === "\\"abbcdef\\" equaled \\"abbcdef\\", and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught7.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abbcdef" should (not (equal ("abbcdef")) or not (startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught8.getMessage === "\\"abbcdef\\" equaled \\"abbcdef\\", and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught8.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string and withGroups when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "abbccdef" should (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) or (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught1.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc, and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbccdef" should ((not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) or (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught2.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc, and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbccdef" should (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) or not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught3.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc, and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbccdef" should (not (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) or not (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught4.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc, and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbccdef" should (not equal ("abbccdef") or (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught5.getMessage === "\\"abbccdef\\" equaled \\"abbccdef\\", and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught5.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbccdef" should ((not equal ("abbccdef")) or (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught6.getMessage === "\\"abbccdef\\" equaled \\"abbccdef\\", and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught6.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abbccdef" should (not equal ("abbccdef") or not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught7.getMessage === "\\"abbccdef\\" equaled \\"abbccdef\\", and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught7.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abbccdef" should (not (equal ("abbccdef")) or not (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught8.getMessage === "\\"abbccdef\\" equaled \\"abbccdef\\", and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught8.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) } } object `(when the regex is specified by an actual Regex)` { def `should do nothing if the string starts with substring that matched the regular expression specified as a string` { "1.7" should startWith regex (decimalRegex) "21.7" should startWith regex (decimalRegex) "1.78" should startWith regex (decimalRegex) "8x" should startWith regex (decimalRegex) "1.x" should startWith regex (decimalRegex) // The remaining are full matches, which should also work with "startWith" "1.7" should startWith regex (decimalRegex) "-1.8" should startWith regex (decimalRegex) "8" should startWith regex (decimalRegex) "1." should startWith regex (decimalRegex) } def `should do nothing if the string starts with substring that matched the regular expression specified as a string withGroup` { "abbcdef" should startWith regex ("a(b*)c".r withGroup "bb") // full matches, which should also work with "startWith" "abbc" should startWith regex ("a(b*)c".r withGroup "bb") } def `should do nothing if the string starts with substring that matched the regular expression specified as a string withGroups` { "abbccdef" should startWith regex ("a(b*)(c*)".r withGroups ("bb", "cc")) // full matches, which should also work with "startWith" "abbcc" should startWith regex ("a(b*)(c*)".r withGroups ("bb", "cc")) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string when used with not` { "eight" should not { startWith regex (decimalRegex) } "one.eight" should not { startWith regex (decimalRegex) } "eight" should not startWith regex (decimalRegex) "one.eight" should not startWith regex (decimalRegex) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string withGroup when used with not` { "abbcdef" should not { startWith regex ("a(b*)c".r withGroup "bbb") } "abbcdef" should not startWith regex ("a(b*)c".r withGroup "bbb") } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string withGroups when used with not` { "abbccdef" should not { startWith regex ("a(b*)(c*)".r withGroups ("bb", "ccc")) } "abbccdef" should not startWith regex ("a(b*)(c*)".r withGroups ("bb", "ccc")) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string when used in a logical-and expression` { "1.7b" should (startWith regex (decimalRegex) and (startWith regex (decimalRegex))) "1.7b" should ((startWith regex (decimalRegex)) and (startWith regex (decimalRegex))) "1.7b" should (startWith regex (decimalRegex) and startWith regex (decimalRegex)) "1.7" should (startWith regex (decimalRegex) and (startWith regex (decimalRegex))) "1.7" should ((startWith regex (decimalRegex)) and (startWith regex (decimalRegex))) "1.7" should (startWith regex (decimalRegex) and startWith regex (decimalRegex)) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string withGroup when used in a logical-and expression` { "abbcdef" should (startWith regex ("a(b*)c" withGroup "bb") and (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should ((startWith regex ("a(b*)c" withGroup "bb")) and (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should (startWith regex ("a(b*)c" withGroup "bb") and startWith regex ("a(b*)c" withGroup "bb")) "abbc" should (startWith regex ("a(b*)c" withGroup "bb") and (startWith regex ("a(b*)c" withGroup "bb"))) "abbc" should ((startWith regex ("a(b*)c" withGroup "bb")) and (startWith regex ("a(b*)c" withGroup "bb"))) "abbc" should (startWith regex ("a(b*)c" withGroup "bb") and startWith regex ("a(b*)c" withGroup "bb")) "abbcdef" should (equal ("abbcdef") and (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should ((equal ("abbcdef")) and (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should (equal ("abbcdef") and startWith regex ("a(b*)c" withGroup "bb")) "abbc" should (equal ("abbc") and (startWith regex ("a(b*)c" withGroup "bb"))) "abbc" should ((equal ("abbc")) and (startWith regex ("a(b*)c" withGroup "bb"))) "abbc" should (equal ("abbc") and startWith regex ("a(b*)c" withGroup "bb")) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string withGroups when used in a logical-and expression` { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should ((startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) and startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) "abbcc" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should ((startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) and startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) "abbccdef" should (equal ("abbccdef") and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should ((equal ("abbccdef")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should (equal ("abbccdef") and startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) "abbcc" should (equal ("abbcc") and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should ((equal ("abbcc")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should (equal ("abbcc") and startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string when used in a logical-or expression` { "1.7b" should (startWith regex ("hello") or (startWith regex (decimalRegex))) "1.7b" should ((startWith regex ("hello")) or (startWith regex (decimalRegex))) "1.7b" should (startWith regex ("hello") or startWith regex (decimalRegex)) "1.7" should (startWith regex ("hello") or (startWith regex (decimalRegex))) "1.7" should ((startWith regex ("hello")) or (startWith regex (decimalRegex))) "1.7" should (startWith regex ("hello") or startWith regex (decimalRegex)) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroup when used in a logical-or expression` { "abbcdef" should (startWith regex ("a(b*)c" withGroup "bbb") or (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should ((startWith regex ("a(b*)c" withGroup "bbb")) or (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should (startWith regex ("a(b*)c" withGroup "bbb") or startWith regex ("a(b*)c" withGroup "bb")) "abbc" should (startWith regex ("a(b*)c" withGroup "bbb") or (startWith regex ("a(b*)c" withGroup "bb"))) "abbc" should ((startWith regex ("a(b*)c" withGroup "bbb")) or (startWith regex ("a(b*)c" withGroup "bb"))) "abbc" should (startWith regex ("a(b*)c" withGroup "bbb") or startWith regex ("a(b*)c" withGroup "bb")) "abbcdef" should (equal ("abbbcdef") or (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should ((equal ("abbbcdef")) or (startWith regex ("a(b*)c" withGroup "bb"))) "abbcdef" should (equal ("abbbcdef") or startWith regex ("a(b*)c" withGroup "bb")) "abbc" should (equal ("abbbc") or (startWith regex ("a(b*)c" withGroup "bb"))) "abbc" should ((equal ("abbbc")) or (startWith regex ("a(b*)c" withGroup "bb"))) "abbc" should (equal ("abbbc") or startWith regex ("a(b*)c" withGroup "bb")) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroups when used in a logical-or expression` { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) or (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should ((startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) or (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) or startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) "abbcc" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) or (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should ((startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) or (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) or startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) "abbccdef" should (equal ("abbcccdef") or (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should ((equal ("abbcccdef")) or (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbccdef" should (equal ("abbcccdef") or startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) "abbcc" should (equal ("abbccc") or (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should ((equal ("abbccc")) or (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) "abbcc" should (equal ("abbccc") or startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string when used in a logical-and expression with not` { "fred" should (not (startWith regex ("bob")) and not (startWith regex (decimalRegex))) "fred" should ((not startWith regex ("bob")) and (not startWith regex (decimalRegex))) "fred" should (not startWith regex ("bob") and not startWith regex (decimalRegex)) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroup when used in a logical-and expression with not` { "abbcdef" should (not (startWith regex ("a(b*)c" withGroup "bob")) and not (startWith regex ("a(b*)c" withGroup "bob"))) "abbcdef" should ((not startWith regex ("a(b*)c" withGroup "bob")) and (not startWith regex ("a(b*)c" withGroup "bob"))) "abbcdef" should (not startWith regex ("a(b*)c" withGroup "bob") and not startWith regex ("a(b*)c" withGroup "bob")) "abbcdef" should (not (equal ("abobcdef")) and not (startWith regex ("a(b*)c" withGroup "bob"))) "abbcdef" should ((not equal ("abobcdef")) and (not startWith regex ("a(b*)c" withGroup "bob"))) "abbcdef" should (not equal ("abobcdef") and not startWith regex ("a(b*)c" withGroup "bob")) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroups when used in a logical-and expression with not` { "abbccdef" should (not (startWith regex ("a(b*)(c*)" withGroups ("bob", "cat"))) and not (startWith regex ("a(b*)(c*)" withGroups ("bob", "cat")))) "abbccdef" should ((not startWith regex ("a(b*)(c*)" withGroups ("bob", "cat"))) and (not startWith regex ("a(b*)(c*)" withGroups ("bob", "cat")))) "abbccdef" should (not startWith regex ("a(b*)(c*)" withGroups ("bob", "cat")) and not startWith regex ("a(b*)(c*)" withGroups ("bob", "cat"))) "abbccdef" should (not (equal ("abobcatdef")) and not (startWith regex ("a(b*)(c*)" withGroups ("bob", "cat")))) "abbccdef" should ((not equal ("abobcatdef")) and (not startWith regex ("a(b*)(c*)" withGroups ("bob", "cat")))) "abbccdef" should (not equal ("abobcatdef") and not startWith regex ("a(b*)(c*)" withGroups ("bob", "cat"))) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string when used in a logical-or expression with not` { "fred" should (not (startWith regex ("fred")) or not (startWith regex (decimalRegex))) "fred" should ((not startWith regex ("fred")) or (not startWith regex (decimalRegex))) "fred" should (not startWith regex ("fred") or not startWith regex (decimalRegex)) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroup when used in a logical-or expression with not` { "abbcdef" should (not (startWith regex ("a(b*)c" withGroup "bb")) or not (startWith regex ("a(b*)c" withGroup "bbb"))) "abbcdef" should ((not startWith regex ("a(b*)c" withGroup "bb")) or (not startWith regex ("a(b*)c" withGroup "bbb"))) "abbcdef" should (not startWith regex ("a(b*)c" withGroup "bb") or not startWith regex ("a(b*)c" withGroup "bbb")) "abbcdef" should (not (equal ("abbcdef")) or not (startWith regex ("a(b*)c" withGroup "bbb"))) "abbcdef" should ((not equal ("abbcdef")) or (not startWith regex ("a(b*)c" withGroup "bbb"))) "abbcdef" should (not equal ("abbcdef") or not startWith regex ("a(b*)c" withGroup "bbb")) } def `should do nothing if the string does not start with a substring that matched the regular expression specified as a string and withGroups when used in a logical-or expression with not` { "abbccdef" should (not (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) or not (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) "abbccdef" should ((not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) or (not startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) "abbccdef" should (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) or not startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) "abbccdef" should (not (equal ("abbccdef")) or not (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) "abbccdef" should ((not equal ("abbccdef")) or (not startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) "abbccdef" should (not equal ("abbccdef") or not startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) } def `should throw TestFailedException if the string does not match substring that matched the regular expression specified as a string` { val caught1 = intercept[TestFailedException] { "1.7" should startWith regex ("1.78") } assert(caught1.getMessage === "\\"1.7\\" did not start with a substring that matched the regular expression 1.78") val caught2 = intercept[TestFailedException] { "1.7" should startWith regex ("21.7") } assert(caught2.getMessage === "\\"1.7\\" did not start with a substring that matched the regular expression 21.7") val caught3 = intercept[TestFailedException] { "-one.eight" should startWith regex (decimalRegex) } assert(caught3.getMessage === "\\"-one.eight\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught6 = intercept[TestFailedException] { "eight" should startWith regex (decimalRegex) } assert(caught6.getMessage === "\\"eight\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught7 = intercept[TestFailedException] { "one.8" should startWith regex (decimalRegex) } assert(caught7.getMessage === "\\"one.8\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught8 = intercept[TestFailedException] { "onedoteight" should startWith regex (decimalRegex) } assert(caught8.getMessage === "\\"onedoteight\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught9 = intercept[TestFailedException] { "***" should startWith regex (decimalRegex) } assert(caught9.getMessage === "\\"***\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string does not match substring that matched the regular expression specified as a string and withGroup` { val caught1 = intercept[TestFailedException] { "abbcdef" should startWith regex ("a(b*)c" withGroup "bbb") } assert(caught1.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbcdef" should startWith regex ("a(b*)c".r withGroup "bbb") } assert(caught2.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string does not match substring that matched the regular expression specified as a string and withGroups` { val caught1 = intercept[TestFailedException] { "abbccdef" should startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) } assert(caught1.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbccdef" should startWith regex ("a(b*)(c*)".r withGroups ("bb", "ccc")) } assert(caught2.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string does matches substring that matched the regular expression specified as a string when used with not` { val caught1 = intercept[TestFailedException] { "1.7" should not { startWith regex ("1.7") } } assert(caught1.getMessage === "\\"1.7\\" started with a substring that matched the regular expression 1.7") val caught2 = intercept[TestFailedException] { "1.7" should not { startWith regex (decimalRegex) } } assert(caught2.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught3 = intercept[TestFailedException] { "-1.8" should not { startWith regex (decimalRegex) } } assert(caught3.getMessage === "\\"-1.8\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught4 = intercept[TestFailedException] { "8" should not { startWith regex (decimalRegex) } } assert(caught4.getMessage === "\\"8\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught5 = intercept[TestFailedException] { "1." should not { startWith regex (decimalRegex) } } assert(caught5.getMessage === "\\"1.\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught11 = intercept[TestFailedException] { "1.7" should not startWith regex ("1.7") } assert(caught11.getMessage === "\\"1.7\\" started with a substring that matched the regular expression 1.7") val caught12 = intercept[TestFailedException] { "1.7" should not startWith regex (decimalRegex) } assert(caught12.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught13 = intercept[TestFailedException] { "-1.8" should not startWith regex (decimalRegex) } assert(caught13.getMessage === "\\"-1.8\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught14 = intercept[TestFailedException] { "8" should not startWith regex (decimalRegex) } assert(caught14.getMessage === "\\"8\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught15 = intercept[TestFailedException] { "1." should not startWith regex (decimalRegex) } assert(caught15.getMessage === "\\"1.\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") // The rest are non-exact matches val caught21 = intercept[TestFailedException] { "1.7a" should not { startWith regex ("1.7") } } assert(caught21.getMessage === "\\"1.7a\\" started with a substring that matched the regular expression 1.7") val caught22 = intercept[TestFailedException] { "1.7b" should not { startWith regex (decimalRegex) } } assert(caught22.getMessage === "\\"1.7b\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught23 = intercept[TestFailedException] { "-1.8b" should not { startWith regex (decimalRegex) } } assert(caught23.getMessage === "\\"-1.8b\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string does matches substring that matched the regular expression specified as a string and withGroup when used with not` { val caught1 = intercept[TestFailedException] { "abbcdef" should not { startWith regex ("a(b*)c" withGroup "bb") } } assert(caught1.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbcdef" should not { startWith regex ("a(b*)c".r withGroup "bb") } } assert(caught2.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbcdef" should not startWith regex ("a(b*)c" withGroup "bb") } assert(caught3.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbcdef" should not startWith regex ("a(b*)c".r withGroup "bb") } assert(caught4.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string does matches substring that matched the regular expression specified as a string and withGroups when used with not` { val caught1 = intercept[TestFailedException] { "abbccdef" should not { startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) } } assert(caught1.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbccdef" should not { startWith regex ("a(b*)(c*)".r withGroups ("bb", "cc")) } } assert(caught2.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbccdef" should not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) } assert(caught3.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbccdef" should not startWith regex ("a(b*)(c*)".r withGroups ("bb", "cc")) } assert(caught4.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "1.7" should (startWith regex (decimalRegex) and (startWith regex ("1.8"))) } assert(caught1.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, but \\"1.7\\" did not start with a substring that matched the regular expression 1.8") val caught2 = intercept[TestFailedException] { "1.7" should ((startWith regex (decimalRegex)) and (startWith regex ("1.8"))) } assert(caught2.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, but \\"1.7\\" did not start with a substring that matched the regular expression 1.8") val caught3 = intercept[TestFailedException] { "1.7" should (startWith regex (decimalRegex) and startWith regex ("1.8")) } assert(caught3.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, but \\"1.7\\" did not start with a substring that matched the regular expression 1.8") // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "one.eight" should (startWith regex (decimalRegex) and (startWith regex ("1.8"))) } assert(caught4.getMessage === "\\"one.eight\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught5 = intercept[TestFailedException] { "one.eight" should ((startWith regex (decimalRegex)) and (startWith regex ("1.8"))) } assert(caught5.getMessage === "\\"one.eight\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught6 = intercept[TestFailedException] { "one.eight" should (startWith regex (decimalRegex) and startWith regex ("1.8")) } assert(caught6.getMessage === "\\"one.eight\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string and withGroup when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "abbcdef" should (startWith regex ("a(b*)c" withGroup "bb") and (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught1.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb, but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbcdef" should ((startWith regex ("a(b*)c" withGroup "bb")) and (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught2.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb, but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbcdef" should (startWith regex ("a(b*)c" withGroup "bb") and startWith regex ("a(b*)c" withGroup "bbb")) } assert(caught3.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb, but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught4.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbccdef" should ((startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught5.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught5.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught6.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught6.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abbcdef" should (equal ("abbcdef") and (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught7.getMessage === "\\"abbcdef\\" equaled \\"abbcdef\\", but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught7.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abbcdef" should ((equal ("abbcdef")) and (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught8.getMessage === "\\"abbcdef\\" equaled \\"abbcdef\\", but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught8.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught9 = intercept[TestFailedException] { "abbcdef" should (equal ("abbcdef") and startWith regex ("a(b*)c" withGroup "bbb")) } assert(caught9.getMessage === "\\"abbcdef\\" equaled \\"abbcdef\\", but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught9.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught9.failedCodeLineNumber === Some(thisLineNumber - 4)) // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught10 = intercept[TestFailedException] { "abbccdef" should (equal ("abbcccdef") and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught10.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\"") assert(caught10.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught10.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught11 = intercept[TestFailedException] { "abbccdef" should ((equal ("abbcccdef")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught11.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\"") assert(caught11.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught11.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught12 = intercept[TestFailedException] { "abbccdef" should (equal ("abbcccdef") and startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught12.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\"") assert(caught12.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught12.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string and withGroups when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught1.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc, but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") val caught2 = intercept[TestFailedException] { "abbccdef" should ((startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught2.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc, but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") val caught3 = intercept[TestFailedException] { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) and startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) } assert(caught3.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc, but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught4.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") val caught5 = intercept[TestFailedException] { "abbccdef" should ((startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught5.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") val caught6 = intercept[TestFailedException] { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught6.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") val caught7 = intercept[TestFailedException] { "abbccdef" should (equal ("abbccdef") and (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught7.getMessage === "\\"abbccdef\\" equaled \\"abbccdef\\", but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") val caught8 = intercept[TestFailedException] { "abbccdef" should ((equal ("abbccdef")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught8.getMessage === "\\"abbccdef\\" equaled \\"abbccdef\\", but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") val caught9 = intercept[TestFailedException] { "abbccdef" should (equal ("abbccdef") and startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) } assert(caught9.getMessage === "\\"abbccdef\\" equaled \\"abbccdef\\", but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught10 = intercept[TestFailedException] { "abbccdef" should (equal ("abbcccdef") and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught10.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\"") val caught11 = intercept[TestFailedException] { "abbccdef" should ((equal ("abbcccdef")) and (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught11.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\"") val caught12 = intercept[TestFailedException] { "abbccdef" should (equal ("abbcccdef") and startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught12.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\"") } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "one.seven" should (startWith regex (decimalRegex) or (startWith regex ("1.8"))) } assert(caught1.getMessage === "\\"one.seven\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"one.seven\\" did not start with a substring that matched the regular expression 1.8") val caught2 = intercept[TestFailedException] { "one.seven" should ((startWith regex (decimalRegex)) or (startWith regex ("1.8"))) } assert(caught2.getMessage === "\\"one.seven\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"one.seven\\" did not start with a substring that matched the regular expression 1.8") val caught3 = intercept[TestFailedException] { "one.seven" should (startWith regex (decimalRegex) or startWith regex ("1.8")) } assert(caught3.getMessage === "\\"one.seven\\" did not start with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"one.seven\\" did not start with a substring that matched the regular expression 1.8") } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string and withGroup when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "abbcdef" should (startWith regex ("a(b*)c" withGroup "bbb") or (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught1.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb, and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbcdef" should ((startWith regex ("a(b*)c" withGroup "bbb")) or (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught2.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb, and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbcdef" should (startWith regex ("a(b*)c" withGroup "bbb") or startWith regex ("a(b*)c" withGroup "bbb")) } assert(caught3.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb, and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbcdef" should (equal ("abbbcdef") or (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught4.getMessage === "\\"abb[]cdef\\" did not equal \\"abb[b]cdef\\", and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbcdef" should ((equal ("abbbcdef")) or (startWith regex ("a(b*)c" withGroup "bbb"))) } assert(caught5.getMessage === "\\"abb[]cdef\\" did not equal \\"abb[b]cdef\\", and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught5.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbcdef" should (equal ("abbbcdef") or startWith regex ("a(b*)c" withGroup "bbb")) } assert(caught6.getMessage === "\\"abb[]cdef\\" did not equal \\"abb[b]cdef\\", and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb") assert(caught6.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string and withGroups when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) or (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught1.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1, and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbccdef" should ((startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) or (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught2.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1, and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbccdef" should (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) or startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) } assert(caught3.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1, and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbccdef" should (equal ("abbcccdef") or (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught4.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\", and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbccdef" should ((equal ("abbcccdef")) or (startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")))) } assert(caught5.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\", and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught5.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbccdef" should (equal ("abbcccdef") or startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) } assert(caught6.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\", and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1") assert(caught6.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not startWith regex ("1.8") and (not startWith regex (decimalRegex))) } assert(caught1.getMessage === "\\"1.7\\" did not start with a substring that matched the regular expression 1.8, but \\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught2 = intercept[TestFailedException] { "1.7" should ((not startWith regex ("1.8")) and (not startWith regex (decimalRegex))) } assert(caught2.getMessage === "\\"1.7\\" did not start with a substring that matched the regular expression 1.8, but \\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught3 = intercept[TestFailedException] { "1.7" should (not startWith regex ("1.8") and not startWith regex (decimalRegex)) } assert(caught3.getMessage === "\\"1.7\\" did not start with a substring that matched the regular expression 1.8, but \\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught4 = intercept[TestFailedException] { "1.7a" should (not startWith regex ("1.8") and (not startWith regex (decimalRegex))) } assert(caught4.getMessage === "\\"1.7a\\" did not start with a substring that matched the regular expression 1.8, but \\"1.7a\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught5 = intercept[TestFailedException] { "1.7" should ((not startWith regex ("1.8")) and (not startWith regex (decimalRegex))) } assert(caught5.getMessage === "\\"1.7\\" did not start with a substring that matched the regular expression 1.8, but \\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string withGroup when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "abbcdef" should (not startWith regex ("a(b*)c" withGroup "bbb") and (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught1.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb, but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbcdef" should ((not startWith regex ("a(b*)c" withGroup "bbb")) and (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught2.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb, but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbcdef" should (not startWith regex ("a(b*)c" withGroup "bbb") and not startWith regex ("a(b*)c" withGroup "bb")) } assert(caught3.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c, but \\"bb\\" did not match group bbb, but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbcdef" should (not equal ("abbbcdef") and (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught4.getMessage === "\\"abb[]cdef\\" did not equal \\"abb[b]cdef\\", but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbcdef" should ((not equal ("abbbcdef")) and (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught5.getMessage === "\\"abb[]cdef\\" did not equal \\"abb[b]cdef\\", but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught5.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbcdef" should (not equal ("abbbcdef") and not startWith regex ("a(b*)c" withGroup "bb")) } assert(caught6.getMessage === "\\"abb[]cdef\\" did not equal \\"abb[b]cdef\\", but \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught6.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string withGroups when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "abbccdef" should (not startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught1.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1, but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbccdef" should ((not startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc"))) and (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught2.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1, but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbccdef" should (not startWith regex ("a(b*)(c*)" withGroups ("bb", "ccc")) and not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught3.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*), but \\"cc\\" did not match group ccc at index 1, but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbccdef" should (not equal ("abbcccdef") and (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught4.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\", but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbccdef" should ((not equal ("abbcccdef")) and (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught5.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\", but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught5.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbccdef" should (not equal ("abbcccdef") and not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught6.getMessage === "\\"abbcc[]def\\" did not equal \\"abbcc[c]def\\", but \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught6.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not startWith regex (decimalRegex) or (not startWith regex ("1.7"))) } assert(caught1.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" started with a substring that matched the regular expression 1.7") val caught2 = intercept[TestFailedException] { "1.7" should ((not startWith regex (decimalRegex)) or (not startWith regex ("1.7"))) } assert(caught2.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" started with a substring that matched the regular expression 1.7") val caught3 = intercept[TestFailedException] { "1.7" should (not startWith regex (decimalRegex) or not startWith regex ("1.7")) } assert(caught3.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" started with a substring that matched the regular expression 1.7") val caught4 = intercept[TestFailedException] { "1.7" should (not (startWith regex (decimalRegex)) or not (startWith regex ("1.7"))) } assert(caught4.getMessage === "\\"1.7\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" started with a substring that matched the regular expression 1.7") val caught5 = intercept[TestFailedException] { "1.7a" should (not startWith regex (decimalRegex) or (not startWith regex ("1.7"))) } assert(caught5.getMessage === "\\"1.7a\\" started with a substring that matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7a\\" started with a substring that matched the regular expression 1.7") } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string and withGroup when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "abbcdef" should (not startWith regex ("a(b*)c" withGroup "bb") or (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught1.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb, and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbcdef" should ((not startWith regex ("a(b*)c" withGroup "bb")) or (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught2.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb, and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbcdef" should (not startWith regex ("a(b*)c" withGroup "bb") or not startWith regex ("a(b*)c" withGroup "bb")) } assert(caught3.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb, and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbcdef" should (not (startWith regex ("a(b*)c" withGroup "bb")) or not (startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught4.getMessage === "\\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb, and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbcdef" should (not equal ("abbcdef") or (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught5.getMessage === "\\"abbcdef\\" equaled \\"abbcdef\\", and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught5.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbcdef" should ((not equal ("abbcdef")) or (not startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught6.getMessage === "\\"abbcdef\\" equaled \\"abbcdef\\", and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught6.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abbcdef" should (not equal ("abbcdef") or not startWith regex ("a(b*)c" withGroup "bb")) } assert(caught7.getMessage === "\\"abbcdef\\" equaled \\"abbcdef\\", and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught7.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abbcdef" should (not (equal ("abbcdef")) or not (startWith regex ("a(b*)c" withGroup "bb"))) } assert(caught8.getMessage === "\\"abbcdef\\" equaled \\"abbcdef\\", and \\"abbcdef\\" started with a substring that matched the regular expression a(b*)c and group bb") assert(caught8.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) } def `should throw TestFailedException if the string starts with substring that matched the regular expression specified as a string and withGroups when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "abbccdef" should (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) or (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught1.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc, and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught1.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught2 = intercept[TestFailedException] { "abbccdef" should ((not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) or (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught2.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc, and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught2.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught3 = intercept[TestFailedException] { "abbccdef" should (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")) or not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught3.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc, and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught3.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught4 = intercept[TestFailedException] { "abbccdef" should (not (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) or not (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught4.getMessage === "\\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc, and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught4.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught5 = intercept[TestFailedException] { "abbccdef" should (not equal ("abbccdef") or (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught5.getMessage === "\\"abbccdef\\" equaled \\"abbccdef\\", and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught5.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught6 = intercept[TestFailedException] { "abbccdef" should ((not equal ("abbccdef")) or (not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught6.getMessage === "\\"abbccdef\\" equaled \\"abbccdef\\", and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught6.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught7 = intercept[TestFailedException] { "abbccdef" should (not equal ("abbccdef") or not startWith regex ("a(b*)(c*)" withGroups ("bb", "cc"))) } assert(caught7.getMessage === "\\"abbccdef\\" equaled \\"abbccdef\\", and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught7.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught7.failedCodeLineNumber === Some(thisLineNumber - 4)) val caught8 = intercept[TestFailedException] { "abbccdef" should (not (equal ("abbccdef")) or not (startWith regex ("a(b*)(c*)" withGroups ("bb", "cc")))) } assert(caught8.getMessage === "\\"abbccdef\\" equaled \\"abbccdef\\", and \\"abbccdef\\" started with a substring that matched the regular expression a(b*)(c*) and group bb, cc") assert(caught8.failedCodeFileName === Some("ShouldStartWithRegexSpec.scala")) assert(caught8.failedCodeLineNumber === Some(thisLineNumber - 4)) } } } }
travisbrown/scalatest
src/test/scala/org/scalatest/ShouldStartWithRegexSpec.scala
Scala
apache-2.0
140,978
/* * LambdaCalculusTest.scala */ package at.logic.gapt.expr import org.specs2.mutable._ import scala.collection.immutable.{ HashSet, HashMap } import scala.math.signum class LambdaCalculusTest extends Specification { "TypedLambdaCalculus" should { "make implicit conversion from String to Name" in { ( Var( "p", Ti ) ) must beEqualTo( Var( "p", Ti ) ) } "create N-ary abstractions (AbsN) correctly" in { val v1 = Var( "x", Ti ) val v2 = Var( "y", Ti ) val f = Var( "f", Ti -> ( Ti -> To ) ) ( Abs( v1 :: v2 :: Nil, f ) match { case Abs( v1, Abs( v2, f ) ) => true case _ => false } ) must beEqualTo( true ) } "create N-ary applications (AppN) correctly" in { val v1 = Var( "x", Ti ) val v2 = Var( "y", Ti ) val f = Var( "f", Ti -> ( Ti -> To ) ) ( App( f, List( v1, v2 ) ) match { case App( App( f, v1 ), v2 ) => true case _ => false } ) must beEqualTo( true ) } } "Equality" should { "distinguish variables with same name but different type" in { val xi = Var( "x", Ti ) val xii = Var( "x", Ti -> Ti ) ( xi ) must not be equalTo( xii ) ( xi.syntaxEquals( xii ) ) must beEqualTo( false ) } "distinguish the constant x from the variable x" in { val x_const = Const( "x", Ti ) val x_var = Var( "x", Ti ) ( x_const ) must not be equalTo( x_var ) ( x_const.syntaxEquals( x_var ) ) must beEqualTo( false ) } "equate variables with same name (but different symbols)" in { val v = Var( "v", Ti ) val v0 = Var( "v0", Ti ) val v_renamed = rename( v, List( v ) ) v_renamed must beEqualTo( v0 ) ( v_renamed.syntaxEquals( v0 ) ) must beEqualTo( true ) } "work correctly for alpha conversion" in { val a0 = Abs( Var( "x", Ti -> Ti ), App( Var( "x", Ti -> Ti ), Var( "y", Ti ) ) ) val b0 = Abs( Var( "x", Ti -> Ti ), App( Var( "x", Ti -> Ti ), Var( "y", Ti ) ) ) "- (\\\\x.xy) = (\\\\x.xy)" in { ( a0 ) must beEqualTo( b0 ) ( a0.syntaxEquals( b0 ) ) must beEqualTo( true ) } val a1 = Abs( Var( "y", Ti ), App( Var( "x", Ti -> Ti ), Var( "y", Ti ) ) ) val b1 = Abs( Var( "z", Ti ), App( Var( "x", Ti -> Ti ), Var( "z", Ti ) ) ) "- (\\\\y.xy) = (\\\\z.xz)" in { ( a1 ) must beEqualTo( b1 ) ( a1.syntaxEquals( b1 ) ) must beEqualTo( false ) } val a2 = Abs( Var( "y", Ti ), a1 ) val b2 = Abs( Var( "w", Ti ), a1 ) "- (\\\\y.\\\\y.xy) = (\\\\w.\\\\y.xy)" in { ( a2 ) must beEqualTo( b2 ) ( a2.syntaxEquals( b2 ) ) must beEqualTo( false ) } val a3 = Abs( Var( "y", Ti ), App( Abs( Var( "y", Ti ), Var( "x", Ti ) ), Var( "y", Ti ) ) ) val b3 = Abs( Var( "w", Ti ), App( Abs( Var( "y", Ti ), Var( "x", Ti ) ), Var( "w", Ti ) ) ) "- (\\\\y.(\\\\y.x)y) = (\\\\w.(\\\\y.x)w)" in { ( a3 ) must beEqualTo( b3 ) ( a3.syntaxEquals( b3 ) ) must beEqualTo( false ) } val a4 = Abs( Var( "y", Ti ), App( Abs( Var( "y", Ti ), Var( "x", Ti ) ), Var( "y", Ti ) ) ) val b4 = Abs( Var( "y", Ti ), App( Abs( Var( "y", Ti ), Var( "x", Ti ) ), Var( "w", Ti ) ) ) "- (\\\\y.(\\\\y.x)y) != (\\\\y.(\\\\y.x)w)" in { ( a4 ) must not be equalTo( b4 ) ( a4.syntaxEquals( b4 ) ) must beEqualTo( false ) } val a5 = Abs( Var( "y", Ti ), App( Abs( Var( "y", Ti ), Var( "y", Ti ) ), Var( "y", Ti ) ) ) val b5 = Abs( Var( "y", Ti ), App( Abs( Var( "w", Ti ), Var( "w", Ti ) ), Var( "y", Ti ) ) ) "- (\\\\y.(\\\\y.y)y) = (\\\\y.(\\\\w.w)y)" in { ( a5 ) must beEqualTo( b5 ) ( a5.syntaxEquals( b5 ) ) must beEqualTo( false ) } val a6 = Abs( Var( "y", Ti ), App( Abs( Var( "y", Ti ), Var( "y", Ti ) ), Var( "y", Ti ) ) ) val b6 = Abs( Var( "y", Ti ), App( Abs( Var( "w", Ti ), Var( "y", Ti ) ), Var( "x", Ti ) ) ) "- (\\\\y.(\\\\y.y)y) != (\\\\y.(\\\\w.y)y)" in { ( a6 ) must not be equalTo( b6 ) ( a6.syntaxEquals( b6 ) ) must beEqualTo( false ) } "\\\\x y z. f y != \\\\z x y. f z" in { val x = Var( "x", Ti ) val y = Var( "y", Ti ) val z = Var( "z", Ti ) val f = Const( "f", Ti -> Ti ) val a = Abs( x, Abs( y, Abs( z, App( f, y ) ) ) ) val b = Abs( z, Abs( x, Abs( y, App( f, z ) ) ) ) a must_!= b b must_!= a } "\\\\y. x != \\\\x. x" in { val x = Var( "x", Ti ) val y = Var( "y", Ti ) Abs( y, x ) must_!= Abs( x, x ) Abs( x, x ) must_!= Abs( y, x ) } "\\\\y x.x = \\\\x x.x" in { val x = Var( "x", Ti ) val y = Var( "y", Ti ) val a = Abs( y, Abs( x, x ) ) val b = Abs( x, Abs( x, x ) ) ( a == b ) must beTrue } "\\\\x y.x = \\\\x x.x" in { val x = Var( "x", Ti ) val y = Var( "y", Ti ) val a = Abs( x, Abs( y, x ) ) val b = Abs( x, Abs( x, x ) ) ( a == b ) must beFalse } } } "Hash Codes" should { "be equal for alpha equal terms" in { val t1 = App( Const( "P", Ti -> To ), Var( "x", Ti ) ) val t2 = App( Const( "P", Ti -> To ), Var( "y", Ti ) ) val t3 = Abs( Var( "x", Ti ), t1 ) val t4 = Abs( Var( "y", Ti ), t2 ) val t5 = Abs( Var( "x", Ti ), t1 ) val t6 = Abs( Var( "y", Ti ), t2 ) val l = List( t1, t2, t3, t4, t5, t6 ) l.forall( x => l.forall( y => { if ( x == y ) x.hashCode() must_== y.hashCode() else true } ) ) ok( "all tests passed" ) } "make maps and sets properly defined" in { val t1 = App( Const( "P", Ti -> To ), Var( "x", Ti ) ) val t2 = App( Const( "P", Ti -> To ), Var( "y", Ti ) ) val t3 = Abs( Var( "x", Ti ), t1 ) val t4 = Abs( Var( "y", Ti ), t2 ) val t5 = Abs( Var( "x", Ti ), t1 ) val t6 = Abs( Var( "y", Ti ), t2 ) val map = HashMap[LambdaExpression, Int]() val set = HashSet[LambdaExpression]() val nmap = map + ( ( t3, 1 ) ) + ( ( t4, 2 ) ) nmap( t3 ) must_== ( 2 ) //the entry for the alpha equal formula must have been overwritten nmap.size must_== ( 1 ) //t3 and t4 are considered equal, so the keyset must not contain both nmap must beEqualTo( Map[LambdaExpression, Int]() + ( ( t3, 1 ) ) + ( ( t4, 2 ) ) ) //map and hashmap must agree val nset = set + t3 + t4 nset.size must_== ( 1 ) //t3 and t4 are considered equal, so the set must not contain both nset must beEqualTo( Set() + t3 + t4 ) //hashset and set must agree } } "Variable renaming" should { "produce a new variable different from all in the blacklist" in { val x = Var( "x", Ti ) val y = Var( "y", Ti ) val z = Var( "z", Ti ) val blacklist = x :: y :: z :: Nil val x_renamed = rename( x, blacklist ) ( blacklist.contains( x_renamed ) ) must beEqualTo( false ) x_renamed.sym must beAnInstanceOf[VariantSymbol] x_renamed.sym.asInstanceOf[VariantSymbol].s must_== "x" } "produce a new variable different from all in the blacklist (in presence of maliciously chosen variable names)" in { val v = Var( "v", Ti ) val v0 = Var( "v0", Ti ) val v_renamed = rename( v, v :: v0 :: Nil ) ( v_renamed ) must not be equalTo( v0 ) ( v_renamed.syntaxEquals( v0 ) ) must beEqualTo( false ) } } "Checking for variable normal form" should { "work correctly for negative" in { val x = Var( "x", Ti ) val z = Var( "z", Ti ) val idx = Abs( x, x ) val M = App( idx, App( idx, z ) ) isInVNF( M ) must beFalse } "work correctly for positive" in { val x = Var( "x", Ti ) val y = Var( "y", Ti ) val z = Var( "z", Ti ) val idx = Abs( x, x ) val idy = Abs( y, y ) val M = App( idx, App( idy, z ) ) isInVNF( M ) must beTrue } "treat overbinding correctly" in { val x = Var( "x", Ti ) val M = Abs( x, Abs( x, x ) ) isInVNF( M ) must beFalse } } "TypedLambdaCalculus" should { "extract free variables correctly" in { val x = Var( "X", Ti -> To ) val y = Var( "y", Ti ) val z = Var( "Z", Ti -> To ) val r = Var( "R", ( Ti -> To ) -> ( Ti -> ( ( Ti -> To ) -> To ) ) ) val a = App( r, x :: y :: z :: Nil ) val qa = Abs( x, a ) val free = freeVariables( qa ) free must not( contain( ( v: Var ) => v.syntaxEquals( x ) ) ) free must ( contain( ( v: Var ) => v.syntaxEquals( y ) ) ) free must ( contain( ( v: Var ) => v.syntaxEquals( z ) ) ) free must ( contain( ( v: Var ) => v.syntaxEquals( r ) ) ) } "extract free variables correctly" in { val x = Var( "x", Ti -> Ti ) val z = Var( "z", Ti ) val M = App( Abs( x, App( x, z ) ), x ) val fv = freeVariables( M ) val fv_correct = Set( x, z ) fv must be equalTo ( fv_correct ) } "extract free variables correctly" in { val x = Var( "x", Ti -> Ti ) val z = Var( "z", Ti ) val M = Abs( x, App( Abs( x, App( x, z ) ), x ) ) val fv = freeVariables( M ) val fv_correct = Set( z ) fv must be equalTo ( fv_correct ) } "deal correctly with bound variables in the Abs extractor" in { val x = Var( "x", Ti ) val p = Var( "p", Ti -> To ) val px = App( p, x ) val xpx = Abs( x, px ) val res = xpx match { case Abs( v, t ) => Abs( v, t ) } res must beEqualTo( xpx ) } } }
loewenheim/gapt
src/test/scala/at/logic/gapt/expr/LambdaCalculusTest.scala
Scala
gpl-3.0
9,626
trait MyRange { inline def foreach(inline f: Int => Unit): Unit } transparent inline def MyRange(inline start: Int, inline end: Int): MyRange = new { inline def foreach(inline f: Int => Unit) = // error: Implementation restriction var i = start val e = end while (i < e) { f(i) i += 1 } } object App { val count: Int = 4 for (i <- MyRange(0, count)) { // error: Deferred inline method foreach in trait MyRange cannot be invoked Console.println("Number: " + i) } }
dotty-staging/dotty
tests/neg/inline-foreach.scala
Scala
apache-2.0
508
package net.fwbrasil.scala import scala.IndexOutOfBoundsException object Product29 { def unapply[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29](x: Product29[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29]): Option[Product29[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29]] = Some(x) } trait Product29[+T1, +T2, +T3, +T4, +T5, +T6, +T7, +T8, +T9, +T10, +T11, +T12, +T13, +T14, +T15, +T16, +T17, +T18, +T19, +T20, +T21, +T22, +T23, +T24, +T25, +T26, +T27, +T28, +T29] extends Product { override def productArity = 29 @throws(classOf[IndexOutOfBoundsException]) override def productElement(n: Int) = n match { case 0 => _1 case 1 => _2 case 2 => _3 case 3 => _4 case 4 => _5 case 5 => _6 case 6 => _7 case 7 => _8 case 8 => _9 case 9 => _10 case 10 => _11 case 11 => _12 case 12 => _13 case 13 => _14 case 14 => _15 case 15 => _16 case 16 => _17 case 17 => _18 case 18 => _19 case 19 => _20 case 20 => _21 case 21 => _22 case 22 => _23 case 23 => _24 case 24 => _25 case 25 => _26 case 26 => _27 case 27 => _28 case 28 => _29 case _ => throw new IndexOutOfBoundsException(n.toString()) } def _1: T1 def _2: T2 def _3: T3 def _4: T4 def _5: T5 def _6: T6 def _7: T7 def _8: T8 def _9: T9 def _10: T10 def _11: T11 def _12: T12 def _13: T13 def _14: T14 def _15: T15 def _16: T16 def _17: T17 def _18: T18 def _19: T19 def _20: T20 def _21: T21 def _22: T22 def _23: T23 def _24: T24 def _25: T25 def _26: T26 def _27: T27 def _28: T28 def _29: T29 }
xdevelsistemas/activate
activate-core/src/main/scala/net/fwbrasil/scala/Product29.scala
Scala
lgpl-2.1
2,113
// Copyright (c) 2016 PSForever.net to present package net.psforever.packet.game import net.psforever.packet.{GamePacketOpcode, Marshallable, PlanetSideGamePacket} import scodec.Codec import scodec.codecs._ /** * Report the raw numerical population for a zone (continent).<br> * <br> * Populations are displayed as percentages of the three main empires against each other. * Populations specific to a zone will be displayed in the Incentives window for that zone. * Populations in all zones will contribute to the Global Population window and the Incentives window for the server. * The Black OPs population does not show up in the Incentives window for a zone but will be indirectly represented in the other two windows. * This packet also shifts the flavor text for that zone.<br> * <br> * The size of zone's queue is the final upper population limit for that zone. * Common values for the zone queue fields are 0 (locked) and 414 positions. * When a continent can not accept any players at all, a lock icon will appear over its view pane in the Interstellar View. * Setting the zone's queue to zero will also render this icon.<br> * <br> * The individual queue fields set the maximum empire occupancy for a zone that is represented in the zone Incentives text. * Common values for the empire queue fields are 0 (locked population), 138 positions, and 500 positions. * Zone Incentives text, however, will never report more than a "100+" vacancy. * The actual limits are probably set based on server load. * The latter queue value is typical for VR area zones.<br> * <br> * The value of the zone queue trumps the sum of all individual empire queues. * Regardless of individual queues, once total zone population matches the zone queue size, all populations will lock. * For normal zones, if the individual queues are not set properly, whole empires can even be locked out of a zone for this reason. * In the worst case, other empires are allowed enough individual queue vacancy that they can occupy all the available slots. * Sanctuary zones possess strange queue values that are occasionally zero'd. * They do not have a lock icon and may not limit populations the same way as normal zones. * * @param continent_guid identifies the zone (continent) * @param zone_queue the maximum population of all three (four) empires that can join this zone * @param tr_queue the maximum number of TR players that can join this zone * @param tr_pop the current TR population in this zone * @param nc_queue the maximum number of NC players that can join this zone * @param nc_pop the current NC population in this zone * @param vs_queue the maximum number of VS players that can join this zone * @param vs_pop the VS population in this zone * @param bo_queue the maximum number of Black OPs players that can join this zone * @param bo_pop the current Black OPs population in this zone */ final case class ZonePopulationUpdateMessage(continent_guid : PlanetSideGUID, zone_queue : Long, tr_queue : Long, tr_pop : Long, nc_queue : Long, nc_pop : Long, vs_queue : Long, vs_pop : Long, bo_queue : Long = 0L, bo_pop : Long = 0L) extends PlanetSideGamePacket { type Packet = ZonePopulationUpdateMessage def opcode = GamePacketOpcode.ZonePopulationUpdateMessage def encode = ZonePopulationUpdateMessage.encode(this) } object ZonePopulationUpdateMessage extends Marshallable[ZonePopulationUpdateMessage] { implicit val codec : Codec[ZonePopulationUpdateMessage] = ( ("continent_guid" | PlanetSideGUID.codec) :: ("zone_queue" | uint32L) :: ("tr_queue" | uint32L) :: ("tr_pop" | uint32L) :: ("nc_queue" | uint32L) :: ("nc_pop" | uint32L) :: ("vs_queue" | uint32L) :: ("vs_pop" | uint32L) :: ("bo_queue" | uint32L) :: ("bo_pop" | uint32L) ).as[ZonePopulationUpdateMessage] }
Fate-JH/PSF-Server
common/src/main/scala/net/psforever/packet/game/ZonePopulationUpdateMessage.scala
Scala
gpl-3.0
4,278
/* * Copyright 2015 LG CNS. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package scouter.server.core.cache; import scouter.util.StringSet; object CacheHelper { val objType =new StringSet(); }
jahnaviancha/scouter
scouter.server/src/scouter/server/core/cache/CacheHelper.scala
Scala
apache-2.0
733
package com.microsoft.partnercatalyst.fortis.spark.analyzer import java.net.URL import com.github.catalystcode.fortis.spark.streaming.facebook.dto.FacebookPost import facebook4j.Post import org.mockito.Mockito import org.scalatest.FlatSpec import org.scalatest.mock.MockitoSugar class FacebookPostAnalyzerTestSpec extends FlatSpec with MockitoSugar { "getSourceURL" should "build a url from getPermalinkUrl.toString" in { val post = mock[Post] val permalink = mock[URL] Mockito.when(permalink.toString).thenReturn("http://github.com/CatalystCode") Mockito.when(permalink.getFile).thenThrow(new RuntimeException("Some exception")) Mockito.when(post.getPermalinkUrl).thenReturn(permalink) val url = new FacebookPostAnalyzer().getSourceURL(FacebookPost( pageId = "abc123", post = post )) assert(url == "http://github.com/CatalystCode") } "getSourceURL" should "build a url from getFile" in { val post = mock[Post] val permalink = mock[URL] Mockito.when(permalink.toString).thenThrow(new RuntimeException("Some exception.")) Mockito.when(permalink.getFile).thenReturn("/some/path/to/post") Mockito.when(post.getPermalinkUrl).thenReturn(permalink) val url = new FacebookPostAnalyzer().getSourceURL(FacebookPost( pageId = "abc123", post = post )) assert(url == "https://www.facebook.com/some/path/to/post") } "getSourceURL" should "build a url from pageId" in { val facebookPost = FacebookPost( pageId = "abc123", post = null ) val url = new FacebookPostAnalyzer().getSourceURL(facebookPost) assert(url == s"https://www.facebook.com/${facebookPost.pageId}/posts") } }
CatalystCode/project-fortis-spark
src/test/scala/com/microsoft/partnercatalyst/fortis/spark/analyzer/FacebookPostAnalyzerTestSpec.scala
Scala
mit
1,696
/* * Copyright 2016 The BigDL Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intel.analytics.bigdl.dllib.keras.layers import com.intel.analytics.bigdl.dllib.nn.abstractnn.AbstractModule import com.intel.analytics.bigdl.dllib.nn.internal.{Flatten => BigDLFlatten} import com.intel.analytics.bigdl.dllib.tensor.Tensor import com.intel.analytics.bigdl.dllib.tensor.TensorNumericMath.TensorNumeric import com.intel.analytics.bigdl.dllib.utils.Shape import com.intel.analytics.bigdl.dllib.keras.Net import scala.reflect.ClassTag /** * Flattens the input without affecting the batch size. * For example, if inputShape = Shape(2, 3, 4), * then outputShape will be Shape(24) with batch dimension unchanged. * * When you use this layer as the first layer of a model, you need to provide the argument * inputShape (a Single Shape, does not include the batch dimension). * * @param inputShape A Single Shape, does not include the batch dimension. * @tparam T Numeric type of parameter(e.g. weight, bias). Only support float/double now. */ class Flatten[T: ClassTag]( override val inputShape: Shape = null)(implicit ev: TensorNumeric[T]) extends BigDLFlatten[T](inputShape) with Net { override def doBuild(inputShape: Shape): AbstractModule[Tensor[T], Tensor[T], T] = { val input = inputShape.toSingle().toArray val layer = com.intel.analytics.bigdl.dllib.nn.Reshape( Array(input.slice(1, input.length).product), batchMode = Some(true)) layer.asInstanceOf[AbstractModule[Tensor[T], Tensor[T], T]] } override private[bigdl] def toKeras2(): String = { val params = Net.inputShapeToString(inputShape) ++ Net.param(getName()) Net.kerasDef(this, params) } } object Flatten { def apply[@specialized(Float, Double) T: ClassTag]( inputShape: Shape = null)(implicit ev: TensorNumeric[T]): Flatten[T] = { new Flatten[T](inputShape) } }
intel-analytics/BigDL
scala/dllib/src/main/scala/com/intel/analytics/bigdl/dllib/keras/layers/Flatten.scala
Scala
apache-2.0
2,437
package org.jetbrains.plugins.scala package lang package psi package api package toplevel package imports import com.intellij.psi.PsiElement import org.jetbrains.plugins.scala.lang.psi.ScalaPsiElement import org.jetbrains.plugins.scala.lang.psi.api.base.ScStableCodeReferenceElement /** * @author Alexander Podkhalyuzin * Date: 20.02.2008 */ trait ScImportExpr extends ScalaPsiElement { def reference: Option[ScStableCodeReferenceElement] def selectorSet: Option[ScImportSelectors] def selectors: Seq[ScImportSelector] = { selectorSet match { case None => Seq.empty case Some(s) => s.selectors } } def singleWildcard: Boolean def wildcardElement: Option[PsiElement] def qualifier: ScStableCodeReferenceElement def deleteExpr() def getNames: Array[String] = getLastChild match { case s: ScImportSelectors => (for (selector <- selectors) yield selector.getText).toArray case _ => getNode.getLastChildNode.getText match { case "_" => Array[String]("_") case _ if getNode.getLastChildNode.getLastChildNode != null => Array[String](getNode.getLastChildNode.getLastChildNode.getText) case _ => Array[String]() } } override def accept(visitor: ScalaElementVisitor) = visitor.visitImportExpr(this) }
consulo/consulo-scala
src/org/jetbrains/plugins/scala/lang/psi/api/toplevel/imports/ScImportExpr.scala
Scala
apache-2.0
1,277
package io.continuum.bokeh package examples package models import math.{Pi=>pi,sin} object DateAxis extends Example { val now = System.currentTimeMillis.toDouble/1000 val x = -2*pi to 2*pi by 0.1 object source extends ColumnDataSource { val times = column(x.indices.map(3600000.0*_ + now)) val y = column(x.map(sin)) } import source.{times,y} val xdr = new DataRange1d() val ydr = new DataRange1d() val circle = Circle().x(times).y(y).fill_color(Color.Red).size(5).line_color(Color.Black) val renderer = new GlyphRenderer() .data_source(source) .glyph(circle) val plot = new Plot().x_range(xdr).y_range(ydr) val xaxis = new DatetimeAxis().plot(plot) val yaxis = new LinearAxis().plot(plot) plot.below <<= (xaxis :: _) plot.left <<= (yaxis :: _) val pantool = new PanTool().plot(plot) val wheelzoomtool = new WheelZoomTool().plot(plot) plot.renderers := List(xaxis, yaxis, renderer) plot.tools := List(pantool, wheelzoomtool) val document = new Document(plot) val html = document.save("dateaxis.html", config.resources) info(s"Wrote ${html.file}. Open ${html.url} in a web browser.") }
bokeh/bokeh-scala
examples/src/main/scala/models/DateAxis.scala
Scala
mit
1,219
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2021 Andre White. * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.truthencode.ddo.session class Synchronization {}
adarro/ddo-calc
subprojects/common/ddo-core/src/main/scala/io/truthencode/ddo/session/Synchronization.scala
Scala
apache-2.0
705
package edu.nus.maxsmtplay import com.microsoft.z3._ abstract class MaxSMT { this: Z3 => def solve(soft: List[BoolExpr], hard: List[BoolExpr]): Option[List[BoolExpr]] = { solveAndGetModel(soft, hard) match { case None => None case Some((clauses, _)) => Some(clauses) } } def solveAndGetModel(soft: List[BoolExpr], hard: List[BoolExpr]): Option[(List[BoolExpr], Model)] }
mechtaev/maxsmt-playground
src/main/scala/edu/nus/maxsmtplay/MaxSMT.scala
Scala
mit
404
package support.bulkImport import org.joda.time.DateTime /** * Created with IntelliJ IDEA. * User: matthijs * Date: 6/29/13 * Time: 7:46 PM * To change this template use File | Settings | File Templates. */ object WorkerResultStatus extends Enumeration { type Status = Value val DONE, FAILED, TIMEOUT, READY, SUICIDE, NO_WORK = Value } class WorkerResult(state: WorkerResultStatus.Status, result : Option[String], payLoad: Option[Payload]) { private val end: DateTime = new DateTime def status: WorkerResultStatus.Status = state def getResult: String = result.getOrElse("") def getProcessingTime: Long = { payLoad match { case Some(pl) => end.getMillis - pl.getCreationDate.getMillis case None => 0L } } def getPayLoad : Option[Payload] = payLoad }
plamola/sendR
app/support/bulkImport/WorkerResult.scala
Scala
gpl-2.0
817
/* * 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.spark.testsuite.aggquery import org.apache.spark.sql.Row import org.scalatest.BeforeAndAfterAll import org.apache.carbondata.core.constants.CarbonCommonConstants import org.apache.carbondata.core.util.CarbonProperties import org.apache.spark.sql.test.util.QueryTest /** * Test Class for aggregate query on Integer datatypes * */ class IntegerDataTypeTestCase extends QueryTest with BeforeAndAfterAll { override def beforeAll { sql("DROP TABLE IF EXISTS integertypetableAgg") sql("DROP TABLE IF EXISTS short_table") sql("CREATE TABLE integertypetableAgg (empno int, workgroupcategory string, deptno int, projectcode int, attendance int) STORED BY 'org.apache.carbondata.format'") sql(s"""LOAD DATA local inpath '$resourcesPath/data.csv' INTO TABLE integertypetableAgg OPTIONS ('DELIMITER'= ',', 'QUOTECHAR'= '\\"', 'FILEHEADER'='')""") } test("select empno from integertypetableAgg") { checkAnswer( sql("select empno from integertypetableAgg"), Seq(Row(11), Row(12), Row(13), Row(14), Row(15), Row(16), Row(17), Row(18), Row(19), Row(20))) } test("short int table boundary test, safe column page") { sql( """ | DROP TABLE IF EXISTS short_int_table """.stripMargin) // value column is less than short int, value2 column is bigger than short int sql( """ | CREATE TABLE short_int_table | (value int, value2 int, name string) | STORED BY 'org.apache.carbondata.format' """.stripMargin) sql( s""" | LOAD DATA LOCAL INPATH '$resourcesPath/shortintboundary.csv' | INTO TABLE short_int_table """.stripMargin) checkAnswer( sql("select value from short_int_table"), Seq(Row(0), Row(127), Row(128), Row(-127), Row(-128), Row(32767), Row(-32767), Row(32768), Row(-32768), Row(65535), Row(-65535), Row(8388606), Row(-8388606), Row(8388607), Row(-8388607), Row(0), Row(0), Row(0), Row(0)) ) checkAnswer( sql("select value2 from short_int_table"), Seq(Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(8388608), Row(-8388608), Row(8388609), Row(-8388609)) ) sql( """ | DROP TABLE short_int_table """.stripMargin) } test("short int table boundary test, unsafe column page") { CarbonProperties.getInstance().addProperty( CarbonCommonConstants.ENABLE_UNSAFE_COLUMN_PAGE, "true" ) sql( """ | DROP TABLE IF EXISTS short_int_table """.stripMargin) // value column is less than short int, value2 column is bigger than short int sql( """ | CREATE TABLE short_int_table | (value int, value2 int, name string) | STORED BY 'org.apache.carbondata.format' """.stripMargin) sql( s""" | LOAD DATA LOCAL INPATH '$resourcesPath/shortintboundary.csv' | INTO TABLE short_int_table """.stripMargin) checkAnswer( sql("select value from short_int_table"), Seq(Row(0), Row(127), Row(128), Row(-127), Row(-128), Row(32767), Row(-32767), Row(32768), Row(-32768), Row(65535), Row(-65535), Row(8388606), Row(-8388606), Row(8388607), Row(-8388607), Row(0), Row(0), Row(0), Row(0)) ) checkAnswer( sql("select value2 from short_int_table"), Seq(Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(0), Row(8388608), Row(-8388608), Row(8388609), Row(-8388609)) ) sql( """ | DROP TABLE short_int_table """.stripMargin) } test("test all codecs") { sql( """ | DROP TABLE IF EXISTS all_encoding_table """.stripMargin) //begin_time column will be encoded by deltaIntegerCodec sql( """ | CREATE TABLE all_encoding_table | (begin_time bigint, name string,begin_time1 long,begin_time2 long,begin_time3 long, | begin_time4 long,begin_time5 int,begin_time6 int,begin_time7 int,begin_time8 short, | begin_time9 bigint,begin_time10 bigint,begin_time11 bigint,begin_time12 int, | begin_time13 int,begin_time14 short,begin_time15 double,begin_time16 double, | begin_time17 double,begin_time18 double,begin_time19 int,begin_time20 double) | STORED BY 'org.apache.carbondata.format' """.stripMargin.replaceAll(System.lineSeparator, "")) sql( s""" | LOAD DATA LOCAL INPATH '$resourcesPath/encoding_types.csv' | INTO TABLE all_encoding_table """.stripMargin) checkAnswer( sql("select begin_time from all_encoding_table"), sql("select begin_time from all_encoding_table") ) val ff = BigInt(2147484000L) checkAnswer( sql("select begin_time,begin_time1,begin_time2,begin_time3,begin_time4,begin_time5,begin_time6,begin_time7,begin_time8,begin_time9,begin_time10,begin_time11,begin_time12,begin_time13,begin_time14,begin_time15,begin_time16,begin_time17,begin_time18,begin_time19,begin_time20 from all_encoding_table"), Seq(Row(1497376581,10000,8388600,125,1497376581,8386600,10000,100,125,1497376581,1497423738,2139095000,1497376581,1497423738,32000,123.4,11.1,3200.1,214744460.2,1497376581,1497376581), Row(1497408581,32000,45000,25,10000,55000,32000,75,35,1497423838,1497423838,ff,1497423838,1497423838,31900,838860.7,12.3,127.1,214748360.2,1497408581,1497408581)) ) sql( """ | DROP TABLE all_encoding_table """.stripMargin) } test("Create a table that contains short data type") { sql("CREATE TABLE if not exists short_table(col1 short, col2 BOOLEAN) STORED BY 'carbondata'") sql("insert into short_table values(1,true)") sql("insert into short_table values(11,false)") sql("insert into short_table values(211,false)") sql("insert into short_table values(3111,true)") sql("insert into short_table values(31111,false)") sql("insert into short_table values(411111,false)") sql("insert into short_table values(5111111,true)") checkAnswer( sql("select count(*) from short_table"), Row(7) ) sql("DROP TABLE IF EXISTS short_table") } override def afterAll { sql("drop table if exists integertypetableAgg") CarbonProperties.getInstance().addProperty( CarbonCommonConstants.ENABLE_UNSAFE_COLUMN_PAGE, CarbonCommonConstants.ENABLE_UNSAFE_COLUMN_PAGE_DEFAULT ) } }
sgururajshetty/carbondata
integration/spark-common-test/src/test/scala/org/apache/carbondata/integration/spark/testsuite/aggquery/IntegerDataTypeTestCase.scala
Scala
apache-2.0
7,306
package com.asto.dmp.shu.service.impl import com.asto.dmp.shu.base.Constants import com.asto.dmp.shu.dao.impl.BizDao import com.asto.dmp.shu.mq.{MsgWrapper, MQAgent, Msg} import com.asto.dmp.shu.service.Service import com.asto.dmp.shu.util.FileUtils import org.apache.spark.Logging object TrendDataService extends Logging { def saveFiles = { if (Constants.App.SAVE_MIDDLE_FILES) { FileUtils.saveAsTextFile(BizDao.getTempSegAndShu, Constants.OutputPath.TEMP_SEG_AND_SHU) FileUtils.saveAsTextFile(BizDao.getSegAndShu, Constants.OutputPath.SEG_AND_SHU) FileUtils.saveAsTextFile(BizDao.getNoDup, Constants.OutputPath.NO_DUP) FileUtils.saveAsTextFile(BizDao.getSegSum, Constants.OutputPath.SEG_SUM) FileUtils.saveAsTextFile(BizDao.getDup, Constants.OutputPath.DUP) FileUtils.saveAsTextFile(BizDao.getDup2, Constants.OutputPath.DUP2) FileUtils.saveAsTextFile(BizDao.getDup3, Constants.OutputPath.DUP3) FileUtils.saveAsTextFile(BizDao.getAllData, Constants.OutputPath.ALL_DATA) FileUtils.saveAsTextFile(BizDao.getModelData, Constants.OutputPath.MODEL_DATA) FileUtils.saveAsTextFile(BizDao.getSeasonIndex, Constants.OutputPath.SEASON_INDEX) } FileUtils.saveAsTextFile(BizDao.getTrendData, Constants.OutputPath.TREND_DATA) if (Constants.App.SAVE_MIDDLE_FILES) { FileUtils.saveAsTextFile(BizDao.getTrendForecast, Constants.OutputPath.TREND_FORECAST) } BizDao.getFinalForecast.collect().foreach { line => val msgs = List( new Msg("M_SHOP_MAJOR_BUSINESS", line._5, line._2) ) MQAgent.send(MsgWrapper.getJson(line._1, msgs)) } FileUtils.saveAsTextFile(BizDao.getFinalForecast, Constants.OutputPath.FINAL_FORECAST) } } class TrendDataService extends Service { override protected def runServices() = { TrendDataService.saveFiles } }
zj-lingxin/Dmp_shu
src/main/scala/com/asto/dmp/shu/service/impl/TrendDataService.scala
Scala
mit
1,875
package com.lucaongaro.similaria.lmdb import scala.language.implicitConversions import java.nio.ByteBuffer case class Key( int: Int ) object Key { def unapply( bytes: Array[Byte] ) = { if ( bytes == null ) None else { val int = ByteBuffer.wrap( bytes ).getInt Some( int ) } } implicit def keyToBytes( key: Key ) = { val bb = ByteBuffer.allocate(4) bb.putInt( key.int ).array() } }
lucaong/similaria
src/main/scala/com/lucaongaro/similaria/lmdb/Key.scala
Scala
mit
431
/* * This file is part of the "consigliere" toolkit for sosreport * and SAR data analytics and visualization. * * Copyright (c) 2014 Red Hat, 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.redhat.et.c9e.sar.analysis import com.redhat.et.c9e.sar.{SarRecord, Metadata, CpuLoad, CpuLoadAll, Memory} import org.apache.spark.mllib.linalg.{Vectors => V} // This file contains some specialized record types to facilitate analyses trait RecordExtracting[T] { def extract(sa: SarRecord): Seq[T] def from(srs: TraversableOnce[SarRecord]): TraversableOnce[T] = srs.flatMap(extract) } case class CpuLoadEntry( nodename: String, timestamp: java.util.Date, cpu: String, idle: Double, iowait: Double, nice: Double, steal: Double, system: Double, user: Double ) { def toVec = V.dense(idle, iowait, nice, steal, system, user) } case class CpuLoadAllEntry( nodename: String, timestamp: java.util.Date, cpu: String, gnice: Double, guest: Double, idle: Double, iowait: Double, irq: Double, nice: Double, soft: Double, steal: Double, sys: Double, usr: Double ) { def toVec = V.dense(gnice, guest, idle, iowait, irq, nice, soft, steal, sys, usr) } case class MemoryEntry( nodename: String, timestamp: java.util.Date, active: Int, /* 1 */ buffers: Int, /* 2 */ bufpg: Double, /* 3 */ cached: Int, /* 4 */ campg: Double, /* 5 */ commit: Int, /* 6 */ commitPercent: Double, /* 7 */ dirty: Int, /* 8 */ frmpg: Double, /* 9 */ inactive: Int, /* 10 */ memfree: Int, /* 11 */ memused: Int, /* 12 */ memusedPercent: Double, /* 13 */ swpcad: Int, /* 14 */ swpcadPercent: Double, /* 15 */ swpfree: Int, /* 16 */ swpused: Int, /* 17 */ swpusedPercent: Double /* 18 */ ) { def toVec = V.dense(active, buffers, bufpg, cached, campg, commit, commitPercent, dirty, frmpg, inactive, memfree, memused, memusedPercent, swpcad, swpcadPercent, swpfree, swpused, swpusedPercent) } object CpuLoadEntry extends RecordExtracting[CpuLoadEntry] { def extract(sa: SarRecord) = { sa.cpuLoad.map { case CpuLoad(cpu, idle, iowait, nice, steal, system, user) => val ts = sa.timestamp CpuLoadEntry(sa._metadata.nodename, ts, cpu, idle, iowait, nice, steal, system, user) } } } object CpuLoadAllEntry extends RecordExtracting[CpuLoadAllEntry] { def extract(sa: SarRecord) = { sa.cpuLoadAll.map { case CpuLoadAll(cpu, gnice, guest, idle, iowait, irq, nice, soft, steal, system, user) => val ts = sa.timestamp CpuLoadAllEntry(sa._metadata.nodename, ts, cpu, gnice.getOrElse(0), guest, idle, iowait, irq, nice, soft, steal, system, user) } } } object MemoryEntry extends RecordExtracting[MemoryEntry] { def extract(sa: SarRecord) = { Seq(sa.memory match { case Memory(active, buffers, bufpg, cached, campg, commit, commitPercent, dirty, frmpg, inactive, memfree, memused, memusedPercent, swpcad, swpcadPercent, swpfree, swpused, swpusedPercent) => val ts = sa.timestamp MemoryEntry(sa._metadata.nodename, ts, active, buffers, bufpg, cached, campg, commit, commitPercent, dirty, frmpg, inactive, memfree, memused, memusedPercent, swpcad, swpcadPercent, swpfree, swpused, swpusedPercent) }) } }
willb/c9e
common/src/main/scala/com/redhat/et/c9e/sar/analysis/specialized.scala
Scala
apache-2.0
4,020
/** * Copyright (C) 2010 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.common import org.dom4j.Document import org.orbeon.errorified.Exceptions import org.orbeon.oxf.pipeline.InitUtils.withPipelineContext import org.orbeon.oxf.processor.DOMSerializer import org.orbeon.oxf.processor.ProcessorImpl.{INPUT_DATA, OUTPUT_DATA} import org.orbeon.oxf.processor.SignatureVerifierProcessor import org.orbeon.oxf.processor.generator.DOMGenerator import org.orbeon.oxf.resources.ResourceManagerWrapper import org.orbeon.oxf.resources.ResourceNotFoundException import org.orbeon.oxf.util.DateUtils._ import org.orbeon.oxf.util.PipelineUtils._ import org.orbeon.oxf.util.ScalaUtils._ import org.orbeon.oxf.xforms.XFormsContainingDocument import org.orbeon.oxf.xforms.analysis.DumbXPathDependencies import org.orbeon.oxf.xforms.analysis.PathMapXPathDependencies import org.orbeon.oxf.xml.dom4j.Dom4jUtils import java.io.{FileInputStream, File} import org.orbeon.oxf.xml.XMLUtils import util.Try import java.security.SignatureException import scala.util.control.NonFatal class PEVersion extends Version { import PEVersion._ import Version._ // Check license file during construction // If the license doesn't pass, throw an exception so that processing is interrupted locally { def licenseError(message: String, throwable: Option[Throwable] = None) = { val fullMessage = VersionString + ": " + message + ". " + LicenseMessage logger.error(fullMessage) throw throwable getOrElse new OXFException(fullMessage) } val licenseInfo = try tryReadLicense flatMap tryGetSignedData flatMap LicenseInfo.tryApply get catch { case NonFatal(t) ⇒ Exceptions.getRootThrowable(t) match { case _: ResourceNotFoundException ⇒ licenseError("License file not found") case _: SignatureException ⇒ licenseError("Invalid license file signature") case NonFatal(t) ⇒ licenseError("Error loading license file", Some(t)) } } licenseInfo.formattedSubscriptionEnd match { case Some(end) ⇒ // There is a subscription end date so we check that the build date is prior to that // NOTE: Don't check against the current date as we don't want to depend on that for production licenses if (licenseInfo.isBuildAfterSubscriptionEnd) licenseError(s"Subscription ended on: $end, Orbeon Forms build dates from: ${licenseInfo.formattedBuildDate.get}") case None ⇒ // There is no subscription end date so we check against the version if (licenseInfo.isBadVersion) licenseError(s"License version doesn't match. License version is: ${licenseInfo.version.get}, Orbeon Forms version is: $VersionNumber") } // Check expiration against the current date (for non-production licenses) if (licenseInfo.isExpired) licenseError(s"License has expired on ${licenseInfo.formattedExpiration.get}") logger.info("This installation of " + VersionString + " is licensed to: " + licenseInfo.toString) } def requirePEFeature(featureName: String) = () def isPEFeatureEnabled(featureRequested: Boolean, featureName: String) = featureRequested def createUIDependencies(containingDocument: XFormsContainingDocument) = { val requested = containingDocument.getStaticState.isXPathAnalysis if (requested) new PathMapXPathDependencies(containingDocument) else new DumbXPathDependencies } } private object PEVersion { import Version._ val LicensePath = "/config/license.xml" val LicenseURL = "oxf:" + LicensePath val OrbeonPublicKeyURL = "oxf:/config/orbeon-public.xml" val LicenseMessage = "Please make sure a proper license file is placed under WEB-INF/resources" + LicensePath + '.' def isVersionExpired(currentVersion: String, licenseVersion: String): Boolean = (majorMinor(currentVersion), majorMinor(licenseVersion)) match { case (Some((currentMajor, currentMinor)), Some((licenseMajor, licenseMinor))) ⇒ currentMajor > licenseMajor || (currentMajor == licenseMajor && currentMinor > licenseMinor) case _ ⇒ true } def majorMinor(versionString: String): Option[(Int, Int)] = { val ints = versionString.split('.') take 2 map (_.toInt) if (ints.size == 2) Some(ints(0), ints(1)) else None } private val MatchTimestamp = """(.*[^\\d]|)(\\d{4})(\\d{2})(\\d{2})\\d{4}([^\\d].*|)""".r def dateFromVersionNumber(currentVersion: String) = ( Some(currentVersion) collect { case MatchTimestamp(_, year, month, day, _) ⇒ year + '-' + month + '-' + day } map parseISODateOrDateTime ) case class LicenseInfo( versionNumber: String, licensor: String, licensee: String, organization: String, email: String, issued: String, version: Option[String], expiration: Option[Long], subscriptionEnd: Option[Long]) { def isBadVersion = version exists (isVersionExpired(versionNumber, _)) def isExpired = expiration exists (System.currentTimeMillis() > _) def isBuildAfterSubscriptionEnd = subscriptionEnd exists (end ⇒ dateFromVersionNumber(versionNumber) exists (_ > end)) def formattedExpiration = expiration map DateNoZone.print def formattedSubscriptionEnd = subscriptionEnd map DateNoZone.print def formattedBuildDate = dateFromVersionNumber(versionNumber) map DateNoZone.print override def toString = { val versionString = version map (" for version " + _) getOrElse "" val subscriptionEndString = formattedSubscriptionEnd map (" with subscription ending on " + _) getOrElse "" val expiresString = formattedExpiration map (" and expires on " + _) getOrElse "" licensee + " / " + organization + " / " + email + versionString + subscriptionEndString + expiresString } } object LicenseInfo { def apply(licenceDocument: Document): LicenseInfo = { import org.orbeon.oxf.xml.XPathUtils.selectStringValueNormalize def select(s: String) = selectStringValueNormalize(licenceDocument, "/license/" + s) val licensor = select("licensor") val licensee = select("licensee") val organization = select("organization") val email = select("email") val issued = select("issued") val versionOpt = nonEmptyOrNone(select("version")) val expirationOpt = nonEmptyOrNone(select("expiration")) map parseISODateOrDateTime val subscriptionEndOpt = nonEmptyOrNone(select("subscription-end")) map parseISODateOrDateTime LicenseInfo(VersionNumber, licensor, licensee, organization, email, issued, versionOpt, expirationOpt, subscriptionEndOpt) } def tryApply(licenceDocument: Document): Try[LicenseInfo] = Try(apply(licenceDocument)) } def tryReadLicense: Try[Document] = { def fromResourceManager = Try(ResourceManagerWrapper.instance.getContentAsDOM4J(LicensePath)) def fromHomeDirectory = Try { val path = dropTrailingSlash(System.getProperty("user.home")) + "/.orbeon/license.xml" useAndClose(new FileInputStream(new File(path))) { is ⇒ Dom4jUtils.readDom4j(is, path, XMLUtils.ParserConfiguration.PLAIN) } } fromResourceManager orElse fromHomeDirectory } def tryGetSignedData(rawDocument: Document): Try[Document] = Try { val key = createURLGenerator(OrbeonPublicKeyURL) // Remove blank spaces as that's the way it was signed val inputLicenseDocument = Dom4jUtils.readDom4j(Dom4jUtils.domToCompactString(rawDocument)) // Connect pipeline val serializer = { val licence = new DOMGenerator(inputLicenseDocument, "license", DOMGenerator.ZeroValidity, LicenseURL) val verifierProcessor = new SignatureVerifierProcessor connect(licence, OUTPUT_DATA, verifierProcessor, INPUT_DATA) connect(key, OUTPUT_DATA, verifierProcessor, SignatureVerifierProcessor.INPUT_PUBLIC_KEY) val result = new DOMSerializer connect(verifierProcessor, OUTPUT_DATA, result, INPUT_DATA) result } // Execute pipeline to obtain license document withPipelineContext { pipelineContext ⇒ serializer.reset(pipelineContext) serializer.runGetDocument(pipelineContext) } } }
evlist/orbeon-forms
src/main/scala/org/orbeon/oxf/common/PEVersion.scala
Scala
lgpl-2.1
9,908
package me.gregd.cineworld.domain.repository import me.gregd.cineworld.domain.model.Cinema trait CinemaRepository[F[_]] { def fetchAll(): F[Seq[Cinema]] def persist(cinemas: Seq[Cinema]): F[Unit] }
Grogs/cinema-service
domain/src/main/scala/me/gregd/cineworld/domain/repository/CinemaRepository.scala
Scala
gpl-3.0
205
object Ranges { // (1 to 10). // (1) this works as expected (1 to 10).toS /*!*/ // (2) this fails }
felixmulder/scala
test/disabled/presentation/ide-bug-1000450/src/Ranges.scala
Scala
bsd-3-clause
106
import scala.reflect.runtime.universe._ class C { val f1 = 2 var f2 = 3 def m1 = 4 def m2() = 5 def m3[T >: String <: Int]: T = ??? def m4[A[_], B <: A[Int]](x: A[B])(implicit y: Int) = ??? def m5(x: => Int, y: Int*): String = ??? class C object M override def toString = "an instance of C" } object M object Test extends App { val cm = scala.reflect.runtime.currentMirror // println(cm) println(cm.reflectClass(cm.staticClass("C"))) println(cm.reflectModule(cm.staticModule("M"))) println(cm.reflect(new C)) val im = cm.reflect(new C) println(im.reflectField(typeOf[C].member(TermName("f1")).asTerm)) println(im.reflectField(typeOf[C].member(TermName("f2")).asTerm)) println(im.reflectMethod(typeOf[C].member(TermName("m1")).asMethod)) println(im.reflectMethod(typeOf[C].member(TermName("m2")).asMethod)) println(im.reflectMethod(typeOf[C].member(TermName("m3")).asMethod)) println(im.reflectMethod(typeOf[C].member(TermName("m4")).asMethod)) println(im.reflectMethod(typeOf[C].member(TermName("m5")).asMethod)) println(im.reflectClass(typeOf[C].member(TypeName("C")).asClass)) println(im.reflectModule(typeOf[C].member(TermName("M")).asModule)) val c = cm.staticClass("C") val cc = typeOf[C].member(TypeName("C")).asClass println(cm.reflectClass(c).reflectConstructor(c.info.member(termNames.CONSTRUCTOR).asMethod)) println(im.reflectClass(cc).reflectConstructor(cc.info.member(termNames.CONSTRUCTOR).asMethod)) }
scala/scala
test/files/run/reflection-allmirrors-tostring.scala
Scala
apache-2.0
1,481
/* Copyright (C) 2008-2014 University of Massachusetts Amherst. This file is part of "FACTORIE" (Factor graphs, Imperative, Extensible) http://factorie.cs.umass.edu, http://github.com/factorie Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cc.factorie.directed import cc.factorie.infer._ import cc.factorie.model.Model import cc.factorie.variable.{DiscreteVar, DiscreteVariable, Var} /** The expectation-maximization method of inference. maximizing is the collection of variables that will be maximized. meanField contains the variables for which to get expectations. You can provide your own Maximizer; other wise an instance of the default MaximizeSuite is provided. */ class EMInferencer[V<:Var,W<:DiscreteVar,M<:Model](val maximizing:Iterable[V], val marginalizing:Iterable[W], val model:M, val expecter:Infer[Iterable[W],M], val maximizer:Infer[Iterable[V],M]) { var summary: Summary = null def eStep(): Unit = summary = expecter.infer(marginalizing.toSeq, model) // The "foreach and Seq(v)" below reflect the fact that in EM we maximize the variables independently of each other def mStep(): Unit = maximizing.foreach(v => maximizer.infer(Seq(v), model, summary).setToMaximize(null)) // This "get" will fail if the Maximizer was unable to handle the request def process(iterations:Int): Unit = for (i <- 0 until iterations) { eStep; mStep } // TODO Which should come first? mStep or eStep? def process(): Unit = process(100) // TODO Make a reasonable convergence criteria } object EMInferencer { def apply[V<:Var](maximizing:Iterable[V], varying:Iterable[DiscreteVariable], model:Model, maximizer:Maximize[Iterable[V],Model] = Maximize, infer:Infer[Iterable[DiscreteVar],Model] = InferByBPTree) = new EMInferencer(maximizing, varying, model, infer, maximizer) }
patverga/factorie
src/main/scala/cc/factorie/directed/ExpectationMaximization.scala
Scala
apache-2.0
2,323
/** * Copyright (c) 2013 Bernard Leach * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.leachbj.hsmsim.commands import org.leachbj.hsmsim.crypto.LMK import org.leachbj.hsmsim.crypto.DES import org.leachbj.hsmsim.util.HexConverter import akka.util.ByteString import java.security.SecureRandom case class GenerateZpkRequest(zmk: Array[Byte], isAtallaVariant: Boolean, keySchemeZmk: Byte, keySchemeLmk: Byte, keyCheckType: Byte) extends HsmRequest case class GenerateZpkResponse(errorCode: String, zpkZmk: Array[Byte], zpkLmk: Array[Byte], checkValue: Array[Byte]) extends HsmResponse { val responseCode = "IB" } object GenerateZpkResponse { def createResponse(req: GenerateZpkRequest): HsmResponse = { val zmk = DES.tripleDesDecryptVariant(LMK.lmkVariant("04-05", 0), req.zmk) val zpk = generateZpk val zpkUnderZmk = DES.tripleDesEncrypt(zmk, zpk) val zpkUnderLmk = DES.tripleDesEncryptVariant(LMK.lmkVariant("06-07", 0), zpk) val checkValue = DES.calculateCheckValue(zpk).take(3) GenerateZpkResponse("00", zpkUnderZmk, zpkUnderLmk, checkValue) } private def generateZpk = { val zpk = new Array[Byte](16) generator.nextBytes(zpk) DES.adjustParity(zpk) } private val generator = new SecureRandom }
leachbj/hsm-emulator
hsmsim-akka/src/main/scala/org/leachbj/hsmsim/commands/GenerateZpk.scala
Scala
mit
2,291
package scalajsjest import scala.concurrent.Future import scala.scalajs.concurrent.JSExecutionContext.Implicits.queue import scala.scalajs.js.JSConverters._ private[scalajsjest] trait BaseSuite { def test(name: String)(block: => Unit): Unit = JestGlobal.test(name,() => block) def testAsync(name: String)(block: => Any): Unit = JestGlobal.test(name,() => block) def testOnly(name: String)(block: => Unit): Unit = JestGlobal.test.only(name,() => block) def testSkip(name: String)(block: => Unit): Unit = JestGlobal.test.skip(name,() => block) def testOnlyAsync(name: String)(block: => Any): Unit = JestGlobal.test.only(name,() => block) def expect[T](value: T) = JestGlobal.expect(value) def expectAsync[T](value: Future[T]) = JestGlobal.expectAsync(value.toJSPromise) def assertions(num: Int) = JestGlobal.expect.assertions(num) def beforeEach(block: => Any) = JestGlobal.beforeEach(() => block) def afterEach(block: => Any) = JestGlobal.afterEach(() => block) def beforeAll(block: => Any) = JestGlobal.beforeAll(() => block) def afterAll(block: => Any) = JestGlobal.afterAll(() => block) }
scalajs-jest/core
src/main/scala/scalajsjest/BaseSuite.scala
Scala
apache-2.0
1,157
package doodle.examples import doodle.core._ import doodle.syntax._ object ColorPalette { // Type alias for cell constructor functions. // Takes a hue and a lightness as parameters: type CellFunc = (Int, Double) => Image // Different types of cell: def squareCell(size: Int): CellFunc = (hue: Int, lightness: Double) => Image.rectangle(size, size) lineWidth 0 fillColor Color.hsl(hue.degrees, 1.0.normalized, lightness.normalized) def circleCell(size: Int): CellFunc = (hue: Int, lightness: Double) => Image.circle(size/2) lineWidth 0 fillColor Color.hsl(hue.degrees, 1.0.normalized, lightness.normalized) // Code to construct a palette // from a given cell definition: def column(hue: Int, lStep: Double, cell: CellFunc): Image = { val cells = (0.0 until 1.0 by lStep).toList map { lightness => cell(hue, lightness) } allAbove(cells) } def palette(hStep: Int, lStep: Double, cell: CellFunc): Image = { val columns = (0 until 360 by hStep).toList map { hue => column(hue, lStep, cell) } allBeside(columns) } // The final palette: def image = palette(10, 0.04, circleCell(20)) }
Angeldude/doodle
shared/src/main/scala/doodle/examples/ColorPalette.scala
Scala
apache-2.0
1,199
/* * Process.scala * Trait to map indices to elements over values * * Created By: Avi Pfeffer ([email protected]) * Creation Date: Oct 14, 2014 * * Copyright 2014 Avrom J. Pfeffer and Charles River Analytics, Inc. * See http://www.cra.com or email [email protected] for information. * * See http://www.github.com/p2t2/figaro for a copy of the software license. */ package com.cra.figaro.library.collection import com.cra.figaro.language._ import com.cra.figaro.util.memo /** * A Process maps indices to elements over values. * * Elements, of course, have a universe. Wherever possible, operations on processes, such as getting elements, or mapping or chaining through * a function, produce an element in the same universe as the original element. * An exception is an element over an optional value created for an index out of range, which goes in the default universe, * because there is no source element. * Another exception is a fold operation on a container, which is given a universe (defaults to the current Universe.universe). */ trait Process[Index, Value] { /** * Thrown if the index does not have an element. */ case class IndexOutOfRangeException(index: Index) extends RuntimeException /** * Check whether the given index has an element. */ def rangeCheck(index: Index): Boolean /** * Produce the elements representing the value of the process at the given indices. * Ensures that any dependencies between the elements are represented. * This method must be implemented by implementations of Process. * The return value maps each provided index to the corresponding element. * This method can assume that the indices has already been range checked. */ def generate(indices: List[Index]): Map[Index, Element[Value]] /** * Produce the element corresponding to the value of the process at the given index. * This method can assume that the indices has already been range checked. */ def generate(index: Index): Element[Value] private val cachedElements = scala.collection.mutable.Map[Index, Element[Value]]() private[collection] def generateCached(index: Index): Element[Value] = { cachedElements.getOrElseUpdate(index, generate(index)) } /** * Get an element representing the value of the process at the given index. * Throws IndexOutOfRangeException if the index has no value. * * This apply method is cached, so calling process(index) always returns the same element. */ def apply(index: Index): Element[Value] = { if (!rangeCheck(index)) throw IndexOutOfRangeException(index) generateCached(index) } /** * Get the elements representing the value of the process at the given indices. * Throws IndexOutOfRangeException if any index has no value. */ def apply(indices: Traversable[Index]): Map[Index, Element[Value]] = { for { index <- indices } { if (!rangeCheck(index)) throw IndexOutOfRangeException(index) } generate(indices.toList) } /** * Safely get an element over an optional value at the index. * If the index is in range, the value of the element will be Some(something). * If the index is out of range, the value of the element will be None. */ def get(index: Index): Element[Option[Value]] = { try { val elem = apply(index) new Apply1("", apply(index), (v: Value) => Some(v), elem.universe) } catch { case _: IndexOutOfRangeException => Constant(None) } } /** * Safely get the elements over optional values at all of the indices. * Any index that is not in range will always have value None. * Dependencies between elements for indices in range will be produced. */ def get(indices: Traversable[Index]): Map[Index, Element[Option[Value]]] = { val (inRange, outOfRange) = indices.partition(rangeCheck(_)) val inRangeElems: Map[Index, Element[Value]] = generate(inRange.toList) val inRangeOptPairs: List[(Index, Element[Option[Value]])] = for { (index, elem) <- inRangeElems.toList } yield { val elem2: Element[Option[Value]] = new Apply1("", elem, (v: Value) => Some(v), elem.universe) (index, elem2) } val outOfRangeOptPairs: List[(Index, Element[Option[Value]])] = { for { i <- outOfRange.toList } yield { val elem: Element[Option[Value]] = new Constant("", None, Universe.universe) (i, elem) } } Map((inRangeOptPairs ::: outOfRangeOptPairs):_*) } /** * Apply the given function to every value in this process, returning a new process. */ def map[Value2](f: Value => Value2): Process[Index, Value2] = { val thisProcess = this new Process[Index, Value2] { def generate(i: Index) = { val elem1 = thisProcess(i) Apply(elem1, f)("", elem1.universe) } def generate(indices: List[Index]) = thisProcess.generate(indices).mapValues((e: Element[Value]) => Apply(e, f)("", e.universe)) def rangeCheck(i: Index) = thisProcess.rangeCheck(i) } } /** * Chain every value in this process through the given function, returning a new process. */ def chain[Value2](f: Value => Element[Value2]): Process[Index, Value2] = { val thisProcess = this new Process[Index, Value2] { def generate(i: Index) = { val elem1 = thisProcess(i) Chain(elem1, f)("", elem1.universe) } def generate(indices: List[Index]) = thisProcess.generate(indices).mapValues((e: Element[Value]) => Chain(e, f)("", e.universe)) def rangeCheck(i: Index) = thisProcess.rangeCheck(i) } } /** * Chain every value in this process through the given function, returning a new process. */ def flatMap[Value2](f: Value => Element[Value2]): Process[Index, Value2] = { chain(f) } /** * Returns a new process containing the elements of this process and the argument. * If an index is defined in both processes, the element of the argument is used. */ def ++(that: Process[Index, Value]): Process[Index, Value] = { val thisProcess = this new Process[Index, Value] { def generate(i: Index) = if (that.rangeCheck(i)) that.generate(i); else thisProcess.generate(i) def generate(indices: List[Index]) = { val (fromThatIndices, fromThisIndices) = indices.partition(that.rangeCheck(_)) val fromThis = thisProcess.generate(fromThisIndices) val fromThat = that.generate(indices) fromThis ++ fromThat } def rangeCheck(i: Index) = that.rangeCheck(i) || thisProcess.rangeCheck(i) } } }
agarbuno/figaro
Figaro/src/main/scala/com/cra/figaro/library/collection/Process.scala
Scala
bsd-3-clause
6,593
/* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package services.flowmanagement.pagerouters.businessmatching.subsectors import controllers.businessmatching.routes import models.flowmanagement.ChangeSubSectorFlowModel import utils.AmlsSpec import play.api.test.Helpers._ class NoPsrNumberPageRouterSpec extends AmlsSpec { trait Fixture { val router = new NoPsrNumberPageRouter } "Getting the next route" must { "route to the 'Check your answers' page" in new Fixture { val model = ChangeSubSectorFlowModel() val result = router.getRoute("internalId", model) redirectLocation(result) mustBe Some(routes.SummaryController.get.url) } } }
hmrc/amls-frontend
test/services/flowmanagement/pagerouters/businessmatching/subsectors/NoPsrNumberPageRouterSpec.scala
Scala
apache-2.0
1,234
/* * Copyright 2017 Datamountaineer. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.datamountaineer.streamreactor.connect.errors import com.datamountaineer.streamreactor.connect.TestUtilsBase import org.apache.kafka.connect.errors.RetriableException import scala.util.Failure /** * Created by [email protected] on 24/08/2017. * kafka-connect-common */ class TestErrorHandlerThrow extends TestUtilsBase with ErrorHandler { initialize(10, ErrorPolicy(ErrorPolicyEnum.THROW)) "should throw" in { intercept[RuntimeException] { try { 1 / 0 } catch { case t: Throwable => { handleTry(Failure(t)) } } } } }
datamountaineer/kafka-connect-common
src/test/scala/com/datamountaineer/streamreactor/connect/errors/TestErrorHandlerThrow.scala
Scala
apache-2.0
1,224
package org.jetbrains.plugins.scala.lang.completion.weighter import com.intellij.codeInsight.completion._ import org.jetbrains.plugins.scala.lang.completion.{ScalaAfterNewCompletionUtil, ScalaCompletionUtil} import org.jetbrains.plugins.scala.lang.refactoring.util.ScalaNamesUtil /** * Created by Kate Ustyuzhanina on 12/2/16. */ object ScalaCompletionSorting { implicit class ResultOps(val result: CompletionResultSet) extends AnyVal { def withScalaSorting(parameters: CompletionParameters): CompletionResultSet = { val isSmart = parameters.getCompletionType == CompletionType.SMART val position = ScalaCompletionUtil.positionFromParameters(parameters) val isAfterNew = ScalaAfterNewCompletionUtil.afterNewPattern.accepts(position) val defaultSorter = CompletionSorter.defaultSorter(parameters, result.getPrefixMatcher) val sorter = if (isSmart) defaultSorter else if (isAfterNew) defaultSorter .weighBefore("liftShorter", new ScalaByTypeWeigher(position)) .weighAfter("scalaTypeCompletionWeigher", new ScalaByExpectedTypeWeigher(position, isAfterNew)) else defaultSorter .weighBefore("liftShorter", new ScalaByTypeWeigher(position)) .weighAfter("scalaKindWeigher", new ScalaByExpectedTypeWeigher(position, isAfterNew)) result.withRelevanceSorter(sorter) } def withBacktickMatcher(): CompletionResultSet = { result.withPrefixMatcher(new BacktickPrefixMatcher(result.getPrefixMatcher)) } } private class BacktickPrefixMatcher(other: PrefixMatcher) extends PrefixMatcher(other.getPrefix) { private val matcherWithoutBackticks = other.cloneWithPrefix(cleanHelper(myPrefix)) override def prefixMatches(name: String): Boolean = if (myPrefix == "`") other.prefixMatches(name) else matcherWithoutBackticks.prefixMatches(ScalaNamesUtil.clean(name)) override def cloneWithPrefix(prefix: String): PrefixMatcher = matcherWithoutBackticks.cloneWithPrefix(prefix) override def isStartMatch(name: String): Boolean = if (myPrefix == "`") other.isStartMatch(name) else matcherWithoutBackticks.isStartMatch(ScalaNamesUtil.clean(name)) private def cleanHelper(prefix: String): String = { if (prefix == null || prefix.isEmpty || prefix == "`") prefix else prefix match { case ScalaNamesUtil.isBacktickedName(s) => s case p if p.head == '`' => p.substring(1) case p if p.last == '`' => prefix.substring(0, prefix.length - 1) case _ => prefix } } } }
triplequote/intellij-scala
scala/scala-impl/src/org/jetbrains/plugins/scala/lang/completion/weighter/ScalaCompletionSorting.scala
Scala
apache-2.0
2,614
package pt.org.apec.services.books.api import spray.routing._ import pt.org.apec.services.books.common.PublicationSorting trait PublicationOrderDirectives extends Directives { import PublicationSorting._ def publicationsSorted: Directive1[PublicationOrder] = readParameter("sortBy") map (_.getOrElse(PublicationOrder(CreatedAt, Desc))) private def readParameter(name: String) = parameter(name.?) map { case Some("title") => Some(PublicationOrder(Title, Asc)) case Some("createdAt") => Some(PublicationOrder(CreatedAt, Desc)) case _ => None } }
apecpt/apec-books-service
service/src/main/scala/pt/org/apec/services/books/api/PublicationOrderDirectives.scala
Scala
apache-2.0
566
package com.mohiva.play.silhouette.api.util import play.api.libs.json.Json import play.api.test._ /** * Test case for the [[com.mohiva.play.silhouette.api.util.Base64]] object. */ class Base64Spec extends PlaySpecification { "The `decode` method" should { "decode a Base64 string" in { Base64.decode("SGVsbG8gV29ybGQh") must be equalTo "Hello World!" } } "The `encode` method" should { "encode a string as Base64" in { Base64.encode("Hello World!") must be equalTo "SGVsbG8gV29ybGQh" } "encode Json as Base64" in { Base64.encode(Json.obj("word" -> "Hello World!")) must be equalTo "eyJ3b3JkIjoiSGVsbG8gV29ybGQhIn0=" } } }
cemcatik/play-silhouette
silhouette/test/com/mohiva/play/silhouette/api/util/Base64Spec.scala
Scala
apache-2.0
679
/* * stateless-future * Copyright 2014 深圳岂凡网络有限公司 (Shenzhen QiFun Network Corp., LTD) * * 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.qifun.statelessFuture import scala.runtime.AbstractPartialFunction import scala.reflect.macros.Context import scala.util.control.Exception.Catcher import scala.util.control.TailCalls._ import scala.concurrent.ExecutionContext import scala.util.Success import scala.util.Failure /** * Used internally only. */ object ANormalForm { abstract class AbstractAwaitable[+AwaitResult, TailRecResult] extends Awaitable.Stateless[AwaitResult, TailRecResult] @inline final def forceOnComplete[TailRecResult](future: Awaitable[Any, TailRecResult], handler: Nothing => TailRec[TailRecResult])(implicit catcher: Catcher[TailRec[TailRecResult]]): TailRec[TailRecResult] = { future.onComplete(handler.asInstanceOf[Any => TailRec[TailRecResult]]) } final class TryCatchFinally[AwaitResult, TailRecResult](tryFuture: Awaitable[AwaitResult, TailRecResult], getCatcherFuture: Catcher[Awaitable[AwaitResult, TailRecResult]], finallyBlock: => Unit) extends AbstractAwaitable[AwaitResult, TailRecResult] { @inline override final def onComplete(rest: AwaitResult => TailRec[TailRecResult])(implicit catcher: Catcher[TailRec[TailRecResult]]) = { tryFuture.onComplete { a => // 成功执行 try try { finallyBlock tailcall(rest(a)) } catch { case e if catcher.isDefinedAt(e) => { // 执行finally时出错 tailcall(catcher(e)) } } } { case e if getCatcherFuture.isDefinedAt(e) => { // 执行 try 失败,用getCatcherFuture进行恢复 val catcherFuture = getCatcherFuture(e) catcherFuture.onComplete { a => // 成功恢复 try { finallyBlock tailcall(rest(a)) } catch { case e if catcher.isDefinedAt(e) => { // 执行finally时出错 tailcall(catcher(e)) } } } { case e if catcher.isDefinedAt(e) => { // 执行 try 失败,getCatcherFuture恢复失败,触发外层异常 try { finallyBlock tailcall(catcher(e)) } catch { case e if catcher.isDefinedAt(e) => { // 执行finally时出错 tailcall(catcher(e)) } } } case e: Throwable => { finallyBlock throw e } } } case e if catcher.isDefinedAt(e) => { // 执行 try 失败,getCatcherFuture不支持恢复,触发外层异常 try { finallyBlock tailcall(catcher(e)) } catch { case e if catcher.isDefinedAt(e) => { // 执行finally时出错 tailcall(catcher(e)) } } } case e: Throwable => { // 执行 try 失败,getCatcherFuture不支持恢复,外层异常 finallyBlock throw e } } } } def applyMacro(c: Context)(block: c.Expr[Any]): c.Expr[Nothing] = { import c.universe._ c.macroApplication match { case Apply(TypeApply(_, List(t)), _) => { applyMacroWithType(c)(block, t, Ident(typeOf[Unit].typeSymbol)) } case Apply(TypeApply(_, List(t, tailRecResultTypeTree)), _) => { applyMacroWithType(c)(block, t, tailRecResultTypeTree) } } } def applyMacroWithType(c: Context)(futureBody: c.Expr[Any], macroAwaitResultTypeTree: c.Tree, tailRecResultTypeTree: c.Tree): c.Expr[Nothing] = { import c.universe.Flag._ import c.universe._ import compat._ def unchecked(tree: Tree) = { Annotated(Apply(Select(New(TypeTree(typeOf[unchecked])), nme.CONSTRUCTOR), List()), tree) } val abstractPartialFunction = typeOf[AbstractPartialFunction[_, _]] val futureType = typeOf[Awaitable[_, _]] val statelessFutureType = typeOf[Awaitable.Stateless[_, _]] val futureClassType = typeOf[AbstractAwaitable[_, _]] val function1Type = typeOf[_ => _] val function1Symbol = function1Type.typeSymbol val tailRecType = typeOf[TailRec[_]] val tailRecSymbol = tailRecType.typeSymbol val uncheckedSymbol = typeOf[scala.unchecked].typeSymbol val AndSymbol = typeOf[Boolean].declaration(newTermName("&&").encodedName) val OrSymbol = typeOf[Boolean].declaration(newTermName("||").encodedName) val tailRecTypeTree = AppliedTypeTree(Ident(tailRecSymbol), List(tailRecResultTypeTree)) val catcherTypeTree = AppliedTypeTree(Ident(typeOf[PartialFunction[_, _]].typeSymbol), List(Ident(typeOf[Throwable].typeSymbol), tailRecTypeTree)) val resultTypeTree = AppliedTypeTree(Ident(statelessFutureType.typeSymbol), List(macroAwaitResultTypeTree, tailRecResultTypeTree)) def checkNakedAwait(tree: Tree, errorMessage: String) { for (subTree @ Select(future, await) <- tree if await.decoded == "await" && future.tpe <:< futureType) { c.error(subTree.pos, errorMessage) } } def transformParameterList(isByNameParam: List[Boolean], trees: List[Tree], catcher: Tree, rest: (List[Tree]) => Tree)(implicit forceAwait: Set[Name]): Tree = { trees match { case Nil => rest(Nil) case head :: tail => { head match { case Typed(origin, typeTree) => transform(origin, catcher, new NotTailcall { override final def apply(transformedOrigin: Tree) = { val parameterName = newTermName(c.fresh("yangBoParameter")) Block( List(ValDef(Modifiers(), parameterName, TypeTree(), transformedOrigin).setPos(origin.pos)), transformParameterList(if (isByNameParam.nonEmpty) isByNameParam.tail else Nil, tail, catcher, { transformedTail => rest(treeCopy.Typed(head, Ident(parameterName), typeTree) :: transformedTail) })) } }) case _ if isByNameParam.nonEmpty && isByNameParam.head => { checkNakedAwait(head, "await must not be used under a by-name argument.") transformParameterList(isByNameParam.tail, tail, catcher, { (transformedTail) => rest(head :: transformedTail) }) } case _ => transform(head, catcher, new NotTailcall { override final def apply(transformedHead: Tree) = { val parameterName = newTermName(c.fresh("yangBoParameter")) Block( List(ValDef(Modifiers(), parameterName, TypeTree(), transformedHead).setPos(head.pos)), transformParameterList(if (isByNameParam.nonEmpty) isByNameParam.tail else Nil, tail, catcher, { transformedTail => rest(Ident(parameterName) :: transformedTail) })) } }) } } } } def newCatcher(cases: List[CaseDef], typeTree: Tree): Tree = { val catcherClassName = newTypeName(c.fresh("YangBoCatcher")) val isDefinedCases = ((for (originCaseDef @ CaseDef(pat, guard, _) <- cases.view) yield { treeCopy.CaseDef(originCaseDef, pat, guard, Literal(Constant(true))) }) :+ CaseDef(Ident(nme.WILDCARD), EmptyTree, Literal(Constant(false)))).toList val defaultName = newTermName(c.fresh("default")) val throwableName = newTermName(c.fresh("throwable")) val applyOrElseCases = cases :+ CaseDef(Ident(nme.WILDCARD), EmptyTree, Apply(Ident(defaultName), List(Ident(throwableName)))) Block( List( ClassDef( Modifiers(FINAL), catcherClassName, List(), Template( List( AppliedTypeTree( Ident(abstractPartialFunction.typeSymbol), List( TypeTree(typeOf[Throwable]), typeTree))), emptyValDef, List( DefDef( Modifiers(), nme.CONSTRUCTOR, List(), List(List()), TypeTree(), Block( List( Apply(Select(Super(This(tpnme.EMPTY), tpnme.EMPTY), nme.CONSTRUCTOR), List())), Literal(Constant(())))), DefDef( Modifiers(OVERRIDE | FINAL), newTermName("applyOrElse"), List( TypeDef(Modifiers(PARAM), newTypeName("A1"), List(), TypeBoundsTree(TypeTree(typeOf[Nothing]), TypeTree(typeOf[Throwable]))), TypeDef(Modifiers(PARAM), newTypeName("B1"), List(), TypeBoundsTree(typeTree, TypeTree(typeOf[Any])))), List(List( ValDef( Modifiers(PARAM), throwableName, Ident(newTypeName("A1")), EmptyTree), ValDef( Modifiers(PARAM), defaultName, AppliedTypeTree(Ident(function1Symbol), List(Ident(newTypeName("A1")), Ident(newTypeName("B1")))), EmptyTree))), Ident(newTypeName("B1")), Match( Annotated( Apply(Select(New(Ident(uncheckedSymbol)), nme.CONSTRUCTOR), List()), Ident(throwableName)), applyOrElseCases)), DefDef( Modifiers(OVERRIDE | FINAL), newTermName("isDefinedAt"), List(), List(List(ValDef(Modifiers(PARAM), throwableName, TypeTree(typeOf[Throwable]), EmptyTree))), TypeTree(typeOf[Boolean]), Match( Annotated( Apply(Select(New(Ident(uncheckedSymbol)), nme.CONSTRUCTOR), List()), Ident(throwableName)), isDefinedCases)))))), Apply(Select(New(Ident(catcherClassName)), nme.CONSTRUCTOR), List())) } sealed trait Rest { def apply(former: Tree): Tree def transformAwait(future: Tree, awaitTypeTree: TypTree, catcher: Tree)(implicit forceAwait: Set[Name]): Tree } // ClassFormatError will be thrown if changing NotTailcall to a trait. scalac's Bug? abstract class NotTailcall extends Rest { override final def transformAwait(future: Tree, awaitTypeTree: TypTree, catcher: Tree)(implicit forceAwait: Set[Name]): Tree = { val nextFutureName = newTermName(c.fresh("yangBoNextFuture")) val futureExpr = c.Expr(ValDef(Modifiers(), nextFutureName, TypeTree(), future)) val AwaitResult = newTermName(c.fresh("awaitValue")) val catcherExpr = c.Expr[Catcher[Nothing]](catcher) val ANormalFormTree = reify(_root_.com.qifun.statelessFuture.ANormalForm).tree val ForceOnCompleteName = newTermName("forceOnComplete") val CatcherTree = catcher val onCompleteCallExpr = c.Expr( Apply( Apply( TypeApply( Select(ANormalFormTree, ForceOnCompleteName), List(tailRecResultTypeTree)), List( Ident(nextFutureName), { val restTree = NotTailcall.this(Ident(AwaitResult)) val tailcallSymbol = reify(scala.util.control.TailCalls).tree.symbol val TailcallName = newTermName("tailcall") val ApplyName = newTermName("apply") val AsInstanceOfName = newTermName("asInstanceOf") def function(awaitValDef: ValDef, restTree: Tree) = { val functionName = newTermName(c.fresh("yangBoHandler")) val restExpr = c.Expr(restTree) Block( List( DefDef( Modifiers(NoFlags, nme.EMPTY, List(Apply(Select(New(Ident(typeOf[scala.inline].typeSymbol)), nme.CONSTRUCTOR), List()))), functionName, List(), List(List(awaitValDef)), TypeTree(), reify { try { restExpr.splice } catch { case e if catcherExpr.splice.isDefinedAt(e) => { _root_.scala.util.control.TailCalls.tailcall(catcherExpr.splice(e)) } } }.tree)), Ident(functionName)) } restTree match { case Block(List(oldVal @ ValDef(_, capturedResultName, _, Ident(AwaitResult))), expr) => { // 参数名优化 function(treeCopy.ValDef(oldVal, Modifiers(PARAM), capturedResultName, awaitTypeTree, EmptyTree), expr) } case Block(List(oldVal @ ValDef(_, capturedResultName, _, Ident(AwaitResult)), restStates @ _*), expr) => { // 参数名优化 function(treeCopy.ValDef(oldVal, Modifiers(PARAM), capturedResultName, awaitTypeTree, EmptyTree), Block(restStates.toList, expr)) } case _ => { function(ValDef(Modifiers(PARAM), AwaitResult, awaitTypeTree, EmptyTree), restTree) } } })), List(catcher))) reify { futureExpr.splice @inline def yangBoTail = onCompleteCallExpr.splice _root_.scala.util.control.TailCalls.tailcall { yangBoTail } }.tree } } def transform(tree: Tree, catcher: Tree, rest: Rest)(implicit forceAwait: Set[Name]): Tree = { tree match { case Try(block, catches, finalizer) => { val futureName = newTermName(c.fresh("tryCatchFinallyFuture")) Block( List( ValDef(Modifiers(), futureName, TypeTree(), Apply( Select( New( AppliedTypeTree( Select(reify(_root_.com.qifun.statelessFuture.ANormalForm).tree, newTypeName("TryCatchFinally")), List(TypeTree(tree.tpe), tailRecResultTypeTree))), nme.CONSTRUCTOR), List( newFuture(block).tree, newCatcher( for (cd @ CaseDef(pat, guard, body) <- catches) yield { treeCopy.CaseDef(cd, pat, guard, newFuture(body).tree) }, AppliedTypeTree( Ident(futureType.typeSymbol), List(TypeTree(tree.tpe), tailRecResultTypeTree))), if (finalizer.isEmpty) { Literal(Constant(())) } else { checkNakedAwait(finalizer, "await must not be used under a finally.") finalizer })))), rest.transformAwait(Ident(futureName), TypeTree(tree.tpe), catcher)) } case ClassDef(mods, _, _, _) => { if (mods.hasFlag(TRAIT)) { checkNakedAwait(tree, "await must not be used under a nested trait.") } else { checkNakedAwait(tree, "await must not be used under a nested class.") } rest(tree) } case _: ModuleDef => { checkNakedAwait(tree, "await must not be used under a nested object.") rest(tree) } case DefDef(mods, _, _, _, _, _) => { if (mods.hasFlag(LAZY)) { checkNakedAwait(tree, "await must not be used under a lazy val initializer.") } else { checkNakedAwait(tree, "await must not be used under a nested method.") } rest(tree) } case _: Function => { checkNakedAwait(tree, "await must not be used under a nested function.") rest(tree) } case EmptyTree | _: New | _: Ident | _: Literal | _: Super | _: This | _: TypTree | _: New | _: TypeDef | _: Import | _: ImportSelector => { rest(tree) } case Select(future, await) if await.decoded == "await" && future.tpe <:< futureType => { transform(future, catcher, new NotTailcall { override final def apply(transformedFuture: Tree) = rest.transformAwait(transformedFuture, TypeTree(tree.tpe), catcher) }) } case Select(instance, field) => { transform(instance, catcher, new NotTailcall { override final def apply(transformedInstance: Tree) = rest(treeCopy.Select(tree, transformedInstance, field)) }) } case TypeApply(method, parameters) => { transform(method, catcher, new NotTailcall { override final def apply(transformedMethod: Tree) = rest(treeCopy.TypeApply(tree, transformedMethod, parameters)) }) } case Apply(method @ Ident(name), parameters) if forceAwait(name) => { transformParameterList(Nil, parameters, catcher, { (transformedParameters) => rest.transformAwait(treeCopy.Apply(tree, Ident(name), transformedParameters), TypeTree(tree.tpe).asInstanceOf[TypTree], catcher) }) } case Apply(method, parameters) => { transform(method, catcher, new NotTailcall { override final def apply(transformedMethod: Tree) = { val isByNameParam = method.symbol match { case AndSymbol | OrSymbol => { List(true) } case _ => { method.tpe match { case MethodType(params, _) => { for (param <- params) yield { param.asTerm.isByNameParam } } case _ => { Nil } } } } transformParameterList(isByNameParam, parameters, catcher, { (transformedParameters) => rest(treeCopy.Apply( tree, transformedMethod, transformedParameters)) }) } }) } case Block(stats, expr) => { def addHead(head: Tree, tuple: (Tree, Boolean)): Tree = { val (tail, mergeable) = tuple tail match { case Block(stats, expr) if mergeable => { treeCopy.Block(tree, head :: stats, expr) } case _ => { treeCopy.Block(tree, List(head), tail) } } } def transformBlock(stats: List[Tree])(implicit forceAwait: Set[Name]): (Tree, Boolean) = { stats match { case Nil => { (transform(expr, catcher, new Rest { override final def transformAwait(future: Tree, awaitTypeTree: TypTree, catcher: Tree)(implicit forceAwait: Set[Name]): Tree = { Block(Nil, rest.transformAwait(future, awaitTypeTree, catcher)) } override final def apply(transformedExpr: Tree) = Block(Nil, rest(transformedExpr)) }), false) } case head :: tail => { (transform(head, catcher, new NotTailcall { override final def apply(transformedHead: Tree) = transformedHead match { case _: Ident | _: Literal => { val (block, _) = transformBlock(tail) block } case _ => { addHead(transformedHead, transformBlock(tail)) } } }), true) } } } Block(Nil, transformBlock(stats)._1) } case ValDef(mods, name, tpt, rhs) => { transform(rhs, catcher, new NotTailcall { override final def apply(transformedRhs: Tree) = rest(treeCopy.ValDef(tree, mods, name, tpt, transformedRhs)) }) } case Assign(left, right) => { transform(left, catcher, new NotTailcall { override final def apply(transformedLeft: Tree) = transform(right, catcher, new NotTailcall { override final def apply(transformedRight: Tree) = rest(treeCopy.Assign(tree, transformedLeft, transformedRight)) }) }) } case Match(selector, cases) => { transform(selector, catcher, new NotTailcall { override final def apply(transformedSelector: Tree) = rest.transformAwait( treeCopy.Match( tree, transformedSelector, for (originCaseDef @ CaseDef(pat, guard, body) <- cases) yield { checkNakedAwait(guard, "await must not be used under a pattern guard.") treeCopy.CaseDef(originCaseDef, pat, guard, newFutureAsType(body, TypeTree(tree.tpe)).tree) }), TypeTree(tree.tpe), catcher) }) } case If(cond, thenp, elsep) => { transform(cond, catcher, new NotTailcall { override final def apply(transformedCond: Tree) = rest.transformAwait( If( transformedCond, newFuture(thenp).tree, newFuture(elsep).tree), TypeTree(tree.tpe), catcher) }) } case Throw(throwable) => { transform(throwable, catcher, new NotTailcall { override final def apply(transformedThrowable: Tree) = rest(treeCopy.Throw(tree, transformedThrowable)) }) } case Typed(expr, tpt@Ident(tpnme.WILDCARD_STAR)) => { transform(expr, catcher, new NotTailcall { override final def apply(transformedExpr: Tree) = rest(treeCopy.Typed(tree, transformedExpr, tpt)) }) } case Typed(expr, tpt) => { transform(expr, catcher, new NotTailcall { override final def apply(transformedExpr: Tree) = rest(treeCopy.Typed(tree, transformedExpr, TypeTree(tpt.tpe))) }) } case Annotated(annot, arg) => { transform(arg, catcher, new NotTailcall { override final def apply(transformedArg: Tree) = rest(treeCopy.Annotated(tree, annot, transformedArg)) }) } case LabelDef(name, params, rhs) => { Block( List( DefDef(Modifiers(), name, List(), List( for (p <- params) yield { ValDef(Modifiers(PARAM), p.name.toTermName, TypeTree(p.tpe), EmptyTree) }), AppliedTypeTree(Ident(futureType.typeSymbol), List(TypeTree(tree.tpe), tailRecResultTypeTree)), newFuture(rhs)(forceAwait + name).tree)), rest.transformAwait( Apply( Ident(name), params), TypeTree(tree.tpe), catcher)) } case _: Return => { c.error(tree.pos, "return is illegal.") rest(tree) } case _: PackageDef | _: Template | _: CaseDef | _: Alternative | _: Star | _: Bind | _: UnApply | _: AssignOrNamedArg | _: ReferenceToBoxed => { c.error(tree.pos, s"Unexpected expression in a `Future` block") rest(tree) } } } def newFutureAsType(tree: Tree, awaitValueTypeTree: Tree)(implicit forceAwait: Set[Name]): c.Expr[Awaitable.Stateless[Nothing, _]] = { val statelessFutureTypeTree = AppliedTypeTree(Ident(statelessFutureType.typeSymbol), List(awaitValueTypeTree, tailRecResultTypeTree)) val futureClassTypeTree = AppliedTypeTree(Ident(futureClassType.typeSymbol), List(awaitValueTypeTree, tailRecResultTypeTree)) val ANormalFormTree = reify(_root_.com.qifun.statelessFuture.ANormalForm).tree val ForceOnCompleteName = newTermName("forceOnComplete") val futureName = newTypeName(c.fresh("YangBoFuture")) val returnName = newTermName(c.fresh("yangBoReturn")) val catcherName = newTermName(c.fresh("yangBoCatcher")) c.Expr( Block( List( ClassDef( Modifiers(FINAL), futureName, List(), Template( List(futureClassTypeTree), emptyValDef, List( DefDef( Modifiers(), nme.CONSTRUCTOR, List(), List(List()), TypeTree(), Block(List(Apply(Select(Super(This(tpnme.EMPTY), tpnme.EMPTY), nme.CONSTRUCTOR), List())), Literal(Constant(())))), DefDef(Modifiers(OVERRIDE | FINAL), newTermName("onComplete"), List(), List( List(ValDef( Modifiers(PARAM), returnName, AppliedTypeTree(Ident(function1Symbol), List(awaitValueTypeTree, tailRecTypeTree)), EmptyTree)), List(ValDef( Modifiers(IMPLICIT | PARAM), catcherName, catcherTypeTree, EmptyTree))), tailRecTypeTree, { val catcherExpr = c.Expr[Catcher[TailRec[Nothing]]](Ident(catcherName)) val tryBodyExpr = c.Expr(transform( tree, Ident(catcherName), new Rest { override final def transformAwait(future: Tree, awaitTypeTree: TypTree, catcher: Tree)(implicit forceAwait: Set[Name]): Tree = { val nextFutureName = newTermName(c.fresh("yangBoNextFuture")) val futureExpr = c.Expr(ValDef(Modifiers(), nextFutureName, TypeTree(), future)) val onCompleteCallExpr = c.Expr( Apply( Apply( TypeApply( Select(ANormalFormTree, ForceOnCompleteName), List(tailRecResultTypeTree)), List( Ident(nextFutureName), Ident(returnName))), List(catcher))) reify { futureExpr.splice @inline def yangBoTail = onCompleteCallExpr.splice _root_.scala.util.control.TailCalls.tailcall { yangBoTail } }.tree } override final def apply(x: Tree) = { val resultExpr = c.Expr(x) val returnExpr = c.Expr[Any => Nothing](Ident(returnName)) reify { val result = resultExpr.splice // Workaround for some nested Future blocks. _root_.scala.util.control.TailCalls.tailcall((returnExpr.splice).asInstanceOf[Any => _root_.scala.util.control.TailCalls.TailRec[Nothing]].apply(result)) }.tree } })) reify { try { tryBodyExpr.splice } catch { case e if catcherExpr.splice.isDefinedAt(e) => { _root_.scala.util.control.TailCalls.tailcall(catcherExpr.splice(e)) } } }.tree }))))), Typed( Apply(Select(New(Ident(futureName)), nme.CONSTRUCTOR), List()), unchecked(statelessFutureTypeTree)))) } def newFuture(tree: Tree)(implicit forceAwait: Set[Name]): c.Expr[Awaitable.Stateless[Nothing, _]] = { newFutureAsType(tree, TypeTree(tree.tpe.widen)) } val result = newFutureAsType(futureBody.tree, macroAwaitResultTypeTree)(Set.empty) // c.warning(c.enclosingPosition, show(result)) c.Expr( TypeApply( Select( c.resetLocalAttrs(result.tree), newTermName("asInstanceOf")), List(resultTypeTree))) } }
Atry/stateless-future
src/main/scala/com/qifun/statelessFuture/ANormalForm.scala
Scala
apache-2.0
30,131
package sri.universal.components import sri.core._ import scalajsplus.macros.{FunctionObjectMacro,exclude,rename} import scalajsplus.{ OptDefault => NoValue, OptionalParam => OP} import sri.universal.MergeJSObjects import scala.scalajs.js import scala.scalajs.js.Dynamic.{literal => json} import scala.scalajs.js.JSConverters.genTravConvertible2JSRichGenTrav import scala.scalajs.js.annotation.JSImport import scala.scalajs.js.| @js.native @JSImport("react-native", "Animated.View") object AnimatedViewComponent extends JSComponent[ViewProps] object AnimatedView { @inline def apply( style: OP[js.Any] = NoValue, @exclude extraProps: OP[ViewProps] = NoValue, @exclude key: String | Int = null, @exclude ref: js.Function1[AnimatedViewComponent.type, Unit] = null)( children: ReactNode*) : ReactElement { type Instance = AnimatedViewComponent.type } = { val props = FunctionObjectMacro() extraProps.foreach(v => { MergeJSObjects(props, v) }) CreateElementJS[AnimatedViewComponent.type](AnimatedViewComponent, props.asInstanceOf[ViewProps], key, ref, children.toJSArray) } } object AnimatedViewC { @inline def apply(children: ReactNode*) = CreateElementJS[AnimatedViewComponent.type](AnimatedViewComponent, json().asInstanceOf[ViewProps], children = children.toJSArray) }
scalajs-react-interface/universal
src/main/scala/sri/universal/components/AnimatedView.scala
Scala
apache-2.0
1,634
package varys.framework.master.scheduler import scala.collection.mutable.{HashMap, ArrayBuffer} import varys.framework.master.{CoflowInfo, SlaveInfo} /** * Primary interface of coflow schedulers. * * Callbacks methods from master must be defined here to address various events. * * User(s) of this must *not* block inside the callback methods. */ trait CoflowScheduler { def schedule(schedulerInput: SchedulerInput): SchedulerOutput } /** * Container class to carry scheduler input */ case class SchedulerInput( activeCoflows: ArrayBuffer[CoflowInfo], activeSlaves: ArrayBuffer[SlaveInfo], sBpsFree: HashMap[String, Double], dBpsFree: HashMap[String, Double] ) /** * Container class to carry back scheduler output */ case class SchedulerOutput( scheduledCoflows: ArrayBuffer[CoflowInfo], markedForRejection: ArrayBuffer[CoflowInfo], sBpsUsed: HashMap[String, Double], dBpsUsed: HashMap[String, Double] )
frankfzw/varys
core/src/main/scala/varys/framework/master/scheduler/coflowScheduler.scala
Scala
apache-2.0
955
package test import javafx.application.Application import javafx.animation.AnimationTimer import javafx.scene.canvas.Canvas import javafx.scene.layout.StackPane import javafx.scene.Scene import javafx.stage.Stage import javafx.scene.media.MediaPlayer import javafx.scene.media.Media import javafx.scene.image.Image import javafx.scene.ImageCursor import javafx.scene.paint.Color import javafx.scene.Scene import javafx.scene.paint.Color import java.awt.Toolkit import java.awt.Dimension import graphics.Sprite import input.InputHandler /** * * * * * * * * * * * * * * * * * * * * * * * * * * * * SpriteTest class * * This class sets up the canvas, initialises the * game world and runs the game loop in a similar * manner to the launcher, but this holds the player * in place on a smaller window and outputs debug * information about the sprite. * * @author Ryan Needham * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ class SpriteTest extends Application { /** * start * * @param Stage * * Determines the host screen size and sets up the canvas * and scene based on these dimensions. The method then * initialises the player objects and inserts them into * the worldObjects array. The H.U.D is also initialised * in a seperate array. When the game objects are set up * the game loop is started and the stage shown. * */ override def start (stage: Stage) = { val screenSize = Toolkit.getDefaultToolkit.getScreenSize val SCREENWIDTH = 256 val SCREENHEIGHT = 256 val canvas = new Canvas (SCREENWIDTH, SCREENHEIGHT) val context = canvas.getGraphicsContext2D val root = new StackPane val scene = new Scene (root, SCREENWIDTH, SCREENHEIGHT) val sprite = new Sprite (SCREENWIDTH, SCREENHEIGHT, "spriteTestTwo") root.getChildren.addAll(canvas) /** * this defines the start positions for each player. * this should be dealt with more elegantly. */ sprite.setX(SCREENWIDTH / 4) sprite.setY(SCREENWIDTH / 4) val input = new InputHandler (sprite, scene) val loop = new AnimationTimer() { override def handle (currentNanoTime: Long) = { // background context.setFill (Color.web("#9E9E9E")) context.fillRect (0, 0, SCREENWIDTH, SCREENHEIGHT) // sprite input.checkForInput sprite.update (currentNanoTime) sprite.testRender (context) // debug context.setFill (Color.WHITE) context.fillText ("time: " + currentNanoTime, 12, 12) context.fillText ("frame: " + sprite.activeFrame, 12, 24) context.fillText ("attacking: " + sprite.attacking, 12, 36) context.fillText ("facing: " + sprite.getActiveSkin, 12, 48) } }.start stage.setTitle ("Panama Engine | Sprite Test") stage.setResizable (false) stage.setScene (scene) stage.show } } object SpriteTest { def main(args: Array[String]) = { Application.launch ( classOf[SpriteTest], args: _* ) } }
MyForteIsTimeTravel/PanamaEngine
src/test/SpriteTest.scala
Scala
mit
3,429
//package com.sksamuel.avro4s // //import com.sksamuel.avro4s.SchemaUpdate.{FullSchemaUpdate, NamespaceUpdate, NoUpdate} //import com.sksamuel.avro4s.ValueTypes._ //import magnolia.{CaseClass, Param} //import org.apache.avro.{Schema, SchemaBuilder} //import scala.reflect.runtime.universe._ // //class ValueTypeEncoder[T: WeakTypeTag](ctx: CaseClass[Encoder, T]) extends Encoder[T] { // // private[avro4s] var encoder: FieldEncoder[T]#ValueEncoder = _ // // def schemaFor = encoder.schemaFor // // def encode(value: T): AnyRef = encoder.encodeValue(value) // // override def withSchema(schemaFor: SchemaFor[T]): Encoder[T] = // ValueTypes.encoder(ctx, DefinitionEnvironment.empty, FullSchemaUpdate(schemaFor)) //} // //class ValueTypeDecoder[T: WeakTypeTag](ctx: CaseClass[Decoder, T]) extends Decoder[T] { // // private[avro4s] var decoder: FieldDecoder[T]#ValueDecoder = _ // // def schemaFor = decoder.schemaFor // // def decode(value: Any): T = ctx.rawConstruct(List(decoder.decodeValue(value))) // // override def withSchema(schemaFor: SchemaFor[T]): Decoder[T] = // ValueTypes.decoder(ctx, DefinitionEnvironment.empty, FullSchemaUpdate(schemaFor)) //} // //object ValueTypes { // // def encoder[T: WeakTypeTag](ctx: CaseClass[Encoder, T], // env: DefinitionEnvironment[Encoder], // update: SchemaUpdate): Encoder[T] = { // val encoder = new ValueTypeEncoder[T](ctx) // val nextEnv = env.updated(encoder) // encoder.encoder = new FieldEncoder[T](ctx.parameters.head)(ctx, nextEnv, update) // encoder // } // // def decoder[T: WeakTypeTag](ctx: CaseClass[Decoder, T], // env: DefinitionEnvironment[Decoder], // update: SchemaUpdate): Decoder[T] = { // val decoder = new ValueTypeDecoder[T](ctx) // val nextEnv = env.updated(decoder) // decoder.decoder = new FieldDecoder[T](ctx.parameters.head)(ctx, nextEnv, update) // decoder // } // // def schema[T](ctx: CaseClass[SchemaFor, T], // env: DefinitionEnvironment[SchemaFor], // update: SchemaUpdate): SchemaFor[T] = // buildSchemaFor(ctx, ctx.parameters.head.typeclass.resolveSchemaFor(env, update).schema, update) // // private def buildSchemaFor[Typeclass[_], T](ctx: CaseClass[Typeclass, T], // paramSchema: Schema, // update: SchemaUpdate): SchemaFor[T] = { // def buildSchema(namespaceUpdate: Option[String]): Schema = { // val annotationExtractor = new AnnotationExtractors(ctx.annotations) // taking over @AvroFixed and the like // // val nameExtractor = NameExtractor(ctx.typeName, ctx.annotations) // val namespace = namespaceUpdate.getOrElse(nameExtractor.namespace) // val name = nameExtractor.name // // // if the class is a value type, then we need to use the schema for the single field inside the type // // in other words, if we have `case class Foo(str:String)` then this just acts like a string // // if we have a value type AND @AvroFixed is present on the class, then we simply return a schema of type fixed // // annotationExtractor.fixed match { // case Some(size) => // val builder = // SchemaBuilder // .fixed(name) // .doc(annotationExtractor.doc.orNull) // .namespace(namespace) // .aliases(annotationExtractor.aliases: _*) // annotationExtractor.props.foreach { case (k, v) => builder.prop(k, v) } // builder.size(size) // case None => paramSchema // } // } // update match { // case FullSchemaUpdate(s) => s.forType[T] // case NamespaceUpdate(ns) => SchemaFor(buildSchema(Some(ns)), DefaultFieldMapper).forType[T] // case NoUpdate => SchemaFor(buildSchema(None), DefaultFieldMapper).forType[T] // } // } // // private def fieldUpdate[Typeclass[_], T](ctx: CaseClass[Typeclass, T]): SchemaUpdate = { // val annotationExtractor = new AnnotationExtractors(ctx.annotations) // (annotationExtractor.fixed, annotationExtractor.namespace) match { // case (Some(size), namespace) => // val nameExtractor = NameExtractor(ctx.typeName, ctx.annotations) // val name = nameExtractor.name // val ns = namespace.getOrElse(nameExtractor.namespace) // FullSchemaUpdate(SchemaFor(SchemaBuilder.fixed(name).namespace(ns).size(size))) // case (_, Some(ns)) => NamespaceUpdate(ns) // case _ => NoUpdate // } // } // // class FieldEncoder[T](p: Param[Encoder, T]) { // // An encoder for a value type just needs to pass through the given value into an encoder // // for the backing type. At runtime, the value type class won't exist, and the input // // will be an instance of whatever the backing field of the value class was defined to be. // // In other words, if you had a value type `case class Foo(str :String)` then the value // // avro expects is a string, not a record of Foo, so the encoder for Foo should just encode // // the underlying string // // class ValueEncoder(encoder: Encoder[p.PType], val schemaFor: SchemaFor[T]) { // def encodeValue(value: T): AnyRef = encoder.encode(p.dereference(value)) // } // // def apply(ctx: CaseClass[Encoder, T], env: DefinitionEnvironment[Encoder], update: SchemaUpdate) = { // val encoder = p.typeclass.resolveEncoder(env, fieldUpdate(ctx)) // val schemaFor = buildSchemaFor(ctx, encoder.schemaFor.schema, update) // new ValueEncoder(encoder, schemaFor) // } // } // // class FieldDecoder[T](p: Param[Decoder, T]) { // class ValueDecoder(decoder: Decoder[p.PType], val schemaFor: SchemaFor[T]) { // def decodeValue(value: Any): Any = decoder.decode(value) // } // // def apply(ctx: CaseClass[Decoder, T], env: DefinitionEnvironment[Decoder], update: SchemaUpdate) = { // val decoder = p.typeclass.resolveDecoder(env, fieldUpdate(ctx)) // val schemaFor = buildSchemaFor(ctx, decoder.schemaFor.schema, update) // new ValueDecoder(decoder, schemaFor) // } // } //}
sksamuel/avro4s
avro4s-core/src/main/scala/com/sksamuel/avro4s/ValueTypes.scala
Scala
apache-2.0
6,198
/* * Copyright 2015 Stephan Rehfeld * * 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 test.scaladelray.texture import org.scalatest.FunSpec import scaladelray.texture.{TexCoord2D, ChessboardTexture} import scaladelray.Color class ChessboardTextureSpec extends FunSpec { describe( "A ChessboardTexture" ) { it( "should return the colors black and white according to the number of configured changes.") { for( x <- 1 to 10; y <- 1 to 10 ) { val t = ChessboardTexture( x, y ) val stepSizeU = 0.5 / x val stepSizeV = 0.5 / y val startU = stepSizeU / 2.0 val startV = stepSizeV / 2.0 for( u <- 0 to x*2; v <- 0 to y*2 ) { val tc = TexCoord2D( startU + (u*stepSizeU), startV + (v*stepSizeV) ) val c = t( tc ) val cr = if( (u+v) % 2 == 0 ) Color( 0, 0, 0 ) else Color( 1, 1, 1 ) assert( c == cr ) } } } } }
stephan-rehfeld/scaladelray
src/test/scala/test/scaladelray/texture/ChessboardTextureSpec.scala
Scala
apache-2.0
1,445
/* * 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.columnar import java.nio.{ByteBuffer, ByteOrder} import scala.annotation.tailrec import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions.{UnsafeArrayData, UnsafeMapData, UnsafeRow} import org.apache.spark.sql.errors.QueryExecutionErrors import org.apache.spark.sql.execution.columnar.compression.CompressibleColumnAccessor import org.apache.spark.sql.execution.vectorized.WritableColumnVector import org.apache.spark.sql.types._ import org.apache.spark.unsafe.types.CalendarInterval /** * An `Iterator` like trait used to extract values from columnar byte buffer. When a value is * extracted from the buffer, instead of directly returning it, the value is set into some field of * a [[InternalRow]]. In this way, boxing cost can be avoided by leveraging the setter methods * for primitive values provided by [[InternalRow]]. */ private[columnar] trait ColumnAccessor { initialize() protected def initialize(): Unit def hasNext: Boolean def extractTo(row: InternalRow, ordinal: Int): Unit protected def underlyingBuffer: ByteBuffer } private[columnar] abstract class BasicColumnAccessor[JvmType]( protected val buffer: ByteBuffer, protected val columnType: ColumnType[JvmType]) extends ColumnAccessor { protected def initialize(): Unit = {} override def hasNext: Boolean = buffer.hasRemaining override def extractTo(row: InternalRow, ordinal: Int): Unit = { extractSingle(row, ordinal) } def extractSingle(row: InternalRow, ordinal: Int): Unit = { columnType.extract(buffer, row, ordinal) } protected def underlyingBuffer = buffer } private[columnar] class NullColumnAccessor(buffer: ByteBuffer) extends BasicColumnAccessor[Any](buffer, NULL) with NullableColumnAccessor private[columnar] abstract class NativeColumnAccessor[T <: AtomicType]( override protected val buffer: ByteBuffer, override protected val columnType: NativeColumnType[T]) extends BasicColumnAccessor(buffer, columnType) with NullableColumnAccessor with CompressibleColumnAccessor[T] private[columnar] class BooleanColumnAccessor(buffer: ByteBuffer) extends NativeColumnAccessor(buffer, BOOLEAN) private[columnar] class ByteColumnAccessor(buffer: ByteBuffer) extends NativeColumnAccessor(buffer, BYTE) private[columnar] class ShortColumnAccessor(buffer: ByteBuffer) extends NativeColumnAccessor(buffer, SHORT) private[columnar] class IntColumnAccessor(buffer: ByteBuffer) extends NativeColumnAccessor(buffer, INT) private[columnar] class LongColumnAccessor(buffer: ByteBuffer) extends NativeColumnAccessor(buffer, LONG) private[columnar] class FloatColumnAccessor(buffer: ByteBuffer) extends NativeColumnAccessor(buffer, FLOAT) private[columnar] class DoubleColumnAccessor(buffer: ByteBuffer) extends NativeColumnAccessor(buffer, DOUBLE) private[columnar] class StringColumnAccessor(buffer: ByteBuffer) extends NativeColumnAccessor(buffer, STRING) private[columnar] class BinaryColumnAccessor(buffer: ByteBuffer) extends BasicColumnAccessor[Array[Byte]](buffer, BINARY) with NullableColumnAccessor private[columnar] class IntervalColumnAccessor(buffer: ByteBuffer) extends BasicColumnAccessor[CalendarInterval](buffer, CALENDAR_INTERVAL) with NullableColumnAccessor private[columnar] class CompactDecimalColumnAccessor(buffer: ByteBuffer, dataType: DecimalType) extends NativeColumnAccessor(buffer, COMPACT_DECIMAL(dataType)) private[columnar] class DecimalColumnAccessor(buffer: ByteBuffer, dataType: DecimalType) extends BasicColumnAccessor[Decimal](buffer, LARGE_DECIMAL(dataType)) with NullableColumnAccessor private[columnar] class StructColumnAccessor(buffer: ByteBuffer, dataType: StructType) extends BasicColumnAccessor[UnsafeRow](buffer, STRUCT(dataType)) with NullableColumnAccessor private[columnar] class ArrayColumnAccessor(buffer: ByteBuffer, dataType: ArrayType) extends BasicColumnAccessor[UnsafeArrayData](buffer, ARRAY(dataType)) with NullableColumnAccessor private[columnar] class MapColumnAccessor(buffer: ByteBuffer, dataType: MapType) extends BasicColumnAccessor[UnsafeMapData](buffer, MAP(dataType)) with NullableColumnAccessor private[sql] object ColumnAccessor { @tailrec def apply(dataType: DataType, buffer: ByteBuffer): ColumnAccessor = { val buf = buffer.order(ByteOrder.nativeOrder) dataType match { case NullType => new NullColumnAccessor(buf) case BooleanType => new BooleanColumnAccessor(buf) case ByteType => new ByteColumnAccessor(buf) case ShortType => new ShortColumnAccessor(buf) case IntegerType | DateType | _: YearMonthIntervalType => new IntColumnAccessor(buf) case LongType | TimestampType | _: DayTimeIntervalType => new LongColumnAccessor(buf) case FloatType => new FloatColumnAccessor(buf) case DoubleType => new DoubleColumnAccessor(buf) case StringType => new StringColumnAccessor(buf) case BinaryType => new BinaryColumnAccessor(buf) case dt: DecimalType if dt.precision <= Decimal.MAX_LONG_DIGITS => new CompactDecimalColumnAccessor(buf, dt) case dt: DecimalType => new DecimalColumnAccessor(buf, dt) case struct: StructType => new StructColumnAccessor(buf, struct) case array: ArrayType => new ArrayColumnAccessor(buf, array) case map: MapType => new MapColumnAccessor(buf, map) case udt: UserDefinedType[_] => ColumnAccessor(udt.sqlType, buffer) case other => throw QueryExecutionErrors.notSupportTypeError(other) } } def decompress(columnAccessor: ColumnAccessor, columnVector: WritableColumnVector, numRows: Int): Unit = { columnAccessor match { case nativeAccessor: NativeColumnAccessor[_] => nativeAccessor.decompress(columnVector, numRows) case _ => throw QueryExecutionErrors.notSupportNonPrimitiveTypeError() } } def decompress( array: Array[Byte], columnVector: WritableColumnVector, dataType: DataType, numRows: Int): Unit = { val byteBuffer = ByteBuffer.wrap(array) val columnAccessor = ColumnAccessor(dataType, byteBuffer) decompress(columnAccessor, columnVector, numRows) } }
vinodkc/spark
sql/core/src/main/scala/org/apache/spark/sql/execution/columnar/ColumnAccessor.scala
Scala
apache-2.0
7,035
package io.gatling.amqp.check import io.gatling.core.check.extractor.xpath.{ JdkXPathExtractorFactory, SaxonXPathExtractorFactory } import io.gatling.core.session.Expression // TODO: use Expression trait AmqpCheckSupport { // def simpleCheck = AmqpSimpleCheck // def xpath(expression: Expression[String], namespaces: List[(String, String)] = Nil)(implicit saxonXPathExtractorFactory: SaxonXPathExtractorFactory, jdkXPathExtractorFactory: JdkXPathExtractorFactory) = // AmqpXPathCheckBuilder.xpath(expression, namespaces) }
maiha/gatling-amqp
src/main/scala/io/gatling/amqp/check/AmqpCheckSupport.scala
Scala
mit
532
import scala.reflect.runtime.{ universe => ru } object Test extends dotty.runtime.LegacyApp { trait FormTrait { val runtimeMirror = ru.runtimeMirror(this.getClass.getClassLoader) val instanceMirror = runtimeMirror.reflect(this) val members = instanceMirror.symbol.typeSignature.members def fields = members.filter(_.typeSignature <:< ru.typeOf[Int]) } val f = () => { class Form1 extends FormTrait { val f1 = 5 } val form1 = new Form1 println(form1.fields) val form2 = new FormTrait { val g1 = new Form1 } form2.g1 // comment this line in order to make the test pass () } val g = () => { // Reported as SI-8195, same root cause trait Form { private val runtimeMirror = ru.runtimeMirror(this.getClass.getClassLoader) private val instanceMirror = runtimeMirror.reflect(this) private val members = instanceMirror.symbol.typeSignature.members } val f1 = new Form { val a = 1 } val f2 = new Form { val b = f1.a } } f() g() }
folone/dotty
tests/pending/run/t8196.scala
Scala
bsd-3-clause
1,080
/*********************************************************************** * 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.utils.geometry sealed trait GeometryPrecision object GeometryPrecision { case object FullPrecision extends GeometryPrecision /** * Precision for serialized geometries * * Precision is the number of base-10 decimal places stored. A positive precision implies retaining * information to the right of the decimal place, while a negative precision implies rounding up to * the left of the decimal place * * See https://github.com/TWKB/Specification/blob/master/twkb.md#type--precision * * If precision exceeds the max precision for TWKB serialization, full double serialization will * be used instead * * @param xy 4-bit signed integer precision for the x and y dimensions * for lat/lon, a precision of 6 is about 10cm * @param z 3-bit unsigned integer precision for the z dimension (if used) * for meters, precision of 1 is 10cm * @param m 3-bit unsigned integer precision for the z dimension (if used) * for milliseconds, precision of 0 is 1ms */ case class TwkbPrecision(xy: Byte = 6, z: Byte = 1, m: Byte = 0) extends GeometryPrecision { require(xy < 8 && xy > -8 && z < 8 && z > -1 && m < 8 && m > -1, s"Invalid TWKB precision: $xy,$z,$m") } }
aheyne/geomesa
geomesa-utils/src/main/scala/org/locationtech/geomesa/utils/geometry/GeometryPrecision.scala
Scala
apache-2.0
1,759
package com.seanshubin.uptodate.logic case class SummaryReport(totalArtifacts: Int, artifactsToUpgrade: Int, notFound: Int, apply: Int, ignore: Int, alreadyUpToDateCount: Int, updatesWereApplied: Boolean)
SeanShubin/up-to-date
logic/src/main/scala/com/seanshubin/uptodate/logic/SummaryReport.scala
Scala
unlicense
356
package talos import scala.language.implicitConversions import scala.reflect.macros.blackbox import scala.language.experimental.macros trait DefaultConstraints { def constraint[T >: Null](fn: T => Constraint[T]): Constraint[T] = fn(null) implicit class ConstraintOperators[T](self: Constraint[T]) { def &&(other: Constraint[T]): Constraint[T] = AndConstraint(self, other) def ||(other: Constraint[T]): Constraint[T] = OrConstraint(self, other) } implicit def toStringWrapper[T](value: String): StringWrapper[T] = macro DefaultConstraintsImpl.toStringWrapper[T] implicit def toNumericWrapper[T, N](value: N)(implicit ev: Numeric[N]): NumericWrapper[T, N] = macro DefaultConstraintsImpl.toNumericWrapper[T, N] implicit def toAnyRefWrapper[T, U](value: U): AnyRefWrapper[T, U] = macro DefaultConstraintsImpl.toAnyRefWrapper[T, U] } object DefaultConstraints extends DefaultConstraints case class StringWrapper[T](memberName: String) { def isRequired: Constraint[T] = NotEmptyConstraint(memberName) def pattern(regex: String): Constraint[T] = PatternConstraint(memberName, regex) def minLength(minLength: Int): Constraint[T] = MinLengthConstraint(memberName, minLength) def maxLength(maxLength: Int): Constraint[T] = MaxLengthConstraint(memberName, maxLength) } case class NumericWrapper[T, N: Numeric](memberName: String) { def isInRange(min: N, max: N, step: N): Constraint[T] = RangeConstraint(memberName, Some(min), Some(max), Some(step)) def isInRange(min: N, max: N): Constraint[T] = RangeConstraint(memberName, Some(min), Some(max), None) def minValue(min: N): Constraint[T] = RangeConstraint(memberName, Some(min), None, None) def maxValue(max: N): Constraint[T] = RangeConstraint(memberName, None, Some(max), None) } case class AnyRefWrapper[T, U](memberName: String) { def isValid(implicit c: Constraint[U]): Constraint[T] = RefConstraint(memberName, c) } class DefaultConstraintsImpl(val c: blackbox.Context) { import c.universe._ def toStringWrapper[T: c.WeakTypeTag](value: c.Tree): c.Tree = { val q"$obj.$memberName" = value q"StringWrapper(${memberName.decodedName.toString})" } def toNumericWrapper[T: c.WeakTypeTag, N: c.WeakTypeTag](value: c.Tree)(ev: c.Tree): c.Tree = { val q"$obj.$memberName" = value q"NumericWrapper(${memberName.decodedName.toString})" } def toAnyRefWrapper[T: c.WeakTypeTag, U: c.WeakTypeTag](value: c.Tree): c.Tree = { val q"$obj.$memberName" = value q"AnyRefWrapper(${memberName.decodedName.toString})" } }
daniel-uzunu/talos
core/src/main/scala/talos/DefaultConstraints.scala
Scala
mit
2,541
package org.genericConfig.admin.shared.user import org.genericConfig.admin.shared.common.ErrorDTO import play.api.libs.functional.syntax._ import play.api.libs.json.{Format, JsPath} case class UserResultDTO( userId: Option[String], username : Option[String], errors : Option[List[ErrorDTO]] ) object UserResultDTO { implicit val format: Format[UserResultDTO] = ( (JsPath \ "userId").format(Format.optionWithNull[String]) and (JsPath \ "username").format(Format.optionWithNull[String]) and (JsPath \ "errors").format(Format.optionWithNull[List[ErrorDTO]]) )(UserResultDTO.apply, unlift(UserResultDTO.unapply)) }
gennadij/admin
shared/src/main/scala/org/genericConfig/admin/shared/user/UserResultDTO.scala
Scala
apache-2.0
720
package build import java.io.{File => JFile} import java.util.UUID import scala.io.Codec import models._ import settings.Global import dao.util.FileHelper import org.apache.commons.io.{FilenameUtils, FileUtils} import org.apache.commons.lang3.StringEscapeUtils sealed trait DocTypeBuilder { def supportedFileExtensions: Array[String] def buildDocument(project: Project, version: String, document: JFile, filename: String, relativePath: String): Unit } trait MultipleDocTypesBuilder extends AbstractDocsBuilder with DocTypeBuilder { self: DirectoryHandler with RepositoryService with DocsIndexer with DocTypeBuilder => override def supportedFileExtensions = MarkdownDocsBuilder.supportedFileExtensions ++ ReTextDocsBuilder.supportedFileExtensions override def buildDocument(project: Project, version: String, document: JFile, filename: String, relativePath: String): Unit = { FilenameUtils.getExtension(filename) match { case "md" => MarkdownDocsBuilder.buildDocument(project, version, document, filename, relativePath) case "markdown" => MarkdownDocsBuilder.buildDocument(project, version, document, filename, relativePath) case "rst" => ReTextDocsBuilder.buildDocument(project, version, document, filename, relativePath) } } } object MarkdownDocsBuilder extends DocTypeBuilder { import eu.henkelmann.actuarius.ActuariusTransformer private val transformer = new ActuariusTransformer() override def supportedFileExtensions: Array[String] = Array("md", "markdown") private val Header = """<h[1-6]>(.*)</h[1-6]>""".r override def buildDocument(project: Project, version: String, document: JFile, filename: String, relativePath: String): Unit = { val htmlContent = transformer(FileUtils.readFileToString(document, "UTF-8")) val fileTitle = StringEscapeUtils.unescapeXml(Header.findFirstMatchIn(htmlContent).map(_.group(1)).getOrElse(filename)) FileHelper.getOrCreateContent(htmlContent) { contentGuid => Global.files.create(UUID.randomUUID().toString, project, version, relativePath, filename, fileTitle, contentGuid) } } } object ReTextDocsBuilder extends DocTypeBuilder { import laika.api.{Render, Parse} import laika.parse.rst.ReStructuredText import laika.render.HTML import laika.tree.Documents.Document import laika.tree.Elements.Text override def supportedFileExtensions: Array[String] = Array("rst") implicit val codec = Codec.UTF8 override def buildDocument(project: Project, version: String, document: JFile, filename: String, relativePath: String): Unit = { val htmlDoc: Document = Parse as ReStructuredText fromFile document val fileTitle = htmlDoc.title.find(_.isInstanceOf[Text]).map(_.asInstanceOf[Text].content).get val htmlContent = Render as HTML from htmlDoc toString() FileHelper.getOrCreateContent(htmlContent) { contentGuid => Global.files.create(UUID.randomUUID().toString, project, version, relativePath, filename, fileTitle, contentGuid) } } }
grahamar/Giles
app/build/DocTypeBuilders.scala
Scala
apache-2.0
3,033
package org.scalaide.core.internal.jdt.model import java.util.{ HashMap => JHashMap } import java.util.{ Map => JMap } import org.eclipse.core.resources.IFile import org.eclipse.core.resources.IResource import org.eclipse.core.runtime.IProgressMonitor import org.eclipse.jdt.core.IBuffer import org.eclipse.jdt.core.ICompilationUnit import org.eclipse.jdt.core.IJavaElement import org.eclipse.jdt.core.IType import org.eclipse.jdt.core.WorkingCopyOwner import org.eclipse.jdt.core.compiler.IProblem import org.eclipse.jdt.internal.core.util.HandleFactory import org.eclipse.jdt.internal.core.BufferManager import org.eclipse.jdt.internal.core.{ CompilationUnit => JDTCompilationUnit } import org.eclipse.jdt.internal.core.OpenableElementInfo import org.eclipse.jdt.internal.core.PackageFragment import org.eclipse.jdt.internal.corext.util.JavaModelUtil import org.eclipse.swt.widgets.Display import scala.tools.nsc.io.AbstractFile import scala.tools.nsc.io.VirtualFile import scala.tools.eclipse.contribution.weaving.jdt.IScalaSourceFile import org.scalaide.core.resources.EclipseFile import org.eclipse.jdt.core.compiler.CharOperation import scala.tools.nsc.interactive.Response import org.scalaide.core.extensions.SourceFileProvider import org.eclipse.jdt.core.JavaModelException import org.scalaide.core.compiler.InteractiveCompilationUnit import org.eclipse.core.runtime.IPath import org.eclipse.core.runtime.NullProgressMonitor import scala.util.control.Exception import org.eclipse.core.runtime.CoreException import org.scalaide.core.compiler.ScalaCompilationProblem class ScalaSourceFileProvider extends SourceFileProvider { override def createFrom(path: IPath): Option[InteractiveCompilationUnit] = ScalaSourceFile.createFromPath(path.toString) } object ScalaSourceFile { /** Considering [[org.eclipse.jdt.internal.core.util.HandleFactory]] isn't thread-safe, and because * `ScalaSourceFile#createFromPath` can be called concurrently from different threads, using a * `ThreadLocal` ensures that a `HandleFactory` instance is never shared across threads. */ private val handleFactory: ThreadLocal[HandleFactory] = new ThreadLocal[HandleFactory] { override protected def initialValue(): HandleFactory = new HandleFactory } /** Creates a Scala source file handle if the given resource path points to a scala source. * The resource path is a path to a Scala source file in the workbench (e.g. /Proj/a/b/c/Foo.scala). * * @note This assumes that the resource path is the toString() of an `IPath`. * * @param path Is a path to a Scala source file in the workbench. */ def createFromPath(path: String) : Option[ScalaSourceFile] = { if (!path.endsWith(".scala")) None else { // Always `null` because `handleFactory.createOpenable` is only called to open source files, and the `scope` is not needed for this. val unusedScope = null val source = handleFactory.get().createOpenable(path, unusedScope) source match { case ssf : ScalaSourceFile => Some(ssf) case _ => None } } } } class ScalaSourceFile(fragment : PackageFragment, elementName: String, workingCopyOwner : WorkingCopyOwner) extends JDTCompilationUnit(fragment, elementName, workingCopyOwner) with ScalaCompilationUnit with IScalaSourceFile { override def getMainTypeName : Array[Char] = getElementName.substring(0, getElementName.length - ".scala".length).toCharArray() /** Schedule this source file for reconciliation. Add the file to * the loaded files managed by the presentation compiler. */ override def initialReconcile(): Response[Unit] = { val reloaded = super.initialReconcile() this.reconcile( ICompilationUnit.NO_AST, false /* don't force problem detection */, null /* use primary owner */, null /* no progress monitor */); reloaded } /* getProblems should be reserved for a Java context, @see getProblems */ def reconcile(newContents: String): List[ScalaCompilationProblem] = { super.forceReconcile() } /** * We cut short this call since reconciliation is performed through the usual mechanism in the * editor. Calls arriving here come from the JDT, for instance from the breadcrumb view, and end * up doing expensive computation on the UI thread. * * @see #1002412 */ override def reconcile( astLevel : Int, reconcileFlags : Int, workingCopyOwner : WorkingCopyOwner, monitor : IProgressMonitor) : org.eclipse.jdt.core.dom.CompilationUnit = { null } override def makeConsistent( astLevel : Int, resolveBindings : Boolean, reconcileFlags : Int, problems : JHashMap[_,_], monitor : IProgressMonitor) : org.eclipse.jdt.core.dom.CompilationUnit = { // don't rerun this expensive operation unless necessary if (!isConsistent()) { if (astLevel != ICompilationUnit.NO_AST && resolveBindings) { val info = createElementInfo.asInstanceOf[OpenableElementInfo] openWhenClosed(info, true, monitor) } else logger.info(s"Skipped `makeConsistent` with resolveBindings: $resolveBindings and astLevel: $astLevel") } null } override def codeSelect(offset : Int, length : Int, workingCopyOwner : WorkingCopyOwner) : Array[IJavaElement] = codeSelect(this, offset, length, workingCopyOwner) override lazy val file : AbstractFile = { val res = try { getCorrespondingResource } catch { case _: JavaModelException => null } res match { case f : IFile => new EclipseFile(f) case _ => new VirtualFile(getElementName, getPath.toString) } } /** Implementing the weaving interface requires to return `null` for an empty array. */ override def getProblems: Array[IProblem] = { val probs = currentProblems() if (probs.isEmpty) null else probs.toArray } override def getType(name : String) : IType = new LazyToplevelClass(this, name) override def getContents() : Array[Char] = { // in the following case, super#getContents() logs an exception for no good reason if (getBufferManager().getBuffer(this) == null && getResource().getLocation() == null && getResource().getLocationURI() == null) { return CharOperation.NO_CHAR } Exception.failAsValue(classOf[CoreException])(CharOperation.NO_CHAR) { super.getContents() } } /** Makes sure {{{this}}} source is not in the ignore buffer of the compiler and ask the compiler to reload it. */ final def forceReload(): Unit = scalaProject.presentationCompiler { compiler => compiler.askToDoFirst(this) reload() } /** Ask the compiler to reload {{{this}}} source. */ final def reload(): Unit = scalaProject.presentationCompiler { _.askReload(this, lastSourceMap().sourceFile) } /** Ask the compiler to discard {{{this}}} source. */ final def discard(): Unit = scalaProject.presentationCompiler { _.discardCompilationUnit(this) } }
romanowski/scala-ide
org.scala-ide.sdt.core/src/org/scalaide/core/internal/jdt/model/ScalaSourceFile.scala
Scala
bsd-3-clause
6,951
package play.json.extra import scala.language.experimental.macros import org.cvogt.scala.constraint.boolean.! import scala.reflect.macros.blackbox import play.api.libs.json._ import collection.immutable.ListMap sealed trait AdtEncoder object AdtEncoder{ trait TypeTagAdtEncoder extends AdtEncoder{ import scala.reflect.runtime.universe.TypeTag def extractClassJson[T: TypeTag](json: JsObject): Option[JsObject] def encodeObject[T: TypeTag]: JsValue def encodeClassType[T: TypeTag](json: JsObject): JsObject } trait ClassTagAdtEncoder extends AdtEncoder{ import scala.reflect.ClassTag def extractClassJson[T: ClassTag](json: JsObject): Option[JsObject] def encodeObject[T: ClassTag]: JsValue def encodeClassType[T: ClassTag](json: JsObject): JsObject } object TypeAsField extends ClassTagAdtEncoder{ import scala.reflect._ def extractClassJson[T: ClassTag](json: JsObject) = { Some(json).filter( _ \\ "type" == JsString(classTag[T].runtimeClass.getSimpleName) ) } def encodeObject[T: ClassTag] = { JsString(classTag[T].runtimeClass.getSimpleName.dropRight(1)) } def encodeClassType[T: ClassTag](json: JsObject) = { json ++ JsObject(Seq("type" -> JsString(classTag[T].runtimeClass.getSimpleName))) } } } private class Macros(val c: blackbox.Context){ import c.universe._ val pkg = q"_root_.play.json.extra" val pjson = q"_root_.play.api.libs.json" /** Generates a list of all known classes and traits in an inheritance tree. Includes the given class itself. Does not include subclasses of non-sealed classes and traits. TODO: move this to scala-extensions */ private def knownTransitiveSubclasses(sym: ClassSymbol): Seq[ClassSymbol] = { sym +: ( if(sym.isModuleClass){ Seq() } else { sym.knownDirectSubclasses.flatMap(s => knownTransitiveSubclasses(s.asClass)) } ).toSeq } private def caseClassFieldsTypes(tpe: Type): List[(String,String, Type)] = { val params = tpe.decls.collectFirst { case m: MethodSymbol if m.isPrimaryConstructor => m }.get.paramLists.head params.map{ field => var attrName=field.name.toTermName.decodedName.toString if(field.annotations.nonEmpty){ field.annotations.map{ annotation => annotation.tree match { case Apply(Select(New(tpe), _), List(Literal(Constant(unique)))) => if(tpe.toString().endsWith(".key")) attrName=unique.toString case extra => } } } ( field.name.toTermName.decodedName.toString, attrName, field.typeSignature) } } def formatCaseClass[T: c.WeakTypeTag]/*(ev: Tree)*/: Tree = { val T = c.weakTypeOf[T] if(!isCaseClass(T)) c.error(c.enclosingPosition, s"not a case class: $T") val (results,mkResults) = caseClassFieldsTypes(T).map{ case (k,key, t) => val name = TermName(c.freshName) if(t.toString.startsWith("Option")){ val subtype=t.typeArgs.head (name, q"""val $name: JsResult[$t] = { val path = (JsPath() \\ $key) val resolved = path.asSingleJsResult(json) val result = (json \\ $key).validate[$subtype].repath(path) if(resolved.isSuccess && result.isSuccess){ result.map(v=> Some(v)) } else { JsSuccess[$t](None) } } """) } else { (name, q"""val $name: JsResult[$t] = { val path = (JsPath() \\ $key) val resolved = path.asSingleJsResult(json) val result = (json \\ $key).validate[$t].repath(path) (resolved,result) match { case (_,result:JsSuccess[_]) => result case _ => resolved.flatMap(_ => result) } } """) } }.unzip val jsonFields = caseClassFieldsTypes(T).map{ case (k,key, _) => q"""${Constant(key)} -> Json.toJson(obj.${TermName(k)})""" } val r=q""" { import $pjson._ new Format[$T]{ def reads(json: JsValue) = { ..$mkResults val errors = Seq[JsResult[_]](..$results).collect{ case JsError(values) => values }.flatten if(errors.isEmpty){ JsSuccess(new $T(..${results.map(r => q"$r.get")})) } else JsError(errors) } def writes(obj: $T) = JsObject(Seq(..$jsonFields).filterNot(_._2 == JsNull)) } } """ // println(r) r } def formatAdt[T: c.WeakTypeTag](encoder: Tree): Tree = { val T = c.weakTypeOf[T].typeSymbol.asClass val allSubs = knownTransitiveSubclasses(T) allSubs.foreach{ sym => lazy val modifiers = sym.toString.split(" ").dropRight(1).mkString if(!sym.isFinal && !sym.isSealed && !sym.isModuleClass ){ c.error(c.enclosingPosition, s"required sealed or final, found $modifiers: ${sym.fullName}") } if(!sym.isCaseClass && !sym.isAbstract){ c.error(c.enclosingPosition, s"required abstract, trait or case class, found $modifiers: ${sym.fullName}") } } val subs = allSubs.filterNot(_.isAbstract) val isModuleJson = (sym: ClassSymbol) => q""" (json: JsValue) => { Some(json).filter{ _ == $encoder.encodeObject[$sym] } } """ val writes = subs.map{ sym => if(sym.isModuleClass){ cq"`${TermName(sym.name.decodedName.toString)}` => $encoder.encodeObject[$sym]"// } else { assert(sym.isCaseClass) cq"""obj: $sym => { $encoder.encodeClassType[$sym]( Json.toJson[$sym](obj).as[JsObject] ) } """ } } val (extractors, reads) = subs.map{ sym => val name = TermName(c.freshName) ( { val extractor = if(sym.isModuleClass){ q""" (json: JsValue) => ${isModuleJson(sym)}(json).map(_ => $pjson.JsSuccess(${sym.asClass.module})) """ } else { assert(sym.isCaseClass) q""" (json: JsValue) => $encoder.extractClassJson[${sym}](json.as[JsObject]) .map($pjson.Json.fromJson[$sym](_)) """ } q"object $name extends $pkg.Extractor($extractor)" }, cq"""$name(json) => json""" ) }.unzip val t = q""" { ..$extractors new Format[$T]{ def reads(json: $pjson.JsValue) = json match {case ..$reads} def writes(obj: $T) = obj match {case ..$writes} } } """ //println(t) t } protected def isCaseClass(tpe: Type) = tpe.typeSymbol.isClass && tpe.typeSymbol.asClass.isCaseClass } trait ImplicitCaseClassFormatDefault{ implicit def formatCaseClass[T] // (implicit ev: ![Format[T]]) : Format[T] = macro Macros.formatCaseClass[T] } object implicits extends ImplicitCaseClassFormatDefault class Extractor[T,R](f: T => Option[R]){ def unapply(arg: T): Option[R] = f(arg) } object Jsonx{ /** Generates a PlayJson Format[T] for a case class T with any number of fields (>22 included) */ def formatCaseClass[T] // (implicit ev: ![Format[T]]) : Format[T] = macro Macros.formatCaseClass[T] /** Generates a PlayJson Format[T] for a sealed trait that only has case object children */ def formatAdt[T](encoder: AdtEncoder): Format[T] = macro Macros.formatAdt[T] }
aparo/scalajs-supler
supler/shared/src/main/scala/play/json/extra/extra.scala
Scala
apache-2.0
7,686
/* * ____ ____ _____ ____ ___ ____ * | _ \\ | _ \\ | ____| / ___| / _/ / ___| Precog (R) * | |_) | | |_) | | _| | | | | /| | | _ Advanced Analytics Engine for NoSQL Data * | __/ | _ < | |___ | |___ |/ _| | | |_| | Copyright (C) 2010 - 2013 SlamData, Inc. * |_| |_| \\_\\ |_____| \\____| /__/ \\____| All Rights Reserved. * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version * 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this * program. If not, see <http://www.gnu.org/licenses/>. * */ package com.precog package yggdrasil package table import scala.util.Random import com.precog.common._ import com.precog.util.VectorCase import com.precog.common.security._ import org.specs2.mutable._ import org.specs2.ScalaCheck import org.scalacheck._ class SliceSpec extends Specification with ArbitrarySlice with ScalaCheck { implicit def cValueOrdering: Ordering[CValue] = CValue.CValueOrder.toScalaOrdering implicit def listOrdering[A](implicit ord0: Ordering[A]) = new Ordering[List[A]] { def compare(a: List[A], b: List[A]): Int = (a zip b) map ((ord0.compare _).tupled) find (_ != 0) getOrElse (a.length - b.length) } def extractCValues(colGroups: List[List[Column]], row: Int): List[CValue] = { colGroups map { _ find (_.isDefinedAt(row)) map (_.cValue(row)) getOrElse CUndefined } } def columnsByCPath(slice: Slice): Map[CPath, List[Column]] = { val byCPath = slice.columns.groupBy(_._1.selector) byCPath.mapValues(_.map(_._2).toList) } def sortableCValues(slice: Slice, cpaths: VectorCase[CPath]): List[(List[CValue], List[CValue])] = { val byCPath = columnsByCPath(slice) (0 until slice.size).map({ row => (extractCValues(cpaths.map(byCPath).toList, row), extractCValues(byCPath.values.toList, row)) })(collection.breakOut) } def toCValues(slice: Slice) = sortableCValues(slice, VectorCase.empty) map (_._2) def fakeSort(slice: Slice, sortKey: VectorCase[CPath]) = sortableCValues(slice, sortKey).sortBy(_._1).map(_._2) def fakeConcat(slices: List[Slice]) = { slices.foldLeft(List.empty[List[CValue]]) { (acc, slice) => acc ++ toCValues(slice) } } def stripUndefineds(cvals: List[CValue]): Set[CValue] = (cvals filter (_ != CUndefined)).toSet // Commented out for now. sortWith is correct semantically, but it ruins // the semantics of sortBy (which uses sortWith). Need to add a global ID. //"sortBy" should { // "sort a trivial slice" in { // val slice = new Slice { // val size = 5 // val columns = Map( // ColumnRef(CPath("a"), CLong) -> new LongColumn { // def isDefinedAt(row: Int) = true // def apply(row: Int) = -row.toLong // }, // ColumnRef(CPath("b"), CLong) -> new LongColumn { // def isDefinedAt(row: Int) = true // def apply(row: Int) = row / 2 // }) // } // val sortKey = VectorCase(CPath("a")) // fakeSort(slice, sortKey) must_== toCValues(slice.sortBy(sortKey)) // } // "sort arbitrary slices" in { check { badSize: Int => // val path = Path("/") // val auth = Authorities(Set()) // val paths = Vector( // CPath("0") -> CLong, // CPath("1") -> CBoolean, // CPath("2") -> CString, // CPath("3") -> CDouble, // CPath("4") -> CNum, // CPath("5") -> CEmptyObject, // CPath("6") -> CEmptyArray, // CPath("7") -> CNum) // val pd = ProjectionDescriptor(0, paths.toList map { case (cpath, ctype) => // ColumnRef(path, cpath, ctype, auth) // }) // val size = scala.math.abs(badSize % 100).toInt // implicit def arbSlice = Arbitrary(genSlice(pd, size)) // check { slice: Slice => // for (i <- 0 to 7; j <- 0 to 7) { // val sortKey = if (i == j) { // VectorCase(paths(i)._1) // } else { // VectorCase(paths(i)._1, paths(j)._1) // } // fakeSort(slice, sortKey) must_== toCValues(slice.sortBy(sortKey)) // } // } // } } //} private def concatProjDesc = Seq( ColumnRef(CPath("0"), CLong), ColumnRef(CPath("1"), CBoolean), ColumnRef(CPath("2"), CString), ColumnRef(CPath("3"), CDouble), ColumnRef(CPath("4"), CNum), ColumnRef(CPath("5"), CEmptyObject), ColumnRef(CPath("6"), CEmptyArray), ColumnRef(CPath("7"), CNum) ) "concat" should { "concat arbitrary slices together" in { implicit def arbSlice = Arbitrary(genSlice(0, concatProjDesc, 23)) check { slices: List[Slice] => val slice = Slice.concat(slices) toCValues(slice) must_== fakeConcat(slices) } } "concat small singleton together" in { implicit def arbSlice = Arbitrary(genSlice(0, concatProjDesc, 1)) check { slices: List[Slice] => val slice = Slice.concat(slices) toCValues(slice) must_== fakeConcat(slices) } } val emptySlice = new Slice { val size = 0 val columns: Map[ColumnRef, Column] = Map.empty } "concat empty slices correctly" in { implicit def arbSlice = Arbitrary(genSlice(0, concatProjDesc, 23)) check { fullSlices: List[Slice] => val slices = fullSlices collect { case slice if Random.nextBoolean => slice case _ => emptySlice } val slice = Slice.concat(slices) toCValues(slice) must_== fakeConcat(slices) } } "concat heterogeneous slices" in { val pds = List.fill(25)(concatProjDesc filter (_ => Random.nextBoolean)) val g1 :: g2 :: gs = pds.map(genSlice(0, _, 17)) implicit val arbSlice = Arbitrary(Gen.oneOf(g1, g2, gs: _*)) check { slices: List[Slice] => val slice = Slice.concat(slices) // This is terrible, but there isn't an immediately easy way to test // without duplicating concat. toCValues(slice).map(stripUndefineds) must_== fakeConcat(slices).map(stripUndefineds) } } } }
precog/platform
yggdrasil/src/test/scala/com/precog/yggdrasil/table/SliceSpec.scala
Scala
agpl-3.0
6,582
/* * (c) Copyright 2016 Hewlett Packard Enterprise Development LP * * 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 cogdebugger.ui.fieldvisualizations.scalar import cogx.runtime.debugger.ProbedField import libcog._ import scala.swing._ import cogdebugger.ui.fieldvisualizations.{UnsupportedDimensionException, EventDrivenViewer} import org.jfree.chart.plot.{XYPlot, PlotOrientation, CombinedDomainXYPlot} import org.jfree.chart.axis.NumberAxis import org.jfree.chart.renderer.xy.StandardXYItemRenderer import org.jfree.data.xy.AbstractXYDataset import org.jfree.chart.{JFreeChart, ChartPanel} /* * Created with IntelliJ IDEA. * User: gonztobi * Date: 10/9/13 * Time: 1:13 PM */ /** A timeseries plot that shows a fixed sized history, not unlike the old * TimeseriesPlotPanel (which was renamed to StackedTimeseriesPanel). This * plot, however, uses a different dataset implementation and is better * suited for fast changing, live data. * * Like the old implementation, each point in the target field is displayed in * its own subplot, with the subplots stacked on top of each other. For fields * with more than a handful of points, this can get pretty expensive to draw. * * This version of the viewer supports up to 2D fields. * * @param fieldType A FieldType desribing the shape of the field being * visualized. * @param historySize How many time steps back the plot shows. */ class AcceleratedStackedTimeseriesPanel(fieldType: FieldType, historySize: Int) extends Panel with EventDrivenViewer { /** Supplies a default history size of 500 time steps */ def this(fieldType: FieldType) = this(fieldType, 500) /** Supplies a default history size of 500 time steps */ def this(target: ProbedField) = this(target.fieldType) private def fieldShape = fieldType.fieldShape val plot = new CombinedDomainXYPlot(new NumberAxis("history")) plot.setGap(10.0) plot.setOrientation(PlotOrientation.VERTICAL) val xAxis = plot.getDomainAxis xAxis.setLowerMargin(0) xAxis.setUpperMargin(0) val dataset = new DynamicXYDataset(fieldShape.points, historySize) // Each subplot charts a single value in the field as it evolves. val subplots = for (i <- 0 until fieldShape.points) yield { val renderer = new StandardXYItemRenderer() renderer.setBaseSeriesVisible(false) val plot = new XYPlot(dataset, null, new NumberAxis(""), renderer) renderer.setSeriesVisible(i, true, false) plot }; subplots foreach plot.add val chart = new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, false) _contents += Component.wrap(new ChartPanel(chart)) def update(src: AnyRef, data: AbstractFieldMemory, simTime: Long) { data match { case sfr: ScalarFieldReader => update(sfr, simTime) case x => throw new Exception("Expeting ScalarFieldReader; got: "+x) } } protected var lastUpdateTick = -1L protected val tmpData = new Array[Float](fieldShape.points) def update(data: ScalarFieldReader, time: Long) { data.fieldShape.dimensions match { case 0 => tmpData(0) = data.read() case 1 => val cols = data.fieldShape(0) for (c <- 0 until cols) tmpData(c) = data.read(c) case 2 => val (rows, cols) = (data.fieldShape(0), data.fieldShape(1)) for (r <- 0 until rows; c <- 0 until cols) tmpData(r * cols + c) = data.read(r, c) case x => throw new UnsupportedDimensionException(x) } val delta = time - lastUpdateTick if (delta < 0) // Sim must have reset dataset.clear() else //if (delta > 0) dataset.advanceTime(delta.toInt) dataset.appendData(tmpData) lastUpdateTick = time } } /** An XYDataset with a fixed size internal circular buffer amenable to fast * "drop oldest and append" operations. */ class DynamicXYDataset(nSeries: Int, nMoments: Int) extends AbstractXYDataset { /** The circular buffer holding chart data. */ protected val data = Array.tabulate(nSeries)(i => new Array[Float](nMoments)) protected var oldestIdx = 0 def getItemCount(series: Int): Int = data(series).size def getX(series: Int, item: Int): Number = item - nMoments + 1//translateIdx(item) + 1 - nMoments def getY(series: Int, item: Int): Number = data(series)(translateIdx(item)) def getSeriesCount: Int = data.size def getSeriesKey(series: Int): Comparable[_] = series def clear() { oldestIdx = 0 for (series <- data) java.util.Arrays.fill(series, 0f) fireDatasetChanged() } /** Controls whether dataset changed events are fired on dataset updates. */ var doNotify = true def advanceTime() { advanceTime(1) } def advanceTime(ticks: Int) { val mostRecentValues = for (i <- 0 until nSeries) yield getY(i, nMoments -1).floatValue() for (i <- 0 until nSeries) for (j <- 0 until (ticks min nMoments)) data(i)(translateIdx(j)) = mostRecentValues(i) oldestIdx = translateIdx(ticks) if (doNotify) fireDatasetChanged() } def appendData(newData: Array[Float]) { require(data.size == newData.size) for ((series, idx) <- data.zipWithIndex) series(oldestIdx) = newData(idx) oldestIdx = (oldestIdx + 1) % nMoments if (doNotify) fireDatasetChanged() } protected def translateIdx(idx: Int): Int = (oldestIdx + idx) % nMoments // (oldestIdx + idx) % nMoments match { // case x if x < 0 => x + nMoments // case x => x // } }
hpe-cct/cct-core
src/main/scala/cogdebugger/ui/fieldvisualizations/scalar/AcceleratedStackedTimeseriesPanel.scala
Scala
apache-2.0
5,960
/******************************************************************************* Copyright (c) 2012-2013, KAIST, S-Core. All rights reserved. Use is subject to license terms. This distribution may include materials developed by third parties. ******************************************************************************/ package kr.ac.kaist.jsaf.analysis.typing.domain abstract class AbsBase { def isTop(): Boolean def isBottom(): Boolean def isConcrete(): Boolean def toAbsString(): AbsString def getConcreteValueAsString(defaultString: String = ""): String = { if(isConcrete) toString else defaultString } }
daejunpark/jsaf
src/kr/ac/kaist/jsaf/analysis/typing/domain/AbsBase.scala
Scala
bsd-3-clause
649
package au.com.agiledigital.toolform.command.generate.kubernetes.minishift import java.io.{BufferedWriter, File, FileWriter} import java.nio.file.Path import au.com.agiledigital.toolform.app.ToolFormError import au.com.agiledigital.toolform.command.generate.kubernetes.DeploymentWriter.writeDeployment import au.com.agiledigital.toolform.command.generate.kubernetes.VolumeClaimWriter.writeVolumeClaim import au.com.agiledigital.toolform.command.generate.kubernetes.ServiceWriter.writeService import au.com.agiledigital.toolform.command.generate.kubernetes.minishift.GenerateMinishiftCommand.runGenerateMinishift import au.com.agiledigital.toolform.command.generate.kubernetes.minishift.RouterWriter.writeRouter import au.com.agiledigital.toolform.command.generate.{WriterContext, YamlWriter} import au.com.agiledigital.toolform.model._ import au.com.agiledigital.toolform.plugin.ToolFormGenerateCommandPlugin import au.com.agiledigital.toolform.reader.ProjectReader import au.com.agiledigital.toolform.util.DateUtil import au.com.agiledigital.toolform.version.BuildInfo import cats.data.Validated.{invalid, valid} import cats.data.Validated import cats.data.NonEmptyList import cats.implicits._ import com.monovore.decline.Opts /** * Takes an abstract project definition and outputs it a combined service/deployment Kubernetes spec in YAML format. * * For each service/resource defined in the Toolform config, a single Kubernetes service and deployment is created. * * @see https://kubernetes.io/docs/api-reference/v1.8/ */ class GenerateMinishiftCommand extends ToolFormGenerateCommandPlugin { /** * The primary class for generating Kubernetes (Minishift) config files. */ def command: Opts[Either[NonEmptyList[ToolFormError], String]] = Opts.subcommand("minishift", "generates config files for Kubernetes (Minishift) container orchestration") { (Opts.option[Path]("in-file", short = "i", metavar = "file", help = "the path to the project config file"), Opts.option[Path]("out-file", short = "o", metavar = "file", help = "the path to output the generated file(s)")) .mapN(execute) } def execute(inputFilePath: Path, outputFilePath: Path): Either[NonEmptyList[ToolFormError], String] = { val inputFile = inputFilePath.toFile val outputFile = outputFilePath.toFile if (!inputFile.exists()) { Left(NonEmptyList.of(ToolFormError(s"Input file [${inputFile}] does not exist."))) } else if (!inputFile.isFile) { Left(NonEmptyList.of(ToolFormError(s"Input file [${inputFile}] is not a valid file."))) } else if (!outputFile.getParentFile.exists()) { Left(NonEmptyList.of(ToolFormError(s"Output directory [${outputFile.getParentFile}] does not exist."))) } else { for { project <- ProjectReader.readProject(inputFile) status <- runGenerateMinishift(inputFile.getAbsolutePath, outputFile, project) } yield status } } } object GenerateMinishiftCommand extends YamlWriter { /** * The main entry point into the Kubernetes (Minishift) file generation. * * @param sourceFilePath project config input file path * @param project the abstract project definition parsed by ToolFormApp. * @return on success it returns a status message to print to the screen, otherwise it will return an * error object describing what went wrong. */ def runGenerateMinishift(sourceFilePath: String, outFile: File, project: Project): Either[NonEmptyList[ToolFormError], String] = for { validatedResources <- project.resources.values.toList.traverse(validateResource).toEither writerStatus <- writeAll(validatedResources, sourceFilePath, outFile, project) } yield writerStatus def writeAll(validResources: List[Resource], sourceFilePath: String, outFile: File, project: Project): Either[NonEmptyList[ToolFormError], String] = { val writer = new BufferedWriter(new FileWriter(outFile, false)) try { val writeFile = for { _ <- write(s"# Generated by ${BuildInfo.name} (${BuildInfo.version})") _ <- write(s"# Source file: $sourceFilePath") _ <- write(s"# Date: ${DateUtil.formattedDateString}") _ <- project.components.values.filter(shouldWriteService).toList.traverse_(writeService) _ <- validResources.filter(shouldWriteService).traverse_(writeService) _ <- validResources.filter(isDiskResourceType).traverse_((resource) => writeVolumeClaim(resource)) _ <- project.components.values.toList.traverse_((component) => writeDeployment(project, component)) _ <- validResources.filterNot(isDiskResourceType).traverse_((resource) => writeDeployment(project, resource)) _ <- project.topology.endpoints.toList.traverse_ { case (endpointId, endpoint) => writeRouter(endpointId, endpoint) } } yield () val context = WriterContext(writer) // Final state needs to be read for anything to happen because of lazy evaluation val _ = writeFile.run(context).value Right(s"Wrote configuration to [$outFile].\\nRun with `kubectl apply -f '$outFile'`") } finally { writer.close() } } def validateResource(resource: Resource): Validated[NonEmptyList[ToolFormError], Resource] = if (!isDiskResourceType(resource) && resource.image.isEmpty) invalid(NonEmptyList.of(ToolFormError(s"Image name is required for: ${resource.id}"))) else valid(resource) private def shouldWriteService(toolFormService: ToolFormService): Boolean = toolFormService.exposedPorts.nonEmpty || toolFormService.externalPorts.nonEmpty private def isDiskResourceType(resource: Resource): Boolean = resource.resourceType.nonEmpty && resource.resourceType == "disk" }
agiledigital/toolform
src/main/scala/au/com/agiledigital/toolform/command/generate/kubernetes/minishift/GenerateMinishiftCommand.scala
Scala
apache-2.0
5,760
package com.manning.androidhacks.hack050.tests import junit.framework.Assert._ import _root_.android.test.AndroidTestCase class UnitTests extends AndroidTestCase { def testPackageIsCorrect { assertEquals("com.manning.androidhacks.hack050", getContext.getPackageName) } }
ZhQYuan/50AH-code
hack034/tests/src/main/scala/UnitTests.scala
Scala
mit
280
// FilterTweets.scala // // Copyright (C) 2014 Ben Wing, The University of Texas at Austin // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////////// package opennlp.textgrounder package preprocess import scala.collection.mutable import java.text.{SimpleDateFormat, ParseException} import net.liftweb import util.argparser._ import util.collection._ import util.experiment._ import util.io.localfh import util.print._ class FilterTweetsParameters(ap: ArgParser) { var tweet_file = ap.option[String]("tweet-file", must = be_specified, help = """File containing usernames and timestamps and possibly other fields, separated by tabs.""") var output = ap.option[String]("output", must = be_specified, help = """Prefix of files to which filtered tweets are written to. There is a separate output file for each input file.""") var input = ap.multiPositional[String]("input", must = be_specified, help = """Tweet file(s) to analyze.""") } /** * An application to filter JSON-format tweets in a series of files * by a list of tweet ID's. */ object FilterTweets extends ExperimentApp("FilterTweets") { type TParam = FilterTweetsParameters def create_param_object(ap: ArgParser) = new FilterTweetsParameters(ap) /** * Convert a Twitter timestamp, e.g. "Tue Jun 05 14:31:21 +0000 2012", * into a time in milliseconds since the Epoch (Jan 1 1970, or so). */ def parse_time(timestring: String): Option[Long] = { val sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZZZ yyyy") try { sdf.parse(timestring) Some(sdf.getCalendar.getTimeInMillis) } catch { case pe: ParseException => { errprint("Error parsing date %s: %s", timestring, pe) None } } } /** * Retrieve a string along a path, checking to make sure the path * exists. */ def force_string(value: liftweb.json.JValue, fields: String*): String = { var fieldval = value var path = List[String]() for (field <- fields) { path :+= field fieldval \\= field if (fieldval == liftweb.json.JNothing) { val fieldpath = path mkString "." // errprint("Can't find field path %s in tweet", fieldpath) return "" } } val values = fieldval.values if (values == null) { // errprint("Null value from path %s", fields mkString ".") "" } else fieldval.values.toString } def run_program(args: Array[String]) = { def parse_line(line: String): Option[(String, Long)] = { val parsed = try { liftweb.json.parse(line) } catch { case jpe: liftweb.json.JsonParser.ParseException => { errprint("Error parsing line: %s", line) jpe.printStackTrace return None } } val user = force_string(parsed, "user", "screen_name") val ts = force_string(parsed, "created_at") if (ts == "") None else { val maybe_timestamp = parse_time(ts) maybe_timestamp.map { timestamp => (user, timestamp) } } } // Set of usernames and timestamps to filter on val names_times = setmap[String, Long]() errprint("Loading usernames and timestamps from %s...", params.tweet_file) for (line <- localfh.openr(params.tweet_file)) { val fields = line.split("\\t") names_times(fields(0)) += fields(1).toLong } for (file <- params.input) { errprint("Processing %s...", file) val (lines, comptype, uncompname) = localfh.openr_with_compression_info(file) val outfile = localfh.openw("%s%s" format (params.output, uncompname), compression = comptype) for (line <- lines) { parse_line(line) match { case Some((user, timestamp)) => { if (names_times(user) contains (timestamp / 1000)) outfile.println(line) } case None => () } } outfile.close() } 0 } }
utcompling/textgrounder
src/main/scala/opennlp/textgrounder/preprocess/FilterTweets.scala
Scala
apache-2.0
4,548
package com.scalaAsm.x86 package Instructions package System // Description: Store Task Register // Category: general trait STR extends InstructionDefinition { val mnemonic = "STR" } object STR extends OneOperand[STR] with STRImpl trait STRImpl extends STR { implicit object _0 extends OneOp[m16] { val opcode: TwoOpcodes = (0x0F, 0x00) /+ 1 val format = RmFormat override def hasImplicitOperand = true } implicit object _1 extends OneOp[r16] { val opcode: TwoOpcodes = (0x0F, 0x00) /+ 1 val format = RegFormat override def hasImplicitOperand = true } implicit object _2 extends OneOp[r32] { val opcode: TwoOpcodes = (0x0F, 0x00) /+ 1 val format = RegFormat override def hasImplicitOperand = true } implicit object _3 extends OneOp[r64] { val opcode: TwoOpcodes = (0x0F, 0x00) /+ 1 override def prefix = REX.W(true) val format = RegFormat override def hasImplicitOperand = true } }
bdwashbu/scala-x86-inst
src/main/scala/com/scalaAsm/x86/Instructions/System/STR.scala
Scala
apache-2.0
959
package im.actor.server.enrich import scala.concurrent.ExecutionContextExecutor import scala.concurrent.duration._ import scala.util.{ Failure, Success, Try } import akka.actor._ import akka.contrib.pattern.DistributedPubSubMediator import akka.event.Logging import akka.http.scaladsl.model.Uri import akka.stream.Materializer import akka.util.Timeout import com.sksamuel.scrimage.{ AsyncImage, Format } import org.joda.time.DateTime import slick.driver.PostgresDriver.api._ import im.actor.api.rpc.files.FastThumb import im.actor.api.rpc.messaging._ import im.actor.server.api.rpc.service.messaging.Events import im.actor.server.api.rpc.service.messaging.MessagingService._ import im.actor.server.push.SeqUpdatesExtension import im.actor.server.user.UserViewRegion import im.actor.server.util._ object RichMessageWorker { val groupId = Some("RichMessageWorker") def startWorker(config: RichMessageConfig, mediator: ActorRef)( implicit system: ActorSystem, db: Database, userViewRegion: UserViewRegion, materializer: Materializer ): ActorRef = system.actorOf(Props( classOf[RichMessageWorker], config, mediator, db, userViewRegion, materializer )) } final class RichMessageWorker(config: RichMessageConfig, mediator: ActorRef)( implicit db: Database, userViewRegion: UserViewRegion, materializer: Materializer ) extends Actor with ActorLogging { import DistributedPubSubMediator.SubscribeAck import AnyRefLogSource._ import PreviewMaker._ import RichMessageWorker._ private implicit val system: ActorSystem = context.system private implicit val ec: ExecutionContextExecutor = system.dispatcher private implicit val timeout: Timeout = Timeout(10.seconds) private implicit val seqUpdExt: SeqUpdatesExtension = SeqUpdatesExtension(context.system) private implicit val fsAdapter: FileStorageAdapter = S3StorageExtension(context.system).s3StorageAdapter override val log = Logging(system, this) val previewMaker = PreviewMaker(config, "previewMaker") import DistributedPubSubMediator.Subscribe mediator ! Subscribe(privateMessagesTopic, groupId, self) mediator ! Subscribe(groupMessagesTopic, groupId, self) def receive: Receive = subscribing(privateAckReceived = false, groupAckReceived = false) def subscribing(privateAckReceived: Boolean, groupAckReceived: Boolean): Receive = { case SubscribeAck(Subscribe(`privateMessagesTopic`, `groupId`, `self`)) ⇒ if (groupAckReceived) context.become(ready) else context.become(subscribing(true, groupAckReceived)) case SubscribeAck(Subscribe(`groupMessagesTopic`, `groupId`, `self`)) ⇒ if (privateAckReceived) context.become(ready) else context.become(subscribing(privateAckReceived, true)) } def ready: Receive = { case Events.PeerMessage(fromPeer, toPeer, randomId, _, message) ⇒ message match { case TextMessage(text, _, _) ⇒ Try(Uri(text.trim)) match { case Success(uri) ⇒ log.debug("TextMessage with uri: {}", uri) previewMaker ! GetPreview(uri.toString(), UpdateHandler.getHandler(fromPeer, toPeer, randomId)) case Failure(_) ⇒ } case _ ⇒ } case PreviewSuccess(imageBytes, optFileName, mimeType, handler) ⇒ log.debug("PreviewSuccess for message with randomId: {}, fileName: {}, mimeType: {}", handler.randomId, optFileName, mimeType) val fullName = optFileName getOrElse { val name = (new DateTime).toString("yyyyMMddHHmmss") val ext = Try(mimeType.split("/").last).getOrElse("tmp") s"$name.$ext" } db.run { for { (file, fileSize) ← DBIO.from(FileUtils.writeBytes(imageBytes)) location ← fsAdapter.uploadFile(fullName, file.toFile) image ← DBIO.from(AsyncImage(imageBytes.toArray)) thumb ← DBIO.from(ImageUtils.scaleTo(image, 90)) thumbBytes ← DBIO.from(thumb.writer(Format.JPEG).write()) _ = log.debug("uploaded file to location {}", location) _ = log.debug("image with width: {}, height: {}", image.width, image.height) updated = DocumentMessage( fileId = location.fileId, accessHash = location.accessHash, fileSize = fileSize.toInt, name = fullName, mimeType = mimeType, thumb = Some(FastThumb(thumb.width, thumb.height, thumbBytes)), ext = Some(DocumentExPhoto(image.width, image.height)) ) _ ← handler.handleDbUpdate(updated) _ ← handler.handleUpdate(updated) } yield () } case PreviewFailure(mess, handler) ⇒ log.debug("failed to make preview for message with randomId: {}, cause: {} ", handler.randomId, mess) } }
supertanglang/actor-platform
actor-server/actor-enrich/src/main/scala/im/actor/server/enrich/RichMessageWorker.scala
Scala
mit
4,881
package scalaxy.enums import scala.language.experimental.macros class EnumValueNames( val names: Array[String], val initializer: AnyRef => Array[AnyRef]) extends Serializable object EnumValueNames { implicit def enumValueNames: EnumValueNames = macro internal.enumValueNames[EnumValueNames] }
nativelibs4java/Scalaxy
Enum/src/main/scala/scalaxy/enums/EnumValueNames.scala
Scala
bsd-3-clause
310
/* * Copyright © 2015 Lukas Rosenthaler, Benjamin Geer, Ivan Subotic, * Tobias Schweizer, André Kilchenmann, and Sepideh Alassi. * * This file is part of Knora. * * Knora is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Knora 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with Knora. If not, see <http://www.gnu.org/licenses/>. */ /* * Copyright © 2015 Lukas Rosenthaler, Benjamin Geer, Ivan Subotic, * Tobias Schweizer, André Kilchenmann, and Sepideh Alassi. * * This file is part of Knora. * * Knora is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Knora 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with Knora. If not, see <http://www.gnu.org/licenses/>. */ package org.knora.webapi.util import akka.testkit.ImplicitSender import com.typesafe.config.ConfigFactory import org.knora.webapi.messages.v1.responder.permissionmessages.{PermissionType, PermissionV1} import org.knora.webapi.routing.Authenticator import org.knora.webapi.{CoreSpec, IRI, OntologyConstants, SharedAdminTestData} import scala.collection.Map object PermissionUtilV1Spec { val config = ConfigFactory.parseString( """ akka.loglevel = "DEBUG" akka.stdout-loglevel = "DEBUG" """.stripMargin) } class PermissionUtilV1Spec extends CoreSpec("PermissionUtilSpec") with ImplicitSender with Authenticator { val permissionLiteral = "RV knora-base:UnknownUser|V knora-base:KnownUser|M knora-base:ProjectMember|CR knora-base:Creator" val parsedPermissionLiteral = Map( "RV" -> Set(OntologyConstants.KnoraBase.UnknownUser), "V" -> Set(OntologyConstants.KnoraBase.KnownUser), "M" -> Set(OntologyConstants.KnoraBase.ProjectMember), "CR" -> Set(OntologyConstants.KnoraBase.Creator) ) "PermissionUtil " should { "return user's max permission for a specific resource (incunabula normal project member user)" in { PermissionUtilV1.getUserPermissionV1( subjectIri = "http://data.knora.org/00014b43f902", subjectCreator = "http://data.knora.org/users/91e19f1e01", subjectProject = SharedAdminTestData.INCUNABULA_PROJECT_IRI, subjectPermissionLiteral = permissionLiteral, userProfile = SharedAdminTestData.incunabulaMemberUser ) should equal(Some(6)) // modify permission } "return user's max permission for a specific resource (incunabula project admin user)" in { PermissionUtilV1.getUserPermissionV1( subjectIri = "http://data.knora.org/00014b43f902", subjectCreator = "http://data.knora.org/users/91e19f1e01", subjectProject = SharedAdminTestData.INCUNABULA_PROJECT_IRI, subjectPermissionLiteral = permissionLiteral, userProfile = SharedAdminTestData.incunabulaProjectAdminUser ) should equal(Some(8)) // change rights permission } "return user's max permission for a specific resource (incunabula creator user)" in { PermissionUtilV1.getUserPermissionV1( subjectIri = "http://data.knora.org/00014b43f902", subjectCreator = "http://data.knora.org/users/91e19f1e01", subjectProject = SharedAdminTestData.INCUNABULA_PROJECT_IRI, subjectPermissionLiteral = permissionLiteral, userProfile = SharedAdminTestData.incunabulaCreatorUser ) should equal(Some(8)) // change rights permission } "return user's max permission for a specific resource (root user)" in { PermissionUtilV1.getUserPermissionV1( subjectIri = "http://data.knora.org/00014b43f902", subjectCreator = "http://data.knora.org/users/91e19f1e01", subjectProject = SharedAdminTestData.INCUNABULA_PROJECT_IRI, subjectPermissionLiteral = permissionLiteral, userProfile = SharedAdminTestData.rootUser ) should equal(Some(8)) // change rights permission } "return user's max permission for a specific resource (normal user)" in { PermissionUtilV1.getUserPermissionV1( subjectIri = "http://data.knora.org/00014b43f902", subjectCreator = "http://data.knora.org/users/91e19f1e01", subjectProject = SharedAdminTestData.INCUNABULA_PROJECT_IRI, subjectPermissionLiteral = permissionLiteral, userProfile = SharedAdminTestData.normalUser ) should equal(Some(2)) // restricted view permission } "return user's max permission for a specific resource (anonymous user)" in { PermissionUtilV1.getUserPermissionV1( subjectIri = "http://data.knora.org/00014b43f902", subjectCreator = "http://data.knora.org/users/91e19f1e01", subjectProject = SharedAdminTestData.INCUNABULA_PROJECT_IRI, subjectPermissionLiteral = permissionLiteral, userProfile = SharedAdminTestData.anonymousUser ) should equal(Some(1)) // restricted view permission } "return user's max permission from assertions for a specific resource" in { val assertions: Seq[(IRI, String)] = Seq( (OntologyConstants.KnoraBase.AttachedToUser, "http://data.knora.org/users/91e19f1e01"), (OntologyConstants.KnoraBase.AttachedToProject, SharedAdminTestData.INCUNABULA_PROJECT_IRI), (OntologyConstants.KnoraBase.HasPermissions, permissionLiteral) ) PermissionUtilV1.getUserPermissionV1FromAssertions( subjectIri = "http://data.knora.org/00014b43f902", assertions = assertions, userProfile = SharedAdminTestData.incunabulaMemberUser ) should equal(Some(6)) // modify permissions } "return user's max permission on link value" ignore { // TODO } "return parsed permissions string as 'Map[IRI, Set[String]]" in { PermissionUtilV1.parsePermissions(permissionLiteral) should equal(parsedPermissionLiteral) } "return parsed permissions string as 'Set[PermissionV1]' (object access permissions)" in { val hasPermissionsString = "M knora-base:Creator,knora-base:ProjectMember|V knora-base:KnownUser,http://data.knora.org/groups/customgroup|RV knora-base:UnknownUser" val permissionsSet = Set( PermissionV1.modifyPermission(OntologyConstants.KnoraBase.Creator), PermissionV1.modifyPermission(OntologyConstants.KnoraBase.ProjectMember), PermissionV1.viewPermission(OntologyConstants.KnoraBase.KnownUser), PermissionV1.viewPermission("http://data.knora.org/groups/customgroup"), PermissionV1.restrictedViewPermission(OntologyConstants.KnoraBase.UnknownUser) ) PermissionUtilV1.parsePermissionsWithType(Some(hasPermissionsString), PermissionType.OAP) should contain allElementsOf permissionsSet } "return parsed permissions string as 'Set[PermissionV1]' (administrative permissions)" in { val hasPermissionsString = "ProjectResourceCreateAllPermission|ProjectAdminAllPermission|ProjectResourceCreateRestrictedPermission <http://www.knora.org/ontology/images#bild>,<http://www.knora.org/ontology/images#bildformat>" val permissionsSet = Set( PermissionV1.ProjectResourceCreateAllPermission, PermissionV1.ProjectAdminAllPermission, PermissionV1.projectResourceCreateRestrictedPermission("http://www.knora.org/ontology/images#bild"), PermissionV1.projectResourceCreateRestrictedPermission("http://www.knora.org/ontology/images#bildformat") ) PermissionUtilV1.parsePermissionsWithType(Some(hasPermissionsString), PermissionType.AP) should contain allElementsOf permissionsSet } "build a 'PermissionV1' object" in { PermissionUtilV1.buildPermissionObject( name = OntologyConstants.KnoraBase.ProjectResourceCreateRestrictedPermission, iris = Set("1", "2", "3") ) should equal( Set( PermissionV1.projectResourceCreateRestrictedPermission("1"), PermissionV1.projectResourceCreateRestrictedPermission("2"), PermissionV1.projectResourceCreateRestrictedPermission("3") ) ) } "remove duplicate permissions" in { val duplicatedPermissions = Seq( PermissionV1.restrictedViewPermission("1"), PermissionV1.restrictedViewPermission("1"), PermissionV1.restrictedViewPermission("2"), PermissionV1.changeRightsPermission("2"), PermissionV1.changeRightsPermission("3"), PermissionV1.changeRightsPermission("3") ) val deduplicatedPermissions = Set( PermissionV1.restrictedViewPermission("1"), PermissionV1.restrictedViewPermission("2"), PermissionV1.changeRightsPermission("2"), PermissionV1.changeRightsPermission("3") ) val result = PermissionUtilV1.removeDuplicatePermissions(duplicatedPermissions) result.size should equal(deduplicatedPermissions.size) result should contain allElementsOf deduplicatedPermissions } "remove lesser permissions" in { val withLesserPermissions = Set( PermissionV1.restrictedViewPermission("1"), PermissionV1.viewPermission("1"), PermissionV1.modifyPermission("2"), PermissionV1.changeRightsPermission("1"), PermissionV1.deletePermission("2") ) val withoutLesserPermissions = Set( PermissionV1.changeRightsPermission("1"), PermissionV1.deletePermission("2") ) val result = PermissionUtilV1.removeLesserPermissions(withLesserPermissions, PermissionType.OAP) result.size should equal(withoutLesserPermissions.size) result should contain allElementsOf withoutLesserPermissions } "create permissions string" in { val permissions = Set( PermissionV1.changeRightsPermission("1"), PermissionV1.deletePermission("2"), PermissionV1.changeRightsPermission(OntologyConstants.KnoraBase.Creator), PermissionV1.modifyPermission(OntologyConstants.KnoraBase.ProjectMember), PermissionV1.viewPermission(OntologyConstants.KnoraBase.KnownUser) ) val permissionsString = "CR knora-base:Creator,1|D 2|M knora-base:ProjectMember|V knora-base:KnownUser" val result = PermissionUtilV1.formatPermissions(permissions, PermissionType.OAP) result should equal(permissionsString) } } }
nie-ine/Knora
webapi/src/test/scala/org/knora/webapi/util/PermissionUtilV1Spec.scala
Scala
agpl-3.0
12,122
package com.lorandszakacs.sg.model.impl import com.lorandszakacs.sg.model._ import com.lorandszakacs.util.mongodb._ import com.lorandszakacs.util.effects._ /** * * @author Lorand Szakacs, [email protected] * @since 14 Jul 2017 * */ private[impl] class RepoSGs(override protected val db: Database)( implicit override val dbIOScheduler: DBIOScheduler, override val futureLift: FutureLift[IO], ) extends MRepo[SG](sgIdentifier) with SGRepoBSON { override val collectionName: String = "sgs" implicit override protected val entityHandler: BSONDocumentHandler[SG] = BSONMacros.handler[SG] }
lorandszakacs/sg-downloader
sg-repo/src/main/scala/com/lorandszakacs/sg/model/impl/RepoSGs.scala
Scala
apache-2.0
619
package org.jetbrains.plugins.scala package lang package parser package parsing package expressions import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes import org.jetbrains.plugins.scala.lang.parser.parsing.builder.ScalaPsiBuilder import org.jetbrains.plugins.scala.lang.parser.parsing.patterns.{Guard, Pattern1} /** * @author Alexander Podkhalyuzin * Date: 06.03.2008 */ /* * Enumerator ::= Generator * | Guard * | 'val' Pattern1 '=' Expr */ object Enumerator { def parse(builder: ScalaPsiBuilder): Boolean = { val enumMarker = builder.mark def parseNonGuard(f: Boolean): Boolean = { if (!Pattern1.parse(builder)) { if (!f) { builder error ErrMsg("wrong.pattern") enumMarker.done(ScalaElementTypes.ENUMERATOR) return true } else if (!Guard.parse(builder, noIf = true)) { enumMarker.rollbackTo() return false } else { enumMarker.drop() return true } } builder.getTokenType match { case ScalaTokenTypes.tASSIGN => builder.advanceLexer //Ate = case ScalaTokenTypes.tCHOOSE => enumMarker.rollbackTo return Generator parse builder case _ => if (!f) { builder error ErrMsg("choose.expected") enumMarker.done(ScalaElementTypes.ENUMERATOR) } else { enumMarker.rollbackTo Guard.parse(builder, noIf = true) } return true } if (!Expr.parse(builder)) { builder error ErrMsg("wrong.expression") } enumMarker.done(ScalaElementTypes.ENUMERATOR) true } builder.getTokenType match { case ScalaTokenTypes.kIF => Guard parse builder enumMarker.drop return true case ScalaTokenTypes.kVAL => builder.advanceLexer //Ate val return parseNonGuard(false) case _ => return parseNonGuard(true) } } }
advancedxy/intellij-scala
src/org/jetbrains/plugins/scala/lang/parser/parsing/expressions/Enumerator.scala
Scala
apache-2.0
2,019
package hooktest /* * Copyright (c) 2016 Yuki Ono * Licensed under the MIT License. */ //import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent._ import com.sun.jna.Pointer import com.sun.jna.WString import com.sun.jna.Memory; import com.sun.jna.ptr.IntByReference import com.sun.jna.platform.win32._ import com.sun.jna.platform.win32.BaseTSD.ULONG_PTR import com.sun.jna.platform.win32.WinDef._ import com.sun.jna.platform.win32.WinUser._ import win32ex._ import win32ex.User32Ex._ import win32ex.Kernel32Ex._ import com.sun.jna.platform.win32.WinUser.{ KBDLLHOOKSTRUCT => KHookInfo } import java.util.Random object Windows { private val ctx = Context private val logger = Logger.getLogger() private val u32 = User32.INSTANCE private val u32ex = User32Ex.INSTANCE private val k32 = Kernel32.INSTANCE private val k32ex = Kernel32Ex.INSTANCE //private val shcore = Shcore.INSTANCE // https://github.com/EsotericSoftware/clippy/blob/master/src/com/esotericsoftware/clippy/Tray.java private val TaskbarCreated = u32.RegisterWindowMessage("TaskbarCreated") private def procRawInput(lParam: LPARAM): Boolean = { val pcbSize = new IntByReference val cbSizeHeader = new RAWINPUTHEADER().size() def getRawInputData(data: Pointer) = u32ex.GetRawInputData(lParam.toPointer(), RID_INPUT, data, pcbSize, cbSizeHeader) def isMouseMoveRelative(ri: RAWINPUT) = ri.header.dwType == RIM_TYPEMOUSE && ri.mouse.usFlags == MOUSE_MOVE_RELATIVE if (getRawInputData(null) == 0) { val buf = new Memory(pcbSize.getValue) if (getRawInputData(buf) == pcbSize.getValue) { val ri = new RAWINPUT(buf) if (isMouseMoveRelative(ri)) { val rm = ri.mouse sendWheelRaw(rm.lLastX, rm.lLastY) return true } } } false } private val windowProc = new WindowProc { override def callback(hwnd: HWND, uMsg: Int, wParam: WPARAM, lParam: LPARAM): LRESULT = { uMsg match { case WM_INPUT => { if (procRawInput(lParam)) return new LRESULT(0) } case WM_QUERYENDSESSION => W10Wheel.procExit return new LRESULT(0) case TaskbarCreated => { logger.debug("TaskbarCreated") Context.resetSystemTray return new LRESULT(0) } case _ => {} } u32.DefWindowProc(hwnd, uMsg, wParam, lParam) } } private val CLASS_NAME = Context.PROGRAM_NAME + "_WM" private val messageHwnd: HWND = { val wx = new WNDCLASSEX wx.lpszClassName = CLASS_NAME wx.lpfnWndProc = windowProc if (u32.RegisterClassEx(wx).intValue() != 0) { val hwnd = u32.CreateWindowEx(0, CLASS_NAME, null, 0, 0, 0, 0, 0, null, null, null, null) u32ex.ChangeWindowMessageFilterEx(hwnd, TaskbarCreated, MSGFLT_ALLOW, null); hwnd } else null } // window message therad private val wmThread = new Thread(() => { val msg = new MSG while (u32.GetMessage(msg, null, 0, 0) > 0) { u32.TranslateMessage(msg) u32.DispatchMessage(msg) } }) wmThread.setDaemon(true) wmThread.start //private val inputQueue = new ArrayBlockingQueue[Array[INPUT]](128, true) private val inputQueue = new LinkedBlockingQueue[Array[INPUT]]() private val senderThread = new Thread(() => while (true) { val msgs = inputQueue.take() u32.SendInput(new DWORD(msgs.length), msgs, msgs(0).size()) } ) senderThread.setDaemon(true) senderThread.start def unhook(hhk: HHOOK) { u32.UnhookWindowsHookEx(hhk) } def setHook(proc: LowLevelMouseProc) = { val hMod = k32.GetModuleHandle(null) u32.SetWindowsHookEx(WH_MOUSE_LL, proc, hMod, 0) } def setHook(proc: LowLevelKeyboardProc) = { val hMod = k32.GetModuleHandle(null) u32.SetWindowsHookEx(WH_KEYBOARD_LL, proc, hMod, 0) } def callNextHook(hhk: HHOOK, nCode: Int, wParam: WPARAM, ptr: Pointer): LRESULT = { val peer = Pointer.nativeValue(ptr) u32.CallNextHookEx(hhk, nCode, wParam, new LPARAM(peer)) } def createInputArray(size: Int) = new INPUT().toArray(size).asInstanceOf[Array[INPUT]] private val rand = new Random // Not Zero private def createRandomNumber: Int = { var res: Int = 0 while (res == 0) res = rand.nextInt res } private val resendTag = createRandomNumber private val resendClickTag = createRandomNumber // LLMHF_INJECTED, LLMHF_LOWER_IL_INJECTED // https://msdn.microsoft.com/en-ca/library/windows/desktop/ms644970(v=vs.85).aspx def isInjectedEvent(me: MouseEvent): Boolean = me.info.flags == 1 || me.info.flags == 2 def isResendEvent(me: MouseEvent): Boolean = me.info.dwExtraInfo.intValue() == resendTag def isResendClickEvent(me: MouseEvent): Boolean = me.info.dwExtraInfo.intValue() == resendClickTag def setInput(msg: INPUT, pt: POINT, data: Int, flags: Int, time: Int, extra: Int) { msg.`type` = new DWORD(INPUT.INPUT_MOUSE) msg.input.setType("mi") val mi = msg.input.mi mi.dx = new LONG(pt.x) mi.dy = new LONG(pt.y) mi.mouseData = new DWORD(data) mi.dwFlags = new DWORD(flags) mi.time = new DWORD(time) mi.dwExtraInfo = new ULONG_PTR(extra) } def sendInput(pt: POINT, data: Int, flags: Int, time: Int, extra: Int) { val input = createInputArray(1) setInput(input(0), pt, data, flags, time, extra) try { //lib.SendInput(new DWORD(1), input, input(0).size()) inputQueue.add(input) } catch { case e: Exception => logger.warn(e.toString()) } } def sendInputDirect(pt: POINT, data: Int, flags: Int, time: Int, extra: Int) { val input = createInputArray(1) setInput(input(0), pt, data, flags, time, extra) u32.SendInput(new DWORD(1), input, input(0).size()) } def sendInput(msgs: Array[INPUT]) { try { //lib.SendInput(new DWORD(msgs.length), msgs, msgs(0).size()) inputQueue.add(msgs) } catch { case e: Exception => logger.warn(e.toString()) } } private var vwCount = 0 private var hwCount = 0 sealed abstract class MoveDirection case class Plus() extends MoveDirection case class Minus() extends MoveDirection case class Zero() extends MoveDirection private var vLastMove: MoveDirection = Zero() private var hLastMove: MoveDirection = Zero() private var vWheelMove = 0 private var hWheelMove = 0 private var quickTurn = false def startWheelCount { vwCount = if (ctx.isQuickFirst) vWheelMove else vWheelMove / 2 hwCount = if (ctx.isQuickFirst) hWheelMove else hWheelMove / 2 vLastMove = Zero() hLastMove = Zero() } import scala.annotation.tailrec // d == Not Zero private def getNearestIndex(d: Int, thr: Array[Int]): Int = { val ad = Math.abs(d) @tailrec def loop(i: Int): Int = { thr(i) match { case n if n == ad => i case n if n > ad => if (n - ad < Math.abs(thr(i - 1) - ad)) i else i - 1 case _ => if (i != thr.length - 1) loop(i + 1) else i } } loop(0) } private var accelThreshold: Array[Int] = null private var accelMultiplier: Array[Double] = null private def passInt(d: Int) = d private var addAccelIf = passInt _ private def addAccel(d: Int): Int = { val i = getNearestIndex(d, accelThreshold) (d * accelMultiplier(i)).toInt } private def reverseIfFlip(d: Int) = -d private var reverseIfV = passInt _ private var reverseIfH = reverseIfFlip _ private var reverseIfDelta = reverseIfFlip _ private var wheelDelta = 0 private def getVWheelDelta(input: Int) = { val delta = wheelDelta val res = if (input > 0) -delta else delta reverseIfDelta(res) } private def getHWheelDelta(input: Int) = { -(getVWheelDelta(input)) } private def isTurnMove(last: MoveDirection, d: Int) = last match { case Plus() => d < 0 case Minus() => d > 0 case _ => false } private def sendRealVWheel(pt: POINT, d: Int) { def send = sendInput(pt, getVWheelDelta(d), MOUSEEVENTF_WHEEL, 0, 0) vwCount += Math.abs(d) if (quickTurn && isTurnMove(vLastMove, d)) send else if (vwCount >= vWheelMove) { send vwCount -= vWheelMove } vLastMove = if (d > 0) Plus() else Minus() } private def sendDirectVWheel(pt: POINT, d: Int) { //println(s"d: $d") sendInput(pt, reverseIfV(addAccelIf(d)), MOUSEEVENTF_WHEEL, 0, 0) } private def sendRealHWheel(pt: POINT, d: Int) { def send = sendInput(pt, getHWheelDelta(d), MOUSEEVENTF_HWHEEL, 0, 0) hwCount += Math.abs(d) if (quickTurn && isTurnMove(hLastMove, d)) send else if (hwCount >= hWheelMove) { send hwCount -= hWheelMove } hLastMove = if (d > 0) Plus() else Minus() } private def sendDirectHWheel(pt: POINT, d: Int) { sendInput(pt, reverseIfH(addAccelIf(d)), MOUSEEVENTF_HWHEEL, 0, 0) } private var sendVWheel = sendDirectVWheel _ private var sendHWheel = sendDirectHWheel _ sealed abstract class VHDirection case class Vertical() extends VHDirection case class Horizontal() extends VHDirection case class NonDirection() extends VHDirection //private var vhDirection: VHDirection = NonDirection() private var fixedVHD: VHDirection = NonDirection() private var latestVHD: VHDirection = NonDirection() private def initFuncs { addAccelIf = if (ctx.isAccelTable) addAccel else passInt swapIf = if (ctx.isSwapScroll) swapIfOn _ else swapIfOff _ reverseIfV = if (ctx.isReverseScroll) passInt else reverseIfFlip reverseIfH = if (ctx.isReverseScroll) reverseIfFlip else passInt sendVWheel = if (ctx.isRealWheelMode) sendRealVWheel else sendDirectVWheel sendHWheel = if (ctx.isRealWheelMode) sendRealHWheel else sendDirectHWheel sendWheelIf = if (ctx.isHorizontalScroll && ctx.isVhAdjusterMode) sendWheelVHA else sendWheelStd } private def initAccelTable { accelThreshold = ctx.getAccelThreshold accelMultiplier = ctx.getAccelMultiplier } private def initRealWheelMode { vWheelMove = ctx.getVWheelMove hWheelMove = ctx.getHWheelMove quickTurn = ctx.isQuickTurn wheelDelta = ctx.getWheelDelta reverseIfDelta = if (ctx.isReverseScroll) reverseIfFlip else passInt startWheelCount } private def initVhAdjusterMode { //vhDirection = NonDirection() fixedVHD = NonDirection() latestVHD = NonDirection() switchingThreshold = ctx.getSwitchingThreshold switchVHDif = if (ctx.isVhAdjusterSwitching) switchVHD _ else switchVHDifNone _ } private def initStdMode { verticalThreshold = ctx.getVerticalThreshold horizontalThreshold = ctx.getHorizontalThreshold sendWheelStdIfHorizontal = if (ctx.isHorizontalScroll) sendWheelStdHorizontal _ else sendWheelStdNone _ } def initScroll { scrollStartPoint = ctx.getScrollStartPoint initFuncs if (ctx.isAccelTable) initAccelTable if (ctx.isRealWheelMode) initRealWheelMode if (ctx.isVhAdjusterMode) initVhAdjusterMode else initStdMode } private def changeCursorVHD(vhd: VHDirection): Unit = vhd match { case Vertical() => { if (ctx.isCursorChange) changeCursorV } case Horizontal() => { if (ctx.isCursorChange) changeCursorH } case _ => () } private def getFirstVHD(adx: Int, ady: Int): VHDirection = { val mthr = ctx.getFirstMinThreshold if (adx > mthr || ady > mthr) { val y = if (ctx.isFirstPreferVertical) ady * 2 else ady if (y >= adx) Vertical() else Horizontal() } else NonDirection() } private var switchingThreshold = 0 private def switchVHD(adx: Int, ady: Int): VHDirection = { val sthr = switchingThreshold if (ady > sthr) Vertical() else if (adx > sthr) Horizontal() else NonDirection() } private def switchVHDifNone(adx: Int, ady: Int): VHDirection = fixedVHD private var switchVHDif = switchVHD _ private def sendWheelVHA(wspt: POINT, dx: Int, dy: Int): Unit = { val adx = Math.abs(dx) val ady = Math.abs(dy) val curVHD = fixedVHD match { case NonDirection() => { fixedVHD = getFirstVHD(adx, ady) fixedVHD } case _ => switchVHDif(adx, ady) } if (curVHD != NonDirection() && curVHD != latestVHD) { changeCursorVHD(curVHD) latestVHD = curVHD } latestVHD match { case Vertical() => if (dy != 0) sendVWheel(wspt, dy) case Horizontal() => if (dx != 0) sendHWheel(wspt, dx) case _ => () } } private var verticalThreshold = 0 private var horizontalThreshold = 0 private def sendWheelStdHorizontal(wspt: POINT, dx: Int, dy: Int) { if (Math.abs(dx) > horizontalThreshold) sendHWheel(wspt, dx) } private def sendWheelStdNone(wspt: POINT, dx: Int, dy: Int) {} private var sendWheelStdIfHorizontal = sendWheelStdHorizontal _ private var sendWheelIf = sendWheelStd _ private def sendWheelStd(wspt: POINT, dx: Int, dy: Int) { if (Math.abs(dy) > verticalThreshold) sendVWheel(wspt, dy) sendWheelStdIfHorizontal(wspt, dx, dy) } private def swapIfOff(x: Int, y: Int) = (x, y) private def swapIfOn(x: Int, y: Int) = (y, x) private var swapIf = swapIfOff _ private var scrollStartPoint: (Int, Int) = null def sendWheel(movePt: POINT) { //logger.debug("movePT: " + movePt.x + "," + movePt.y); val (sx, sy) = scrollStartPoint val (dx, dy) = swapIf(movePt.x - sx, movePt.y - sy) sendWheelIf(new POINT(sx, sy), dx, dy) } def sendWheelRaw(x: Int, y: Int) { //logger.debug("sendWheelRaw: " + x + "," + y) val (sx, sy) = scrollStartPoint if (sx != x && sy != y) { val (dx, dy) = swapIf(x, y) sendWheelIf(new POINT(sx, sy), dx, dy) } } private def createClick(mc: MouseClick) = { val extra = resendClickTag val input = createInputArray(2) def set(mouseData: Int, down: Int, up: Int) { setInput(input(0), mc.info.pt, mouseData, down, 0, extra) setInput(input(1), mc.info.pt, mouseData, up, 0, extra) } mc match { case LeftClick(_) => set(0, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP) case RightClick(_) => set(0, MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP) case MiddleClick(_) => set(0, MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP) case X1Click(_) => set(XBUTTON1, MOUSEEVENTF_XDOWN, MOUSEEVENTF_XUP) case X2Click(_) => set(XBUTTON2, MOUSEEVENTF_XDOWN, MOUSEEVENTF_XUP) } input } def resendClick(mc: MouseClick) { sendInput(createClick(mc)) } def resendClick(down: MouseEvent, up: MouseEvent) { (down, up) match { case (LeftDown(_), LeftUp(_)) => resendClick(LeftClick(down.info)) case (RightDown(_), RightUp(_)) => resendClick(RightClick(down.info)) case x => { throw new IllegalStateException("Not matched: " + x) } } } def resendDown(me: MouseEvent) { me match { case LeftDown(info) => sendInput(info.pt, 0, MOUSEEVENTF_LEFTDOWN, 0, resendTag) case RightDown(info) => sendInput(info.pt, 0, MOUSEEVENTF_RIGHTDOWN, 0, resendTag) case _ => throw new IllegalArgumentException() } } def resendUp(me: MouseEvent) { me match { case LeftUp(info) => sendInput(info.pt, 0, MOUSEEVENTF_LEFTUP, 0, resendTag) case RightUp(info) => sendInput(info.pt, 0, MOUSEEVENTF_RIGHTUP, 0, resendTag) case _ => throw new IllegalArgumentException() } } // https://github.com/java-native-access/jna/blob/master/contrib/platform/src/com/sun/jna/platform/win32/Kernel32Util.java private def loadCursor(id: Int) = { val id_ptr = new Pointer(id) u32ex.LoadImageW(null, id_ptr, IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE | LR_SHARED) } private val CURSOR_V = loadCursor(IDC_SIZENS) private val CURSOR_H = loadCursor(IDC_SIZEWE) private def copyCursor(icon: HICON) = u32.CopyIcon(icon).getPointer def changeCursor(hCur: Pointer) = { val icon = new HICON(hCur) u32ex.SetSystemCursor(copyCursor(icon), OCR_NORMAL) u32ex.SetSystemCursor(copyCursor(icon), OCR_IBEAM) u32ex.SetSystemCursor(copyCursor(icon), OCR_HAND) } def changeCursorV: Unit = changeCursor(CURSOR_V) def changeCursorH: Unit = changeCursor(CURSOR_H) //val SPIF_UPDATEINIFILE = 0x01; //val SPIF_SENDCHANGE = 0x02; //val SPIF_SENDWININICHANGE = 0x02; def restoreCursor = { //val fWinIni = if (!sendChange) 0 else (SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE) u32ex.SystemParametersInfoW(SPI_SETCURSORS, 0, null, 0) } private def getAsyncKeyState(vKey: Int) = (u32ex.GetAsyncKeyState(vKey) & 0xf000) != 0 def getShiftState = getAsyncKeyState(VK_SHIFT) def getCtrlState = getAsyncKeyState(VK_CONTROL) def getAltState = getAsyncKeyState(VK_MENU) def getLeftState = getAsyncKeyState(VK_LBUTTON) def getRightState = getAsyncKeyState(VK_RBUTTON) def getEscState = getAsyncKeyState(VK_ESCAPE) sealed trait Priority { def name = this.getClass.getSimpleName } case class Normal() extends Priority case class AboveNormal() extends Priority case class High() extends Priority def getPriority(name: String) = name match { case DataID.High => High() case DataID.AboveNormal | "Above Normal" => AboveNormal() case DataID.Normal => Normal() } def setPriority(p: Priority) = { val process = k32.GetCurrentProcess() def setPriorityClass(pc: Int) = k32ex.SetPriorityClass(process, pc) p match { case Normal() => setPriorityClass(NORMAL_PRIORITY_CLASS) case AboveNormal() => setPriorityClass(ABOVE_NORMAL_PRIORITY_CLASS) case High() => setPriorityClass(HIGH_PRIORITY_CLASS) } } def getCursorPos = { val pos = new POINT u32.GetCursorPos(pos) pos } private def createRawInputDevice = new RAWINPUTDEVICE().toArray(1).asInstanceOf[Array[RAWINPUTDEVICE]] private def registerMouseRawInputDevice(dwFlags: Int, hwnd: HWND): Boolean = { val rid = createRawInputDevice rid(0).usUsagePage = HID_USAGE_PAGE_GENERIC rid(0).usUsage = HID_USAGE_GENERIC_MOUSE rid(0).dwFlags = dwFlags rid(0).hwndTarget = hwnd u32ex.RegisterRawInputDevices(rid, 1, rid(0).size) } def getLastErrorCode: Int = { return k32.GetLastError(); } def getLastErrorMessage: String = { return Kernel32Util.formatMessage(getLastErrorCode); } def registerRawInput { if (!registerMouseRawInputDevice(RIDEV_INPUTSINK, messageHwnd)) Dialog.errorMessage("Failed register RawInput: " + getLastErrorMessage) } def unregisterRawInput { if (!registerMouseRawInputDevice(RIDEV_REMOVE, null)) Dialog.errorMessage("Failed unregister RawInput: " + getLastErrorMessage) } }
ykon/w10wheel
src/main/scala/hooktest/Windows.scala
Scala
mit
20,754
package domala.jdbc import java.sql.Connection import javax.sql.DataSource import domala.internal.macros.reflect.DaoProviderMacro import scala.reflect.ClassTag import scala.language.experimental.macros /** A provider of Dao instance. */ object DaoProvider { def get[T](implicit config: Config, classTag: ClassTag[T]): T = macro DaoProviderMacro.get[T] def get[T](config: Config)(implicit classTag: ClassTag[T]): T = macro DaoProviderMacro.getByConfig[T] def get[T](connection: Connection)(implicit config: Config, classTag: ClassTag[T]): T = macro DaoProviderMacro.getByConnection[T] def get[T](dataSource: DataSource)(implicit config: Config, classTag: ClassTag[T]): T = macro DaoProviderMacro.getByDataSource[T] }
bakenezumi/domala
core/src/main/scala/domala/jdbc/DaoProvider.scala
Scala
apache-2.0
728
// Expression-oriented Language // Scala favors expressions over statements. // This idea is present in constructs throughout Scala // - try/catch // - loops // - return values // - ... // Note: You can turn a series of statements and // expressions into an expression using curly braces! val baz = { val zoop = 30 val bing = Random.nextInt() zoop * bing // this becomes the value of baz }
agconti/scala-school
01-intro-to-scala/slides/slide005.scala
Scala
mit
412
package com.cevaris.hashes trait HashOperation object Remove extends HashOperation object Set extends HashOperation object Get extends HashOperation object HashedMap { implicit class Sieve(val N: Int) extends AnyVal { def primes: Seq[Int] = { val isPrime = collection.mutable.BitSet(2 to N: _*) -- (4 to N by 2) for (p <- 2 +: (3 to Math.sqrt(N).toInt by 2) if isPrime(p)) { isPrime --= p * p to N by p } isPrime.toImmutable.toSeq } } } trait HashedMap[A] { val defaultSize: Int = 19 def get(key: Int): Option[A] /** * @return inserted value A */ def set(key: Int, value: A): A def size(): Int /** * Number of elements cleared */ def clear(): Int /** * @return Option[A] Item removed if found */ def remove(key: Int): Option[A] } case class KeyValue[A](key: Int, value: A)
cevaris/hashes
src/main/scala/com/cevaris/hashes/HashedMap.scala
Scala
apache-2.0
867
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.deploy.k8s.features import scala.collection.JavaConverters._ import scala.collection.mutable.ArrayBuffer import io.fabric8.kubernetes.api.model._ import org.apache.spark.deploy.k8s._ import org.apache.spark.deploy.k8s.Constants.{ENV_EXECUTOR_ID, SPARK_APP_ID_LABEL} private[spark] class MountVolumesFeatureStep(conf: KubernetesConf) extends KubernetesFeatureConfigStep { import MountVolumesFeatureStep._ val additionalResources = ArrayBuffer.empty[HasMetadata] override def configurePod(pod: SparkPod): SparkPod = { val (volumeMounts, volumes) = constructVolumes(conf.volumes).unzip val podWithVolumes = new PodBuilder(pod.pod) .editSpec() .addToVolumes(volumes.toSeq: _*) .endSpec() .build() val containerWithVolumeMounts = new ContainerBuilder(pod.container) .addToVolumeMounts(volumeMounts.toSeq: _*) .build() SparkPod(podWithVolumes, containerWithVolumeMounts) } private def constructVolumes( volumeSpecs: Iterable[KubernetesVolumeSpec] ): Iterable[(VolumeMount, Volume)] = { val duplicateMountPaths = volumeSpecs.map(_.mountPath).toSeq.groupBy(identity).collect { case (x, ys) if ys.length > 1 => s"'$x'" } require(duplicateMountPaths.isEmpty, s"Found duplicated mountPath: ${duplicateMountPaths.mkString(", ")}") volumeSpecs.zipWithIndex.map { case (spec, i) => val volumeMount = new VolumeMountBuilder() .withMountPath(spec.mountPath) .withReadOnly(spec.mountReadOnly) .withSubPath(spec.mountSubPath) .withName(spec.volumeName) .build() val volumeBuilder = spec.volumeConf match { case KubernetesHostPathVolumeConf(hostPath) => /* "" means that no checks will be performed before mounting the hostPath volume */ new VolumeBuilder() .withHostPath(new HostPathVolumeSource(hostPath, "")) case KubernetesPVCVolumeConf(claimNameTemplate, storageClass, size) => val claimName = conf match { case c: KubernetesExecutorConf => claimNameTemplate .replaceAll(PVC_ON_DEMAND, s"${conf.resourceNamePrefix}-exec-${c.executorId}$PVC_POSTFIX-$i") .replaceAll(ENV_EXECUTOR_ID, c.executorId) case _ => claimNameTemplate .replaceAll(PVC_ON_DEMAND, s"${conf.resourceNamePrefix}-driver$PVC_POSTFIX-$i") } if (storageClass.isDefined && size.isDefined) { additionalResources.append(new PersistentVolumeClaimBuilder() .withKind(PVC) .withApiVersion("v1") .withNewMetadata() .withName(claimName) .addToLabels(SPARK_APP_ID_LABEL, conf.sparkConf.getAppId) .endMetadata() .withNewSpec() .withStorageClassName(storageClass.get) .withAccessModes(PVC_ACCESS_MODE) .withResources(new ResourceRequirementsBuilder() .withRequests(Map("storage" -> new Quantity(size.get)).asJava).build()) .endSpec() .build()) } new VolumeBuilder() .withPersistentVolumeClaim( new PersistentVolumeClaimVolumeSource(claimName, spec.mountReadOnly)) case KubernetesEmptyDirVolumeConf(medium, sizeLimit) => new VolumeBuilder() .withEmptyDir( new EmptyDirVolumeSource(medium.getOrElse(""), sizeLimit.map(new Quantity(_)).orNull)) case KubernetesNFSVolumeConf(path, server) => new VolumeBuilder() .withNfs(new NFSVolumeSource(path, null, server)) } val volume = volumeBuilder.withName(spec.volumeName).build() (volumeMount, volume) } } override def getAdditionalKubernetesResources(): Seq[HasMetadata] = { additionalResources.toSeq } } private[spark] object MountVolumesFeatureStep { val PVC_ON_DEMAND = "OnDemand" val PVC = "PersistentVolumeClaim" val PVC_POSTFIX = "-pvc" val PVC_ACCESS_MODE = "ReadWriteOnce" }
hvanhovell/spark
resource-managers/kubernetes/core/src/main/scala/org/apache/spark/deploy/k8s/features/MountVolumesFeatureStep.scala
Scala
apache-2.0
4,943
package metamorphic.dsl.util object Instantiator { def instance[T](className: String): T = { val clasz = Class.forName(className) val constructor = clasz.getConstructor() constructor.newInstance().asInstanceOf[T] } def instance[T](className: Option[String]): Option[T] = { className match { case Some(className) => Some(instance[T](className)) case None => None } } }
frroliveira/metamorphic
metamorphic/src/main/scala/metamorphic/dsl/util/Instantiator.scala
Scala
mit
415
package com.github.cthulhu314.scalaba.auth trait Authentication[T,+User] { def authenticate(userContext : T) : Stream[User] }
cthulhu314/scalaba
src/main/scala/com/github/cthulhu314/scalaba/auth/Authentication.scala
Scala
mit
128
/* * Drop.scala * (FScape) * * Copyright (c) 2001-2022 Hanns Holger Rutz. All rights reserved. * * This software is published under the GNU Affero General Public License v3+ * * * For further information, please contact Hanns Holger Rutz at * [email protected] */ package de.sciss.fscape package graph import de.sciss.fscape.Graph.{ProductReader, RefMapIn} import de.sciss.fscape.UGenSource.unwrap import de.sciss.fscape.stream.{StreamIn, StreamOut} import scala.collection.immutable.{IndexedSeq => Vec} object Drop extends ProductReader[Drop] { override def read(in: RefMapIn, key: String, arity: Int): Drop = { require (arity == 2) val _in = in.readGE() val _length = in.readGE() new Drop(_in, _length) } } final case class Drop(in: GE, length: GE) extends UGenSource.SingleOut { protected def makeUGens(implicit b: UGenGraph.Builder): UGenInLike = unwrap(this, Vector(in.expand, length.expand)) protected def makeUGen(args: Vec[UGenIn])(implicit b: UGenGraph.Builder): UGenInLike = UGen.SingleOut(this, args) private[fscape] def makeStream(args: Vec[StreamIn])(implicit b: stream.Builder): StreamOut = { val Vec(in, length) = args: @unchecked import in.tpe val out = stream.Drop[in.A, in.Buf](in = in.toElem, length = length.toLong) tpe.mkStreamOut(out) } }
Sciss/FScape-next
core/shared/src/main/scala/de/sciss/fscape/graph/Drop.scala
Scala
agpl-3.0
1,338
/** * This file is part of mycollab-services. * * mycollab-services 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. * * mycollab-services 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 mycollab-services. If not, see <http://www.gnu.org/licenses/>. */ package com.esofthead.mycollab.schedule.email import scala.collection.mutable._ /** * @author MyCollab Ltd * @since 5.1.0 */ class MailStyles { private val styles: Map[String, String] = Map(); styles.put("footer_background", "#3A3A3A") styles.put("font", "13px Arial, 'Times New Roman', sans-serif") styles.put("background", "#FFFFFF") styles.put("link_color", "#006DAC") def get(name: String): String = { val option: Option[String] = styles.get(name) option.get } } object MailStyles { private val _instance: MailStyles = new MailStyles() def instance(): MailStyles = _instance }
maduhu/mycollab
mycollab-services/src/main/scala/com/esofthead/mycollab/schedule/email/MailStyles.scala
Scala
agpl-3.0
1,356
/* * 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.spark.testsuite.createTable import org.apache.spark.sql.{AnalysisException, CarbonEnv, Row} import org.apache.spark.sql.catalyst.analysis.TableAlreadyExistsException import org.apache.spark.sql.hive.CarbonRelation import org.apache.spark.sql.test.SparkTestQueryExecutor import org.apache.spark.sql.test.util.QueryTest import org.scalatest.BeforeAndAfterAll import org.apache.carbondata.core.constants.CarbonCommonConstants import org.apache.carbondata.core.datastore.filesystem.{CarbonFile, CarbonFileFilter} import org.apache.carbondata.core.datastore.impl.FileFactory import org.apache.carbondata.core.util.CarbonProperties /** * test functionality for create table as select command */ class TestCreateTableAsSelect extends QueryTest with BeforeAndAfterAll { private def createTablesAndInsertData { // create carbon table and insert data sql("CREATE TABLE carbon_ctas_test(key INT, value STRING) STORED AS carbondata") sql("insert into carbon_ctas_test select 100,'spark'") sql("insert into carbon_ctas_test select 200,'hive'") // create parquet table and insert data sql("CREATE TABLE parquet_ctas_test(key INT, value STRING) STORED as parquet") sql("insert into parquet_ctas_test select 100,'spark'") sql("insert into parquet_ctas_test select 200,'hive'") // create hive table and insert data sql("CREATE TABLE orc_ctas_test(key INT, value STRING) STORED as ORC") sql("insert into orc_ctas_test select 100,'spark'") sql("insert into orc_ctas_test select 200,'hive'") } override def beforeAll { sql("DROP TABLE IF EXISTS carbon_ctas_test") sql("DROP TABLE IF EXISTS parquet_ctas_test") sql("DROP TABLE IF EXISTS orc_ctas_test") createTablesAndInsertData CarbonProperties.getInstance(). addProperty(CarbonCommonConstants.COMPACTION_SEGMENT_LEVEL_THRESHOLD, CarbonCommonConstants.DEFAULT_SEGMENT_LEVEL_THRESHOLD) } test("test create table as select with select from same carbon table name with if not exists clause") { sql("drop table if exists ctas_same_table_name") sql("CREATE TABLE ctas_same_table_name(key INT, value STRING) STORED AS carbondata") checkExistence(sql("SHOW TABLES"), true, "ctas_same_table_name") sql( """ | CREATE TABLE IF NOT EXISTS ctas_same_table_name | STORED AS carbondata | AS SELECT * FROM ctas_same_table_name """.stripMargin) val e = intercept[TableAlreadyExistsException] { sql( """ | CREATE TABLE ctas_same_table_name | STORED AS carbondata | AS SELECT * FROM ctas_same_table_name """.stripMargin) } assert(e.getMessage().contains("Table or view 'ctas_same_table_name' already exists")) } test("test create table as select with select from same table name when table does not exists") { sql("drop table if exists ctas_same_table_name") intercept[Exception] { sql("create table ctas_same_table_name STORED AS carbondata as select * from ctas_same_table_name") } } test("test create table as select with select from another carbon table") { sql("DROP TABLE IF EXISTS ctas_select_carbon") sql("create table ctas_select_carbon STORED AS carbondata as select * from carbon_ctas_test") checkAnswer(sql("select * from ctas_select_carbon"), sql("select * from carbon_ctas_test")) } test("test create table as select with select from another parquet table") { sql("DROP TABLE IF EXISTS ctas_select_parquet") sql("create table ctas_select_parquet STORED AS carbondata as select * from parquet_ctas_test") checkAnswer(sql("select * from ctas_select_parquet"), sql("select * from parquet_ctas_test")) } test("test create table as select with select from another hive/orc table") { sql("DROP TABLE IF EXISTS ctas_select_orc") sql("create table ctas_select_orc STORED AS carbondata as select * from orc_ctas_test") checkAnswer(sql("select * from ctas_select_orc"), sql("select * from orc_ctas_test")) } test("test create table as select with where clause in select from carbon table that returns data") { sql("DROP TABLE IF EXISTS ctas_select_where_carbon") sql("create table ctas_select_where_carbon STORED AS carbondata as select * from carbon_ctas_test where key=100") checkAnswer(sql("select * from ctas_select_where_carbon"), sql("select * from carbon_ctas_test where key=100")) } test( "test create table as select with where clause in select from carbon table that does not return data") { sql("DROP TABLE IF EXISTS ctas_select_where_carbon") sql("create table ctas_select_where_carbon STORED AS carbondata as select * from carbon_ctas_test where key=300") checkAnswer(sql("select * from ctas_select_where_carbon"), sql("select * from carbon_ctas_test where key=300")) } test("test create table as select with where clause in select from carbon table and load again") { sql("DROP TABLE IF EXISTS ctas_select_where_carbon") sql("create table ctas_select_where_carbon STORED AS carbondata as select * from carbon_ctas_test where key=100") sql("insert into ctas_select_where_carbon select 200,'hive'") checkAnswer(sql("select * from ctas_select_where_carbon"), sql("select * from carbon_ctas_test")) } test("test create table as select with where clause in select from parquet table") { sql("DROP TABLE IF EXISTS ctas_select_where_parquet") sql("create table ctas_select_where_parquet STORED AS carbondata as select * from parquet_ctas_test where key=100") checkAnswer(sql("select * from ctas_select_where_parquet"), sql("select * from parquet_ctas_test where key=100")) } test("test create table as select with where clause in select from hive/orc table") { sql("DROP TABLE IF EXISTS ctas_select_where_orc") sql("create table ctas_select_where_orc STORED AS carbondata as select * from orc_ctas_test where key=100") checkAnswer(sql("select * from ctas_select_where_orc"), sql("select * from orc_ctas_test where key=100")) } test("test create table as select with select directly having the data") { sql("DROP TABLE IF EXISTS ctas_select_direct_data") sql("create table ctas_select_direct_data STORED AS carbondata as select 300,'carbondata'") checkAnswer(sql("select * from ctas_select_direct_data"), Seq(Row(300, "carbondata"))) } test("test create table as select with TBLPROPERTIES") { sql("DROP TABLE IF EXISTS ctas_tblproperties_testt") sql( "create table ctas_tblproperties_testt STORED AS carbondata TBLPROPERTIES" + "('sort_scope'='global_sort') as select * from carbon_ctas_test") checkAnswer(sql("select * from ctas_tblproperties_testt"), sql("select * from carbon_ctas_test")) val carbonTable = CarbonEnv.getInstance(SparkTestQueryExecutor.spark).carbonMetaStore .lookupRelation(Option("default"), "ctas_tblproperties_testt")(SparkTestQueryExecutor.spark) .asInstanceOf[CarbonRelation].carbonTable val metadataFolderPath: CarbonFile = FileFactory.getCarbonFile(carbonTable.getMetadataPath) assert(metadataFolderPath.exists()) } test("test create table as select with column name as tupleid") { intercept[Exception] { sql("create table t2 STORED AS carbondata as select count(value) AS tupleid from carbon_ctas_test") } } test("test create table as select with column name as positionid") { intercept[Exception] { sql("create table t2 STORED AS carbondata as select count(value) AS positionid from carbon_ctas_test") } } test("test create table as select with column name as positionreference") { intercept[Exception] { sql("create table t2 STORED AS carbondata as select count(value) AS positionreference from carbon_ctas_test") } } test("test create table as select with where clause in select from parquet table that does not return data") { sql("DROP TABLE IF EXISTS ctas_select_where_parquet") sql( """ | CREATE TABLE ctas_select_where_parquet | STORED AS carbondata | as select * FROM parquet_ctas_test | where key=300""".stripMargin) checkAnswer(sql("SELECT * FROM ctas_select_where_parquet"), sql("SELECT * FROM parquet_ctas_test where key=300")) } test("test create table as select with where clause in select from hive/orc table that does not return data") { sql("DROP TABLE IF EXISTS ctas_select_where_orc") sql( """ | CREATE TABLE ctas_select_where_orc | STORED AS carbondata | AS SELECT * FROM orc_ctas_test | where key=300""".stripMargin) checkAnswer(sql("SELECT * FROM ctas_select_where_orc"), sql("SELECT * FROM orc_ctas_test where key=300")) } test("test create table as select with select from same carbon table name with if not exists clause and source table not exists") { sql("DROP TABLE IF EXISTS ctas_same_table_name") checkExistence(sql("SHOW TABLES"), false, "ctas_same_table_name") //TODO: should throw NoSuchTableException val e = intercept[AnalysisException] { sql( """ | CREATE TABLE IF NOT EXISTS ctas_same_table_name | STORED AS carbondata | AS SELECT * FROM ctas_same_table_name """.stripMargin) } assert(e.getMessage().contains("Table or view not found: ctas_same_table_name")) } test("add example for documentation") { sql("DROP TABLE IF EXISTS target_table") sql("DROP TABLE IF EXISTS source_table") // create carbon table and insert data sql( """ | CREATE TABLE source_table( | id INT, | name STRING, | city STRING, | age INT) | STORED AS parquet | """.stripMargin) sql("INSERT INTO source_table SELECT 1,'bob','shenzhen',27") sql("INSERT INTO source_table SELECT 2,'david','shenzhen',31") sql( """ | CREATE TABLE target_table | STORED AS carbondata | AS | SELECT city,avg(age) FROM source_table group by city """.stripMargin) // results: // sql("SELECT * FROM target_table").show // +--------+--------+ // | city|avg(age)| // +--------+--------+ // |shenzhen| 29.0| // +--------+--------+ checkAnswer(sql("SELECT * FROM target_table"), Seq(Row("shenzhen", 29))) } test("test create table as select with sum,count,min,max") { sql("DROP TABLE IF EXISTS target_table") sql("DROP TABLE IF EXISTS source_table") // create carbon table and insert data sql( """ | CREATE TABLE source_table( | id INT, | name STRING, | city STRING, | age INT) | STORED AS carbondata """.stripMargin) sql("INSERT INTO source_table SELECT 1,'bob','shenzhen',27") sql("INSERT INTO source_table SELECT 2,'david','shenzhen',31") sql( """ | CREATE TABLE target_table | STORED AS carbondata | AS | SELECT city,sum(age),count(age),min(age),max(age) | FROM source_table group by city """.stripMargin) checkAnswer(sql("SELECT * FROM target_table"), Seq(Row("shenzhen", 58, 2, 27, 31))) } test("test create table as select with insert data into source_table after CTAS") { sql("DROP TABLE IF EXISTS target_table") sql("DROP TABLE IF EXISTS source_table") // create carbon table and insert data sql( """ | CREATE TABLE source_table( | id INT, | name STRING, | city STRING, | age INT) | STORED AS carbondata | """.stripMargin) sql("INSERT INTO source_table SELECT 1,'bob','shenzhen',27") sql("INSERT INTO source_table SELECT 2,'david','shenzhen',31") sql( """ | CREATE TABLE target_table | STORED AS carbondata | AS | SELECT city,sum(age),count(age),min(age),max(age) | FROM source_table group by city """.stripMargin) sql("INSERT INTO source_table SELECT 1,'bob','shenzhen',27") sql("INSERT INTO source_table SELECT 2,'david','shenzhen',31") checkAnswer(sql("SELECT * FROM target_table"), Seq(Row("shenzhen", 58, 2, 27, 31))) } test("test create table as select with auto merge") { CarbonProperties.getInstance(). addProperty(CarbonCommonConstants.ENABLE_AUTO_LOAD_MERGE, "true") sql("DROP TABLE IF EXISTS target_table") sql("DROP TABLE IF EXISTS source_table") // create carbon table and insert data sql( """ | CREATE TABLE source_table( | id INT, | name STRING, | city STRING, | age INT) | STORED AS carbondata | """.stripMargin) sql("INSERT INTO source_table SELECT 1,'bob','shenzhen',27") sql("INSERT INTO source_table SELECT 2,'david','shenzhen',31") sql( """ | CREATE TABLE target_table | STORED AS carbondata | AS | SELECT city,avg(age) | FROM source_table group by city """.stripMargin) sql("INSERT INTO source_table SELECT 1,'bob','shenzhen',27") sql("INSERT INTO source_table SELECT 2,'david','shenzhen',31") checkExistence(sql("SHOW SEGMENTS FOR TABLE source_table"), true, "Compacted") checkExistence(sql("SHOW SEGMENTS FOR TABLE target_table"), false, "Compacted") sql("INSERT INTO target_table SELECT 'shenzhen',8") sql("INSERT INTO target_table SELECT 'shenzhen',9") sql("INSERT INTO target_table SELECT 'shenzhen',3") checkExistence(sql("SHOW SEGMENTS FOR TABLE target_table"), true, "Compacted") checkAnswer(sql("SELECT * FROM target_table"), Seq(Row("shenzhen", 29), Row("shenzhen", 8), Row("shenzhen", 9), Row("shenzhen", 3))) CarbonProperties.getInstance(). addProperty(CarbonCommonConstants.ENABLE_AUTO_LOAD_MERGE, CarbonCommonConstants.DEFAULT_ENABLE_AUTO_LOAD_MERGE) } test("test create table as select with filter, <, and, >=") { sql("DROP TABLE IF EXISTS target_table") sql("DROP TABLE IF EXISTS source_table") // create carbon table and insert data sql( """ | CREATE TABLE source_table( | id INT, | name STRING, | city STRING, | age INT) | STORED AS carbondata | """.stripMargin) sql("INSERT INTO source_table SELECT 1,'bob','shenzhen',27") sql("INSERT INTO source_table SELECT 2,'david','shenzhen',31") sql("INSERT INTO source_table SELECT 3,'jack','shenzhen',5") sql("INSERT INTO source_table SELECT 4,'alice','shenzhen',35") sql( """ | CREATE TABLE target_table | STORED AS carbondata | AS | SELECT city,avg(age) | FROM source_table where age > 20 and age <= 31 GROUP BY city """.stripMargin) checkAnswer(sql("SELECT * FROM target_table"), Seq(Row("shenzhen", 29))) } test("test create table as select with filter, >=, or, =") { sql("DROP TABLE IF EXISTS target_table") sql("DROP TABLE IF EXISTS source_table") // create carbon table and insert data sql( """ | CREATE TABLE source_table( | id INT, | name STRING, | city STRING, | age INT) | STORED AS carbondata | """.stripMargin) sql("INSERT INTO source_table SELECT 1,'bob','shenzhen',27") sql("INSERT INTO source_table SELECT 2,'david','shenzhen',31") sql("INSERT INTO source_table SELECT 3,'jack','shenzhen',5") sql("INSERT INTO source_table SELECT 4,'alice','shenzhen',35") sql( """ | CREATE TABLE target_table | STORED AS carbondata | AS | SELECT city,avg(age) | FROM source_table where age >= 20 or age = 5 group by city """.stripMargin) checkAnswer(sql("SELECT * FROM target_table"), Seq(Row("shenzhen", 24.5))) } test("test duplicate columns with select query") { sql("DROP TABLE IF EXISTS target_table") sql("DROP TABLE IF EXISTS source_table") // create carbon table and insert data sql( """ | CREATE TABLE source_table( | id INT, | name STRING, | city STRING, | age INT) | STORED AS carbondata | """.stripMargin) sql("INSERT INTO source_table SELECT 1,'bob','shenzhen',27") val e = intercept[AnalysisException] { sql( """ | CREATE TABLE target_table | STORED AS carbondata | AS | SELECT t1.city, t2.city | FROM source_table t1, source_table t2 where t1.city=t2.city and t1.city = 'shenzhen' """.stripMargin) } e.getMessage().toString.contains("Duplicated column names found in table definition of " + "`target_table`: [\\"city\\"]") sql( """ | CREATE TABLE target_table | STORED AS carbondata | AS | SELECT t1.city as a, t2.city as b | FROM source_table t1, source_table t2 where t1.city=t2.city and t1.city = 'shenzhen' """.stripMargin) checkAnswer(sql("select * from target_table"), Seq(Row("shenzhen", "shenzhen"))) } override def afterAll { sql("DROP TABLE IF EXISTS carbon_ctas_test") sql("DROP TABLE IF EXISTS parquet_ctas_test") sql("DROP TABLE IF EXISTS orc_ctas_test") sql("DROP TABLE IF EXISTS ctas_same_table_name") sql("DROP TABLE IF EXISTS ctas_select_carbon") sql("DROP TABLE IF EXISTS ctas_select_direct_data") sql("DROP TABLE IF EXISTS ctas_select_parquet") sql("DROP TABLE IF EXISTS ctas_select_orc") sql("DROP TABLE IF EXISTS ctas_select_where_carbon") sql("DROP TABLE IF EXISTS ctas_select_where_parquet") sql("DROP TABLE IF EXISTS ctas_select_where_orc") sql("DROP TABLE IF EXISTS ctas_tblproperties_testt") sql("DROP TABLE IF EXISTS ctas_if_table_name") sql("DROP TABLE IF EXISTS source_table") sql("DROP TABLE IF EXISTS target_table") } }
jackylk/incubator-carbondata
integration/spark/src/test/scala/org/apache/carbondata/spark/testsuite/createTable/TestCreateTableAsSelect.scala
Scala
apache-2.0
18,900
package rwt.spritz import java.io._ import com.waywardcode.crypto._ object RePass { def repass(f : File, oldkey : String, newkey : String): String = { val headerBytes = new Array[Byte](SpritzHeader.size); val raf = new RandomAccessFile(f, "rw") try { raf.seek(0) raf.readFully(headerBytes) val is = new ByteArrayInputStream(headerBytes) val oldHdr = SpritzHeader.fromStream(is, oldkey) val os = new ByteArrayOutputStream() SpritzHeader.changeIV(oldHdr).write(os, newkey) raf.seek(0) raf.write(os.toByteArray) } catch { case e : Exception => return e.toString(); } finally { raf.close() } f.getName() } def cmd(args: List[String]) : Unit = { var oldPw : String = "" var newPw : String = "" @annotation.tailrec def parseArgs(args: List[String]) : List[String] = { args match { case "-op" :: pw :: rest => oldPw = pw parseArgs(rest) case "-np" :: pw :: rest => newPw = pw parseArgs(rest) case rest => rest } } var flist = parseArgs(args) if (oldPw.length == 0) { oldPw = Passwords.getPassword("Old Password: ", false).getOrElse("") if (oldPw.length == 0) { throw new Exception("Password Required!") } } if (newPw.length == 0) { newPw = Passwords.getPassword("New Password: ", true).getOrElse("") if (newPw.length == 0) { throw new Exception("Password Required!") } } flist.par.map(str => repass(new File(str),oldPw,newPw)).foreach(println) } }
rwtodd/spritz_cipher
scala_version/cmd/repass.scala
Scala
gpl-2.0
1,847
/* * Copyright 2001-2013 Artima, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.scalatest import org.scalatest.prop.Checkers import org.scalacheck._ import Arbitrary._ import Prop._ import org.scalatest.exceptions.TestFailedException class ShouldFullyMatchSpec extends Spec with Matchers with Checkers with ReturnsNormallyThrowsAssertion { /* s should include substring t s should include regex t s should startWith substring t s should startWith regex t s should endWith substring t s should endWith regex t s should fullyMatch regex t */ object `The fullyMatch regex syntax` { val decimal = """(-)?(\\d+)(\\.\\d*)?""" val decimalRegex = """(-)?(\\d+)(\\.\\d*)?""".r object `(when the regex is specified by a string)` { def `should do nothing if the string fully matches the regular expression specified as a string` { "1.7" should fullyMatch regex ("1.7") "1.7" should fullyMatch regex (decimal) "-1.8" should fullyMatch regex (decimal) "8" should fullyMatch regex (decimal) "1." should fullyMatch regex (decimal) } def `should do nothing if the string does not fully match the regular expression specified as a string when used with not` { "eight" should not { fullyMatch regex (decimal) } "1.eight" should not { fullyMatch regex (decimal) } "one.8" should not { fullyMatch regex (decimal) } "eight" should not fullyMatch regex (decimal) "1.eight" should not fullyMatch regex (decimal) "one.8" should not fullyMatch regex (decimal) "1.8-" should not fullyMatch regex (decimal) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-and expression` { "1.7" should (fullyMatch regex (decimal) and (fullyMatch regex (decimal))) "1.7" should ((fullyMatch regex (decimal)) and (fullyMatch regex (decimal))) "1.7" should (fullyMatch regex (decimal) and fullyMatch regex (decimal)) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-or expression` { "1.7" should (fullyMatch regex ("hello") or (fullyMatch regex (decimal))) "1.7" should ((fullyMatch regex ("hello")) or (fullyMatch regex (decimal))) "1.7" should (fullyMatch regex ("hello") or fullyMatch regex (decimal)) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-and expression with not` { "fred" should (not (fullyMatch regex ("bob")) and not (fullyMatch regex (decimal))) "fred" should ((not fullyMatch regex ("bob")) and (not fullyMatch regex (decimal))) "fred" should (not fullyMatch regex ("bob") and not fullyMatch regex (decimal)) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-or expression with not` { "fred" should (not (fullyMatch regex ("fred")) or not (fullyMatch regex (decimal))) "fred" should ((not fullyMatch regex ("fred")) or (not fullyMatch regex (decimal))) "fred" should (not fullyMatch regex ("fred") or not fullyMatch regex (decimal)) } def `should throw TestFailedException if the string does not match the regular expression specified as a string` { val caught1 = intercept[TestFailedException] { "1.7" should fullyMatch regex ("1.78") } assert(caught1.getMessage === "\\"1.7\\" did not fully match the regular expression 1.78") val caught2 = intercept[TestFailedException] { "1.7" should fullyMatch regex ("21.7") } assert(caught2.getMessage === "\\"1.7\\" did not fully match the regular expression 21.7") val caught3 = intercept[TestFailedException] { "-1.eight" should fullyMatch regex (decimal) } assert(caught3.getMessage === "\\"-1.eight\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught6 = intercept[TestFailedException] { "eight" should fullyMatch regex (decimal) } assert(caught6.getMessage === "\\"eight\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught7 = intercept[TestFailedException] { "1.eight" should fullyMatch regex (decimal) } assert(caught7.getMessage === "\\"1.eight\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught8 = intercept[TestFailedException] { "one.8" should fullyMatch regex (decimal) } assert(caught8.getMessage === "\\"one.8\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught9 = intercept[TestFailedException] { "1.8-" should fullyMatch regex (decimal) } assert(caught9.getMessage === "\\"1.8-\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string does matches the regular expression specified as a string when used with not` { val caught1 = intercept[TestFailedException] { "1.7" should not { fullyMatch regex ("1.7") } } assert(caught1.getMessage === "\\"1.7\\" fully matched the regular expression 1.7") val caught2 = intercept[TestFailedException] { "1.7" should not { fullyMatch regex (decimal) } } assert(caught2.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught3 = intercept[TestFailedException] { "-1.8" should not { fullyMatch regex (decimal) } } assert(caught3.getMessage === "\\"-1.8\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught4 = intercept[TestFailedException] { "8" should not { fullyMatch regex (decimal) } } assert(caught4.getMessage === "\\"8\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught5 = intercept[TestFailedException] { "1." should not { fullyMatch regex (decimal) } } assert(caught5.getMessage === "\\"1.\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught11 = intercept[TestFailedException] { "1.7" should not fullyMatch regex ("1.7") } assert(caught11.getMessage === "\\"1.7\\" fully matched the regular expression 1.7") val caught12 = intercept[TestFailedException] { "1.7" should not fullyMatch regex (decimal) } assert(caught12.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught13 = intercept[TestFailedException] { "-1.8" should not fullyMatch regex (decimal) } assert(caught13.getMessage === "\\"-1.8\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught14 = intercept[TestFailedException] { "8" should not fullyMatch regex (decimal) } assert(caught14.getMessage === "\\"8\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught15 = intercept[TestFailedException] { "1." should not fullyMatch regex (decimal) } assert(caught15.getMessage === "\\"1.\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "1.7" should (fullyMatch regex (decimal) and (fullyMatch regex ("1.8"))) } assert(caught1.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, but \\"1.7\\" did not fully match the regular expression 1.8") val caught2 = intercept[TestFailedException] { "1.7" should ((fullyMatch regex (decimal)) and (fullyMatch regex ("1.8"))) } assert(caught2.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, but \\"1.7\\" did not fully match the regular expression 1.8") val caught3 = intercept[TestFailedException] { "1.7" should (fullyMatch regex (decimal) and fullyMatch regex ("1.8")) } assert(caught3.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, but \\"1.7\\" did not fully match the regular expression 1.8") // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "1.eight" should (fullyMatch regex (decimal) and (fullyMatch regex ("1.8"))) } assert(caught4.getMessage === "\\"1.eight\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught5 = intercept[TestFailedException] { "1.eight" should ((fullyMatch regex (decimal)) and (fullyMatch regex ("1.8"))) } assert(caught5.getMessage === "\\"1.eight\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught6 = intercept[TestFailedException] { "1.eight" should (fullyMatch regex (decimal) and fullyMatch regex ("1.8")) } assert(caught6.getMessage === "\\"1.eight\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "1.seven" should (fullyMatch regex (decimal) or (fullyMatch regex ("1.8"))) } assert(caught1.getMessage === "\\"1.seven\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.seven\\" did not fully match the regular expression 1.8") val caught2 = intercept[TestFailedException] { "1.seven" should ((fullyMatch regex (decimal)) or (fullyMatch regex ("1.8"))) } assert(caught2.getMessage === "\\"1.seven\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.seven\\" did not fully match the regular expression 1.8") val caught3 = intercept[TestFailedException] { "1.seven" should (fullyMatch regex (decimal) or fullyMatch regex ("1.8")) } assert(caught3.getMessage === "\\"1.seven\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.seven\\" did not fully match the regular expression 1.8") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex ("1.8") and (not fullyMatch regex (decimal))) } assert(caught1.getMessage === "\\"1.7\\" did not fully match the regular expression 1.8, but \\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught2 = intercept[TestFailedException] { "1.7" should ((not fullyMatch regex ("1.8")) and (not fullyMatch regex (decimal))) } assert(caught2.getMessage === "\\"1.7\\" did not fully match the regular expression 1.8, but \\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught3 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex ("1.8") and not fullyMatch regex (decimal)) } assert(caught3.getMessage === "\\"1.7\\" did not fully match the regular expression 1.8, but \\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex (decimal) or (not fullyMatch regex ("1.7"))) } assert(caught1.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" fully matched the regular expression 1.7") val caught2 = intercept[TestFailedException] { "1.7" should ((not fullyMatch regex (decimal)) or (not fullyMatch regex ("1.7"))) } assert(caught2.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" fully matched the regular expression 1.7") val caught3 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex (decimal) or not fullyMatch regex ("1.7")) } assert(caught3.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" fully matched the regular expression 1.7") val caught4 = intercept[TestFailedException] { "1.7" should (not (fullyMatch regex (decimal)) or not (fullyMatch regex ("1.7"))) } assert(caught4.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" fully matched the regular expression 1.7") } } object `(when the regex is specified by an actual Regex)` { def `should do nothing if the string fully matches the regular expression specified as a string` { "1.7" should fullyMatch regex ("1.7") "1.7" should fullyMatch regex (decimalRegex) "-1.8" should fullyMatch regex (decimalRegex) "8" should fullyMatch regex (decimalRegex) "1." should fullyMatch regex (decimalRegex) } def `should do nothing if the string does not fully match the regular expression specified as a string when used with not` { "eight" should not { fullyMatch regex (decimalRegex) } "1.eight" should not { fullyMatch regex (decimalRegex) } "one.8" should not { fullyMatch regex (decimalRegex) } "eight" should not fullyMatch regex (decimalRegex) "1.eight" should not fullyMatch regex (decimalRegex) "one.8" should not fullyMatch regex (decimalRegex) "1.8-" should not fullyMatch regex (decimalRegex) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-and expression` { "1.7" should (fullyMatch regex (decimalRegex) and (fullyMatch regex (decimalRegex))) "1.7" should ((fullyMatch regex (decimalRegex)) and (fullyMatch regex (decimalRegex))) "1.7" should (fullyMatch regex (decimalRegex) and fullyMatch regex (decimalRegex)) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-or expression` { "1.7" should (fullyMatch regex ("hello") or (fullyMatch regex (decimalRegex))) "1.7" should ((fullyMatch regex ("hello")) or (fullyMatch regex (decimalRegex))) "1.7" should (fullyMatch regex ("hello") or fullyMatch regex (decimalRegex)) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-and expression with not` { "fred" should (not (fullyMatch regex ("bob")) and not (fullyMatch regex (decimalRegex))) "fred" should ((not fullyMatch regex ("bob")) and (not fullyMatch regex (decimalRegex))) "fred" should (not fullyMatch regex ("bob") and not fullyMatch regex (decimalRegex)) } def `should do nothing if the string does not fully match the regular expression specified as a string when used in a logical-or expression with not` { "fred" should (not (fullyMatch regex ("fred")) or not (fullyMatch regex (decimalRegex))) "fred" should ((not fullyMatch regex ("fred")) or (not fullyMatch regex (decimalRegex))) "fred" should (not fullyMatch regex ("fred") or not fullyMatch regex (decimalRegex)) } def `should throw TestFailedException if the string does not match the regular expression specified as a string` { val caught1 = intercept[TestFailedException] { "1.7" should fullyMatch regex ("1.78") } assert(caught1.getMessage === "\\"1.7\\" did not fully match the regular expression 1.78") val caught2 = intercept[TestFailedException] { "1.7" should fullyMatch regex ("21.7") } assert(caught2.getMessage === "\\"1.7\\" did not fully match the regular expression 21.7") val caught3 = intercept[TestFailedException] { "-1.eight" should fullyMatch regex (decimalRegex) } assert(caught3.getMessage === "\\"-1.eight\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught6 = intercept[TestFailedException] { "eight" should fullyMatch regex (decimalRegex) } assert(caught6.getMessage === "\\"eight\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught7 = intercept[TestFailedException] { "1.eight" should fullyMatch regex (decimalRegex) } assert(caught7.getMessage === "\\"1.eight\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught8 = intercept[TestFailedException] { "one.8" should fullyMatch regex (decimalRegex) } assert(caught8.getMessage === "\\"one.8\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught9 = intercept[TestFailedException] { "1.8-" should fullyMatch regex (decimalRegex) } assert(caught9.getMessage === "\\"1.8-\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string does matches the regular expression specified as a string when used with not` { val caught1 = intercept[TestFailedException] { "1.7" should not { fullyMatch regex ("1.7") } } assert(caught1.getMessage === "\\"1.7\\" fully matched the regular expression 1.7") val caught2 = intercept[TestFailedException] { "1.7" should not { fullyMatch regex (decimalRegex) } } assert(caught2.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught3 = intercept[TestFailedException] { "-1.8" should not { fullyMatch regex (decimalRegex) } } assert(caught3.getMessage === "\\"-1.8\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught4 = intercept[TestFailedException] { "8" should not { fullyMatch regex (decimalRegex) } } assert(caught4.getMessage === "\\"8\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught5 = intercept[TestFailedException] { "1." should not { fullyMatch regex (decimalRegex) } } assert(caught5.getMessage === "\\"1.\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught11 = intercept[TestFailedException] { "1.7" should not fullyMatch regex ("1.7") } assert(caught11.getMessage === "\\"1.7\\" fully matched the regular expression 1.7") val caught12 = intercept[TestFailedException] { "1.7" should not fullyMatch regex (decimalRegex) } assert(caught12.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught13 = intercept[TestFailedException] { "-1.8" should not fullyMatch regex (decimalRegex) } assert(caught13.getMessage === "\\"-1.8\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught14 = intercept[TestFailedException] { "8" should not fullyMatch regex (decimalRegex) } assert(caught14.getMessage === "\\"8\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught15 = intercept[TestFailedException] { "1." should not fullyMatch regex (decimalRegex) } assert(caught15.getMessage === "\\"1.\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-and expression` { val caught1 = intercept[TestFailedException] { "1.7" should (fullyMatch regex (decimalRegex) and (fullyMatch regex ("1.8"))) } assert(caught1.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, but \\"1.7\\" did not fully match the regular expression 1.8") val caught2 = intercept[TestFailedException] { "1.7" should ((fullyMatch regex (decimalRegex)) and (fullyMatch regex ("1.8"))) } assert(caught2.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, but \\"1.7\\" did not fully match the regular expression 1.8") val caught3 = intercept[TestFailedException] { "1.7" should (fullyMatch regex (decimalRegex) and fullyMatch regex ("1.8")) } assert(caught3.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, but \\"1.7\\" did not fully match the regular expression 1.8") // Check to make sure the error message "short circuits" (i.e., just reports the left side's failure) val caught4 = intercept[TestFailedException] { "1.eight" should (fullyMatch regex (decimalRegex) and (fullyMatch regex ("1.8"))) } assert(caught4.getMessage === "\\"1.eight\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught5 = intercept[TestFailedException] { "1.eight" should ((fullyMatch regex (decimalRegex)) and (fullyMatch regex ("1.8"))) } assert(caught5.getMessage === "\\"1.eight\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught6 = intercept[TestFailedException] { "1.eight" should (fullyMatch regex (decimalRegex) and fullyMatch regex ("1.8")) } assert(caught6.getMessage === "\\"1.eight\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-or expression` { val caught1 = intercept[TestFailedException] { "1.seven" should (fullyMatch regex (decimalRegex) or (fullyMatch regex ("1.8"))) } assert(caught1.getMessage === "\\"1.seven\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.seven\\" did not fully match the regular expression 1.8") val caught2 = intercept[TestFailedException] { "1.seven" should ((fullyMatch regex (decimalRegex)) or (fullyMatch regex ("1.8"))) } assert(caught2.getMessage === "\\"1.seven\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.seven\\" did not fully match the regular expression 1.8") val caught3 = intercept[TestFailedException] { "1.seven" should (fullyMatch regex (decimalRegex) or fullyMatch regex ("1.8")) } assert(caught3.getMessage === "\\"1.seven\\" did not fully match the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.seven\\" did not fully match the regular expression 1.8") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-and expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex ("1.8") and (not fullyMatch regex (decimalRegex))) } assert(caught1.getMessage === "\\"1.7\\" did not fully match the regular expression 1.8, but \\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught2 = intercept[TestFailedException] { "1.7" should ((not fullyMatch regex ("1.8")) and (not fullyMatch regex (decimalRegex))) } assert(caught2.getMessage === "\\"1.7\\" did not fully match the regular expression 1.8, but \\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") val caught3 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex ("1.8") and not fullyMatch regex (decimalRegex)) } assert(caught3.getMessage === "\\"1.7\\" did not fully match the regular expression 1.8, but \\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?") } def `should throw TestFailedException if the string fully matches the regular expression specified as a string when used in a logical-or expression used with not` { val caught1 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex (decimalRegex) or (not fullyMatch regex ("1.7"))) } assert(caught1.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" fully matched the regular expression 1.7") val caught2 = intercept[TestFailedException] { "1.7" should ((not fullyMatch regex (decimalRegex)) or (not fullyMatch regex ("1.7"))) } assert(caught2.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" fully matched the regular expression 1.7") val caught3 = intercept[TestFailedException] { "1.7" should (not fullyMatch regex (decimalRegex) or not fullyMatch regex ("1.7")) } assert(caught3.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" fully matched the regular expression 1.7") val caught4 = intercept[TestFailedException] { "1.7" should (not (fullyMatch regex (decimalRegex)) or not (fullyMatch regex ("1.7"))) } assert(caught4.getMessage === "\\"1.7\\" fully matched the regular expression (-)?(\\\\d+)(\\\\.\\\\d*)?, and \\"1.7\\" fully matched the regular expression 1.7") } } } }
svn2github/scalatest
src/test/scala/org/scalatest/ShouldFullyMatchSpec.scala
Scala
apache-2.0
26,822
/* * Copyright (C) 2012 Romain Reuillon * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openmole.plugin.task.external import java.io.File import org.openmole.core.tools.service.OS import org.openmole.core.workflow.builder.TaskBuilder import org.openmole.core.workflow.data._ import org.openmole.core.workflow.tools.ExpandedString import org.openmole.core.workflow.data.Prototype import org.openmole.plugin.task.external.ExternalTask._ import scala.collection.mutable.ListBuffer import org.openmole.core.workflow.task.PluginSet /** * Builder for task using external files or directories * * Use it to copy files or directories, from the dataflow or from your computer in the task * workspace and prior to the task execution and to get files generated by the * task after its execution. * */ abstract class ExternalTaskBuilder extends TaskBuilder { builder ⇒ private val _inputFiles = new ListBuffer[InputFile] private val _outputFiles = new ListBuffer[OutputFile] private val _resources = new ListBuffer[Resource] def inputFiles = _inputFiles.toList def outputFiles = _outputFiles.toList def resources = _resources.toList /** * Copy a file from your computer in the workspace of the task * * @param file the file or directory to copy in the task workspace * @param name the destination name of the file in the task workspace, by * default it is the same as the original file name * @param link tels if the entire content of the file should be copied or * if a symbolic link is suitable. In the case link is set to true openmole will * try to use a symbolic link if available on your system. * */ def addResource(file: File, name: Option[ExpandedString] = None, link: Boolean = false, inWorkDir: Boolean = false, os: OS = OS()): ExternalTaskBuilder.this.type = { _resources += Resource(file, name.getOrElse(file.getName), link, inWorkDir, os) this } /** * Copy a file or directory from the dataflow to the task workspace * * @param p the prototype of the data containing the file to be copied * @param name the destination name of the file in the task workspace * @param link @see addResouce * */ def addInputFile(p: Prototype[File], name: ExpandedString, link: Boolean = false, inWorkDir: Boolean = true): this.type = { _inputFiles += InputFile(p, name, link, inWorkDir) this addInput p this } /** * Get a file generate by the task and inject it in the dataflow * * @param name the name of the file to be injected * @param p the prototype that is injected * */ def addOutputFile(name: ExpandedString, p: Prototype[File], inWorkDir: Boolean = true): this.type = { _outputFiles += OutputFile(name, p, inWorkDir) this addOutput p this } trait Built extends super.Built { def inputFiles = builder.inputFiles.toList def outputFiles = builder.outputFiles.toList def resources = builder.resources.toList } }
ISCPIF/PSEExperiments
openmole-src/openmole/plugins/org.openmole.plugin.task.external/src/main/scala/org/openmole/plugin/task/external/ExternalTaskBuilder.scala
Scala
agpl-3.0
3,584
/* * Copyright (C) 2012-2014 Typesafe Inc. <http://www.typesafe.com> */ package com.qifun.statelessFuture package test package run package ifelse2 import language.{reflectiveCalls, postfixOps} import scala.concurrent.{ExecutionContext, Await} import scala.concurrent.duration._ import com.qifun.statelessFuture.test.Async.{async, await, future} import org.junit.Test import ExecutionContext.Implicits.global import AutoStart._ class TestIfElse2Class { import ExecutionContext.Implicits.global def base(x: Int): Future[Int] = future { x + 2 } def m(y: Int): Future[Int] = async { val f = base(y) var z = 0 if (y > 0) { val x = await(f) z = x + 2 } else { val x = await(f) z = x - 2 } z } } class IfElse2Spec { @Test def `variables of the same name in different blocks`() { val o = new TestIfElse2Class val fut = o.m(10) val res = Await.result(fut, 2 seconds) res mustBe (14) } }
Atry/stateless-future-test
test/src/test/scala/com/qifun/statelessFuture/test/run/ifelse2/ifelse2.scala
Scala
bsd-3-clause
972
/* * 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 scala.collection.mutable.{ArrayBuffer, ListBuffer} import scala.util.control.Breaks._ import org.apache.spark.CarbonInputMetrics import org.apache.spark.rdd.RDD import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions.{Alias, AttributeReference, GetArrayItem, GetStructField, NamedExpression} import org.apache.spark.sql.execution.command.management.CarbonInsertIntoCommand import org.apache.spark.sql.hive.CarbonRelation import org.apache.spark.sql.optimizer.CarbonFilters import org.apache.spark.sql.sources.{BaseRelation, Filter, InsertableRelation} import org.apache.spark.sql.types.{ArrayType, StructType} import org.apache.spark.sql.util.CarbonException import org.apache.carbondata.core.constants.CarbonCommonConstants import org.apache.carbondata.core.indexstore.PartitionSpec import org.apache.carbondata.core.metadata.AbsoluteTableIdentifier import org.apache.carbondata.core.metadata.schema.table.CarbonTable import org.apache.carbondata.core.scan.expression.Expression import org.apache.carbondata.core.scan.expression.logical.AndExpression import org.apache.carbondata.hadoop.CarbonProjection import org.apache.carbondata.hadoop.util.CarbonInputFormatUtil import org.apache.carbondata.spark.rdd.{CarbonScanRDD, SparkReadSupport} case class CarbonDatasourceHadoopRelation( sparkSession: SparkSession, paths: Array[String], parameters: Map[String, String], tableSchema: Option[StructType], isSubquery: ArrayBuffer[Boolean] = new ArrayBuffer[Boolean]()) extends BaseRelation with InsertableRelation { val caseInsensitiveMap: Map[String, String] = parameters.map(f => (f._1.toLowerCase, f._2)) lazy val identifier: AbsoluteTableIdentifier = AbsoluteTableIdentifier.from( paths.head, CarbonEnv.getDatabaseName(caseInsensitiveMap.get("dbname"))(sparkSession), caseInsensitiveMap("tablename")) lazy val databaseName: String = carbonTable.getDatabaseName lazy val tableName: String = carbonTable.getTableName CarbonSession.updateSessionInfoToCurrentThread(sparkSession) @transient lazy val carbonRelation: CarbonRelation = CarbonEnv.getInstance(sparkSession).carbonMetastore. createCarbonRelation(parameters, identifier, sparkSession) @transient lazy val carbonTable: CarbonTable = carbonRelation.carbonTable override def sqlContext: SQLContext = sparkSession.sqlContext override def schema: StructType = tableSchema.getOrElse(carbonRelation.schema) def buildScan(requiredColumns: Array[String], filterComplex: Seq[org.apache.spark.sql.catalyst.expressions.Expression], projects: Seq[NamedExpression], filters: Array[Filter], partitions: Seq[PartitionSpec]): RDD[InternalRow] = { val filterExpression: Option[Expression] = filters.flatMap { filter => CarbonFilters.createCarbonFilter(schema, filter) }.reduceOption(new AndExpression(_, _)) val projection = new CarbonProjection // As Filter pushdown for Complex datatype is not supported, if filter is applied on complex // column, then Projection pushdown on Complex Columns will not take effect. Hence, check if // filter contains Struct Complex Column. val complexFilterExists = filterComplex.map(col => col.map(_.isInstanceOf[GetStructField])) if (!complexFilterExists.exists(f => f.contains(true))) { var parentColumn = new ListBuffer[String] // In case of Struct or StructofStruct Complex type, get the project column for given // parent/child field and pushdown the corresponding project column. In case of Array, // ArrayofStruct or StructofArray, pushdown parent column var reqColumns = projects.map { case a@Alias(s: GetStructField, name) => var arrayTypeExists = false var ifGetArrayItemExists = s breakable({ while (ifGetArrayItemExists.containsChild != null) { if (ifGetArrayItemExists.childSchema.toString().contains("ArrayType")) { arrayTypeExists = ifGetArrayItemExists.childSchema.toString().contains("ArrayType") break } if (ifGetArrayItemExists.child.isInstanceOf[AttributeReference]) { arrayTypeExists = s.childSchema.toString().contains("ArrayType") break } else { if (ifGetArrayItemExists.child.isInstanceOf[GetArrayItem]) { arrayTypeExists = true break } else { ifGetArrayItemExists = ifGetArrayItemExists.child.asInstanceOf[GetStructField] } } } }) if (!arrayTypeExists) { parentColumn += s.toString().split("\\\\.")(0).replaceAll("#.*", "").toLowerCase parentColumn = parentColumn.distinct s.toString().replaceAll("#[0-9]*", "").toLowerCase } else { s.toString().split("\\\\.")(0).replaceAll("#.*", "").toLowerCase } case a@Alias(s: GetArrayItem, name) => s.toString().split("\\\\.")(0).replaceAll("#.*", "").toLowerCase case attributeReference: AttributeReference => var columnName: String = attributeReference.name requiredColumns.foreach(colName => if (colName.equalsIgnoreCase(attributeReference.name)) { columnName = colName }) columnName case other => None } reqColumns = reqColumns.filter(col => !col.equals(None)) var output = new ListBuffer[String] if (null != requiredColumns && requiredColumns.nonEmpty) { requiredColumns.foreach(col => { if (null != reqColumns && reqColumns.nonEmpty) { reqColumns.foreach(reqCol => { if (!reqCol.toString.equalsIgnoreCase(col) && !reqCol.toString.startsWith(col.toLowerCase + ".") && !parentColumn.contains(col.toLowerCase)) { output += col } else { output += reqCol.toString } }) } else { output += col } output = output.map(_.toLowerCase).distinct }) } output.toArray.foreach(projection.addColumn) } else { requiredColumns.foreach(projection.addColumn) } CarbonSession.threadUnset(CarbonCommonConstants.SUPPORT_DIRECT_QUERY_ON_DATAMAP) val inputMetricsStats: CarbonInputMetrics = new CarbonInputMetrics new CarbonScanRDD( sparkSession, projection, filterExpression.orNull, identifier, carbonTable.getTableInfo.serialize(), carbonTable.getTableInfo, inputMetricsStats, partitions) } override def unhandledFilters(filters: Array[Filter]): Array[Filter] = new Array[Filter](0) override def toString: String = { "CarbonDatasourceHadoopRelation [ " + "Database name :" + databaseName + ", " + "Table name :" + tableName + ", Schema :" + tableSchema + " ]" } override def sizeInBytes: Long = carbonRelation.sizeInBytes override def insert(data: DataFrame, overwrite: Boolean): Unit = { if (carbonRelation.output.size > CarbonCommonConstants.DEFAULT_MAX_NUMBER_OF_COLUMNS) { CarbonException.analysisException("Maximum supported column by carbon is: " + CarbonCommonConstants.DEFAULT_MAX_NUMBER_OF_COLUMNS) } if (data.logicalPlan.output.size >= carbonRelation.output.size) { CarbonInsertIntoCommand(this, data.logicalPlan, overwrite, Map.empty).run(sparkSession) } else { CarbonException.analysisException( "Cannot insert into target table because number of columns mismatch") } } }
sgururajshetty/carbondata
integration/spark2/src/main/scala/org/apache/spark/sql/CarbonDatasourceHadoopRelation.scala
Scala
apache-2.0
8,545
package at.logic.gapt.utils.logging import org.slf4j.LoggerFactory trait Logger { protected def loggerName = getClass.getName protected val log = LoggerFactory.getLogger( loggerName ) // Ordered by level of importance. // E.g. if the logging level is chosen to be info, info, warn and error // messages will be logged as well, but not debug and trace. protected def error( msg: => String ) = if ( log.isErrorEnabled ) log.error( msg ) protected def error( msg: => String, e: Throwable ) = { if ( log.isErrorEnabled ) log.error( msg, e ); throw e } protected def warn( msg: => String ) = if ( log.isWarnEnabled ) log.warn( msg ) protected def warn( msg: => String, e: Throwable ) = if ( log.isWarnEnabled ) log.warn( msg, e ) protected def info( msg: => String ) = if ( log.isInfoEnabled ) log.info( msg ) protected def debug( msg: => String ) = if ( log.isDebugEnabled ) log.debug( msg ) protected def trace( msg: => String ) = if ( log.isTraceEnabled ) log.trace( msg ) }
loewenheim/gapt
src/main/scala/at/logic/gapt/utils/logging/Logger.scala
Scala
gpl-3.0
1,001
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.hive.thriftserver import java.io.{File, FilenameFilter} import java.net.URL import java.nio.charset.StandardCharsets import java.sql.{Date, DriverManager, SQLException, Statement} import java.util.{Locale, UUID} import scala.collection.JavaConverters._ import scala.collection.mutable import scala.collection.mutable.ArrayBuffer import scala.concurrent.{ExecutionContext, Future, Promise} import scala.concurrent.duration._ import scala.io.Source import scala.util.Try import com.google.common.io.Files import org.apache.hadoop.hive.conf.HiveConf.ConfVars import org.apache.hive.jdbc.HiveDriver import org.apache.hive.service.auth.PlainSaslHelper import org.apache.hive.service.cli.{FetchOrientation, FetchType, GetInfoType, RowSet} import org.apache.hive.service.cli.thrift.ThriftCLIServiceClient import org.apache.hive.service.rpc.thrift.TCLIService.Client import org.apache.thrift.protocol.TBinaryProtocol import org.apache.thrift.transport.TSocket import org.scalatest.BeforeAndAfterAll import org.scalatest.concurrent.Eventually._ import org.apache.spark.{SparkException, SparkFunSuite} import org.apache.spark.ProcessTestUtils.ProcessOutputCapturer import org.apache.spark.internal.Logging import org.apache.spark.sql.hive.HiveUtils import org.apache.spark.sql.hive.test.HiveTestJars import org.apache.spark.sql.internal.SQLConf import org.apache.spark.sql.internal.StaticSQLConf.HIVE_THRIFT_SERVER_SINGLESESSION import org.apache.spark.util.{ShutdownHookManager, ThreadUtils, Utils} object TestData { def getTestDataFilePath(name: String): URL = { Thread.currentThread().getContextClassLoader.getResource(s"data/files/$name") } val smallKv = getTestDataFilePath("small_kv.txt") val smallKvWithNull = getTestDataFilePath("small_kv_with_null.txt") } class HiveThriftBinaryServerSuite extends HiveThriftServer2Test { override def mode: ServerMode.Value = ServerMode.binary private def withCLIServiceClient(f: ThriftCLIServiceClient => Unit): Unit = { // Transport creation logic below mimics HiveConnection.createBinaryTransport val rawTransport = new TSocket("localhost", serverPort) val user = System.getProperty("user.name") val transport = PlainSaslHelper.getPlainTransport(user, "anonymous", rawTransport) val protocol = new TBinaryProtocol(transport) val client = new ThriftCLIServiceClient(new Client(protocol)) transport.open() try f(client) finally transport.close() } test("GetInfo Thrift API") { withCLIServiceClient { client => val user = System.getProperty("user.name") val sessionHandle = client.openSession(user, "") assertResult("Spark SQL", "Wrong GetInfo(CLI_DBMS_NAME) result") { client.getInfo(sessionHandle, GetInfoType.CLI_DBMS_NAME).getStringValue } assertResult("Spark SQL", "Wrong GetInfo(CLI_SERVER_NAME) result") { client.getInfo(sessionHandle, GetInfoType.CLI_SERVER_NAME).getStringValue } assertResult(true, "Spark version shouldn't be \\"Unknown\\"") { val version = client.getInfo(sessionHandle, GetInfoType.CLI_DBMS_VER).getStringValue logInfo(s"Spark version: $version") version != "Unknown" } } } test("SPARK-16563 ThriftCLIService FetchResults repeat fetching result") { withCLIServiceClient { client => val user = System.getProperty("user.name") val sessionHandle = client.openSession(user, "") withJdbcStatement("test_16563") { statement => val queries = Seq( "CREATE TABLE test_16563(key INT, val STRING) USING hive", s"LOAD DATA LOCAL INPATH '${TestData.smallKv}' OVERWRITE INTO TABLE test_16563") queries.foreach(statement.execute) val confOverlay = new java.util.HashMap[java.lang.String, java.lang.String] val operationHandle = client.executeStatement( sessionHandle, "SELECT * FROM test_16563", confOverlay) // Fetch result first time assertResult(5, "Fetching result first time from next row") { val rows_next = client.fetchResults( operationHandle, FetchOrientation.FETCH_NEXT, 1000, FetchType.QUERY_OUTPUT) rows_next.numRows() } // Fetch result second time from first row assertResult(5, "Repeat fetching result from first row") { val rows_first = client.fetchResults( operationHandle, FetchOrientation.FETCH_FIRST, 1000, FetchType.QUERY_OUTPUT) rows_first.numRows() } } } } test("Support beeline --hiveconf and --hivevar") { withJdbcStatement() { statement => executeTest(hiveConfList) executeTest(hiveVarList) def executeTest(hiveList: String): Unit = { hiveList.split(";").foreach{ m => val kv = m.split("=") val k = kv(0) val v = kv(1) val modValue = s"${v}_MOD_VALUE" // select '${a}'; ---> avalue val resultSet = statement.executeQuery(s"select '$${$k}'") resultSet.next() assert(resultSet.getString(1) === v) statement.executeQuery(s"set $k=$modValue") val modResultSet = statement.executeQuery(s"select '$${$k}'") modResultSet.next() assert(modResultSet.getString(1) === s"$modValue") } } } } test("JDBC query execution") { withJdbcStatement("test") { statement => val queries = Seq( "SET spark.sql.shuffle.partitions=3", "CREATE TABLE test(key INT, val STRING) USING hive", s"LOAD DATA LOCAL INPATH '${TestData.smallKv}' OVERWRITE INTO TABLE test", "CACHE TABLE test") queries.foreach(statement.execute) assertResult(5, "Row count mismatch") { val resultSet = statement.executeQuery("SELECT COUNT(*) FROM test") resultSet.next() resultSet.getInt(1) } } } test("Checks Hive version") { withJdbcStatement() { statement => val resultSet = statement.executeQuery("SET spark.sql.hive.version") resultSet.next() assert(resultSet.getString(1) === "spark.sql.hive.version") assert(resultSet.getString(2) === HiveUtils.builtinHiveVersion) } } test("SPARK-3004 regression: result set containing NULL") { withJdbcStatement("test_null") { statement => val queries = Seq( "CREATE TABLE test_null(key INT, val STRING) USING hive", s"LOAD DATA LOCAL INPATH '${TestData.smallKvWithNull}' OVERWRITE INTO TABLE test_null") queries.foreach(statement.execute) val resultSet = statement.executeQuery("SELECT * FROM test_null WHERE key IS NULL") (0 until 5).foreach { _ => resultSet.next() assert(resultSet.getInt(1) === 0) assert(resultSet.wasNull()) } assert(!resultSet.next()) } } test("SPARK-4292 regression: result set iterator issue") { withJdbcStatement("test_4292") { statement => val queries = Seq( "CREATE TABLE test_4292(key INT, val STRING) USING hive", s"LOAD DATA LOCAL INPATH '${TestData.smallKv}' OVERWRITE INTO TABLE test_4292") queries.foreach(statement.execute) val resultSet = statement.executeQuery("SELECT key FROM test_4292") Seq(238, 86, 311, 27, 165).foreach { key => resultSet.next() assert(resultSet.getInt(1) === key) } } } test("SPARK-4309 regression: Date type support") { withJdbcStatement("test_date") { statement => val queries = Seq( "CREATE TABLE test_date(key INT, value STRING) USING hive", s"LOAD DATA LOCAL INPATH '${TestData.smallKv}' OVERWRITE INTO TABLE test_date") queries.foreach(statement.execute) assertResult(Date.valueOf("2011-01-01")) { val resultSet = statement.executeQuery( "SELECT CAST('2011-01-01' as date) FROM test_date LIMIT 1") resultSet.next() resultSet.getDate(1) } } } test("SPARK-4407 regression: Complex type support") { withJdbcStatement("test_map") { statement => val queries = Seq( "CREATE TABLE test_map(key INT, value STRING) USING hive", s"LOAD DATA LOCAL INPATH '${TestData.smallKv}' OVERWRITE INTO TABLE test_map") queries.foreach(statement.execute) assertResult("""{238:"val_238"}""") { val resultSet = statement.executeQuery("SELECT MAP(key, value) FROM test_map LIMIT 1") resultSet.next() resultSet.getString(1) } assertResult("""["238","val_238"]""") { val resultSet = statement.executeQuery( "SELECT ARRAY(CAST(key AS STRING), value) FROM test_map LIMIT 1") resultSet.next() resultSet.getString(1) } } } test("SPARK-12143 regression: Binary type support") { withJdbcStatement("test_binary") { statement => val queries = Seq( "CREATE TABLE test_binary(key INT, value STRING) USING hive", s"LOAD DATA LOCAL INPATH '${TestData.smallKv}' OVERWRITE INTO TABLE test_binary") queries.foreach(statement.execute) val expected: Array[Byte] = "val_238".getBytes assertResult(expected) { val resultSet = statement.executeQuery( "SELECT CAST(value as BINARY) FROM test_binary LIMIT 1") resultSet.next() resultSet.getObject(1) } } } test("test multiple session") { var defaultV1: String = null var defaultV2: String = null var data: ArrayBuffer[Int] = null withMultipleConnectionJdbcStatement("test_map", "db1.test_map2")( // create table { statement => val queries = Seq( "CREATE TABLE test_map(key INT, value STRING) USING hive", s"LOAD DATA LOCAL INPATH '${TestData.smallKv}' OVERWRITE INTO TABLE test_map", "CACHE TABLE test_table AS SELECT key FROM test_map ORDER BY key DESC", "CREATE DATABASE db1") queries.foreach(statement.execute) val plan = statement.executeQuery("explain select * from test_table") plan.next() plan.next() assert(plan.getString(1).contains("Scan In-memory table test_table")) val rs1 = statement.executeQuery("SELECT key FROM test_table ORDER BY KEY DESC") val buf1 = new collection.mutable.ArrayBuffer[Int]() while (rs1.next()) { buf1 += rs1.getInt(1) } rs1.close() val rs2 = statement.executeQuery("SELECT key FROM test_map ORDER BY KEY DESC") val buf2 = new collection.mutable.ArrayBuffer[Int]() while (rs2.next()) { buf2 += rs2.getInt(1) } rs2.close() assert(buf1 === buf2) data = buf1 }, // first session, we get the default value of the session status { statement => val rs1 = statement.executeQuery(s"SET ${SQLConf.SHUFFLE_PARTITIONS.key}") rs1.next() defaultV1 = rs1.getString(1) assert(defaultV1 != "200") rs1.close() val rs2 = statement.executeQuery("SET hive.cli.print.header") rs2.next() defaultV2 = rs2.getString(1) assert(defaultV1 != "true") rs2.close() }, // second session, we update the session status { statement => val queries = Seq( s"SET ${SQLConf.SHUFFLE_PARTITIONS.key}=291", "SET hive.cli.print.header=true" ) queries.map(statement.execute) val rs1 = statement.executeQuery(s"SET ${SQLConf.SHUFFLE_PARTITIONS.key}") rs1.next() assert("spark.sql.shuffle.partitions" === rs1.getString(1)) assert("291" === rs1.getString(2)) rs1.close() val rs2 = statement.executeQuery("SET hive.cli.print.header") rs2.next() assert("hive.cli.print.header" === rs2.getString(1)) assert("true" === rs2.getString(2)) rs2.close() }, // third session, we get the latest session status, supposed to be the // default value { statement => val rs1 = statement.executeQuery(s"SET ${SQLConf.SHUFFLE_PARTITIONS.key}") rs1.next() assert(defaultV1 === rs1.getString(1)) rs1.close() val rs2 = statement.executeQuery("SET hive.cli.print.header") rs2.next() assert(defaultV2 === rs2.getString(1)) rs2.close() }, // try to access the cached data in another session { statement => // Cached temporary table can't be accessed by other sessions intercept[SQLException] { statement.executeQuery("SELECT key FROM test_table ORDER BY KEY DESC") } // The cached temporary table can be used indirectly if the query matches. val plan = statement.executeQuery("explain select key from test_map ORDER BY key DESC") plan.next() plan.next() assert(plan.getString(1).contains("Scan In-memory table test_table")) val rs = statement.executeQuery("SELECT key FROM test_map ORDER BY KEY DESC") val buf = new collection.mutable.ArrayBuffer[Int]() while (rs.next()) { buf += rs.getInt(1) } rs.close() assert(buf === data) }, // switch another database { statement => statement.execute("USE db1") // there is no test_map table in db1 intercept[SQLException] { statement.executeQuery("SELECT key FROM test_map ORDER BY KEY DESC") } statement.execute("CREATE TABLE test_map2(key INT, value STRING)") }, // access default database { statement => // current database should still be `default` intercept[SQLException] { statement.executeQuery("SELECT key FROM test_map2") } statement.execute("USE db1") // access test_map2 statement.executeQuery("SELECT key from test_map2") } ) } // This test often hangs and then times out, leaving the hanging processes. // Let's ignore it and improve the test. ignore("test jdbc cancel") { withJdbcStatement("test_map") { statement => val queries = Seq( "CREATE TABLE test_map(key INT, value STRING)", s"LOAD DATA LOCAL INPATH '${TestData.smallKv}' OVERWRITE INTO TABLE test_map") queries.foreach(statement.execute) implicit val ec = ExecutionContext.fromExecutorService( ThreadUtils.newDaemonSingleThreadExecutor("test-jdbc-cancel")) try { // Start a very-long-running query that will take hours to finish, then cancel it in order // to demonstrate that cancellation works. val f = Future { statement.executeQuery( "SELECT COUNT(*) FROM test_map " + List.fill(10)("join test_map").mkString(" ")) } // Note that this is slightly race-prone: if the cancel is issued before the statement // begins executing then we'll fail with a timeout. As a result, this fixed delay is set // slightly more conservatively than may be strictly necessary. Thread.sleep(1000) statement.cancel() val e = intercept[SparkException] { ThreadUtils.awaitResult(f, 3.minute) }.getCause assert(e.isInstanceOf[SQLException]) assert(e.getMessage.contains("cancelled")) // Cancellation is a no-op if spark.sql.hive.thriftServer.async=false statement.executeQuery("SET spark.sql.hive.thriftServer.async=false") try { val sf = Future { statement.executeQuery( "SELECT COUNT(*) FROM test_map " + List.fill(4)("join test_map").mkString(" ") ) } // Similarly, this is also slightly race-prone on fast machines where the query above // might race and complete before we issue the cancel. Thread.sleep(1000) statement.cancel() val rs1 = ThreadUtils.awaitResult(sf, 3.minute) rs1.next() assert(rs1.getInt(1) === math.pow(5, 5)) rs1.close() val rs2 = statement.executeQuery("SELECT COUNT(*) FROM test_map") rs2.next() assert(rs2.getInt(1) === 5) rs2.close() } finally { statement.executeQuery("SET spark.sql.hive.thriftServer.async=true") } } finally { ec.shutdownNow() } } } test("test add jar") { withMultipleConnectionJdbcStatement("smallKV", "addJar")( { statement => val jarFile = HiveTestJars.getHiveHcatalogCoreJar().getCanonicalPath statement.executeQuery(s"ADD JAR $jarFile") }, { statement => val queries = Seq( "CREATE TABLE smallKV(key INT, val STRING) USING hive", s"LOAD DATA LOCAL INPATH '${TestData.smallKv}' OVERWRITE INTO TABLE smallKV", """CREATE TABLE addJar(key string) |ROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe' """.stripMargin) queries.foreach(statement.execute) statement.executeQuery( """ |INSERT INTO TABLE addJar SELECT 'k1' as key FROM smallKV limit 1 """.stripMargin) val actualResult = statement.executeQuery("SELECT key FROM addJar") val actualResultBuffer = new collection.mutable.ArrayBuffer[String]() while (actualResult.next()) { actualResultBuffer += actualResult.getString(1) } actualResult.close() val expectedResult = statement.executeQuery("SELECT 'k1'") val expectedResultBuffer = new collection.mutable.ArrayBuffer[String]() while (expectedResult.next()) { expectedResultBuffer += expectedResult.getString(1) } expectedResult.close() assert(expectedResultBuffer === actualResultBuffer) } ) } test("Checks Hive version via SET -v") { withJdbcStatement() { statement => val resultSet = statement.executeQuery("SET -v") val conf = mutable.Map.empty[String, String] while (resultSet.next()) { conf += resultSet.getString(1) -> resultSet.getString(2) } assert(conf.get(HiveUtils.BUILTIN_HIVE_VERSION.key) === Some(HiveUtils.builtinHiveVersion)) } } test("Checks Hive version via SET") { withJdbcStatement() { statement => val resultSet = statement.executeQuery("SET") val conf = mutable.Map.empty[String, String] while (resultSet.next()) { conf += resultSet.getString(1) -> resultSet.getString(2) } assert(conf.get(HiveUtils.BUILTIN_HIVE_VERSION.key) === Some(HiveUtils.builtinHiveVersion)) } } test("SPARK-11595 ADD JAR with input path having URL scheme") { withJdbcStatement("test_udtf") { statement => try { val jarPath = "../hive/src/test/resources/TestUDTF.jar" val jarURL = s"file://${System.getProperty("user.dir")}/$jarPath" Seq( s"ADD JAR $jarURL", s"""CREATE TEMPORARY FUNCTION udtf_count2 |AS 'org.apache.spark.sql.hive.execution.GenericUDTFCount2' """.stripMargin ).foreach(statement.execute) val rs1 = statement.executeQuery("DESCRIBE FUNCTION udtf_count2") assert(rs1.next()) assert(rs1.getString(1) === "Function: udtf_count2") assert(rs1.next()) assertResult("Class: org.apache.spark.sql.hive.execution.GenericUDTFCount2") { rs1.getString(1) } assert(rs1.next()) assert(rs1.getString(1) === "Usage: N/A.") val dataPath = "../hive/src/test/resources/data/files/kv1.txt" Seq( "CREATE TABLE test_udtf(key INT, value STRING) USING hive", s"LOAD DATA LOCAL INPATH '$dataPath' OVERWRITE INTO TABLE test_udtf" ).foreach(statement.execute) val rs2 = statement.executeQuery( "SELECT key, cc FROM test_udtf LATERAL VIEW udtf_count2(value) dd AS cc") assert(rs2.next()) assert(rs2.getInt(1) === 97) assert(rs2.getInt(2) === 500) assert(rs2.next()) assert(rs2.getInt(1) === 97) assert(rs2.getInt(2) === 500) } finally { statement.executeQuery("DROP TEMPORARY FUNCTION udtf_count2") } } } test("SPARK-11043 check operation log root directory") { val expectedLine = "Operation log root directory is created: " + operationLogPath.getAbsoluteFile val bufferSrc = Source.fromFile(logPath) Utils.tryWithSafeFinally { assert(bufferSrc.getLines().exists(_.contains(expectedLine))) } { bufferSrc.close() } } test("SPARK-23547 Cleanup the .pipeout file when the Hive Session closed") { def pipeoutFileList(sessionID: UUID): Array[File] = { lScratchDir.listFiles(new FilenameFilter { override def accept(dir: File, name: String): Boolean = { name.startsWith(sessionID.toString) && name.endsWith(".pipeout") } }) } withCLIServiceClient { client => val user = System.getProperty("user.name") val sessionHandle = client.openSession(user, "") val sessionID = sessionHandle.getSessionId assert(pipeoutFileList(sessionID) === null) client.closeSession(sessionHandle) assert(pipeoutFileList(sessionID) === null) } } test("SPARK-24829 Checks cast as float") { withJdbcStatement() { statement => val resultSet = statement.executeQuery("SELECT CAST('4.56' AS FLOAT)") resultSet.next() assert(resultSet.getString(1) === "4.56") } } test("SPARK-28463: Thriftserver throws BigDecimal incompatible with HiveDecimal") { withJdbcStatement() { statement => val rs = statement.executeQuery("SELECT CAST(1 AS decimal(38, 18))") assert(rs.next()) assert(rs.getBigDecimal(1) === new java.math.BigDecimal("1.000000000000000000")) } } test("Support interval type") { withJdbcStatement() { statement => val rs = statement.executeQuery("SELECT interval 5 years 7 months") assert(rs.next()) assert(rs.getString(1) === "5-7") } withJdbcStatement() { statement => val rs = statement.executeQuery("SELECT interval 8 days 10 hours 5 minutes 10 seconds") assert(rs.next()) assert(rs.getString(1) === "8 10:05:10.000000000") } withJdbcStatement() { statement => val rs = statement.executeQuery("SELECT interval 3 days 1 hours") assert(rs.next()) assert(rs.getString(1) === "3 01:00:00.000000000") } // Invalid interval value withJdbcStatement() { statement => val e = intercept[SQLException] { statement.executeQuery("SELECT interval 5 yea 7 months") } assert(e.getMessage.contains("org.apache.spark.sql.catalyst.parser.ParseException")) } withJdbcStatement() { statement => val e = intercept[SQLException] { statement.executeQuery("SELECT interval 8 days 10 hours 5 minutes 10 secon") } assert(e.getMessage.contains("org.apache.spark.sql.catalyst.parser.ParseException")) } withJdbcStatement() { statement => val e = intercept[SQLException] { statement.executeQuery("SELECT interval 3 months 1 hou") } assert(e.getMessage.contains("org.apache.spark.sql.catalyst.parser.ParseException")) } withJdbcStatement() { statement => val rs = statement.executeQuery("SELECT interval '3-1' year to month;") assert(rs.next()) assert(rs.getString(1) === "3-1") } withJdbcStatement() { statement => val rs = statement.executeQuery("SELECT interval '3 1:1:1' day to second;") assert(rs.next()) assert(rs.getString(1) === "3 01:01:01.000000000") } } test("Query Intervals in VIEWs through thrift server") { val viewName1 = "view_interval_1" val viewName2 = "view_interval_2" val ddl1 = s""" |CREATE GLOBAL TEMP VIEW $viewName1 |AS SELECT | INTERVAL 1 DAY AS a, | INTERVAL '2-1' YEAR TO MONTH AS b, | INTERVAL '3 1:1:1' DAY TO SECOND AS c """.stripMargin val ddl2 = s"CREATE TEMP VIEW $viewName2 as select * from global_temp.$viewName1" withJdbcStatement(viewName1, viewName2) { statement => statement.executeQuery(ddl1) statement.executeQuery(ddl2) val rs = statement.executeQuery( s""" |SELECT v1.a AS a1, v2.a AS a2, | v1.b AS b1, v2.b AS b2, | v1.c AS c1, v2.c AS c2 |FROM global_temp.$viewName1 v1 |JOIN $viewName2 v2 |ON date_part('DAY', v1.a) = date_part('DAY', v2.a) | AND v1.b = v2.b | AND v1.c = v2.c |""".stripMargin) while (rs.next()) { assert(rs.getString("a1") === "1 00:00:00.000000000") assert(rs.getString("a2") === "1 00:00:00.000000000") assert(rs.getString("b1") === "2-1") assert(rs.getString("b2") === "2-1") assert(rs.getString("c1") === "3 01:01:01.000000000") assert(rs.getString("c2") === "3 01:01:01.000000000") } } } test("ThriftCLIService FetchResults FETCH_FIRST, FETCH_NEXT, FETCH_PRIOR") { def checkResult(rows: RowSet, start: Long, end: Long): Unit = { assert(rows.getStartOffset() == start) assert(rows.numRows() == end - start) rows.iterator.asScala.zip((start until end).iterator).foreach { case (row, v) => assert(row(0).asInstanceOf[Long] === v) } } withCLIServiceClient { client => val user = System.getProperty("user.name") val sessionHandle = client.openSession(user, "") val confOverlay = new java.util.HashMap[java.lang.String, java.lang.String] val operationHandle = client.executeStatement( sessionHandle, "SELECT * FROM range(10)", confOverlay) // 10 rows result with sequence 0, 1, 2, ..., 9 var rows: RowSet = null // Fetch 5 rows with FETCH_NEXT rows = client.fetchResults( operationHandle, FetchOrientation.FETCH_NEXT, 5, FetchType.QUERY_OUTPUT) checkResult(rows, 0, 5) // fetched [0, 5) // Fetch another 2 rows with FETCH_NEXT rows = client.fetchResults( operationHandle, FetchOrientation.FETCH_NEXT, 2, FetchType.QUERY_OUTPUT) checkResult(rows, 5, 7) // fetched [5, 7) // FETCH_PRIOR 3 rows rows = client.fetchResults( operationHandle, FetchOrientation.FETCH_PRIOR, 3, FetchType.QUERY_OUTPUT) checkResult(rows, 2, 5) // fetched [2, 5) // FETCH_PRIOR again will scroll back to 0, and then the returned result // may overlap the results of previous FETCH_PRIOR rows = client.fetchResults( operationHandle, FetchOrientation.FETCH_PRIOR, 3, FetchType.QUERY_OUTPUT) checkResult(rows, 0, 3) // fetched [0, 3) // FETCH_PRIOR again will stay at 0 rows = client.fetchResults( operationHandle, FetchOrientation.FETCH_PRIOR, 4, FetchType.QUERY_OUTPUT) checkResult(rows, 0, 4) // fetched [0, 4) // FETCH_NEXT will continue moving forward from offset 4 rows = client.fetchResults( operationHandle, FetchOrientation.FETCH_NEXT, 10, FetchType.QUERY_OUTPUT) checkResult(rows, 4, 10) // fetched [4, 10) until the end of results // FETCH_NEXT is at end of results rows = client.fetchResults( operationHandle, FetchOrientation.FETCH_NEXT, 5, FetchType.QUERY_OUTPUT) checkResult(rows, 10, 10) // fetched empty [10, 10) (at end of results) // FETCH_NEXT is at end of results again rows = client.fetchResults( operationHandle, FetchOrientation.FETCH_NEXT, 2, FetchType.QUERY_OUTPUT) checkResult(rows, 10, 10) // fetched empty [10, 10) (at end of results) // FETCH_PRIOR 1 rows yet again rows = client.fetchResults( operationHandle, FetchOrientation.FETCH_PRIOR, 1, FetchType.QUERY_OUTPUT) checkResult(rows, 9, 10) // fetched [9, 10) // FETCH_NEXT will return 0 yet again rows = client.fetchResults( operationHandle, FetchOrientation.FETCH_NEXT, 5, FetchType.QUERY_OUTPUT) checkResult(rows, 10, 10) // fetched empty [10, 10) (at end of results) // FETCH_FIRST results from first row rows = client.fetchResults( operationHandle, FetchOrientation.FETCH_FIRST, 3, FetchType.QUERY_OUTPUT) checkResult(rows, 0, 3) // fetch [0, 3) // Fetch till the end rows with FETCH_NEXT" rows = client.fetchResults( operationHandle, FetchOrientation.FETCH_NEXT, 1000, FetchType.QUERY_OUTPUT) checkResult(rows, 3, 10) // fetched [3, 10) client.closeOperation(operationHandle) client.closeSession(sessionHandle) } } test("SPARK-29492: use add jar in sync mode") { withCLIServiceClient { client => val user = System.getProperty("user.name") val sessionHandle = client.openSession(user, "") withJdbcStatement("smallKV", "addJar") { statement => val confOverlay = new java.util.HashMap[java.lang.String, java.lang.String] val jarFile = HiveTestJars.getHiveHcatalogCoreJar().getCanonicalPath Seq(s"ADD JAR $jarFile", "CREATE TABLE smallKV(key INT, val STRING) USING hive", s"LOAD DATA LOCAL INPATH '${TestData.smallKv}' OVERWRITE INTO TABLE smallKV") .foreach(query => client.executeStatement(sessionHandle, query, confOverlay)) client.executeStatement(sessionHandle, """CREATE TABLE addJar(key string) |ROW FORMAT SERDE 'org.apache.hive.hcatalog.data.JsonSerDe' """.stripMargin, confOverlay) client.executeStatement(sessionHandle, "INSERT INTO TABLE addJar SELECT 'k1' as key FROM smallKV limit 1", confOverlay) val operationHandle = client.executeStatement( sessionHandle, "SELECT key FROM addJar", confOverlay) // Fetch result first time assertResult(1, "Fetching result first time from next row") { val rows_next = client.fetchResults( operationHandle, FetchOrientation.FETCH_NEXT, 1000, FetchType.QUERY_OUTPUT) rows_next.numRows() } } } } test("SPARK-31859 Thriftserver works with spark.sql.datetime.java8API.enabled=true") { withJdbcStatement() { st => st.execute("set spark.sql.datetime.java8API.enabled=true") val rs = st.executeQuery("select date '2020-05-28', timestamp '2020-05-28 00:00:00'") rs.next() assert(rs.getDate(1).toString() == "2020-05-28") assert(rs.getTimestamp(2).toString() == "2020-05-28 00:00:00.0") } } test("SPARK-31861 Thriftserver respects spark.sql.session.timeZone") { withJdbcStatement() { st => st.execute("set spark.sql.session.timeZone=+03:15") // different than Thriftserver's JVM tz val rs = st.executeQuery("select timestamp '2020-05-28 10:00:00'") rs.next() // The timestamp as string is the same as the literal assert(rs.getString(1) == "2020-05-28 10:00:00.0") // Parsing it to java.sql.Timestamp in the client will always result in a timestamp // in client default JVM timezone. The string value of the Timestamp will match the literal, // but if the JDBC application cares about the internal timezone and UTC offset of the // Timestamp object, it should set spark.sql.session.timeZone to match its client JVM tz. assert(rs.getTimestamp(1).toString() == "2020-05-28 10:00:00.0") } } test("SPARK-31863 Session conf should persist between Thriftserver worker threads") { val iter = 20 withJdbcStatement() { statement => // date 'now' is resolved during parsing, and relies on SQLConf.get to // obtain the current set timezone. We exploit this to run this test. // If the timezones are set correctly to 25 hours apart across threads, // the dates should reflect this. // iterate a few times for the odd chance the same thread is selected for (_ <- 0 until iter) { statement.execute("SET spark.sql.session.timeZone=GMT-12") val firstResult = statement.executeQuery("SELECT date 'now'") firstResult.next() val beyondDateLineWest = firstResult.getDate(1) statement.execute("SET spark.sql.session.timeZone=GMT+13") val secondResult = statement.executeQuery("SELECT date 'now'") secondResult.next() val dateLineEast = secondResult.getDate(1) assert( dateLineEast after beyondDateLineWest, "SQLConf changes should persist across execution threads") } } } test("SPARK-30808: use Java 8 time API and Proleptic Gregorian calendar by default") { withJdbcStatement() { st => // Proleptic Gregorian calendar has no gap in the range 1582-10-04..1582-10-15 val date = "1582-10-10" val rs = st.executeQuery(s"select date '$date'") rs.next() val expected = java.sql.Date.valueOf(date) assert(rs.getDate(1) === expected) assert(rs.getString(1) === expected.toString) } } test("SPARK-26533: Support query auto timeout cancel on thriftserver - setQueryTimeout") { withJdbcStatement() { statement => statement.setQueryTimeout(1) val e = intercept[SQLException] { statement.execute("select java_method('java.lang.Thread', 'sleep', 10000L)") }.getMessage assert(e.contains("Query timed out after")) statement.setQueryTimeout(0) val rs1 = statement.executeQuery( "select 'test', java_method('java.lang.Thread', 'sleep', 3000L)") rs1.next() assert(rs1.getString(1) == "test") statement.setQueryTimeout(-1) val rs2 = statement.executeQuery( "select 'test', java_method('java.lang.Thread', 'sleep', 3000L)") rs2.next() assert(rs2.getString(1) == "test") } } test("SPARK-26533: Support query auto timeout cancel on thriftserver - SQLConf") { withJdbcStatement() { statement => statement.execute(s"SET ${SQLConf.THRIFTSERVER_QUERY_TIMEOUT.key}=1") val e1 = intercept[SQLException] { statement.execute("select java_method('java.lang.Thread', 'sleep', 10000L)") }.getMessage assert(e1.contains("Query timed out after")) statement.execute(s"SET ${SQLConf.THRIFTSERVER_QUERY_TIMEOUT.key}=0") val rs = statement.executeQuery( "select 'test', java_method('java.lang.Thread', 'sleep', 3000L)") rs.next() assert(rs.getString(1) == "test") // Uses a smaller timeout value of a config value and an a user-specified one statement.execute(s"SET ${SQLConf.THRIFTSERVER_QUERY_TIMEOUT.key}=1") statement.setQueryTimeout(30) val e2 = intercept[SQLException] { statement.execute("select java_method('java.lang.Thread', 'sleep', 10000L)") }.getMessage assert(e2.contains("Query timed out after")) statement.execute(s"SET ${SQLConf.THRIFTSERVER_QUERY_TIMEOUT.key}=30") statement.setQueryTimeout(1) val e3 = intercept[SQLException] { statement.execute("select java_method('java.lang.Thread', 'sleep', 10000L)") }.getMessage assert(e3.contains("Query timed out after")) } } } class SingleSessionSuite extends HiveThriftServer2TestBase { override def mode: ServerMode.Value = ServerMode.binary override protected def extraConf: Seq[String] = s"--conf ${HIVE_THRIFT_SERVER_SINGLESESSION.key}=true" :: Nil test("share the temporary functions across JDBC connections") { withMultipleConnectionJdbcStatement("test_udtf")( { statement => val jarPath = "../hive/src/test/resources/TestUDTF.jar" val jarURL = s"file://${System.getProperty("user.dir")}/$jarPath" // Configurations and temporary functions added in this session should be visible to all // the other sessions. Seq( "SET foo=bar", s"ADD JAR $jarURL", "CREATE TABLE test_udtf(key INT, value STRING) USING hive", s"LOAD DATA LOCAL INPATH '${TestData.smallKv}' OVERWRITE INTO TABLE test_udtf", s"""CREATE TEMPORARY FUNCTION udtf_count2 |AS 'org.apache.spark.sql.hive.execution.GenericUDTFCount2' """.stripMargin ).foreach(statement.execute) }, { statement => try { val rs1 = statement.executeQuery("SET foo") assert(rs1.next()) assert(rs1.getString(1) === "foo") assert(rs1.getString(2) === "bar") val rs2 = statement.executeQuery("DESCRIBE FUNCTION udtf_count2") assert(rs2.next()) assert(rs2.getString(1) === "Function: udtf_count2") assert(rs2.next()) assertResult("Class: org.apache.spark.sql.hive.execution.GenericUDTFCount2") { rs2.getString(1) } assert(rs2.next()) assert(rs2.getString(1) === "Usage: N/A.") val rs3 = statement.executeQuery( "SELECT key, cc FROM test_udtf LATERAL VIEW udtf_count2(value) dd AS cc") assert(rs3.next()) assert(rs3.getInt(1) === 165) assert(rs3.getInt(2) === 5) assert(rs3.next()) assert(rs3.getInt(1) === 165) assert(rs3.getInt(2) === 5) } finally { statement.executeQuery("DROP TEMPORARY FUNCTION udtf_count2") } } ) } test("unable to changing spark.sql.hive.thriftServer.singleSession using JDBC connections") { withJdbcStatement() { statement => // JDBC connections are not able to set the conf spark.sql.hive.thriftServer.singleSession val e = intercept[SQLException] { statement.executeQuery("SET spark.sql.hive.thriftServer.singleSession=false") }.getMessage assert(e.contains( "Cannot modify the value of a static config: spark.sql.hive.thriftServer.singleSession")) } } test("share the current database and temporary tables across JDBC connections") { withMultipleConnectionJdbcStatement()( { statement => statement.execute("CREATE DATABASE IF NOT EXISTS db1") }, { statement => val rs1 = statement.executeQuery("SELECT current_database()") assert(rs1.next()) assert(rs1.getString(1) === "default") statement.execute("USE db1") val rs2 = statement.executeQuery("SELECT current_database()") assert(rs2.next()) assert(rs2.getString(1) === "db1") statement.execute("CREATE TEMP VIEW tempView AS SELECT 123") }, { statement => // the current database is set to db1 by another JDBC connection. val rs1 = statement.executeQuery("SELECT current_database()") assert(rs1.next()) assert(rs1.getString(1) === "db1") val rs2 = statement.executeQuery("SELECT * from tempView") assert(rs2.next()) assert(rs2.getString(1) === "123") statement.execute("USE default") statement.execute("DROP VIEW tempView") statement.execute("DROP DATABASE db1 CASCADE") } ) } } class HiveThriftCleanUpScratchDirSuite extends HiveThriftServer2TestBase { var tempScratchDir: File = _ override protected def beforeAll(): Unit = { tempScratchDir = Utils.createTempDir() tempScratchDir.setWritable(true, false) assert(tempScratchDir.list().isEmpty) new File(tempScratchDir.getAbsolutePath + File.separator + "SPARK-31626").createNewFile() assert(tempScratchDir.list().nonEmpty) super.beforeAll() } override def mode: ServerMode.Value = ServerMode.binary override protected def extraConf: Seq[String] = s" --hiveconf ${ConfVars.HIVE_START_CLEANUP_SCRATCHDIR}=true " :: s"--hiveconf ${ConfVars.SCRATCHDIR}=${tempScratchDir.getAbsolutePath}" :: Nil test("Cleanup the Hive scratchdir when starting the Hive Server") { assert(!tempScratchDir.exists()) withJdbcStatement() { statement => val rs = statement.executeQuery("SELECT id FROM range(1)") assert(rs.next()) assert(rs.getLong(1) === 0L) } } override protected def afterAll(): Unit = { Utils.deleteRecursively(tempScratchDir) super.afterAll() } } class HiveThriftHttpServerSuite extends HiveThriftServer2Test { override def mode: ServerMode.Value = ServerMode.http test("JDBC query execution") { withJdbcStatement("test") { statement => val queries = Seq( "SET spark.sql.shuffle.partitions=3", "CREATE TABLE test(key INT, val STRING) USING hive", s"LOAD DATA LOCAL INPATH '${TestData.smallKv}' OVERWRITE INTO TABLE test", "CACHE TABLE test") queries.foreach(statement.execute) assertResult(5, "Row count mismatch") { val resultSet = statement.executeQuery("SELECT COUNT(*) FROM test") resultSet.next() resultSet.getInt(1) } } } test("Checks Hive version") { withJdbcStatement() { statement => val resultSet = statement.executeQuery("SET spark.sql.hive.version") resultSet.next() assert(resultSet.getString(1) === "spark.sql.hive.version") assert(resultSet.getString(2) === HiveUtils.builtinHiveVersion) } } test("SPARK-24829 Checks cast as float") { withJdbcStatement() { statement => val resultSet = statement.executeQuery("SELECT CAST('4.56' AS FLOAT)") resultSet.next() assert(resultSet.getString(1) === "4.56") } } } object ServerMode extends Enumeration { val binary, http = Value } abstract class HiveThriftServer2TestBase extends SparkFunSuite with BeforeAndAfterAll with Logging { def mode: ServerMode.Value private val CLASS_NAME = HiveThriftServer2.getClass.getCanonicalName.stripSuffix("$") private val LOG_FILE_MARK = s"starting $CLASS_NAME, logging to " protected val startScript = "../../sbin/start-thriftserver.sh".split("/").mkString(File.separator) protected val stopScript = "../../sbin/stop-thriftserver.sh".split("/").mkString(File.separator) private var listeningPort: Int = _ protected def serverPort: Int = listeningPort protected val hiveConfList = "a=avalue;b=bvalue" protected val hiveVarList = "c=cvalue;d=dvalue" protected def user = System.getProperty("user.name") protected var warehousePath: File = _ protected var metastorePath: File = _ protected def metastoreJdbcUri = s"jdbc:derby:;databaseName=$metastorePath;create=true" private val pidDir: File = Utils.createTempDir(namePrefix = "thriftserver-pid") protected var logPath: File = _ protected var operationLogPath: File = _ protected var lScratchDir: File = _ private var logTailingProcess: Process = _ private var diagnosisBuffer: ArrayBuffer[String] = ArrayBuffer.empty[String] protected def extraConf: Seq[String] = Nil protected def serverStartCommand(): Seq[String] = { val portConf = if (mode == ServerMode.binary) { ConfVars.HIVE_SERVER2_THRIFT_PORT } else { ConfVars.HIVE_SERVER2_THRIFT_HTTP_PORT } val driverClassPath = { // Writes a temporary log4j.properties and prepend it to driver classpath, so that it // overrides all other potential log4j configurations contained in other dependency jar files. val tempLog4jConf = Utils.createTempDir().getCanonicalPath Files.write( """log4j.rootCategory=INFO, console |log4j.appender.console=org.apache.log4j.ConsoleAppender |log4j.appender.console.target=System.err |log4j.appender.console.layout=org.apache.log4j.PatternLayout |log4j.appender.console.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{1}: %m%n """.stripMargin, new File(s"$tempLog4jConf/log4j.properties"), StandardCharsets.UTF_8) tempLog4jConf } s"""$startScript | --master local | --hiveconf ${ConfVars.METASTORECONNECTURLKEY}=$metastoreJdbcUri | --hiveconf ${ConfVars.METASTOREWAREHOUSE}=$warehousePath | --hiveconf ${ConfVars.HIVE_SERVER2_THRIFT_BIND_HOST}=localhost | --hiveconf ${ConfVars.HIVE_SERVER2_TRANSPORT_MODE}=$mode | --hiveconf ${ConfVars.HIVE_SERVER2_LOGGING_OPERATION_LOG_LOCATION}=$operationLogPath | --hiveconf ${ConfVars.LOCALSCRATCHDIR}=$lScratchDir | --hiveconf $portConf=0 | --driver-class-path $driverClassPath | --driver-java-options -Dlog4j.debug | --conf spark.ui.enabled=false | ${extraConf.mkString("\\n")} """.stripMargin.split("\\\\s+").toSeq } /** * String to scan for when looking for the thrift binary endpoint running. * This can change across Hive versions. */ val THRIFT_BINARY_SERVICE_LIVE = "Starting ThriftBinaryCLIService on port" /** * String to scan for when looking for the thrift HTTP endpoint running. * This can change across Hive versions. */ val THRIFT_HTTP_SERVICE_LIVE = "Started ThriftHttpCLIService in http" val SERVER_STARTUP_TIMEOUT = 3.minutes private def startThriftServer(attempt: Int) = { warehousePath = Utils.createTempDir() warehousePath.delete() metastorePath = Utils.createTempDir() metastorePath.delete() operationLogPath = Utils.createTempDir() operationLogPath.delete() lScratchDir = Utils.createTempDir() lScratchDir.delete() logPath = null logTailingProcess = null val command = serverStartCommand() diagnosisBuffer ++= s""" |### Attempt $attempt ### |HiveThriftServer2 command line: $command |Listening port: 0 |System user: $user """.stripMargin.split("\\n") logPath = { val lines = Utils.executeAndGetOutput( command = command, extraEnvironment = Map( // Disables SPARK_TESTING to exclude log4j.properties in test directories. "SPARK_TESTING" -> "0", // But set SPARK_SQL_TESTING to make spark-class happy. "SPARK_SQL_TESTING" -> "1", // Points SPARK_PID_DIR to SPARK_HOME, otherwise only 1 Thrift server instance can be // started at a time, which is not Jenkins friendly. "SPARK_PID_DIR" -> pidDir.getCanonicalPath), redirectStderr = true) logInfo(s"COMMAND: $command") logInfo(s"OUTPUT: $lines") lines.split("\\n").collectFirst { case line if line.contains(LOG_FILE_MARK) => new File(line.drop(LOG_FILE_MARK.length)) }.getOrElse { throw new RuntimeException("Failed to find HiveThriftServer2 log file.") } } val serverStarted = Promise[Unit]() // Ensures that the following "tail" command won't fail. logPath.createNewFile() val successLine = if (mode == ServerMode.http) { THRIFT_HTTP_SERVICE_LIVE } else { THRIFT_BINARY_SERVICE_LIVE } logTailingProcess = { val command = s"/usr/bin/env tail -n +0 -f ${logPath.getCanonicalPath}".split(" ") // Using "-n +0" to make sure all lines in the log file are checked. val builder = new ProcessBuilder(command: _*) val captureOutput = (line: String) => diagnosisBuffer.synchronized { diagnosisBuffer += line if (line.contains(successLine)) { listeningPort = line.split(" on port ")(1).split(' ').head.toInt logInfo(s"Started HiveThriftServer2: port=$listeningPort, mode=$mode, attempt=$attempt") serverStarted.trySuccess(()) () } } val process = builder.start() new ProcessOutputCapturer(process.getInputStream, captureOutput).start() new ProcessOutputCapturer(process.getErrorStream, captureOutput).start() process } ShutdownHookManager.addShutdownHook(stopThriftServer _) ThreadUtils.awaitResult(serverStarted.future, SERVER_STARTUP_TIMEOUT) } private def stopThriftServer(): Unit = { if (pidDir.list.nonEmpty) { // The `spark-daemon.sh' script uses kill, which is not synchronous, have to wait for a while. Utils.executeAndGetOutput( command = Seq(stopScript), extraEnvironment = Map("SPARK_PID_DIR" -> pidDir.getCanonicalPath)) Thread.sleep(3.seconds.toMillis) warehousePath.delete() warehousePath = null metastorePath.delete() metastorePath = null operationLogPath.delete() operationLogPath = null lScratchDir.delete() lScratchDir = null Option(logPath).foreach(_.delete()) logPath = null Option(logTailingProcess).foreach(_.destroy()) logTailingProcess = null } } private def dumpLogs(): Unit = { logError( s""" |===================================== |HiveThriftServer2Suite failure output |===================================== |${diagnosisBuffer.mkString("\\n")} |========================================= |End HiveThriftServer2Suite failure output |========================================= """.stripMargin) } override protected def beforeAll(): Unit = { super.beforeAll() diagnosisBuffer.clear() // Retries up to 3 times with different port numbers if the server fails to start (1 to 3).foldLeft(Try(startThriftServer(0))) { case (started, attempt) => started.orElse { stopThriftServer() Try { startThriftServer(attempt) eventually(timeout(30.seconds), interval(1.seconds)) { withJdbcStatement() { _.execute("SELECT 1") } } } } }.recover { case cause: Throwable => dumpLogs() throw cause }.get logInfo(s"HiveThriftServer2 started successfully") } override protected def afterAll(): Unit = { try { stopThriftServer() logInfo("HiveThriftServer2 stopped") } finally { super.afterAll() } } Utils.classForName(classOf[HiveDriver].getCanonicalName) protected def jdbcUri(database: String = "default"): String = if (mode == ServerMode.http) { s"""jdbc:hive2://localhost:$serverPort/ |$database? |hive.server2.transport.mode=http; |hive.server2.thrift.http.path=cliservice; |${hiveConfList}#${hiveVarList} """.stripMargin.split("\\n").mkString.trim } else { s"jdbc:hive2://localhost:$serverPort/$database?${hiveConfList}#${hiveVarList}" } private def tryCaptureSysLog(f: => Unit): Unit = { try f catch { case e: Exception => // Dump the HiveThriftServer2 log if error occurs, e.g. getConnection failure. dumpLogs() throw e } } def withMultipleConnectionJdbcStatement( tableNames: String*)(fs: (Statement => Unit)*): Unit = tryCaptureSysLog { val user = System.getProperty("user.name") val connections = fs.map { _ => DriverManager.getConnection(jdbcUri(), user, "") } val statements = connections.map(_.createStatement()) try { statements.zip(fs).foreach { case (s, f) => f(s) } } finally { tableNames.foreach { name => // TODO: Need a better way to drop the view. if (name.toUpperCase(Locale.ROOT).startsWith("VIEW")) { statements(0).execute(s"DROP VIEW IF EXISTS $name") } else { statements(0).execute(s"DROP TABLE IF EXISTS $name") } } statements.foreach(_.close()) connections.foreach(_.close()) } } def withDatabase(dbNames: String*)(fs: (Statement => Unit)*): Unit = tryCaptureSysLog { val user = System.getProperty("user.name") val connections = fs.map { _ => DriverManager.getConnection(jdbcUri(), user, "") } val statements = connections.map(_.createStatement()) try { statements.zip(fs).foreach { case (s, f) => f(s) } } finally { dbNames.foreach { name => statements(0).execute(s"DROP DATABASE IF EXISTS $name") } statements.foreach(_.close()) connections.foreach(_.close()) } } def withJdbcStatement(tableNames: String*)(f: Statement => Unit): Unit = { withMultipleConnectionJdbcStatement(tableNames: _*)(f) } } /** * Common tests for both binary and http mode thrift server * TODO: SPARK-31914: Move common tests from subclasses to this trait */ abstract class HiveThriftServer2Test extends HiveThriftServer2TestBase { test("SPARK-17819: Support default database in connection URIs") { withDatabase("spark17819") { statement => statement.execute(s"CREATE DATABASE IF NOT EXISTS spark17819") val jdbcStr = jdbcUri("spark17819") val connection = DriverManager.getConnection(jdbcStr, user, "") val statementN = connection.createStatement() try { val resultSet = statementN.executeQuery("select current_database()") resultSet.next() assert(resultSet.getString(1) === "spark17819") } finally { statementN.close() connection.close() } } } }
taroplus/spark
sql/hive-thriftserver/src/test/scala/org/apache/spark/sql/hive/thriftserver/HiveThriftServer2Suites.scala
Scala
apache-2.0
53,775