scala.collection.Set Scala Examples

The following examples show how to use scala.collection.Set. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: SpecHelpers.scala    From money   with Apache License 2.0 5 votes vote down vote up
package com.comcast.money.core

import com.comcast.money.api.{ SpanId, SpanInfo }
import com.comcast.money.core.handlers.LoggingSpanHandler
import com.typesafe.config.Config
import org.scalatest.Matchers
import org.scalatest.concurrent.Eventually
import org.scalatest.time.{ Millis, Span }

import scala.collection.{ Set, mutable }
import scala.concurrent.duration._

object LogRecord {
  private val spans = new mutable.ArrayBuffer[SpanInfo]
  private val messages = new mutable.HashMap[String, mutable.Set[String]] with mutable.MultiMap[String, String]

  def clear(): Unit = {
    messages.clear()
    spans.clear()
  }

  def add(log: String, message: String): Unit = messages.addBinding(log, message)

  def add(spanInfo: SpanInfo): Unit = spans.append(spanInfo)

  def contains(log: String)(cond: String => Boolean): Boolean = messages.entryExists(log, cond)

  def contains(cond: SpanInfo => Boolean): Boolean = spans.exists(cond)

  def log(name: String): Set[String] = messages.getOrElse(name, mutable.Set.empty)
}

class LogRecorderSpanHandler extends LoggingSpanHandler {

  override def configure(config: Config): Unit = {
    super.configure(config)
    logFunction = record
  }

  override def handle(spanInfo: SpanInfo): Unit = {
    LogRecord.add(spanInfo)
    super.handle(spanInfo)
  }

  def record(message: String): Unit = LogRecord.add("log", message)
}

trait SpecHelpers extends Eventually { this: Matchers =>

  def awaitCond(condition: => Boolean, max: FiniteDuration = 2.seconds, interval: Duration = 100.millis, message: String = "failed waiting"): Unit = {
    implicit val patienceConfig: PatienceConfig = PatienceConfig(Span(max.toMillis, Millis), Span(interval.toMillis, Millis))
    eventually {
      assert(condition, message)
    }
  }

  def expectSpanInfoThat(message: String, condition: SpanInfo => Boolean, wait: FiniteDuration = 2.seconds): Unit = {
    awaitCond(
      LogRecord.contains(condition), wait, 100 milliseconds,
      s"Expected span info that $message not found after $wait")
  }

  def dontExpectSpanInfoThat(message: String, condition: SpanInfo => Boolean, wait: FiniteDuration = 2.seconds): Unit = {
    awaitCond(
      !LogRecord.contains(condition), wait, 100 milliseconds,
      s"Not expected span info that $message found after $wait")
  }

  def expectLogMessageContaining(contains: String, wait: FiniteDuration = 2.seconds) {
    awaitCond(
      LogRecord.contains("log")(_.contains(contains)), wait, 100 milliseconds,
      s"Expected log message containing string $contains not found after $wait")
  }

  def expectLogMessageContainingStrings(strings: Seq[String], wait: FiniteDuration = 2.seconds) {
    awaitCond(
      LogRecord.contains("log")(s => strings.forall(s.contains)), wait, 100 milliseconds,
      s"Expected log message containing $strings not found after $wait")
  }

  def testSpan(id: SpanId) = Money.Environment.factory.newSpan(id, "test")
} 
Example 2
Source File: Cache.scala    From sangria   with Apache License 2.0 5 votes vote down vote up
package sangria.util

import scala.collection.{Map, Set}

trait Cache[Key, Value] {
  def size: Int

  def contains(key: Key): Boolean
  def apply(key: Key): Value
  def get(key: Key): Option[Value]
  def getOrElse(key: Key, default: => Value): Value
  def update(key: Key, value: Value): Unit
  def remove(key: Key): Unit
  def clear(): Unit

