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
package ly.stealth.testing import java.util.Properties import org.apache.kafka.clients.producer.ProducerConfig import org.apache.kafka.clients.producer.{KafkaProducer => NewKafkaProducer} trait BaseSpec { def createNewKafkaProducer(brokerList: String, acks: Int = -1, metadataFetchTimeout: Long = 3000L, blockOnBufferFull: Boolean = true, bufferSize: Long = 1024L * 1024L, retries: Int = 0): NewKafkaProducer = { val producerProps = new Properties() producerProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList) producerProps.put(ProducerConfig.ACKS_CONFIG, acks.toString) producerProps.put(ProducerConfig.METADATA_FETCH_TIMEOUT_CONFIG, metadataFetchTimeout.toString) producerProps.put(ProducerConfig.BLOCK_ON_BUFFER_FULL_CONFIG, blockOnBufferFull.toString) producerProps.put(ProducerConfig.BUFFER_MEMORY_CONFIG, bufferSize.toString) producerProps.put(ProducerConfig.RETRIES_CONFIG, retries.toString) producerProps.put(ProducerConfig.RETRY_BACKOFF_MS_CONFIG, "100") producerProps.put(ProducerConfig.RECONNECT_BACKOFF_MS_CONFIG, "200") new NewKafkaProducer(producerProps) } }
amorfis/reactive-kafka
src/test/scala/ly/stealth/testing/BaseSpec.scala
Scala
apache-2.0
1,296
package com.gshakhn.privatewiki.client.components import com.gshakhn.privatewiki.client.LockedBinder import com.gshakhn.privatewiki.client.components.testutil.{PrivateWikiBaseSpec, PageInteractions} import PageInteractions._ import com.gshakhn.privatewiki.shared.{NoEncryption, AuthenticationRequest, BinderLoaded, WrongPassword} import org.scalajs.jquery._ import org.scalatest.path class LoadingBindersSpec extends PrivateWikiBaseSpec { override def newInstance: path.FunSpecLike = new LoadingBindersSpec describe("A PrivateWiki") { implicit val client = new TestClient render it("has 0 binders to start with") { val listItems = jQuery(".binder-list-item") listItems.length shouldBe 0 } describe("loading a binder that exists on the server") { enterBinderName("binder") enterBinderPassword("secure") describe("with the wrong password") { client.response = WrongPassword clickLoadBinder() it("makes the authentication request") { client.requestReceived.value shouldBe AuthenticationRequest("binder", "secure") } it("does not add the binder to the list of loaded binders") { rootComponent.state.loadedBinders shouldBe empty } it("does not add the binder to the list") { val listItems = jQuery(".binder-list-item") listItems.length shouldBe 0 } it("shows an error in the password field") { val passwordForm = jQuery(s"#${BinderLoader.binderServerPasswordFormId}") passwordForm should haveClass("has-error") } } describe("with the right password") { client.response = BinderLoaded("binder", NoEncryption, "") clickLoadBinder() it("makes the authentication request") { client.requestReceived.value shouldBe AuthenticationRequest("binder", "secure") } it("clears the binder name") { jQuery(s"#${BinderLoader.binderNameInputId}").value() shouldBe "" } it("clears the binder password") { jQuery(s"#${BinderLoader.binderServerPasswordId}").value() shouldBe "" } describe("adds the binder") { val listItems = jQuery(".binder-list-item") it("into the list") { listItems.length shouldBe 1 } it("with its name") { listItems.eq(0).text() shouldBe "binder" } it("locked") { listItems.eq(0) should haveClass("locked-binder") } } it("adds the binder to the list of loaded binders") { rootComponent.state.loadedBinders should matchPattern{case Seq(LockedBinder("binder", _, _)) => } } } } describe("after a binder is loaded") { enterBinderName("binder") enterBinderPassword("secure") client.response = BinderLoaded("binder", NoEncryption, "") clickLoadBinder() client.requestReceived = None describe("trying to load the binder again") { enterBinderName("binder") enterBinderPassword("secure") client.response = BinderLoaded("binder", NoEncryption, "") clickLoadBinder() it("will not make an authentication request") { client.requestReceived shouldBe None } it("clears the binder name") { jQuery(s"#${BinderLoader.binderNameInputId}").value() shouldBe "" } it("clears the binder password") { jQuery(s"#${BinderLoader.binderServerPasswordId}").value() shouldBe "" } it("does not add the binder to the list twice") { val listItems = jQuery(".binder-list-item") listItems.length shouldBe 1 } it("does not add the binder to the list of loaded binders twice") { rootComponent.state.loadedBinders should matchPattern{case Seq(LockedBinder("binder", _, _)) => } } } } } tearDown() }
gshakhn/private-wiki
client/src/test/scala/com/gshakhn/privatewiki/client/components/LoadingBindersSpec.scala
Scala
apache-2.0
3,977
package satisfaction package engine package actors import akka.actor.ActorRef case class CheckEvidence( val evidencdId : String,w : Witness ) case class EvidenceCheckResult(val evidenceId : String, w: Witness, val isAlreadySatisfied : Boolean) case class JobRunSuccess( val result : ExecutionResult ) case class JobRunFailed( val result : ExecutionResult ) //// Satisfy the current goal for the specified witness case class Satisfy(runID: String, parentRunID: String, forceSatisfy: Boolean = false) { def apply() = { Satisfy(null,null,false) } } object Satisfy { def apply() = { new Satisfy(null,null,false) } def apply( forceSatisfy: Boolean) = { new Satisfy(null,null,forceSatisfy) } } /// Query whether the evidence already exists, and the goal /// has actually been completed case class IsSatisfied(doRecursive: Boolean) /// Abort the current execution case class Abort( killChildren: Boolean=true) /// Query the current status of all witnesses case class WhatsYourStatus() case class AddListener(actorRef:ActorRef) /// Re-run a job which has previously been marked as failure case class RestartJob(runID: String, parentRunID: String) object RestartJob { def apply() = { new RestartJob(null,null) } } /// Respond with your currrent status case class StatusResponse(goalStatus: GoalStatus) case class GoalSuccess(goalStatus: GoalStatus) case class GoalFailure(goalStatus: GoalStatus) //// Message that the actor can't handle the current request at this time .. case class InvalidRequest(goalStatus: GoalStatus, reason : String)
jeromebanks/satisfaction
modules/engine/src/main/scala/satisfaction/engine/actors/Messages.scala
Scala
apache-2.0
1,603
/* Facsimile: A Discrete-Event Simulation Library Copyright © 2004-2020, Michael J Allen. This file is part of Facsimile. Facsimile is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Facsimile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Facsimile. If not, see http://www.gnu.org/licenses/lgpl. The developers welcome all comments, suggestions and offers of assistance. For further information, please visit the project home page at: http://facsim.org/ Thank you for your interest in the Facsimile project! IMPORTANT NOTE: All patches (modifications to existing files and/or the addition of new files) submitted for inclusion as part of the official Facsimile code base, must comply with the published Facsimile Coding Standards. If your code fails to comply with the standard, then your patches will be rejected. For further information, please visit the coding standards at: http://facsim.org/Documentation/CodingStandards/ ======================================================================================================================== Scala source file from the org.facsim.anim.cell package. */ package org.facsim.anim.cell import org.facsim.LibResource import scalafx.scene.Group /** Class representing ''[[http://www.automod.com/ AutoMod®]] cell triad'' primitives. @see [[http://facsim.org/Documentation/Resources/AutoModCellFile/Triads.html Triads]] for further information. @todo In a cell file, a triad is used as a debugging aid to demonstrate the alignment of a primitive's local X-, Y- and Z-axes. It may be a useful tool for users importing ''cell'' files into ''Facsimile''. However, for now, we do not implement triads—they are processed, but otherwise ignored. @constructor Construct a new triad primitive from the data stream. @param scene Reference to the CellScene of which this cell is a part. @param parent Parent set of this cell primitive. If this value is `None`, then this cell is the scene's root cell. @throws org.facsim.anim.cell.IncorrectFormatException if the file supplied is not an ''AutoMod® cell'' file. @throws org.facsim.anim.cell.ParsingErrorException if errors are encountered during parsing of the file. @see [[http://facsim.org/Documentation/Resources/AutoModCellFile/Triads.html Triads]] for further information. */ private[cell] final class Triad(scene: CellScene, parent: Option[Set]) extends Cell(scene, parent) { /* Read and disregard the "unknown" triad flag. (The current theory is that this value is a visibility flag: a 0 value means that the triad is invisible; any other value, that it's visible. It's academic here as we simply ignore it.) */ scene.readInt(LibResource("anim.cell.Triad.read")) /** @inheritdoc @note Triads are not currently rendered. */ private[cell] override def toNode = new Group() }
MichaelJAllen/facsimile
core/src/main/scala/org/facsim/anim/cell/Triad.scala
Scala
lgpl-3.0
3,256
/******************************************************************************* * Copyright (c) 2014 Łukasz Szpakowski. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. ******************************************************************************/ package pl.luckboy.purfuncor.frontend.typer import scalaz._ import scalaz.Scalaz._ case class TreeInfo[+T, U, V](treeInfo: T, typeTable: InferredTypeTable[U, V]) { override def toString = (if(!treeInfo.toString.isEmpty) treeInfo + "\\n" else "") + "//// typeTables\\n" + typeTable.types.map { case (l, t) => "// " + l + ": " + t + "\\n" }.mkString("\\n") }
luckboy/Purfuncor
src/main/scala/pl/luckboy/purfuncor/frontend/typer/TreeInfo.scala
Scala
mpl-2.0
778
/* * Copyright 2021 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.hmrc.ct.ct600.v2 import uk.gov.hmrc.ct.box.{CtBoxIdentifier, CtOptionalBoolean, Linked} import uk.gov.hmrc.ct.computations.CPQ18 case class B31(value: Option[Boolean]) extends CtBoxIdentifier with CtOptionalBoolean object B31 extends Linked[CPQ18, B31] { override def apply(source: CPQ18): B31 = B31(source.value) }
hmrc/ct-calculations
src/main/scala/uk/gov/hmrc/ct/ct600/v2/B31.scala
Scala
apache-2.0
942
/* * Copyright (c) 2002-2018 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j 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.neo4j.cypher.internal.compiler.v2_3.executionplan import org.neo4j.cypher.internal.compiler.v2_3.spi.PlanContext import org.neo4j.cypher.internal.compiler.v2_3.pipes.PipeMonitor /* PlanBuilders are basically partial functions that can execute for some input, and can answer if an input is something it can work on. The idea is that they take an ExecutionPlanInProgress, and moves it a little bit towards a more solved plan, which is represented by the stack of Pipes. A PlanBuilder should only concern itself with the first PartiallySolvedQuery part - the tail query parts will be seen later. It's important that PlanBuilders never return the input unchanged. */ trait PlanBuilder { def canWorkWith(plan: ExecutionPlanInProgress, ctx: PlanContext)(implicit pipeMonitor: PipeMonitor): Boolean def apply(plan: ExecutionPlanInProgress, ctx: PlanContext)(implicit pipeMonitor: PipeMonitor): ExecutionPlanInProgress def missingDependencies(plan: ExecutionPlanInProgress): Seq[String] = Seq() implicit class SeqWithReplace[A](inSeq: Seq[A]) { def replace(remove: A, replaceWith: A) = inSeq.filterNot(_ == remove) :+ replaceWith } }
HuangLS/neo4j
community/cypher/cypher-compiler-2.3/src/main/scala/org/neo4j/cypher/internal/compiler/v2_3/executionplan/PlanBuilder.scala
Scala
apache-2.0
1,957
package chana.serializer import akka.actor.ExtendedActorSystem import akka.serialization.{ Serializer } import akka.util.ByteString import chana.PutSchema import java.nio.ByteOrder import java.util.concurrent.TimeUnit import scala.concurrent.duration.Duration import scala.concurrent.duration.FiniteDuration final class SchemaEventSerializer(system: ExtendedActorSystem) extends Serializer { implicit val byteOrder = ByteOrder.BIG_ENDIAN override def identifier: Int = 238710283 override def includeManifest: Boolean = false override def toBinary(obj: AnyRef): Array[Byte] = obj match { case PutSchema(entityName, schema, entityFullName, idleTimeout) => val builder = ByteString.newBuilder StringSerializer.appendToByteString(builder, entityName) StringSerializer.appendToByteString(builder, schema.toString) if (entityFullName.isDefined) { builder.putByte(0) StringSerializer.appendToByteString(builder, entityFullName.get) } else { builder.putByte(1) } if (idleTimeout.isFinite) { builder.putLong(idleTimeout.toMillis) } else { builder.putLong(-1) } builder.result.toArray case _ => { val errorMsg = "Can't serialize a non-Schema message using SchemaSerializer [" + obj + "]" throw new IllegalArgumentException(errorMsg) } } override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = { val data = ByteString(bytes).iterator val entityName = StringSerializer.fromByteIterator(data) val schemaJson = StringSerializer.fromByteIterator(data) val entityFullName = data.getByte match { case 0 => Some(StringSerializer.fromByteIterator(data)) case 1 => None } val duration = data.getLong val idleTimeout = if (duration >= 0) { FiniteDuration(duration, TimeUnit.MILLISECONDS) } else { Duration.Undefined } PutSchema(entityName, schemaJson, entityFullName, idleTimeout) } }
matthewtt/chana
src/main/scala/chana/serializer/SchemaEventSerializer.scala
Scala
apache-2.0
1,999
/* * 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.dynamicpruning import org.apache.spark.sql.catalyst.expressions._ import org.apache.spark.sql.catalyst.planning.ExtractEquiJoinKeys import org.apache.spark.sql.catalyst.plans._ import org.apache.spark.sql.catalyst.plans.logical._ import org.apache.spark.sql.catalyst.rules.Rule import org.apache.spark.sql.execution.datasources.{HadoopFsRelation, LogicalRelation} import org.apache.spark.sql.internal.SQLConf /** * Dynamic partition pruning optimization is performed based on the type and * selectivity of the join operation. During query optimization, we insert a * predicate on the partitioned table using the filter from the other side of * the join and a custom wrapper called DynamicPruning. * * The basic mechanism for DPP inserts a duplicated subquery with the filter from the other side, * when the following conditions are met: * (1) the table to prune is partitioned by the JOIN key * (2) the join operation is one of the following types: INNER, LEFT SEMI, * LEFT OUTER (partitioned on right), or RIGHT OUTER (partitioned on left) * * In order to enable partition pruning directly in broadcasts, we use a custom DynamicPruning * clause that incorporates the In clause with the subquery and the benefit estimation. * During query planning, when the join type is known, we use the following mechanism: * (1) if the join is a broadcast hash join, we replace the duplicated subquery with the reused * results of the broadcast, * (2) else if the estimated benefit of partition pruning outweighs the overhead of running the * subquery query twice, we keep the duplicated subquery * (3) otherwise, we drop the subquery. */ object PartitionPruning extends Rule[LogicalPlan] with PredicateHelper { /** * Search the partitioned table scan for a given partition column in a logical plan */ def getPartitionTableScan(a: Expression, plan: LogicalPlan): Option[LogicalRelation] = { val srcInfo: Option[(Expression, LogicalPlan)] = findExpressionAndTrackLineageDown(a, plan) srcInfo.flatMap { case (resExp, l: LogicalRelation) => l.relation match { case fs: HadoopFsRelation => val partitionColumns = AttributeSet( l.resolve(fs.partitionSchema, fs.sparkSession.sessionState.analyzer.resolver)) if (resExp.references.subsetOf(partitionColumns)) { return Some(l) } else { None } case _ => None } case _ => None } } /** * Insert a dynamic partition pruning predicate on one side of the join using the filter on the * other side of the join. * - to be able to identify this filter during query planning, we use a custom * DynamicPruning expression that wraps a regular In expression * - we also insert a flag that indicates if the subquery duplication is worthwhile and it * should run regardless of the join strategy, or is too expensive and it should be run only if * we can reuse the results of a broadcast */ private def insertPredicate( pruningKey: Expression, pruningPlan: LogicalPlan, filteringKey: Expression, filteringPlan: LogicalPlan, joinKeys: Seq[Expression], partScan: LogicalRelation): LogicalPlan = { val reuseEnabled = SQLConf.get.exchangeReuseEnabled val index = joinKeys.indexOf(filteringKey) lazy val hasBenefit = pruningHasBenefit(pruningKey, partScan, filteringKey, filteringPlan) if (reuseEnabled || hasBenefit) { // insert a DynamicPruning wrapper to identify the subquery during query planning Filter( DynamicPruningSubquery( pruningKey, filteringPlan, joinKeys, index, SQLConf.get.dynamicPartitionPruningReuseBroadcastOnly || !hasBenefit), pruningPlan) } else { // abort dynamic partition pruning pruningPlan } } /** * Given an estimated filtering ratio we assume the partition pruning has benefit if * the size in bytes of the partitioned plan after filtering is greater than the size * in bytes of the plan on the other side of the join. We estimate the filtering ratio * using column statistics if they are available, otherwise we use the config value of * `spark.sql.optimizer.joinFilterRatio`. */ private def pruningHasBenefit( partExpr: Expression, partPlan: LogicalPlan, otherExpr: Expression, otherPlan: LogicalPlan): Boolean = { // get the distinct counts of an attribute for a given table def distinctCounts(attr: Attribute, plan: LogicalPlan): Option[BigInt] = { plan.stats.attributeStats.get(attr).flatMap(_.distinctCount) } // the default filtering ratio when CBO stats are missing, but there is a // predicate that is likely to be selective val fallbackRatio = SQLConf.get.dynamicPartitionPruningFallbackFilterRatio // the filtering ratio based on the type of the join condition and on the column statistics val filterRatio = (partExpr.references.toList, otherExpr.references.toList) match { // filter out expressions with more than one attribute on any side of the operator case (leftAttr :: Nil, rightAttr :: Nil) if SQLConf.get.dynamicPartitionPruningUseStats => // get the CBO stats for each attribute in the join condition val partDistinctCount = distinctCounts(leftAttr, partPlan) val otherDistinctCount = distinctCounts(rightAttr, otherPlan) val availableStats = partDistinctCount.isDefined && partDistinctCount.get > 0 && otherDistinctCount.isDefined if (!availableStats) { fallbackRatio } else if (partDistinctCount.get.toDouble <= otherDistinctCount.get.toDouble) { // there is likely an estimation error, so we fallback fallbackRatio } else { 1 - otherDistinctCount.get.toDouble / partDistinctCount.get.toDouble } case _ => fallbackRatio } // the pruning overhead is the total size in bytes of all scan relations val overhead = otherPlan.collectLeaves().map(_.stats.sizeInBytes).sum.toFloat filterRatio * partPlan.stats.sizeInBytes.toFloat > overhead.toFloat } /** * Returns whether an expression is likely to be selective */ private def isLikelySelective(e: Expression): Boolean = e match { case Not(expr) => isLikelySelective(expr) case And(l, r) => isLikelySelective(l) || isLikelySelective(r) case Or(l, r) => isLikelySelective(l) && isLikelySelective(r) case Like(_, _, _) => true case _: BinaryComparison => true case _: In | _: InSet => true case _: StringPredicate => true case _ => false } /** * Search a filtering predicate in a given logical plan */ private def hasSelectivePredicate(plan: LogicalPlan): Boolean = { plan.find { case f: Filter => isLikelySelective(f.condition) case _ => false }.isDefined } /** * To be able to prune partitions on a join key, the filtering side needs to * meet the following requirements: * (1) it can not be a stream * (2) it needs to contain a selective predicate used for filtering */ private def hasPartitionPruningFilter(plan: LogicalPlan): Boolean = { !plan.isStreaming && hasSelectivePredicate(plan) } private def canPruneLeft(joinType: JoinType): Boolean = joinType match { case Inner | LeftSemi | RightOuter => true case _ => false } private def canPruneRight(joinType: JoinType): Boolean = joinType match { case Inner | LeftSemi | LeftOuter => true case _ => false } private def prune(plan: LogicalPlan): LogicalPlan = { plan transformUp { // skip this rule if there's already a DPP subquery on the LHS of a join case j @ Join(Filter(_: DynamicPruningSubquery, _), _, _, _, _) => j case j @ Join(_, Filter(_: DynamicPruningSubquery, _), _, _, _) => j case j @ Join(left, right, joinType, Some(condition), hint) => var newLeft = left var newRight = right // extract the left and right keys of the join condition val (leftKeys, rightKeys) = j match { case ExtractEquiJoinKeys(_, lkeys, rkeys, _, _, _, _) => (lkeys, rkeys) case _ => (Nil, Nil) } // checks if two expressions are on opposite sides of the join def fromDifferentSides(x: Expression, y: Expression): Boolean = { def fromLeftRight(x: Expression, y: Expression) = !x.references.isEmpty && x.references.subsetOf(left.outputSet) && !y.references.isEmpty && y.references.subsetOf(right.outputSet) fromLeftRight(x, y) || fromLeftRight(y, x) } splitConjunctivePredicates(condition).foreach { case EqualTo(a: Expression, b: Expression) if fromDifferentSides(a, b) => val (l, r) = if (a.references.subsetOf(left.outputSet) && b.references.subsetOf(right.outputSet)) { a -> b } else { b -> a } // there should be a partitioned table and a filter on the dimension table, // otherwise the pruning will not trigger var partScan = getPartitionTableScan(l, left) if (partScan.isDefined && canPruneLeft(joinType) && hasPartitionPruningFilter(right)) { newLeft = insertPredicate(l, newLeft, r, right, rightKeys, partScan.get) } else { partScan = getPartitionTableScan(r, right) if (partScan.isDefined && canPruneRight(joinType) && hasPartitionPruningFilter(left) ) { newRight = insertPredicate(r, newRight, l, left, leftKeys, partScan.get) } } case _ => } Join(newLeft, newRight, joinType, Some(condition), hint) } } override def apply(plan: LogicalPlan): LogicalPlan = plan match { // Do not rewrite subqueries. case s: Subquery if s.correlated => plan case _ if !SQLConf.get.dynamicPartitionPruningEnabled => plan case _ => prune(plan) } }
witgo/spark
sql/core/src/main/scala/org/apache/spark/sql/execution/dynamicpruning/PartitionPruning.scala
Scala
apache-2.0
11,033
/* * 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.mllib.feature import org.apache.spark.SparkFunSuite import org.apache.spark.mllib.util.MLlibTestSparkContext import org.apache.spark.mllib.util.TestingUtils._ import org.apache.spark.util.Utils /** * Word2Vec模型来根据词义比较两个字词相似性 * Word2Vec将词语转换为向量, * 通过测量两个向量内积空间的夹角的余弦值来度量它们之间的相似性, * Word2Vec 计算单词的向量表示。这种表示的主要优点是相似的词在向量空间中离得近, * 这使得向新模式的泛化更容易并且模型估计更鲁棒。向量表示在诸如命名实体识别、歧义消除、句子解析、 * 打标签以及机器翻译等自然语言处理程序中比较有用. */ class Word2VecSuite extends SparkFunSuite with MLlibTestSparkContext { // TODO: add more tests /** * word2vec计算的是余弦值,距离范围为0-1之间,值越大代表这两个词关联度越高,所以越排在上面的词与输入的词越紧密 */ test("Word2Vec") { //首先导入文本文件,然后将数据解析为RDD[Seq[String]] val sentence = "a b " * 100 + "a c " * 10 val localDoc = Seq(sentence, sentence) val doc = sc.parallelize(localDoc).map(line => line.split(" ").toSeq) //接着构造Word2Vec实例并使用输入数据拟合出Word2VecModel模型,setVectorSize设置矩阵长度 //通过计算向量之间的距离(欧式距离、余弦距离等)来体现词与词的相似性,设置向量大小 val model = new Word2Vec().setVectorSize(10).setSeed(42L).fit(doc) //fit()方法将DataFrame转化为一个Transformer的算法 /*** * 通过计算向量之间的距离(欧式距离、余弦距离等)来体现词与词的相似性 * res7: Map[String,Array[Float]] = Map( a -> Array(-0.09504074,-0.32639217,-0.13462302,0.39578366,0.03197848,0.22833848,-0.017002914,0.017881352,0.05745892,0.44812882), b -> Array(-0.7736193,-0.14744955,-0.3899,0.9144978,-0.5287293,0.2534397,-0.7889658,-0.36363065,-0.005014119,-0.2064493), c -> Array(0.18965095,0.20619483,0.12036613,-0.2947198,0.13945016,-0.108583875,0.17885813,0.1146979,0.004605832,-0.16548984)) */ model.getVectors //查找最相似的2个单词 //res5: Array[(String, Double)] = Array((b,0.29619476624627045), (c,-0.5884667195230214)) val syms = model.findSynonyms("a", 2) assert(syms.length == 2) assert(syms(0)._1 == "b") assert(syms(1)._1 == "c") // Test that model built using Word2Vec, i.e wordVectors and wordIndec // and a Word2VecMap give the same values. //测试模型使用Word2vec,wordvectors和wordindec和word2vecmap给相同的价值 val word2VecMap = model.getVectors val newModel = new Word2VecModel(word2VecMap) assert(newModel.getVectors.mapValues(_.toSeq) === word2VecMap.mapValues(_.toSeq)) } test("Word2Vec throws exception when vocabulary is empty") {//Word2vec词汇为空时抛出异常 intercept[IllegalArgumentException] { val sentence = "a b c" val localDoc = Seq(sentence, sentence) val doc = sc.parallelize(localDoc) .map(line => line.split(" ").toSeq) //fit()方法将DataFrame转化为一个Transformer的算法 new Word2Vec().setMinCount(10).fit(doc) } } test("Word2VecModel") {//word2vec模型 val num = 2 val word2VecMap = Map( //每个单词都关联两个向量,分别表示词向量和上下文向量 ("china", Array(0.50f, 0.50f, 0.50f, 0.50f)), ("japan", Array(0.40f, 0.50f, 0.50f, 0.50f)), ("taiwan", Array(0.60f, 0.50f, 0.50f, 0.50f)), ("korea", Array(0.45f, 0.60f, 0.60f, 0.60f)) ) //word2vec是一个将单词转换成向量形式的工具。 //可以把对文本内容的处理简化为向量空间中的向量运算,计算出向量空间上的相似度,来表示文本语义上的相似度 val model = new Word2VecModel(word2VecMap) //显示了指定单词的2个同义词, val syms = model.findSynonyms("china", num) assert(syms.length == num) assert(syms(0)._1 == "taiwan") assert(syms(1)._1 == "japan") } test("model load / save") {//模型加载/保存 val word2VecMap = Map( ("china", Array(0.50f, 0.50f, 0.50f, 0.50f)), ("japan", Array(0.40f, 0.50f, 0.50f, 0.50f)), ("taiwan", Array(0.60f, 0.50f, 0.50f, 0.50f)), ("korea", Array(0.45f, 0.60f, 0.60f, 0.60f)) ) val model = new Word2VecModel(word2VecMap) val tempDir = Utils.createTempDir() val path = tempDir.toURI.toString try { model.save(sc, path) val sameModel = Word2VecModel.load(sc, path) assert(sameModel.getVectors.mapValues(_.toSeq) === model.getVectors.mapValues(_.toSeq)) } finally { Utils.deleteRecursively(tempDir) } } }
tophua/spark1.52
mllib/src/test/scala/org/apache/spark/mllib/feature/Word2VecSuite.scala
Scala
apache-2.0
5,634
package blended.updater.config case class ServiceInfo( name: String, serviceType: String, timestampMsec: Long, lifetimeMsec: Long, props: Map[String, String] ) { def isOutdatedAt(refTimeStampMsec: Long): Boolean = refTimeStampMsec > (math.min(0L, timestampMsec) + math.min(0, lifetimeMsec)) def isOutdated(): Boolean = isOutdatedAt(System.currentTimeMillis()) override def toString(): String = getClass().getSimpleName() + "(name=" + name + ",serviceType=" + serviceType + ",timestampMsec=" + timestampMsec + ",lifetimeMsec=" + lifetimeMsec + ",props=" + props + ")" }
woq-blended/blended
blended.updater.config/shared/src/main/scala/blended/updater/config/ServiceInfo.scala
Scala
apache-2.0
643
package scdbpf import java.nio.ByteBuffer import DbpfUtil._ sealed trait LText extends DbpfType { val text: String } object LText { def apply(text: String): LText = new FreeLText(text) implicit val converter = new Converter[DbpfType, LText] { def apply(from: DbpfType): LText = { new BufferedLText(from.dataView) } } private val controlChar: Short = 0x1000 private class BufferedLText(arr: Array[Byte]) extends RawType(arr) with LText { val text: String = { val buf = wrapLEBB(data) if (data.length < 4) { throw new DbpfDecodeFailedException(f"length is only ${data.length}, minimum is 4 bytes") } val expectedSize = data.length - 4 val count = buf.getShort() * 2 val cc = buf.getShort() // 0x1000 if (cc != controlChar) { throw new DbpfDecodeFailedException(f"control character was 0x$cc%04X, expected 0x1000") } else if (count != expectedSize) { // currently treats UTF-16 as fixed-width encoding throw new DbpfDecodeFailedException(f"declared length was $count, expected $expectedSize") } new String(data, 4, expectedSize, "UTF-16LE") } } private class FreeLText(val text: String) extends LText { protected lazy val data: Array[Byte] = { val buf = allocLEBB(4 + 2 * text.length) buf.putShort(text.length.toShort) buf.putShort(LText.controlChar) buf.put(text.getBytes("UTF-16LE")) assert(buf.remaining() == 0) buf.array() } } }
memo33/scdbpf
src/main/scala/scdbpf/LText.scala
Scala
mit
1,507
/* * 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 import org.apache.spark.sql._ import org.apache.spark.sql.catalyst.expressions._ import org.apache.spark.sql.catalyst.planning._ import org.apache.spark.sql.catalyst.plans._ import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan import org.apache.spark.sql.execution.datasources.{CreateTableUsing, CreateTableUsingAsSelect, DescribeCommand} import org.apache.spark.sql.execution.{DescribeCommand => RunnableDescribeCommand, _} import org.apache.spark.sql.hive.execution._ private[hive] trait HiveStrategies { // Possibly being too clever with types here... or not clever enough. self: SQLContext#SparkPlanner => val hiveContext: HiveContext object Scripts extends Strategy { def apply(plan: LogicalPlan): Seq[SparkPlan] = plan match { case logical.ScriptTransformation(input, script, output, child, schema: HiveScriptIOSchema) => ScriptTransformation(input, script, output, planLater(child), schema)(hiveContext) :: Nil case _ => Nil } } object DataSinks extends Strategy { def apply(plan: LogicalPlan): Seq[SparkPlan] = plan match { case logical.InsertIntoTable( table: MetastoreRelation, partition, child, overwrite, ifNotExists) => execution.InsertIntoHiveTable( table, partition, planLater(child), overwrite, ifNotExists) :: Nil case hive.InsertIntoHiveTable( table: MetastoreRelation, partition, child, overwrite, ifNotExists) => execution.InsertIntoHiveTable( table, partition, planLater(child), overwrite, ifNotExists) :: Nil case _ => Nil } } /** * Retrieves data using a HiveTableScan. Partition pruning predicates are also detected and * applied. * 使用HiveTableScan检索数据,还检测并应用分区修剪谓词 */ object HiveTableScans extends Strategy { def apply(plan: LogicalPlan): Seq[SparkPlan] = plan match { case PhysicalOperation(projectList, predicates, relation: MetastoreRelation) => // Filter out all predicates that only deal with partition keys, these are given to the // hive table scan operator to be used for partition pruning. val partitionKeyIds = AttributeSet(relation.partitionKeys) val (pruningPredicates, otherPredicates) = predicates.partition { predicate => !predicate.references.isEmpty && predicate.references.subsetOf(partitionKeyIds) } pruneFilterProject( projectList, otherPredicates, identity[Seq[Expression]], HiveTableScan(_, relation, pruningPredicates)(hiveContext)) :: Nil case _ => Nil } } object HiveDDLStrategy extends Strategy { def apply(plan: LogicalPlan): Seq[SparkPlan] = plan match { case CreateTableUsing( tableIdent, userSpecifiedSchema, provider, false, opts, allowExisting, managedIfNoPath) => val cmd = CreateMetastoreDataSource( tableIdent, userSpecifiedSchema, provider, opts, allowExisting, managedIfNoPath) ExecutedCommand(cmd) :: Nil case CreateTableUsingAsSelect( tableIdent, provider, false, partitionCols, mode, opts, query) => val cmd = CreateMetastoreDataSourceAsSelect(tableIdent, provider, partitionCols, mode, opts, query) ExecutedCommand(cmd) :: Nil case _ => Nil } } case class HiveCommandStrategy(context: HiveContext) extends Strategy { def apply(plan: LogicalPlan): Seq[SparkPlan] = plan match { case describe: DescribeCommand => val resolvedTable = context.executePlan(describe.table).analyzed resolvedTable match { case t: MetastoreRelation => ExecutedCommand( DescribeHiveTableCommand(t, describe.output, describe.isExtended)) :: Nil case o: LogicalPlan => val resultPlan = context.executePlan(o).executedPlan ExecutedCommand(RunnableDescribeCommand( resultPlan, describe.output, describe.isExtended)) :: Nil } case _ => Nil } } }
tophua/spark1.52
sql/hive/src/main/scala/org/apache/spark/sql/hive/HiveStrategies.scala
Scala
apache-2.0
4,899
package net.danielkza.http2.hpack.coders import scalaz.\\/- import org.specs2.matcher.DataTables import org.specs2.mutable.Specification import net.danielkza.http2.TestHelpers import net.danielkza.http2.hpack.HeaderRepr._ class HeaderCoderTest extends Specification with DataTables with TestHelpers { val plainCoder = new HeaderCoder(HeaderCoder.compress.Never) val compressedCoder = new HeaderCoder(HeaderCoder.compress.Always) val plainCases = { "header" | "encoded" |> IncrementalLiteral("custom-key", "custom-header") ! hex_bs"40 0a 6375 7374 6f6d 2d6b 6579 0d 6375 7374 6f6d 2d68 6561 6465 72" | LiteralWithIndexedName(4, "/sample/path") ! hex_bs"04 0c 2f73 616d 706c 652f 7061 7468 " | NeverIndexed("password", "secret") ! hex_bs"10 08 7061 7373 776f 7264 06 7365 6372 6574" | Indexed(2) ! hex_bs"82" | DynamicTableSizeUpdate(256) ! hex_bs"3f e1 01" } val compressedCases = { "header" | "encoded" |> IncrementalLiteralWithIndexedName(1, "www.example.com") ! hex_bs"41 8c f1e3 c2e5 f23a 6ba0 ab90 f4ff" | IncrementalLiteral("custom-key", "custom-value") ! hex_bs"40 88 25a8 49e9 5ba9 7d7f 89 25a8 49e9 5bb8 e8b4 bf" | IncrementalLiteralWithIndexedName(33, "Mon, 21 Oct 2013 20:13:21 GMT") ! hex_bs"61 96 d07a be94 1054 d444 a820 0595 040b 8166 e082 a62d 1bff" | IncrementalLiteralWithIndexedName(55, "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1") ! hex_bs""" 77 ad 94e7 821d d7f2 e6c7 b335 dfdf cd5b 3960 d5af 2708 7f36 72c1 ab27 0fb5 291f 9587 3160 65c0 03ed 4ee5 b106 3d50 07""" } "HeaderCoder" should { "decode" in { "plain-text" in { plainCases | { (header, encoded) => plainCoder.decode(encoded) must_== \\/-((header, encoded.length)) } } "compressed" in { compressedCases | { (header, encoded) => val res = compressedCoder.decode(encoded) res must_== \\/-((header, encoded.length)) } } } "encode" in { "plain-text" in { plainCases | { (header, encoded) => plainCoder.encode(header) must_== \\/-(encoded) } } "compressed" in { compressedCases | { (header, encoded) => val res = compressedCoder.encode(header) res must_== \\/-(encoded) } } } } }
danielkza/h2scala
core/src/test/scala/net/danielkza/http2/hpack/coders/HeaderCoderTest.scala
Scala
apache-2.0
2,357
package com.sksamuel.elastic4s.alias import com.sksamuel.elastic4s.searches.QueryDefinition import com.sksamuel.elastic4s.searches.queries.QueryStringQueryDefinition import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest.AliasActions import org.elasticsearch.index.query.QueryBuilder case class RemoveAliasActionDefinition(alias: String, index: String, routing: Option[String] = None, indexRouting: Option[String] = None, searchRouting: Option[String] = None, filter: Option[QueryBuilder] = None) extends AliasActionDefinition { require(alias.nonEmpty, "alias must not be null or empty") require(index.nonEmpty, "index must not be null or empty") def withRouting(route: String) = copy(routing = Option(route)) def withSearchRouting(searchRouting: String) = copy(searchRouting = Option(searchRouting)) def withIndexRouting(indexRouting: String) = copy(indexRouting = Option(indexRouting)) def withFilter(query: String): RemoveAliasActionDefinition = withFilter(QueryStringQueryDefinition(query)) def withFilter(query: QueryBuilder): RemoveAliasActionDefinition = copy(filter = Option(query)) def withFilter(query: QueryDefinition): RemoveAliasActionDefinition = withFilter(query.builder) override def build: IndicesAliasesRequest.AliasActions = { val action = AliasActions.remove().alias(alias).index(index) routing.foreach(action.routing) indexRouting.foreach(action.indexRouting) searchRouting.foreach(action.searchRouting) searchRouting.foreach(action.filter) action } }
ulric260/elastic4s
elastic4s-core/src/main/scala/com/sksamuel/elastic4s/alias/RemoveAliasActionDefinition.scala
Scala
apache-2.0
1,810
package planck /** Based on * http://graphics.cs.williams.edu/courses/cs371/s07/reading/quaternions.pdf * * @param entriesSeq A sequence of entries, (w,x,y,z) */ case class Quaterniond(entriesSeq: Seq[Double]) { if(entriesSeq.size != 4) throw new SizeMismatchException val entries = Vecd(entriesSeq) def apply(i: Integer) = entries(i) def normalize = Quaterniond.v(entries.normalize) val lengthSq = entries.lengthSq lazy val length = entries.length def ~=(that: Any) = that match { case e: Quaterniond => this.entries ~= e.entries case _ => false } def *(o: Quaterniond) = { val q = this.entries.entries val r = o.entries.entries val qw = q(0) val rw = r(0) val qx = q(1) val rx = r(1) val qy = q(2) val ry = r(2) val qz = q(3) val rz = r(3) val w = qw*rw - qx*rx - qy*ry - qz*rz val x = qw*rx + qx*rw + qy*rz - qz*ry val y = qw*ry - qx*rz + qy*rw + qz*rx val z = qw*rz + qx*ry - qy*rx + qz*rw Quaterniond(Seq(w, x, y, z)) } def toRotationMatrix = { val q = this.entries.entries val qw = q(0) val qx = q(1) val qy = q(2) val qz = q(3) val qx2 = 2*qx*qx val qy2 = 2*qy*qy val qz2 = 2*qz*qz val qwqx = 2*qw*qx val qwqy = 2*qw*qy val qwqz = 2*qw*qz val qxqy = 2*qx*qy val qxqz = 2*qx*qz val qyqz = 2*qy*qz val col1 = Vecd.n(1-qy2-qz2, qxqy+qwqz, qxqz-qwqy, 0) val col2 = Vecd.n(qxqy-qwqz, 1-qx2-qz2, qyqz+qwqx, 0) val col3 = Vecd.n(qxqz+qwqy, qyqz-qwqx, 1-qx2-qy2, 0) val col4 = Vecd.n(0, 0, 0, 1) Matrixd.n(col1, col2, col3, col4) } } object Quaterniond { def n(w: Double, x: Double, y: Double, z: Double) = Quaterniond(Seq(w,x,y,z)) def v(vec: Vecd) = Quaterniond(vec.entries) /** Create a quaternion from yaw, pitch and roll. * * @param yaw Rotation in radians around the X axis. * @param pitch Rotation in radians around the Y axis. * @param roll Rotation in radians around the Z axis. * @return The rotation quaternion. */ def fromYPR(yaw: Double, pitch: Double, roll: Double) = { val c1 = Math.cos(yaw / 2) val c2 = Math.cos(pitch / 2) val c3 = Math.cos(roll / 2) val s1 = Math.sin(yaw / 2) val s2 = Math.sin(pitch / 2) val s3 = Math.sin(roll / 2) val w = c1*c2*c3 - s1*s2*s3 val x = s1*s2*c3 + c1*c2*s3 val y = s1*c2*c3 + c1*s2*s3 val z = c1*s2*c3 - s1*c2*s3 Quaterniond(Seq(w, x, y, z)) } }
noryb009/planck
src/planck/Quaterniond.scala
Scala
mit
2,473
package edu.cornell.cdm89.scalaspec.domain import akka.actor.{Actor, ActorLogging, ActorRef} import edu.cornell.cdm89.scalaspec.pde.LaxFriedrichsFlux import LaxFriedrichsFlux.BoundaryValues class InternalBoundaryActor(x: Double) extends Actor with ActorLogging { //override def preStart(): Unit = log.info(s"Starting internal boundary at $x") def receive = state0 def state0: Receive = { case bv1: BoundaryValues => context.become(state1(bv1, sender)) } def state1(bv1: BoundaryValues, element1: ActorRef): Receive = { case bv2: BoundaryValues => require(bv1.t == bv2.t) require(bv1.norm*bv2.norm < 0.0) val element2 = sender val flux = LaxFriedrichsFlux.flux(bv1, bv2) //println(self.path.name + s": $bv1 $bv2 -> ${flux}") element1 ! flux element2 ! flux context.become(state0) } }
cdmuhlb/DGenerate
src/main/scala/edu/cornell/cdm89/scalaspec/domain/InternalBoundaryActor.scala
Scala
mit
866
package us.feliscat.ner import us.feliscat.text.StringOption import us.feliscat.time.TimeTmp /** * @author K.Sakamoto * Created on 2015/11/26 */ object NamedEntity { def apply(textOpt: StringOption, time: TimeTmp, indexOffset: Range, metaInfoOpt: StringOption, recognizerOpt: StringOption, synonyms: Seq[String]): NamedEntity = { new NamedEntity(textOpt, time, indexOffset, metaInfoOpt, recognizerOpt, synonyms) } } /** * @author K.Sakamoto * @param textOpt us.feliscat.text * @param time us.feliscat.time * @param indexOffset index and offset * @param metaInfoOpt meta info * @param recognizerOpt recognizer * @param synonyms synonyms */ class NamedEntity(val textOpt: StringOption, val time: TimeTmp, val indexOffset: Range, val metaInfoOpt: StringOption, val recognizerOpt: StringOption, val synonyms: Seq[String])
ktr-skmt/FelisCatusZero-multilingual
libraries/src/main/scala/us/feliscat/ner/NamedEntity.scala
Scala
apache-2.0
1,009
import java.util.concurrent.TimeUnit import cats.effect.IO import com.codahale.metrics.graphite.{Graphite, GraphiteReporter} import com.codahale.metrics.{ConsoleReporter, MetricRegistry} import org.http4s.server.blaze.BlazeBuilder import scopt.OptionParser import cats._ import cats.implicits._ import cats.data._ import cats.syntax._ import cats.effect._ import fs2._ object Main extends StreamApp[IO] { case class Config(host: String = "localhost", port: Int = 8090, consoleMetrics: Boolean = false, graphite: Option[String] = None, graphitePrefix: String = "moe.pizza.timerboard") val parser = new OptionParser[Config]("timerboard") { head("timerboard backend") opt[String]("host") .action { (x, c) => c.copy(host = x) } .optional() .text("defaults to localhost") opt[Int]("port") .action { (x, c) => c.copy(port = x) } .optional() .text("defaults to 8090") opt[Boolean]("console_metrics") .action { (x, c) => c.copy(consoleMetrics = x) } .optional() .text("dump metrics to the console, defaults off") opt[String]("graphite") .action { (x, c) => c.copy(graphite = Some(x)) } .optional() .text("address to the graphite server, sends metrics if enabled") opt[String]("graphite_prefix") .action { (x, c) => c.copy(graphitePrefix = x) } .optional() .text("prefix for graphite metrics, defaults to moe.pizza.timerboard") } override def stream(args: List[String], requestShutdown: IO[Unit]): fs2.Stream[IO, StreamApp.ExitCode] = { implicit val ec = scala.concurrent.ExecutionContext.global parser.parse(args, Config()) match { case Some(config) => println("starting") val metrics = new MetricRegistry if (config.consoleMetrics) { ConsoleReporter .forRegistry(metrics) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .build() .start(30, TimeUnit.SECONDS) } config.graphite.foreach { g => GraphiteReporter .forRegistry(metrics) .convertRatesTo(TimeUnit.SECONDS) .convertDurationsTo(TimeUnit.MILLISECONDS) .prefixedWith(config.graphitePrefix) .build(new Graphite(g, 2003)) .start(1, TimeUnit.SECONDS) } for { sched <- Scheduler.apply[IO](8) svc = new StreamingService(metrics, sched, scala.concurrent.ExecutionContext.global) _ = println("streaming set up, mounting as http server") exit <- BlazeBuilder[IO] .mountService(svc.service, "/") .bindHttp(config.port, config.host) .serve } yield exit case None => Stream.emit(StreamApp.ExitCode.Error) } } }
xxpizzaxx/timerboard-net-backend-esi
src/main/scala/Main.scala
Scala
mit
2,982
/* * Copyright 2018 Analytics Zoo 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.zoo.feature import com.intel.analytics.bigdl.nn.abstractnn.DataFormat import com.intel.analytics.bigdl.tensor.Tensor import com.intel.analytics.bigdl.tensor.TensorNumericMath.TensorNumeric import com.intel.analytics.bigdl.transform.vision.image import com.intel.analytics.bigdl.transform.vision.image.MatToFloats._ import com.intel.analytics.bigdl.transform.vision.image.opencv.OpenCVMat import com.intel.analytics.bigdl.transform.vision.image._ import com.intel.analytics.zoo.common.{NNContext, Utils} import com.intel.analytics.zoo.feature.common.{BigDLAdapter, Preprocessing} import com.intel.analytics.zoo.feature.image._ import org.apache.commons.io.FileUtils import org.apache.logging.log4j.LogManager import org.apache.spark.{SparkConf, SparkContext} import org.opencv.imgcodecs.Imgcodecs import org.scalatest.{BeforeAndAfter, FlatSpec, Matchers} import scala.reflect.ClassTag class FeatureSpec extends FlatSpec with Matchers with BeforeAndAfter { val resource = getClass.getClassLoader.getResource("imagenet/n04370456/") val imagenet = getClass.getClassLoader.getResource("imagenet") val gray = getClass.getClassLoader.getResource("gray") var sc : SparkContext = _ before { val conf = new SparkConf().setAppName("Test Feature Engineering").setMaster("local[1]") sc = NNContext.initNNContext(conf) } after { if (sc != null) { sc.stop() } } "BigDLAdapter" should "adapt BigDL Transformer" in { val newResize = BigDLAdapter(ImageResize(1, 1)) assert(newResize.isInstanceOf[Preprocessing[_, _]]) } "Local ImageSet" should "work with resize" in { val image = ImageSet.read(resource.getFile, resizeH = 200, resizeW = 200) val imf = image.toLocal().array.head require(imf.getHeight() == 200) require(imf.getWidth() == 200) require(imf.getChannel() == 3) val imageGray = ImageSet.read(gray.getFile, resizeH = 200, resizeW = 200) val imfGray = imageGray.toLocal().array.head require(imfGray.getHeight() == 200) require(imfGray.getWidth() == 200) require(imfGray.getChannel() == 1) } "Distribute ImageSet" should "work with resize" in { val image = ImageSet.read(resource.getFile, sc, resizeH = 200, resizeW = 200) val imf = image.toDistributed().rdd.collect().head require(imf.getHeight() == 200) require(imf.getWidth() == 200) require(imf.getChannel() == 3) val imageGray = ImageSet.read(gray.getFile, sc, resizeH = 200, resizeW = 200) val imfGray = imageGray.toDistributed().rdd.collect().head require(imfGray.getHeight() == 200) require(imfGray.getWidth() == 200) require(imfGray.getChannel() == 1) } "Local ImageSet" should "work with bytes" in { val files = Utils.listLocalFiles(resource.getFile) val bytes = files.map { p => FileUtils.readFileToByteArray(p) } ImageSet.array(bytes) } "Distribute ImageSet" should "work with bytes" in { val data = sc.binaryFiles(resource.getFile).map { case (p, stream) => stream.toArray() } val images = ImageSet.rddBytes(data) images.toDistributed().rdd.collect() } private def getRelativePath(path: String) = { val fileUri = new java.io.File(path).toURI val currentUri = new java.io.File("").toURI currentUri.relativize(fileUri).getRawPath } "Distributed ImageSet" should "read relative path" in { val relativePath = getRelativePath(imagenet.getFile) val image = ImageSet.read(relativePath, sc, withLabel = true) image.toDistributed().rdd.collect() } "Local ImageSet" should "read relative path" in { val relativePath = getRelativePath(imagenet.getFile) val image = ImageSet.read(relativePath, withLabel = true) image.toLocal().array } "ImageBytesToMat" should "work with png and jpg" in { val path = getClass.getClassLoader.getResource("png").getFile val image = ImageSet.read(path, sc) val image2 = ImageSet.read(path, sc) val jpg = image -> ImageBytesToMat(imageCodec = Imgcodecs.CV_LOAD_IMAGE_COLOR) val png = image2 -> ImageBytesToMat() val imfJpg = jpg.toDistributed().rdd.collect().head val imfPng = png.toDistributed().rdd.collect().head val (height, width, channel) = imfJpg.opencvMat().shape() val (height2, width2, channel2) = imfPng.opencvMat().shape() require(height == height2 && width == width2) require(channel == 3 && channel2 == 4) } "ImageNormalize" should "work with min max normType" in { val image = ImageSet.read(resource.getFile, sc) val jpg = image -> PerImageNormalize(0, 1) -> ImageMatToFloats() val imfJpg = jpg.toDistributed().rdd.collect().head imfJpg.floats().foreach{ t => assert(t>=0 && t<=1.0)} } "ImageMatToTensor" should "work with both NCHW and NHWC" in { val resource = getClass.getClassLoader.getResource("pascal/") val data = ImageSet.read(resource.getFile) val nhwc = (data -> ImageMatToTensor[Float](format = DataFormat.NHWC)).toLocal() .array.head.apply[Tensor[Float]](ImageFeature.imageTensor) require(nhwc.isContiguous() == true) val data2 = ImageSet.read(resource.getFile) require(data2.toLocal().array.head.apply[Tensor[Float]](ImageFeature.imageTensor) == null) val nchw = (data2 -> ImageMatToTensor[Float]()).toLocal() .array.head.apply[Tensor[Float]](ImageFeature.imageTensor) require(nchw.transpose(1, 2).transpose(2, 3).contiguous().storage().array().deep == nhwc.storage().array().deep) } "ImageChannelNormalize with std not 1" should "work properly" in { val data = ImageSet.read(resource.getFile) val transformer = ImageChannelNormalize(100, 200, 300, 4, 3, 2) -> ImageMatToTensor[Float]() val transformed = transformer(data) val imf = transformed.asInstanceOf[LocalImageSet].array(0) val data2 = ImageFrame.read(resource.getFile) val toFloat = new MatToFloatsWithNorm(meanRGB = Some(100f, 200f, 300f), stdRGB = Some(4f, 3f, 2f)) val transformed2 = toFloat(data2) val imf2 = transformed2.asInstanceOf[LocalImageFrame].array(0) imf2.floats().length should be (270 * 290 * 3) imf2.floats() should equal(imf.floats()) } } class MatToFloatsWithNorm(validHeight: Int = 300, validWidth: Int = 300, validChannels: Int = 3, meanRGB: Option[(Float, Float, Float)] = None, stdRGB: Option[(Float, Float, Float)] = None, outKey: String = ImageFeature.floats) extends FeatureTransformer { @transient private var data: Array[Float] = _ private def normalize(img: Array[Float], meanR: Float, meanG: Float, meanB: Float, stdR: Float = 1f, stdG: Float = 1f, stdB: Float = 1f): Array[Float] = { val content = img require(content.length % 3 == 0) var i = 0 while (i < content.length) { content(i + 2) = (content(i + 2) - meanR) / stdR content(i + 1) = (content(i + 1) - meanG) / stdG content(i + 0) = (content(i + 0) - meanB) / stdB i += 3 } img } override def transform(feature: ImageFeature): ImageFeature = { var input: OpenCVMat = null val (height, width, channel) = if (feature.isValid) { input = feature.opencvMat() (input.height(), input.width(), input.channels()) } else { (validHeight, validWidth, validChannels) } if (null == data || data.length < height * width * channel) { data = new Array[Float](height * width * channel) } if (feature.isValid) { try { OpenCVMat.toFloatPixels(input, data) normalize(data, meanRGB.get._1, meanRGB.get._2, meanRGB.get._3 , stdRGB.get._1, stdRGB.get._2, stdRGB.get._3) } finally { if (null != input) input.release() feature(ImageFeature.mat) = null } } feature(outKey) = data feature(ImageFeature.size) = (height, width, channel) feature } }
intel-analytics/analytics-zoo
zoo/src/test/scala/com/intel/analytics/zoo/feature/FeatureSpec.scala
Scala
apache-2.0
8,436
package com.metl.utils import java.math._ import java.security._ import java.security.interfaces._ import java.security.spec._ import javax.crypto._ import javax.crypto.spec._ import net.liftweb.common._ import scala.xml._ object CryptoTester extends Logger { val seeds = List("hello all","8charact","16characterslong","a worm","15","a") def testAll(crypto:Crypto) = { seeds.map(s => testSymmetric(crypto,s)) val c1 = crypto.cloneCrypto val c2 = crypto.cloneCrypto seeds.map(s => testCommutative(c1,c2,s)) } def testSymmetric(c:Crypto,input:String):Boolean = { try { debug("testSymmetric: %s, %s".format(c,input)) val inputBytes = input.getBytes val s1 = c.encryptCred(inputBytes) val s2 = c.decryptCred(s1) val s3 = new String(s2).trim == input.trim List(s1,s2,s3).foreach(li => trace("step: %s".format(li.toString))) debug("orig: %s, res: %s".format(input.trim,new String(s2).trim)) s3 } catch { case e:Throwable => { error("step: false",e) false } } } def testCommutative(c1:Crypto,c2:Crypto,input:String):Boolean = { try { debug("testCommutative, %s, %s".format(c1,input)) val inputBytes = input.getBytes val s1 = c1.encryptCred(inputBytes) val s2 = c2.encryptCred(s1) val s3 = c1.decryptCred(s2) val s4 = c2.decryptCred(s3) val s5 = new String(s4).trim == input.trim val s6 = c2.encryptCred(inputBytes) val s7 = c1.encryptCred(s6) val s8 = new String(s7).trim == new String(s2).trim List(s1,s2,s3,s4,s5,s6,s7,s8).foreach(li => trace("step: %s".format(li.toString))) debug("orig: %s, res: %s".format(input.trim,new String(s4).trim)) s5 && s8 } catch { case e:Throwable => { error("step: false",e) false } } } } //this allows for key exchange between dot.net and java class RSANormal extends Crypto("RSA","ECB","PKCS1Padding",None,None) //these three are the only one so far that's commutative class RSACommutative extends Crypto("RSA","None","NoPadding",None,None) class RSACommutative1 extends Crypto("RSA","ECB","NoPadding",None,None) class AESCTRCrypto extends Crypto("AES","CTR","NoPadding",None,None) //these are working tripleDes class DESCBCCrypto extends Crypto("DESede","CBC","ISO10126Padding",None,None) class DESECBCrypto extends Crypto("DESede","ECB","ISO10126Padding",None,None) //this is working AES class AESCBCCrypto extends Crypto("AES","CBC","ISO10126Padding",None,None) class Crypto(cipherName:String = "AES",cipherMode:String = "CBC",padding:String = "ISO10126Padding",inputKey:Option[Array[Byte]] = None,inputIv:Option[Array[Byte]] = None) { var publicKey:Option[java.security.Key] = None var privateKey:Option[java.security.Key] = None var key:Option[Object] = None var iv:Option[Object] = None var keyFactory:Option[Object] = None var keyGenerator:Option[Object] = None val cipher = List(cipherName,cipherMode,padding).filter(i => i.length > 0).mkString("/") val (ecipher,dcipher) = Stopwatch.time("Crypto(%s,%s,%s)".format(cipher,inputKey,inputIv), { val eciph = Cipher.getInstance(cipher) val dciph = Cipher.getInstance(cipher) cipherName match { case "RSA" => { //for RSA, I'm using inputKey and inputIv as the two primes necessary to share to ensure commutative RSA behaviour val shouldUseInput = inputKey match { case Some(keyBytes) => inputIv match { case Some(inputIv) => true case _ => false } case _ => false } shouldUseInput match { case true => { val p = inputKey.map(i => new BigInteger(i)).getOrElse(BigInteger.probablePrime(512,new SecureRandom)) val q = inputIv.map(i => new BigInteger(i)).getOrElse(BigInteger.probablePrime(512,new SecureRandom)) val n = p.multiply(q) val phi = (p.subtract(new BigInteger("1")).multiply(q.subtract(new BigInteger("1")))) val modulus = n var pubKeyWorking = java.lang.Math.abs((modulus.divide(new BigInteger("100")).intValue * new java.util.Random().nextFloat).toInt) var pubKeyFound = false while (pubKeyFound == false){ print(pubKeyWorking+",") if (phi.gcd(new BigInteger(pubKeyWorking.toString)).equals(BigInteger.ONE)) { pubKeyFound = true } else { pubKeyWorking = pubKeyWorking + 1 } } val pubExp = new BigInteger(pubKeyWorking.toString) val privExp = pubExp.modInverse(phi) val kgen = KeyFactory.getInstance(cipherName) val pubKeySpec = new RSAPublicKeySpec(modulus, pubExp) val privKeySpec = new RSAPrivateKeySpec(modulus, privExp) val pubKey = kgen.generatePublic(pubKeySpec) val privKey = kgen.generatePrivate(privKeySpec) eciph.init(Cipher.ENCRYPT_MODE, pubKey) dciph.init(Cipher.DECRYPT_MODE, privKey) publicKey = Some(pubKey) privateKey = Some(privKey) keyFactory = Some(kgen) } case false => { val generator = KeyPairGenerator.getInstance(cipherName) generator.initialize(1024) val keyPair = generator.generateKeyPair val pubKey = keyPair.getPublic val privKey = keyPair.getPrivate eciph.init(Cipher.ENCRYPT_MODE, pubKey) dciph.init(Cipher.DECRYPT_MODE, privKey) publicKey = Some(pubKey) privateKey = Some(privKey) keyGenerator = Some(generator) } } } case _ => { val kgen = KeyGenerator.getInstance(cipherName) val internalKey = cipherName match { case "DES" => { kgen.init(56) inputKey.map(i => new SecretKeySpec(i,cipherName)).getOrElse(kgen.generateKey) } case "AES" => { kgen.init(128) inputKey.map(i => new SecretKeySpec(i,cipherName)).getOrElse(kgen.generateKey) } case "DESede" => { kgen.init(168) inputKey.map(i => new SecretKeySpec(i,cipherName)).getOrElse(kgen.generateKey) } case _ => { kgen.init(128) inputKey.map(i => new SecretKeySpec(i,cipherName)).getOrElse(kgen.generateKey) } } val internalIv = cipherName match { // List(1,2,3,4,5,6,7,8).map(a => a.asInstanceOf[Byte]).toArray.take(8) case "DESede" => new IvParameterSpec(inputIv.getOrElse(Array[Byte](1,2,3,4,5,6,7,8))) case _ => new IvParameterSpec(inputIv.getOrElse(kgen.generateKey.getEncoded)) } eciph.init(Cipher.ENCRYPT_MODE, internalKey, internalIv) dciph.init(Cipher.DECRYPT_MODE, internalKey, internalIv) key = Some(internalKey) iv = Some(internalIv) keyGenerator = Some(kgen) } } (eciph,dciph) }) def cloneCrypto = Stopwatch.time("Crypto.cloneCrypto",new Crypto(cipherName,cipherMode,padding,inputKey,inputIv)) override def toString = "Crypto(%s,%s,%s)".format(cipher,inputKey,inputIv) val encoding = "UTF8" def encryptCred(plainText:String):String = { val b64Encoder = new sun.misc.BASE64Encoder() b64Encoder.encode(encryptCred(plainText.getBytes)) } def encryptCred(plainText:Array[Byte]):Array[Byte] = Stopwatch.time("Crypto.encryptCred",{ ecipher.doFinal(plainText) }) def decryptCred(encryptedText:String):String = { val b64Encoder = new sun.misc.BASE64Decoder() new String(decryptCred(b64Encoder.decodeBuffer(encryptedText))) } def decryptCred(encryptedText:Array[Byte]):Array[Byte] = Stopwatch.time("Crypto.decryptCred", { dcipher.doFinal(encryptedText) }) def decryptToken(username:String, encryptedText:String):String = { "not yet implemented" } def getXmlPublicKey:Node = Stopwatch.time("Crypto.getXmlPublicKey", { privateKey.map(pk => { val b64Encoder = new sun.misc.BASE64Encoder() val privKey = pk.asInstanceOf[RSAPrivateCrtKey] val wrap = (i:BigInteger) => b64Encoder.encode(i.toByteArray) val keySpec = KeyFactory.getInstance(cipherName).getKeySpec(privKey, classOf[RSAPrivateCrtKeySpec]) val mod = wrap(keySpec.getModulus) val pubExp = wrap(keySpec.getPublicExponent) <RSAKeyValue><Modulus>{mod}</Modulus><Exponent>{pubExp}</Exponent></RSAKeyValue> }).getOrElse(<NoKey/>) }) def getXmlPrivateKey:Node = Stopwatch.time("Crypto.getXmlPrivateKey", { privateKey.map(pk => { val b64Encoder = new sun.misc.BASE64Encoder() val privKey = pk.asInstanceOf[RSAPrivateCrtKey] val wrap = (i:BigInteger) => b64Encoder.encode(i.toByteArray) val keySpec = KeyFactory.getInstance(cipherName).getKeySpec(privKey, classOf[RSAPrivateCrtKeySpec]) val mod = wrap(keySpec.getModulus) val pubExp = wrap(keySpec.getPublicExponent) val p = wrap(keySpec.getPrimeP) val q = wrap(keySpec.getPrimeQ) val dp = wrap(keySpec.getPrimeExponentP) val dq = wrap(keySpec.getPrimeExponentQ) val iq = wrap(keySpec.getCrtCoefficient) val d = wrap(keySpec.getPrivateExponent) <RSAKeyValue><Modulus>{mod}</Modulus><Exponent>{pubExp}</Exponent><P>{p}</P><Q>{q}</Q><DP>{dp}</DP><DQ>{dq}</DQ><InverseQ>{iq}</InverseQ><D>{d}</D></RSAKeyValue> }).getOrElse(<NoKey/>) }) def getXmlKey:Node = Stopwatch.time("Crypto.getXmlKey", { key.map(k => { val internalKeyBytes = k.asInstanceOf[java.security.Key].getEncoded val b64Encoder = new sun.misc.BASE64Encoder() val internalKey = b64Encoder.encode(internalKeyBytes) <KeyPair><Key>{internalKey}</Key></KeyPair> }).getOrElse(<NoKey/>) }) def getXmlKeyAndIv:Node = Stopwatch.time("Crypto.getXmlKeyAndIv", { key.map(k => { val b64Encoder = new sun.misc.BASE64Encoder() val internalKey = b64Encoder.encode(k.asInstanceOf[java.security.Key].getEncoded) val internalIv = iv.map(i => b64Encoder.encode(i.asInstanceOf[javax.crypto.spec.IvParameterSpec].getIV)).getOrElse("") <KeyPair><Key>{internalKey}</Key><Iv>{internalIv}</Iv></KeyPair> }).getOrElse(<NoKey/>) }) } // The Dot.Net code (Unity Compliant) which will communicate correctly with this java encryption class /* // FOR RSA - we'll use this for the authcate exchange, and to provide the client with an appropriate key and iv for the later behaviour // this keystring should be fetched from the java server-side Crypto.getXmlPublicKey var keyString = "<RSAKeyValue><Modulus>AI3U/glU+EL31OVNVYs7T35BLdYZ55O9yMYHzH+W/SXEwRv08/7T3nBX72m5GLSeq56gMj3gyPhLe7MaFsndne30b9NA5WqRu6CkBayR+/3tMC86bs8P7b/2k+YmKhry6q+RCf82PDXk7cEpx4P/1CeWX4AptDV4IVNmSQk2PaBH</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; var orig = "hello"; var inputBytes = Encoding.UTF8.GetBytes(orig); Debug.Log("RSA from XML"); var rprovider = new System.Security.Cryptography.RSACryptoServiceProvider(1024); rprovider.FromXmlString(keyString); var rEncryptedBytes = rprovider.Encrypt(inputBytes, false); Debug.Log("enc64: " + Convert.ToBase64String(rEncryptedBytes)); Debug.Log("RSA from XML complete"); // FOR DSA - we'll be given the key and IV during the initial handshake, and we'll then use this to make all subsequent web requests. var provider = new System.Security.Cryptography.TripleDESCryptoServiceProvider(); provider.Padding = System.Security.Cryptography.PaddingMode.ISO10126; provider.Mode = System.Security.Cryptography.CipherMode.CBC; provider.GenerateKey(); provider.GenerateIV(); var encryptor = provider.CreateEncryptor(); var decryptor = provider.CreateDecryptor(); var enc = encryptor.TransformFinalBlock(inputBytes,0,inputBytes.Length); var dec = decryptor.TransformFinalBlock(enc, 0, enc.Length); Debug.Log(String.Format("ORIG: {0}, ENC: {1}, DEC: {2}", orig, Encoding.UTF8.GetString(enc), Encoding.UTF8.GetString(dec))); */
StackableRegiments/analyticalmetlx
src/main/scala/com/metl/utils/Crypto.scala
Scala
apache-2.0
11,499
/* * Copyright (c) 2014-2018 by The Monix Project Developers. * See the project homepage at: https://monix.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package monix.reactive.internal.operators import monix.execution.Ack.{Continue, Stop} import scala.util.control.NonFatal import monix.reactive.Observable.Operator import monix.reactive.observers.Subscriber private[reactive] final class DropByPredicateWithIndexOperator[A](p: (A, Int) => Boolean) extends Operator[A,A] { def apply(out: Subscriber[A]): Subscriber[A] = new Subscriber[A] { implicit val scheduler = out.scheduler private[this] var continueDropping = true private[this] var index = 0 private[this] var isDone = false def onNext(elem: A) = { if (continueDropping) { // See Section 6.4. in the Rx Design Guidelines: // Protect calls to user code from within an operator var streamError = true try { val isStillInvalid = p(elem, index) streamError = false if (isStillInvalid) { index += 1 Continue } else { continueDropping = false out.onNext(elem) } } catch { case NonFatal(ex) if streamError => onError(ex) Stop } } else out.onNext(elem) } def onError(ex: Throwable): Unit = if (!isDone) { isDone = true out.onError(ex) } def onComplete(): Unit = if (!isDone) { isDone = true out.onComplete() } } }
Wogan/monix
monix-reactive/shared/src/main/scala/monix/reactive/internal/operators/DropByPredicateWithIndexOperator.scala
Scala
apache-2.0
2,173
/* * Copyright 2014–2018 SlamData 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 quasar.impl.datasources import slamdata.Predef.{Exception, Option, Unit} import quasar.Condition import quasar.fp.ski.κ import cats.Functor import cats.effect.Sync import cats.effect.concurrent.Ref import cats.syntax.functor._ import scalaz.{IMap, Order} final class DefaultDatasourceErrors[F[_]: Functor, I: Order] private ( errors: Ref[F, IMap[I, Exception]]) extends DatasourceErrors[F, I] { val erroredDatasources: F[IMap[I, Exception]] = errors.get def datasourceError(datasourceId: I): F[Option[Exception]] = erroredDatasources.map(_.lookup(datasourceId)) } object DefaultDatasourceErrors { /** * Returns the `DatasourceErrors` impl and a callback function to invoke * when the condition of a `Datasource` changes. */ def apply[F[_]: Sync, I: Order] : F[(DatasourceErrors[F, I], (I, Condition[Exception]) => F[Unit])] = Ref[F].of(IMap.empty[I, Exception]) map { errors => val onChange: (I, Condition[Exception]) => F[Unit] = (i, c) => errors.update(_.alter(i, κ(Condition.optionIso.get(c)))) (new DefaultDatasourceErrors(errors), onChange) } }
slamdata/slamengine
impl/src/main/scala/quasar/impl/datasources/DefaultDatasourceErrors.scala
Scala
apache-2.0
1,742
/*********************************************************************** * Copyright (c) 2013-2018 Commonwealth Computer Research, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at * http://www.opensource.org/licenses/apache2.0.php. ***********************************************************************/ package org.locationtech.geomesa.utils.stats import java.util.Date import com.vividsolutions.jts.geom.Geometry import org.junit.runner.RunWith import org.locationtech.geomesa.utils.geotools.GeoToolsDateFormat import org.locationtech.geomesa.utils.text.WKTUtils import org.specs2.mutable.Specification import org.specs2.runner.JUnitRunner @RunWith(classOf[JUnitRunner]) class EnumerationStatTest extends Specification with StatTestHelper { def newStat[T](attribute: String, observe: Boolean = true): EnumerationStat[T] = { val stat = Stat(sft, s"Enumeration($attribute)") if (observe) { features.foreach { stat.observe } } stat.asInstanceOf[EnumerationStat[T]] } "Histogram stat" should { "work with strings" >> { "be empty initiallly" >> { val stat = newStat[String]("strAttr", observe = false) stat.property mustEqual "strAttr" stat.enumeration must beEmpty stat.isEmpty must beTrue } "observe correct values" >> { val stat = newStat[String]("strAttr") stat.enumeration must haveSize(100) forall(0 until 100)(i => stat.enumeration(f"abc$i%03d") mustEqual 1L) } "unobserve correct values" >> { val stat = newStat[String]("strAttr") stat.enumeration must haveSize(100) forall(0 until 100)(i => stat.enumeration(f"abc$i%03d") mustEqual 1L) features.take(10).foreach(stat.unobserve) stat.enumeration must haveSize(90) forall(0 until 10)(i => stat.enumeration(f"abc$i%03d") mustEqual 0L) forall(10 until 100)(i => stat.enumeration(f"abc$i%03d") mustEqual 1L) } "serialize to json" >> { val stat = newStat[String]("strAttr") val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked must beAnInstanceOf[EnumerationStat[String]] unpacked.asInstanceOf[EnumerationStat[String]].property mustEqual stat.property unpacked.asInstanceOf[EnumerationStat[String]].enumeration mustEqual stat.enumeration unpacked.asInstanceOf[EnumerationStat[String]].size mustEqual stat.size unpacked.asInstanceOf[EnumerationStat[String]].toJson mustEqual stat.toJson } "serialize empty to json" >> { val stat = newStat[String]("strAttr", observe = false) stat.toJson must beEqualTo("{ }").ignoreSpace } "serialize and deserialize" >> { val stat = newStat[String]("strAttr") val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked.toJson mustEqual stat.toJson } "serialize and deserialize empty stat" >> { val stat = newStat[String]("strAttr", observe = false) val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked.toJson mustEqual stat.toJson } "deserialize as immutable value" >> { val stat = newStat[String]("strAttr") val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed, immutable = true) unpacked.toJson mustEqual stat.toJson unpacked.clear must throwAn[Exception] unpacked.+=(stat) must throwAn[Exception] unpacked.observe(features.head) must throwAn[Exception] unpacked.unobserve(features.head) must throwAn[Exception] } "combine two states" >> { val stat = newStat[String]("strAttr") val stat2 = newStat[String]("strAttr", observe = false) features2.foreach { stat2.observe } stat2.enumeration must haveSize(100) forall(100 until 200)(i => stat2.enumeration(f"abc$i%03d") mustEqual 1L) stat += stat2 stat.enumeration must haveSize(200) forall(0 until 200)(i => stat.enumeration(f"abc$i%03d") mustEqual 1L) stat2.enumeration must haveSize(100) forall(100 until 200)(i => stat2.enumeration(f"abc$i%03d") mustEqual 1L) } "clear" >> { val stat = newStat[String]("strAttr") stat.isEmpty must beFalse stat.clear() stat.enumeration must beEmpty stat.isEmpty must beTrue } } "work with ints" >> { "be empty initiallly" >> { val stat = newStat[java.lang.Integer]("intAttr", observe = false) stat.property mustEqual "intAttr" stat.enumeration must beEmpty stat.isEmpty must beTrue } "observe correct values" >> { val stat = newStat[java.lang.Integer]("intAttr") forall(0 until 100)(i => stat.enumeration(i) mustEqual 1) } "serialize to json" >> { val stat = newStat[java.lang.Integer]("intAttr") val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked must beAnInstanceOf[EnumerationStat[java.lang.Integer]] unpacked.asInstanceOf[EnumerationStat[java.lang.Integer]].property mustEqual stat.property unpacked.asInstanceOf[EnumerationStat[java.lang.Integer]].enumeration mustEqual stat.enumeration unpacked.asInstanceOf[EnumerationStat[java.lang.Integer]].size mustEqual stat.size unpacked.asInstanceOf[EnumerationStat[java.lang.Integer]].toJson mustEqual stat.toJson } "serialize empty to json" >> { val stat = newStat[java.lang.Integer]("intAttr", observe = false) stat.toJson must beEqualTo("{ }").ignoreSpace } "serialize and deserialize" >> { val stat = newStat[java.lang.Integer]("intAttr") val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked.toJson mustEqual stat.toJson } "serialize and deserialize empty stat" >> { val stat = newStat[java.lang.Integer]("intAttr", observe = false) val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked.toJson mustEqual stat.toJson } "combine two stats" >> { val stat = newStat[java.lang.Integer]("intAttr") val stat2 = newStat[java.lang.Integer]("intAttr", observe = false) features2.foreach { stat2.observe } stat2.enumeration must haveSize(100) forall(100 until 200)(i => stat2.enumeration(i) mustEqual 1L) stat += stat2 stat.enumeration must haveSize(200) forall(0 until 200)(i => stat.enumeration(i) mustEqual 1L) stat2.enumeration must haveSize(100) forall(100 until 200)(i => stat2.enumeration(i) mustEqual 1L) } "clear" >> { val stat = newStat[java.lang.Integer]("intAttr") stat.isEmpty must beFalse stat.clear() stat.enumeration must beEmpty stat.isEmpty must beTrue } } "work with longs" >> { "be empty initiallly" >> { val stat = newStat[java.lang.Long]("longAttr", observe = false) stat.property mustEqual "longAttr" stat.enumeration must beEmpty stat.isEmpty must beTrue } "observe correct values" >> { val stat = newStat[java.lang.Long]("longAttr") forall(0 until 100)(i => stat.enumeration(i.toLong) mustEqual 1) } "serialize to json" >> { val stat = newStat[java.lang.Long]("longAttr") val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked must beAnInstanceOf[EnumerationStat[java.lang.Long]] unpacked.asInstanceOf[EnumerationStat[java.lang.Long]].property mustEqual stat.property unpacked.asInstanceOf[EnumerationStat[java.lang.Long]].enumeration mustEqual stat.enumeration unpacked.asInstanceOf[EnumerationStat[java.lang.Long]].size mustEqual stat.size unpacked.asInstanceOf[EnumerationStat[java.lang.Long]].toJson mustEqual stat.toJson } "serialize empty to json" >> { val stat = newStat[java.lang.Long]("longAttr", observe = false) stat.toJson must beEqualTo("{ }").ignoreSpace } "serialize and deserialize" >> { val stat = newStat[java.lang.Long]("longAttr") val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked.toJson mustEqual stat.toJson } "serialize and deserialize empty stat" >> { val stat = newStat[java.lang.Long]("longAttr", observe = false) val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked.toJson mustEqual stat.toJson } "combine two states" >> { val stat = newStat[java.lang.Long]("longAttr") val stat2 = newStat[java.lang.Long]("longAttr", observe = false) features2.foreach { stat2.observe } stat2.enumeration must haveSize(100) forall(100 until 200)(i => stat2.enumeration(i.toLong) mustEqual 1L) stat += stat2 stat.enumeration must haveSize(200) forall(0 until 200)(i => stat.enumeration(i.toLong) mustEqual 1L) stat2.enumeration must haveSize(100) forall(100 until 200)(i => stat2.enumeration(i.toLong) mustEqual 1L) } "clear" >> { val stat = newStat[java.lang.Long]("longAttr") stat.isEmpty must beFalse stat.clear() stat.enumeration must beEmpty stat.isEmpty must beTrue } } "work with floats" >> { "be empty initiallly" >> { val stat = newStat[java.lang.Float]("floatAttr", observe = false) stat.property mustEqual "floatAttr" stat.enumeration must beEmpty stat.isEmpty must beTrue } "observe correct values" >> { val stat = newStat[java.lang.Float]("floatAttr") forall(0 until 100)(i => stat.enumeration(i.toFloat) mustEqual 1) } "serialize to json" >> { val stat = newStat[java.lang.Float]("floatAttr") val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked must beAnInstanceOf[EnumerationStat[java.lang.Float]] unpacked.asInstanceOf[EnumerationStat[java.lang.Float]].property mustEqual stat.property unpacked.asInstanceOf[EnumerationStat[java.lang.Float]].enumeration mustEqual stat.enumeration unpacked.asInstanceOf[EnumerationStat[java.lang.Float]].size mustEqual stat.size unpacked.asInstanceOf[EnumerationStat[java.lang.Float]].toJson mustEqual stat.toJson } "serialize empty to json" >> { val stat = newStat[java.lang.Float]("floatAttr", observe = false) stat.toJson must beEqualTo("{ }").ignoreSpace } "serialize and deserialize" >> { val stat = newStat[java.lang.Float]("floatAttr") val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked.toJson mustEqual stat.toJson } "serialize and deserialize empty stat" >> { val stat = newStat[java.lang.Float]("floatAttr", observe = false) val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked.toJson mustEqual stat.toJson } "combine two states" >> { val stat = newStat[java.lang.Float]("floatAttr") val stat2 = newStat[java.lang.Float]("floatAttr", observe = false) features2.foreach { stat2.observe } stat2.enumeration must haveSize(100) forall(100 until 200)(i => stat2.enumeration(i.toFloat) mustEqual 1L) stat += stat2 stat.enumeration must haveSize(200) forall(0 until 200)(i => stat.enumeration(i.toFloat) mustEqual 1L) stat2.enumeration must haveSize(100) forall(100 until 200)(i => stat2.enumeration(i.toFloat) mustEqual 1L) } "clear" >> { val stat = newStat[java.lang.Float]("floatAttr") stat.isEmpty must beFalse stat.clear() stat.enumeration must beEmpty stat.isEmpty must beTrue } } "work with doubles" >> { "be empty initiallly" >> { val stat = newStat[java.lang.Double]("doubleAttr", observe = false) stat.property mustEqual "doubleAttr" stat.enumeration must beEmpty stat.isEmpty must beTrue } "observe correct values" >> { val stat = newStat[java.lang.Double]("doubleAttr") forall(0 until 100)(i => stat.enumeration(i.toDouble) mustEqual 1) } "serialize to json" >> { val stat = newStat[java.lang.Double]("doubleAttr") val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked must beAnInstanceOf[EnumerationStat[java.lang.Double]] unpacked.asInstanceOf[EnumerationStat[java.lang.Double]].property mustEqual stat.property unpacked.asInstanceOf[EnumerationStat[java.lang.Double]].enumeration mustEqual stat.enumeration unpacked.asInstanceOf[EnumerationStat[java.lang.Double]].size mustEqual stat.size unpacked.asInstanceOf[EnumerationStat[java.lang.Double]].toJson mustEqual stat.toJson } "serialize empty to json" >> { val stat = newStat[java.lang.Double]("doubleAttr", observe = false) stat.toJson must beEqualTo("{ }").ignoreSpace } "serialize and deserialize" >> { val stat = newStat[java.lang.Double]("doubleAttr") val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked.toJson mustEqual stat.toJson } "serialize and deserialize empty stat" >> { val stat = newStat[java.lang.Double]("doubleAttr", observe = false) val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked.toJson mustEqual stat.toJson } "combine two states" >> { val stat = newStat[java.lang.Double]("doubleAttr") val stat2 = newStat[java.lang.Double]("doubleAttr", observe = false) features2.foreach { stat2.observe } stat2.enumeration must haveSize(100) forall(100 until 200)(i => stat2.enumeration(i.toDouble) mustEqual 1L) stat += stat2 stat.enumeration must haveSize(200) forall(0 until 200)(i => stat.enumeration(i.toDouble) mustEqual 1L) stat2.enumeration must haveSize(100) forall(100 until 200)(i => stat2.enumeration(i.toDouble) mustEqual 1L) } "clear" >> { val stat = newStat[java.lang.Double]("doubleAttr") stat.isEmpty must beFalse stat.clear() stat.enumeration must beEmpty stat.isEmpty must beTrue } } "work with dates" >> { "be empty initiallly" >> { val stat = newStat[Date]("dtg", observe = false) stat.property mustEqual "dtg" stat.enumeration must beEmpty stat.isEmpty must beTrue } "observe correct values" >> { val stat = newStat[Date]("dtg") val dates = (0 until 24).map(i => java.util.Date.from(java.time.LocalDateTime.parse(f"2012-01-01T$i%02d:00:00.000Z", GeoToolsDateFormat).toInstant(java.time.ZoneOffset.UTC))) forall(dates.take(4))(d => stat.enumeration(d) mustEqual 5) forall(dates.drop(4))(d => stat.enumeration(d) mustEqual 4) } "serialize to json" >> { val stat = newStat[Date]("dtg") val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked must beAnInstanceOf[EnumerationStat[Date]] unpacked.asInstanceOf[EnumerationStat[Date]].property mustEqual stat.property unpacked.asInstanceOf[EnumerationStat[Date]].enumeration mustEqual stat.enumeration unpacked.asInstanceOf[EnumerationStat[Date]].size mustEqual stat.size unpacked.asInstanceOf[EnumerationStat[Date]].toJson mustEqual stat.toJson } "serialize empty to json" >> { val stat = newStat[Date]("dtg", observe = false) stat.toJson must beEqualTo("{ }").ignoreSpace } "serialize and deserialize" >> { val stat = newStat[Date]("dtg") val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked.toJson mustEqual stat.toJson } "serialize and deserialize empty stat" >> { val stat = newStat[Date]("dtg", observe = false) val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked.toJson mustEqual stat.toJson } "combine two states" >> { val stat = newStat[Date]("dtg") val stat2 = newStat[Date]("dtg", observe = false) features2.foreach { stat2.observe } val dates = (0 until 24).map(i => java.util.Date.from(java.time.LocalDateTime.parse(f"2012-01-01T$i%02d:00:00.000Z", GeoToolsDateFormat).toInstant(java.time.ZoneOffset.UTC))) val dates2 = (0 until 24).map(i => java.util.Date.from(java.time.LocalDateTime.parse(f"2012-01-02T$i%02d:00:00.000Z", GeoToolsDateFormat).toInstant(java.time.ZoneOffset.UTC))) stat2.enumeration must haveSize(24) forall(dates2.slice(4, 8))(d => stat2.enumeration(d) mustEqual 5) forall(dates2.take(4) ++ dates2.drop(8))(d => stat2.enumeration(d) mustEqual 4) stat += stat2 stat.enumeration must haveSize(48) forall(dates.take(4) ++ dates2.slice(4, 8))(d => stat.enumeration(d) mustEqual 5) forall(dates.drop(4) ++ dates2.take(4) ++ dates2.drop(8))(d => stat.enumeration(d) mustEqual 4) stat2.enumeration must haveSize(24) forall(dates2.slice(4, 8))(d => stat2.enumeration(d) mustEqual 5) forall(dates2.take(4) ++ dates2.drop(8))(d => stat2.enumeration(d) mustEqual 4) } "clear" >> { val stat = newStat[Date]("dtg") stat.isEmpty must beFalse stat.clear() stat.enumeration must beEmpty stat.isEmpty must beTrue } } "work with geometries" >> { "be empty initiallly" >> { val stat = newStat[Geometry]("geom", observe = false) stat.property mustEqual "geom" stat.enumeration must beEmpty stat.isEmpty must beTrue } "observe correct values" >> { val stat = newStat[Geometry]("geom") forall(0 until 100)(i => stat.enumeration(WKTUtils.read(s"POINT(-$i ${i / 2})")) mustEqual 1) } "serialize to json" >> { val stat = newStat[Geometry]("geom") val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked must beAnInstanceOf[EnumerationStat[Geometry]] unpacked.asInstanceOf[EnumerationStat[Geometry]].property mustEqual stat.property unpacked.asInstanceOf[EnumerationStat[Geometry]].enumeration mustEqual stat.enumeration unpacked.asInstanceOf[EnumerationStat[Geometry]].size mustEqual stat.size unpacked.asInstanceOf[EnumerationStat[Geometry]].toJson mustEqual stat.toJson } "serialize empty to json" >> { val stat = newStat[Geometry]("geom", observe = false) stat.toJson must beEqualTo("{ }").ignoreSpace } "serialize and deserialize" >> { val stat = newStat[Geometry]("geom") val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked.toJson mustEqual stat.toJson } "serialize and deserialize empty stat" >> { val stat = newStat[Geometry]("geom", observe = false) val packed = StatSerializer(sft).serialize(stat) val unpacked = StatSerializer(sft).deserialize(packed) unpacked.toJson mustEqual stat.toJson } "combine two states" >> { val stat = newStat[Geometry]("geom") val stat2 = newStat[Geometry]("geom", observe = false) features2.foreach { stat2.observe } stat2.enumeration must haveSize(100) forall(100 until 200)(i => stat2.enumeration(WKTUtils.read(s"POINT(${i -20} ${i / 2 - 20})")) mustEqual 1) stat += stat2 stat.enumeration must haveSize(200) forall(0 until 100)(i => stat.enumeration(WKTUtils.read(s"POINT(-$i ${i / 2})")) mustEqual 1) forall(100 until 200)(i => stat.enumeration(WKTUtils.read(s"POINT(${i -20} ${i / 2 - 20})")) mustEqual 1) stat2.enumeration must haveSize(100) forall(100 until 200)(i => stat2.enumeration(WKTUtils.read(s"POINT(${i -20} ${i / 2 - 20})")) mustEqual 1) } "clear" >> { val stat = newStat[Geometry]("geom") stat.isEmpty must beFalse stat.clear() stat.enumeration must beEmpty stat.isEmpty must beTrue } } } }
ddseapy/geomesa
geomesa-utils/src/test/scala/org/locationtech/geomesa/utils/stats/EnumerationStatTest.scala
Scala
apache-2.0
21,587
/* * 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.examples import java.io.File import org.apache.spark.sql.SparkSession import org.apache.carbondata.core.constants.CarbonCommonConstants import org.apache.carbondata.core.util.CarbonProperties import org.apache.carbondata.examples.util.ExampleUtils /** * This example is for showing how to use custom compaction to merge specified segments. */ object CustomCompactionExample { def main(args: Array[String]): Unit = { val spark = ExampleUtils.createSparkSession("CustomCompactionExample") exampleBody(spark) spark.close() } def exampleBody(spark : SparkSession): Unit = { CarbonProperties.getInstance() .addProperty(CarbonCommonConstants.CARBON_DATE_FORMAT, "yyyy/MM/dd") spark.sql("DROP TABLE IF EXISTS custom_compaction_table") spark.sql( s""" | CREATE TABLE IF NOT EXISTS custom_compaction_table( | ID Int, | date Date, | country String, | name String, | phonetype String, | serialname String, | salary Int, | floatField float | ) | STORED AS carbondata """.stripMargin) val rootPath = new File(this.getClass.getResource("/").getPath + "../../../..").getCanonicalPath val path = s"$rootPath/examples/spark/src/main/resources/dataSample.csv" // load 4 segments // scalastyle:off (1 to 4).foreach(_ => spark.sql( s""" | LOAD DATA LOCAL INPATH '$path' | INTO TABLE custom_compaction_table | OPTIONS('HEADER'='true') """.stripMargin)) // scalastyle:on // show all segment ids: 0,1,2,3 spark.sql("SHOW SEGMENTS FOR TABLE custom_compaction_table").show() // query data spark.sql("SELECT count(*) FROM custom_compaction_table").show() spark.sql("SELECT * FROM custom_compaction_table WHERE ID=5").show() // do custom compaction, segments specified will be merged spark.sql("ALTER TABLE custom_compaction_table COMPACT 'CUSTOM' WHERE SEGMENT.ID IN (1,2)") // show all segment ids after custom compaction spark.sql("SHOW SEGMENTS FOR TABLE custom_compaction_table").show() // query data again, results should be same spark.sql("SELECT count(*) FROM custom_compaction_table").show() spark.sql("SELECT * FROM custom_compaction_table WHERE ID=5").show() CarbonProperties.getInstance().addProperty( CarbonCommonConstants.CARBON_DATE_FORMAT, CarbonCommonConstants.CARBON_DATE_DEFAULT_FORMAT) // Drop table spark.sql("DROP TABLE IF EXISTS custom_compaction_table") } }
zzcclp/carbondata
examples/spark/src/main/scala/org/apache/carbondata/examples/CustomCompactionExample.scala
Scala
apache-2.0
3,417
final class A { private var x1 = false var x2 = false // manipulates private var @inline private def wrapper1[T](body: => T): T = { val saved = x1 x1 = true try body finally x1 = saved } // manipulates public var @inline private def wrapper2[T](body: => T): T = { val saved = x2 x2 = true try body finally x2 = saved } // not inlined def f1a() = wrapper1(5) // inlined! def f1b() = identity(wrapper1(5)) // not inlined def f2a() = wrapper2(5) // inlined! def f2b() = identity(wrapper2(5)) } object Test { def methodClasses = List("f1a", "f2a") map ("A$$anonfun$" + _ + "$1") def main(args: Array[String]): Unit = { val a = new A import a.* println(f1a() + f1b() + f2a() + f2b()) // Don't know how else to test this: all these should have been // inlined, so all should fail. methodClasses foreach { clazz => val foundClass = ( try Class.forName(clazz) catch { case _: Throwable => null } ) assert(foundClass == null, foundClass) } } }
dotty-staging/dotty
tests/pending/run/private-inline.scala
Scala
apache-2.0
1,078
/* * 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.ui.jobs import javax.servlet.http.HttpServletRequest import scala.xml.{Node, NodeSeq} import org.apache.spark.scheduler.Schedulable import org.apache.spark.ui.{WebUIPage, UIUtils} /** Page showing list of all ongoing and recently finished stages and pools */ private[ui] class JobProgressPage(parent: JobProgressTab) extends WebUIPage("") { private val appName = parent.appName private val basePath = parent.basePath private val live = parent.live private val sc = parent.sc private val listener = parent.listener private lazy val isFairScheduler = parent.isFairScheduler def render(request: HttpServletRequest): Seq[Node] = { listener.synchronized { val activeStages = listener.activeStages.values.toSeq val completedStages = listener.completedStages.reverse.toSeq val failedStages = listener.failedStages.reverse.toSeq val now = System.currentTimeMillis val activeStagesTable = new StageTableBase(activeStages.sortBy(_.submissionTime).reverse, parent, parent.killEnabled) val completedStagesTable = new StageTableBase(completedStages.sortBy(_.submissionTime).reverse, parent) val failedStagesTable = new FailedStageTable(failedStages.sortBy(_.submissionTime).reverse, parent) // For now, pool information is only accessible in live UIs val pools = if (live) sc.getAllPools else Seq[Schedulable]() val poolTable = new PoolTable(pools, parent) val summary: NodeSeq = <div> <ul class="unstyled"> {if (live) { // Total duration is not meaningful unless the UI is live <li> <strong>Total Duration: </strong> {UIUtils.formatDuration(now - sc.startTime)} </li> }} <li> <strong>Scheduling Mode: </strong> {listener.schedulingMode.map(_.toString).getOrElse("Unknown")} </li> <li> <a href="#active"><strong>Active Stages:</strong></a> {activeStages.size} </li> <li> <a href="#completed"><strong>Completed Stages:</strong></a> {completedStages.size} </li> <li> <a href="#failed"><strong>Failed Stages:</strong></a> {failedStages.size} </li> </ul> </div> val content = summary ++ {if (live && isFairScheduler) { <h4>{pools.size} Fair Scheduler Pools</h4> ++ poolTable.toNodeSeq } else { Seq[Node]() }} ++ <h4 id="active">Active Stages ({activeStages.size})</h4> ++ activeStagesTable.toNodeSeq ++ <h4 id="completed">Completed Stages ({completedStages.size})</h4> ++ completedStagesTable.toNodeSeq ++ <h4 id ="failed">Failed Stages ({failedStages.size})</h4> ++ failedStagesTable.toNodeSeq UIUtils.headerSparkPage(content, basePath, appName, "Spark Stages", parent.headerTabs, parent) } } }
zhangjunfang/eclipse-dir
spark/core/src/main/scala/org/apache/spark/ui/jobs/JobProgressPage.scala
Scala
bsd-2-clause
3,886
package immortan import java.util.concurrent.atomic.AtomicLong import akka.actor.{ActorRef, ActorSystem, PoisonPill, Props} import akka.util.Timeout import com.softwaremill.quicklens._ import fr.acinq.bitcoin.Crypto.{PrivateKey, PublicKey} import fr.acinq.bitcoin._ import fr.acinq.eclair.Features._ import fr.acinq.eclair._ import fr.acinq.eclair.blockchain.electrum._ import fr.acinq.eclair.blockchain.electrum.db.{CompleteChainWalletInfo, SigningWallet, WatchingWallet} import fr.acinq.eclair.channel.{ChannelKeys, LocalParams, PersistentChannelData} import fr.acinq.eclair.router.ChannelUpdateExt import fr.acinq.eclair.router.Router.{PublicChannel, RouterConf} import fr.acinq.eclair.transactions.{DirectedHtlc, RemoteFulfill} import fr.acinq.eclair.wire._ import immortan.SyncMaster.ShortChanIdSet import immortan.crypto.CanBeShutDown import immortan.crypto.Noise.KeyPair import immortan.crypto.Tools._ import immortan.sqlite._ import immortan.utils._ import scodec.bits.{ByteVector, HexStringSyntax} import scala.concurrent.duration._ import scala.concurrent.{Await, ExecutionContextExecutor} import scala.util.Try object LNParams { val blocksPerDay: Int = 144 // On average we can expect this many blocks per day val ncFulfillSafetyBlocks: Int = 36 // Force-close and redeem revealed incoming payment on chain if NC peer stalls state update and this many blocks are left until expiration val hcFulfillSafetyBlocks: Int = 72 // Offer to publish revealed incoming payment preimage on chain if HC peer stalls state update and this many blocks are left until expiration val cltvRejectThreshold: Int = hcFulfillSafetyBlocks + 36 // Reject incoming payment right away if CLTV expiry is closer than this to current chain tip when HTLC arrives val incomingFinalCltvExpiry: CltvExpiryDelta = CltvExpiryDelta(hcFulfillSafetyBlocks + 72) // Ask payer to set final CLTV expiry to current chain tip + this many blocks val failedChanRecoveryMsec: Double = 600000D // Failed-at-amount channels are fully recovered and their original capacity can be tried again after this much time val maxCltvExpiryDelta: CltvExpiryDelta = CltvExpiryDelta(2016) // A relative expiry of the whole route can not exceed this much blocks val maxToLocalDelay: CltvExpiryDelta = CltvExpiryDelta(2016) // We ask peer to delay their payment for this long in case of force-close val maxFundingSatoshis: Satoshi = Satoshi(10000000000L) // Proposed channels of capacity more than this are not allowed val maxReserveToFundingRatio: Double = 0.02 // % val maxNegotiationIterations: Int = 20 val maxChainConnectionsCount: Int = 3 val maxAcceptedHtlcs: Int = 483 val maxInChannelHtlcs: Int = 10 val maxHoldSecs: Long = 600L val maxOffChainFeeRatio: Double = 0.01 // We are OK with paying up to this % of LN fee relative to payment amount val maxOffChainFeeAboveRatio: MilliSatoshi = MilliSatoshi(10000L) // For small amounts we always accept fee up to this val shouldSendUpdateFeerateDiff = 5.0 val shouldRejectPaymentFeerateDiff = 20.0 val shouldForceClosePaymentFeerateDiff = 50.0 val ourRoutingCltvExpiryDelta: CltvExpiryDelta = CltvExpiryDelta(144 * 2) // We will reserve this many blocks for our incoming routed HTLC val minRoutingCltvExpiryDelta: CltvExpiryDelta = CltvExpiryDelta(144 * 3) // Ask relayer to set CLTV expiry delta to at least this many blocks val minInvoiceExpiryDelta: CltvExpiryDelta = CltvExpiryDelta(18) // If payee does not provide an explicit relative CLTV this is what we use by default val minForceClosableIncomingHtlcAmountToFeeRatio = 4 // When incoming HTLC gets (nearly) expired, how much higher than trim threshold should it be for us to force-close val minForceClosableOutgoingHtlcAmountToFeeRatio = 5 // When peer sends a suspiciously low feerate, how much higher than trim threshold should our outgoing HTLC be for us to force-close val minPayment: MilliSatoshi = MilliSatoshi(1000L) // We can neither send nor receive LN payments which are below this value val minChanDustLimit: Satoshi = Satoshi(354L) val minDepthBlocks: Int = 3 // Variables to be assigned at runtime var secret: WalletSecret = _ var chainHash: ByteVector32 = _ var chainWallets: WalletExt = _ var connectionProvider: ConnectionProvider = _ var logBag: SQLiteLog = _ var cm: ChannelMaster = _ var ourInit: Init = _ var routerConf: RouterConf = _ var syncParams: SyncParams = _ var fiatRates: FiatRates = _ var feeRates: FeeRates = _ var trampoline: TrampolineOn = TrampolineOn(minPayment, Long.MaxValue.msat, feeProportionalMillionths = 1000L, exponent = 0.0, logExponent = 0.0, minRoutingCltvExpiryDelta) val blockCount: AtomicLong = new AtomicLong(0L) def isOperational: Boolean = null != chainHash && null != secret && null != chainWallets && connectionProvider != null && null != syncParams && null != trampoline && null != fiatRates && null != feeRates && null != cm && null != cm.inProcessors && null != cm.sendTo && null != logBag && null != routerConf && null != ourInit implicit val timeout: Timeout = Timeout(30.seconds) implicit val system: ActorSystem = ActorSystem("immortan-actor-system") implicit val ec: ExecutionContextExecutor = scala.concurrent.ExecutionContext.Implicits.global def createInit: Init = { val networks: InitTlv = InitTlv.Networks(chainHash :: Nil) val tlvStream: TlvStream[InitTlv] = TlvStream(networks) Init(Features( (ChannelRangeQueries, FeatureSupport.Optional), (ChannelRangeQueriesExtended, FeatureSupport.Optional), (BasicMultiPartPayment, FeatureSupport.Optional), (OptionDataLossProtect, FeatureSupport.Optional), (VariableLengthOnion, FeatureSupport.Optional), (ShutdownAnySegwit, FeatureSupport.Optional), (StaticRemoteKey, FeatureSupport.Optional), (HostedChannels, FeatureSupport.Optional), (PaymentSecret, FeatureSupport.Optional), (ChainSwap, FeatureSupport.Optional), (Wumbo, FeatureSupport.Optional) ), tlvStream) } // We make sure force-close pays directly to our local wallet always def makeChannelParams(isFunder: Boolean, fundingAmount: Satoshi): LocalParams = { val walletPubKey = Await.result(chainWallets.lnWallet.getReceiveAddresses, atMost = 40.seconds).keys.head.publicKey makeChannelParams(Script.write(Script.pay2wpkh(walletPubKey).toList), walletPubKey, isFunder, fundingAmount) } // We make sure that funder and fundee key path end differently def makeChannelParams(defaultFinalScriptPubkey: ByteVector, walletStaticPaymentBasepoint: PublicKey, isFunder: Boolean, fundingAmount: Satoshi): LocalParams = makeChannelParams(defaultFinalScriptPubkey, walletStaticPaymentBasepoint, isFunder, ChannelKeys.newKeyPath(isFunder), fundingAmount) // Note: we set local maxHtlcValueInFlightMsat to channel capacity to simplify calculations def makeChannelParams(defFinalScriptPubkey: ByteVector, walletStaticPaymentBasepoint: PublicKey, isFunder: Boolean, keyPath: DeterministicWallet.KeyPath, fundingAmount: Satoshi): LocalParams = LocalParams(ChannelKeys.fromPath(secret.keys.master, keyPath), minChanDustLimit, UInt64(fundingAmount.toMilliSatoshi.toLong), channelReserve = (fundingAmount * 0.001).max(minChanDustLimit), minPayment, maxToLocalDelay, maxInChannelHtlcs, isFunder, defFinalScriptPubkey, walletStaticPaymentBasepoint) def currentBlockDay: Long = blockCount.get / blocksPerDay def isPeerSupports(theirInit: Init)(feature: Feature): Boolean = Features.canUseFeature(ourInit.features, theirInit.features, feature) def loggedActor(childProps: Props, childName: String): ActorRef = system actorOf Props(classOf[LoggingSupervisor], childProps, childName) def addressToPubKeyScript(address: String): ByteVector = Script write addressToPublicKeyScript(address, chainHash) def isMainnet: Boolean = chainHash == Block.LivenetGenesisBlock.hash } case class WalletExt(wallets: List[ElectrumEclairWallet], catcher: ActorRef, sync: ActorRef, pool: ActorRef, watcher: ActorRef, params: WalletParameters) extends CanBeShutDown { me => lazy val lnWallet: ElectrumEclairWallet = wallets.find(_.isBuiltIn).get lazy val usableWallets: List[ElectrumEclairWallet] = wallets.filter(wallet => wallet.isBuiltIn || wallet.hasFingerprint) def findByPubKey(pub: PublicKey): Option[ElectrumEclairWallet] = wallets.find(_.ewt.xPub.publicKey == pub) def makeSigningWalletParts(core: SigningWallet, lastBalance: Satoshi, label: String): ElectrumEclairWallet = { val ewt = ElectrumWalletType.makeSigningType(tag = core.walletType, master = LNParams.secret.keys.master, chainHash = LNParams.chainHash) val walletRef = LNParams.loggedActor(Props(classOf[ElectrumWallet], pool, sync, params, ewt), core.walletType + "-signing-wallet") val infoNoPersistent = CompleteChainWalletInfo(core, data = ByteVector.empty, lastBalance, label, isCoinControlOn = false) ElectrumEclairWallet(walletRef, ewt, infoNoPersistent) } def makeWatchingWallet84Parts(core: WatchingWallet, lastBalance: Satoshi, label: String): ElectrumEclairWallet = { val ewt: ElectrumWallet84 = new ElectrumWallet84(secrets = None, xPub = core.xPub, chainHash = LNParams.chainHash) val walletRef = LNParams.loggedActor(Props(classOf[ElectrumWallet], pool, sync, params, ewt), core.walletType + "-watching-wallet") val infoNoPersistent = CompleteChainWalletInfo(core, data = ByteVector.empty, lastBalance, label, isCoinControlOn = false) ElectrumEclairWallet(walletRef, ewt, infoNoPersistent) } def withFreshWallet(eclairWallet: ElectrumEclairWallet): WalletExt = { params.walletDb.addChainWallet(eclairWallet.info, params.emptyPersistentDataBytes, eclairWallet.ewt.xPub.publicKey) eclairWallet.walletRef ! params.emptyPersistentDataBytes sync ! ElectrumWallet.ChainFor(eclairWallet.walletRef) copy(wallets = eclairWallet :: wallets) } def withoutWallet(wallet: ElectrumEclairWallet): WalletExt = { require(wallet.info.core.isRemovable, "Wallet is not removable") params.walletDb.remove(pub = wallet.ewt.xPub.publicKey) params.txDb.removeByPub(xPub = wallet.ewt.xPub) val wallets1 = wallets diff List(wallet) wallet.walletRef ! PoisonPill copy(wallets = wallets1) } def withNewLabel(label: String)(wallet1: ElectrumEclairWallet): WalletExt = { require(!wallet1.isBuiltIn, "Can not re-label a default built in chain wallet") def sameXPub(wallet: ElectrumEclairWallet): Boolean = wallet.ewt.xPub == wallet1.ewt.xPub params.walletDb.updateLabel(label, pub = wallet1.ewt.xPub.publicKey) me.modify(_.wallets.eachWhere(sameXPub).info.label).setTo(label) } override def becomeShutDown: Unit = { val actors = List(catcher, sync, pool, watcher) val allActors = wallets.map(_.walletRef) ++ actors allActors.foreach(_ ! PoisonPill) } } class SyncParams { val satm: RemoteNodeInfo = RemoteNodeInfo(PublicKey(hex"02cd1b7bc418fac2dc99f0ba350d60fa6c45fde5ab6017ee14df6425df485fb1dd"), NodeAddress.unresolved(80, host = 134, 209, 228, 207), "SATM") val motherbase: RemoteNodeInfo = RemoteNodeInfo(PublicKey(hex"021e7ea08e31a576b4fd242761d701452a8ac98113eac3074c153db85d2dcc7d27"), NodeAddress.unresolved(9001, host = 5, 9, 83, 143), "Motherbase") val bCashIsTrash: RemoteNodeInfo = RemoteNodeInfo(PublicKey(hex"0298f6074a454a1f5345cb2a7c6f9fce206cd0bf675d177cdbf0ca7508dd28852f"), NodeAddress.unresolved(9735, host = 73, 119, 255, 56), "bCashIsTrash") val ergveinNet: RemoteNodeInfo = RemoteNodeInfo(PublicKey(hex"034a7b1ac1239ff2ac8438ce0a7ade1048514b77d4322f514e96918e6c13944861"), NodeAddress.unresolved(9735, host = 188, 244, 4, 78), "ergvein.net") val conductor: RemoteNodeInfo = RemoteNodeInfo(PublicKey(hex"03c436af41160a355fc1ed230a64f6a64bcbd2ae50f12171d1318f9782602be601"), NodeAddress.unresolved(9735, host = 18, 191, 89, 219), "Conductor") val lntxbot1: RemoteNodeInfo = RemoteNodeInfo(PublicKey(hex"03ee58475055820fbfa52e356a8920f62f8316129c39369dbdde3e5d0198a9e315"), NodeAddress.unresolved(9734, host = 198, 251, 89, 159), "LNTXBOT-E") val silentBob: RemoteNodeInfo = RemoteNodeInfo(PublicKey(hex"02e9046555a9665145b0dbd7f135744598418df7d61d3660659641886ef1274844"), NodeAddress.unresolved(9735, host = 31, 16, 52, 37), "SilentBob") val lightning: RemoteNodeInfo = RemoteNodeInfo(PublicKey(hex"03baa70886d9200af0ffbd3f9e18d96008331c858456b16e3a9b41e735c6208fef"), NodeAddress.unresolved(9735, host = 45, 20, 67, 1), "LIGHTNING") val acinq: RemoteNodeInfo = RemoteNodeInfo(PublicKey(hex"03864ef025fde8fb587d989186ce6a4a186895ee44a926bfc370e2c366597a3f8f"), NodeAddress.unresolved(9735, host = 34, 239, 230, 56), "ACINQ") val syncNodes: Set[RemoteNodeInfo] = Set(satm, motherbase, bCashIsTrash, ergveinNet, conductor, silentBob, lightning, acinq) val phcSyncNodes: Set[RemoteNodeInfo] = Set(satm, motherbase, lntxbot1) val maxPHCCapacity: MilliSatoshi = MilliSatoshi(100000000000000L) // PHC can not be larger than 1000 BTC val minPHCCapacity: MilliSatoshi = MilliSatoshi(1000000000L) // PHC can not be smaller than 0.01 BTC val minNormalChansForPHC = 5 // How many normal chans a node must have to be eligible for PHCs val maxPHCPerNode = 3 // How many PHCs a node can have in total val minCapacity: MilliSatoshi = MilliSatoshi(750000000L) // 750k sat val maxNodesToSyncFrom = 1 // How many disjoint peers to use for majority sync val acceptThreshold = 0 // ShortIds and updates are accepted if confirmed by more than this peers val messagesToAsk = 400 // Ask for this many messages from peer before they say this chunk is done val chunksToWait = 4 // Wait for at least this much chunk iterations from any peer before recording results } class TestNetSyncParams extends SyncParams { val sbw: RemoteNodeInfo = RemoteNodeInfo(PublicKey(hex"03b8534f2d84de39a68d1359f6833fde819b731e188ddf633a666f7bf8c1d7650a"), NodeAddress.unresolved(9735, host = 45, 61, 187, 156), "SBW") val endurance: RemoteNodeInfo = RemoteNodeInfo(PublicKey(hex"03933884aaf1d6b108397e5efe5c86bcf2d8ca8d2f700eda99db9214fc2712b134"), NodeAddress.unresolved(9735, host = 76, 223, 71, 211), "Endurance") val localhost: RemoteNodeInfo = RemoteNodeInfo(PublicKey(hex"038d5cdea665f68e597da00ae0612238bd30a06bdf08d34fa9af783b1f1b3ba9b7"), NodeAddress.unresolved(9735, host = 10, 0, 2, 2), "localhost") override val syncNodes: Set[RemoteNodeInfo] = Set(endurance, localhost, sbw) override val phcSyncNodes: Set[RemoteNodeInfo] = Set(localhost, sbw) override val minCapacity: MilliSatoshi = MilliSatoshi(100000000L) override val minNormalChansForPHC = 1 override val maxNodesToSyncFrom = 1 override val acceptThreshold = 0 } // Important: LNParams.secret must be defined case class RemoteNodeInfo(nodeId: PublicKey, address: NodeAddress, alias: String) { lazy val nodeSpecificExtendedKey: DeterministicWallet.ExtendedPrivateKey = LNParams.secret.keys.ourFakeNodeIdKey(nodeId) lazy val nodeSpecificPair: KeyPairAndPubKey = KeyPairAndPubKey(KeyPair(nodeSpecificPubKey.value, nodeSpecificPrivKey.value), nodeId) lazy val nodeSpecificPrivKey: PrivateKey = nodeSpecificExtendedKey.privateKey lazy val nodeSpecificPubKey: PublicKey = nodeSpecificPrivKey.publicKey def safeAlias: RemoteNodeInfo = copy(alias = alias take 24) } case class WalletSecret(keys: LightningNodeKeys, mnemonic: List[String], seed: ByteVector) case class UpdateAddHtlcExt(theirAdd: UpdateAddHtlc, remoteInfo: RemoteNodeInfo) case class SwapInStateExt(state: SwapInState, nodeId: PublicKey) // Interfaces trait NetworkBag { def addChannelAnnouncement(ca: ChannelAnnouncement, newSqlPQ: PreparedQuery) def addChannelUpdateByPosition(cu: ChannelUpdate, newSqlPQ: PreparedQuery, updSqlPQ: PreparedQuery) // When adding an excluded channel we disregard an update position: channel as a whole is always excluded def addExcludedChannel(shortId: Long, untilStamp: Long, newSqlPQ: PreparedQuery) def removeChannelUpdate(shortId: Long, killSqlPQ: PreparedQuery) def addChannelUpdateByPosition(cu: ChannelUpdate) def removeChannelUpdate(shortId: Long) def listChannelAnnouncements: Iterable[ChannelAnnouncement] def listChannelUpdates: Iterable[ChannelUpdateExt] def listChannelsWithOneUpdate: ShortChanIdSet def listExcludedChannels: Set[Long] def incrementScore(cu: ChannelUpdateExt) def getRoutingData: Map[Long, PublicChannel] def removeGhostChannels(ghostIds: ShortChanIdSet, oneSideIds: ShortChanIdSet) def processCompleteHostedData(pure: CompleteHostedRoutingData) def processPureData(data: PureRoutingData) } // Bag of stored payments and successful relays trait PaymentBag { def getPreimage(hash: ByteVector32): Try[ByteVector32] def setPreimage(paymentHash: ByteVector32, preimage: ByteVector32) def addRelayedPreimageInfo(fullTag: FullPaymentTag, preimage: ByteVector32, relayed: MilliSatoshi, earned: MilliSatoshi) def addSearchablePayment(search: String, paymentHash: ByteVector32) def searchPayments(rawSearchQuery: String): RichCursor def replaceOutgoingPayment(prex: PaymentRequestExt, description: PaymentDescription, action: Option[PaymentAction], finalAmount: MilliSatoshi, balanceSnap: MilliSatoshi, fiatRateSnap: Fiat2Btc, chainFee: MilliSatoshi, seenAt: Long) def replaceIncomingPayment(prex: PaymentRequestExt, preimage: ByteVector32, description: PaymentDescription, balanceSnap: MilliSatoshi, fiatRateSnap: Fiat2Btc) def getPaymentInfo(paymentHash: ByteVector32): Try[PaymentInfo] def removePaymentInfo(paymentHash: ByteVector32) def updDescription(description: PaymentDescription, paymentHash: ByteVector32) def updOkIncoming(receivedAmount: MilliSatoshi, paymentHash: ByteVector32) def updOkOutgoing(fulfill: RemoteFulfill, fee: MilliSatoshi) def updAbortedOutgoing(paymentHash: ByteVector32) def listRecentRelays(limit: Int): RichCursor def listRecentPayments(limit: Int): RichCursor def listPendingSecrets: Iterable[ByteVector32] def paymentSummary: Try[PaymentSummary] def relaySummary: Try[RelaySummary] def toRelayedPreimageInfo(rc: RichCursor): RelayedPreimageInfo def toPaymentInfo(rc: RichCursor): PaymentInfo } trait DataBag { def putSecret(secret: WalletSecret) def tryGetSecret: Try[WalletSecret] def putFiatRatesInfo(data: FiatRatesInfo) def tryGetFiatRatesInfo: Try[FiatRatesInfo] def putFeeRatesInfo(data: FeeRatesInfo) def tryGetFeeRatesInfo: Try[FeeRatesInfo] def putReport(paymentHash: ByteVector32, report: String) def tryGetReport(paymentHash: ByteVector32): Try[String] def putBranding(nodeId: PublicKey, branding: HostedChannelBranding) def tryGetBranding(nodeId: PublicKey): Try[HostedChannelBranding] def putSwapInState(nodeId: PublicKey, state: SwapInState) def tryGetSwapInState(nodeId: PublicKey): Try[SwapInStateExt] } object ChannelBag { case class Hash160AndCltv(hash160: ByteVector, cltvExpiry: CltvExpiry) } trait ChannelBag { val db: DBInterface def all: Iterable[PersistentChannelData] def put(data: PersistentChannelData): PersistentChannelData def delete(channelId: ByteVector32) def htlcInfos(commitNumer: Long): Iterable[ChannelBag.Hash160AndCltv] def putHtlcInfo(sid: Long, commitNumber: Long, paymentHash: ByteVector32, cltvExpiry: CltvExpiry) def putHtlcInfos(htlcs: Seq[DirectedHtlc], sid: Long, commitNumber: Long) def rmHtlcInfos(sid: Long) def channelTxFeesSummary: Try[ChannelTxFeesSummary] def addChannelTxFee(feePaid: Satoshi, idenitifer: String, tag: String) }
btcontract/wallet
app/src/main/java/immortan/LNParams.scala
Scala
apache-2.0
19,625
package Impl import akka.actor.ActorSystem import akka.actor.Props import akka.actor.actorRef2Scala import java.util.logging.SimpleFormatter import java.util.logging.FileHandler import java.util.logging.Logger /** * I make this main class to test the paxos behavior, once users run this class, it set up a * paxos server with a selected id. In this example, I assume there are 5 replicated machiness * within a system, the information of the replicated machiens is in the paxos.config. I am using * host name '127.0.0.1' for each node. users should run at least 3 nodes with ids among 1-5 to * be able to propose a value. * At the same time, users can use this main class as a client to ask each existing paxos to propose * a value by simply run command 'propose' from the console. * * @author zepeng zhao */ object Main extends App{ override def main(args:Array[String]){ var logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) logger.setUseParentHandlers(false); var fileTxt = new FileHandler("log_3.txt"); var formatterTxt = new SimpleFormatter(); fileTxt.setFormatter(formatterTxt); logger.addHandler(fileTxt); val system = ActorSystem("RemoteSystem") var id = -1 try{ var m = Util.loadPaxos() while(id < 0){ try{ print("Select node id:") id = readLine().toInt if(!(id > 0 && id <=m.size)){ println("id should be a number between 1 and " +m.size) id = -1 } } catch{ case e:Exception => println("nid should be a number between 1 and " +m.size); id = -1 } } var master = system.actorOf(Props(classOf[Paxos_Actor],m,id), "Paxos") while(true){ print("->") var command = readLine() if(command.equals("propose")){ print("value:") var v = readLine().asInstanceOf[java.io.Serializable] print("node:") try{ var nid = readLine().toInt if(nid > 0 && nid <=m.size) master ! propose(v,nid) else println("nid should be a number between 1 and " +m.size) }catch{ case e:Exception => println("nid should be a number between 1 and " +m.size) } } } } catch{ case e:Exception => println(e.getMessage) } } }
allenfromu/Single-Decree-Paxos
src/main/scala/Impl/Main.scala
Scala
mit
2,438
package im.actor.server.util import scala.concurrent.ExecutionContext import slick.dbio.Effect.Read import slick.dbio.{ DBIO, DBIOAction, NoStream } import im.actor.api.rpc.AuthorizedClientData import im.actor.api.rpc.groups.{ Group, Member } import im.actor.api.rpc.pubgroups.PublicGroup import im.actor.server.{ models, persist } object GroupUtils { import ImageUtils._ private def getGroupStructOption(groupId: Int, senderUserId: Int)(implicit ec: ExecutionContext): DBIOAction[Option[Group], NoStream, Read with Read] = { persist.Group.find(groupId) flatMap { case Some(group) ⇒ getGroupStructUnsafe(group, senderUserId).map(Some(_)) case None ⇒ DBIO.successful(None) } } private def getGroupStructOption(groupId: Int)(implicit clientData: AuthorizedClientData, ec: ExecutionContext): DBIOAction[Option[Group], NoStream, Read with Read] = { getGroupStructOption(groupId, clientData.userId) } def getGroupStructUnsafe(group: models.Group, senderUserId: Int)(implicit ec: ExecutionContext): DBIOAction[Group, NoStream, Read with Read] = { for { groupUsers ← persist.GroupUser.find(group.id) isMember ← DBIO.successful(groupUsers.map(_.userId).contains(senderUserId)) groupAvatarModelOpt ← persist.AvatarData.findByGroupId(group.id) } yield { val (userIds, members) = if (isMember) { groupUsers.foldLeft(Vector.empty[Int], Vector.empty[Member]) { case ((userIdsAcc, membersAcc), groupUser) ⇒ val member = Member(groupUser.userId, groupUser.inviterUserId, groupUser.invitedAt.getMillis) (userIdsAcc :+ groupUser.userId, membersAcc :+ member) } } else (Vector.empty[Int], Vector.empty[Member]) Group(group.id, group.accessHash, group.title, groupAvatarModelOpt map getAvatar, isMember, group.creatorUserId, members, group.createdAt.getMillis) } } def getPubgroupStructUnsafe(group: models.Group, senderUserId: Int)(implicit ec: ExecutionContext): DBIOAction[PublicGroup, NoStream, Read with Read] = { for { membersIds ← persist.GroupUser.findUserIds(group.id) userContactsIds ← persist.contact.UserContact.findNotDeletedIds(senderUserId) friendsCount = (membersIds intersect userContactsIds).length groupAvatarModelOpt ← persist.AvatarData.findByGroupId(group.id) } yield { PublicGroup(group.id, group.accessHash, group.title, membersIds.length, friendsCount, group.description, groupAvatarModelOpt map getAvatar) } } def getGroupStructUnsafe(group: models.Group)(implicit clientData: AuthorizedClientData, ec: ExecutionContext): DBIOAction[Group, NoStream, Read with Read] = { getGroupStructUnsafe(group, clientData.userId) } def getPubgroupStructUnsafe(group: models.Group)(implicit clientData: AuthorizedClientData, ec: ExecutionContext): DBIOAction[PublicGroup, NoStream, Read with Read] = { getPubgroupStructUnsafe(group, clientData.userId) } // TODO: #perf eliminate lots of sql queries def getGroupsStructs(groupIds: Set[Int])(implicit clientData: AuthorizedClientData, ec: ExecutionContext): DBIOAction[Seq[Group], NoStream, Read with Read] = { DBIO.sequence(groupIds.toSeq map getGroupStructOption) map (_.flatten) } def getGroupStructs(groupIds: Set[Int], senderUserId: Int)(implicit ec: ExecutionContext) = { DBIO.sequence(groupIds.toSeq map (getGroupStructOption(_, senderUserId))) map (_.flatten) } def withGroup[A](groupId: Int)(f: models.Group ⇒ DBIO[A])(implicit ec: ExecutionContext): DBIO[A] = { persist.Group.find(groupId) flatMap { case Some(group) ⇒ f(group) case None ⇒ DBIO.failed(new Exception(s"Group ${groupId} not found")) } } def withGroupUserIds[A](groupId: Int)(f: Seq[Int] ⇒ DBIO[A])(implicit ec: ExecutionContext): DBIO[A] = { persist.GroupUser.findUserIds(groupId) flatMap f } }
zomeelee/actor-platform
actor-server/actor-utils/src/main/scala/im/actor/server/util/GroupUtils.scala
Scala
mit
3,935
package dotty.tools package dotc package typer import core._ import ast._ import Trees._, Constants._, StdNames._, Scopes._, Denotations._ import Contexts._, Symbols._, Types._, SymDenotations._, Names._, NameOps._, Flags._, Decorators._ import ast.desugar, ast.desugar._ import ProtoTypes._ import util.Positions._ import util.{Attachment, SourcePosition, DotClass} import collection.mutable import annotation.tailrec import ErrorReporting._ import tpd.ListOfTreeDecorator import config.Printers._ import Annotations._ import transform.ValueClasses._ import language.implicitConversions trait NamerContextOps { this: Context => /** Enter symbol into current class, if current class is owner of current context, * or into current scope, if not. Should always be called instead of scope.enter * in order to make sure that updates to class members are reflected in * finger prints. */ def enter(sym: Symbol): Symbol = { ctx.owner match { case cls: ClassSymbol => cls.enter(sym) case _ => this.scope.openForMutations.enter(sym) } sym } /** The denotation with the given name in current context */ def denotNamed(name: Name): Denotation = if (owner.isClass) if (outer.owner == owner) { // inner class scope; check whether we are referring to self if (scope.size == 1) { val elem = scope.lastEntry if (elem.name == name) return elem.sym.denot // return self } assert(scope.size <= 1, scope) owner.thisType.member(name) } else // we are in the outermost context belonging to a class; self is invisible here. See inClassContext. owner.findMember(name, owner.thisType, EmptyFlags) else scope.denotsNamed(name).toDenot(NoPrefix) /** Either the current scope, or, if the current context owner is a class, * the declarations of the current class. */ def effectiveScope: Scope = if (owner != null && owner.isClass) owner.asClass.unforcedDecls else scope /** The symbol (stored in some typer's symTree) of an enclosing context definition */ def symOfContextTree(tree: untpd.Tree) = { def go(ctx: Context): Symbol = { ctx.typeAssigner match { case typer: Typer => tree.getAttachment(typer.SymOfTree) match { case Some(sym) => sym case None => var cx = ctx.outer while (cx.typeAssigner eq typer) cx = cx.outer go(cx) } case _ => NoSymbol } } go(this) } /** Context where `sym` is defined, assuming we are in a nested context. */ def defContext(sym: Symbol) = outersIterator .dropWhile(_.owner != sym) .dropWhile(_.owner == sym) .next /** The given type, unless `sym` is a constructor, in which case the * type of the constructed instance is returned */ def effectiveResultType(sym: Symbol, typeParams: List[Symbol], given: Type) = if (sym.name == nme.CONSTRUCTOR) sym.owner.typeRef.appliedTo(typeParams map (_.typeRef)) else given /** if isConstructor, make sure it has one non-implicit parameter list */ def normalizeIfConstructor(paramSymss: List[List[Symbol]], isConstructor: Boolean) = if (isConstructor && (paramSymss.isEmpty || paramSymss.head.nonEmpty && (paramSymss.head.head is Implicit))) Nil :: paramSymss else paramSymss /** The method type corresponding to given parameters and result type */ def methodType(typeParams: List[Symbol], valueParamss: List[List[Symbol]], resultType: Type, isJava: Boolean = false)(implicit ctx: Context): Type = { val monotpe = (valueParamss :\\ resultType) { (params, resultType) => val make = if (params.nonEmpty && (params.head is Implicit)) ImplicitMethodType else if (isJava) JavaMethodType else MethodType if (isJava) for (param <- params) if (param.info.isDirectRef(defn.ObjectClass)) param.info = defn.AnyType make.fromSymbols(params, resultType) } if (typeParams.nonEmpty) PolyType.fromSymbols(typeParams, monotpe) else if (valueParamss.isEmpty) ExprType(monotpe) else monotpe } /** Find moduleClass/sourceModule in effective scope */ private def findModuleBuddy(name: Name)(implicit ctx: Context) = { val scope = effectiveScope val it = scope.lookupAll(name).filter(_ is Module) assert(it.hasNext, s"no companion $name in $scope") it.next } /** Add moduleClass or sourceModule functionality to completer * for a module or module class */ def adjustModuleCompleter(completer: LazyType, name: Name) = if (name.isTermName) completer withModuleClass (_ => findModuleBuddy(name.moduleClassName)) else completer withSourceModule (_ => findModuleBuddy(name.sourceModuleName)) } /** This class creates symbols from definitions and imports and gives them * lazy types. * * Timeline: * * During enter, trees are expanded as necessary, populating the expandedTree map. * Symbols are created, and the symOfTree map is set up. * * Symbol completion causes some trees to be already typechecked and typedTree * entries are created to associate the typed trees with the untyped expanded originals. * * During typer, original trees are first expanded using expandedTree. For each * expanded member definition or import we extract and remove the corresponding symbol * from the symOfTree map and complete it. We then consult the typedTree map to see * whether a typed tree exists already. If yes, the typed tree is returned as result. * Otherwise, we proceed with regular type checking. * * The scheme is designed to allow sharing of nodes, as long as each duplicate appears * in a different method. */ class Namer { typer: Typer => import untpd._ val TypedAhead = new Attachment.Key[tpd.Tree] val ExpandedTree = new Attachment.Key[Tree] val SymOfTree = new Attachment.Key[Symbol] /** A partial map from unexpanded member and pattern defs and to their expansions. * Populated during enterSyms, emptied during typer. */ //lazy val expandedTree = new mutable.AnyRefMap[DefTree, Tree] /*{ override def default(tree: DefTree) = tree // can't have defaults on AnyRefMaps :-( }*/ /** A map from expanded MemberDef, PatDef or Import trees to their symbols. * Populated during enterSyms, emptied at the point a typed tree * with the same symbol is created (this can be when the symbol is completed * or at the latest when the tree is typechecked. */ //lazy val symOfTree = new mutable.AnyRefMap[Tree, Symbol] /** A map from expanded trees to their typed versions. * Populated when trees are typechecked during completion (using method typedAhead). */ // lazy val typedTree = new mutable.AnyRefMap[Tree, tpd.Tree] /** A map from method symbols to nested typers. * Populated when methods are completed. Emptied when they are typechecked. * The nested typer contains new versions of the four maps above including this * one, so that trees that are shared between different DefDefs can be independently * used as indices. It also contains a scope that contains nested parameters. */ lazy val nestedTyper = new mutable.AnyRefMap[Symbol, Typer] /** The scope of the typer. * For nested typers this is a place parameters are entered during completion * and where they survive until typechecking. A context with this typer also * has this scope. */ val scope = newScope /** The symbol of the given expanded tree. */ def symbolOfTree(tree: Tree)(implicit ctx: Context): Symbol = { val xtree = expanded(tree) xtree.getAttachment(TypedAhead) match { case Some(ttree) => ttree.symbol case none => xtree.attachment(SymOfTree) } } /** The enclosing class with given name; error if none exists */ def enclosingClassNamed(name: TypeName, pos: Position)(implicit ctx: Context): Symbol = { if (name.isEmpty) NoSymbol else { val cls = ctx.owner.enclosingClassNamed(name) if (!cls.exists) ctx.error(s"no enclosing class or object is named $name", pos) cls } } /** If this tree is a member def or an import, create a symbol of it * and store in symOfTree map. */ def createSymbol(tree: Tree)(implicit ctx: Context): Symbol = { def privateWithinClass(mods: Modifiers) = enclosingClassNamed(mods.privateWithin, mods.pos) def record(sym: Symbol): Symbol = { val refs = tree.attachmentOrElse(References, Nil) if (refs.nonEmpty) { tree.removeAttachment(References) refs foreach (_.pushAttachment(OriginalSymbol, sym)) } tree.pushAttachment(SymOfTree, sym) sym } /** Add moduleClass/sourceModule to completer if it is for a module val or class */ def adjustIfModule(completer: LazyType, tree: MemberDef) = if (tree.mods is Module) ctx.adjustModuleCompleter(completer, tree.name.encode) else completer typr.println(i"creating symbol for $tree in ${ctx.mode}") def checkNoConflict(name: Name): Name = { def errorName(msg: => String) = { ctx.error(msg, tree.pos) name.freshened } def preExisting = ctx.effectiveScope.lookup(name) if (ctx.owner is PackageClass) if (preExisting.isDefinedInCurrentRun) errorName(s"${preExisting.showLocated} is compiled twice") else name else if ((!ctx.owner.isClass || name.isTypeName) && preExisting.exists) errorName(i"$name is already defined as $preExisting") else name } val inSuperCall = if (ctx.mode is Mode.InSuperCall) InSuperCall else EmptyFlags tree match { case tree: TypeDef if tree.isClassDef => val name = checkNoConflict(tree.name.encode).asTypeName val cls = record(ctx.newClassSymbol( ctx.owner, name, tree.mods.flags | inSuperCall, cls => adjustIfModule(new ClassCompleter(cls, tree)(ctx), tree), privateWithinClass(tree.mods), tree.pos, ctx.source.file)) cls.completer.asInstanceOf[ClassCompleter].init() cls case tree: MemberDef => val name = checkNoConflict(tree.name.encode) val isDeferred = lacksDefinition(tree) val deferred = if (isDeferred) Deferred else EmptyFlags val method = if (tree.isInstanceOf[DefDef]) Method else EmptyFlags val inSuperCall1 = if (tree.mods is ParamOrAccessor) EmptyFlags else inSuperCall // suppress inSuperCall for constructor parameters val higherKinded = tree match { case tree: TypeDef if tree.tparams.nonEmpty && isDeferred => HigherKinded case _ => EmptyFlags } // to complete a constructor, move one context further out -- this // is the context enclosing the class. Note that the context in which a // constructor is recorded and the context in which it is completed are // different: The former must have the class as owner (because the // constructor is owned by the class), the latter must not (because // constructor parameters are interpreted as if they are outside the class). // Don't do this for Java constructors because they need to see the import // of the companion object, and it is not necessary for them because they // have no implementation. val cctx = if (tree.name == nme.CONSTRUCTOR && !(tree.mods is JavaDefined)) ctx.outer else ctx record(ctx.newSymbol( ctx.owner, name, tree.mods.flags | deferred | method | higherKinded | inSuperCall1, adjustIfModule(new Completer(tree)(cctx), tree), privateWithinClass(tree.mods), tree.pos)) case tree: Import => record(ctx.newSymbol( ctx.owner, nme.IMPORT, Synthetic, new Completer(tree), NoSymbol, tree.pos)) case _ => NoSymbol } } /** If `sym` exists, enter it in effective scope. Check that * package members are not entered twice in the same run. */ def enterSymbol(sym: Symbol)(implicit ctx: Context) = { if (sym.exists) { typr.println(s"entered: $sym in ${ctx.owner} and ${ctx.effectiveScope}") ctx.enter(sym) } sym } /** Create package if it does not yet exist. */ private def createPackageSymbol(pid: RefTree)(implicit ctx: Context): Symbol = { val pkgOwner = pid match { case Ident(_) => if (ctx.owner eq defn.EmptyPackageClass) defn.RootClass else ctx.owner case Select(qual: RefTree, _) => createPackageSymbol(qual).moduleClass } val existing = pkgOwner.info.decls.lookup(pid.name) if ((existing is Package) && (pkgOwner eq existing.owner)) existing else ctx.newCompletePackageSymbol(pkgOwner, pid.name.asTermName).entered } /** Expand tree and store in `expandedTree` */ def expand(tree: Tree)(implicit ctx: Context): Unit = tree match { case mdef: DefTree => val expanded = desugar.defTree(mdef) typr.println(i"Expansion: $mdef expands to $expanded") if (expanded ne mdef) mdef.pushAttachment(ExpandedTree, expanded) case _ => } /** The expanded version of this tree, or tree itself if not expanded */ def expanded(tree: Tree)(implicit ctx: Context): Tree = tree match { case ddef: DefTree => ddef.attachmentOrElse(ExpandedTree, ddef) case _ => tree } /** A new context that summarizes an import statement */ def importContext(sym: Symbol, selectors: List[Tree])(implicit ctx: Context) = ctx.fresh.setImportInfo(new ImportInfo(sym, selectors)) /** A new context for the interior of a class */ def inClassContext(selfInfo: DotClass /* Should be Type | Symbol*/)(implicit ctx: Context): Context = { val localCtx: Context = ctx.fresh.setNewScope selfInfo match { case sym: Symbol if sym.exists && sym.name != nme.WILDCARD => localCtx.scope.openForMutations.enter(sym) case _ => } localCtx } /** For all class definitions `stat` in `xstats`: If the companion class if not also defined * in `xstats`, invalidate it by setting its info to NoType. */ def invalidateCompanions(pkg: Symbol, xstats: List[untpd.Tree])(implicit ctx: Context): Unit = { val definedNames = xstats collect { case stat: NameTree => stat.name } def invalidate(name: TypeName) = if (!(definedNames contains name)) { val member = pkg.info.decl(name).asSymDenotation if (member.isClass && !(member is Package)) member.info = NoType } xstats foreach { case stat: TypeDef if stat.isClassDef => invalidate(stat.name.moduleClassName) case _ => } } /** Expand tree and create top-level symbols for statement and enter them into symbol table */ def index(stat: Tree)(implicit ctx: Context): Context = { expand(stat) indexExpanded(stat) } /** Create top-level symbols for all statements in the expansion of this statement and * enter them into symbol table */ def indexExpanded(stat: Tree)(implicit ctx: Context): Context = expanded(stat) match { case pcl: PackageDef => val pkg = createPackageSymbol(pcl.pid) index(pcl.stats)(ctx.fresh.setOwner(pkg.moduleClass)) invalidateCompanions(pkg, Trees.flatten(pcl.stats map expanded)) ctx case imp: Import => importContext(createSymbol(imp), imp.selectors) case mdef: DefTree => enterSymbol(createSymbol(mdef)) ctx case stats: Thicket => for (tree <- stats.toList) enterSymbol(createSymbol(tree)) ctx case _ => ctx } /** Create top-level symbols for statements and enter them into symbol table */ def index(stats: List[Tree])(implicit ctx: Context): Context = { val classDef = mutable.Map[TypeName, TypeDef]() val moduleDef = mutable.Map[TypeName, TypeDef]() /** Merge the definitions of a synthetic companion generated by a case class * and the real companion, if both exist. */ def mergeCompanionDefs() = { for (cdef @ TypeDef(name, _) <- stats) if (cdef.isClassDef) { classDef(name) = cdef cdef.attachmentOrElse(ExpandedTree, cdef) match { case Thicket(cls :: mval :: (mcls @ TypeDef(_, _: Template)) :: crest) => moduleDef(name) = mcls case _ => } } for (mdef @ ModuleDef(name, _) <- stats if !mdef.mods.is(Flags.Package)) { val typName = name.toTypeName val Thicket(vdef :: (mcls @ TypeDef(_, impl: Template)) :: Nil) = mdef.attachment(ExpandedTree) moduleDef(typName) = mcls classDef get name.toTypeName match { case Some(cdef) => cdef.attachmentOrElse(ExpandedTree, cdef) match { case Thicket(cls :: mval :: TypeDef(_, compimpl: Template) :: crest) => val mcls1 = cpy.TypeDef(mcls)( rhs = cpy.Template(impl)(body = compimpl.body ++ impl.body)) mdef.putAttachment(ExpandedTree, Thicket(vdef :: mcls1 :: Nil)) moduleDef(typName) = mcls1 cdef.putAttachment(ExpandedTree, Thicket(cls :: crest)) case _ => } case none => } } } def createLinks(classTree: TypeDef, moduleTree: TypeDef)(implicit ctx: Context) = { val claz = ctx.denotNamed(classTree.name.encode).symbol val modl = ctx.denotNamed(moduleTree.name.encode).symbol ctx.synthesizeCompanionMethod(nme.COMPANION_CLASS_METHOD, claz, modl).entered ctx.synthesizeCompanionMethod(nme.COMPANION_MODULE_METHOD, modl, claz).entered } def createCompanionLinks(implicit ctx: Context): Unit = { for (cdef @ TypeDef(name, _) <- classDef.values) { moduleDef.getOrElse(name, EmptyTree) match { case t: TypeDef => createLinks(cdef, t) case EmptyTree => } } } stats foreach expand mergeCompanionDefs() val ctxWithStats = (ctx /: stats) ((ctx, stat) => indexExpanded(stat)(ctx)) createCompanionLinks(ctxWithStats) ctxWithStats } /** The completer of a symbol defined by a member def or import (except ClassSymbols) */ class Completer(val original: Tree)(implicit ctx: Context) extends LazyType { protected def localContext(owner: Symbol) = ctx.fresh.setOwner(owner).setTree(original) private def typeSig(sym: Symbol): Type = original match { case original: ValDef => if (sym is Module) moduleValSig(sym) else valOrDefDefSig(original, sym, Nil, Nil, identity)(localContext(sym).setNewScope) case original: DefDef => val typer1 = new Typer nestedTyper(sym) = typer1 typer1.defDefSig(original, sym)(localContext(sym).setTyper(typer1)) case original: TypeDef => assert(!original.isClassDef) typeDefSig(original, sym)(localContext(sym).setNewScope) case imp: Import => try { val expr1 = typedAheadExpr(imp.expr, AnySelectionProto) ImportType(expr1) } catch { case ex: CyclicReference => typr.println(s"error while completing ${imp.expr}") throw ex } } final override def complete(denot: SymDenotation)(implicit ctx: Context) = { if (completions != noPrinter && ctx.typerState != this.ctx.typerState) { completions.println(completions.getClass.toString) def levels(c: Context): Int = if (c.typerState eq this.ctx.typerState) 0 else if (c.typerState == null) -1 else if (c.outer.typerState == c.typerState) levels(c.outer) else levels(c.outer) + 1 completions.println(s"!!!completing ${denot.symbol.showLocated} in buried typerState, gap = ${levels(ctx)}") } completeInCreationContext(denot) } protected def addAnnotations(denot: SymDenotation): Unit = original match { case original: untpd.MemberDef => for (annotTree <- untpd.modsDeco(original).mods.annotations) { val cls = typedAheadAnnotation(annotTree) val ann = Annotation.deferred(cls, implicit ctx => typedAnnotation(annotTree)) denot.addAnnotation(ann) } case _ => } /** Intentionally left without `implicit ctx` parameter. We need * to pick up the context at the point where the completer was created. */ def completeInCreationContext(denot: SymDenotation): Unit = { denot.info = typeSig(denot.symbol) addAnnotations(denot) } } class ClassCompleter(cls: ClassSymbol, original: TypeDef)(ictx: Context) extends Completer(original)(ictx) { withDecls(newScope) protected implicit val ctx: Context = localContext(cls).setMode(ictx.mode &~ Mode.InSuperCall) val TypeDef(name, impl @ Template(constr, parents, self, _)) = original val (params, rest) = impl.body span { case td: TypeDef => td.mods is Param case vd: ValDef => vd.mods is ParamAccessor case _ => false } def init() = index(params) /** The type signature of a ClassDef with given symbol */ override def completeInCreationContext(denot: SymDenotation): Unit = { /** The type of a parent constructor. Types constructor arguments * only if parent type contains uninstantiated type parameters. */ def parentType(parent: untpd.Tree)(implicit ctx: Context): Type = if (parent.isType) { typedAheadType(parent).tpe } else { val (core, targs) = stripApply(parent) match { case TypeApply(core, targs) => (core, targs) case core => (core, Nil) } val Select(New(tpt), nme.CONSTRUCTOR) = core val targs1 = targs map (typedAheadType(_)) val ptype = typedAheadType(tpt).tpe appliedTo targs1.tpes if (ptype.typeParams.isEmpty) ptype else typedAheadExpr(parent).tpe } def checkedParentType(parent: untpd.Tree): Type = { val ptype = parentType(parent)(ctx.superCallContext) if (cls.isRefinementClass) ptype else checkClassTypeWithStablePrefix(ptype, parent.pos, traitReq = parent ne parents.head) } val selfInfo = if (self.isEmpty) NoType else if (cls is Module) cls.owner.thisType select sourceModule else createSymbol(self) // pre-set info, so that parent types can refer to type params denot.info = ClassInfo(cls.owner.thisType, cls, Nil, decls, selfInfo) // Ensure constructor is completed so that any parameter accessors // which have type trees deriving from its parameters can be // completed in turn. Note that parent types access such parameter // accessors, that's why the constructor needs to be completed before // the parent types are elaborated. index(constr) symbolOfTree(constr).ensureCompleted() val parentTypes = ensureFirstIsClass(parents map checkedParentType) val parentRefs = ctx.normalizeToClassRefs(parentTypes, cls, decls) typr.println(s"completing $denot, parents = $parents, parentTypes = $parentTypes, parentRefs = $parentRefs") index(rest)(inClassContext(selfInfo)) denot.info = ClassInfo(cls.owner.thisType, cls, parentRefs, decls, selfInfo) addAnnotations(denot) if (isDerivedValueClass(cls)) cls.setFlag(Final) cls.setApplicableFlags( (NoInitsInterface /: impl.body)((fs, stat) => fs & defKind(stat))) } } /** Typecheck tree during completion, and remember result in typedtree map */ private def typedAheadImpl(tree: Tree, pt: Type)(implicit ctx: Context): tpd.Tree = { val xtree = expanded(tree) xtree.getAttachment(TypedAhead) match { case Some(ttree) => ttree case none => val ttree = typer.typed(tree, pt) xtree.pushAttachment(TypedAhead, ttree) ttree } } def typedAheadType(tree: Tree, pt: Type = WildcardType)(implicit ctx: Context): tpd.Tree = typedAheadImpl(tree, pt)(ctx retractMode Mode.PatternOrType addMode Mode.Type) def typedAheadExpr(tree: Tree, pt: Type = WildcardType)(implicit ctx: Context): tpd.Tree = typedAheadImpl(tree, pt)(ctx retractMode Mode.PatternOrType) def typedAheadAnnotation(tree: Tree)(implicit ctx: Context): Symbol = tree match { case Apply(fn, _) => typedAheadAnnotation(fn) case TypeApply(fn, _) => typedAheadAnnotation(fn) case Select(qual, nme.CONSTRUCTOR) => typedAheadAnnotation(qual) case New(tpt) => typedAheadType(tpt).tpe.classSymbol } /** Enter and typecheck parameter list */ def completeParams(params: List[MemberDef])(implicit ctx: Context) = { index(params) for (param <- params) typedAheadExpr(param) } /** The signature of a module valdef. * This will compute the corresponding module class TypeRef immediately * without going through the defined type of the ValDef. This is necessary * to avoid cyclic references involving imports and module val defs. */ def moduleValSig(sym: Symbol)(implicit ctx: Context): Type = { val clsName = sym.name.moduleClassName val cls = ctx.denotNamed(clsName) suchThat (_ is ModuleClass) ctx.owner.thisType select (clsName, cls) } /** The type signature of a ValDef or DefDef * @param mdef The definition * @param sym Its symbol * @param paramFn A wrapping function that produces the type of the * defined symbol, given its final return type */ def valOrDefDefSig(mdef: ValOrDefDef, sym: Symbol, typeParams: List[Symbol], paramss: List[List[Symbol]], paramFn: Type => Type)(implicit ctx: Context): Type = { def inferredType = { /** A type for this definition that might be inherited from elsewhere: * If this is a setter parameter, the corresponding getter type. * If this is a class member, the conjunction of all result types * of overridden methods. * NoType if neither case holds. */ val inherited = if (sym.owner.isTerm) NoType else { // TODO: Look only at member of supertype instead? lazy val schema = paramFn(WildcardType) val site = sym.owner.thisType ((NoType: Type) /: sym.owner.info.baseClasses.tail) { (tp, cls) => val iRawInfo = cls.info.nonPrivateDecl(sym.name).matchingDenotation(site, schema).info val iInstInfo = iRawInfo match { case iRawInfo: PolyType => if (iRawInfo.paramNames.length == typeParams.length) iRawInfo.instantiate(typeParams map (_.typeRef)) else NoType case _ => if (typeParams.isEmpty) iRawInfo else NoType } val iResType = iInstInfo.finalResultType.asSeenFrom(site, cls) if (iResType.exists) typr.println(i"using inherited type for ${mdef.name}; raw: $iRawInfo, inst: $iInstInfo, inherited: $iResType") tp & iResType } } /** The proto-type to be used when inferring the result type from * the right hand side. This is `WildcardType` except if the definition * is a default getter. In that case, the proto-type is the type of * the corresponding parameter where bound parameters are replaced by * Wildcards. */ def rhsProto = { val name = sym.asTerm.name val idx = name.defaultGetterIndex if (idx < 0) WildcardType else { val original = name.defaultGetterToMethod val meth: Denotation = if (original.isConstructorName && (sym.owner is ModuleClass)) sym.owner.companionClass.info.decl(nme.CONSTRUCTOR) else ctx.defContext(sym).denotNamed(original) def paramProto(paramss: List[List[Type]], idx: Int): Type = paramss match { case params :: paramss1 => if (idx < params.length) wildApprox(params(idx)) else paramProto(paramss1, idx - params.length) case nil => WildcardType } val defaultAlts = meth.altsWith(_.hasDefaultParams) if (defaultAlts.length == 1) paramProto(defaultAlts.head.info.widen.paramTypess, idx) else WildcardType } } // println(s"final inherited for $sym: ${inherited.toString}") !!! // println(s"owner = ${sym.owner}, decls = ${sym.owner.info.decls.show}") def isInline = sym.is(Final, butNot = Method) def widenRhs(tp: Type): Type = tp.widenTermRefExpr match { case tp: ConstantType if isInline => tp case _ => tp.widen.approximateUnion } val rhsCtx = ctx.addMode(Mode.InferringReturnType) def rhsType = typedAheadExpr(mdef.rhs, inherited orElse rhsProto)(rhsCtx).tpe def cookedRhsType = ctx.deskolemize(widenRhs(rhsType)) lazy val lhsType = fullyDefinedType(cookedRhsType, "right-hand side", mdef.pos) //if (sym.name.toString == "y") println(i"rhs = $rhsType, cooked = $cookedRhsType") if (inherited.exists) if (sym.is(Final, butNot = Method) && lhsType.isInstanceOf[ConstantType]) lhsType // keep constant types that fill in for a non-constant (to be revised when inline has landed). else inherited else { if (sym is Implicit) { val resStr = if (mdef.isInstanceOf[DefDef]) "result " else "" ctx.error(d"${resStr}type of implicit definition needs to be given explicitly", mdef.pos) sym.resetFlag(Implicit) } lhsType orElse WildcardType } } val tptProto = mdef.tpt match { case _: untpd.DerivedTypeTree => WildcardType case TypeTree(untpd.EmptyTree) => inferredType case TypedSplice(tpt: TypeTree) if !isFullyDefined(tpt.tpe, ForceDegree.none) => val rhsType = typedAheadExpr(mdef.rhs, tpt.tpe).tpe mdef match { case mdef: DefDef if mdef.name == nme.ANON_FUN => val hygienicType = avoid(rhsType, paramss.flatten) if (!(hygienicType <:< tpt.tpe)) ctx.error(i"return type ${tpt.tpe} of lambda cannot be made hygienic;\\n" + i"it is not a supertype of the hygienic type $hygienicType", mdef.pos) //println(i"lifting $rhsType over $paramss -> $hygienicType = ${tpt.tpe}") //println(TypeComparer.explained { implicit ctx => hygienicType <:< tpt.tpe }) case _ => } WildcardType case _ => WildcardType } paramFn(typedAheadType(mdef.tpt, tptProto).tpe) } /** The type signature of a DefDef with given symbol */ def defDefSig(ddef: DefDef, sym: Symbol)(implicit ctx: Context) = { val DefDef(name, tparams, vparamss, _, _) = ddef completeParams(tparams) vparamss foreach completeParams val isConstructor = name == nme.CONSTRUCTOR def typeParams = tparams map symbolOfTree val paramSymss = ctx.normalizeIfConstructor(vparamss.nestedMap(symbolOfTree), isConstructor) def wrapMethType(restpe: Type): Type = { val restpe1 = // try to make anonymous functions non-dependent, so that they can be used in closures if (name == nme.ANON_FUN) avoid(restpe, paramSymss.flatten) else restpe ctx.methodType(tparams map symbolOfTree, paramSymss, restpe1, isJava = ddef.mods is JavaDefined) } if (isConstructor) { // set result type tree to unit, but take the current class as result type of the symbol typedAheadType(ddef.tpt, defn.UnitType) wrapMethType(ctx.effectiveResultType(sym, typeParams, NoType)) } else valOrDefDefSig(ddef, sym, typeParams, paramSymss, wrapMethType) } def typeDefSig(tdef: TypeDef, sym: Symbol)(implicit ctx: Context): Type = { completeParams(tdef.tparams) val tparamSyms = tdef.tparams map symbolOfTree val isDerived = tdef.rhs.isInstanceOf[untpd.DerivedTypeTree] val toParameterize = tparamSyms.nonEmpty && !isDerived val needsLambda = sym.allOverriddenSymbols.exists(_ is HigherKinded) && !isDerived def abstracted(tp: Type): Type = if (needsLambda) tp.LambdaAbstract(tparamSyms) else if (toParameterize) tp.parameterizeWith(tparamSyms) else tp sym.info = abstracted(TypeBounds.empty) // Temporarily set info of defined type T to ` >: Nothing <: Any. // This is done to avoid cyclic reference errors for F-bounds. // This is subtle: `sym` has now an empty TypeBounds, but is not automatically // made an abstract type. If it had been made an abstract type, it would count as an // abstract type of its enclosing class, which might make that class an invalid // prefix. I verified this would lead to an error when compiling io.ClassPath. // A distilled version is in pos/prefix.scala. // // The scheme critically relies on an implementation detail of isRef, which // inspects a TypeRef's info, instead of simply dealiasing alias types. val rhsType = typedAheadType(tdef.rhs).tpe val unsafeInfo = rhsType match { case _: TypeBounds => abstracted(rhsType).asInstanceOf[TypeBounds] case _ => TypeAlias(abstracted(rhsType), if (sym is Local) sym.variance else 0) } sym.info = NoCompleter checkNonCyclic(sym, unsafeInfo, reportErrors = true) } }
yusuke2255/dotty
src/dotty/tools/dotc/typer/Namer.scala
Scala
bsd-3-clause
33,445
// Copyright (c) 2015 Ben Zimmer. All rights reserved. // Secondary project build.scala file import sbt._ import Keys._ case class JvmSettings(javacSource: String, javacTarget: String, scalacTarget: String)
bdzimmer/secondary
project/build.scala
Scala
bsd-3-clause
209
package ir import ir.ast._ object GenerateIR{ // 0 -> f, 1 -> Map(f), 2 -> Map(Map(f)), ... def wrapInMaps(f: => Lambda, count: Int): Lambda = { if(count < 1) f else Map(wrapInMaps(f, count-1)) } // creates Map(...(Map(f)...) o ... o Map(f) o f def applyInEveryDimUntilDim(f: => Lambda, dim: Int): Lambda = { if(dim <= 1) f else applyInEveryDimUntilDim(Map(f), dim-1) o f //else Map(applyInEveryDimUntilDim(f)(dim-1)) o f <- fused-maps version } // creates f o Map(f) o ... o Map(...(Map(f)...) def applyInEveryDimUntilDimReverse(f: => Lambda, dim: Int): Lambda = { if(dim <= 1) f else f o applyInEveryDimUntilDimReverse(Map(f), dim-1) //else f o Map(applyInEveryDimUntilDimReverse(f)(dim-1)) <- fused-maps version } // [a][A][b][B][c][C]... => [a][b][c]...[A][B][C]... def interleaveDimensions(count: Int, i: Int): Lambda = { val howManyMaps = -2 * (count - 1 - i) - 1 if(i < 2) throw new IllegalArgumentException("Not enough dimensions to interleave") if(count == 2) GenerateIR.wrapInMaps(Transpose(), howManyMaps) else { GenerateIR.applyInEveryDimUntilDim(GenerateIR.wrapInMaps(Transpose(), howManyMaps), count - 1) o interleaveDimensions(count - 1, i) } } def interleaveDimensionsReverse(dim: Int): Lambda = { if(dim < 2) throw new IllegalArgumentException("Not enough dimensions to interleave") if(dim == 2) Map(Transpose()) else interleaveDimensionsReverse(dim -1) o GenerateIR.applyInEveryDimUntilDim(GenerateIR.wrapInMaps(Transpose(), dim -1), dim-1) } }
lift-project/lift
src/main/ir/GenerateIR.scala
Scala
mit
1,582
package com.chrisomeara.pillar class IrreversibleMigrationException(migration: IrreversibleMigration) extends RuntimeException(s"Migration ${migration.authoredAt.getTime}: ${migration.description} is not reversible")
smr-co-uk/pillar
src/main/scala/com/chrisomeara/pillar/IrreversibleMigrationException.scala
Scala
mit
219
package asobu.distributed import akka.actor._ import akka.cluster.{Member, MemberStatus, Cluster} import akka.cluster.ddata.{LWWMap, LWWMapKey, DistributedData} import akka.cluster.ddata.Replicator._ import asobu.distributed.EndpointsRegistry.DocDataType import asobu.distributed.gateway.enricher.Interpreter import asobu.distributed.protocol.EndpointDefinition import play.api.libs.json.{JsNumber, Json, JsObject} import concurrent.duration._ trait EndpointsRegistry { def writeConsistency: WriteConsistency def readConsistency: ReadConsistency val EndpointsDataKey = LWWMapKey[EndpointDefinition]("endpoints-registry-endpoints") val EndpointsDocsKey = LWWMapKey[DocDataType]("endpoints-registry-apidocs") def emptyDocs: LWWMap[DocDataType] val emptyData = LWWMap.empty[EndpointDefinition] implicit def node: Cluster def replicator: ActorRef } object EndpointsRegistry { //Doc json is stored as String (JsObject isn't that serializable after manipulation) type DocDataType = String } case class DefaultEndpointsRegistry(system: ActorSystem) extends EndpointsRegistry { val timeout = 30.seconds val writeConsistency = WriteAll(timeout) val readConsistency = ReadMajority(timeout) val emptyDocs = LWWMap.empty[DocDataType] implicit val node = Cluster(system) val replicator: ActorRef = DistributedData(system).replicator } class EndpointsRegistryUpdater(registry: EndpointsRegistry) extends Actor with ActorLogging { import EndpointsRegistryUpdater._ import registry._ def receive: Receive = { case Add(endpointDef) ⇒ update(Added(sender)) { m ⇒ m + (endpointDef.id → endpointDef) } case AddDoc(role, doc) ⇒ log.info(s"Registering Api Documentation for $role") updateDoc(Added(sender))(_ + (role → doc)) case Remove(role) ⇒ removeEndpoint(sender) { endpointDef ⇒ endpointDef.clusterRole == role } updateDoc(Removed(sender))(_ - role) case Sanitize ⇒ def inCluster(member: Member): Boolean = List(MemberStatus.Up, MemberStatus.Joining, MemberStatus.WeaklyUp).contains(member.status) val currentRoles = Cluster(context.system).state.members.filter(inCluster).flatMap(_.roles).toSet log.info("Sanitizing current endpoint defs based current roles " + currentRoles.mkString(", ")) removeEndpoint(sender) { ef ⇒ !currentRoles.contains(ef.clusterRole) } updateDoc(Removed(sender)) { m ⇒ m.entries.keys.foldLeft(m) { (lwwMap, role) ⇒ if (!currentRoles.contains(role)) lwwMap - role else lwwMap } } case UpdateSuccess(_, Some(result: Result)) ⇒ log.info(s"EndpointRegistry updated by $result") result.confirm() } def update(res: Result)(f: LWWMap[EndpointDefinition] ⇒ LWWMap[EndpointDefinition]): Unit = { replicator ! Update(EndpointsDataKey, emptyData, writeConsistency, Some(res))(f) } def updateDoc(res: Result)(f: LWWMap[DocDataType] ⇒ LWWMap[DocDataType]): Unit = { replicator ! Update(EndpointsDocsKey, emptyDocs, writeConsistency, Some(res))(f) } def removeEndpoint(sender: ActorRef)(predictor: EndpointDefinition ⇒ Boolean): Unit = update(Removed(sender)) { m ⇒ m.entries.values.foldLeft(m) { (lwwMap, endpointDef) ⇒ if (predictor(endpointDef)) lwwMap - endpointDef.id else lwwMap } } } object EndpointsRegistryUpdater { def props(registry: EndpointsRegistry) = Props(new EndpointsRegistryUpdater(registry)) sealed trait UpdateRequest case class Add(endpointDef: EndpointDefinition) extends UpdateRequest case class AddDoc(role: String, doc: String) case class Remove(role: String) extends UpdateRequest /** * Remove all endpoints whose role isn't in this list. */ case object Sanitize extends UpdateRequest sealed trait Result { def replyTo: ActorRef def confirm(): Unit = { replyTo ! this } } case class Added(replyTo: ActorRef) extends Result case class Removed(replyTo: ActorRef) extends Result case class Checked(replyTo: ActorRef) extends Result }
iheartradio/asobu
distributed/src/main/scala/asobu/distributed/EndpointsRegistry.scala
Scala
apache-2.0
4,195
/* * Copyright 2014-2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.atlas.core.util import org.openjdk.jol.info.ClassLayout import org.openjdk.jol.info.GraphLayout import munit.FunSuite import scala.util.Random class LongHashSetSuite extends FunSuite { test("add") { val s = new LongHashSet(-1, 10) s.add(11) assertEquals(List(11L), s.toList) assertEquals(1, s.size) } test("dedup") { val s = new LongHashSet(-1, 10) s.add(42) assertEquals(List(42L), s.toList) assertEquals(1, s.size) s.add(42) assertEquals(List(42L), s.toList) assertEquals(1, s.size) } test("resize") { val s = new LongHashSet(-1L, 10) (0L until 10000L).foreach(s.add) assertEquals((0L until 10000L).toSet, s.toList.toSet) assertEquals(s.size, 10000) } test("random") { val jset = new scala.collection.mutable.HashSet[Long] val iset = new LongHashSet(-1, 10) (0 until 10000).foreach { i => val v = Random.nextLong() iset.add(v) jset.add(v) } assertEquals(jset.toSet, iset.toList.toSet) } private def arrayCompare(a1: Array[Long], a2: Array[Long]): Unit = { // Need to sort as traversal order could be different when generating the arrays java.util.Arrays.sort(a1) java.util.Arrays.sort(a2) assertEquals(a1.toSeq, a2.toSeq) } test("toArray") { val jset = new scala.collection.mutable.HashSet[Long] val iset = new LongHashSet(-1, 10) (0 until 10000).foreach { i => val v = Random.nextLong() iset.add(v) jset.add(v) } arrayCompare(jset.toArray, iset.toArray) } test("memory per set") { // Sanity check to verify if some change introduces more overhead per set val bytes = ClassLayout.parseClass(classOf[LongHashSet]).instanceSize() assertEquals(bytes, 32L) } test("memory - 5 items") { val iset = new LongHashSet(-1, 10) val jset = new java.util.HashSet[Int](10) (0 until 5).foreach { i => iset.add(i) jset.add(i) } val igraph = GraphLayout.parseInstance(iset) //val jgraph = GraphLayout.parseInstance(jset) //println(igraph.toFootprint) //println(jgraph.toFootprint) // Only objects should be the array and the set itself assertEquals(igraph.totalCount(), 2L) // Sanity check size is < 100 bytes assert(igraph.totalSize() <= 250) } test("memory - 10k items") { val iset = new LongHashSet(-1, 10) val jset = new java.util.HashSet[Int](10) (0 until 10000).foreach { i => iset.add(i) jset.add(i) } val igraph = GraphLayout.parseInstance(iset) //val jgraph = GraphLayout.parseInstance(jset) //println(igraph.toFootprint) //println(jgraph.toFootprint) // Only objects should be the array and the set itself assertEquals(igraph.totalCount(), 2L) // Sanity check size is < 220kb assert(igraph.totalSize() <= 220000) } test("negative absolute value") { val s = new LongHashSet(-1, 10) s.add(java.lang.Long.MIN_VALUE) } }
Netflix/atlas
atlas-core/src/test/scala/com/netflix/atlas/core/util/LongHashSetSuite.scala
Scala
apache-2.0
3,588
package org.bitcoins.core.protocol.transaction import org.bitcoins.core.number.UInt32 import org.bitcoins.core.util.TestUtil import org.scalatest.{FlatSpec, MustMatchers} /** * Created by chris on 3/30/16. */ class TransactionOutPointFactoryTest extends FlatSpec with MustMatchers { "TransactionOutPointFactory" must "create an outpoint from its base components" in { val outPoint = TransactionOutPoint(TestUtil.parentSimpleTransaction.outputs.head, TestUtil.parentSimpleTransaction) outPoint.vout must be (UInt32.zero) outPoint.txId must be (TestUtil.parentSimpleTransaction.txId) } it must "throw an exception if the given output is not part of the given transaciton" in { intercept[RuntimeException] { TransactionOutPoint(TestUtil.simpleTransaction.outputs.head, TestUtil.parentSimpleTransaction) } } }
SuredBits/bitcoin-s-sidechains
src/test/scala/org/bitcoins/core/protocol/transaction/TransactionOutPointFactoryTest.scala
Scala
mit
847
import com.jme3.material.Material import com.jme3.math.ColorRGBA import com.jme3.scene.Geometry /** * Created by shinmox on 01/04/14. */ class Minion(Geometry: Geometry, _modele: Modele, Nom: String, _material: Material) extends Personnage(Geometry, _modele, Nom) { Force = 1 PointVie = 3 override def RecoitFrappe(quantite: Int) { _material.setColor("Color", ColorRGBA.Brown) Geometry.setMaterial(_material) super.RecoitFrappe(quantite) } }
shinmox/shinFPS
shinFPS/src/Minion.scala
Scala
apache-2.0
490
/* * Copyright (c) 2014-2019 by The Minitest Project Developers. * Some rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package minitest import minitest.api._ import scala.concurrent.{ExecutionContext, Future} trait TestSuite[Env] extends AbstractTestSuite with Asserts { def setupSuite(): Unit = () def tearDownSuite(): Unit = () def setup(): Env def tearDown(env: Env): Unit def test(name: String)(f: Env => Void): Unit = synchronized { if (isInitialized) throw initError() propertiesSeq = propertiesSeq :+ TestSpec.sync[Env](name, env => f(env)) } def testAsync(name: String)(f: Env => Future[Unit]): Unit = synchronized { if (isInitialized) throw initError() propertiesSeq = propertiesSeq :+ TestSpec.async[Env](name, f) } lazy val properties: Properties[_] = synchronized { if (!isInitialized) isInitialized = true Properties(setup _, (env: Env) => { tearDown(env); Void.UnitRef }, setupSuite _, tearDownSuite _, propertiesSeq) } private[this] var propertiesSeq = Seq.empty[TestSpec[Env, Unit]] private[this] var isInitialized = false private[this] implicit lazy val ec: ExecutionContext = DefaultExecutionContext private[this] def initError() = new AssertionError( "Cannot define new tests after TestSuite was initialized" ) }
monifu/minitest
shared/src/main/scala/minitest/TestSuite.scala
Scala
apache-2.0
1,890
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.catalyst.csv import java.io.Writer import com.univocity.parsers.csv.CsvWriter import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.util.{DateFormatter, DateTimeUtils, IntervalStringStyles, IntervalUtils, TimestampFormatter} import org.apache.spark.sql.catalyst.util.LegacyDateFormats.FAST_DATE_FORMAT import org.apache.spark.sql.types._ class UnivocityGenerator( schema: StructType, writer: Writer, options: CSVOptions) { private val writerSettings = options.asWriterSettings writerSettings.setHeaders(schema.fieldNames: _*) private val gen = new CsvWriter(writer, writerSettings) // A `ValueConverter` is responsible for converting a value of an `InternalRow` to `String`. // When the value is null, this converter should not be called. private type ValueConverter = (InternalRow, Int) => String // `ValueConverter`s for all values in the fields of the schema private val valueConverters: Array[ValueConverter] = schema.map(_.dataType).map(makeConverter).toArray private val timestampFormatter = TimestampFormatter( options.timestampFormatInWrite, options.zoneId, options.locale, legacyFormat = FAST_DATE_FORMAT, isParsing = false) private val timestampNTZFormatter = TimestampFormatter( options.timestampNTZFormatInWrite, options.zoneId, legacyFormat = FAST_DATE_FORMAT, isParsing = false, forTimestampNTZ = true) private val dateFormatter = DateFormatter( options.dateFormatInWrite, options.locale, legacyFormat = FAST_DATE_FORMAT, isParsing = false) @scala.annotation.tailrec private def makeConverter(dataType: DataType): ValueConverter = dataType match { case DateType => (row: InternalRow, ordinal: Int) => dateFormatter.format(row.getInt(ordinal)) case TimestampType => (row: InternalRow, ordinal: Int) => timestampFormatter.format(row.getLong(ordinal)) case TimestampNTZType => (row: InternalRow, ordinal: Int) => timestampNTZFormatter.format(DateTimeUtils.microsToLocalDateTime(row.getLong(ordinal))) case YearMonthIntervalType(start, end) => (row: InternalRow, ordinal: Int) => IntervalUtils.toYearMonthIntervalString( row.getInt(ordinal), IntervalStringStyles.ANSI_STYLE, start, end) case DayTimeIntervalType(start, end) => (row: InternalRow, ordinal: Int) => IntervalUtils.toDayTimeIntervalString( row.getLong(ordinal), IntervalStringStyles.ANSI_STYLE, start, end) case udt: UserDefinedType[_] => makeConverter(udt.sqlType) case dt: DataType => (row: InternalRow, ordinal: Int) => row.get(ordinal, dt).toString } private def convertRow(row: InternalRow): Seq[String] = { var i = 0 val values = new Array[String](row.numFields) while (i < row.numFields) { if (!row.isNullAt(i)) { values(i) = valueConverters(i).apply(row, i) } i += 1 } values } def writeHeaders(): Unit = { gen.writeHeaders() } /** * Writes a single InternalRow to CSV using Univocity. */ def write(row: InternalRow): Unit = { gen.writeRow(convertRow(row): _*) } def writeToString(row: InternalRow): String = { gen.writeRowToString(convertRow(row): _*) } def close(): Unit = gen.close() def flush(): Unit = gen.flush() }
mahak/spark
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/csv/UnivocityGenerator.scala
Scala
apache-2.0
4,182
package net.scalax.cpoi.utils.compat object CollectionCompat { type LazyList[T] = scala.collection.immutable.LazyList[T] def seqToLazyList[T](seq: Seq[T]): LazyList[T] = seq.to(LazyList) def mapFromMutable[T1, T2](map: scala.collection.mutable.Map[T1, T2]): Map[T1, T2] = map.to(Map) def mapFromImmutable[T1, T2](map: scala.collection.immutable.Map[T1, T2]): scala.collection.mutable.Map[T1, T2] = map.to(scala.collection.mutable.Map) }
scalax/poi-collection
src/main/scala-2.13/CollectionCompat.scala
Scala
mit
478
package com.eevolution.context.dictionary.infrastructure.repository import com.eevolution.context.dictionary.domain.model.Find import com.eevolution.context.dictionary.infrastructure.db.DbContext._ /** * Copyright (C) 2003-2017, e-Evolution Consultants S.A. , http://www.e-evolution.com * 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/>. * Email: [email protected], http://www.e-evolution.com , http://github.com/EmerisScala * Created by [email protected] , www.e-evolution.com on 20/10/17. */ /** * Find Mapping */ trait FindMapping { val queryFind = quote { querySchema[Find]("AD_Find", _.findId-> "AD_Find_ID", _.tenantId-> "AD_Client_ID", _.organizationId-> "AD_Org_ID", _.isActive-> "IsActive", _.created-> "Created", _.createdBy-> "CreatedBy", _.updated-> "Updated", _.updatedBy-> "UpdatedBy", _.andOr-> "AndOr", _.attributeId-> "AD_Column_ID", _.operation-> "Operation", _.value-> "Value", _.value2-> "Value2", _.uuid-> "UUID") } }
adempiere/ADReactiveSystem
dictionary-impl/src/main/scala/com/eevolution/context/dictionary/infrastructure/repository/FindMapping.scala
Scala
gpl-3.0
1,676
/* * Copyright 2017 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.hmrc.bforms.models import play.api.libs.json.{ Format, JsError, JsString, JsSuccess, Reads, Writes } case class FieldId(value: String) extends AnyVal { override def toString = value def withSuffix(suffix: String): FieldId = FieldId(value + "." + suffix) } object FieldId { implicit val format: Format[FieldId] = ValueClassFormat.format(FieldId.apply)(_.value) }
VlachJosef/bforms-frontend
app/uk/gov/hmrc/bforms/models/FieldId.scala
Scala
apache-2.0
992
package com.iheart.playSwagger import com.iheart.playSwagger.OutputTransformer.SimpleOutputTransformer import org.specs2.mutable.Specification import play.api.libs.json._ import scala.util.{ Failure, Success } class OutputTransformerSpec extends Specification { "OutputTransformer.traverseTransformer" >> { "traverse and transform object and update simple paths" >> { val result = OutputTransformer.traverseTransformer(Json.obj( "a" → 1, "b" → "c")) { _ ⇒ Success(JsNumber(10)) } result === Success(Json.obj("a" → 10, "b" → 10)) } "traverse and transform object and update nested paths" >> { val result = OutputTransformer.traverseTransformer(Json.obj( "a" → 1, "b" → Json.obj( "c" → 1))) { _ ⇒ Success(JsNumber(10)) } result === Success(Json.obj("a" → 10, "b" → Json.obj("c" → 10))) } "traverse and transform object and update array paths" >> { val result = OutputTransformer.traverseTransformer(Json.obj( "a" → 1, "b" → Json.arr( Json.obj("c" → 1), Json.obj("d" → 1), Json.obj("e" → 1)))) { _ ⇒ Success(JsNumber(10)) } result === Success(Json.obj("a" → 10, "b" → Json.arr( Json.obj("c" → 10), Json.obj("d" → 10), Json.obj("e" → 10)))) } "return a failure when there's a problem transforming data" >> { val err: IllegalArgumentException = new scala.IllegalArgumentException("failed") val result = OutputTransformer.traverseTransformer(Json.obj( "a" → 1, "b" → Json.obj( "c" → 1))) { _ ⇒ Failure(err) } result === Failure(err) } } "OutputTransformer.>=>" >> { "return composed function" >> { val a = SimpleOutputTransformer(OutputTransformer.traverseTransformer(_) { case JsString(content) ⇒ Success(JsString(content + "a")) case _ ⇒ Failure(new IllegalStateException()) }) val b = SimpleOutputTransformer(OutputTransformer.traverseTransformer(_) { case JsString(content) ⇒ Success(JsString(content + "b")) case _ ⇒ Failure(new IllegalStateException()) }) val g = a >=> b g(Json.obj( "A" → "Z", "B" → "Y")) must beSuccessfulTry.withValue(Json.obj( "A" → "Zab", "B" → "Yab")) } "fail if one composed function fails" >> { val a = SimpleOutputTransformer(OutputTransformer.traverseTransformer(_) { case JsString(content) ⇒ Success(JsString("a" + content)) case _ ⇒ Failure(new IllegalStateException()) }) val b = SimpleOutputTransformer(OutputTransformer.traverseTransformer(_) { case JsString(content) ⇒ Failure(new IllegalStateException("not strings")) case _ ⇒ Failure(new IllegalStateException()) }) val g = a >=> b g(Json.obj( "A" → "Z", "B" → "Y")) must beFailedTry[JsObject].withThrowable[IllegalStateException]("not strings") } } } class EnvironmentVariablesSpec extends Specification { "EnvironmentVariables" >> { "transform json with markup values" >> { val envs = Map("A" → "B", "C" → "D") val instance = MapVariablesTransformer(envs) instance(Json.obj( "a" → "${A}", "b" → Json.obj( "c" → "${C}"))) === Success(Json.obj("a" → "B", "b" → Json.obj("c" → "D"))) } "return failure when using non present environment variables" >> { val envs = Map("A" → "B", "C" → "D") val instance = MapVariablesTransformer(envs) instance(Json.obj( "a" → "${A}", "b" → Json.obj( "c" → "${NON_EXISTING}"))) must beFailedTry[JsObject].withThrowable[IllegalStateException]("Unable to find variable NON_EXISTING") } } } class EnvironmentVariablesIntegrationSpec extends Specification { implicit val cl = getClass.getClassLoader "integration" >> { "generate api with placeholders in place" >> { val envs = Map("LAST_TRACK_DESCRIPTION" → "Last track", "PLAYED_TRACKS_DESCRIPTION" → "Add tracks") val json = SwaggerSpecGenerator( NamingStrategy.None, PrefixDomainModelQualifier("com.iheart"), outputTransformers = MapVariablesTransformer(envs) :: Nil).generate("env.routes").get val pathJson = json \ "paths" val stationJson = (pathJson \ "/api/station/{sid}/playedTracks/last" \ "get").as[JsObject] val addTrackJson = (pathJson \ "/api/station/playedTracks" \ "post").as[JsObject] ((addTrackJson \ "parameters").as[JsArray].value.head \ "description").as[String] === "Add tracks" (stationJson \ "responses" \ "200" \ "description").as[String] === "Last track" } } "fail to generate API if environment variable is not found" >> { val envs = Map("LAST_TRACK_DESCRIPTION" → "Last track") val json = SwaggerSpecGenerator( NamingStrategy.None, PrefixDomainModelQualifier("com.iheart"), outputTransformers = MapVariablesTransformer(envs) :: Nil).generate("env.routes") json must beFailedTry[JsObject].withThrowable[IllegalStateException]("Unable to find variable PLAYED_TRACKS_DESCRIPTION") } }
iheartradio/play-swagger
core/src/test/scala/com/iheart/playSwagger/OutputTransformerSpec.scala
Scala
apache-2.0
5,320
package js.hw3 import scala.util.parsing.combinator._ import scala.util.parsing.combinator.lexical._ import scala.util.parsing.combinator.token._ import scala.util.parsing.combinator.syntactical._ import scala.util.parsing.input._ import ast._ object parse extends JavaTokenParsers { val reserved: Set[String] = Set("const", "function", "return") def stmt: Parser[Expr] = rep(basicStmt) ~ opt(lastBasicStmt) ^^ { case (sts: List[Expr])~lst => (sts :+ (lst getOrElse Undefined)) reduceRight[Expr] { case (Undefined, st2) => st2 case (st1, Undefined) => st1 case (f @ Function(Some(x), _, _), st2) => ConstDecl(x, f, st2) case (ConstDecl(v, e1, _), st2) => ConstDecl(v, e1, st2) case (st1, st2) => BinOp(Seq, st1, st2) } } //def eol: Parser[String] = """\\r?\\n""".r def stmtSep: Parser[String] = ";" def basicStmt: Parser[Expr] = stmtSep ^^^ Undefined | "{" ~> stmt <~ "}" | constDecl <~ stmtSep | expr <~ stmtSep def lastBasicStmt: Parser[Expr] = stmtSep ^^^ Undefined | "{" ~> stmt <~ "}" | constDecl | expr def constDecl: Parser[ConstDecl] = positioned( ("const" ~> ident <~ "=") ~ expr ^^ { case s~e => ConstDecl(s, e, Undefined)}) def expr: Parser[Expr] = commaExpr def commaExpr: Parser[Expr] = condExpr ~ rep("," ~> condExpr) ^^ { case e~es => (e :: es) reduceRight[Expr] { case (e1, e2) => BinOp(Seq, e1, e2).setPos(e1.pos) } } def condExpr: Parser[Expr] = (orExpr <~ "?") ~ (orExpr <~ ":") ~ orExpr ^^ { case e1~e2~e3 => If(e1, e2, e3).setPos(e1.pos) } | orExpr def orExpr: Parser[Expr] = andExpr ~ rep("||" ~> andExpr) ^^ { case e1~es => (e1 /: es) { case (e1, e2) => BinOp(Or, e1, e2).setPos(e1.pos) } } def andExpr: Parser[Expr] = eqExpr ~ rep("&&" ~> eqExpr) ^^ { case e1~es => (e1 /: es) { case (e1, e2) => BinOp(And, e1, e2).setPos(e1.pos) } } def eqOp: Parser[Bop] = "===" ^^^ Eq | "!==" ^^^ Ne def eqExpr: Parser[Expr] = relExpr ~ rep(eqOp ~ relExpr) ^^ { case e1~opes => (e1 /: opes) { case (e1, op~e2) => BinOp(op, e1, e2).setPos(e1.pos) } } def relOp: Parser[Bop] = "<=" ^^^ Le | "<" ^^^ Lt | ">=" ^^^ Ge | ">" ^^^ Gt def relExpr: Parser[Expr] = additiveExpr ~ rep(relOp ~ additiveExpr) ^^ { case e1~opes => (e1 /: opes) { case (e1, op~e2) => BinOp(op, e1, e2).setPos(e1.pos) } } def additiveOp: Parser[Bop] = "+" ^^^ Plus | "-" ^^^ Minus def additiveExpr: Parser[Expr] = multitiveExpr ~ rep(additiveOp ~ multitiveExpr) ^^ { case e1~opes => (e1 /: opes) { case (e1, op~e2) => BinOp(op, e1, e2).setPos(e1.pos) } } def multitiveOp: Parser[Bop] = "*" ^^^ Times | "/" ^^^ Div def multitiveExpr: Parser[Expr] = unaryExpr ~ rep(multitiveOp ~ unaryExpr) ^^ { case e1~opes => (e1 /: opes) { case (e1, op~e2) => BinOp(op, e1, e2).setPos(e1.pos) } } def unaryOp: Parser[Uop] = "-" ^^^ UMinus "!" ^^^ Not def unaryExpr: Parser[Expr] = positioned(unaryOp ~ primaryExpr ^^ { case uop~e => UnOp(uop, e) }) | callExpr def callExpr: Parser[Expr] = positioned("console.log(" ~> expr <~ ")" ^^ { Print(_) }) | positioned(functionExpr ~ rep("(" ~> expr <~ ")") ^^ { case e1~args => (e1 /: args) { case (e1, e2) => Call(e1, e2).setPos(e1.pos) } }) def functionExpr: Parser[Expr] = positioned("function" ~> opt(ident) ~ functionArg ~ functionBody ^^ { case f~x~e => Function(f, x, e) }) | primaryExpr def functionArg: Parser[String] = "(" ~> ident <~ ")" def functionBody: Parser[Expr] = positioned ("{" ~> opt(stmt) ~ ("return" ~> expr <~ opt(stmtSep)) <~ "}" ^^ { case Some(s)~e => mkSeq(s, e) case None~e => e } ) def primaryExpr: Parser[Expr] = literal | positioned(ident ^^ { Var(_) }) | "(" ~> expr <~ ")" override def ident: Parser[String] = super.ident ^? ({ case id if !reserved(id) => id }, { id => s"$id is reserved." }) | "$" ~> super.ident ^^ (s => "$" + s) def literal: Parser[Expr] = positioned(floatingPointNumber ^^ { d => Num(d.toDouble) }) | positioned("true" ^^^ Bool(true)) | positioned("false" ^^^ Bool(false)) | positioned("undefined" ^^^ Undefined) | positioned(stringLiteral ^^ (s => Str(s.substring(1, s.length() - 1)))) override def stringLiteral: Parser[String] = ("\\""+"""([^"\\p{Cntrl}\\\\]|\\\\[\\\\'"bfnrt]|\\\\[0-7]{3}|\\\\u[a-fA-F0-9]{2}|\\\\u[a-fA-F0-9]{4})*"""+"\\"").r | ("\\'"+"""([^'\\p{Cntrl}\\\\]|\\\\[\\\\'"bfnrt]|\\\\[0-7]{3}|\\\\u[a-fA-F0-9]{2}|\\\\u[a-fA-F0-9]{4})*"""+"\\'").r private def getExpr(p: ParseResult[Expr]): Expr = p match { case Success(e, _) => e case NoSuccess(msg, next) => throw new js.util.JsException(msg, next.pos) } def fromString(s: String) = getExpr(parseAll(stmt, s)) def fromFile(file: java.io.File) = { val reader = new java.io.FileReader(file) val result = parseAll(stmt, StreamReader(reader)) getExpr(result) } }
mpgarate/ProgLang-Assignments
HW3/src/main/scala/js/hw3/parse.scala
Scala
mit
5,402
package de.htwg.scala.person import com.github.nscala_time.time.Imports.DateTime object Today { def now = DateTime.now def year = now.getYear def month = now.getMonthOfYear() def day = now.getDayOfMonth() def date = new Date(year, month, day) } trait Ordered[A] { def compare(that: A): Int def <(that: A): Boolean = (this compare that) < 0 def >(that: A): Boolean = (this compare that) > 0 def <=(that: A): Boolean = (this compare that) <= 0 def >=(that: A): Boolean = (this compare that) >= 0 } case class Date(year: Int = Today.year, month: Int = Today.month, day: Int = Today.day) extends Ordered[Date] { override def compare(that: Date) = { if (this.year != that.year) this.year - that.year else if (this.month != that.month) this.month - that.month else this.day - that.day } def anniversary(nth: Int) = copy(year = year + nth) def anniversary = copy(year = Today.year) def fullYearsSince(that: Date): Int = if (this <= that) { if (this.anniversary <= that.anniversary) that.year - year else that.year - year - 1 } else 0 def fullYearsSince: Int = fullYearsSince(Today.date) override def toString = year + "-" + month + "-" + day }
markoboger/de.htwg.scala.inAction
src/main/scala/de/htwg/scala/person/Date.scala
Scala
mit
1,193
/* * Copyright (C) 2009 Lalit Pant <[email protected]> * * The contents of this file are subject to the GNU General Public License * Version 3 (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.gnu.org/copyleft/gpl.html * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * */ package net.kogics.kojo package staging import org.junit.Test import org.junit.Assert._ import net.kogics.kojo.util._ class TimekeepingTest extends StagingTestBase { val f = SpriteCanvas.instance.figure0 def peekPNode = f.dumpLastChild /* Testing manifest * * def millis = System.currentTimeMillis() * def second = Calendar.getInstance().get(Calendar.SECOND) * def minute = Calendar.getInstance().get(Calendar.MINUTE) * def hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) * def day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH) * def month = Calendar.getInstance().get(Calendar.MONTH) + 1 * def year = Calendar.getInstance().get(Calendar.YEAR) */ @Test // lalit sez: if we have more than five tests, we run out of heap space - maybe a leak in the Scala interpreter/compiler // subsystem. So we run (mostly) everything in one test def test1 = { //W //W==Timekeeping== //W //WA number of methods report the current time. //W //W //W{{{ //Wmillis // milliseconds Tester("Staging.millis") //Wsecond // second of the minute Tester( "val a = Staging.second ; println(a.isInstanceOf[Int] && a >= 0 && a < 60)", Some("$truea: Int = \\\\d+") ) //Wminute // minute of the hour Tester( "val a = Staging.minute ; println(a.isInstanceOf[Int] && a >= 0 && a < 60)", Some("$truea: Int = \\\\d+") ) //Whour // hour of the day Tester( "val a = Staging.hour ; println(a.isInstanceOf[Int] && a >= 0 && a < 24)", Some("$truea: Int = \\\\d+") ) //Wday // day of the month Tester( "val a = Staging.day ; println(a.isInstanceOf[Int] && a > 0 && a <= 31)", Some("$truea: Int = \\\\d+") ) //Wmonth // month of the year (1..12) Tester( "val a = Staging.month ; println(a.isInstanceOf[Int] && a > 0 && a <= 12)", Some("$truea: Int = \\\\d+") ) //Wyear // year C.E. Tester( "val a = Staging.year ; println(a.isInstanceOf[Int] && a > 2009)", Some("$truea: Int = \\\\d+") ) //W}}} //W } }
richardfontana/fontana2007-t
KojoEnv/test/unit/src/net/kogics/kojo/staging/TimekeepingTest.scala
Scala
gpl-3.0
2,658
import leon.lang._ object NestedFunctinAliasing1 { def f(a: Array(1,2,3,4)): Int = { def g(b: Array[Int]): Unit = { require(b.length > 0 && a.length > 0) b(0) = 10 a(0) = 17 } ensuring(_ => b(0) == 10) g(a) a(0) } ensuring(_ == 10) }
epfl-lara/leon
src/test/resources/regression/xlang/error/NestedFunctionAliasing2.scala
Scala
gpl-3.0
277
/* * Copyright (C) 2014-2015 by Nokia. * See the LICENCE.txt file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package wookie.yql.news import wookie.collector.cli.{RealConfig, KafkaPusherApp} import NewsCodecs._ object NewsCollector extends KafkaPusherApp[List[NewsEntry]](RealConfig(_))
elyast/wookie
examples/src/main/scala/wookie/yql/news/NewsCollector.scala
Scala
apache-2.0
896
package filodb.query.exec import scala.collection.mutable import monix.eval.Task import monix.reactive.Observable import filodb.core.query._ import filodb.memory.format.RowReader import filodb.query._ import filodb.query.Query.qLogger object StitchRvsExec { def merge(vectors: Seq[RangeVectorCursor]): RangeVectorCursor = { // This is an n-way merge without using a heap. // Heap is not used since n is expected to be very small (almost always just 1 or 2) new RangeVectorCursor { val bVectors = vectors.map(_.buffered) val mins = new mutable.ArrayBuffer[BufferedIterator[RowReader]](2) val noResult = new TransientRow(0, 0) override def hasNext: Boolean = bVectors.exists(_.hasNext) override def next(): RowReader = { mins.clear() var minTime = Long.MaxValue bVectors.foreach { r => if (r.hasNext) { val t = r.head.getLong(0) if (mins.isEmpty) { minTime = t mins += r } else if (t < minTime) { mins.clear() mins += r minTime = t } else if (t == minTime) { mins += r } } } if (mins.size == 1) mins.head.next() else if (mins.isEmpty) throw new IllegalStateException("next was called when no element") else { mins.foreach(it => if (it.hasNext) it.next()) // move iterator forward noResult.timestamp = minTime noResult.value = Double.NaN // until we have a different indicator for "unable-to-calculate" use NaN noResult } } override def close(): Unit = vectors.foreach(_.close()) } } } /** * Use when data for same time series spans multiple shards, or clusters. */ final case class StitchRvsExec(queryContext: QueryContext, dispatcher: PlanDispatcher, children: Seq[ExecPlan]) extends NonLeafExecPlan { require(children.nonEmpty) protected def args: String = "" protected def compose(childResponses: Observable[(QueryResponse, Int)], firstSchema: Task[ResultSchema], querySession: QuerySession): Observable[RangeVector] = { qLogger.debug(s"StitchRvsExec: Stitching results:") val stitched = childResponses.map { case (QueryResult(_, _, result), _) => result case (QueryError(_, ex), _) => throw ex }.toListL.map(_.flatten).map { srvs => val groups = srvs.groupBy(_.key.labelValues) groups.mapValues { toMerge => val rows = StitchRvsExec.merge(toMerge.map(_.rows)) val key = toMerge.head.key IteratorBackedRangeVector(key, rows) }.values }.map(Observable.fromIterable) Observable.fromTask(stitched).flatten } // overriden since stitch can reduce schemas with different vector lengths as long as the columns are same override def reduceSchemas(rs: ResultSchema, resp: QueryResult): ResultSchema = IgnoreFixedVectorLenAndColumnNamesSchemaReducer.reduceSchema(rs, resp) } /** * Range Vector Transformer version of StitchRvsExec */ final case class StitchRvsMapper() extends RangeVectorTransformer { def apply(source: Observable[RangeVector], querySession: QuerySession, limit: Int, sourceSchema: ResultSchema, paramResponse: Seq[Observable[ScalarRangeVector]]): Observable[RangeVector] = { qLogger.debug(s"StitchRvsMapper: Stitching results:") val stitched = source.toListL.map { rvs => val groups = rvs.groupBy(_.key) groups.mapValues { toMerge => val rows = StitchRvsExec.merge(toMerge.map(_.rows)) val key = toMerge.head.key IteratorBackedRangeVector(key, rows) }.values }.map(Observable.fromIterable) Observable.fromTask(stitched).flatten } override protected[query] def args: String = "" override def funcParams: Seq[FuncArgs] = Nil }
tuplejump/FiloDB
query/src/main/scala/filodb/query/exec/StitchRvsExec.scala
Scala
apache-2.0
4,009
/* * This file is part of the Kompics component model runtime. * * Copyright (C) 2009 Swedish Institute of Computer Science (SICS) * Copyright (C) 2009 Royal Institute of Technology (KTH) * * Kompics 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 2 * 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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package se.sics.kompics import org.scalatest._ class MatcherTestScala extends sl.KompicsUnitSuite { import sl.KompicsUnitSuite._ test("ClassMatchers should work in Scala") { val ew = new EventWaiter; val (cd, init) = setup({ cd => val req = cd.child(classOf[DataParent]); val prov = cd.child(classOf[DataChild]); //req -- TestPort ++ prov; sl.`!connect`[DataPort](prov -> req); }, ew); ew { Kompics.createAndStart(cd, init); } ew { event => event should equal(Start.EVENT); } ew { event => event shouldBe a[DataContainer]; val dc = event.asInstanceOf[DataContainer]; dc.data shouldBe a[CData]; } ew.await(); Kompics.shutdown(); } } trait Data; class CData extends Data {} class FData extends Data {} class DataContainer(val data: Data) extends PatternExtractor[Class[Object], Data] { override def extractPattern(): Class[Object] = data.getClass.asInstanceOf[Class[Object]]; override def extractValue(): Data = data; } class DataPort extends PortType { indication(classOf[DataContainer]); } class DataParent extends ComponentDefinition with sl.EventTester { val dp = requires(classOf[DataPort]); val child = create(classOf[DataChild], Init.NONE); connect(dp.getPair(), child.getPositive(classOf[DataPort]), Channel.TWO_WAY); val dataHandler = new ClassMatchedHandler[CData, DataContainer]() { override def handle(content: CData, context: DataContainer): Unit = { if ((content != null) && (context != null)) { check(context); } else { throw new RuntimeException(s"Expected CData not ${content} and DataContainer not ${context}"); } } }; val falseDataHandler = new ClassMatchedHandler[FData, DataContainer]() { override def handle(content: FData, context: DataContainer): Unit = { throw new RuntimeException("Only CData handlers should be triggered, not FData!"); } }; subscribe(falseDataHandler, dp); subscribe(dataHandler, dp); } class DataChild extends ComponentDefinition with sl.EventTester { val dp = provides(classOf[DataPort]); val startHandler = new Handler[Start]() { override def handle(event: Start): Unit = { check(event); trigger(new DataContainer(new CData()), dp); } }; subscribe(startHandler, control); }
kompics/kompics-scala
core/src/test/scala/se/sics/kompics/MatcherTestScala.scala
Scala
gpl-2.0
3,267
/** * Global Sensor Networks (GSN) Source Code * Copyright (c) 2006-2016, Ecole Polytechnique Federale de Lausanne (EPFL) * * This file is part of GSN. * * GSN 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. * * GSN 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 GSN. If not, see <http://www.gnu.org/licenses/>. * * File: src/ch/epfl/gsn/data/format/TimeFormat.scala * * @author Jean-Paul Calbimonte * */ package ch.epfl.gsn.data.format import org.joda.time.format.ISODateTimeFormat import org.joda.time.format.DateTimeFormat import scala.util.Try import org.joda.time.format.DateTimeFormatter object TimeFormats { def formatTime(t:Long)(implicit timeFormat:Option[String])=timeFormat match{ case Some("unixTime") | None => t case _ => getTimeFormat(timeFormat).withZoneUTC().print(t) } def formatTime(t:Long, timeFormat:DateTimeFormatter)= timeFormat.print(t) private def getTimeFormat(tf:Option[String])={// e.g. yyyyMMdd tf match { case Some("iso8601") => ISODateTimeFormat.dateTimeNoMillis() case Some("iso8601ms") => ISODateTimeFormat.dateTime() case Some(f) => Try(DateTimeFormat.forPattern(f)) .recover{case e => println("error here "+e) throw new IllegalArgumentException(s"Invalid time format: $f ${e.getMessage}")}.get case None => ISODateTimeFormat.dateHourMinuteSecond() } } }
LSIR/gsn
gsn-tools/src/main/scala/ch/epfl/gsn/data/format/TimeFormats.scala
Scala
gpl-3.0
1,863
/* *\\ ** \\ \\ / _) \\ \\ / \\ | ** ** \\ \\ / | __ \\ _ \\ __| \\ \\ / |\\/ | ** ** \\ \\ / | | | __/ | \\ \\ / | | ** ** \\_/ _| .__/ \\___| _| \\_/ _| _| ** ** _| ** ** ** ** ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ** ** ** ** http://www.vipervm.org ** ** GPLv3 ** \\* */ package org.vipervm.platform.opencl import org.vipervm.bindings.opencl._ /** * Program is a wrapper for cl_program. * * It stores a list of built programs for different devices */ class OpenCLProgram(val source:String) { private var peers: Map[OpenCLProcessor,Program] = Map.empty private var compatibleDevices: Map[OpenCLProcessor,Boolean] = Map.empty /** * Indicate whether the program can be executed on the given device (None if we don't know) * * Without any further information, we can only know it after trying * to compile it for the device. * Inherited classes overload this method to enhance this */ def isCompatibleWith(device:OpenCLProcessor): Option[Boolean] = compatibleDevices.get(device) /** * Try to compile the program for the given device. * TODO: program should be compiled once for every possible target */ def compileFor(device:OpenCLProcessor): Program = { val t = isCompatibleWith(device).getOrElse(true) if (!t) sys.error("This program isn't compatible with the specified device") try { val p = new Program(device.context, source) p.build(List(device.peer)) peers += (device -> p) compatibleDevices += (device -> true) p } catch { case e@OpenCLBuildProgramException(err,prog,devs) => { println(e.buildInfo(device.peer).log) compatibleDevices += (device -> false) throw e } } } /** * Return the compiled program for the device */ def get(device:OpenCLProcessor): Program = peers.get(device) match { case Some(p) => p case None => compileFor(device) } }
hsyl20/Scala_ViperVM
src/main/scala/org/vipervm/platform/opencl/Program.scala
Scala
gpl-3.0
2,306
package com.softwaremill.codebrag.rest import com.softwaremill.codebrag.finders.browsingcontext.UserBrowsingContextFinder import com.softwaremill.codebrag.service.user.Authenticator import com.softwaremill.codebrag.usecases.{UpdateUserBrowsingContextForm, UpdateUserBrowsingContextUseCase} class BrowsingContextServlet(val authenticator: Authenticator, contextFinder: UserBrowsingContextFinder, updateContext: UpdateUserBrowsingContextUseCase) extends JsonServletWithAuthentication { get("/") { haltIfNotAuthenticated() contextFinder.findAll(user.id) } get("/:repo") { haltIfNotAuthenticated() val repo = params("repo") contextFinder.find(user.id, repo) } put("/:repo") { haltIfNotAuthenticated() val form = UpdateUserBrowsingContextForm(user.id, params("repo"), extractReq[String]("branch")) updateContext.execute(form) } } object BrowsingContextServlet { val MappingPath = "browsing-context" }
softwaremill/codebrag
codebrag-rest/src/main/scala/com/softwaremill/codebrag/rest/BrowsingContextServlet.scala
Scala
agpl-3.0
949
package truerss.db.driver import java.time.{Instant, LocalDateTime, ZoneId, ZoneOffset, ZonedDateTime} import java.util.Date import slick.jdbc.{JdbcProfile, JdbcType} import slick.sql.SqlProfile.ColumnOption.{NotNull, Nullable, SqlType} import play.api.libs.json._ import slick.ast.BaseTypedType import truerss.db._ /** * Created by mike on 6.5.17. */ case class CurrentDriver(profile: JdbcProfile, tableNames: TableNames) { import profile.api._ object DateSupport { implicit val javaTimeMapper: JdbcType[LocalDateTime] = MappedColumnType.base[LocalDateTime, Long]( d => d.withNano(0).toInstant(ZoneOffset.UTC).getEpochSecond, d => LocalDateTime.ofInstant(Instant.ofEpochSecond(d), ZoneOffset.UTC) .withNano(0) ) } object StateSupport { implicit val sourceStateMapper: JdbcType[SourceState] with BaseTypedType[SourceState] = MappedColumnType.base[SourceState, Byte]( { case SourceStates.Neutral => 0 case SourceStates.Enable => 1 case SourceStates.Disable => 2 }, { case 0 => SourceStates.Neutral case 1 => SourceStates.Enable case 2 => SourceStates.Disable } ) } object SettingValueSupport { implicit val inputValueMapper: JdbcType[SettingValue] with BaseTypedType[SettingValue] = MappedColumnType.base[SettingValue, String]( value => Json.stringify(DbSettingJsonFormats.settingValueFormat.writes(value)), from => { DbSettingJsonFormats.settingValueFormat.reads(Json.parse(from)) .getOrElse(SelectableValue.empty) } ) } class Sources(tag: Tag) extends Table[Source](tag, tableNames.sources) { import StateSupport._ def id = column[Long]("id", O.PrimaryKey, O.AutoInc) def url = column[String]("url", O.Length(CurrentDriver.defaultLength)) def name = column[String]("name", O.Length(CurrentDriver.defaultLength)) def interval = column[Int]("interval", O.Default[Int](86400)) def state = column[SourceState]("state") def normalized = column[String]("normalized") def lastUpdate = column[LocalDateTime]("lastupdate") def count = column[Int]("count", O.Default(0)) // ignored def byNameIndex = index("idx_name", name) def byUrlIndex = index("idx_url", url) def * = (id.?, url, name, interval, state, normalized, lastUpdate, count) <> (Source.tupled, Source.unapply) } class Feeds(tag: Tag) extends Table[Feed](tag, tableNames.feeds) { def id = column[Long]("id", O.PrimaryKey, O.AutoInc) def sourceId = column[Long]("source_id", NotNull) def url = column[String]("url") def title = column[String]("title", SqlType("TEXT")) def author = column[String]("author") def publishedDate = column[LocalDateTime]("published_date") def description = column[String]("description", Nullable, SqlType("TEXT")) def content = column[String]("content", Nullable, SqlType("TEXT")) def enclosure = column[String]("enclosure", Nullable, SqlType("TEXT")) def normalized = column[String]("normalized") def favorite = column[Boolean]("favorite", O.Default(false)) def read = column[Boolean]("read", O.Default(false)) def delete = column[Boolean]("delete", O.Default(false)) def bySourceIndex = index("idx_source", sourceId) def byReadIndex = index("idx_read", read) def bySourceAndReadIndex = index("idx_source_read", (sourceId, read)) def byFavoriteIndex = index("idx_favorites", favorite) def bySourceAndFavorite = index("idx_source_favorite", (sourceId, favorite)) def * = (id.?, sourceId, url, title, author, publishedDate, description.?, content.?, enclosure.?, normalized, favorite, read, delete) <> (Feed.tupled, Feed.unapply) def source = foreignKey("source_fk", sourceId, query.sources)(_.id, onUpdate = ForeignKeyAction.Restrict, onDelete = ForeignKeyAction.Cascade) } class Versions(tag: Tag) extends Table[Version](tag, tableNames.versions) { def id = column[Long]("id", O.PrimaryKey, O.AutoInc) def fact = column[String]("fact", SqlType("TEXT")) def when = column[LocalDateTime]("when", O.Default(LocalDateTime.now())) override def * = (id, fact, when) <> (Version.tupled, Version.unapply) } class PredefinedSettingsTable(tag: Tag) extends Table[PredefinedSettings](tag, tableNames.predefinedSettings) { import SettingValueSupport._ def key = column[String]("key", O.Unique, O.Length(25)) def description = column[String]("description") def value = column[SettingValue]("value") def byKeyIndex = index("idx_key", key) override def * = (key, description, value) <> (PredefinedSettings.tupled, PredefinedSettings.unapply) } class UserSettingsTable(tag: Tag) extends Table[UserSettings](tag, tableNames.userSettings) { def key = column[String]("key", O.Unique, O.PrimaryKey) def description = column[String]("description") def valueInt = column[Option[Int]]("valueInt") def valueBoolean = column[Option[Boolean]]("valueBoolean") def valueString = column[Option[String]]("valueString") override def * = (key, description, valueInt, valueBoolean, valueString) <> (UserSettings.tupled, UserSettings.unapply) } class PluginSourcesTable(tag: Tag) extends Table[PluginSource](tag, tableNames.pluginSources) { def id = column[Long]("id", O.PrimaryKey) def url = column[String]("url") override def * = (id.?, url) <> (PluginSource.tupled, PluginSource.unapply) } class SourceStatusesTable(tag: Tag) extends Table[SourceStatus](tag, tableNames.sourceStatuses) { def sourceId = column[Long]("sourceId", O.Unique) def errorCount = column[Int]("errorsCount") override def * = (sourceId, errorCount) <> (SourceStatus.tupled, SourceStatus.unapply) } object query { lazy val sources = TableQuery[Sources] lazy val feeds = TableQuery[Feeds] def bySource(sourceId: Long): Query[Feeds, Feed, Seq] = { TableQuery[Feeds].filter(_.sourceId === sourceId) } def byFeed(feedId: Long): Query[Feeds, Feed, Seq] = { TableQuery[Feeds].filter(_.id === feedId) } lazy val versions = TableQuery[Versions] lazy val predefinedSettings = TableQuery[PredefinedSettingsTable] lazy val userSettings = TableQuery[UserSettingsTable] lazy val pluginSources = TableQuery[PluginSourcesTable] lazy val sourceStatuses = TableQuery[SourceStatusesTable] implicit class FeedsTQExt(val x: TableQuery[Feeds]) { def unreadOnly: Query[Feeds, Feed, Seq] = { x.filter(_.read === false) } def isFavorite: Query[Feeds, Feed, Seq] = { x.filter(_.favorite === true) } } implicit class FeedsQExt(val x: Query[Feeds, Feed, Seq]) { def unreadOnly: Query[Feeds, Feed, Seq] = { x.filter(_.read === false) } def isFavorite: Query[Feeds, Feed, Seq] = { x.filter(_.favorite === true) } } } } object CurrentDriver { final val defaultLength = 256 } case class TableNames(sources: String, feeds: String, versions: String, predefinedSettings: String, userSettings: String, pluginSources: String, sourceStatuses: String, ) object TableNames { val default = TableNames( sources = "sources", feeds = "feeds", versions = "versions", predefinedSettings = "predefined_settings", userSettings = "user_settings", pluginSources = "plugin_sources", sourceStatuses = "source_statuses" ) def withPrefix(prefix: String): TableNames = { TableNames( sources = s"${prefix}_sources", feeds = s"${prefix}_feeds", versions = s"${prefix}_versions", predefinedSettings = s"${prefix}_predefined_settings", userSettings = s"${prefix}_user_settings", pluginSources = s"${prefix}_plugin_sources", sourceStatuses = s"${prefix}_source_statuses" ) } }
truerss/truerss
src/main/scala/truerss/db/driver/CurrentDriver.scala
Scala
mit
8,046
package main.scala.overlapping.containers import org.apache.spark.rdd.RDD import org.joda.time.DateTime import scala.math.Ordering import scala.reflect.ClassTag /** * Created by Francois Belletti on 8/6/15. * * This class samples out from an RDD and computes the approximate intervals * that should be used for an even partitioning. * */ object IntervalSampler{ /** * Sample out a small data set from the complete data and * devise intervals so that about the same number of data points * belong to each interval. * * @param nIntervals Number of intervals desired * @param sampleSize Number of samples used to decide interval lengths * @param sourceRDD Data * @param count If n samples is already known, avoids recomputation * @param withReplacement Sample with or without replacement * @return An array of intervals (begin, end) */ def apply[IndexT : Ordering : ClassTag, ValueT: ClassTag]( nIntervals: Int, sampleSize: Int, sourceRDD: RDD[(IndexT, ValueT)], count: Option[Long], withReplacement: Boolean = false): Array[(IndexT, IndexT)] = { val fraction = sampleSize.toDouble / count.getOrElse(sourceRDD.count()).toDouble val stride = sampleSize / nIntervals if(stride >= sampleSize){ return Array((sourceRDD.map(_._1).min(), sourceRDD.map(_._1).max())) } val sortedKeys = sourceRDD .sample(withReplacement, fraction) .map(_._1) .sortBy(x => x) .collect() .sliding(1, stride) .map(_.head) .toArray sortedKeys.zip(sortedKeys.drop(1)) } }
bellettif/sparkGeoTS
sparkTS/src/main/scala/overlapping/containers/IntervalSampler.scala
Scala
bsd-3-clause
1,598
/* * 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.azure.documentdb import com.datamountaineer.streamreactor.connect.azure.documentdb.config.DocumentDbSinkSettings import com.microsoft.azure.documentdb.{ConnectionPolicy, DocumentClient} import org.apache.http.HttpHost /** * Creates an instance of Azure DocumentClient class */ object DocumentClientProvider { def get(settings: DocumentDbSinkSettings): DocumentClient = { val policy = ConnectionPolicy.GetDefault() settings.proxy.map(HttpHost.create).foreach(policy.setProxy) new DocumentClient(settings.endpoint, settings.masterKey, policy, settings.consistency) } }
CodeSmell/stream-reactor
kafka-connect-azure-documentdb/src/main/scala/com/datamountaineer/streamreactor/connect/azure/documentdb/DocumentClientProvider.scala
Scala
apache-2.0
1,255
package com.twitter.finatra.http.internal.request import com.twitter.finagle.http.{ParamMap, Request, RequestProxy} private[http] class RequestWithRouteParams( wrapped: Request, incomingParams: Map[String, String]) extends RequestProxy { override lazy val params: ParamMap = { new RouteParamMap( super.params, incomingParams) } def request: Request = wrapped }
syamantm/finatra
http/src/main/scala/com/twitter/finatra/http/internal/request/RequestWithRouteParams.scala
Scala
apache-2.0
393
package io.ubiqesh.uplink.disruptor.translator import io.ubiqesh.uplink.vertx.event.StateChangeEvent import scala.reflect.BeanProperty import org.vertx.java.core.json.JsonObject class UbiqeshEventTranslator(private var stateChangeEvent: StateChangeEvent) extends com.lmax.disruptor.EventTranslator[StateChangeEvent] { @BeanProperty var sequence: Long = _ override def translateTo(event: StateChangeEvent, sequence: Long) { io.ubiqesh.uplink.vertx.json.Node.clear(event) event.mergeIn(new JsonObject(stateChangeEvent.toString)) this.sequence = sequence } }
ubiqesh/ubiqesh
uplink/src/main/scala/io/ubiqesh/uplink/disruptor/translator/UbiqeshEventTranslator.scala
Scala
apache-2.0
580
/* * Copyright (c) 2014-2021 by The Monix Project Developers. * See the project homepage at: https://monix.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package monix.execution.internal import monix.execution.atomic.PaddingStrategy import monix.execution.atomic.AtomicAny import monix.execution.internal.GenericSemaphore.Listener import scala.annotation.tailrec import scala.collection.immutable.Queue private[monix] abstract class GenericSemaphore[CancelToken] protected (provisioned: Long, ps: PaddingStrategy) extends Serializable { import GenericSemaphore.State require(provisioned >= 0, "provisioned >= 0") private[this] val stateRef = AtomicAny.withPadding(GenericSemaphore.initialState(provisioned), ps) protected def emptyCancelable: CancelToken protected def makeCancelable(f: Listener[Unit] => Unit, p: Listener[Unit]): CancelToken protected final def unsafeAvailable(): Long = stateRef.get().available protected final def unsafeCount(): Long = stateRef.get().count @tailrec protected final def unsafeAcquireN(n: Long, await: Listener[Unit]): CancelToken = { assert(n >= 0, "n must be positive") stateRef.get() match { case current @ State(available, awaitPermits, _) => val stillAvailable = available - n if (stillAvailable >= 0) { val update = current.copy(available = stillAvailable) if (!stateRef.compareAndSet(current, update)) unsafeAcquireN(n, await) // retry else { await(Constants.eitherOfUnit) emptyCancelable } } else { val tuple = (-stillAvailable, await) val update = current.copy(available = 0, awaitPermits = awaitPermits.enqueue(tuple)) if (!stateRef.compareAndSet(current, update)) unsafeAcquireN(n, await) // retry else makeCancelable(cancelAcquisition(n, isAsync = false), await) } } } @tailrec protected final def unsafeAsyncAcquireN(n: Long, await: Listener[Unit]): CancelToken = { assert(n >= 0, "n must be positive") stateRef.get() match { case current @ State(available, awaitPermits, _) => val stillAvailable = available - n if (stillAvailable >= 0) { val update = current.copy(available = stillAvailable) if (!stateRef.compareAndSet(current, update)) unsafeAsyncAcquireN(n, await) // retry else { await(Constants.eitherOfUnit) makeCancelable(cancelAcquisition(n, isAsync = true), await) } } else { val tuple = (-stillAvailable, await) val update = current.copy(available = 0, awaitPermits = awaitPermits.enqueue(tuple)) if (!stateRef.compareAndSet(current, update)) unsafeAsyncAcquireN(n, await) // retry else makeCancelable(cancelAcquisition(n, isAsync = true), await) } } } @tailrec protected final def unsafeTryAcquireN(n: Long): Boolean = stateRef.get() match { case current @ State(available, _, _) => val stillAvailable = available - n if (stillAvailable >= 0) { val update = current.copy(available = stillAvailable) if (!stateRef.compareAndSet(current, update)) unsafeTryAcquireN(n) // retry else true } else { false } } @tailrec protected final def unsafeReleaseN(n: Long): Unit = { assert(n >= 0, "n must be positive") stateRef.get() match { case current @ State(available, promises, awaitReleases) => // No promises made means we should only increase if (promises.isEmpty) { val available2 = available + n val triggeredReleases = current.triggerAwaitReleases(available2) var promisesAwaitingRelease: List[Listener[Unit]] = Nil val awaitReleases2 = triggeredReleases match { case None => awaitReleases case Some((list, newValue)) => promisesAwaitingRelease = list newValue } val update = current.copy( available = available2, awaitReleases = awaitReleases2 ) if (!stateRef.compareAndSet(current, update)) unsafeReleaseN(n) else if (promisesAwaitingRelease ne Nil) triggerAll(promisesAwaitingRelease) } else { val ((c, cb), newPromises) = if (promises.nonEmpty) promises.dequeue else (null, promises) if (c <= n) { val rem = n - c val update = current.copy(awaitPermits = newPromises) if (!stateRef.compareAndSet(current, update)) unsafeReleaseN(n) else { cb(Constants.eitherOfUnit) // Keep going - try to release another one if (rem > 0) unsafeReleaseN(rem) } } else { val rem = c - n val update = current.copy(awaitPermits = (rem, cb) +: newPromises) if (!stateRef.compareAndSet(current, update)) unsafeReleaseN(n) } } } } @tailrec protected final def unsafeAwaitAvailable(n: Long, await: Listener[Unit]): CancelToken = stateRef.get() match { case current @ State(available, _, awaitReleases) => if (available >= n) { await(Constants.eitherOfUnit) emptyCancelable } else { val update = current.copy(awaitReleases = (n -> await) :: awaitReleases) if (!stateRef.compareAndSet(current, update)) unsafeAwaitAvailable(n, await) else makeCancelable(cancelAwaitRelease, await) } } private final def triggerAll(promises: Seq[Listener[Unit]]): Unit = { val cursor = promises.iterator while (cursor.hasNext) cursor.next().apply(Constants.eitherOfUnit) } private[this] val cancelAwaitRelease: (Listener[Unit] => Unit) = { @tailrec def loop(p: Listener[Unit]): Unit = { val current: State = stateRef.get() val update = current.removeAwaitReleaseRef(p) if (!stateRef.compareAndSet(current, update)) loop(p) // retry } loop } private[this] def cancelAcquisition(n: Long, isAsync: Boolean): (Listener[Unit] => Unit) = { @tailrec def loop(permit: Listener[Unit]): Unit = { val current: State = stateRef.get() current.awaitPermits.find(_._2 eq permit) match { case None => if (isAsync) unsafeReleaseN(n) case Some((m, _)) => val update = current.removeAwaitPermitRef(permit) if (!stateRef.compareAndSet(current, update)) loop(permit) // retry else if (n > m) unsafeReleaseN(n - m) } } loop } } private[monix] object GenericSemaphore { /** Internal. Reusable initial state. */ private def initialState(available: Long): State = State(available, Queue.empty, Nil) /** Callback type used internally. */ type Listener[A] = Either[Throwable, A] => Unit /** Internal. For keeping the state of our * [[GenericSemaphore]] in an atomic reference. */ private final case class State( available: Long, awaitPermits: Queue[(Long, Listener[Unit])], awaitReleases: List[(Long, Listener[Unit])]) { def count: Long = { if (available > 0) available else -awaitPermits.map(_._1).sum } def removeAwaitPermitRef(p: Listener[Unit]): State = copy(awaitPermits = awaitPermits.filter { case (_, ref) => ref ne p }) def removeAwaitReleaseRef(p: Listener[Unit]): State = copy(awaitReleases = awaitReleases.filter { case (_, ref) => ref ne p }) def triggerAwaitReleases(available2: Long): Option[(List[Listener[Unit]], List[(Long, Listener[Unit])])] = { assert(available2 >= 0, "n >= 0") if (available2 == 0) None else awaitReleases match { case Nil => None case list => val cursor = list.iterator var toComplete = List.empty[Listener[Unit]] var toKeep = List.empty[(Long, Listener[Unit])] while (cursor.hasNext) { val ref = cursor.next() val (awaits, p) = ref if (awaits <= available2) toComplete = p :: toComplete else toKeep = ref :: toKeep } Some((toComplete, toKeep)) } } } }
monix/monix
monix-execution/shared/src/main/scala/monix/execution/internal/GenericSemaphore.scala
Scala
apache-2.0
9,023
/* * Copyright 2015 Webtrends (http://www.webtrends.com) * * See the LICENCE.txt file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webtrends.service.rest import akka.util.Timeout import com.webtrends.harness.command.{CommandException, Command, CommandResponse, CommandBean} import com.webtrends.harness.component.ComponentHelper import com.webtrends.harness.component.spray.route.{SprayHead, SprayOptions, SprayGet} import com.webtrends.service.{PersonService, Person} import spray.http.HttpEntity import spray.httpx.marshalling.Marshaller import scala.concurrent.{Promise, Future} import scala.concurrent.duration._ import scala.util.{Failure, Success} class Read extends Command with SprayGet with SprayOptions with SprayHead with ComponentHelper { implicit val executionContext = context.dispatcher implicit val timeout = Timeout(2 seconds) override def path: String = "/person/$name" override implicit def OutputMarshaller[T <:AnyRef] = Marshaller.of[T](PersonService.`application/vnd.webtrends.person`) { (value, contentType, ctx) => val Person(name, age) = value val string = "Person: %s, %s".format(name, age) ctx.marshalTo(HttpEntity(contentType, string)) } /** * Name of the command that will be used for the actor name * * @return */ override def commandName: String = Read.CommandName /** * The primary entry point for the command, the actor for this command * will ignore all other messaging and only execute through this * * @return */ def execute[T](bean: Option[CommandBean]): Future[CommandResponse[T]] = { val p = Promise[CommandResponse[T]] bean match { case Some(b) => getComponent("wookiee-cache-memcache") onComplete { case Success(actor) => val personName = b("name").asInstanceOf[String] Person(personName).readFromCache(actor) onComplete { case Success(person) => person match { case Some(per) => p success CommandResponse[T](Some(per.asInstanceOf[T]), PersonService.PersonMimeType) case None => p failure CommandException("PersonRead", s"Person not found with name [$personName]") } case Failure(f) => p failure f } case Failure(f) => p failure f } case None => p failure new CommandException("Read", "Cache not initialized") } p.future } } object Read { def CommandName = "Read" }
mjwallin1/wookiee-spray
example-rest/src/main/scala/com/webtrends/service/rest/Read.scala
Scala
apache-2.0
3,119
import stainless.lang.StaticChecks._ object StaticChecks2 { def add(n: BigInt, m: BigInt): BigInt = { require(n >= 0 && m >= 0) var res = if(m == 0) n else add(n, m-1) + 1 assert(res >= 0) res } ensuring((res: BigInt) => res >= 0) }
epfl-lara/stainless
frontends/benchmarks/verification/valid/MicroTests/StaticChecks2.scala
Scala
apache-2.0
257
package $basePackageName$; import io.skysail.server.restlet.resources.EntityServerResource import io.skysail.domain.GenericIdentifiable import org.slf4j.LoggerFactory class OAuth2CallbackResource extends EntityServerResource[GenericIdentifiable] { val log = LoggerFactory.getLogger(classOf[OAuth2CallbackResource]) def getEntity(): GenericIdentifiable = { val storedState = getContext().getAttributes().get(TemplateApplication.TEMPLATE_AUTH_STATE).asInstanceOf[String]; // if (state == null || !state.equals(storedState)) { // log.warn("state does not match when logging in to spotify, redirecting to root"); //// Reference redirectTo = new Reference("/"); //// getResponse().redirectSeeOther(redirectTo); //// return null; // } // getContext().getAttributes().remove(TemplateApplication.TEMPLATE_AUTH_STATE); //String callbackJson = application.getSpotifyApi().getToken(code); //ApiServices.setAccessData(getPrincipal(), callbackJson); var target = getContext().getAttributes().get("oauthTarget").asInstanceOf[String] target += "?code=" + getQueryValue("code") + "&state=" + getQueryValue("state"); log.info("redirecting to '{}'", target); getResponse().redirectTemporary(target); return null; } }
evandor/skysail
skysail.oauth.clientapp.scala.template/resources/template/$srcDir$/$basePackageDir$/OAuth2CallbackResource.scala
Scala
apache-2.0
1,330
package org.opennetworkinsight /** * Parses arguments for the suspicious connections analysis. */ object SuspiciousConnectsArgumentParser { case class SuspiciousConnectsConfig(analysis: String = "", inputPath: String = "", scoresFile: String = "", duplicationFactor: Int = 1, modelFile: String = "", topicDocumentFile: String = "", topicWordFile: String = "", mpiPreparationCmd: String = "", mpiCmd: String = "", mpiProcessCount: String = "", mpiTopicCount: String = "", localPath: String = "", localUser: String = "", ldaPath: String = "", dataSource: String = "", nodes: String = "", hdfsScoredConnect: String = "", threshold: Double = 1.0d, maxResults: Int = -1, outputDelimiter: String = "\t") val parser: scopt.OptionParser[SuspiciousConnectsConfig] = new scopt.OptionParser[SuspiciousConnectsConfig]("LDA") { head("LDA Process", "1.1") opt[String]('z', "analysis").required().valueName("< flow | proxy | dns >"). action((x, c) => c.copy(analysis = x)). text("choice of suspicious connections analysis to perform") opt[String]('i', "input").required().valueName("<hdfs path>"). action((x, c) => c.copy(inputPath = x)). text("HDFS path to input") opt[String]('f', "feedback").valueName("<local file>"). action((x, c) => c.copy(scoresFile = x)). text("the local path of the file that contains the feedback scores") opt[Int]('d', "dupfactor").valueName("<non-negative integer>"). action((x, c) => c.copy(duplicationFactor = x)). text("duplication factor controlling how to downgrade non-threatening connects from the feedback file") opt[String]('m', "model").required().valueName("<local file>"). action((x, c) => c.copy(modelFile = x)). text("Model file location") opt[String]('o', "topicdoc").required().valueName("<local file>"). action((x, c) => c.copy(topicDocumentFile = x)). text("final.gamma file location") opt[String]('w', "topicword").required().valueName("<local file>"). action((x, c) => c.copy(topicWordFile = x)). text("final.beta file location") opt[String]('p', "mpiprep").valueName("<mpi command>"). action((x, c) => c.copy(mpiPreparationCmd = x)). text("MPI preparation command") opt[String]('c', "mpicmd").required().valueName("<mpi command>"). action((x, c) => c.copy(mpiCmd = x)). text("MPI command") opt[String]('t', "proccount").required().valueName("<mpi param>"). action((x, c) => c.copy(mpiProcessCount = x)). text("MPI process count") opt[String]('u', "topiccount").required().valueName("<mpi param>"). action((x, c) => c.copy(mpiTopicCount = x)). text("MPI topic count") opt[String]('l', "lpath").required().valueName("<local path>"). action((x, c) => c.copy(localPath = x)). text("Local Path") opt[String]('a', "ldapath").required().valueName("<local path>"). action((x, c) => c.copy(ldaPath = x)). text("LDA Path") opt[String]('r', "luser").required().valueName("<local path>"). action((x, c) => c.copy(localUser = x)). text("Local user path") opt[String]('n', "nodes").required().valueName("<input param>"). action((x, c) => c.copy(nodes = x)). text("Node list") opt[String]('s', "scored").required().valueName("<hdfs path>"). action((x, c) => c.copy(hdfsScoredConnect = x)). text("HDFS path for results") opt[Double]('e', "threshold").required().valueName("float64"). action((x, c) => c.copy(threshold = x)). text("probability threshold for declaring anomalies") opt[Int]('k', "maxresults").required().valueName("integer"). action((x, c) => c.copy(maxResults = x)). text("number of most suspicious connections to return") opt[String]('b', "delimiter").optional().valueName("character"). action((x, c) => c.copy(outputDelimiter = x)). text("number of most suspicious connections to return") } }
Open-Network-Insight/oni-ml
src/main/scala/org/opennetworkinsight/SuspiciousConnectsArgumentParser.scala
Scala
apache-2.0
4,694
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.catalyst import java.beans.{Introspector, PropertyDescriptor} import java.lang.{Iterable => JIterable} import java.lang.reflect.Type import java.util.{Iterator => JIterator, List => JList, Map => JMap} import scala.language.existentials import com.google.common.reflect.TypeToken import org.apache.spark.sql.catalyst.analysis.{GetColumnByOrdinal, UnresolvedAttribute, UnresolvedExtractValue} import org.apache.spark.sql.catalyst.expressions._ import org.apache.spark.sql.catalyst.expressions.objects._ import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, DateTimeUtils, GenericArrayData} import org.apache.spark.sql.types._ import org.apache.spark.unsafe.types.UTF8String /** * Type-inference utilities for POJOs and Java collections. */ object JavaTypeInference { private val iterableType = TypeToken.of(classOf[JIterable[_]]) private val mapType = TypeToken.of(classOf[JMap[_, _]]) private val listType = TypeToken.of(classOf[JList[_]]) private val iteratorReturnType = classOf[JIterable[_]].getMethod("iterator").getGenericReturnType private val nextReturnType = classOf[JIterator[_]].getMethod("next").getGenericReturnType private val keySetReturnType = classOf[JMap[_, _]].getMethod("keySet").getGenericReturnType private val valuesReturnType = classOf[JMap[_, _]].getMethod("values").getGenericReturnType /** * Infers the corresponding SQL data type of a JavaBean class. * @param beanClass Java type * @return (SQL data type, nullable) */ def inferDataType(beanClass: Class[_]): (DataType, Boolean) = { inferDataType(TypeToken.of(beanClass)) } /** * Infers the corresponding SQL data type of a Java type. * @param beanType Java type * @return (SQL data type, nullable) */ private[sql] def inferDataType(beanType: Type): (DataType, Boolean) = { inferDataType(TypeToken.of(beanType)) } /** * Infers the corresponding SQL data type of a Java type. * @param typeToken Java type * @return (SQL data type, nullable) */ private def inferDataType(typeToken: TypeToken[_], seenTypeSet: Set[Class[_]] = Set.empty) : (DataType, Boolean) = { typeToken.getRawType match { case c: Class[_] if c.isAnnotationPresent(classOf[SQLUserDefinedType]) => (c.getAnnotation(classOf[SQLUserDefinedType]).udt().newInstance(), true) case c: Class[_] if UDTRegistration.exists(c.getName) => val udt = UDTRegistration.getUDTFor(c.getName).get.newInstance() .asInstanceOf[UserDefinedType[_ >: Null]] (udt, true) case c: Class[_] if c == classOf[java.lang.String] => (StringType, true) case c: Class[_] if c == classOf[Array[Byte]] => (BinaryType, true) case c: Class[_] if c == java.lang.Short.TYPE => (ShortType, false) case c: Class[_] if c == java.lang.Integer.TYPE => (IntegerType, false) case c: Class[_] if c == java.lang.Long.TYPE => (LongType, false) case c: Class[_] if c == java.lang.Double.TYPE => (DoubleType, false) case c: Class[_] if c == java.lang.Byte.TYPE => (ByteType, false) case c: Class[_] if c == java.lang.Float.TYPE => (FloatType, false) case c: Class[_] if c == java.lang.Boolean.TYPE => (BooleanType, false) case c: Class[_] if c == classOf[java.lang.Short] => (ShortType, true) case c: Class[_] if c == classOf[java.lang.Integer] => (IntegerType, true) case c: Class[_] if c == classOf[java.lang.Long] => (LongType, true) case c: Class[_] if c == classOf[java.lang.Double] => (DoubleType, true) case c: Class[_] if c == classOf[java.lang.Byte] => (ByteType, true) case c: Class[_] if c == classOf[java.lang.Float] => (FloatType, true) case c: Class[_] if c == classOf[java.lang.Boolean] => (BooleanType, true) case c: Class[_] if c == classOf[java.math.BigDecimal] => (DecimalType.SYSTEM_DEFAULT, true) case c: Class[_] if c == classOf[java.math.BigInteger] => (DecimalType.BigIntDecimal, true) case c: Class[_] if c == classOf[java.sql.Date] => (DateType, true) case c: Class[_] if c == classOf[java.sql.Timestamp] => (TimestampType, true) case _ if typeToken.isArray => val (dataType, nullable) = inferDataType(typeToken.getComponentType, seenTypeSet) (ArrayType(dataType, nullable), true) case _ if iterableType.isAssignableFrom(typeToken) => val (dataType, nullable) = inferDataType(elementType(typeToken), seenTypeSet) (ArrayType(dataType, nullable), true) case _ if mapType.isAssignableFrom(typeToken) => val (keyType, valueType) = mapKeyValueType(typeToken) val (keyDataType, _) = inferDataType(keyType, seenTypeSet) val (valueDataType, nullable) = inferDataType(valueType, seenTypeSet) (MapType(keyDataType, valueDataType, nullable), true) case other => if (seenTypeSet.contains(other)) { throw new UnsupportedOperationException( "Cannot have circular references in bean class, but got the circular reference " + s"of class $other") } // TODO: we should only collect properties that have getter and setter. However, some tests // pass in scala case class as java bean class which doesn't have getter and setter. val properties = getJavaBeanReadableProperties(other) val fields = properties.map { property => val returnType = typeToken.method(property.getReadMethod).getReturnType val (dataType, nullable) = inferDataType(returnType, seenTypeSet + other) new StructField(property.getName, dataType, nullable) } (new StructType(fields), true) } } def getJavaBeanReadableProperties(beanClass: Class[_]): Array[PropertyDescriptor] = { val beanInfo = Introspector.getBeanInfo(beanClass) beanInfo.getPropertyDescriptors.filterNot(_.getName == "class") .filter(_.getReadMethod != null) } private def getJavaBeanReadableAndWritableProperties( beanClass: Class[_]): Array[PropertyDescriptor] = { getJavaBeanReadableProperties(beanClass).filter(_.getWriteMethod != null) } private def elementType(typeToken: TypeToken[_]): TypeToken[_] = { val typeToken2 = typeToken.asInstanceOf[TypeToken[_ <: JIterable[_]]] val iterableSuperType = typeToken2.getSupertype(classOf[JIterable[_]]) val iteratorType = iterableSuperType.resolveType(iteratorReturnType) iteratorType.resolveType(nextReturnType) } private def mapKeyValueType(typeToken: TypeToken[_]): (TypeToken[_], TypeToken[_]) = { val typeToken2 = typeToken.asInstanceOf[TypeToken[_ <: JMap[_, _]]] val mapSuperType = typeToken2.getSupertype(classOf[JMap[_, _]]) val keyType = elementType(mapSuperType.resolveType(keySetReturnType)) val valueType = elementType(mapSuperType.resolveType(valuesReturnType)) keyType -> valueType } /** * Returns the Spark SQL DataType for a given java class. Where this is not an exact mapping * to a native type, an ObjectType is returned. * * Unlike `inferDataType`, this function doesn't do any massaging of types into the Spark SQL type * system. As a result, ObjectType will be returned for things like boxed Integers. */ private def inferExternalType(cls: Class[_]): DataType = cls match { case c if c == java.lang.Boolean.TYPE => BooleanType case c if c == java.lang.Byte.TYPE => ByteType case c if c == java.lang.Short.TYPE => ShortType case c if c == java.lang.Integer.TYPE => IntegerType case c if c == java.lang.Long.TYPE => LongType case c if c == java.lang.Float.TYPE => FloatType case c if c == java.lang.Double.TYPE => DoubleType case c if c == classOf[Array[Byte]] => BinaryType case _ => ObjectType(cls) } /** * Returns an expression that can be used to deserialize an internal row to an object of java bean * `T` with a compatible schema. Fields of the row will be extracted using UnresolvedAttributes * of the same name as the constructor arguments. Nested classes will have their fields accessed * using UnresolvedExtractValue. */ def deserializerFor(beanClass: Class[_]): Expression = { deserializerFor(TypeToken.of(beanClass), None) } private def deserializerFor(typeToken: TypeToken[_], path: Option[Expression]): Expression = { /** Returns the current path with a sub-field extracted. */ def addToPath(part: String): Expression = path .map(p => UnresolvedExtractValue(p, expressions.Literal(part))) .getOrElse(UnresolvedAttribute(part)) /** Returns the current path or `GetColumnByOrdinal`. */ def getPath: Expression = path.getOrElse(GetColumnByOrdinal(0, inferDataType(typeToken)._1)) typeToken.getRawType match { case c if !inferExternalType(c).isInstanceOf[ObjectType] => getPath case c if c == classOf[java.lang.Short] || c == classOf[java.lang.Integer] || c == classOf[java.lang.Long] || c == classOf[java.lang.Double] || c == classOf[java.lang.Float] || c == classOf[java.lang.Byte] || c == classOf[java.lang.Boolean] => StaticInvoke( c, ObjectType(c), "valueOf", getPath :: Nil, propagateNull = true) case c if c == classOf[java.sql.Date] => StaticInvoke( DateTimeUtils.getClass, ObjectType(c), "toJavaDate", getPath :: Nil, propagateNull = true) case c if c == classOf[java.sql.Timestamp] => StaticInvoke( DateTimeUtils.getClass, ObjectType(c), "toJavaTimestamp", getPath :: Nil, propagateNull = true) case c if c == classOf[java.lang.String] => Invoke(getPath, "toString", ObjectType(classOf[String])) case c if c == classOf[java.math.BigDecimal] => Invoke(getPath, "toJavaBigDecimal", ObjectType(classOf[java.math.BigDecimal])) case c if c.isArray => val elementType = c.getComponentType val primitiveMethod = elementType match { case c if c == java.lang.Boolean.TYPE => Some("toBooleanArray") case c if c == java.lang.Byte.TYPE => Some("toByteArray") case c if c == java.lang.Short.TYPE => Some("toShortArray") case c if c == java.lang.Integer.TYPE => Some("toIntArray") case c if c == java.lang.Long.TYPE => Some("toLongArray") case c if c == java.lang.Float.TYPE => Some("toFloatArray") case c if c == java.lang.Double.TYPE => Some("toDoubleArray") case _ => None } primitiveMethod.map { method => Invoke(getPath, method, ObjectType(c)) }.getOrElse { Invoke( MapObjects( p => deserializerFor(typeToken.getComponentType, Some(p)), getPath, inferDataType(elementType)._1), "array", ObjectType(c)) } case c if listType.isAssignableFrom(typeToken) => val et = elementType(typeToken) MapObjects( p => deserializerFor(et, Some(p)), getPath, inferDataType(et)._1, customCollectionCls = Some(c)) case _ if mapType.isAssignableFrom(typeToken) => val (keyType, valueType) = mapKeyValueType(typeToken) val keyDataType = inferDataType(keyType)._1 val valueDataType = inferDataType(valueType)._1 val keyData = Invoke( MapObjects( p => deserializerFor(keyType, Some(p)), Invoke(getPath, "keyArray", ArrayType(keyDataType)), keyDataType), "array", ObjectType(classOf[Array[Any]])) val valueData = Invoke( MapObjects( p => deserializerFor(valueType, Some(p)), Invoke(getPath, "valueArray", ArrayType(valueDataType)), valueDataType), "array", ObjectType(classOf[Array[Any]])) StaticInvoke( ArrayBasedMapData.getClass, ObjectType(classOf[JMap[_, _]]), "toJavaMap", keyData :: valueData :: Nil) case other => val properties = getJavaBeanReadableAndWritableProperties(other) val setters = properties.map { p => val fieldName = p.getName val fieldType = typeToken.method(p.getReadMethod).getReturnType val (_, nullable) = inferDataType(fieldType) val constructor = deserializerFor(fieldType, Some(addToPath(fieldName))) val setter = if (nullable) { constructor } else { AssertNotNull(constructor, Seq("currently no type path record in java")) } p.getWriteMethod.getName -> setter }.toMap val newInstance = NewInstance(other, Nil, ObjectType(other), propagateNull = false) val result = InitializeJavaBean(newInstance, setters) if (path.nonEmpty) { expressions.If( IsNull(getPath), expressions.Literal.create(null, ObjectType(other)), result ) } else { result } } } /** * Returns an expression for serializing an object of the given type to an internal row. */ def serializerFor(beanClass: Class[_]): CreateNamedStruct = { val inputObject = BoundReference(0, ObjectType(beanClass), nullable = true) val nullSafeInput = AssertNotNull(inputObject, Seq("top level input bean")) serializerFor(nullSafeInput, TypeToken.of(beanClass)) match { case expressions.If(_, _, s: CreateNamedStruct) => s case other => CreateNamedStruct(expressions.Literal("value") :: other :: Nil) } } private def serializerFor(inputObject: Expression, typeToken: TypeToken[_]): Expression = { def toCatalystArray(input: Expression, elementType: TypeToken[_]): Expression = { val (dataType, nullable) = inferDataType(elementType) if (ScalaReflection.isNativeType(dataType)) { NewInstance( classOf[GenericArrayData], input :: Nil, dataType = ArrayType(dataType, nullable)) } else { MapObjects(serializerFor(_, elementType), input, ObjectType(elementType.getRawType)) } } if (!inputObject.dataType.isInstanceOf[ObjectType]) { inputObject } else { typeToken.getRawType match { case c if c == classOf[String] => StaticInvoke( classOf[UTF8String], StringType, "fromString", inputObject :: Nil) case c if c == classOf[java.sql.Timestamp] => StaticInvoke( DateTimeUtils.getClass, TimestampType, "fromJavaTimestamp", inputObject :: Nil) case c if c == classOf[java.sql.Date] => StaticInvoke( DateTimeUtils.getClass, DateType, "fromJavaDate", inputObject :: Nil) case c if c == classOf[java.math.BigDecimal] => StaticInvoke( Decimal.getClass, DecimalType.SYSTEM_DEFAULT, "apply", inputObject :: Nil) case c if c == classOf[java.lang.Boolean] => Invoke(inputObject, "booleanValue", BooleanType) case c if c == classOf[java.lang.Byte] => Invoke(inputObject, "byteValue", ByteType) case c if c == classOf[java.lang.Short] => Invoke(inputObject, "shortValue", ShortType) case c if c == classOf[java.lang.Integer] => Invoke(inputObject, "intValue", IntegerType) case c if c == classOf[java.lang.Long] => Invoke(inputObject, "longValue", LongType) case c if c == classOf[java.lang.Float] => Invoke(inputObject, "floatValue", FloatType) case c if c == classOf[java.lang.Double] => Invoke(inputObject, "doubleValue", DoubleType) case _ if typeToken.isArray => toCatalystArray(inputObject, typeToken.getComponentType) case _ if listType.isAssignableFrom(typeToken) => toCatalystArray(inputObject, elementType(typeToken)) case _ if mapType.isAssignableFrom(typeToken) => val (keyType, valueType) = mapKeyValueType(typeToken) ExternalMapToCatalyst( inputObject, ObjectType(keyType.getRawType), serializerFor(_, keyType), ObjectType(valueType.getRawType), serializerFor(_, valueType), valueNullable = true ) case other => val properties = getJavaBeanReadableAndWritableProperties(other) val nonNullOutput = CreateNamedStruct(properties.flatMap { p => val fieldName = p.getName val fieldType = typeToken.method(p.getReadMethod).getReturnType val fieldValue = Invoke( inputObject, p.getReadMethod.getName, inferExternalType(fieldType.getRawType)) expressions.Literal(fieldName) :: serializerFor(fieldValue, fieldType) :: Nil }) val nullOutput = expressions.Literal.create(null, nonNullOutput.dataType) expressions.If(IsNull(inputObject), nullOutput, nonNullOutput) } } } }
map222/spark
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/JavaTypeInference.scala
Scala
apache-2.0
18,154
package uk.gov.dvla.vehicles.presentation.common.views import org.scalatest.AppendedClues import org.scalatest.selenium.WebBrowser.click import org.scalatest.selenium.WebBrowser.go import org.scalatest.selenium.WebBrowser.pageTitle import play.api.i18n.Messages import play.api.libs.json.Json import uk.gov.dvla.vehicles.presentation.common.composition.TestHarness import uk.gov.dvla.vehicles.presentation.common.helpers.UiSpec import uk.gov.dvla.vehicles.presentation.common.model.{Address, SearchFields} import uk.gov.dvla.vehicles.presentation.common.models.AddressPickerModel import uk.gov.dvla.vehicles.presentation.common.pages.{AddressPickerPage, ErrorPanel} class AddressPickerSpec extends UiSpec with TestHarness with AppendedClues { "Address picker widget" should { "show all the expected fields" in new WebBrowserWithJs { go to AddressPickerPage pageTitle should equal(AddressPickerPage.title) val widget = AddressPickerPage.addressPickerDriver widget.assertLookupInputVisible() widget.assertAddressInputsInvisible() widget.postCodeSearch.value should equal("") widget.searchButton widget.enterManuallyLink widget.addressSelect widget.addressLine1.value should equal("") widget.addressLine2.value should equal("") widget.addressLine3.value should equal("") widget.town.value should equal("") widget.postcode.value should equal("") widget.remember.isSelected should equal(false) } "only display the lookup container" in new WebBrowserWithJs { go to AddressPickerPage pageTitle should equal(AddressPickerPage.title) val widget = AddressPickerPage.addressPickerDriver widget.assertLookupInputVisible() widget.assertAddressInputsInvisible() widget.assertAddressListInvisible() } "show show manual address entry" in new WebBrowserWithJs { go to AddressPickerPage pageTitle should equal(AddressPickerPage.title) val widget = AddressPickerPage.addressPickerDriver widget.assertLookupInputVisible() click on widget.enterAddressManuallyLink.underlying widget.assertLookupInputInvisible() widget.assertAddressListInvisible() widget.assertAddressInputsVisible() widget.assertServerErrorInvisible() widget.assertMissingPostcodeInvisible() } "keep Lookup container and Dropdown select invisible on resubmit for manual lookup" in new WebBrowserWithJs { go to AddressPickerPage pageTitle should equal(AddressPickerPage.title) val widget = AddressPickerPage.addressPickerDriver widget.assertLookupInputVisible() click on widget.enterAddressManuallyLink.underlying widget.addressLine2.value = "address 2" widget.addressLine3.value = "address 3" click on AddressPickerPage.submit widget.assertAddressInputsVisible() widget.assertLookupInputInvisible() widget.assertAddressListInvisible() widget.assertServerErrorInvisible() widget.assertMissingPostcodeInvisible() } "validate the address code only if missing " in new WebBrowserWithJs { go to AddressPickerPage pageTitle should equal(AddressPickerPage.title) val widget = AddressPickerPage.addressPickerDriver widget.assertLookupInputVisible() widget.postCodeSearch.value = "AAAAAAA" click on AddressPickerPage.submit val errors = ErrorPanel.text.lines.filter(_ != "Please correct the details below").toSeq errors should have size 1 errors.head should include(Messages("address-picker-1.address-postcode-lookup")) } "lookup an address with ajax call" in new WebBrowserWithJs { go to AddressPickerPage pageTitle should equal(AddressPickerPage.title) val widget = AddressPickerPage.addressPickerDriver widget.assertLookupInputVisible() widget.assertAddressInputsInvisible() widget.search("ABCD") widget.assertLookupInputVisible() widget.assertAddressListVisible() widget.assertAddressInputsInvisible() widget.assertServerErrorInvisible() widget.assertMissingPostcodeInvisible() widget.addressSelect.value = "0" widget.addressLine1.value should equal("a1") widget.addressLine2.value should equal("a2") widget.addressLine3.value should equal("a3") widget.town.value should equal("a4") widget.postcode.value should equal("ABCD") widget.addressSelect.value = "default" widget.addressLine1.value should equal("") widget.addressLine2.value should equal("") widget.addressLine3.value should equal("") widget.town.value should equal("") widget.postcode.value should equal("") click on widget.changeMyDetailsLink.underlying widget.assertLookupInputVisible() widget.assertAddressInputsInvisible() widget.assertAddressListInvisible() widget.assertServerErrorInvisible() widget.assertMissingPostcodeInvisible() } "show manual input only with javascript disabled" in new WebBrowserWithJsDisabled { go to AddressPickerPage pageTitle should equal(AddressPickerPage.title) // Testing for utility classes as our browser automation suite does not work with Javascript disabled val widget = AddressPickerPage.addressPickerDriver AddressPickerPage.elementHasClass(".postcode-lookup-container", "no-js-hidden") should equal(true) } "not show manual input with javascript enabled" in new WebBrowserWithJs { go to AddressPickerPage pageTitle should equal(AddressPickerPage.title) val widget = AddressPickerPage.addressPickerDriver widget.assertAddressVisible() widget.assertLookupInputVisible() widget.assertAddressInputsInvisible() } "show server error message" in new WebBrowserWithJs { go to AddressPickerPage pageTitle should equal(AddressPickerPage.title) val widget = AddressPickerPage.addressPickerDriver widget.assertLookupInputVisible() widget.postCodeSearch.value = "123" // 123 is a special postcode that will make the server return 500 click on widget.searchButton.underlying widget.assertLookupInputVisible() widget.assertAddressInputsInvisible() widget.assertAddressListInvisible() widget.assertServerErrorVisible() widget.assertMissingPostcodeInvisible() } "show server postcode not found message" in new WebBrowserWithJs { go to AddressPickerPage pageTitle should equal(AddressPickerPage.title) val widget = AddressPickerPage.addressPickerDriver widget.assertLookupInputVisible() widget.postCodeSearch.value = "456" // 456 is a special postcode that will make the server return 500 click on widget.searchButton.underlying widget.assertLookupInputVisible() widget.assertAddressInputsInvisible() widget.assertAddressListInvisible() widget.assertServerErrorInvisible() widget.assertMissingPostcodeVisible() } "validate required elements (missing address line 1)" in new WebBrowserWithJs { go to AddressPickerPage val widget = AddressPickerPage.addressPickerDriver widget.assertLookupInputVisible() widget.search("AA11AA") widget.addressSelect.value = "1" widget.addressLine1.value = "" widget.addressLine2.value = "address 2" widget.addressLine3.value = "address 3" widget.assertLookupInputVisible() widget.assertAddressListVisible() widget.assertAddressInputsVisible() widget.assertServerErrorInvisible() widget.assertMissingPostcodeInvisible() click on AddressPickerPage.submit pageTitle should equal(AddressPickerPage.title) ErrorPanel.text should include(Messages("error.address.addressLine1")) widget.assertLookupInputVisible() widget.assertAddressListInvisible() widget.assertAddressInputsVisible() widget.assertServerErrorInvisible() widget.assertMissingPostcodeInvisible() } "validate required elements (three alpha constraint)" in new WebBrowserWithJs { go to AddressPickerPage val widget = AddressPickerPage.addressPickerDriver widget.assertLookupInputVisible() widget.search("AA11AA") widget.addressSelect.value = "1" widget.addressLine1.value = "1 a 2 b 3" widget.addressLine2.value = "address 2" widget.addressLine3.value = "address 3" widget.assertLookupInputVisible() widget.assertAddressListVisible() widget.assertAddressInputsVisible() widget.assertServerErrorInvisible() widget.assertMissingPostcodeInvisible() click on AddressPickerPage.submit pageTitle should equal(AddressPickerPage.title) ErrorPanel.text should include(Messages("error.address.threeAlphas")) widget.assertLookupInputVisible() widget.assertAddressListInvisible() widget.assertAddressInputsVisible() widget.assertServerErrorInvisible() widget.assertMissingPostcodeInvisible() } "preserve the submitted values" in new WebBrowserWithJs { go to AddressPickerPage val widget = AddressPickerPage.addressPickerDriver widget.assertLookupInputVisible() widget.search("AA11AA") widget.addressSelect.value = "1" widget.addressLine1.value = "address 1" widget.addressLine2.value = "address 2" widget.addressLine3.value = "address 3" widget.town.value = "town" widget.postcode.value = "" //leave one missing to see if the others are there after submit click on AddressPickerPage.submit pageTitle should equal(AddressPickerPage.title) ErrorPanel.text should include(Messages("error.address.postCode")) widget.addressLine1.value should equal("address 1") widget.addressLine2.value should equal("address 2") widget.addressLine3.value should equal("address 3") widget.town.value should equal("town") widget.postcode.value should equal("") } "submit when required are present" in new WebBrowserWithJs { val model = Address( SearchFields(showSearchFields = true, showAddressSelect = true, showAddressFields = true, Some("AA11AA"), Some("1"), remember = true ), "address line 1", Some("address line 2"), Some("address line 3"), "Post town", "N19 3NN" ) go to AddressPickerPage val widget = AddressPickerPage.addressPickerDriver widget.assertLookupInputVisible() widget.search("AA11AA") widget.addressSelect.value = "1" widget.addressLine1.value = model.streetAddress1 widget.addressLine2.value = model.streetAddress2.get widget.addressLine3.value = model.streetAddress3.get widget.town.value = model.postTown widget.postcode.value = model.postCode widget.remember.select() click on AddressPickerPage.submit pageTitle should equal("Success") withClue s"Errors: ${ErrorPanel.text}" val addressCookie = webDriver.manage().getCookieNamed(AddressPickerModel.Key.value) val json = addressCookie.getValue AddressPickerModel.JsonFormat.reads(Json.parse(json)) .map(a => a.address1 should equal(model)) orElse fail("Did not have a AddressPickerModel in the response") } "enter address manually with html unit only" in new WebBrowserWithJs() { go to AddressPickerPage val widget = AddressPickerPage.addressPickerDriver widget.assertLookupInputVisible() click on widget.enterAddressManuallyLink.underlying widget.assertLookupInputInvisible() // just make sure the address line is visible and it's value can be entered widget.addressLine1.value = "address line 1" } "enter address manually with javascript disabled" in new WebBrowserWithJsDisabled { val model = Address( SearchFields(showSearchFields = false, showAddressSelect = false, showAddressFields = true, None, None, remember = true ), "address line 1", Some("address line 2"), Some("address line 3"), "Post town", "N19 3NN" ) go to AddressPickerPage val widget = AddressPickerPage.addressPickerDriver widget.addressLine1.value = model.streetAddress1 widget.addressLine2.value = model.streetAddress2.get widget.addressLine3.value = model.streetAddress3.get widget.town.value = model.postTown widget.postcode.value = model.postCode widget.remember.select() click on AddressPickerPage.submit val addressCookie = webDriver.manage().getCookieNamed(AddressPickerModel.Key.value) val json = addressCookie.getValue AddressPickerModel.JsonFormat.reads(Json.parse(json)) .map(a => a.address1 should equal(model)) orElse fail("Did not have a AddressPickerModel in the response") } "validate form with js disabled" in new WebBrowserWithJsDisabled { go to AddressPickerPage val widget = AddressPickerPage.addressPickerDriver click on AddressPickerPage.submit ErrorPanel.numberOfErrors should equal(3) ErrorPanel.hasErrors should equal(true) } } "validate required elements (address lines length)" in new WebBrowserWithJs { go to AddressPickerPage val widget = AddressPickerPage.addressPickerDriver widget.assertLookupInputVisible() widget.search("AA11AA") widget.addressSelect.value = "1" widget.addressLine1.value = "1" widget.addressLine2.value = "" widget.addressLine3.value = "" widget.assertLookupInputVisible() widget.assertAddressListVisible() widget.assertAddressInputsVisible() widget.assertServerErrorInvisible() widget.assertMissingPostcodeInvisible() click on AddressPickerPage.submit pageTitle should equal(AddressPickerPage.title) //info("errors: " + ErrorPanel.text) ErrorPanel.numberOfErrors should equal(2) ErrorPanel.text should include(Messages("error.address.postTown")) ErrorPanel.text should include(Messages("error.address.buildingNameOrNumber.invalid")) widget.assertLookupInputVisible() widget.assertAddressListInvisible() widget.assertAddressInputsVisible() widget.assertServerErrorInvisible() widget.assertMissingPostcodeInvisible() } "validate required elements (max length for address line and post town)" in new WebBrowserWithJs { go to AddressPickerPage val widget = AddressPickerPage.addressPickerDriver widget.assertLookupInputVisible() widget.search("AA11AA") widget.addressSelect.value = "1" widget.addressLine1.value = "abcdefghij0123456789abcdefghij0" // 31 characters widget.addressLine2.value = "address 2" widget.addressLine3.value = "address 3" widget.town.value = "abcdefghij0123456789abcdefghij01" // 31 characters widget.assertLookupInputVisible() widget.assertAddressListVisible() widget.assertAddressInputsVisible() widget.assertServerErrorInvisible() widget.assertMissingPostcodeInvisible() click on AddressPickerPage.submit pageTitle should equal(AddressPickerPage.title) widget.addressLine1.value.length should equal(30) widget.town.value.length should equal(20) widget.assertLookupInputVisible() widget.assertAddressListInvisible() widget.assertAddressInputsVisible() widget.assertServerErrorInvisible() widget.assertMissingPostcodeInvisible() } }
dvla/vehicles-presentation-common
common-test/test/uk/gov/dvla/vehicles/presentation/common/views/AddressPickerSpec.scala
Scala
mit
15,676
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.catalyst.expressions.codegen import java.io.ObjectInputStream import com.esotericsoftware.kryo.{Kryo, KryoSerializable} import com.esotericsoftware.kryo.io.{Input, Output} import org.apache.spark.internal.Logging import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.expressions._ import org.apache.spark.sql.catalyst.expressions.BindReferences.bindReferences import org.apache.spark.sql.types.StructType import org.apache.spark.util.Utils /** * Generates bytecode for an [[Ordering]] of rows for a given set of expressions. */ object GenerateOrdering extends CodeGenerator[Seq[SortOrder], BaseOrdering] with Logging { protected def canonicalize(in: Seq[SortOrder]): Seq[SortOrder] = in.map(ExpressionCanonicalizer.execute(_).asInstanceOf[SortOrder]) protected def bind(in: Seq[SortOrder], inputSchema: Seq[Attribute]): Seq[SortOrder] = bindReferences(in, inputSchema) /** * Creates a code gen ordering for sorting this schema, in ascending order. */ def create(schema: StructType): BaseOrdering = { create(schema.zipWithIndex.map { case (field, ordinal) => SortOrder(BoundReference(ordinal, field.dataType, nullable = true), Ascending) }) } /** * Generates the code for comparing a struct type according to its natural ordering * (i.e. ascending order by field 1, then field 2, ..., then field n. */ def genComparisons(ctx: CodegenContext, schema: StructType): String = { val ordering = schema.fields.map(_.dataType).zipWithIndex.map { case(dt, index) => SortOrder(BoundReference(index, dt, nullable = true), Ascending) } genComparisons(ctx, ordering) } /** * Creates the variables for ordering based on the given order. */ private def createOrderKeys( ctx: CodegenContext, row: String, ordering: Seq[SortOrder]): Seq[ExprCode] = { ctx.INPUT_ROW = row // to use INPUT_ROW we must make sure currentVars is null ctx.currentVars = null ordering.map(_.child.genCode(ctx)) } /** * Generates the code for ordering based on the given order. */ def genComparisons(ctx: CodegenContext, ordering: Seq[SortOrder]): String = { val oldInputRow = ctx.INPUT_ROW val oldCurrentVars = ctx.currentVars val rowAKeys = createOrderKeys(ctx, "a", ordering) val rowBKeys = createOrderKeys(ctx, "b", ordering) val comparisons = rowAKeys.zip(rowBKeys).zipWithIndex.map { case ((l, r), i) => val dt = ordering(i).child.dataType val asc = ordering(i).isAscending val nullOrdering = ordering(i).nullOrdering val lRetValue = nullOrdering match { case NullsFirst => "-1" case NullsLast => "1" } val rRetValue = nullOrdering match { case NullsFirst => "1" case NullsLast => "-1" } s""" |${l.code} |${r.code} |if (${l.isNull} && ${r.isNull}) { | // Nothing |} else if (${l.isNull}) { | return $lRetValue; |} else if (${r.isNull}) { | return $rRetValue; |} else { | int comp = ${ctx.genComp(dt, l.value, r.value)}; | if (comp != 0) { | return ${if (asc) "comp" else "-comp"}; | } |} """.stripMargin } val code = ctx.splitExpressions( expressions = comparisons, funcName = "compare", arguments = Seq(("InternalRow", "a"), ("InternalRow", "b")), returnType = "int", makeSplitFunction = { body => s""" |$body |return 0; """.stripMargin }, foldFunctions = { funCalls => funCalls.zipWithIndex.map { case (funCall, i) => val comp = ctx.freshName("comp") s""" |int $comp = $funCall; |if ($comp != 0) { | return $comp; |} """.stripMargin }.mkString }) ctx.currentVars = oldCurrentVars ctx.INPUT_ROW = oldInputRow code } protected def create(ordering: Seq[SortOrder]): BaseOrdering = { val ctx = newCodeGenContext() val comparisons = genComparisons(ctx, ordering) val codeBody = s""" public SpecificOrdering generate(Object[] references) { return new SpecificOrdering(references); } class SpecificOrdering extends ${classOf[BaseOrdering].getName} { private Object[] references; ${ctx.declareMutableStates()} public SpecificOrdering(Object[] references) { this.references = references; ${ctx.initMutableStates()} } public int compare(InternalRow a, InternalRow b) { $comparisons return 0; } ${ctx.declareAddedFunctions()} }""" val code = CodeFormatter.stripOverlappingComments( new CodeAndComment(codeBody, ctx.getPlaceHolderToComments())) logDebug(s"Generated Ordering by ${ordering.mkString(",")}:\\n${CodeFormatter.format(code)}") val (clazz, _) = CodeGenerator.compile(code) clazz.generate(ctx.references.toArray).asInstanceOf[BaseOrdering] } } /** * A lazily generated row ordering comparator. */ class LazilyGeneratedOrdering(val ordering: Seq[SortOrder]) extends Ordering[InternalRow] with KryoSerializable { def this(ordering: Seq[SortOrder], inputSchema: Seq[Attribute]) = this(bindReferences(ordering, inputSchema)) @transient private[this] var generatedOrdering = GenerateOrdering.generate(ordering) def compare(a: InternalRow, b: InternalRow): Int = { generatedOrdering.compare(a, b) } private def readObject(in: ObjectInputStream): Unit = Utils.tryOrIOException { in.defaultReadObject() generatedOrdering = GenerateOrdering.generate(ordering) } override def write(kryo: Kryo, out: Output): Unit = Utils.tryOrIOException { kryo.writeObject(out, ordering.toArray) } override def read(kryo: Kryo, in: Input): Unit = Utils.tryOrIOException { generatedOrdering = GenerateOrdering.generate(kryo.readObject(in, classOf[Array[SortOrder]])) } } object LazilyGeneratedOrdering { /** * Creates a [[LazilyGeneratedOrdering]] for the given schema, in natural ascending order. */ def forSchema(schema: StructType): LazilyGeneratedOrdering = { new LazilyGeneratedOrdering(schema.zipWithIndex.map { case (field, ordinal) => SortOrder(BoundReference(ordinal, field.dataType, nullable = true), Ascending) }) } }
goldmedal/spark
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/codegen/GenerateOrdering.scala
Scala
apache-2.0
7,291
package com.github.mmolimar.ksql.jdbc import java.sql.{Connection, Driver, DriverPropertyInfo} import java.util.Properties import java.util.logging.Logger import com.github.mmolimar.ksql.jdbc.Exceptions._ import scala.util.matching.Regex object KsqlDriver { val ksqlName = "ksqlDB" val ksqlPrefix = "jdbc:ksql://" val driverName = "ksqlDB JDBC driver" val driverMajorVersion = 1 val driverMinorVersion = 2 val driverVersion = s"$driverMajorVersion.$driverMinorVersion" val jdbcMajorVersion = 4 val jdbcMinorVersion = 1 val ksqlMajorVersion = 5 val ksqlMinorVersion = 4 val ksqlMicroVersion = 0 val ksqlVersion = s"$ksqlMajorVersion.$ksqlMinorVersion.$ksqlMicroVersion" private val ksqlUserPassRegex = "((.+):(.+)@){0,1}" private val ksqlServerRegex = "([A-Za-z0-9._%+-]+):([0-9]{1,5})" private val ksqlPropsRegex = "(\\\\?([A-Za-z0-9._-]+=[A-Za-z0-9._-]+(&[A-Za-z0-9._-]+=[A-Za-z0-9._-]+)*)){0,1}" val urlRegex: Regex = s"$ksqlPrefix$ksqlUserPassRegex$ksqlServerRegex$ksqlPropsRegex\\\\z".r def parseUrl(url: String): KsqlConnectionValues = url match { case urlRegex(_, username, password, ksqlServer, port, _, props, _) => KsqlConnectionValues( ksqlServer, port.toInt, Option(username), Option(password), Option(props).map(_.split("&").map(_.split("=")).map(p => p(0) -> p(1)).toMap).getOrElse(Map.empty) ) case _ => throw InvalidUrl(url) } } class KsqlDriver extends Driver { override def acceptsURL(url: String): Boolean = Option(url).exists(_.startsWith(KsqlDriver.ksqlPrefix)) override def jdbcCompliant: Boolean = false override def getPropertyInfo(url: String, info: Properties): scala.Array[DriverPropertyInfo] = scala.Array.empty override def getMinorVersion: Int = KsqlDriver.driverMinorVersion override def getMajorVersion: Int = KsqlDriver.driverMajorVersion override def getParentLogger: Logger = throw NotSupported("getParentLogger") override def connect(url: String, properties: Properties): Connection = { if (!acceptsURL(url)) throw InvalidUrl(url) val connection = buildConnection(KsqlDriver.parseUrl(url), properties) connection.validate() connection } private[jdbc] def buildConnection(values: KsqlConnectionValues, properties: Properties): KsqlConnection = { new KsqlConnection(values, properties) } }
mmolimar/ksql-jdbc-driver
src/main/scala/com/github/mmolimar/ksql/jdbc/KsqlDriver.scala
Scala
apache-2.0
2,376
package io.catbird.util import cats.{ CoflatMap, Comonad, Eq, Monad, Monoid, Semigroup } import com.twitter.util.Var import scala.Boolean import scala.util.{ Either, Left, Right } trait VarInstances extends VarInstances1 { implicit final val twitterVarInstance: Monad[Var] with CoflatMap[Var] = new VarCoflatMap with Monad[Var] { final def pure[A](x: A): Var[A] = Var.value(x) final def flatMap[A, B](fa: Var[A])(f: A => Var[B]): Var[B] = fa.flatMap(f) override final def map[A, B](fa: Var[A])(f: A => B): Var[B] = fa.map(f) } implicit final def twitterVarSemigroup[A](implicit A: Semigroup[A]): Semigroup[Var[A]] = new VarSemigroup[A] final def varEq[A](implicit A: Eq[A]): Eq[Var[A]] = new Eq[Var[A]] { final def eqv(fx: Var[A], fy: Var[A]): Boolean = Var.sample( fx.join(fy).map { case (x, y) => A.eqv(x, y) } ) } } trait VarInstances1 { final def varComonad: Comonad[Var] = new VarCoflatMap with Comonad[Var] { final def extract[A](x: Var[A]): A = Var.sample(x) final def map[A, B](fa: Var[A])(f: A => B): Var[B] = fa.map(f) } implicit final def twitterVarMonoid[A](implicit A: Monoid[A]): Monoid[Var[A]] = new VarSemigroup[A] with Monoid[Var[A]] { final def empty: Var[A] = Var.value(A.empty) } } private[util] abstract class VarCoflatMap extends CoflatMap[Var] { final def coflatMap[A, B](fa: Var[A])(f: Var[A] => B): Var[B] = Var(f(fa)) /** * Note that this implementation is not stack-safe. */ final def tailRecM[A, B](a: A)(f: A => Var[Either[A, B]]): Var[B] = f(a).flatMap { case Left(a1) => tailRecM(a1)(f) case Right(b) => Var.value(b) } } private[util] class VarSemigroup[A](implicit A: Semigroup[A]) extends Semigroup[Var[A]] { final def combine(fx: Var[A], fy: Var[A]): Var[A] = fx.join(fy).map { case (x, y) => A.combine(x, y) } }
travisbrown/catbird
util/src/main/scala/io/catbird/util/var.scala
Scala
apache-2.0
1,896
package com.pharmpress.common.model.dmd /** * Record a trade family (from the SNOMED CT UK drug extension). * * Created by jonathan stott on 05/05/2015. */ case class TradeFamily( id: String, name: String, groupId: Option[String] ) extends DmdIdentifiable
pharmpress/DmdBrowserScalaJs
jvm/app/com/pharmpress/common/model/dmd/TradeFamily.scala
Scala
apache-2.0
267
/* * Copyright 2001-2008 Artima, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this apple 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.matchers import org.scalatest._ class ShouldBeAnSymbolSpec extends Spec with ShouldMatchers with FruitMocks { describe("The be an ('symbol) syntax") { it("should do nothing if the object has an appropriately named method, which returns true") { appleMock should be an ('apple) isAppleMock should be an ('apple) } it("should throw TestFailedException if no <symbol> or is<Symbol> method exists") { val ex1 = intercept[TestFailedException] { noPredicateMock should be an ('apple) } ex1.getMessage should equal ("NoPredicateMock has neither an apple nor an isApple method") // Check message for name that starts with a consonant (should use a instead of an) val ex2 = intercept[TestFailedException] { noPredicateMock should be an ('crabApple) } ex2.getMessage should equal ("NoPredicateMock has neither a crabApple nor an isCrabApple method") } it("should do nothing if the object has an appropriately named method, which returns false when used with not") { notAppleMock should not { be an ('apple) } notAppleMock should not be an ('apple) isNotAppleMock should not { be an ('apple) } isNotAppleMock should not be an ('apple) } it("should throw TestFailedException if no <symbol> or is<Symbol> method exists, when used with not") { val ex1 = intercept[TestFailedException] { noPredicateMock should not { be an ('apple) } } ex1.getMessage should equal ("NoPredicateMock has neither an apple nor an isApple method") val ex2 = intercept[TestFailedException] { noPredicateMock should not (be an ('orange)) } ex2.getMessage should equal ("NoPredicateMock has neither an orange nor an isOrange method") val ex3 = intercept[TestFailedException] { noPredicateMock should not be an ('apple) } ex3.getMessage should equal ("NoPredicateMock has neither an apple nor an isApple method") val ex4 = intercept[TestFailedException] { noPredicateMock should not be an ('orange) } ex4.getMessage should equal ("NoPredicateMock has neither an orange nor an isOrange method") } it("should do nothing if the object has an appropriately named method, which returns true, when used in a logical-and expression") { appleMock should ((be an ('apple)) and (be an ('apple))) appleMock should (be an ('apple) and (be an ('apple))) appleMock should (be an ('apple) and be an ('apple)) isAppleMock should ((be an ('apple)) and (be an ('apple))) isAppleMock should (be an ('apple) and (be an ('apple))) isAppleMock should (be an ('apple) and be an ('apple)) } it("should do nothing if the object has an appropriately named method, which returns true, when used in a logical-or expression") { appleMock should ((be an ('orange)) or (be an ('apple))) appleMock should (be an ('orange) or (be an ('apple))) appleMock should (be an ('orange) or be an ('apple)) isAppleMock should ((be an ('orange)) or (be an ('apple))) isAppleMock should (be an ('orange) or (be an ('apple))) isAppleMock should (be an ('orange) or be an ('apple)) appleMock should ((be an ('apple)) or (be an ('orange))) appleMock should (be an ('apple) or (be an ('orange))) appleMock should (be an ('apple) or be an ('orange)) isAppleMock should ((be an ('apple)) or (be an ('orange))) isAppleMock should (be an ('apple) or (be an ('orange))) isAppleMock should (be an ('apple) or be an ('orange)) } it("should do nothing if the object has an appropriately named method, which returns false, when used in a logical-and expression with not") { notAppleMock should (not (be an ('apple)) and not (be an ('apple))) notAppleMock should ((not be an ('apple)) and (not be an ('apple))) notAppleMock should (not be an ('apple) and not be an ('apple)) isNotAppleMock should (not (be an ('apple)) and not (be an ('apple))) isNotAppleMock should ((not be an ('apple)) and (not be an ('apple))) isNotAppleMock should (not be an ('apple) and not be an ('apple)) } it("should do nothing if the object has an appropriately named method, which returns false, when used in a logical-or expression with not") { notAppleMock should (not (be an ('apple)) or not (be an ('apple))) notAppleMock should ((not be an ('apple)) or (not be an ('apple))) notAppleMock should (not be an ('apple) or not be an ('apple)) isNotAppleMock should (not (be an ('apple)) or not (be an ('apple))) isNotAppleMock should ((not be an ('apple)) or (not be an ('apple))) isNotAppleMock should (not be an ('apple) or not be an ('apple)) notAppleMock should (not (be an ('orange)) or not (be an ('apple))) notAppleMock should ((not be an ('orange)) or (not be an ('apple))) notAppleMock should (not be an ('orange) or not be an ('apple)) isNotAppleMock should (not (be an ('orange)) or not (be an ('apple))) isNotAppleMock should ((not be an ('orange)) or (not be an ('apple))) isNotAppleMock should (not be an ('orange) or not be an ('apple)) } it("should throw TestFailedException if the object has an appropriately named method, which returns false") { val caught1 = intercept[TestFailedException] { notAppleMock should be an ('apple) } assert(caught1.getMessage === "NotAppleMock was not an apple") val caught2 = intercept[TestFailedException] { isNotAppleMock should be an ('apple) } assert(caught2.getMessage === "IsNotAppleMock was not an apple") } it("should throw TestFailedException if the object has an appropriately named method, which returns true when used with not") { val caught1 = intercept[TestFailedException] { appleMock should not { be an ('apple) } } assert(caught1.getMessage === "AppleMock was an apple") val caught2 = intercept[TestFailedException] { appleMock should not be an ('apple) } assert(caught2.getMessage === "AppleMock was an apple") val caught3 = intercept[TestFailedException] { isAppleMock should not { be an ('apple) } } assert(caught3.getMessage === "IsAppleMock was an apple") val caught4 = intercept[TestFailedException] { isAppleMock should not be an ('apple) } assert(caught4.getMessage === "IsAppleMock was an apple") } it("should throw TestFailedException if the object has an appropriately named method, which returns false, when used in a logical-and expression") { val caught1 = intercept[TestFailedException] { appleMock should ((be an ('apple)) and (be an ('orange))) } assert(caught1.getMessage === "AppleMock was an apple, but AppleMock was not an orange") val caught2 = intercept[TestFailedException] { appleMock should (be an ('apple) and (be an ('orange))) } assert(caught2.getMessage === "AppleMock was an apple, but AppleMock was not an orange") val caught3 = intercept[TestFailedException] { appleMock should (be an ('apple) and be an ('orange)) } assert(caught3.getMessage === "AppleMock was an apple, but AppleMock was not an orange") val caught4 = intercept[TestFailedException] { isAppleMock should ((be an ('apple)) and (be an ('orange))) } assert(caught4.getMessage === "IsAppleMock was an apple, but IsAppleMock was not an orange") val caught5 = intercept[TestFailedException] { isAppleMock should (be an ('apple) and (be an ('orange))) } assert(caught5.getMessage === "IsAppleMock was an apple, but IsAppleMock was not an orange") val caught6 = intercept[TestFailedException] { isAppleMock should (be an ('apple) and be an ('orange)) } assert(caught6.getMessage === "IsAppleMock was an apple, but IsAppleMock was not an orange") } it("should throw TestFailedException if the object has an appropriately named method, which returns false, when used in a logical-or expression") { val caught1 = intercept[TestFailedException] { notAppleMock should ((be an ('apple)) or (be an ('apple))) } assert(caught1.getMessage === "NotAppleMock was not an apple, and NotAppleMock was not an apple") val caught2 = intercept[TestFailedException] { notAppleMock should (be an ('apple) or (be an ('apple))) } assert(caught2.getMessage === "NotAppleMock was not an apple, and NotAppleMock was not an apple") val caught3 = intercept[TestFailedException] { notAppleMock should (be an ('apple) or be an ('apple)) } assert(caught3.getMessage === "NotAppleMock was not an apple, and NotAppleMock was not an apple") val caught4 = intercept[TestFailedException] { isNotAppleMock should ((be an ('apple)) or (be an ('apple))) } assert(caught4.getMessage === "IsNotAppleMock was not an apple, and IsNotAppleMock was not an apple") val caught5 = intercept[TestFailedException] { isNotAppleMock should (be an ('apple) or (be an ('apple))) } assert(caught5.getMessage === "IsNotAppleMock was not an apple, and IsNotAppleMock was not an apple") val caught6 = intercept[TestFailedException] { isNotAppleMock should (be an ('apple) or be an ('apple)) } assert(caught6.getMessage === "IsNotAppleMock was not an apple, and IsNotAppleMock was not an apple") } it("should throw TestFailedException if the object has an appropriately named method, which returns true, when used in a logical-and expression with not") { val caught1 = intercept[TestFailedException] { appleMock should (not (be an ('orange)) and not (be an ('apple))) } assert(caught1.getMessage === "AppleMock was not an orange, but AppleMock was an apple") val caught2 = intercept[TestFailedException] { appleMock should ((not be an ('orange)) and (not be an ('apple))) } assert(caught2.getMessage === "AppleMock was not an orange, but AppleMock was an apple") val caught3 = intercept[TestFailedException] { appleMock should (not be an ('orange) and not be an ('apple)) } assert(caught3.getMessage === "AppleMock was not an orange, but AppleMock was an apple") val caught4 = intercept[TestFailedException] { isAppleMock should (not (be an ('orange)) and not (be an ('apple))) } assert(caught4.getMessage === "IsAppleMock was not an orange, but IsAppleMock was an apple") val caught5 = intercept[TestFailedException] { isAppleMock should ((not be an ('orange)) and (not be an ('apple))) } assert(caught5.getMessage === "IsAppleMock was not an orange, but IsAppleMock was an apple") val caught6 = intercept[TestFailedException] { isAppleMock should (not be an ('orange) and not be an ('apple)) } assert(caught6.getMessage === "IsAppleMock was not an orange, but IsAppleMock was an apple") // Check that the error message "short circuits" val caught7 = intercept[TestFailedException] { appleMock should (not (be an ('apple)) and not (be an ('orange))) } assert(caught7.getMessage === "AppleMock was an apple") } it("should throw TestFailedException if the object has an appropriately named method, which returns true, when used in a logical-or expression with not") { val caught1 = intercept[TestFailedException] { appleMock should (not (be an ('apple)) or not (be an ('apple))) } assert(caught1.getMessage === "AppleMock was an apple, and AppleMock was an apple") val caught2 = intercept[TestFailedException] { appleMock should ((not be an ('apple)) or (not be an ('apple))) } assert(caught2.getMessage === "AppleMock was an apple, and AppleMock was an apple") val caught3 = intercept[TestFailedException] { appleMock should (not be an ('apple) or not be an ('apple)) } assert(caught3.getMessage === "AppleMock was an apple, and AppleMock was an apple") val caught4 = intercept[TestFailedException] { isAppleMock should (not (be an ('apple)) or not (be an ('apple))) } assert(caught4.getMessage === "IsAppleMock was an apple, and IsAppleMock was an apple") val caught5 = intercept[TestFailedException] { isAppleMock should ((not be an ('apple)) or (not be an ('apple))) } assert(caught5.getMessage === "IsAppleMock was an apple, and IsAppleMock was an apple") val caught6 = intercept[TestFailedException] { isAppleMock should (not be an ('apple) or not be an ('apple)) } assert(caught6.getMessage === "IsAppleMock was an apple, and IsAppleMock was an apple") } } }
kevinwright/scalatest
src/test/scala/org/scalatest/matchers/ShouldBeAnSymbolSpec.scala
Scala
apache-2.0
13,540
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kafka.tools import java.io.PrintStream import java.nio.charset.StandardCharsets import java.time.Duration import java.util.concurrent.CountDownLatch import java.util.regex.Pattern import java.util.{Collections, Locale, Properties, Random} import com.typesafe.scalalogging.LazyLogging import joptsimple._ import kafka.common.MessageFormatter import kafka.utils._ import kafka.utils.Implicits._ import org.apache.kafka.clients.consumer.{Consumer, ConsumerConfig, ConsumerRecord, KafkaConsumer} import org.apache.kafka.common.TopicPartition import org.apache.kafka.common.errors.{AuthenticationException, TimeoutException, WakeupException} import org.apache.kafka.common.record.TimestampType import org.apache.kafka.common.requests.ListOffsetRequest import org.apache.kafka.common.serialization.{ByteArrayDeserializer, Deserializer} import org.apache.kafka.common.utils.Utils import scala.collection.JavaConverters._ /** * Consumer that dumps messages to standard out. */ object ConsoleConsumer extends Logging { var messageCount = 0 private val shutdownLatch = new CountDownLatch(1) def main(args: Array[String]) { val conf = new ConsumerConfig(args) try { run(conf) } catch { case e: AuthenticationException => error("Authentication failed: terminating consumer process", e) Exit.exit(1) case e: Throwable => error("Unknown error when running consumer: ", e) Exit.exit(1) } } def run(conf: ConsumerConfig) { val timeoutMs = if (conf.timeoutMs >= 0) conf.timeoutMs else Long.MaxValue val consumer = new KafkaConsumer(consumerProps(conf), new ByteArrayDeserializer, new ByteArrayDeserializer) val consumerWrapper = if (conf.partitionArg.isDefined) new ConsumerWrapper(Option(conf.topicArg), conf.partitionArg, Option(conf.offsetArg), None, consumer, timeoutMs) else new ConsumerWrapper(Option(conf.topicArg), None, None, Option(conf.whitelistArg), consumer, timeoutMs) addShutdownHook(consumerWrapper, conf) try process(conf.maxMessages, conf.formatter, consumerWrapper, System.out, conf.skipMessageOnError) finally { consumerWrapper.cleanup() conf.formatter.close() reportRecordCount() shutdownLatch.countDown() } } def addShutdownHook(consumer: ConsumerWrapper, conf: ConsumerConfig) { Runtime.getRuntime.addShutdownHook(new Thread() { override def run() { consumer.wakeup() shutdownLatch.await() if (conf.enableSystestEventsLogging) { System.out.println("shutdown_complete") } } }) } def process(maxMessages: Integer, formatter: MessageFormatter, consumer: ConsumerWrapper, output: PrintStream, skipMessageOnError: Boolean) { while (messageCount < maxMessages || maxMessages == -1) { val msg: ConsumerRecord[Array[Byte], Array[Byte]] = try { consumer.receive() } catch { case _: WakeupException => trace("Caught WakeupException because consumer is shutdown, ignore and terminate.") // Consumer will be closed return case e: Throwable => error("Error processing message, terminating consumer process: ", e) // Consumer will be closed return } messageCount += 1 try { formatter.writeTo(new ConsumerRecord(msg.topic, msg.partition, msg.offset, msg.timestamp, msg.timestampType, 0, 0, 0, msg.key, msg.value, msg.headers), output) } catch { case e: Throwable => if (skipMessageOnError) { error("Error processing message, skipping this message: ", e) } else { // Consumer will be closed throw e } } if (checkErr(output, formatter)) { // Consumer will be closed return } } } def reportRecordCount() { System.err.println(s"Processed a total of $messageCount messages") } def checkErr(output: PrintStream, formatter: MessageFormatter): Boolean = { val gotError = output.checkError() if (gotError) { // This means no one is listening to our output stream anymore, time to shutdown System.err.println("Unable to write to standard out, closing consumer.") } gotError } private[tools] def consumerProps(config: ConsumerConfig): Properties = { val props = new Properties props ++= config.consumerProps props ++= config.extraConsumerProps setAutoOffsetResetValue(config, props) props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, config.bootstrapServer) props.put(ConsumerConfig.ISOLATION_LEVEL_CONFIG, config.isolationLevel) props } /** * Used by consumerProps to retrieve the correct value for the consumer parameter 'auto.offset.reset'. * * Order of priority is: * 1. Explicitly set parameter via --consumer.property command line parameter * 2. Explicit --from-beginning given -> 'earliest' * 3. Default value of 'latest' * * In case both --from-beginning and an explicit value are specified an error is thrown if these * are conflicting. */ def setAutoOffsetResetValue(config: ConsumerConfig, props: Properties) { val (earliestConfigValue, latestConfigValue) = ("earliest", "latest") if (props.containsKey(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG)) { // auto.offset.reset parameter was specified on the command line val autoResetOption = props.getProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG) if (config.options.has(config.resetBeginningOpt) && earliestConfigValue != autoResetOption) { // conflicting options - latest und earliest, throw an error System.err.println(s"Can't simultaneously specify --from-beginning and 'auto.offset.reset=$autoResetOption', " + "please remove one option") Exit.exit(1) } // nothing to do, checking for valid parameter values happens later and the specified // value was already copied during .putall operation } else { // no explicit value for auto.offset.reset was specified // if --from-beginning was specified use earliest, otherwise default to latest val autoResetOption = if (config.options.has(config.resetBeginningOpt)) earliestConfigValue else latestConfigValue props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoResetOption) } } class ConsumerConfig(args: Array[String]) { val parser = new OptionParser(false) val topicIdOpt = parser.accepts("topic", "The topic id to consume on.") .withRequiredArg .describedAs("topic") .ofType(classOf[String]) val whitelistOpt = parser.accepts("whitelist", "Whitelist of topics to include for consumption.") .withRequiredArg .describedAs("whitelist") .ofType(classOf[String]) val partitionIdOpt = parser.accepts("partition", "The partition to consume from. Consumption " + "starts from the end of the partition unless '--offset' is specified.") .withRequiredArg .describedAs("partition") .ofType(classOf[java.lang.Integer]) val offsetOpt = parser.accepts("offset", "The offset id to consume from (a non-negative number), or 'earliest' which means from beginning, or 'latest' which means from end") .withRequiredArg .describedAs("consume offset") .ofType(classOf[String]) .defaultsTo("latest") val consumerPropertyOpt = parser.accepts("consumer-property", "A mechanism to pass user-defined properties in the form key=value to the consumer.") .withRequiredArg .describedAs("consumer_prop") .ofType(classOf[String]) val consumerConfigOpt = parser.accepts("consumer.config", s"Consumer config properties file. Note that ${consumerPropertyOpt} takes precedence over this config.") .withRequiredArg .describedAs("config file") .ofType(classOf[String]) val messageFormatterOpt = parser.accepts("formatter", "The name of a class to use for formatting kafka messages for display.") .withRequiredArg .describedAs("class") .ofType(classOf[String]) .defaultsTo(classOf[DefaultMessageFormatter].getName) val messageFormatterArgOpt = parser.accepts("property", "The properties to initialize the message formatter. Default properties include:\\n" + "\\tprint.timestamp=true|false\\n" + "\\tprint.key=true|false\\n" + "\\tprint.value=true|false\\n" + "\\tkey.separator=<key.separator>\\n" + "\\tline.separator=<line.separator>\\n" + "\\tkey.deserializer=<key.deserializer>\\n" + "\\tvalue.deserializer=<value.deserializer>\\n" + "\\nUsers can also pass in customized properties for their formatter; more specifically, users " + "can pass in properties keyed with \\'key.deserializer.\\' and \\'value.deserializer.\\' prefixes to configure their deserializers.") .withRequiredArg .describedAs("prop") .ofType(classOf[String]) val resetBeginningOpt = parser.accepts("from-beginning", "If the consumer does not already have an established offset to consume from, " + "start with the earliest message present in the log rather than the latest message.") val maxMessagesOpt = parser.accepts("max-messages", "The maximum number of messages to consume before exiting. If not set, consumption is continual.") .withRequiredArg .describedAs("num_messages") .ofType(classOf[java.lang.Integer]) val timeoutMsOpt = parser.accepts("timeout-ms", "If specified, exit if no message is available for consumption for the specified interval.") .withRequiredArg .describedAs("timeout_ms") .ofType(classOf[java.lang.Integer]) val skipMessageOnErrorOpt = parser.accepts("skip-message-on-error", "If there is an error when processing a message, " + "skip it instead of halt.") val bootstrapServerOpt = parser.accepts("bootstrap-server", "REQUIRED: The server(s) to connect to.") .withRequiredArg .describedAs("server to connect to") .ofType(classOf[String]) val keyDeserializerOpt = parser.accepts("key-deserializer") .withRequiredArg .describedAs("deserializer for key") .ofType(classOf[String]) val valueDeserializerOpt = parser.accepts("value-deserializer") .withRequiredArg .describedAs("deserializer for values") .ofType(classOf[String]) val enableSystestEventsLoggingOpt = parser.accepts("enable-systest-events", "Log lifecycle events of the consumer in addition to logging consumed " + "messages. (This is specific for system tests.)") val isolationLevelOpt = parser.accepts("isolation-level", "Set to read_committed in order to filter out transactional messages which are not committed. Set to read_uncommitted" + "to read all messages.") .withRequiredArg() .ofType(classOf[String]) .defaultsTo("read_uncommitted") val groupIdOpt = parser.accepts("group", "The consumer group id of the consumer.") .withRequiredArg .describedAs("consumer group id") .ofType(classOf[String]) if (args.length == 0) CommandLineUtils.printUsageAndDie(parser, "The console consumer is a tool that reads data from Kafka and outputs it to standard output.") var groupIdPassed = true val options: OptionSet = tryParse(parser, args) val enableSystestEventsLogging = options.has(enableSystestEventsLoggingOpt) // topic must be specified. var topicArg: String = null var whitelistArg: String = null var filterSpec: TopicFilter = null val extraConsumerProps = CommandLineUtils.parseKeyValueArgs(options.valuesOf(consumerPropertyOpt).asScala) val consumerProps = if (options.has(consumerConfigOpt)) Utils.loadProps(options.valueOf(consumerConfigOpt)) else new Properties() val fromBeginning = options.has(resetBeginningOpt) val partitionArg = if (options.has(partitionIdOpt)) Some(options.valueOf(partitionIdOpt).intValue) else None val skipMessageOnError = options.has(skipMessageOnErrorOpt) val messageFormatterClass = Class.forName(options.valueOf(messageFormatterOpt)) val formatterArgs = CommandLineUtils.parseKeyValueArgs(options.valuesOf(messageFormatterArgOpt).asScala) val maxMessages = if (options.has(maxMessagesOpt)) options.valueOf(maxMessagesOpt).intValue else -1 val timeoutMs = if (options.has(timeoutMsOpt)) options.valueOf(timeoutMsOpt).intValue else -1 val bootstrapServer = options.valueOf(bootstrapServerOpt) val keyDeserializer = options.valueOf(keyDeserializerOpt) val valueDeserializer = options.valueOf(valueDeserializerOpt) val isolationLevel = options.valueOf(isolationLevelOpt).toString val formatter: MessageFormatter = messageFormatterClass.newInstance().asInstanceOf[MessageFormatter] if (keyDeserializer != null && !keyDeserializer.isEmpty) { formatterArgs.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, keyDeserializer) } if (valueDeserializer != null && !valueDeserializer.isEmpty) { formatterArgs.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, valueDeserializer) } formatter.init(formatterArgs) val topicOrFilterOpt = List(topicIdOpt, whitelistOpt).filter(options.has) if (topicOrFilterOpt.size != 1) CommandLineUtils.printUsageAndDie(parser, "Exactly one of whitelist/topic is required.") topicArg = options.valueOf(topicIdOpt) whitelistArg = options.valueOf(whitelistOpt) if (partitionArg.isDefined) { if (!options.has(topicIdOpt)) CommandLineUtils.printUsageAndDie(parser, "The topic is required when partition is specified.") if (fromBeginning && options.has(offsetOpt)) CommandLineUtils.printUsageAndDie(parser, "Options from-beginning and offset cannot be specified together.") } else if (options.has(offsetOpt)) CommandLineUtils.printUsageAndDie(parser, "The partition is required when offset is specified.") def invalidOffset(offset: String): Nothing = CommandLineUtils.printUsageAndDie(parser, s"The provided offset value '$offset' is incorrect. Valid values are " + "'earliest', 'latest', or a non-negative long.") val offsetArg = if (options.has(offsetOpt)) { options.valueOf(offsetOpt).toLowerCase(Locale.ROOT) match { case "earliest" => ListOffsetRequest.EARLIEST_TIMESTAMP case "latest" => ListOffsetRequest.LATEST_TIMESTAMP case offsetString => try { val offset = offsetString.toLong if (offset < 0) invalidOffset(offsetString) offset } catch { case _: NumberFormatException => invalidOffset(offsetString) } } } else if (fromBeginning) ListOffsetRequest.EARLIEST_TIMESTAMP else ListOffsetRequest.LATEST_TIMESTAMP CommandLineUtils.checkRequiredArgs(parser, options, bootstrapServerOpt) // if the group id is provided in more than place (through different means) all values must be the same val groupIdsProvided = Set( Option(options.valueOf(groupIdOpt)), // via --group Option(consumerProps.get(ConsumerConfig.GROUP_ID_CONFIG)), // via --consumer-property Option(extraConsumerProps.get(ConsumerConfig.GROUP_ID_CONFIG)) // via --cosumer.config ).flatten if (groupIdsProvided.size > 1) { CommandLineUtils.printUsageAndDie(parser, "The group ids provided in different places (directly using '--group', " + "via '--consumer-property', or via '--consumer.config') do not match. " + s"Detected group ids: ${groupIdsProvided.mkString("'", "', '", "'")}") } groupIdsProvided.headOption match { case Some(group) => consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, group) case None => consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, s"console-consumer-${new Random().nextInt(100000)}") // By default, avoid unnecessary expansion of the coordinator cache since // the auto-generated group and its offsets is not intended to be used again if (!consumerProps.containsKey(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG)) consumerProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false") groupIdPassed = false } def tryParse(parser: OptionParser, args: Array[String]): OptionSet = { try parser.parse(args: _*) catch { case e: OptionException => CommandLineUtils.printUsageAndDie(parser, e.getMessage) } } } private[tools] class ConsumerWrapper(topic: Option[String], partitionId: Option[Int], offset: Option[Long], whitelist: Option[String], consumer: Consumer[Array[Byte], Array[Byte]], val timeoutMs: Long = Long.MaxValue) { consumerInit() var recordIter = Collections.emptyList[ConsumerRecord[Array[Byte], Array[Byte]]]().iterator() def consumerInit() { (topic, partitionId, offset, whitelist) match { case (Some(topic), Some(partitionId), Some(offset), None) => seek(topic, partitionId, offset) case (Some(topic), Some(partitionId), None, None) => // default to latest if no offset is provided seek(topic, partitionId, ListOffsetRequest.LATEST_TIMESTAMP) case (Some(topic), None, None, None) => consumer.subscribe(Collections.singletonList(topic)) case (None, None, None, Some(whitelist)) => consumer.subscribe(Pattern.compile(whitelist)) case _ => throw new IllegalArgumentException("An invalid combination of arguments is provided. " + "Exactly one of 'topic' or 'whitelist' must be provided. " + "If 'topic' is provided, an optional 'partition' may also be provided. " + "If 'partition' is provided, an optional 'offset' may also be provided, otherwise, consumption starts from the end of the partition.") } } def seek(topic: String, partitionId: Int, offset: Long) { val topicPartition = new TopicPartition(topic, partitionId) consumer.assign(Collections.singletonList(topicPartition)) offset match { case ListOffsetRequest.EARLIEST_TIMESTAMP => consumer.seekToBeginning(Collections.singletonList(topicPartition)) case ListOffsetRequest.LATEST_TIMESTAMP => consumer.seekToEnd(Collections.singletonList(topicPartition)) case _ => consumer.seek(topicPartition, offset) } } def resetUnconsumedOffsets() { val smallestUnconsumedOffsets = collection.mutable.Map[TopicPartition, Long]() while (recordIter.hasNext) { val record = recordIter.next() val tp = new TopicPartition(record.topic, record.partition) // avoid auto-committing offsets which haven't been consumed smallestUnconsumedOffsets.getOrElseUpdate(tp, record.offset) } smallestUnconsumedOffsets.foreach { case (tp, offset) => consumer.seek(tp, offset) } } def receive(): ConsumerRecord[Array[Byte], Array[Byte]] = { if (!recordIter.hasNext) { recordIter = consumer.poll(Duration.ofMillis(timeoutMs)).iterator if (!recordIter.hasNext) throw new TimeoutException() } recordIter.next } def wakeup(): Unit = { this.consumer.wakeup() } def cleanup() { resetUnconsumedOffsets() this.consumer.close() } def commitSync() { this.consumer.commitSync() } } } class DefaultMessageFormatter extends MessageFormatter { var printKey = false var printValue = true var printTimestamp = false var keySeparator = "\\t".getBytes(StandardCharsets.UTF_8) var lineSeparator = "\\n".getBytes(StandardCharsets.UTF_8) var keyDeserializer: Option[Deserializer[_]] = None var valueDeserializer: Option[Deserializer[_]] = None override def init(props: Properties) { if (props.containsKey("print.timestamp")) printTimestamp = props.getProperty("print.timestamp").trim.equalsIgnoreCase("true") if (props.containsKey("print.key")) printKey = props.getProperty("print.key").trim.equalsIgnoreCase("true") if (props.containsKey("print.value")) printValue = props.getProperty("print.value").trim.equalsIgnoreCase("true") if (props.containsKey("key.separator")) keySeparator = props.getProperty("key.separator").getBytes(StandardCharsets.UTF_8) if (props.containsKey("line.separator")) lineSeparator = props.getProperty("line.separator").getBytes(StandardCharsets.UTF_8) // Note that `toString` will be called on the instance returned by `Deserializer.deserialize` if (props.containsKey("key.deserializer")) { keyDeserializer = Some(Class.forName(props.getProperty("key.deserializer")).newInstance().asInstanceOf[Deserializer[_]]) keyDeserializer.get.configure(propertiesWithKeyPrefixStripped("key.deserializer.", props).asScala.asJava, true) } // Note that `toString` will be called on the instance returned by `Deserializer.deserialize` if (props.containsKey("value.deserializer")) { valueDeserializer = Some(Class.forName(props.getProperty("value.deserializer")).newInstance().asInstanceOf[Deserializer[_]]) valueDeserializer.get.configure(propertiesWithKeyPrefixStripped("value.deserializer.", props).asScala.asJava, false) } } private def propertiesWithKeyPrefixStripped(prefix: String, props: Properties): Properties = { val newProps = new Properties() props.asScala.foreach { case (key, value) => if (key.startsWith(prefix) && key.length > prefix.length) newProps.put(key.substring(prefix.length), value) } newProps } def writeTo(consumerRecord: ConsumerRecord[Array[Byte], Array[Byte]], output: PrintStream) { def writeSeparator(columnSeparator: Boolean): Unit = { if (columnSeparator) output.write(keySeparator) else output.write(lineSeparator) } def write(deserializer: Option[Deserializer[_]], sourceBytes: Array[Byte]) { val nonNullBytes = Option(sourceBytes).getOrElse("null".getBytes(StandardCharsets.UTF_8)) val convertedBytes = deserializer.map(_.deserialize(null, nonNullBytes).toString. getBytes(StandardCharsets.UTF_8)).getOrElse(nonNullBytes) output.write(convertedBytes) } import consumerRecord._ if (printTimestamp) { if (timestampType != TimestampType.NO_TIMESTAMP_TYPE) output.write(s"$timestampType:$timestamp".getBytes(StandardCharsets.UTF_8)) else output.write(s"NO_TIMESTAMP".getBytes(StandardCharsets.UTF_8)) writeSeparator(printKey || printValue) } if (printKey) { write(keyDeserializer, key) writeSeparator(printValue) } if (printValue) { write(valueDeserializer, value) output.write(lineSeparator) } } } class LoggingMessageFormatter extends MessageFormatter with LazyLogging { private val defaultWriter: DefaultMessageFormatter = new DefaultMessageFormatter override def init(props: Properties): Unit = defaultWriter.init(props) def writeTo(consumerRecord: ConsumerRecord[Array[Byte], Array[Byte]], output: PrintStream): Unit = { import consumerRecord._ defaultWriter.writeTo(consumerRecord, output) logger.info({if (timestampType != TimestampType.NO_TIMESTAMP_TYPE) s"$timestampType:$timestamp, " else ""} + s"key:${if (key == null) "null" else new String(key, StandardCharsets.UTF_8)}, " + s"value:${if (value == null) "null" else new String(value, StandardCharsets.UTF_8)}") } } class NoOpMessageFormatter extends MessageFormatter { override def init(props: Properties) {} def writeTo(consumerRecord: ConsumerRecord[Array[Byte], Array[Byte]], output: PrintStream){} } class ChecksumMessageFormatter extends MessageFormatter { private var topicStr: String = _ override def init(props: Properties) { topicStr = props.getProperty("topic") if (topicStr != null) topicStr = topicStr + ":" else topicStr = "" } def writeTo(consumerRecord: ConsumerRecord[Array[Byte], Array[Byte]], output: PrintStream) { output.println(topicStr + "checksum:" + consumerRecord.checksum) } }
ollie314/kafka
core/src/main/scala/kafka/tools/ConsoleConsumer.scala
Scala
apache-2.0
25,137
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.api.scala.typeutils import java.io.IOException import org.apache.flink.annotation.Internal import org.apache.flink.api.common.typeutils.{CompatibilityResult, TypeSerializer, TypeSerializerConfigSnapshot} import org.apache.flink.api.common.typeutils.base.IntSerializer import org.apache.flink.api.java.typeutils.runtime.{DataInputViewStream, DataOutputViewStream} import org.apache.flink.core.memory.{DataInputView, DataOutputView} import org.apache.flink.util.InstantiationUtil /** * Serializer for [[Enumeration]] values. */ @Internal class EnumValueSerializer[E <: Enumeration](val enum: E) extends TypeSerializer[E#Value] { type T = E#Value val intSerializer = new IntSerializer() override def duplicate: EnumValueSerializer[E] = this override def createInstance: T = enum(0) override def isImmutableType: Boolean = true override def getLength: Int = intSerializer.getLength override def copy(from: T): T = enum.apply(from.id) override def copy(from: T, reuse: T): T = copy(from) override def copy(src: DataInputView, tgt: DataOutputView): Unit = intSerializer.copy(src, tgt) override def serialize(v: T, tgt: DataOutputView): Unit = intSerializer.serialize(v.id, tgt) override def deserialize(source: DataInputView): T = enum(intSerializer.deserialize(source)) override def deserialize(reuse: T, source: DataInputView): T = deserialize(source) override def equals(obj: Any): Boolean = { obj match { case enumValueSerializer: EnumValueSerializer[_] => enumValueSerializer.canEqual(this) && enum == enumValueSerializer.enum case _ => false } } override def hashCode(): Int = { enum.hashCode() } override def canEqual(obj: scala.Any): Boolean = { obj.isInstanceOf[EnumValueSerializer[_]] } // -------------------------------------------------------------------------------------------- // Serializer configuration snapshotting & compatibility // -------------------------------------------------------------------------------------------- override def snapshotConfiguration(): EnumValueSerializer.ScalaEnumSerializerConfigSnapshot[E] = { new EnumValueSerializer.ScalaEnumSerializerConfigSnapshot[E]( enum.getClass.asInstanceOf[Class[E]]) } override def ensureCompatibility( configSnapshot: TypeSerializerConfigSnapshot): CompatibilityResult[E#Value] = { configSnapshot match { case enumSerializerConfigSnapshot: EnumValueSerializer.ScalaEnumSerializerConfigSnapshot[_] => val enumClass = enum.getClass.asInstanceOf[Class[E]] if (enumClass.equals(enumSerializerConfigSnapshot.getEnumClass)) { val currentEnumConstants = enumSerializerConfigSnapshot.getEnumClass.getEnumConstants for ( i <- 0 to currentEnumConstants.length) { // compatible only if new enum constants are only appended, // and original constants must be in the exact same order if (currentEnumConstants(i) != enumSerializerConfigSnapshot.getEnumConstants(i)) { return CompatibilityResult.requiresMigration() } } CompatibilityResult.compatible() } else { CompatibilityResult.requiresMigration() } case _ => CompatibilityResult.requiresMigration() } } } object EnumValueSerializer { class ScalaEnumSerializerConfigSnapshot[E <: Enumeration](private var enumClass: Class[E]) extends TypeSerializerConfigSnapshot { var enumConstants: Array[E] = enumClass.getEnumConstants /** This empty nullary constructor is required for deserializing the configuration. */ def this() = this(null) override def write(out: DataOutputView): Unit = { super.write(out) try { val outViewWrapper = new DataOutputViewStream(out) try { InstantiationUtil.serializeObject(outViewWrapper, enumClass) InstantiationUtil.serializeObject(outViewWrapper, enumConstants) } finally if (outViewWrapper != null) outViewWrapper.close() } } override def read(in: DataInputView): Unit = { super.read(in) try { val inViewWrapper = new DataInputViewStream(in) try try { enumClass = InstantiationUtil.deserializeObject( inViewWrapper, getUserCodeClassLoader) enumConstants = InstantiationUtil.deserializeObject( inViewWrapper, getUserCodeClassLoader) } catch { case e: ClassNotFoundException => throw new IOException("The requested enum class cannot be found in classpath.", e) } finally if (inViewWrapper != null) inViewWrapper.close() } } override def getVersion: Int = ScalaEnumSerializerConfigSnapshot.VERSION def getEnumClass: Class[E] = enumClass def getEnumConstants: Array[E] = enumConstants override def equals(obj: scala.Any): Boolean = { if (obj == this) { return true } if (obj == null) { return false } obj.isInstanceOf[ScalaEnumSerializerConfigSnapshot[E]] && enumClass.equals(obj.asInstanceOf[ScalaEnumSerializerConfigSnapshot[E]].enumClass) && enumConstants.sameElements( obj.asInstanceOf[ScalaEnumSerializerConfigSnapshot[E]].enumConstants) } override def hashCode(): Int = { enumClass.hashCode() * 31 + enumConstants.toSeq.hashCode() } } object ScalaEnumSerializerConfigSnapshot { val VERSION = 1 } }
WangTaoTheTonic/flink
flink-scala/src/main/scala/org/apache/flink/api/scala/typeutils/EnumValueSerializer.scala
Scala
apache-2.0
6,349
/** * For copyright information see the LICENSE document. */ package entice.server.world.systems import entice.server._ import entice.server.world._ import entice.server.utils._ import entice.protocol._ import akka.actor._ import shapeless._ import scala.concurrent.duration._ import scala.language.postfixOps /** * TODO: With a more advanced System, this should have the following aspect: * must either (have(GroupLeader) or have(GroupMember)) * * TODO: Idea: to unclutter the entity creation process, add the GroupLeader * component to the entity upon spawning. Possible problem: might cause problems * with the client if it expects the GroupLeader to be present. (Specification issue) */ class GroupSystem extends System[HNil] with Actor with Subscriber { val subscriptions = //classOf[Spawned] :: classOf[Despawned] :: classOf[GroupInvite] :: classOf[GroupDecline] :: classOf[GroupAccept] :: classOf[GroupLeave] :: classOf[GroupKick] :: Nil override def preStart { register } def receive = { // invite case MessageEvent(_, GroupInvite(me, other)) if (me != other && me .get[GroupLeader] != None && other.get[GroupLeader] != None) => invite(me, other) // decline (either invited or join-request, doesnt matter) case MessageEvent(_, GroupDecline(me, other)) if (me != other && me .get[GroupLeader] != None && other.get[GroupLeader] != None) => decline(me, other) // accept case MessageEvent(_, GroupAccept(me, other)) if (me != other && me .get[GroupLeader] != None && other.get[GroupLeader] != None) => accept(me, other) // leave (1.1: Member) case MessageEvent(_, GroupLeave(me)) if me.get[GroupMember] != None => leaveAsMember(me) // leave (1.2: Member + Despawn) case MessageEvent(_, Despawned(world, me, comps)) if comps.contains[GroupMember] => despawnAsMember(world, me, comps[GroupMember]) // leave (2.1: Leader) case MessageEvent(_, GroupLeave(me)) if me.get[GroupLeader] != None => leaveAsLeader(me) // leave (2.2: Leader + Despawn) case MessageEvent(_, Despawned(world, me, comps)) if comps.contains[GroupLeader] => despawnAsLeader(world, me, comps[GroupLeader]) // kick case MessageEvent(_, GroupKick(me, other)) if (me != other && me .get[GroupLeader] != None && other.get[GroupMember] != None) => kick(me, other) } def invite(me: RichEntity, other: RichEntity) { val meLeader = me[GroupLeader] var otherLeader = other[GroupLeader] // update my invited if needed if (!meLeader.invited.contains(other.entity)) { me.set(meLeader.copy(invited = other.entity :: meLeader.invited)) } // update recipients join requests if needed if (!otherLeader.joinRequests.contains(me.entity)) { other.set(otherLeader.copy(joinRequests = me.entity :: otherLeader.joinRequests)) } } def decline(me: RichEntity, other: RichEntity) { val meLeader = me[GroupLeader] val otherLeader = other[GroupLeader] // remove the other from our invited or joinReq lists me.set(meLeader.copy( invited = meLeader.invited filterNot { _ == other.entity }, joinRequests = meLeader.joinRequests filterNot { _ == other.entity })) // remove us from the other entities invited or joinReq lists other.set(otherLeader.copy( invited = otherLeader.invited filterNot { _ == me.entity }, joinRequests = otherLeader.joinRequests filterNot { _ == me.entity })) } def accept(me: RichEntity, other: RichEntity) { val meLeader = me[GroupLeader] var otherLeader = other[GroupLeader] // make me and my members members of other otherLeader = otherLeader.copy(members = otherLeader.members ::: List(me.entity)) otherLeader = otherLeader.copy(members = otherLeader.members ::: meLeader.members) // new leader for my members meLeader.members .filter { inv => me.world.contains(inv) } .map { inv => me.world.getRich(inv).get } .filter { inv => inv.get[GroupMember] != None } .foreach { inv => inv.set(GroupMember(other.entity)) } // clean up my invites meLeader.invited .filter { inv => me.world.contains(inv) } .map { inv => me.world.getRich(inv).get } .filter { inv => inv.get[GroupLeader] != None } .foreach { inv => inv.set(inv[GroupLeader].copy( joinRequests = inv[GroupLeader].joinRequests filterNot { _ == me.entity })) } // clean up my joinrequests meLeader.joinRequests .filter { jn => me.world.contains(jn) } .map { jn => me.world.getRich(jn).get } .filter { jn => jn.get[GroupLeader] != None } .foreach { jn => jn.set(jn[GroupLeader].copy( invited = jn[GroupLeader].invited filterNot { _ == me.entity })) } // new leader for me (swap components) me.drop[GroupLeader] me.set(GroupMember(other.entity)) // update invitation of recipient other.set(otherLeader.copy(invited = otherLeader.invited filterNot { _ == me.entity })) } def leaveAsMember(me: RichEntity) { // we will need to clean up the old group later on... val recipient = me.world.getRich(me[GroupMember].leader).get val recLeader = recipient[GroupLeader] // get us a new group me.drop[GroupMember] me.set(GroupLeader()) // remove us from the old group recipient.set(recLeader.copy(members = recLeader.members filterNot { _ == me.entity })) } def despawnAsMember(meWorld: World, meEntity: Entity, meMember: GroupMember) { // we will need to clean up the old group later on... val recipient = meWorld.getRich(meMember.leader).get val recLeader = recipient[GroupLeader] // remove us from the old group recipient.set(recLeader.copy(members = recLeader.members filterNot { _ == meEntity })) } def leaveAsLeader(me: RichEntity) { val oldLeader = me[GroupLeader] val recipient = me.world.getRich(oldLeader.members(0)).get // make recipient the new leader... recipient.drop[GroupMember] recipient.set(oldLeader.copy(members = oldLeader.members filterNot { _ == recipient.entity })) // update other team members to have a new leader recipient[GroupLeader].members .filter { mem => me.world.contains(mem) } .map { mem => me.world.getRich(mem).get } .foreach { mem => mem.set(GroupMember(recipient)) } // get us a new group me.drop[GroupMember] me.set(GroupLeader()) } def despawnAsLeader(meWorld: World, meEntity: Entity, meLeader: GroupLeader) { if (meLeader.members != Nil) { val recipient = meWorld.getRich(meLeader.members(0)).get // make recipient the new leader... recipient.drop[GroupMember] recipient.set(meLeader.copy(members = meLeader.members filterNot { _ == recipient.entity })) // update other team members to have a new leader recipient[GroupLeader].members .filter { mem => meWorld.contains(mem) } .map { mem => meWorld.getRich(mem).get } .foreach { mem => mem.set(GroupMember(recipient)) } } // clean up my invites meLeader.invited .filter { inv => meWorld.contains(inv) } .map { inv => meWorld.getRich(inv).get } .filter { inv => inv.get[GroupLeader] != None } .foreach { inv => inv.set(inv[GroupLeader].copy( joinRequests = inv[GroupLeader].joinRequests filterNot { _ == meEntity })) } // clean up my joinrequests meLeader.joinRequests .filter { jn => meWorld.contains(jn) } .map { jn => meWorld.getRich(jn).get } .filter { jn => jn.get[GroupLeader] != None } .foreach { jn => jn.set(jn[GroupLeader].copy( invited = jn[GroupLeader].invited filterNot { _ == meEntity })) } } def kick(me: RichEntity, other: RichEntity) { val oldLeader = me[GroupLeader] // get the former member its own group other.drop[GroupMember] other.set(GroupLeader()) // clean up my members me.set(oldLeader.copy(members = oldLeader.members filterNot { _ == other.entity })) } }
entice/old-server
src/main/scala/entice/server/world/systems/GroupSystem.scala
Scala
bsd-3-clause
9,257
package sigmastate import org.ergoplatform.SigmaConstants.ScriptCostLimit import org.ergoplatform.validation.ValidationRules import org.ergoplatform.{ErgoBox, ErgoLikeContext} import scorex.crypto.authds.avltree.batch.Lookup import scorex.crypto.authds.{ADDigest, ADKey} import scorex.crypto.hash.Blake2b256 import sigmastate.Values._ import sigmastate.eval.Extensions._ import sigmastate.eval.Sized._ import sigmastate.eval._ import sigmastate.helpers.TestingHelpers._ import sigmastate.helpers.{ContextEnrichingTestProvingInterpreter, ErgoLikeTestInterpreter} import sigmastate.interpreter.ContextExtension import sigmastate.interpreter.Interpreter.{ScriptEnv, ScriptNameProp, emptyEnv} import sigmastate.utxo.CostTable import sigmastate.utxo.CostTable._ import special.sigma.{AvlTree, SigmaTestingData} import sigmastate.lang.Terms.ValueOps import sigmastate.lang.exceptions.CostLimitException class CostingSpecification extends SigmaTestingData with CrossVersionProps { implicit lazy val IR = new TestingIRContext { // override val okPrintEvaluatedEntries = true substFromCostTable = false } lazy val interpreter = new ContextEnrichingTestProvingInterpreter lazy val pkA = interpreter.dlogSecrets(0).publicImage lazy val pkB = interpreter.dlogSecrets(1).publicImage val printCosts = true val (keysArr, _, _, avlProver) = sampleAvlProver val keys = Colls.fromItems(keysArr(0)) val key1 = keys(0) val key2 = keyCollGen.sample.get avlProver.performOneOperation(Lookup(ADKey @@ key1.toArray)) val digest = avlProver.digest.toColl val lookupProof = avlProver.generateProof().toColl val avlTreeData = AvlTreeData(ADDigest @@ digest.toArray, AvlTreeFlags.AllOperationsAllowed, 32, None) val avlTree: AvlTree = CAvlTree(avlTreeData) lazy val env: ScriptEnv = Map( ScriptNameProp -> s"filename_verify", "key1" -> key1, "key2" -> key2, "keys" -> keys, "lookupProof" -> lookupProof, "pkA" -> pkA, "pkB" -> pkB ) val extension: ContextExtension = ContextExtension(Map( 1.toByte -> IntConstant(1), 2.toByte -> BooleanConstant(true), 3.toByte -> BigIntConstant(BigInt("12345678901").bigInteger) )) val tokenId = Blake2b256("tokenA") class TestData { val headerFlags = ErgoTree.headerWithVersion(ergoTreeVersionInTests) val selfBox = createBox(0, ErgoTree.withoutSegregation(headerFlags, TrueSigmaProp), Seq(tokenId -> 10L), Map(ErgoBox.R4 -> ByteArrayConstant(Array[Byte](1, 2, 3)), ErgoBox.R5 -> IntConstant(3), ErgoBox.R6 -> AvlTreeConstant(avlTree))) val outBoxA = testBox(10, ErgoTree.fromSigmaBoolean(headerFlags, pkA), 0) val outBoxB = testBox(20, ErgoTree.fromSigmaBoolean(headerFlags, pkB), 0) val dataBox = createBox(1000, ErgoTree.withoutSegregation(headerFlags, TrueSigmaProp), Seq(tokenId1 -> 10L, tokenId2 -> 20L), Map(ErgoBox.R4 -> IntConstant(100), ErgoBox.R5 -> BooleanConstant(true))) val tx = createTransaction(IndexedSeq(dataBox), IndexedSeq(outBoxA, outBoxB)) val context = new ErgoLikeContext( lastBlockUtxoRoot = header2.stateRoot.asInstanceOf[CAvlTree].treeData, headers = headers, preHeader = preHeader, dataBoxes = IndexedSeq(dataBox), boxesToSpend = IndexedSeq(selfBox), spendingTransaction = tx, selfIndex = 0, extension, ValidationRules.currentSettings, ScriptCostLimit.value, CostTable.interpreterInitCost, activatedVersionInTests ).withErgoTreeVersion(ergoTreeVersionInTests) def cost(script: String)(expCost: Int): Unit = { val ergoTree = compiler.compile(env, script) val res = interpreter.reduceToCrypto(context, env, ergoTree).get.cost if (printCosts) println(script + s" --> cost $res") res shouldBe ((expCost * CostTable.costFactorIncrease / CostTable.costFactorDecrease) + CostTable.interpreterInitCost).toLong } val ContextVarAccess = getVarCost + selectField // `getVar(id)` + `.get` val RegisterAccess = accessRegister + selectField // `getReg(id)` + `.get` val GTConstCost = comparisonCost + constCost val LengthGTConstCost = collLength + GTConstCost val LengthGTCost = collLength + comparisonCost // can be used when constCost is already accumulated val OutputsCost = selectField + accessBox * tx.outputs.length val InputsCost = selectField + accessBox * context.boxesToSpend.length val DataInputsCost = selectField + accessBox * context.dataBoxes.length val HeadersCost = selectField val PreHeaderCost = selectField val AccessHeaderCost = selectField + collByIndex + constCost } property("basic (smoke) tests") { val d = new TestData; import d._ cost("{ getVar[Boolean](2).get }")(ContextVarAccess) cost("{ getVar[Int](1).get > 1 }")(ContextVarAccess + GTConstCost) // accessing two context variables cost("{ getVar[Int](1).get > 1 && getVar[Boolean](2).get }")(ContextVarAccess * 2 + GTConstCost + logicCost) // the same var is used twice doesn't lead to double cost cost("{ getVar[Int](1).get + 1 > getVar[Int](1).get }")(ContextVarAccess + plusMinus + constCost + comparisonCost) // cost is accumulated along the expression tree cost("{ getVar[Int](1).get + 1 > getVar[Int](1).get && getVar[Boolean](2).get }")( ContextVarAccess * 2 + plusMinus + constCost + comparisonCost + logicCost) } property("logical op costs") { val d = new TestData; import d._ cost("{ val cond = getVar[Boolean](2).get; cond && cond }")(ContextVarAccess + logicCost) cost("{ val cond = getVar[Boolean](2).get; cond || cond }")(ContextVarAccess + logicCost) cost("{ val cond = getVar[Boolean](2).get; cond || cond && true }")(ContextVarAccess + logicCost * 2 + constCost) cost("{ val cond = getVar[Boolean](2).get; cond || cond && true || cond }")(ContextVarAccess + logicCost * 3 + constCost) cost("{ val cond = getVar[Boolean](2).get; cond ^ cond && true ^ cond }")(ContextVarAccess + logicCost * 3 + constCost) cost("{ val cond = getVar[Boolean](2).get; allOf(Coll(cond, true, cond)) }")(ContextVarAccess + logicCost * 2 + constCost) cost("{ val cond = getVar[Boolean](2).get; anyOf(Coll(cond, true, cond)) }")(ContextVarAccess + logicCost * 2 + constCost) cost("{ val cond = getVar[Boolean](2).get; xorOf(Coll(cond, true, cond)) }") (ContextVarAccess + logicCost * 2 + constCost) } property("atLeast costs") { val d = new TestData; import d._ cost("{ atLeast(2, Coll(pkA, pkB, pkB)) }")( concreteCollectionItemCost * 3 + collToColl + proveDlogEvalCost * 2 + logicCost + constCost) } property("allZK costs") { val d = new TestData; import d._ cost("{ pkA && pkB }") (proveDlogEvalCost * 2 + sigmaAndCost * 2) } property("anyZK costs") { val d = new TestData; import d._ cost("{ pkA || pkB }") (proveDlogEvalCost * 2 + sigmaOrCost * 2) } property("blake2b256 costs") { val d = new TestData; import d._ cost("{ blake2b256(key1).size > 0 }") (constCost + hashPerKb + LengthGTConstCost) } property("sha256 costs") { val d = new TestData; import d._ cost("{ sha256(key1).size > 0 }") (constCost + hashPerKb + LengthGTConstCost) } property("byteArrayToBigInt") { val d = new TestData; import d._ cost("{ byteArrayToBigInt(Coll[Byte](1.toByte)) > 0 }")( constCost // byte const + collToColl // concrete collection + concreteCollectionItemCost * 1 // build from array cost + castOp + newBigIntPerItem + comparisonBigInt + constCost) } property("byteArrayToLong") { val d = new TestData; import d._ cost("{ byteArrayToLong(Coll[Byte](1.toByte, 1.toByte, 1.toByte, 1.toByte, 1.toByte, 1.toByte, 1.toByte, 1.toByte)) > 0 }") ( constCost // byte const + collToColl // concrete collection + concreteCollectionItemCost * 8 // build from array cost + castOp + GTConstCost) } property("longToByteArray") { val d = new TestData; import d._ cost("{ longToByteArray(1L).size > 0 }") (constCost + castOp + LengthGTConstCost) } property("decodePoint and GroupElement.getEncoded") { val d = new TestData; import d._ cost("{ decodePoint(groupGenerator.getEncoded) == groupGenerator }") (selectField + selectField + decodePointCost + comparisonCost) } property("GroupElement.negate") { val d = new TestData; import d._ cost("{ groupGenerator.negate != groupGenerator }") (selectField + negateGroup + comparisonCost) } property("GroupElement.exp") { val d = new TestData; import d._ cost("{ groupGenerator.exp(getVar[BigInt](3).get) == groupGenerator }") (selectField + expCost + ContextVarAccess + comparisonCost) } property("SELF box operations cost") { val d = new TestData; import d._ cost("{ SELF.value > 0 }")(accessBox + extractCost + GTConstCost) cost("{ SELF.id.size > 0 }")(accessBox + extractCost + LengthGTConstCost) cost("{ SELF.tokens.size > 0 }")(accessBox + extractCost + LengthGTConstCost) cost("{ SELF.creationInfo._1 > 0 }")(accessBox + accessRegister + selectField + GTConstCost) cost("{ SELF.R5[Int].get > 0 }")(accessBox + RegisterAccess + GTConstCost) } property("Global operations cost") { val d = new TestData; import d._ // TODO costing: related to https://github.com/ScorexFoundation/sigmastate-interpreter/issues/479 // cost("{ groupGenerator.isIdentity > 0 }")(selectField + selectField + GTConstCost) val sizeOfArgs = Seq(sizeOf(key1), sizeOf(key1)).foldLeft(0L)(_ + _.dataSize) val xorCost = constCost + perKbCostOf(sizeOfArgs, hashPerKb / 2) cost("{ xor(key1, key1).size > 0 }")(xorCost + LengthGTConstCost) } property("Context operations cost") { val d = new TestData; import d._ cost("{ HEIGHT > 0 }")(selectField + GTConstCost) cost("{ OUTPUTS.size > 0 }")(OutputsCost + LengthGTConstCost) cost("{ INPUTS.size > 0 }")(InputsCost + LengthGTConstCost) cost("{ CONTEXT.dataInputs.size > 0 }")(DataInputsCost + LengthGTConstCost) cost("{ LastBlockUtxoRootHash.isUpdateAllowed }")(selectField + selectField) cost("{ MinerPubkey.size > 0 }")(selectField + LengthGTConstCost) cost("{ CONTEXT.headers.size > 0 }")(HeadersCost + LengthGTConstCost) cost("{ CONTEXT.preHeader.height > 0 }")(PreHeaderCost + selectField + GTConstCost) cost("{ CONTEXT.selfBoxIndex > 0 }") (selectField + GTConstCost) } property("PreHeader operations cost") { val d = new TestData; import d._ cost("{ CONTEXT.preHeader.version > 0 }")(PreHeaderCost + selectField + castOp + GTConstCost) cost("{ CONTEXT.preHeader.parentId.size > 0 }")(PreHeaderCost + selectField + LengthGTConstCost) cost("{ CONTEXT.preHeader.timestamp > 0L }")(PreHeaderCost + selectField + GTConstCost) cost("{ CONTEXT.preHeader.nBits > 0L }")(PreHeaderCost + selectField + GTConstCost) cost("{ CONTEXT.preHeader.height > 0 }")(PreHeaderCost + selectField + GTConstCost) cost("{ CONTEXT.preHeader.minerPk == groupGenerator }")( PreHeaderCost + selectField + comparisonCost + selectField) cost("{ CONTEXT.preHeader.votes.size > 0 }")(PreHeaderCost + selectField + LengthGTConstCost) } property("Header operations cost") { val d = new TestData; import d._ val header = "CONTEXT.headers(0)" cost(s"{ $header.id.size > 0 }")(AccessHeaderCost + selectField + LengthGTCost) cost(s"{ $header.version > 0 }")(AccessHeaderCost + selectField + castOp + comparisonCost) cost(s"{ $header.parentId.size > 0 }")(AccessHeaderCost + selectField + LengthGTCost) cost(s"{ $header.ADProofsRoot.size > 0 }")(AccessHeaderCost + selectField + LengthGTCost) cost(s"{ $header.stateRoot.isUpdateAllowed }")(AccessHeaderCost + selectField + selectField) cost(s"{ $header.transactionsRoot.size > 0 }")(AccessHeaderCost + selectField + LengthGTCost) cost(s"{ $header.timestamp > 0L }")(AccessHeaderCost + selectField + GTConstCost) cost(s"{ $header.nBits > 0L }")(AccessHeaderCost + selectField + GTConstCost) cost(s"{ $header.height > 0 }")(AccessHeaderCost + selectField + comparisonCost) cost(s"{ $header.extensionRoot.size > 0 }")(AccessHeaderCost + selectField + LengthGTCost) cost(s"{ $header.minerPk == groupGenerator }")(AccessHeaderCost + selectField + comparisonCost + selectField) cost(s"{ $header.powOnetimePk == groupGenerator }")(AccessHeaderCost + selectField + comparisonCost + selectField) cost(s"{ $header.powNonce.size > 0 }")(AccessHeaderCost + selectField + LengthGTCost) cost(s"{ $header.powDistance > 0 }")(AccessHeaderCost + selectField + comparisonBigInt + constCost) cost(s"{ $header.votes.size > 0 }")(AccessHeaderCost + selectField + LengthGTCost) } val AccessRootHash = selectField def perKbCostOf(dataSize: Long, opCost: Int) = { ((dataSize / 1024L).toInt + 1) * opCost } property("AvlTree operations cost") { val d = new TestData; import d._ val rootTree = "LastBlockUtxoRootHash" // cost(s"{ $rootTree.digest.size > 0 }")(AccessRootHash + selectField + LengthGTConstCost) // cost(s"{ $rootTree.enabledOperations > 0 }")(AccessRootHash + selectField + castOp + GTConstCost) // cost(s"{ $rootTree.keyLength > 0 }")(AccessRootHash + selectField + GTConstCost) // cost(s"{ $rootTree.isInsertAllowed }")(AccessRootHash + selectField) // cost(s"{ $rootTree.isUpdateAllowed }")(AccessRootHash + selectField) // cost(s"{ $rootTree.isRemoveAllowed }")(AccessRootHash + selectField) // cost(s"{ $rootTree.updateDigest($rootTree.digest) == $rootTree }") shouldBe // (AccessRootHash + selectField + newAvlTreeCost + comparisonCost /* for isConstantSize AvlTree type */) // cost(s"{ $rootTree.updateOperations(1.toByte) == $rootTree }") shouldBe // (AccessRootHash + newAvlTreeCost + comparisonCost + constCost) val AccessTree = accessBox + RegisterAccess val selfTree = "SELF.R6[AvlTree].get" val sizeOfArgs = Seq(sizeOf(avlTree), sizeOf(key1), sizeOf(lookupProof)).foldLeft(0L)(_ + _.dataSize) val containsCost = perKbCostOf(sizeOfArgs, avlTreeOp) cost(s"{ $selfTree.contains(key1, lookupProof) }")(AccessTree + containsCost + 2 * constCost) cost(s"{ $selfTree.get(key1, lookupProof).isDefined }")(AccessTree + containsCost + 2 * constCost + selectField) cost(s"{ $selfTree.getMany(keys, lookupProof).size > 0 }")(AccessTree + containsCost + 2 * constCost + LengthGTConstCost) cost(s"{ $rootTree.valueLengthOpt.isDefined }") (AccessRootHash + selectField + selectField) cost(s"{ $selfTree.update(Coll[(Coll[Byte], Coll[Byte])]((key1, key1)), lookupProof).isDefined }") ( AccessTree + perKbCostOf( Seq(sizeOf(avlTree), sizeOf(key1), sizeOf(key1), sizeOf(lookupProof)).foldLeft(0L)(_ + _.dataSize), avlTreeOp ) + concreteCollectionItemCost + collToColl + constCost * 2 + newPairValueCost + selectField) cost(s"{ $selfTree.remove(keys, lookupProof).isDefined }")( AccessTree + perKbCostOf( Seq(sizeOf(avlTree), sizeOf(key1), sizeOf(lookupProof)).foldLeft(0L)(_ + _.dataSize), avlTreeOp ) + constCost * 2 + selectField) // cost(s"{ $selfTree.insert(Coll[(Coll[Byte], Coll[Byte])]((key2, key1)), lookupProof).isDefined }") // (AccessTree + // perKbCostOf( // Seq(sizeOf(avlTree), sizeOf(key2), sizeOf(key1), sizeOf(lookupProof)).foldLeft(0L)(_ + _.dataSize), // avlTreeOp // ) // + concreteCollectionItemCost + collToColl + constCost * 3 + newPairValueCost + selectField) } property("Coll operations cost") { val d = new TestData; import d._ val coll = "OUTPUTS" val nOutputs = tx.outputs.length val collBytes = "CONTEXT.headers(0).id" cost(s"{ $coll.filter({ (b: Box) => b.value > 1L }).size > 0 }")( selectField + lambdaCost + (accessBox + extractCost + constCost + comparisonCost + lambdaInvoke) * nOutputs + collToColl + LengthGTConstCost) cost(s"{ $coll.flatMap({ (b: Box) => b.propositionBytes }).size > 0 }")( lambdaCost + selectField + (accessBox + extractCost + lambdaInvoke) * nOutputs + collToColl + LengthGTConstCost) cost(s"{ $coll.zip(OUTPUTS).size > 0 }")( selectField + accessBox * tx.outputs.length + accessBox * nOutputs * 2 + collToColl + LengthGTConstCost) cost(s"{ $coll.map({ (b: Box) => b.value })(0) > 0 }")( lambdaCost + selectField + (accessBox + extractCost + lambdaInvoke) * nOutputs + collToColl + collByIndex + constCost + GTConstCost) cost(s"{ $coll.exists({ (b: Box) => b.value > 1L }) }") ( lambdaCost + selectField + (accessBox + extractCost + constCost + comparisonCost + lambdaInvoke) * nOutputs + collToColl) cost(s"{ $coll.append(OUTPUTS).size > 0 }")( selectField + accessBox * tx.outputs.length + accessBox * tx.outputs.length * 2 + collToColl + LengthGTConstCost) cost(s"{ $coll.indices.size > 0 }")( selectField + accessBox * tx.outputs.length + selectField + LengthGTConstCost) cost(s"{ $collBytes.getOrElse(0, 1.toByte) == 0 }")( AccessHeaderCost + selectField + castOp + collByIndex + comparisonCost + constCost) // cost(s"{ $coll.fold(0L, { (acc: Long, b: Box) => acc + b.value }) > 0 }")( // selectField + constCost + // (extractCost + plusMinus + lambdaInvoke) * nOutputs + GTConstCost) cost(s"{ $coll.forall({ (b: Box) => b.value > 1L }) }")( lambdaCost + selectField + (accessBox + extractCost + GTConstCost + lambdaInvoke) * nOutputs + collToColl) cost(s"{ $coll.slice(0, 1).size > 0 }")( selectField + collToColl + accessBox * tx.outputs.length + LengthGTConstCost) // cost(s"{ $collBytes.patch(1, Coll(3.toByte), 1).size > 0 }")( // AccessHeaderCost + constCost * 3 + concreteCollectionItemCost + collToColl + collToColl + LengthGTConstCost) cost(s"{ $collBytes.updated(0, 1.toByte).size > 0 }")( AccessHeaderCost + selectField + collToColl + LengthGTConstCost) // cost(s"{ $collBytes.updateMany(Coll(0), Coll(1.toByte)).size > 0 }") // (AccessHeaderCost + collToColl + constCost * 2 + concreteCollectionItemCost + LengthGTConstCost) } property("Option operations cost") { val d = new TestData; import d._ val opt = "SELF.R5[Int]" val accessOpt = accessBox + accessRegister cost(s"{ $opt.get > 0 }")(accessOpt + selectField + GTConstCost) cost(s"{ $opt.isDefined }")(accessOpt + selectField) cost(s"{ $opt.getOrElse(1) > 0 }")(accessOpt + selectField + constCost + GTConstCost) cost(s"{ $opt.filter({ (x: Int) => x > 0}).isDefined }")( accessOpt + OptionOp + lambdaCost + GTConstCost + selectField) cost(s"{ $opt.map({ (x: Int) => x + 1}).isDefined }")( accessOpt + OptionOp + lambdaCost + plusMinus + constCost + selectField) } property("TrueLeaf cost") { val d = new TestData; import d._ cost("{ true }")(constCost) } property("ErgoTree with TrueLeaf costs") { val d = new TestData; import d._ val tree = ErgoTree(16, IndexedSeq(TrueLeaf), BoolToSigmaProp(ConstantPlaceholder(0, SBoolean))) val pr = interpreter.prove(tree, context, fakeMessage).get val expressionCost = constCost + logicCost + // SigmaPropIsProven logicCost // BoolToSigmaProp val expectedCost = (expressionCost * CostTable.costFactorIncrease / CostTable.costFactorDecrease) + CostTable.interpreterInitCost + tree.complexity if (isActivatedVersion4) { pr.cost shouldBe expectedCost } else { pr.cost shouldBe 10185 } val verifier = new ErgoLikeTestInterpreter val cost = verifier.verify(emptyEnv, tree, context, pr, fakeMessage).get._2 if (isActivatedVersion4) { cost shouldBe expectedCost } else { cost shouldBe 10185 } } property("ErgoTree with SigmaPropConstant costs") { val d = new TestData; import d._ /** Helper method used in tests. * @param expectedCostV5 expected value of v5.0 cost if defined, otherwise should be * equal to `expectedCost` */ def proveAndVerify(ctx: ErgoLikeContext, tree: ErgoTree, expectedCost: Long, expectedCostV5: Option[Long] = None) = { val pr = interpreter.prove(tree, ctx, fakeMessage).get if (isActivatedVersion4) { pr.cost shouldBe expectedCost } else { pr.cost shouldBe expectedCostV5.getOrElse(expectedCost) } val verifier = new ErgoLikeTestInterpreter val cost = verifier.verify(emptyEnv, tree, ctx, pr, fakeMessage).get._2 if (isActivatedVersion4) { cost shouldBe expectedCost } else { cost shouldBe expectedCostV5.getOrElse(expectedCost) } } // simple trees containing SigmaPropConstant val tree1 = ErgoTree.fromSigmaBoolean(pkA) // without segregation val tree2 = ErgoTree.withSegregation(pkA) // with segregation, have different `complexity` { val ctx = context.withInitCost(0) proveAndVerify(ctx, tree1, expectedCost = 10141, expectedCostV5 = Some(483)) proveAndVerify(ctx, tree2, expectedCost = 10161, expectedCostV5 = Some(503)) } { val ctx = context.withInitCost(10000) proveAndVerify(ctx, tree1, expectedCost = 20141, expectedCostV5 = Some(10483)) proveAndVerify(ctx, tree2, expectedCost = 20161, expectedCostV5 = Some(10503)) } { if (isActivatedVersion4) { val ctx = context.withInitCost(10000).withCostLimit(20000) assertExceptionThrown( proveAndVerify(ctx, tree1, expectedCost = 20141), exceptionLike[CostLimitException]( "Estimated execution cost", "exceeds the limit") ) } else { val ctx = context.withInitCost(10000).withCostLimit(10400) assertExceptionThrown( proveAndVerify(ctx, tree1, expectedCost = 20141, expectedCostV5 = Some(10483)), exceptionLike[CostLimitException]( "Estimated execution cost", "exceeds the limit") ) } } // more complex tree without Deserialize val tree3 = ErgoTree.fromProposition(compiler .compile(env, "{ sigmaProp(HEIGHT == 2) }") .asSigmaProp) proveAndVerify(context.withInitCost(0), tree3, expectedCost = 541, expectedCostV5 = Some(495)) proveAndVerify(context.withInitCost(10000), tree3, expectedCost = 10541, expectedCostV5 = Some(10495)) } property("laziness of AND, OR costs") { val d = new TestData; import d._ cost("{ val cond = getVar[Boolean](2).get; !(!cond && (1 / 0 == 1)) }")( ContextVarAccess + constCost * 2 + logicCost * 3 + multiply + comparisonCost) cost("{ val cond = getVar[Boolean](2).get; (cond || (1 / 0 == 1)) }")( ContextVarAccess + constCost * 2 + logicCost + multiply + comparisonCost) } }
ScorexFoundation/sigmastate-interpreter
sigmastate/src/test/scala/sigmastate/CostingSpecification.scala
Scala
mit
22,905
package breeze.optimize /* Copyright 2009 David Hall, Daniel Ramage 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. */ import org.scalatest._ import org.scalatest.junit._ import org.scalatest.prop._ import org.scalacheck._ import org.junit.runner.RunWith import breeze.linalg._ @RunWith(classOf[JUnitRunner]) class StochasticAveragedGradientTest extends OptimizeTestBase { test("optimize a simple multivariate gaussian") { val lbfgs = new StochasticAveragedGradient [DenseVector[Double]](100) def optimizeThis(init: DenseVector[Double]) = { val f = BatchDiffFunction.wrap(new DiffFunction[DenseVector[Double]] { def calculate(x: DenseVector[Double]) = { ((sum((x - 3.0) :^ 2.0)), (x * 2.0) - 6.0) } }) val result = lbfgs.minimize(f,init) norm(result - 3.0,2) < 1E-3 } check(Prop.forAll(optimizeThis _)) } test("optimize a simple multivariate gaussian with l2 regularization") { val lbfgs = new StochasticAveragedGradient [DenseVector[Double]](400, l2Regularization = 1.0) def optimizeThis(init: DenseVector[Double]) = { val f = new DiffFunction[DenseVector[Double]] { def calculate(x: DenseVector[Double]) = { (norm((x -3.0) :^ 2.0,1), (x * 2.0) - 6.0) } } val targetValue = 3 / (1.0 / 2 + 1) val result = lbfgs.minimize(BatchDiffFunction.wrap(f),init) val ok = norm(result :- DenseVector.ones[Double](init.size) * targetValue,2)/result.size < 3E-3 ok || (throw new RuntimeException("Failed to find optimum for init " + init + " " + result + " " + targetValue)) } check(Prop.forAll(optimizeThis _)) } /* test("lbfgs-c rosenbroch example") { val lbfgs = new LBFGS[DenseVector[Double]](40,6) def optimizeThis(init: DenseVector[Double]) = { val f = new DiffFunction[DenseVector[Double]] { def calculate(x: DenseVector[Double]) = { var fx = 0.0 val g = DenseVector.zeros[Double](x.length) for(i <- 0 until x.length by 2) { val t1 = 1.0 - x(i) val t2 = 10.0 * (x(i+1) - x(i) * x(i)) g(i+1) = 20 * t2 g(i) = -2 * (x(i) * g(i+1) + t1) fx += t1 * t1 + t2 * t2 } fx -> g } } val targetValue = 1.0 val result = lbfgs.minimize(f,init) val ok = norm(result :- DenseVector.ones[Double](init.size) * targetValue,2)/result.size < 1E-5 ok || (throw new RuntimeException("Failed to find optimum for init " + init)) } val init = DenseVector.zeros[Double](100) init(0 until init.length by 2) := -1.2 init(1 until init.length by 2) := 1.0 assert(optimizeThis(init)) } */ }
chen0031/breeze
math/src/test/scala/breeze/optimize/StochasticAveragedGradientTest.scala
Scala
apache-2.0
3,216
package com.twitter.finagle.memcached import com.twitter.io.Buf import com.twitter.util._ import _root_.java.util.concurrent.Executors import scala.collection.mutable.ArrayBuffer import _root_.java.util.Random /** * This class is designed to support replicated memcached setups. It supports a limited * subset of operations (just get, set, and delete). */ class PoolingReadRepairClient( allClients: Seq[BaseClient[Buf]], readRepairProbability: Float, readRepairCount: Int = 1, futurePool: FuturePool = new ExecutorServiceFuturePool(Executors.newCachedThreadPool())) extends Client { val rand = new Random() def getResult(keys: Iterable[String]) = { val clients = getSubsetOfClients() val futures = clients.map(_.getResult(keys)) if (futures.size == 1) { // Don't bother being fancy, just GTFO futures.head } else { // We construct a return value future that we will update manually ourselves // to accommodate the more complicated logic. val answer = new Promise[GetResult] // First pass: return the first complete, correct answer from the clients val futureAttempts = futures.map { future => future.map { result => if (result.hits.size == keys.size) { answer.updateIfEmpty(Try(result)) } result } } // Second pass Future.collect(futureAttempts).map { results => // Generate the union of the clients answers, and call it truth val canon = results.foldLeft(new GetResult())(_ ++ _) // Return the truth, if we didn't earlier answer.updateIfEmpty(Try(canon)) // Read-repair clients that had partial values results.zip(clients).map { tuple => val missing = canon.hits -- tuple._1.hits.keys missing.map { hit => set(hit._1, hit._2.value) } } } answer } } def getSubsetOfClients() = { val num = if (rand.nextFloat < readRepairProbability) readRepairCount + 1 else 1 val buf = new ArrayBuffer[BaseClient[Buf]] allClients.copyToBuffer(buf) while (buf.size > num) { buf.remove(rand.nextInt(buf.size)) } buf.toSeq } def close(deadline: Time): Future[Unit] = Closable.all(allClients: _*).close(deadline) def set(key: String, flags: Int, expiry: Time, value: Buf) = { val futures = allClients.map(_.set(key, flags, expiry, value)) val base = futures.head futures.tail.foldLeft(base)(_.or(_)) } def delete(key: String) = Future.collect(allClients.map(_.delete(key))).map(_.exists(x => x)) def getsResult(keys: Iterable[String]) = unsupported def stats(args: Option[String]) = unsupported def decr(key: String, delta: Long) = unsupported def incr(key: String, delta: Long) = unsupported def checkAndSet(key: String, flags: Int, expiry: Time, value: Buf, casUnique: Buf) = unsupported def replace(key: String, flags: Int, expiry: Time, value: Buf) = unsupported def prepend(key: String, flags: Int, expiry: Time, value: Buf) = unsupported def append(key: String, flags: Int, expiry: Time, value: Buf) = unsupported def add(key: String, flags: Int, expiry: Time, value: Buf) = unsupported private def unsupported = throw new UnsupportedOperationException }
twitter/finagle
finagle-memcached/src/main/scala/com/twitter/finagle/memcached/PoolingReadRepairClient.scala
Scala
apache-2.0
3,281
/* * Copyright 2017 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.hmrc.ct.ct600e.v3 import uk.gov.hmrc.ct.box._ import uk.gov.hmrc.ct.ct600e.v3.retriever.CT600EBoxRetriever case class E175(value: Option[Int]) extends CtBoxIdentifier("Held at the end of the period (use accounts figures): Other current assets") with CtOptionalInteger with Input with ValidatableBox[CT600EBoxRetriever]{ override def validate(boxRetriever: CT600EBoxRetriever): Set[CtValidation] = validateZeroOrPositiveInteger(this) }
liquidarmour/ct-calculations
src/main/scala/uk/gov/hmrc/ct/ct600e/v3/E175.scala
Scala
apache-2.0
1,061
package com.github.agourlay.cornichon.core import cats.syntax.monoid._ case class RunState( session: Session, logs: Vector[LogInstruction], depth: Int, cleanupSteps: List[Step] ) { lazy val goDeeper = copy(depth = depth + 1) lazy val resetLogs = copy(logs = Vector.empty) // Helper fct to setup up a child nested context for a run which result must be merged back in using 'mergeNested'. // Only the session is propagated downstream as it is. lazy val nestedContext = copy(depth = depth + 1, logs = Vector.empty, cleanupSteps = Nil) lazy val sameLevelContext = copy(logs = Vector.empty, cleanupSteps = Nil) def withSession(s: Session) = copy(session = s) def addToSession(tuples: Seq[(String, String)]) = withSession(session.addValuesUnsafe(tuples: _*)) def addToSession(key: String, value: String) = withSession(session.addValueUnsafe(key, value)) def mergeSessions(other: Session) = copy(session = session.combine(other)) def withLog(log: LogInstruction) = copy(logs = Vector(log)) // Vector concat. is not great, maybe change logs data structure def appendLogs(add: Vector[LogInstruction]) = copy(logs = logs ++ add) def appendLogsFrom(from: RunState) = appendLogs(from.logs) def appendLog(add: LogInstruction) = copy(logs = logs :+ add) // Cleanups steps are added in the opposite order def prependCleanupStep(add: Step) = copy(cleanupSteps = add :: cleanupSteps) def prependCleanupSteps(add: List[Step]) = copy(cleanupSteps = add ::: cleanupSteps) def prependCleanupStepsFrom(from: RunState) = copy(cleanupSteps = from.cleanupSteps ::: cleanupSteps) lazy val resetCleanupSteps = copy(cleanupSteps = Nil) // Helpers to propagate info from nested computation def mergeNested(r: RunState): RunState = mergeNested(r, r.logs) def mergeNested(r: RunState, computationLogs: Vector[LogInstruction]): RunState = this.copy( session = r.session, // no need to combine, nested session is built on top of the initial one cleanupSteps = r.cleanupSteps ::: this.cleanupSteps, // prepend cleanup steps logs = this.logs ++ computationLogs // logs are often built manually and not extracted from RunState ) } object RunState { val emptyRunState = RunState(Session.newEmpty, Vector.empty, 1, Nil) }
OlegIlyenko/cornichon
cornichon-core/src/main/scala/com/github/agourlay/cornichon/core/RunState.scala
Scala
apache-2.0
2,284
/* * Copyright 2017 HM Revenue & Customs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.gov.hmrc.ct.ct600j.v2.retriever import uk.gov.hmrc.ct.box.retriever.BoxRetriever import uk.gov.hmrc.ct.ct600j.v2.TAQ01 trait CT600JBoxRetriever extends BoxRetriever { def taq01(): TAQ01 }
liquidarmour/ct-calculations
src/main/scala/uk/gov/hmrc/ct/ct600j/v2/retriever/CT600JBoxRetriever.scala
Scala
apache-2.0
809
package slick.codegen import java.net.URI import scala.concurrent.{ExecutionContext, Await} import scala.concurrent.duration.Duration import scala.util.Try import slick.basic.DatabaseConfig import slick.{model => m} import slick.jdbc.JdbcProfile import slick.util.ConfigExtensionMethods.configExtensionMethods /** * A customizable code generator for working with Slick. * * For usage information please see the corresponding part of the Slick documentation. * * The implementation is structured into a small hierarchy of sub-generators responsible * for different fragments of the complete output. The implementation of each * sub-generator can be swapped out for a customized one by overriding the corresponding * factory method. SourceCodeGenerator contains a factory method Table, which it uses to * generate a sub-generator for each table. The sub-generator Table in turn contains * sub-generators for Table classes, entity case classes, columns, key, indices, etc. * Custom sub-generators can easily be added as well. * * Within the sub-generators the relevant part of the Slick data `model` can * be accessed to drive the code generation. * * Of coures it makes sense to integrate this into your build process. * @param model Slick data model for which code should be generated. */ class SourceCodeGenerator(model: m.Model) extends AbstractSourceCodeGenerator(model) with OutputHelpers{ // "Tying the knot": making virtual classes concrete type Table = TableDef def Table = new TableDef(_) class TableDef(model: m.Table) extends super.TableDef(model){ // Using defs instead of (caching) lazy vals here to provide consitent interface to the user. // Performance should really not be critical in the code generator. Models shouldn't be huge. // Also lazy vals don't inherit docs from defs type EntityType = EntityTypeDef def EntityType = new EntityType{} type PlainSqlMapper = PlainSqlMapperDef def PlainSqlMapper = new PlainSqlMapper{} type TableClass = TableClassDef def TableClass = new TableClass{} type TableValue = TableValueDef def TableValue = new TableValue{} type Column = ColumnDef def Column = new Column(_) type PrimaryKey = PrimaryKeyDef def PrimaryKey = new PrimaryKey(_) type ForeignKey = ForeignKeyDef def ForeignKey = new ForeignKey(_) type Index = IndexDef def Index = new Index(_) } } /** A runnable class to execute the code generator without further setup */ object SourceCodeGenerator { def run(profile: String, jdbcDriver: String, url: String, outputDir: String, pkg: String, user: Option[String], password: Option[String], ignoreInvalidDefaults: Boolean): Unit = { val profileInstance: JdbcProfile = Class.forName(profile + "$").getField("MODULE$").get(null).asInstanceOf[JdbcProfile] val dbFactory = profileInstance.api.Database val db = dbFactory.forURL(url, driver = jdbcDriver, user = user.getOrElse(null), password = password.getOrElse(null), keepAliveConnection = true) try { val m = Await.result(db.run(profileInstance.createModel(None, ignoreInvalidDefaults)(ExecutionContext.global).withPinnedSession), Duration.Inf) new SourceCodeGenerator(m).writeToFile(profile,outputDir,pkg) } finally db.close } def run(uri: URI, outputDir: Option[String], ignoreInvalidDefaults: Boolean = true): Unit = { val dc = DatabaseConfig.forURI[JdbcProfile](uri) val pkg = dc.config.getString("codegen.package") val out = outputDir.getOrElse(dc.config.getStringOr("codegen.outputDir", ".")) val profile = if(dc.profileIsObject) dc.profileName else "new " + dc.profileName try { val m = Await.result(dc.db.run(dc.profile.createModel(None, ignoreInvalidDefaults)(ExecutionContext.global).withPinnedSession), Duration.Inf) new SourceCodeGenerator(m).writeToFile(profile, out, pkg) } finally dc.db.close } def main(args: Array[String]): Unit = { args.toList match { case uri :: Nil => run(new URI(uri), None) case uri :: outputDir :: Nil => run(new URI(uri), Some(outputDir)) case profile :: jdbcDriver :: url :: outputDir :: pkg :: Nil => run(profile, jdbcDriver, url, outputDir, pkg, None, None, true) case profile :: jdbcDriver :: url :: outputDir :: pkg :: user :: password :: Nil => run(profile, jdbcDriver, url, outputDir, pkg, Some(user), Some(password), true) case profile:: jdbcDriver :: url :: outputDir :: pkg :: user :: password :: ignoreInvalidDefaults :: Nil => run(profile, jdbcDriver, url, outputDir, pkg, Some(user), Some(password), ignoreInvalidDefaults.toBoolean) case _ => { println(""" |Usage: | SourceCodeGenerator configURI [outputDir] | SourceCodeGenerator profile jdbcDriver url outputDir pkg [user password] | |Options: | configURI: A URL pointing to a standard database config file (a fragment is | resolved as a path in the config), or just a fragment used as a path in | application.conf on the class path | profile: Fully qualified name of Slick profile class, e.g. "slick.jdbc.H2Profile" | jdbcDriver: Fully qualified name of jdbc driver class, e.g. "org.h2.Driver" | url: JDBC URL, e.g. "jdbc:postgresql://localhost/test" | outputDir: Place where the package folder structure should be put | pkg: Scala package the generated code should be places in | user: database connection user name | password: database connection password | |When using a config file, in addition to the standard config parameters from |slick.basic.DatabaseConfig you can set "codegen.package" and |"codegen.outputDir". The latter can be overridden on the command line. """.stripMargin.trim) System.exit(1) } } } }
AtkinsChang/slick
slick-codegen/src/main/scala/slick/codegen/SourceCodeGenerator.scala
Scala
bsd-2-clause
6,136
package rescala.api import rescala.core.{CreationTicket, Engine, Struct} import rescala.meta._ import rescala.reactives.Signals import scala.language.higherKinds trait Api { type Signal[+A] type Event[+A] type Var[A] <: Signal[A] type Evt[A] <: Event[A] def Evt[A](): Evt[A] def Var[A](v: A): Var[A] def observe[A](event: Event[A])(f: A => Unit): Unit def now[A](signal: Signal[A]): A def fire[A](evt: Evt[A], value: A): Unit def set[A](vr: Var[A], value: A): Unit def disconnectE(event: Event[_]): Unit def disconnectS(signal: Signal[_]): Unit def mapS[A, B](signal: Signal[A])(f: A => B): Signal[B] def mapE[A, B](event: Event[A])(f: A => B): Event[B] def fold[A, Acc](event: Event[A])(init: Acc)(f: (Acc, A) => Acc): Signal[Acc] def changed[A](signal: Signal[A]): Event[A] def filter[A](event: Event[A])(f: A => Boolean): Event[A] def and[A, B, C](event: Event[A], other: Event[B])(merger: (A, B) => C): Event[C] def or[A, B >: A](event: Event[A], other: Event[B]): Event[B] def zip[A, B](event: Event[A], other: Event[B]): Event[(A, B)] def except[A, B](event: Event[A], other: Event[B]): Event[A] def change[A](signal: Signal[A]): Event[Signals.Diff[A]] def snapshot[A](event: Event[_], signal: Signal[A]): Signal[A] def switchOnce[A](event: Event[_], a: Signal[A], b: Signal[A]): Signal[A] def switchTo[A](event: Event[A], a: Signal[A]): Signal[A] def toggle[A](event: Event[_], a: Signal[A], b: Signal[A]): Signal[A] } object Api { object synchronApi extends Api { import rescala.Schedulers.synchron override type Signal[+A] = synchron.Signal[A] override type Event[+A] = synchron.Event[A] override type Var[A] = synchron.Var[A] override type Evt[A] = synchron.Evt[A] override def Evt[A](): Evt[A] = synchron.Evt() override def Var[A](v: A): Var[A] = synchron.Var(v) override def mapS[A, B](signal: Signal[A])(f: (A) => B): Signal[B] = signal.map(f) override def mapE[A, B](event: Event[A])(f: (A) => B): Event[B] = event.map(f) override def fold[A, Acc](event: Event[A])(init: Acc)(f: (Acc, A) => Acc): Signal[Acc] = event.fold(init)(f) override def changed[A](signal: Signal[A]): Event[A] = signal.changed override def observe[A](event: Event[A])(f: (A) => Unit): Unit = event.observe(f) override def now[A](signal: Signal[A]): A = signal.readValueOnce override def fire[A](evt: Evt[A], value: A): Unit = evt.fire(value) override def set[A](vr: Var[A], value: A): Unit = vr.set(value) override def disconnectE(event: Event[_]): Unit = event.disconnect() override def disconnectS(signal: Signal[_]): Unit = signal.disconnect() override def filter[A](event: Event[A])(f: A => Boolean): Event[A] = event.filter(f) override def and[A, B, C](event: Event[A], other: Event[B])(merger: (A, B) => C): Event[C] = event.and(other)(merger) override def or[A, B >: A](event: Event[A], other: Event[B]): Event[B] = event || other override def zip[A, B](event: Event[A], other: Event[B]): Event[(A, B)] = event.zip(other) override def except[A, B](event: Event[A], other: Event[B]): Event[A] = event \\ other override def change[A](signal: Signal[A]): Event[Signals.Diff[A]] = signal.change override def snapshot[A](event: Event[_], signal: Signal[A]): Signal[A] = event.snapshot(signal) override def switchOnce[A](event: Event[_], a: Signal[A], b: Signal[A]): Signal[A] = event.switchOnce(a, b) override def switchTo[A](event: Event[A], a: Signal[A]): Signal[A] = event.switchTo(a) override def toggle[A](event: Event[_], a: Signal[A], b: Signal[A]): Signal[A] = event.toggle(a, b) } class metaApi[S <: Struct](graph: DataFlowGraph)(implicit val reifier: Reifier[S], ticket: CreationTicket[S], engine: Engine[S] ) extends Api { override type Signal[+A] = SignalRef[A] override type Event[+A] = EventRef[A] override type Var[A] = VarRef[A] override type Evt[A] = EvtRef[A] override def Evt[A](): Evt[A] = graph.createEvt() override def Var[A](v: A): Var[A] = graph.createVar(v) override def mapS[A, B](signal: Signal[A])(f: (A) => B): Signal[B] = signal.map(f) override def mapE[A, B](event: Event[A])(f: (A) => B): Event[B] = event.map(f) override def fold[A, Acc](event: Event[A])(init: Acc)(f: (Acc, A) => Acc): Signal[Acc] = event.fold(init)(f) override def changed[A](signal: Signal[A]): Event[A] = signal.changed override def observe[A](event: Event[A])(f: (A) => Unit): Unit = event.observe(f) override def now[A](signal: Signal[A]): A = signal.now override def fire[A](evt: Evt[A], value: A): Unit = evt.fire(value) override def set[A](vr: Var[A], value: A): Unit = vr.set(value) override def disconnectE(event: Event[_]): Unit = event.disconnect() override def disconnectS(signal: Signal[_]): Unit = signal.disconnect() override def filter[A](event: Event[A])(f: A => Boolean): Event[A] = event && f override def and[A, B, C](event: Event[A], other: Event[B])(merger: (A, B) => C): Event[C] = event.and(other)(merger) override def or[A, B >: A](event: Event[A], other: Event[B]): Event[B] = event || other override def zip[A, B](event: Event[A], other: Event[B]): Event[(A, B)] = event.zip(other) override def except[A, B](event: Event[A], other: Event[B]): Event[A] = event \\ other override def change[A](signal: Signal[A]): Event[Signals.Diff[A]] = signal.change override def snapshot[A](event: Event[_], signal: Signal[A]): Signal[A] = event.snapshot(signal) override def switchOnce[A](event: Event[_], a: Signal[A], b: Signal[A]): Signal[A] = event.switchOnce(a, b) override def switchTo[A](event: Event[A], a: Signal[A]): Signal[A] = event.switchTo(a) override def toggle[A](event: Event[_], a: Signal[A], b: Signal[A]): Signal[A] = event.toggle(a, b) } }
guidosalva/REScala
Historical/Meta/src/main/scala/rescala/api/Api.scala
Scala
apache-2.0
6,601
package pl.project13.scala.akka.raft.config import akka.actor.{ExtendedActorSystem, ExtensionIdProvider, ExtensionId} object RaftConfiguration extends ExtensionId[RaftConfig] with ExtensionIdProvider { def lookup() = RaftConfiguration def createExtension(system: ExtendedActorSystem): RaftConfig = new RaftConfig(system.settings.config) }
ktoso/akka-raft
src/main/scala/pl/project13/scala/akka/raft/config/RaftConfiguration.scala
Scala
apache-2.0
347
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.catalyst import org.apache.spark.sql.catalyst.analysis.{GetColumnByOrdinal, UnresolvedAttribute, UnresolvedExtractValue} import org.apache.spark.sql.catalyst.expressions._ import org.apache.spark.sql.catalyst.expressions.objects._ import org.apache.spark.sql.catalyst.util.{ArrayBasedMapData, DateTimeUtils, GenericArrayData} import org.apache.spark.sql.types._ import org.apache.spark.unsafe.types.{CalendarInterval, UTF8String} /** * A helper trait to create [[org.apache.spark.sql.catalyst.encoders.ExpressionEncoder]]s * for classes whose fields are entirely defined by constructor params but should not be * case classes. */ trait DefinedByConstructorParams /** * A default version of ScalaReflection that uses the runtime universe. */ object ScalaReflection extends ScalaReflection { val universe: scala.reflect.runtime.universe.type = scala.reflect.runtime.universe // Since we are creating a runtime mirror using the class loader of current thread, // we need to use def at here. So, every time we call mirror, it is using the // class loader of the current thread. // SPARK-13640: Synchronize this because universe.runtimeMirror is not thread-safe in Scala 2.10. override def mirror: universe.Mirror = ScalaReflectionLock.synchronized { universe.runtimeMirror(Thread.currentThread().getContextClassLoader) } import universe._ // The Predef.Map is scala.collection.immutable.Map. // Since the map values can be mutable, we explicitly import scala.collection.Map at here. import scala.collection.Map /** * Returns the Spark SQL DataType for a given scala type. Where this is not an exact mapping * to a native type, an ObjectType is returned. Special handling is also used for Arrays including * those that hold primitive types. * * Unlike `schemaFor`, this function doesn't do any massaging of types into the Spark SQL type * system. As a result, ObjectType will be returned for things like boxed Integers */ def dataTypeFor[T : TypeTag]: DataType = dataTypeFor(localTypeOf[T]) private def dataTypeFor(tpe: `Type`): DataType = ScalaReflectionLock.synchronized { tpe match { case t if t <:< definitions.IntTpe => IntegerType case t if t <:< definitions.LongTpe => LongType case t if t <:< definitions.DoubleTpe => DoubleType case t if t <:< definitions.FloatTpe => FloatType case t if t <:< definitions.ShortTpe => ShortType case t if t <:< definitions.ByteTpe => ByteType case t if t <:< definitions.BooleanTpe => BooleanType case t if t <:< localTypeOf[Array[Byte]] => BinaryType case t if t <:< localTypeOf[CalendarInterval] => CalendarIntervalType case t if t <:< localTypeOf[Decimal] => DecimalType.SYSTEM_DEFAULT case _ => val className = getClassNameFromType(tpe) className match { case "scala.Array" => val TypeRef(_, _, Seq(elementType)) = tpe arrayClassFor(elementType) case other => val clazz = getClassFromType(tpe) ObjectType(clazz) } } } /** * Given a type `T` this function constructs and ObjectType that holds a class of type * Array[T]. Special handling is performed for primitive types to map them back to their raw * JVM form instead of the Scala Array that handles auto boxing. */ private def arrayClassFor(tpe: `Type`): DataType = ScalaReflectionLock.synchronized { val cls = tpe match { case t if t <:< definitions.IntTpe => classOf[Array[Int]] case t if t <:< definitions.LongTpe => classOf[Array[Long]] case t if t <:< definitions.DoubleTpe => classOf[Array[Double]] case t if t <:< definitions.FloatTpe => classOf[Array[Float]] case t if t <:< definitions.ShortTpe => classOf[Array[Short]] case t if t <:< definitions.ByteTpe => classOf[Array[Byte]] case t if t <:< definitions.BooleanTpe => classOf[Array[Boolean]] case other => // There is probably a better way to do this, but I couldn't find it... val elementType = dataTypeFor(other).asInstanceOf[ObjectType].cls java.lang.reflect.Array.newInstance(elementType, 1).getClass } ObjectType(cls) } /** * Returns true if the value of this data type is same between internal and external. */ def isNativeType(dt: DataType): Boolean = dt match { case NullType | BooleanType | ByteType | ShortType | IntegerType | LongType | FloatType | DoubleType | BinaryType | CalendarIntervalType => true case _ => false } /** * Returns an expression that can be used to deserialize an input row to an object of type `T` * with a compatible schema. Fields of the row will be extracted using UnresolvedAttributes * of the same name as the constructor arguments. Nested classes will have their fields accessed * using UnresolvedExtractValue. * * When used on a primitive type, the constructor will instead default to extracting the value * from ordinal 0 (since there are no names to map to). The actual location can be moved by * calling resolve/bind with a new schema. */ def deserializerFor[T : TypeTag]: Expression = { val tpe = localTypeOf[T] val clsName = getClassNameFromType(tpe) val walkedTypePath = s"""- root class: "${clsName}"""" :: Nil deserializerFor(tpe, None, walkedTypePath) } private def deserializerFor( tpe: `Type`, path: Option[Expression], walkedTypePath: Seq[String]): Expression = ScalaReflectionLock.synchronized { /** Returns the current path with a sub-field extracted. */ def addToPath(part: String, dataType: DataType, walkedTypePath: Seq[String]): Expression = { val newPath = path .map(p => UnresolvedExtractValue(p, expressions.Literal(part))) .getOrElse(UnresolvedAttribute(part)) upCastToExpectedType(newPath, dataType, walkedTypePath) } /** Returns the current path with a field at ordinal extracted. */ def addToPathOrdinal( ordinal: Int, dataType: DataType, walkedTypePath: Seq[String]): Expression = { val newPath = path .map(p => GetStructField(p, ordinal)) .getOrElse(GetColumnByOrdinal(ordinal, dataType)) upCastToExpectedType(newPath, dataType, walkedTypePath) } /** Returns the current path or `GetColumnByOrdinal`. */ def getPath: Expression = { val dataType = schemaFor(tpe).dataType if (path.isDefined) { path.get } else { upCastToExpectedType(GetColumnByOrdinal(0, dataType), dataType, walkedTypePath) } } /** * When we build the `deserializer` for an encoder, we set up a lot of "unresolved" stuff * and lost the required data type, which may lead to runtime error if the real type doesn't * match the encoder's schema. * For example, we build an encoder for `case class Data(a: Int, b: String)` and the real type * is [a: int, b: long], then we will hit runtime error and say that we can't construct class * `Data` with int and long, because we lost the information that `b` should be a string. * * This method help us "remember" the required data type by adding a `UpCast`. Note that we * don't need to cast struct type because there must be `UnresolvedExtractValue` or * `GetStructField` wrapping it, thus we only need to handle leaf type. */ def upCastToExpectedType( expr: Expression, expected: DataType, walkedTypePath: Seq[String]): Expression = expected match { case _: StructType => expr case _ => UpCast(expr, expected, walkedTypePath) } tpe match { case t if !dataTypeFor(t).isInstanceOf[ObjectType] => getPath case t if t <:< localTypeOf[Option[_]] => val TypeRef(_, _, Seq(optType)) = t val className = getClassNameFromType(optType) val newTypePath = s"""- option value class: "$className"""" +: walkedTypePath WrapOption(deserializerFor(optType, path, newTypePath), dataTypeFor(optType)) case t if t <:< localTypeOf[java.lang.Integer] => val boxedType = classOf[java.lang.Integer] val objectType = ObjectType(boxedType) NewInstance(boxedType, getPath :: Nil, objectType) case t if t <:< localTypeOf[java.lang.Long] => val boxedType = classOf[java.lang.Long] val objectType = ObjectType(boxedType) NewInstance(boxedType, getPath :: Nil, objectType) case t if t <:< localTypeOf[java.lang.Double] => val boxedType = classOf[java.lang.Double] val objectType = ObjectType(boxedType) NewInstance(boxedType, getPath :: Nil, objectType) case t if t <:< localTypeOf[java.lang.Float] => val boxedType = classOf[java.lang.Float] val objectType = ObjectType(boxedType) NewInstance(boxedType, getPath :: Nil, objectType) case t if t <:< localTypeOf[java.lang.Short] => val boxedType = classOf[java.lang.Short] val objectType = ObjectType(boxedType) NewInstance(boxedType, getPath :: Nil, objectType) case t if t <:< localTypeOf[java.lang.Byte] => val boxedType = classOf[java.lang.Byte] val objectType = ObjectType(boxedType) NewInstance(boxedType, getPath :: Nil, objectType) case t if t <:< localTypeOf[java.lang.Boolean] => val boxedType = classOf[java.lang.Boolean] val objectType = ObjectType(boxedType) NewInstance(boxedType, getPath :: Nil, objectType) case t if t <:< localTypeOf[java.sql.Date] => StaticInvoke( DateTimeUtils.getClass, ObjectType(classOf[java.sql.Date]), "toJavaDate", getPath :: Nil) case t if t <:< localTypeOf[java.sql.Timestamp] => StaticInvoke( DateTimeUtils.getClass, ObjectType(classOf[java.sql.Timestamp]), "toJavaTimestamp", getPath :: Nil) case t if t <:< localTypeOf[java.lang.String] => Invoke(getPath, "toString", ObjectType(classOf[String])) case t if t <:< localTypeOf[UTF8String] => Invoke(getPath, "cloneIfRequired", ObjectType(classOf[UTF8String])) case t if t <:< localTypeOf[java.math.BigDecimal] => Invoke(getPath, "toJavaBigDecimal", ObjectType(classOf[java.math.BigDecimal])) case t if t <:< localTypeOf[BigDecimal] => Invoke(getPath, "toBigDecimal", ObjectType(classOf[BigDecimal])) case t if t <:< localTypeOf[java.math.BigInteger] => Invoke(getPath, "toJavaBigInteger", ObjectType(classOf[java.math.BigInteger])) case t if t <:< localTypeOf[scala.math.BigInt] => Invoke(getPath, "toScalaBigInt", ObjectType(classOf[scala.math.BigInt])) case t if t <:< localTypeOf[Array[_]] => val TypeRef(_, _, Seq(elementType)) = t // TODO: add runtime null check for primitive array val primitiveMethod = elementType match { case t if t <:< definitions.IntTpe => Some("toIntArray") case t if t <:< definitions.LongTpe => Some("toLongArray") case t if t <:< definitions.DoubleTpe => Some("toDoubleArray") case t if t <:< definitions.FloatTpe => Some("toFloatArray") case t if t <:< definitions.ShortTpe => Some("toShortArray") case t if t <:< definitions.ByteTpe => Some("toByteArray") case t if t <:< definitions.BooleanTpe => Some("toBooleanArray") case _ => None } primitiveMethod.map { method => Invoke(getPath, method, arrayClassFor(elementType)) }.getOrElse { val className = getClassNameFromType(elementType) val newTypePath = s"""- array element class: "$className"""" +: walkedTypePath Invoke( MapObjects( p => deserializerFor(elementType, Some(p), newTypePath), getPath, schemaFor(elementType).dataType), "array", arrayClassFor(elementType)) } case t if t <:< localTypeOf[Seq[_]] => val TypeRef(_, _, Seq(elementType)) = t val Schema(dataType, nullable) = schemaFor(elementType) val className = getClassNameFromType(elementType) val newTypePath = s"""- array element class: "$className"""" +: walkedTypePath val mapFunction: Expression => Expression = p => { val converter = deserializerFor(elementType, Some(p), newTypePath) if (nullable) { converter } else { AssertNotNull(converter, newTypePath) } } val array = Invoke( MapObjects(mapFunction, getPath, dataType), "array", ObjectType(classOf[Array[Any]])) StaticInvoke( scala.collection.mutable.WrappedArray.getClass, ObjectType(classOf[Seq[_]]), "make", array :: Nil) case t if t <:< localTypeOf[Map[_, _]] => // TODO: add walked type path for map val TypeRef(_, _, Seq(keyType, valueType)) = t val keyData = Invoke( MapObjects( p => deserializerFor(keyType, Some(p), walkedTypePath), Invoke(getPath, "keyArray", ArrayType(schemaFor(keyType).dataType)), schemaFor(keyType).dataType), "array", ObjectType(classOf[Array[Any]])) val valueData = Invoke( MapObjects( p => deserializerFor(valueType, Some(p), walkedTypePath), Invoke(getPath, "valueArray", ArrayType(schemaFor(valueType).dataType)), schemaFor(valueType).dataType), "array", ObjectType(classOf[Array[Any]])) StaticInvoke( ArrayBasedMapData.getClass, ObjectType(classOf[scala.collection.immutable.Map[_, _]]), "toScalaMap", keyData :: valueData :: Nil) case t if t.typeSymbol.annotations.exists(_.tpe =:= typeOf[SQLUserDefinedType]) => val udt = getClassFromType(t).getAnnotation(classOf[SQLUserDefinedType]).udt().newInstance() val obj = NewInstance( udt.userClass.getAnnotation(classOf[SQLUserDefinedType]).udt(), Nil, dataType = ObjectType(udt.userClass.getAnnotation(classOf[SQLUserDefinedType]).udt())) Invoke(obj, "deserialize", ObjectType(udt.userClass), getPath :: Nil) case t if UDTRegistration.exists(getClassNameFromType(t)) => val udt = UDTRegistration.getUDTFor(getClassNameFromType(t)).get.newInstance() .asInstanceOf[UserDefinedType[_]] val obj = NewInstance( udt.getClass, Nil, dataType = ObjectType(udt.getClass)) Invoke(obj, "deserialize", ObjectType(udt.userClass), getPath :: Nil) case t if definedByConstructorParams(t) => val params = getConstructorParameters(t) val cls = getClassFromType(tpe) val arguments = params.zipWithIndex.map { case ((fieldName, fieldType), i) => val Schema(dataType, nullable) = schemaFor(fieldType) val clsName = getClassNameFromType(fieldType) val newTypePath = s"""- field (class: "$clsName", name: "$fieldName")""" +: walkedTypePath // For tuples, we based grab the inner fields by ordinal instead of name. if (cls.getName startsWith "scala.Tuple") { deserializerFor( fieldType, Some(addToPathOrdinal(i, dataType, newTypePath)), newTypePath) } else { val constructor = deserializerFor( fieldType, Some(addToPath(fieldName, dataType, newTypePath)), newTypePath) if (!nullable) { AssertNotNull(constructor, newTypePath) } else { constructor } } } val newInstance = NewInstance(cls, arguments, ObjectType(cls), propagateNull = false) if (path.nonEmpty) { expressions.If( IsNull(getPath), expressions.Literal.create(null, ObjectType(cls)), newInstance ) } else { newInstance } } } /** * Returns an expression for serializing an object of type T to an internal row. * * If the given type is not supported, i.e. there is no encoder can be built for this type, * an [[UnsupportedOperationException]] will be thrown with detailed error message to explain * the type path walked so far and which class we are not supporting. * There are 4 kinds of type path: * * the root type: `root class: "abc.xyz.MyClass"` * * the value type of [[Option]]: `option value class: "abc.xyz.MyClass"` * * the element type of [[Array]] or [[Seq]]: `array element class: "abc.xyz.MyClass"` * * the field of [[Product]]: `field (class: "abc.xyz.MyClass", name: "myField")` */ def serializerFor[T : TypeTag](inputObject: Expression): CreateNamedStruct = { val tpe = localTypeOf[T] val clsName = getClassNameFromType(tpe) val walkedTypePath = s"""- root class: "$clsName"""" :: Nil serializerFor(inputObject, tpe, walkedTypePath) match { case expressions.If(_, _, s: CreateNamedStruct) if definedByConstructorParams(tpe) => s case other => CreateNamedStruct(expressions.Literal("value") :: other :: Nil) } } /** Helper for extracting internal fields from a case class. */ private def serializerFor( inputObject: Expression, tpe: `Type`, walkedTypePath: Seq[String]): Expression = ScalaReflectionLock.synchronized { def toCatalystArray(input: Expression, elementType: `Type`): Expression = { dataTypeFor(elementType) match { case dt: ObjectType => val clsName = getClassNameFromType(elementType) val newPath = s"""- array element class: "$clsName"""" +: walkedTypePath MapObjects(serializerFor(_, elementType, newPath), input, dt) case dt @ (BooleanType | ByteType | ShortType | IntegerType | LongType | FloatType | DoubleType) => val cls = input.dataType.asInstanceOf[ObjectType].cls if (cls.isArray && cls.getComponentType.isPrimitive) { StaticInvoke( classOf[UnsafeArrayData], ArrayType(dt, false), "fromPrimitiveArray", input :: Nil) } else { NewInstance( classOf[GenericArrayData], input :: Nil, dataType = ArrayType(dt, schemaFor(elementType).nullable)) } case dt => NewInstance( classOf[GenericArrayData], input :: Nil, dataType = ArrayType(dt, schemaFor(elementType).nullable)) } } tpe match { case _ if !inputObject.dataType.isInstanceOf[ObjectType] => inputObject case t if t <:< localTypeOf[Option[_]] => val TypeRef(_, _, Seq(optType)) = t val className = getClassNameFromType(optType) val newPath = s"""- option value class: "$className"""" +: walkedTypePath val unwrapped = UnwrapOption(dataTypeFor(optType), inputObject) serializerFor(unwrapped, optType, newPath) // Since List[_] also belongs to localTypeOf[Product], we put this case before // "case t if definedByConstructorParams(t)" to make sure it will match to the // case "localTypeOf[Seq[_]]" case t if t <:< localTypeOf[Seq[_]] => val TypeRef(_, _, Seq(elementType)) = t toCatalystArray(inputObject, elementType) case t if t <:< localTypeOf[Array[_]] => val TypeRef(_, _, Seq(elementType)) = t toCatalystArray(inputObject, elementType) case t if t <:< localTypeOf[Map[_, _]] => val TypeRef(_, _, Seq(keyType, valueType)) = t val keyClsName = getClassNameFromType(keyType) val valueClsName = getClassNameFromType(valueType) val keyPath = s"""- map key class: "$keyClsName"""" +: walkedTypePath val valuePath = s"""- map value class: "$valueClsName"""" +: walkedTypePath ExternalMapToCatalyst( inputObject, dataTypeFor(keyType), serializerFor(_, keyType, keyPath), dataTypeFor(valueType), serializerFor(_, valueType, valuePath)) case t if t <:< localTypeOf[String] => StaticInvoke( classOf[UTF8String], StringType, "fromString", inputObject :: Nil) case t if t <:< localTypeOf[UTF8String] => Invoke( inputObject, "cloneIfRequired", StringType) case t if t <:< localTypeOf[java.sql.Timestamp] => StaticInvoke( DateTimeUtils.getClass, TimestampType, "fromJavaTimestamp", inputObject :: Nil) case t if t <:< localTypeOf[java.sql.Date] => StaticInvoke( DateTimeUtils.getClass, DateType, "fromJavaDate", inputObject :: Nil) case t if t <:< localTypeOf[BigDecimal] => StaticInvoke( Decimal.getClass, DecimalType.SYSTEM_DEFAULT, "apply", inputObject :: Nil) case t if t <:< localTypeOf[java.math.BigDecimal] => StaticInvoke( Decimal.getClass, DecimalType.SYSTEM_DEFAULT, "apply", inputObject :: Nil) case t if t <:< localTypeOf[java.math.BigInteger] => StaticInvoke( Decimal.getClass, DecimalType.BigIntDecimal, "apply", inputObject :: Nil) case t if t <:< localTypeOf[scala.math.BigInt] => StaticInvoke( Decimal.getClass, DecimalType.BigIntDecimal, "apply", inputObject :: Nil) case t if t <:< localTypeOf[java.lang.Integer] => Invoke(inputObject, "intValue", IntegerType) case t if t <:< localTypeOf[java.lang.Long] => Invoke(inputObject, "longValue", LongType) case t if t <:< localTypeOf[java.lang.Double] => Invoke(inputObject, "doubleValue", DoubleType) case t if t <:< localTypeOf[java.lang.Float] => Invoke(inputObject, "floatValue", FloatType) case t if t <:< localTypeOf[java.lang.Short] => Invoke(inputObject, "shortValue", ShortType) case t if t <:< localTypeOf[java.lang.Byte] => Invoke(inputObject, "byteValue", ByteType) case t if t <:< localTypeOf[java.lang.Boolean] => Invoke(inputObject, "booleanValue", BooleanType) case t if t.typeSymbol.annotations.exists(_.tpe =:= typeOf[SQLUserDefinedType]) => val udt = getClassFromType(t) .getAnnotation(classOf[SQLUserDefinedType]).udt().newInstance() val obj = NewInstance( udt.userClass.getAnnotation(classOf[SQLUserDefinedType]).udt(), Nil, dataType = ObjectType(udt.userClass.getAnnotation(classOf[SQLUserDefinedType]).udt())) Invoke(obj, "serialize", udt, inputObject :: Nil) case t if UDTRegistration.exists(getClassNameFromType(t)) => val udt = UDTRegistration.getUDTFor(getClassNameFromType(t)).get.newInstance() .asInstanceOf[UserDefinedType[_]] val obj = NewInstance( udt.getClass, Nil, dataType = ObjectType(udt.getClass)) Invoke(obj, "serialize", udt, inputObject :: Nil) case t if definedByConstructorParams(t) => val params = getConstructorParameters(t) val nonNullOutput = CreateNamedStruct(params.flatMap { case (fieldName, fieldType) => if (javaKeywords.contains(fieldName)) { throw new UnsupportedOperationException(s"`$fieldName` is a reserved keyword and " + "cannot be used as field name\\n" + walkedTypePath.mkString("\\n")) } val fieldValue = Invoke(inputObject, fieldName, dataTypeFor(fieldType)) val clsName = getClassNameFromType(fieldType) val newPath = s"""- field (class: "$clsName", name: "$fieldName")""" +: walkedTypePath expressions.Literal(fieldName) :: serializerFor(fieldValue, fieldType, newPath) :: Nil }) val nullOutput = expressions.Literal.create(null, nonNullOutput.dataType) expressions.If(IsNull(inputObject), nullOutput, nonNullOutput) case other => throw new UnsupportedOperationException( s"No Encoder found for $tpe\\n" + walkedTypePath.mkString("\\n")) } } /** * Returns true if the given type is option of product type, e.g. `Option[Tuple2]`. Note that, * we also treat [[DefinedByConstructorParams]] as product type. */ def optionOfProductType(tpe: `Type`): Boolean = ScalaReflectionLock.synchronized { tpe match { case t if t <:< localTypeOf[Option[_]] => val TypeRef(_, _, Seq(optType)) = t definedByConstructorParams(optType) case _ => false } } /** * Returns the parameter names and types for the primary constructor of this class. * * Note that it only works for scala classes with primary constructor, and currently doesn't * support inner class. */ def getConstructorParameters(cls: Class[_]): Seq[(String, Type)] = { val m = runtimeMirror(cls.getClassLoader) val classSymbol = m.staticClass(cls.getName) val t = classSymbol.selfType getConstructorParameters(t) } /** * Returns the parameter names for the primary constructor of this class. * * Logically we should call `getConstructorParameters` and throw away the parameter types to get * parameter names, however there are some weird scala reflection problems and this method is a * workaround to avoid getting parameter types. */ def getConstructorParameterNames(cls: Class[_]): Seq[String] = { val m = runtimeMirror(cls.getClassLoader) val classSymbol = m.staticClass(cls.getName) val t = classSymbol.selfType constructParams(t).map(_.name.toString) } /** * Returns the parameter values for the primary constructor of this class. */ def getConstructorParameterValues(obj: DefinedByConstructorParams): Seq[AnyRef] = { getConstructorParameterNames(obj.getClass).map { name => obj.getClass.getMethod(name).invoke(obj) } } /* * Retrieves the runtime class corresponding to the provided type. */ def getClassFromType(tpe: Type): Class[_] = mirror.runtimeClass(tpe.typeSymbol.asClass) case class Schema(dataType: DataType, nullable: Boolean) /** Returns a Sequence of attributes for the given case class type. */ def attributesFor[T: TypeTag]: Seq[Attribute] = schemaFor[T] match { case Schema(s: StructType, _) => s.toAttributes } /** Returns a catalyst DataType and its nullability for the given Scala Type using reflection. */ def schemaFor[T: TypeTag]: Schema = schemaFor(localTypeOf[T]) /** Returns a catalyst DataType and its nullability for the given Scala Type using reflection. */ def schemaFor(tpe: `Type`): Schema = ScalaReflectionLock.synchronized { tpe match { case t if t.typeSymbol.annotations.exists(_.tpe =:= typeOf[SQLUserDefinedType]) => val udt = getClassFromType(t).getAnnotation(classOf[SQLUserDefinedType]).udt().newInstance() Schema(udt, nullable = true) case t if UDTRegistration.exists(getClassNameFromType(t)) => val udt = UDTRegistration.getUDTFor(getClassNameFromType(t)).get.newInstance() .asInstanceOf[UserDefinedType[_]] Schema(udt, nullable = true) case t if t <:< localTypeOf[Option[_]] => val TypeRef(_, _, Seq(optType)) = t Schema(schemaFor(optType).dataType, nullable = true) case t if t <:< localTypeOf[Array[Byte]] => Schema(BinaryType, nullable = true) case t if t <:< localTypeOf[Array[_]] => val TypeRef(_, _, Seq(elementType)) = t val Schema(dataType, nullable) = schemaFor(elementType) Schema(ArrayType(dataType, containsNull = nullable), nullable = true) case t if t <:< localTypeOf[Seq[_]] => val TypeRef(_, _, Seq(elementType)) = t val Schema(dataType, nullable) = schemaFor(elementType) Schema(ArrayType(dataType, containsNull = nullable), nullable = true) case t if t <:< localTypeOf[Map[_, _]] => val TypeRef(_, _, Seq(keyType, valueType)) = t val Schema(valueDataType, valueNullable) = schemaFor(valueType) Schema(MapType(schemaFor(keyType).dataType, valueDataType, valueContainsNull = valueNullable), nullable = true) case t if t <:< localTypeOf[String] => Schema(StringType, nullable = true) case t if t <:< localTypeOf[UTF8String] => Schema(StringType, nullable = true) case t if t <:< localTypeOf[java.sql.Timestamp] => Schema(TimestampType, nullable = true) case t if t <:< localTypeOf[java.sql.Date] => Schema(DateType, nullable = true) case t if t <:< localTypeOf[BigDecimal] => Schema(DecimalType.SYSTEM_DEFAULT, nullable = true) case t if t <:< localTypeOf[java.math.BigDecimal] => Schema(DecimalType.SYSTEM_DEFAULT, nullable = true) case t if t <:< localTypeOf[java.math.BigInteger] => Schema(DecimalType.BigIntDecimal, nullable = true) case t if t <:< localTypeOf[scala.math.BigInt] => Schema(DecimalType.BigIntDecimal, nullable = true) case t if t <:< localTypeOf[Decimal] => Schema(DecimalType.SYSTEM_DEFAULT, nullable = true) case t if t <:< localTypeOf[java.lang.Integer] => Schema(IntegerType, nullable = true) case t if t <:< localTypeOf[java.lang.Long] => Schema(LongType, nullable = true) case t if t <:< localTypeOf[java.lang.Double] => Schema(DoubleType, nullable = true) case t if t <:< localTypeOf[java.lang.Float] => Schema(FloatType, nullable = true) case t if t <:< localTypeOf[java.lang.Short] => Schema(ShortType, nullable = true) case t if t <:< localTypeOf[java.lang.Byte] => Schema(ByteType, nullable = true) case t if t <:< localTypeOf[java.lang.Boolean] => Schema(BooleanType, nullable = true) case t if t <:< definitions.IntTpe => Schema(IntegerType, nullable = false) case t if t <:< definitions.LongTpe => Schema(LongType, nullable = false) case t if t <:< definitions.DoubleTpe => Schema(DoubleType, nullable = false) case t if t <:< definitions.FloatTpe => Schema(FloatType, nullable = false) case t if t <:< definitions.ShortTpe => Schema(ShortType, nullable = false) case t if t <:< definitions.ByteTpe => Schema(ByteType, nullable = false) case t if t <:< definitions.BooleanTpe => Schema(BooleanType, nullable = false) case t if definedByConstructorParams(t) => val params = getConstructorParameters(t) Schema(StructType( params.map { case (fieldName, fieldType) => val Schema(dataType, nullable) = schemaFor(fieldType) StructField(fieldName, dataType, nullable) }), nullable = true) case other => throw new UnsupportedOperationException(s"Schema for type $other is not supported") } } /** * Whether the fields of the given type is defined entirely by its constructor parameters. */ def definedByConstructorParams(tpe: Type): Boolean = { tpe <:< localTypeOf[Product] || tpe <:< localTypeOf[DefinedByConstructorParams] } private val javaKeywords = Set("abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const", "continue", "default", "do", "double", "else", "extends", "false", "final", "finally", "float", "for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new", "null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super", "switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile", "while") } /** * Support for generating catalyst schemas for scala objects. Note that unlike its companion * object, this trait able to work in both the runtime and the compile time (macro) universe. */ trait ScalaReflection { /** The universe we work in (runtime or macro) */ val universe: scala.reflect.api.Universe /** The mirror used to access types in the universe */ def mirror: universe.Mirror import universe._ // The Predef.Map is scala.collection.immutable.Map. // Since the map values can be mutable, we explicitly import scala.collection.Map at here. /** * Return the Scala Type for `T` in the current classloader mirror. * * Use this method instead of the convenience method `universe.typeOf`, which * assumes that all types can be found in the classloader that loaded scala-reflect classes. * That's not necessarily the case when running using Eclipse launchers or even * Sbt console or test (without `fork := true`). * * @see SPARK-5281 */ // SPARK-13640: Synchronize this because TypeTag.tpe is not thread-safe in Scala 2.10. def localTypeOf[T: TypeTag]: `Type` = ScalaReflectionLock.synchronized { val tag = implicitly[TypeTag[T]] tag.in(mirror).tpe.normalize } /** * Returns the full class name for a type. The returned name is the canonical * Scala name, where each component is separated by a period. It is NOT the * Java-equivalent runtime name (no dollar signs). * * In simple cases, both the Scala and Java names are the same, however when Scala * generates constructs that do not map to a Java equivalent, such as singleton objects * or nested classes in package objects, it uses the dollar sign ($) to create * synthetic classes, emulating behaviour in Java bytecode. */ def getClassNameFromType(tpe: `Type`): String = { tpe.erasure.typeSymbol.asClass.fullName } /** * Returns classes of input parameters of scala function object. */ def getParameterTypes(func: AnyRef): Seq[Class[_]] = { val methods = func.getClass.getMethods.filter(m => m.getName == "apply" && !m.isBridge) assert(methods.length == 1) methods.head.getParameterTypes } /** * Returns the parameter names and types for the primary constructor of this type. * * Note that it only works for scala classes with primary constructor, and currently doesn't * support inner class. */ def getConstructorParameters(tpe: Type): Seq[(String, Type)] = { val formalTypeArgs = tpe.typeSymbol.asClass.typeParams val TypeRef(_, _, actualTypeArgs) = tpe constructParams(tpe).map { p => p.name.toString -> p.typeSignature.substituteTypes(formalTypeArgs, actualTypeArgs) } } protected def constructParams(tpe: Type): Seq[Symbol] = { val constructorSymbol = tpe.member(nme.CONSTRUCTOR) val params = if (constructorSymbol.isMethod) { constructorSymbol.asMethod.paramss } else { // Find the primary constructor, and use its parameter ordering. val primaryConstructorSymbol: Option[Symbol] = constructorSymbol.asTerm.alternatives.find( s => s.isMethod && s.asMethod.isPrimaryConstructor) if (primaryConstructorSymbol.isEmpty) { sys.error("Internal SQL error: Product object did not have a primary constructor.") } else { primaryConstructorSymbol.get.asMethod.paramss } } params.flatten } }
big-pegasus/spark
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/ScalaReflection.scala
Scala
apache-2.0
36,192
/* 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.app.nlp.pos import cc.factorie._ import cc.factorie.app.nlp._ import cc.factorie.variable._ abstract class PosTag(val token:Token, initialIndex:Int) extends CategoricalVariable[String](initialIndex) /** Penn Treebank part-of-speech tag domain. */ object PennPosDomain extends CategoricalDomain[String] { this ++= Vector( "#", // In WSJ but not in Ontonotes "$", "''", ",", "-LRB-", "-RRB-", ".", ":", "CC", "CD", "DT", "EX", "FW", "IN", "JJ", "JJR", "JJS", "LS", "MD", "NN", "NNP", "NNPS", "NNS", "PDT", "POS", "PRP", "PRP$", "PUNC", "RB", "RBR", "RBS", "RP", "SYM", "TO", "UH", "VB", "VBD", "VBG", "VBN", "VBP", "VBZ", "WDT", "WP", "WP$", "WRB", "``", "ADD", // in Ontonotes, but not WSJ "AFX", // in Ontonotes, but not WSJ "HYPH", // in Ontonotes, but not WSJ "NFP", // in Ontonotes, but not WSJ "XX" // in Ontonotes, but not WSJ ) freeze() // Short-cuts for a few commonly-queried tags val posIndex = index("POS") val nnpIndex = index("NNP") val nnpsIndex = index("NNPS") val prpIndex = index("PRP") val prpdIndex = index("PRP$") val wpIndex = index("WP") val wpdIndex = index("WP$") val ccIndex = index("CC") def isNoun(pos:String): Boolean = pos(0) == 'N' def isProperNoun(pos:String) = { pos == "NNP" || pos == "NNPS" } def isVerb(pos:String) = pos(0) == 'V' def isAdjective(pos:String) = pos(0) == 'J' def isPersonalPronoun(pos: String) = pos == "PRP" } /** A categorical variable, associated with a token, holding its Penn Treebank part-of-speech category. */ class PennPosTag(token:Token, initialIndex:Int) extends PosTag(token, initialIndex) with Serializable { def this(token:Token, initialCategory:String) = this(token, PennPosDomain.index(initialCategory)) final def domain = PennPosDomain def isNoun = PennPosDomain.isNoun(categoryValue) def isProperNoun = PennPosDomain.isProperNoun(categoryValue) def isVerb = PennPosDomain.isVerb(categoryValue) def isAdjective = PennPosDomain.isAdjective(categoryValue) def isPersonalPronoun = PennPosDomain.isPersonalPronoun(categoryValue) } /** A categorical variable, associated with a token, holding its Penn Treebank part-of-speech category, which also separately holds its desired correct "target" value. */ class LabeledPennPosTag(token:Token, targetValue:String) extends PennPosTag(token, targetValue) with CategoricalLabeling[String] with Serializable /** The "A Universal Part-of-Speech Tagset" by Slav Petrov, Dipanjan Das and Ryan McDonald http://arxiv.org/abs/1104.2086 http://code.google.com/p/universal-pos-tags VERB - verbs (all tenses and modes) NOUN - nouns (common and proper) PRON - pronouns ADJ - adjectives ADV - adverbs ADP - adpositions (prepositions and postpositions) CONJ - conjunctions DET - determiners NUM - cardinal numbers PRT - particles or other function words X - other: foreign words, typos, abbreviations . - punctuation */ object UniversalPosDomain extends EnumDomain { this ++= Vector("VERB", "NOUN", "PRON", "ADJ", "ADV", "ADP", "CONJ", "DET", "NUM", "PRT", "X", ".") freeze() private val Penn2universal = new scala.collection.mutable.HashMap[String,String] ++= Vector( "!" -> ".", "#" -> ".", "$" -> ".", "''" -> ".", "(" -> ".", ")" -> ".", "," -> ".", "-LRB-" -> ".", "-RRB-" -> ".", "." -> ".", ":" -> ".", "?" -> ".", "CC" -> "CONJ", "CD" -> "NUM", "CD|RB" -> "X", "DT" -> "DET", "EX"-> "DET", "FW" -> "X", "IN" -> "ADP", "IN|RP" -> "ADP", "JJ" -> "ADJ", "JJR" -> "ADJ", "JJRJR" -> "ADJ", "JJS" -> "ADJ", "JJ|RB" -> "ADJ", "JJ|VBG" -> "ADJ", "LS" -> "X", "MD" -> "VERB", "NN" -> "NOUN", "NNP" -> "NOUN", "NNPS" -> "NOUN", "NNS" -> "NOUN", "NN|NNS" -> "NOUN", "NN|SYM" -> "NOUN", "NN|VBG" -> "NOUN", "NP" -> "NOUN", "PDT" -> "DET", "POS" -> "PRT", "PRP" -> "PRON", "PRP$" -> "PRON", "PRP|VBP" -> "PRON", "PRT" -> "PRT", "RB" -> "ADV", "RBR" -> "ADV", "RBS" -> "ADV", "RB|RP" -> "ADV", "RB|VBG" -> "ADV", "RN" -> "X", "RP" -> "PRT", "SYM" -> "X", "TO" -> "PRT", "UH" -> "X", "VB" -> "VERB", "VBD" -> "VERB", "VBD|VBN" -> "VERB", "VBG" -> "VERB", "VBG|NN" -> "VERB", "VBN" -> "VERB", "VBP" -> "VERB", "VBP|TO" -> "VERB", "VBZ" -> "VERB", "VP" -> "VERB", "WDT" -> "DET", "WH" -> "X", "WP" -> "PRON", "WP$" -> "PRON", "WRB" -> "ADV", "``" -> ".") def categoryFromPenn(PennPosCategory:String): String = Penn2universal(PennPosCategory) } /** A categorical variable, associated with a token, holding its Google Universal part-of-speech category. */ class UniversalPosTag(val token:Token, initialValue:String) extends CategoricalVariable(initialValue) { def this(token:Token, other:PennPosTag) = this(token, UniversalPosDomain.categoryFromPenn(other.categoryValue)) def domain = UniversalPosDomain } /** A categorical variable, associated with a token, holding its Google Universal part-of-speech category, which also separately holds its desired correct "target" value. */ class LabeledUniversalPosTag(token:Token, targetValue:String) extends UniversalPosTag(token, targetValue) with CategoricalLabeling[String] /** Penn Treebank part-of-speech tag domain. */ object SpanishPosDomain extends CategoricalDomain[String] { this ++= Vector( "a", // adjective "c", // conjunction "d", // determiner "f", // punctuation "i", // interjection "n", // noun "p", // pronoun "r", // adverb "s", // preposition "v", // verb "w", // date "z", // number "_" // unknown ) freeze() def isNoun(pos:String): Boolean = pos(0) == 'n' // def isProperNoun(pos:String) = { pos == "NNP" || pos == "NNPS" } def isVerb(pos:String) = pos(0) == 'v' def isAdjective(pos:String) = pos(0) == 'a' // def isPersonalPronoun(pos: String) = pos == "PRP" } /** A categorical variable, associated with a token, holding its Penn Treebank part-of-speech category. */ class SpanishPosTag(token:Token, initialIndex:Int) extends PosTag(token, initialIndex) { def this(token:Token, initialCategory:String) = this(token, SpanishPosDomain.index(initialCategory)) final def domain = SpanishPosDomain def isNoun = SpanishPosDomain.isNoun(categoryValue) // def isProperNoun = SpanishPosDomain.isProperNoun(categoryValue) def isVerb = SpanishPosDomain.isVerb(categoryValue) def isAdjective = SpanishPosDomain.isAdjective(categoryValue) // def isPersonalPronoun = SpanishPosDomain.isPersonalPronoun(categoryValue) } /** A categorical variable, associated with a token, holding its Spanish Treebank part-of-speech category, which also separately holds its desired correct "target" value. */ class LabeledSpanishPosTag(token:Token, targetValue:String) extends SpanishPosTag(token, targetValue) with CategoricalLabeling[String]
hlin117/factorie
src/main/scala/cc/factorie/app/nlp/pos/PosTag.scala
Scala
apache-2.0
8,186
package org.http4s.parser import org.http4s.{Header, ParseResult} trait HeaderParserHelper[H <: Header] { def hparse(value: String): ParseResult[H] // Also checks to make sure whitespace doesn't effect the outcome protected def parse(value: String): H = { val a = hparse(value).fold(err => sys.error(s"Couldn't parse: '$value'.\\nError: $err"), identity) val b = hparse(value.replace(" ", "")).fold(_ => sys.error(s"Couldn't parse: $value"), identity) assert(a == b, "Whitespace resulted in different headers") a } }
reactormonk/http4s
tests/src/test/scala/org/http4s/parser/HeaderParserHelper.scala
Scala
apache-2.0
557
/** * Copyright (C) 2011 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.xforms.analysis import collection.JavaConverters._ import collection.immutable.Stream._ import collection.immutable.TreeMap import collection.mutable.{HashSet, HashMap, LinkedHashMap, LinkedHashSet} import java.util.{Map ⇒ JMap} import org.dom4j.io.DocumentSource import org.orbeon.oxf.resources.{ResourceNotFoundException, ResourceManagerWrapper} import org.orbeon.oxf.xforms.XFormsStaticStateImpl.StaticStateDocument import org.orbeon.oxf.xforms.XFormsUtils import org.orbeon.oxf.xforms.state.AnnotatedTemplate import org.orbeon.oxf.xforms.xbl.XBLResources import org.orbeon.oxf.xml.{TransformerUtils, NamespaceMapping, SAXStore} /** * Container for element metadata gathered during document annotation/extraction: * * - id generation * - namespace mappings * - automatic XBL mappings * - full update marks * * Split into traits for modularity. */ class Metadata(val idGenerator: IdGenerator) extends NamespaceMappings with Bindings with Marks { def this() { this(new IdGenerator) } } object Metadata { // Restore a Metadata object from the given StaticStateDocument def apply(staticStateDocument: StaticStateDocument, template: Option[AnnotatedTemplate]): Metadata = { // Restore generator with last id val metadata = new Metadata(new IdGenerator(staticStateDocument.lastId)) // Restore namespace mappings and ids TransformerUtils.sourceToSAX(new DocumentSource(staticStateDocument.xmlDocument), new XFormsAnnotatorContentHandler(metadata)) // Restore marks if there is a template template foreach { template ⇒ for (mark ← template.saxStore.getMarks.asScala) metadata.putMark(mark) } metadata } } // Handling of template marks trait Marks { private val marks = new HashMap[String, SAXStore#Mark] def putMark(mark: SAXStore#Mark) = marks += mark.id → mark def getMark(prefixedId: String) = marks.get(prefixedId).orNull private def topLevelMarks = marks collect { case (prefixedId, mark) if XFormsUtils.isTopLevelId(prefixedId) ⇒ mark } def hasTopLevelMarks = topLevelMarks.nonEmpty } // Handling of XBL bindings trait Bindings { private val xblBindings = new HashMap[String, collection.mutable.Set[String]] private var lastModified = -1L val bindingIncludes = new LinkedHashSet[String] def isXBLBindingCheckAutomaticBindings(uri: String, localname: String): Boolean = { // Is this already registered? if (isXBLBinding(uri, localname)) return true // If not, check if it exists as automatic binding XBLResources.getAutomaticXBLMappingPath(uri, localname) match { case Some(path) ⇒ storeXBLBinding(uri, localname) bindingIncludes.add(path) true case _ ⇒ false } } def storeXBLBinding(bindingURI: String, localname: String) { val localnames = xblBindings.getOrElseUpdate(bindingURI, new HashSet[String]) localnames += localname } def isXBLBinding(uri: String, localname: String) = xblBindings.get(uri) match { case Some(localnames) ⇒ localnames(localname) case None ⇒ false } def getBindingIncludesJava = bindingIncludes.asJava def updateBindingsLastModified(lastModified: Long) { this.lastModified = math.max(this.lastModified, lastModified) } // Check if the binding includes are up to date. def checkBindingsIncludes = try { // true if all last modification dates are at most equal to our last modification date bindingIncludes.toStream map (ResourceManagerWrapper.instance.lastModified(_, false)) forall (_ <= this.lastModified) } catch { // If a resource cannot be found, consider that something has changed case e: ResourceNotFoundException ⇒ false } } // Handling of namespaces trait NamespaceMappings { private val namespaceMappings = new HashMap[String, NamespaceMapping] private val hashes = new LinkedHashMap[String, NamespaceMapping] def addNamespaceMapping(prefixedId: String, mapping: JMap[String, String]): Unit = { // Sort mappings by prefix val sorted = TreeMap(mapping.asScala.toSeq: _*) // Hash key/values val hexHash = NamespaceMapping.hashMapping(sorted.asJava) // Retrieve or create mapping object val namespaceMapping = hashes.getOrElseUpdate(hexHash, { val newNamespaceMapping = new NamespaceMapping(hexHash, sorted.asJava) hashes += (hexHash → newNamespaceMapping) newNamespaceMapping }) // Remember that id has this mapping namespaceMappings += prefixedId → namespaceMapping } def removeNamespaceMapping(prefixedId: String): Unit = namespaceMappings -= prefixedId def getNamespaceMapping(prefixedId: String) = namespaceMappings.get(prefixedId).orNull def debugPrintNamespaces() { println("Number of different namespace mappings: " + hashes.size) for ((key, value) ← hashes) { println(" hash: " + key) for ((prefix, uri) ← value.mapping.asScala) println(" " + prefix + " → " + uri) } } }
evlist/orbeon-forms
src/main/scala/org/orbeon/oxf/xforms/analysis/Metadata.scala
Scala
lgpl-2.1
6,058
/* * Copyright 2014 DataGenerator Contributors * * 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.finra.datagenerator.common.NodeData import org.finra.datagenerator.common.Helpers.StringHelper._ import NodeDataType.NodeDataType /** * Trait used for any data with a displayable ID and optional fields, and with around event type. * For example, this could be used for an object that can be viewed as an element in a DOT file, but it's not specific to that. */ trait DisplayableData { private var _overrideDisplayableDataId = "" def overrideDisplayableDataId: String = _overrideDisplayableDataId def overrideDisplayableDataId_=(value: String): Unit = { _overrideDisplayableDataId = value } def getOverrideDisplayableDataId: String = overrideDisplayableDataId def defaultDisplayableDataId: String def getDefaultDisplayableDataId: String = defaultDisplayableDataId def displayableDataId: String = { // Anything that uniquely identifies a childNode; e.g., 1, 2, 3, or NW_1, NW_2, RT_1 if (overrideDisplayableDataId.nonEmpty) { overrideDisplayableDataId } else { defaultDisplayableDataId } } def getDisplayableDataId: String = displayableDataId def displayableElements: Iterable[String] = Iterable[String](displayableDataId) def getDisplayableElements: Iterable[String] = displayableElements def simplifiedDisplayableElements: Iterable[String] = Iterable[String](displayableDataId) def getSimplifiedDisplayableElements: Iterable[String] = simplifiedDisplayableElements def dataType: NodeDataType[_, _, _, _] def getDataType: NodeDataType[_, _, _, _] = dataType /** * Used for testing graph isomorphism. * @return String uniquely representing this graph's structure */ def getStructuralMD5: String = { s"${dataType.name},${displayableElements.mkString(",")}".md5 } }
Brijeshrpatel9/SingleThreaderProcessingDG
dg-common/src/main/code/org/finra/datagenerator/common/NodeData/DisplayableData.scala
Scala
apache-2.0
2,375
object Test { def testPermutations1(num: Int, stream: LazyList[Int]): Unit = { val perm = stream.permutations print(num) while(perm.hasNext) { print(" " + perm.next().toList) } println() } def testPermutations2(num: Int, stream: List[Int]): Unit = { val perm = stream.permutations print(num) while(perm.hasNext) { print(" " + perm.next().toList) } println() } def main(args: Array[String]): Unit = { testPermutations1(1, LazyList(1)) testPermutations2(1, List(1)) testPermutations1(2, LazyList(1, 2)) testPermutations2(2, List(1, 2)) testPermutations1(2, LazyList(2, 1)) testPermutations2(2, List(2, 1)) testPermutations1(3, LazyList(1, 2, 3)) testPermutations2(3, List(1, 2, 3)) testPermutations1(3, LazyList(1, 3, 2)) testPermutations2(3, List(1, 3, 2)) testPermutations1(3, LazyList(2, 1, 3)) testPermutations2(3, List(2, 1, 3)) testPermutations1(3, LazyList(2, 3, 1)) testPermutations2(3, List(2, 3, 1)) testPermutations1(3, LazyList(3, 1, 2)) testPermutations2(3, List(3, 1, 2)) testPermutations1(3, LazyList(3, 2, 1)) testPermutations2(3, List(3, 2, 1)) } }
lampepfl/dotty
tests/run/t5377.scala
Scala
apache-2.0
1,209
// // DOrcExecution.scala -- Scala classes DOrcExecution, DOrcLeaderExecution, and DOrcFollowerExecution // Project OrcScala // // Created by jthywiss on Dec 29, 2015. // // Copyright (c) 2019 The University of Texas at Austin. All rights reserved. // // Use and redistribution of this file is governed by the license terms in // the LICENSE file found in the project's top-level directory and also found at // URL: http://orc.csres.utexas.edu/license.shtml . // package orc.run.distrib.token import orc.{ OrcEvent, OrcExecutionOptions } import orc.run.core.{ Execution, Token } import orc.run.distrib.Logger import orc.run.distrib.common.{ MashalingAndRemoteRefSupport, RemoteObjectManager, RemoteRefIdManager, ValueMarshaler, PlacementController } /** Top level Group, associated with a program running in a dOrc runtime * engine. dOrc executions have an ID, the program AST and OrcOptions, * etc. * * Rule of thumb: Orc Executions keep program state and handle engine-internal * behavior (Tokens, Groups, Frames, etc.). External interaction (with the * environment) is the bailiwick of Orc Runtimes. * * An Execution (Distributed Orc program run) is identified by a execution ID * UUID. Each runtime participating in an execution is assigned an * unique-to-that-execution follower number. (The leader runtime for an * execution uses "follower" number zero.) * * @author jthywiss */ abstract class DOrcExecution( val executionId: DOrcExecution#ExecutionId, override val followerExecutionNum: Int, programAst: DOrcRuntime#ProgramAST, options: OrcExecutionOptions, eventHandler: OrcEvent => Unit, override val runtime: DOrcRuntime) extends Execution(programAst, options, eventHandler, runtime) /* Implemented interfaces: */ with MashalingAndRemoteRefSupport[PeerLocation] /* Mixed-in implementation fragments: */ with RemoteObjectManager[PeerLocation] with RemoteRefIdManager[PeerLocation] with PlacementController[PeerLocation] with ValueMarshaler[DOrcExecution, PeerLocation] with ExecutionMashaler with GroupProxyManager with RemoteFutureManager { //TODO: Move to superclass def runProgram() { /* Initial program token */ val t = new Token(programAst, this) runtime.schedule(t) } override type ExecutionId = String /* For now, runtime IDs and Execution follower numbers are the same. When * we host more than one execution in an engine, they will be different. */ override def locationForFollowerNum(followerNum: Int): PeerLocation = runtime.locationForRuntimeId(new DOrcRuntime.RuntimeId(followerNum)) override def currentlyActiveLocation(location: PeerLocation): Boolean = runtime.allLocations.contains(location) def selectLocationForCall(candidateLocations: Set[PeerLocation]): PeerLocation = candidateLocations.head } object DOrcExecution { def freshExecutionId(): String = java.util.UUID.randomUUID().toString } /** DOrcExecution in the dOrc LeaderRuntime. This is the "true" root group. * * @author jthywiss */ class DOrcLeaderExecution( executionId: DOrcExecution#ExecutionId, programAst: DOrcRuntime#ProgramAST, options: OrcExecutionOptions, eventHandler: OrcEvent => Unit, runtime: LeaderRuntime) extends DOrcExecution(executionId, 0, programAst, options, eventHandler, runtime) { protected val startingFollowers = java.util.concurrent.ConcurrentHashMap.newKeySet[DOrcRuntime.RuntimeId]() protected val readyFollowers = java.util.concurrent.ConcurrentHashMap.newKeySet[DOrcRuntime.RuntimeId]() protected val followerStartWait = new Object() def followerStarting(followerNum: DOrcRuntime.RuntimeId): Unit = { startingFollowers.add(followerNum) } def followerReady(followerNum: DOrcRuntime.RuntimeId): Unit = { readyFollowers.add(followerNum) startingFollowers.remove(followerNum) followerStartWait synchronized followerStartWait.notifyAll() } def awaitAllFollowersReady(): Unit = { while (!startingFollowers.isEmpty()) followerStartWait synchronized followerStartWait.wait() } override def notifyOrc(event: OrcEvent): Unit = { super.notifyOrc(event) Logger.Downcall.fine(event.toString) } } /** Execution group to contain migrated tokens. This is a "fake" root group to * anchor the partial group tree in FollowerRuntimes. * * @author jthywiss */ class DOrcFollowerExecution( executionId: DOrcExecution#ExecutionId, followerExecutionNum: Int, programAst: DOrcRuntime#ProgramAST, options: OrcExecutionOptions, eventHandler: OrcEvent => Unit, runtime: FollowerRuntime) extends DOrcExecution(executionId, followerExecutionNum, programAst, options, eventHandler, runtime) { override def onHalt() { /* Group halts are not significant here, disregard */ } }
orc-lang/orc
OrcScala/src/orc/run/distrib/token/DOrcExecution.scala
Scala
bsd-3-clause
4,810
/******************************************************************************* * Copyright (C) 2012 Łukasz Szpakowski. * * This library is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package org.lkbgraph.immutable.spec import org.scalatest.Spec import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner import org.lkbgraph._ import org.lkbgraph.immutable._ @RunWith(classOf[JUnitRunner]) class AdjListGraphSpec extends Spec with base.spec.GraphBehaviors[AdjListGraph] { override def graphFactory: base.GraphFactory[AdjListGraph] = AdjListGraph describe("An AdjListGraph") { it should behave like graph } }
luckboy/LkbGraph
src/test/org/lkbgraph/immutable/spec/AdjListGraphSpec.scala
Scala
lgpl-3.0
1,328
package jp.rotaryo.whitespace protected[whitespace] object RetrieveOperation extends Operation { override def getSource(): String = { return heapAccess + "\t" } override def getParameter(): Option[Parameter] = { return None } override def preRun(container: Container, index: Int): Unit = { } override def run(container: Container, index: Int): Int = { container.pushValue(container.getHeap(container.popValue())) return index + 1 } }
rotary-o/scala2ws
src/main/scala/jp/rotaryo/whitespace/RetrieveOperation.scala
Scala
mit
472
package yuuto.enhancedinventories.tile.base import yuuto.yuutolib.tile.traits.TTileRotatableMachine import yuuto.enhancedinventories.tile.traits.TDecorativeInventoryConnective import yuuto.enhancedinventories.tile.traits.TInventoryConnectiveUpgradeable import yuuto.enhancedinventories.tile.traits.TInventorySecurable import yuuto.enhancedinventories.tile.traits.TSecurableUpgradeable import yuuto.enhancedinventories.tile.traits.TConnective import net.minecraft.nbt.NBTTagCompound /** * @author Jacob */ abstract class TileConnectiveUpgradeable extends TileBaseEI with TTileRotatableMachine with TDecorativeInventoryConnective with TInventorySecurable with TSecurableUpgradeable{ }
Joccob/EnhancedInventories
src/main/scala/yuuto/enhancedinventories/tile/base/TileConnectiveUpgradeable.scala
Scala
gpl-2.0
701
package scadla.backends import eu.mihosoft.jcsg.{Cube => JCube, Sphere => JSphere, Cylinder => JCylinder, Polyhedron => JPolyhedron, _} import eu.mihosoft.vvecmath.{Vector3d, Transform, Plane} import scadla._ import InlineOps._ import java.util.ArrayList import squants.space.{Length, Millimeters, LengthUnit} //backend using: https://github.com/miho/JCSG object JCSG extends JCSG(16, Millimeters) class JCSG(numSlices: Int, unit: LengthUnit = Millimeters) extends Renderer(unit) { override def isSupported(s: Solid): Boolean = s match { case s: Shape => super.isSupported(s) case _: Multiply => false case t: scadla.Transform => isSupported(t.child) case u @ Union(_) => u.children.forall(isSupported) case i @ Intersection(_) => i.children.forall(isSupported) case d @ Difference(_,_) => d.children.forall(isSupported) case c @ Hull(_) => c.children.forall(isSupported) case m @ Minkowski(_) => m.children.forall(isSupported) case _ => false } protected def empty = new JPolyhedron(Array[Vector3d](), Array[Array[Integer]]()).toCSG protected def stupidMinkowski2(a: Polyhedron, b: Polyhedron): Polyhedron = { // for all face in A: move B to each point and take the hull val parts1 = a.faces.toSeq.map{ case Face(p1, p2, p3) => Hull( b.move(p1.x, p1.y, p1.z), b.move(p2.x, p2.y, p2.z), b.move(p3.x, p3.y, p3.z)) } // and then deal with internal holes (union with A translated by every point in B ?) val bPoints = b.faces.foldLeft(Set.empty[Point])( (acc, f) => acc + f.p1 + f.p2 + f.p3 ) val parts2 = bPoints.toSeq.map(a.move(_)) // then union everything and render val res = Union( (parts1 ++ parts2) :_*) apply(res) } protected def stupidMinkowski(objs: Seq[Solid]): CSG = { val objs2 = objs.map( apply ) val res = objs2.reduce(stupidMinkowski2) to(res) } protected def to(s: Solid): CSG = { import scala.language.implicitConversions implicit def toDouble(l: Length): Double = length2Double(l) s match { case Empty => empty case Cube(width, depth, height) => new JCube(Vector3d.xyz(width/2, depth/2, height/2), Vector3d.xyz(width, depth, height)).toCSG() case Sphere(radius) => new JSphere(radius, numSlices, numSlices/2).toCSG() case Cylinder(radiusBot, radiusTop, height) => new JCylinder(radiusBot, radiusTop, height, numSlices).toCSG() case Polyhedron(triangles) => val points = triangles.foldLeft(Set[Point]())( (acc, face) => acc + face.p1 + face.p2 + face.p3 ) val indexed = points.toSeq.zipWithIndex val idx: Map[Point, Int] = indexed.toMap val vs = Array.ofDim[Vector3d](indexed.size) indexed.foreach{ case (p, i) => vs(i) = Vector3d.xyz(p.x,p.y,p.z) } val is = Array.ofDim[Array[Integer]](triangles.size) triangles.zipWithIndex.foreach { case (Face(a,b,c), i) => is(i) = Array(idx(a), idx(b), idx(c)) } new JPolyhedron(vs, is).toCSG() case f @ FromFile(path, format) => format match { case "stl" => STL.file(java.nio.file.Paths.get(path)) case _ => to(f.load) } case Union(objs @ _*) => if (objs.isEmpty) empty else objs.map(to).reduce( _.union(_) ) case Intersection(objs @ _*) => if (objs.isEmpty) empty else objs.map(to).reduce( _.intersect(_) ) case Difference(pos, negs @ _*) => negs.map(to).foldLeft(to(pos))( _.difference(_) ) case Minkowski(objs @ _*) => stupidMinkowski(objs) case Hull(objs @ _*) => to(Union(objs:_*)).hull case Scale(x, y, z, obj) => to(obj).transformed(Transform.unity().scale(x, y, z)) case Rotate(x, y, z, obj) => to(obj).transformed(Transform.unity().rot(x.toDegrees, y.toDegrees, z.toDegrees)) case Translate(x, y, z, obj) => to(obj).transformed(Transform.unity().translate(x, y, z)) case Mirror(x, y, z, obj) => to(obj).transformed(Transform.unity().mirror(Plane.fromPointAndNormal(Vector3d.ZERO, Vector3d.xyz(x,y,z)))) case Multiply(m, obj) => sys.error("JCSG does not support arbitrary matrix transform") } } protected def polyToFaces(p: Polygon): List[Face] = { val vs = p.vertices.toArray(Array.ofDim[Vertex](p.vertices.size)) val pts = vs.map( v => Point(unit(v.pos.x), unit(v.pos.y), unit(v.pos.z))) //if more than 3 vertices if needs to be triangulated //assume that the vertices form a convex loop (0 until vs.size - 2).toList.map(i => Face(pts(0), pts(i+1), pts(i+2)) ) } protected def from(c: CSG): Polyhedron = { val polygons = c.getPolygons.iterator var faces = List[Face]() while (polygons.hasNext) { faces = polyToFaces(polygons.next) ::: faces } Polyhedron(faces) } def apply(obj: Solid): Polyhedron = obj match { case p @ Polyhedron(_) => p case other => from(to(other)) } }
dzufferey/scadla
src/main/scala/scadla/backends/JCSG.scala
Scala
apache-2.0
4,948
/* * Copyright 2007-2011 WorldWide Conferencing, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.liftweb package util import java.util.Locale import java.text.{NumberFormat, DecimalFormat} trait TwoFractionDigits { def numberOfFractionDigits = 2 def scale = 10 } trait DollarCurrency extends TwoFractionDigits { def currencySymbol: String = "$" } /* Various Currencies */ object AU extends CurrencyZone { type Currency = AUD var locale = new Locale("en", "AU") def make(x: BigDecimal) = new Currency{def amount = x} abstract class AUD extends AbstractCurrency("AUD") with DollarCurrency {} } object US extends CurrencyZone { type Currency = USD var locale = Locale.US def make(x: BigDecimal) = new Currency{def amount = x} abstract class USD extends AbstractCurrency("USD") with DollarCurrency {} } object GB extends CurrencyZone { type Currency = GBP var locale = Locale.UK def make(x: BigDecimal) = new Currency{def amount = x} abstract class GBP extends AbstractCurrency("GBP") with TwoFractionDigits {def currencySymbol = "£"} } object EU extends CurrencyZone { type Currency = EUR var locale = Locale.GERMANY // guess this is why its a var def make(x: BigDecimal) = new Currency{def amount = x; override val _locale = locale} abstract class EUR extends AbstractCurrency("EUR") with TwoFractionDigits {def currencySymbol = "€"} } abstract class CurrencyZone { type Currency <: AbstractCurrency var locale: Locale def make(x: BigDecimal): Currency def apply(x: String): Currency = { try { make(BigDecimal(x)) // try normal number } catch { case e: java.lang.NumberFormatException => { try { make(BigDecimal(""+NumberFormat.getNumberInstance(locale).parse(x))) // try with grouping separator } catch { case e: java.text.ParseException => { make(BigDecimal(""+NumberFormat.getCurrencyInstance(locale).parse(x))) } // try with currency symbol and grouping separator } } } } def apply(x: BigDecimal): Currency = make(x) /* currency factory*/ abstract class AbstractCurrency(val designation: String) extends Ordered[Currency] { val _locale: Locale = locale def amount: BigDecimal def floatValue = amount.floatValue def doubleValue = amount.doubleValue def currencySymbol: String def numberOfFractionDigits: Int def scale: Int def +(that: Currency): Currency = make(this.amount + that.amount) def +(that: Int): Currency = this + make(that) def *(that: Currency): Currency = make(this.amount * that.amount) def *(that: Int): Currency = this * make(that) def -(that: Currency): Currency = make(this.amount - that.amount) def -(that: Int): Currency = this - make(that) def /(that: Currency): Currency = make(new BigDecimal(this.amount.bigDecimal.divide(that.amount.bigDecimal, scale, java.math.BigDecimal.ROUND_HALF_UP)) ) def /(that: Int): Currency = this / make(that) def compare(that: Currency) = this.amount compare that.amount override def equals(that: Any) = that match { case that: AbstractCurrency => this.designation+this.format("", scale) == that.designation+that.format("", scale) case _ => false } override def hashCode = (this.designation+format("", scale)).hashCode def round(precision: Int) = make(BigDecimal(get(precision))) override def toString = format("", numberOfFractionDigits) def format(fd: Int): String = format(currencySymbol, fd) def format: String = format(currencySymbol, numberOfFractionDigits) def format(currencySymbol: String, numberOfFractionDigits: Int): String = { val moneyValue = amount match { case null => 0 case _ => amount.setScale(numberOfFractionDigits, BigDecimal.RoundingMode.HALF_UP).doubleValue; } val numberFormat = NumberFormat.getCurrencyInstance(_locale); numberFormat.setMinimumFractionDigits(numberOfFractionDigits); numberFormat.setMaximumFractionDigits(numberOfFractionDigits); val symbol=numberFormat.getCurrency.getSymbol(_locale) numberFormat.format(moneyValue).replace(symbol, currencySymbol) } def get: String = get(numberOfFractionDigits) def get(numberOfFractionDigits: Int): String = { val nf = NumberFormat.getNumberInstance(_locale) val df = nf.asInstanceOf[DecimalFormat] val groupingSeparator = df.getDecimalFormatSymbols.getGroupingSeparator format("", numberOfFractionDigits).replaceAll(groupingSeparator+"", ""); } } }
lzpfmh/framework-2
core/util/src/main/scala/net/liftweb/util/CurrencyZone.scala
Scala
apache-2.0
5,452
import scalaz._ object Vec { implicit object VecEqual extends Equal[Vec] { def equal(v1: Vec, v2: Vec): Boolean = v1 == v2 } implicit object VecMonoid extends Monoid[Vec] { def zero: Vec = Vec(0, 0) def append(v1: Vec, v2: => Vec): Vec = Vec(v1.x + v2.x, v1.y + v2.y) } } case class Vec(x: Int, y: Int)
debasishg/proptest
src/main/scala/net/debasishg/prop/vec.scala
Scala
apache-2.0
326
/* * Copyright (c) 2015 Daniel Higuero. * * 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.scala.exercises object Exercise3{ } /** * Class that provides the implementation for the solution of the exercise 3. */ class Exercise3 { }
dhiguero/scala-exercises
src/main/scala/org/scala/exercises/Exercise3.scala
Scala
apache-2.0
760
object HelloWorld { def hello() = "Hello, World!" def hello(name: String) = s"Hello, $name!" }
nlochschmidt/xscala
hello-world/example.scala
Scala
mit
100
/** * Graph class, which is used to search the shorted path between * source/destination stations. * * Be CAREFUL about the relation of different "infinities". * Here we set the infinity of a vertex as 999999, the guard value * to find the vertex with the smallest dist metric as 99999999, * and the penalty value for transit in City.scala as 9999 (minutes). * * @author Yujian Zhang <yujian{dot}zhang[at]gmail(dot)com> * * License: * GNU General Public License v2 * http://www.gnu.org/licenses/gpl-2.0.html * Copyright (C) 2013 Yujian Zhang */ package net.whily.scasci.collection import scala.collection.mutable import scala.util.control.Breaks._ class Edge(val vertex: Int, val weight: Int) { override def toString = "e(" + vertex + " ," + weight + ")" } object Vertex { val Infinity = 999999 val Undefined = -1 } /** * We use adjacency list (http://en.wikipedia.org/wiki/Adjacency_list) to implement graph, * which is done in field neighbors. * Fields like dist and prev are used for Dijkstra's algorithm. * Field tag is the name of the Vertex. */ class Vertex(val tag: String, var neighbors: List[Edge]) { var dist: Int = Vertex.Infinity var prev: Int = Vertex.Undefined } object Graph { /** * Construct a graph object based on the weight map. * We don't care whether the graph is directed or not. * If it is undirected, the caller should make sure to add * both u->v and v->u in the weightMap. */ def Graph(weightMap: mutable.HashMap[(String, String), Int]): Graph = { val pairs = weightMap.keys val tags = pairs.map(_._1).toSet ++ pairs.map(_._2).toSet val vertices = tags.toArray.map(new Vertex(_, List())) var tagIndexMap = new mutable.HashMap[String, Int]() for (i <- 0 until vertices.size) tagIndexMap += (vertices(i).tag -> i) for (pair <- pairs) { val u = tagIndexMap(pair._1) val v = tagIndexMap(pair._2) val edge = new Edge(v, weightMap(pair)) vertices(u).neighbors = edge :: vertices(u).neighbors } val graph = new Graph(vertices) graph } } class Graph(val vertices: Array[Vertex]) { /** Initialize dist and prev fields of each vertex. */ private def initVertices() { for (vertex <- vertices) { vertex.dist = Vertex.Infinity vertex.prev = Vertex.Undefined } } /** Return the array of neighbor indices of the given vertex. */ private def neighbors(vertex: Int) = vertices(vertex).neighbors.map(_.vertex) /** Return the shortest path (in a list of tags) with Dijkstra's algorithm in: * http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm * * @param source index of source vertex * @param targets indices of target vertices * * We use Dijkstra's algorithm instead of A* algorithm because it is somehow * difficult to find one good heuristic function to take care minimum time and transits * for metro route finding. * * In addition, we don't use priority queue as it might be challenging to implement * "decrease key" operation. */ def find(source: Int, targets: List[Int]): List[List[String]] = { /** Return the path given `target`. */ def path(target: Int): List[String] = { var s: List[Int] = List() var u = target while (vertices(u).prev != Vertex.Undefined) { s = u :: s u = vertices(u).prev } s = source :: s s.map(vertices(_).tag) } initVertices() var ts = targets.toSet vertices(source).dist = 0 // Performance might be improved if we separate q to two sets, one set whose // dist values not update, while dist is updated in another set. In this way, // finding the vertex with minimum dist can be done in the latter set only. // However we will do such optimization until we see performance problems. var q = (0 until vertices.length).toSet breakable { while (!q.isEmpty) { // Find the vertex with the smallest dist var u = -1 var d = 99999999 for (v <- q) { val dist = vertices(v).dist if (dist < d) { u = v d = dist } } ts -= u if (ts.isEmpty) break q -= u // Error input if all remaining vertices are inaccessible from source. assert(vertices(u).dist != Vertex.Infinity) for (vv <- vertices(u).neighbors if q.contains(vv.vertex)) { val v = vv.vertex val alt = vertices(u).dist + vv.weight if (alt < vertices(v).dist) { vertices(v).dist = alt vertices(v).prev = u } } } } targets.map(path _) } def find(sourceTag: String, targetTags: List[String]): List[List[String]] = { var sourceIndex = -1 val targetIndices = targetTags.map(_ => -1).toArray for (i <- 0 to vertices.size - 1) { if (vertices(i).tag == sourceTag) sourceIndex = i for (j <- 0 to targetIndices.size - 1) if (vertices(i).tag == targetTags(j)) targetIndices(j) = i } assert (sourceIndex != -1 && targetIndices.forall(_ != -1)) find(sourceIndex, targetIndices.toList) } }
whily/scasci
src/main/scala/collection/Graph.scala
Scala
gpl-2.0
5,248
package com.github.jeroenr.tepkin.protocol.exception import com.github.jeroenr.tepkin.protocol.result.WriteConcernError case class WriteConcernException(writeConcernError: WriteConcernError) extends TepkinException
jeroenr/tepkin
tepkin/src/main/scala/com/github/jeroenr/tepkin/protocol/exception/WriteConcernException.scala
Scala
apache-2.0
217