  // NOTE: that `getOrElseUpdate` allows a race condition between value retrieval and cache update.
  // It is an explicit decision to avoid any kind of synchronization (it is preferred to recompute value multiple times than to synchronize)
  def getOrElseUpdate(key: Key, fn: => Value): Value
  def find(fn: (Key, Value) => Boolean): Option[(Key, Value)]
  def mapToSet[R](fn: (Key, Value) => R): Set[R]
  def mapValues[R](fn: Value => R): Map[Key, R]
  def keyExists(fn: Key => Boolean): Boolean
  def forEachValue(fn: Value => Unit): Unit
  def removeKeys(fn: Key => Boolean): Unit
}

object Cache {
  def empty[Key, Value]: Cache[Key, Value] = emptyConcurrentHashMap[Key, Value]

  def emptyTrieMap[Key, Value] = new TrieMapCache[Key, Value]
  def emptyConcurrentHashMap[Key, Value] = new ConcurrentHashMapCache[Key, Value]
  
  def apply[Key, Value](elems: (Key, Value)*) = {
    val c = empty[Key, Value]
    elems.foreach {case (key, value) => c(key) = value}
    c
  }
} 
Example 3
Source File: ResolvableStableCodeReferenceElement.scala    From intellij-lsp   with Apache License 2.0 5 votes vote down vote up
package org.jetbrains.plugins.scala.lang.resolve

import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi._
import org.jetbrains.plugins.scala.lang.psi.api.base._
import org.jetbrains.plugins.scala.macroAnnotations.{CachedWithRecursionGuard, ModCount}

import scala.collection.Set

trait ResolvableStableCodeReferenceElement

object ResolvableStableCodeReferenceElement {

  implicit class Ext(val stableRef: ScStableCodeReferenceElement) extends AnyVal {

    @CachedWithRecursionGuard(stableRef, Array.empty, ModCount.getBlockModificationCount)
    def resolveTypesOnly(incomplete: Boolean): Array[ResolveResult] = {
      val importResolverNoMethods = new StableCodeReferenceElementResolver(stableRef, false, false, false) {
        override protected def getKindsFor(ref: ScStableCodeReferenceElement): Set[ResolveTargets.Value] = {
          ref.getKinds(incomplete = false) -- StdKinds.methodRef
        }
      }
      importResolverNoMethods.resolve(stableRef, incomplete)
    }

    @CachedWithRecursionGuard(stableRef, Array.empty, ModCount.getBlockModificationCount)
    def resolveMethodsOnly(incomplete: Boolean): Array[ResolveResult] = {
      val importResolverNoTypes = new StableCodeReferenceElementResolver(stableRef, false, false, false) {
        override protected def getKindsFor(ref: ScStableCodeReferenceElement): Set[ResolveTargets.Value] = {
          ref.getKinds(incomplete = false) -- StdKinds.stableClass
        }
      }

      importResolverNoTypes.resolve(stableRef, incomplete)
    }

    @CachedWithRecursionGuard(stableRef, EMPTY_ARRAY, ModCount.getBlockModificationCount)
    def resolveNoConstructor: Array[ResolveResult] = {
      ProgressManager.checkCanceled()
      val noConstructorResolver = new StableCodeReferenceElementResolver(stableRef, false, false, true)
      noConstructorResolver.resolve(stableRef, incomplete = false)
    }

    @CachedWithRecursionGuard(stableRef, EMPTY_ARRAY, ModCount.getBlockModificationCount)
    def resolveAllConstructors: Array[ResolveResult] = {
      ProgressManager.checkCanceled()
      val resolverAllConstructors = new StableCodeReferenceElementResolver(stableRef, false, true, false)
      resolverAllConstructors.resolve(stableRef, incomplete = false)
    }

    @CachedWithRecursionGuard(stableRef, EMPTY_ARRAY, ModCount.getBlockModificationCount)
    def shapeResolve: Array[ResolveResult] = {
      ProgressManager.checkCanceled()
      val shapesResolver = new StableCodeReferenceElementResolver(stableRef, true, false, false)
      shapesResolver.resolve(stableRef, incomplete = false)
    }

    @CachedWithRecursionGuard(stableRef, EMPTY_ARRAY, ModCount.getBlockModificationCount)
    def shapeResolveConstr: Array[ResolveResult] = {
      ProgressManager.checkCanceled()
      val shapesResolverAllConstructors = new StableCodeReferenceElementResolver(stableRef, true, true, false)
      shapesResolverAllConstructors.resolve(stableRef, incomplete = false)
    }
  }

  val EMPTY_ARRAY: Array[ResolveResult] = Array.empty[ResolveResult]
} 
Example 4
Source File: CollectAllForImportProcessor.scala    From intellij-lsp   with Apache License 2.0 5 votes vote down vote up
package org.jetbrains.plugins.scala.lang.resolve.processor

import com.intellij.psi._
import org.jetbrains.plugins.scala.lang.psi.impl.ScPackageImpl
import org.jetbrains.plugins.scala.lang.resolve.{ResolveTargets, ScalaResolveResult}

import scala.collection.Set

class CollectAllForImportProcessor(override val kinds: Set[ResolveTargets.Value],
                                   override val ref: PsiElement,
                                   override val name: String)
  extends ResolveProcessor(kinds, ref, name) {
  override def execute(element: PsiElement, state: ResolveState): Boolean = {
    val named = element.asInstanceOf[PsiNamedElement]
    if (nameAndKindMatch(named, state)) {
      val accessible = isAccessible(named, ref)
      if (accessibility && !accessible) return true
      named match {
        case pack: PsiPackage =>
          candidatesSet += new ScalaResolveResult(ScPackageImpl(pack), getSubst(state), getImports(state),
            isAccessible = true)
        case _ =>  candidatesSet += new ScalaResolveResult(named, getSubst(state), getImports(state),
          boundClass = getBoundClass(state), fromType = getFromType(state), isAccessible = true)
      }
    }
    true
  }
} 
Example 5
Source File: ImplicitProcessor.scala    From intellij-lsp   with Apache License 2.0 5 votes vote down vote up
package org.jetbrains.plugins.scala.lang.resolve.processor

import java.util

import org.jetbrains.plugins.scala.lang.resolve.ResolveTargets._
import org.jetbrains.plugins.scala.lang.resolve.ScalaResolveResult
import org.jetbrains.plugins.scala.lang.resolve.processor.precedence._
import org.jetbrains.plugins.scala.project.ProjectContext

import scala.collection.Set


abstract class ImplicitProcessor(kinds: Set[Value], withoutPrecedence: Boolean)
                                (implicit projectContext: ProjectContext) extends BaseProcessor(kinds) with SubstitutablePrecedenceHelper[String] {

  override protected val holder: TopPrecedenceHolder[String] = new TopPrecedenceHolderImpl[String] {

    override def toRepresentation(result: ScalaResolveResult): String = result
  }

  protected val levelMap: util.HashMap[String, util.HashSet[ScalaResolveResult]] = new util.HashMap[String, util.HashSet[ScalaResolveResult]]()

  override protected def clearLevelQualifiedSet(result: ScalaResolveResult) {
    //optimisation, do nothing
  }

  override protected def getLevelSet(result: ScalaResolveResult): util.HashSet[ScalaResolveResult] = {
    import holder.toRepresentation
    val qualifiedName: String = result
    var levelSet = levelMap.get(qualifiedName)
    if (levelSet == null) {
      levelSet = new util.HashSet[ScalaResolveResult]
      levelMap.put(qualifiedName, levelSet)
    }
    levelSet
  }

  override protected def addResults(results: Seq[ScalaResolveResult]): Boolean = {
    if (withoutPrecedence) {
      candidatesSet ++= results
      true
    } else super.addResults(results)
  }

  override def changedLevel: Boolean = {
    if (levelMap.isEmpty) return true
    val iterator = levelMap.values().iterator()
    while (iterator.hasNext) {
      val setIterator = iterator.next().iterator()
      while (setIterator.hasNext) {
        candidatesSet += setIterator.next
      }
    }
    qualifiedNamesSet.addAll(levelQualifiedNamesSet)
    levelMap.clear()
    levelQualifiedNamesSet.clear()
    true
  }

  override def candidatesS: Set[ScalaResolveResult] = {
    val res = candidatesSet
    val iterator = levelMap.values().iterator()
    while (iterator.hasNext) {
      val setIterator = iterator.next().iterator()
      while (setIterator.hasNext) {
        candidatesSet += setIterator.next
      }
    }
    res
  }

  override protected def isCheckForEqualPrecedence = false

  override def isImplicitProcessor: Boolean = true
} 
Example 6
Source File: ExpandedExtractorResolveProcessor.scala    From intellij-lsp   with Apache License 2.0 5 votes vote down vote up
package org.jetbrains.plugins.scala.lang.resolve.processor

import com.intellij.psi._
import org.jetbrains.plugins.scala.lang.psi.api.base.ScReferenceElement
import org.jetbrains.plugins.scala.lang.psi.api.statements._
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.ScTypedDefinition
import org.jetbrains.plugins.scala.lang.psi.types._
import org.jetbrains.plugins.scala.lang.psi.types.api.designator.ScProjectionType
import org.jetbrains.plugins.scala.lang.psi.types.result._
import org.jetbrains.plugins.scala.lang.resolve.{ResolveTargets, ScalaResolveResult, StdKinds}

import scala.collection.Set
import scala.collection.mutable.ArrayBuffer

class ExpandedExtractorResolveProcessor(ref: ScReferenceElement,
                                        refName: String,
                                        kinds: Set[ResolveTargets.Value],
                                        expected: Option[ScType])
        extends ExtractorResolveProcessor(ref, refName, kinds, expected) {
  override def execute(element: PsiElement, state: ResolveState): Boolean = {
    val named = element.asInstanceOf[PsiNamedElement]
    if (nameAndKindMatch(named, state)) {
      val accessible = isAccessible(named, ref)
      if (accessibility && !accessible) return true
      named match {
        case bind: ScTypedDefinition => {
          val parentSubst = getSubst(state)
          val parentImports = getImports(state)
          val typez = getFromType(state) match {
            case Some(tp) => ScProjectionType(tp, bind, superReference = false)
            case _ => bind.`type`().getOrAny
          }
          var seq = false
          val buffer = new ArrayBuffer[ScalaResolveResult]
          val proc = new BaseProcessor(StdKinds.methodRef) {
            def execute(element: PsiElement, state: ResolveState): Boolean = {
              val subst = getSubst(state)
              element match {
                case fun: ScFunction if fun.name == "unapply" || (seq && fun.name == "unapplySeq") =>
                  buffer += new ScalaResolveResult(fun,
                    parentSubst.followed(subst), parentImports, parentElement = Some(bind),
                    isAccessible = accessible)
                case _ =>
              }
              true
            }
          }
          proc.processType(parentSubst.subst(typez), ref, ResolveState.initial)
          addResults(buffer.toSeq)
          if (candidatesSet.isEmpty && levelSet.isEmpty) {
            buffer.clear()
            seq = true
            proc.processType(parentSubst.subst(typez), ref, ResolveState.initial)
            addResults(buffer.toSeq)
          }
        }
        case _ => return super.execute(element, state)
      }
    }
    true
  }
} 
Example 7
Source File: ImplicitCollectorCache.scala    From intellij-lsp   with Apache License 2.0 5 votes vote down vote up
package org.jetbrains.plugins.scala.lang.psi.implicits

import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.plugins.scala.lang.psi.api.statements.ScFunction
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.ScTypeParametersOwner
import org.jetbrains.plugins.scala.lang.psi.types.ScType
import org.jetbrains.plugins.scala.lang.psi.types.api.TypeParameterType
import org.jetbrains.plugins.scala.lang.resolve.ScalaResolveResult

import scala.collection.{Seq, Set}


class ImplicitCollectorCache(project: Project) {
  private val map =
    ContainerUtil.newConcurrentMap[(ImplicitSearchScope, ScType), Seq[ScalaResolveResult]]()

  private val typeParametersOwnersCache =
    ContainerUtil.newConcurrentMap[ScType, Set[ScTypeParametersOwner]]


  def get(place: PsiElement, tp: ScType): Option[Seq[ScalaResolveResult]] = {
    val scope = ImplicitSearchScope.forElement(place)
    Option(map.get((scope, tp)))
  }

  def put(place: PsiElement, tp: ScType, value: Seq[ScalaResolveResult]): Unit = {
    val scope = ImplicitSearchScope.forElement(place)
    map.put((scope, tp), value)
  }

  def typeParametersOwners(tp: ScType): Set[ScTypeParametersOwner] = {
    def collectOwners: Set[ScTypeParametersOwner] = {
      var result = Set[ScTypeParametersOwner]()
      tp.visitRecursively {
        case TypeParameterType(_, _, _, psiTP) =>
          psiTP.getOwner match {
            case f: ScFunction => result += f
            case _ =>
          }
        case _ =>
      }
      result
    }

    typeParametersOwnersCache.get(tp) match {
      case null =>
        val owners = collectOwners
        typeParametersOwnersCache.putIfAbsent(tp, owners)
        owners
      case seq => seq
    }
  }

  def clear(): Unit = {
    map.clear()
    typeParametersOwnersCache.clear()
  }
} 
Example 8
Source File: NodeRank.scala    From CkoocNLP   with Apache License 2.0 5 votes vote down vote up
package algorithms.graph

import algorithms.graph.common.{Edge, Node}

import scala.collection.{Set, mutable}
import scala.util.control.Breaks._


  private def init() = {
    //添加节点children,将节点flag初始化,并将节点添加到nodeMap
    for (edge <- edgeList) {
      val src = edge.getSrc
      val tar = edge.getTar

      val srcNode: Node = nodeMap.getOrElse(src, new Node())
      val tarNode: Node = nodeMap.getOrElse(tar, new Node())

      if (!isDirected) {
        val tarChildren: List[String] = tarNode.getChildren
        tarNode.setChildren(tarChildren.:+(src)).setFlag(true)
        nodeMap.put(tar, tarNode)
      }

      val srcChildren: List[String] = srcNode.getChildren
      srcNode.setChildren(srcChildren.:+(tar)).setFlag(true)
      nodeMap.put(src, srcNode)
    }

    //添加孤立节点到nodeMap
    for (node <- nodeList) {
      if (nodeMap.get(node.getId).isEmpty) {
        node.setFlag(true)
        nodeMap.put(node.getId, node)
      }
    }
  }
} 
Example 9
Source File: SurvivalDecider.scala    From simple-akka-downing   with Apache License 2.0 5 votes vote down vote up
package com.ajjpj.simpleakkadowning

import akka.actor.Address
import akka.cluster.{Member, UniqueAddress}
import com.ajjpj.simpleakkadowning.SurvivalDecider.ClusterState
import com.typesafe.config.Config

import scala.collection.Set
import scala.collection.immutable.SortedSet


trait SurvivalDecider {
  def isInMinority(clusterState: ClusterState, selfAddress: Address): Boolean
}

object SurvivalDecider {
  private val memberOrdering = new Ordering[ClusterMemberInfo] {
    override def compare (x: ClusterMemberInfo, y: ClusterMemberInfo) =
      Member.addressOrdering.compare(x.uniqueAddress.address, y.uniqueAddress.address)
  }

  case class ClusterMemberInfo(uniqueAddress: UniqueAddress, roles: Set[String], member: Member)
  case class ClusterState(upMembers: Set[ClusterMemberInfo], unreachable: Set[UniqueAddress]) {
    lazy val sortedUpMembers = SortedSet.empty(memberOrdering) ++  upMembers
    lazy val sortedUpAndReachable = sortedUpMembers.filterNot (x => unreachable.contains(x.uniqueAddress))
    lazy val upReachable = upMembers.filterNot(x => unreachable(x.uniqueAddress))
    lazy val upUnreachable = upMembers.filter(x => unreachable(x.uniqueAddress))
  }


  def apply(config: Config): SurvivalDecider = {
    val cc = config.getConfig("simple-akka-downing")

    cc.getString("active-strategy") match {
      case "static-quorum" =>
        val ccc = cc.getConfig("static-quorum")
        val quorumSize = ccc.getInt("quorum-size")
        val role = ccc.getString("role") match {
          case r if r.trim.isEmpty => None
          case r => Some(r)
        }
        new FixedQuorumDecider(quorumSize, role)
      case "keep-majority" =>
        val ccc = cc.getConfig("keep-majority")
        val role = ccc.getString("role") match {
          case r if r.trim.isEmpty => None
          case r => Some(r)
        }
        new KeepMajorityDecider(role)
      case "keep-oldest" =>
        val ccc = cc.getConfig("keep-oldest")
        val downIfAlone = ccc.getBoolean("down-if-alone")
        new KeepOldestDecider(downIfAlone)
    }
  }


  class FixedQuorumDecider(quorumSize: Int, role: Option[String]) extends SurvivalDecider {
    override def isInMinority(clusterState: ClusterState, selfAddress: Address) = {
      val relevantMembers = role match {
        case Some (r) => clusterState.upMembers.filter (_.roles contains r)
        case None =>     clusterState.upMembers
      }

      (relevantMembers -- clusterState.upUnreachable).size < quorumSize
    }
  }

  class KeepMajorityDecider(role: Option[String]) extends SurvivalDecider {
    override def isInMinority (clusterState: ClusterState, selfAddress: Address) = {
      role match {
        case Some(r) =>
          val all = clusterState.upMembers.filter(_.roles contains r)
          val unreachable = clusterState.upUnreachable.filter(_.roles contains r)
          all.size <= 2*unreachable.size
        case None =>
          clusterState.upMembers.size <= 2*clusterState.upUnreachable.size
      }
    }
  }

  class KeepOldestDecider(downIfAlone: Boolean) extends SurvivalDecider {
    override def isInMinority (clusterState: ClusterState, selfAddress: Address) = {
      val allRelevant = clusterState.upMembers
      val oldestRelevant = allRelevant.foldLeft(allRelevant.head)((a, b) => if (a.member isOlderThan b.member) a else b)

      if (downIfAlone) {
        clusterState.upReachable match {
          case s if s == Set(oldestRelevant) => true                                       // only the oldest node --> terminate
          case _ if clusterState.unreachable == Set(oldestRelevant.uniqueAddress) => false // the oldest node is the only unreachable node --> survive
          case _ => clusterState.unreachable contains oldestRelevant.uniqueAddress
        }
      }
      else {
        clusterState.unreachable contains oldestRelevant.uniqueAddress
      }
    }
  }
} 
Example 10
Source File: Settings.scala    From neuroflow   with Apache License 2.0 5 votes vote down vote up
package neuroflow.core

import neuroflow.core.Network.LearningRate

import scala.collection.{Map, Set}


case class Settings[V]
                    (verbose           :  Boolean                      =  true,
                     learningRate      :  LearningRate[V]              =  { case (i, α) => α }: LearningRate[V],
                     updateRule        :  Update[V]                    =  Vanilla[V](),
                     precision         :  Double                       =  1E-3,
                     iterations        :  Int                          =  Int.MaxValue,
                     prettyPrint       :  Boolean                      =  false,
                     batchSize         :  Option[Int]                  =  None,
                     gcThreshold       :  Option[Long]                 =  None,
                     lossFuncOutput    :  Option[LossFuncOutput]       =  None,
                     waypoint          :  Option[Waypoint[V]]          =  None,
                     approximation     :  Option[Approximation[V]]     =  None,
                     regularization    :  Option[Regularization]       =  None,
                     partitions        :  Option[Set[Int]]             =  None,
                     specifics         :  Option[Map[String, V]]       =  None) extends Serializable