当前位置: 首页>>代码示例>>Scala>>正文


Scala Set类代码示例

本文整理汇总了Scala中scala.collection.mutable.Set的典型用法代码示例。如果您正苦于以下问题:Scala Set类的具体用法?Scala Set怎么用?Scala Set使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Set类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: MedicineProcess

//设置package包名称以及导入依赖的类
package cn.com.warlock.practice.ml

import java.io.BufferedReader
import java.nio.charset.StandardCharsets
import java.nio.file.{Files, Paths}

import org.apache.spark.ml.UnaryTransformer
import org.apache.spark.ml.param.ParamMap
import org.apache.spark.ml.util.Identifiable
import org.apache.spark.sql.types.{ArrayType, DataType, StringType}

import scala.collection.mutable.Set

class MedicineProcess(override val uid: String, private val dict: String)
  extends UnaryTransformer[Seq[String], Seq[String], MedicineProcess] {

  def this(dict: String) = this(Identifiable.randomUID("med"), dict)

  // ?????????
  private val wordsSet = loadDict

  // ????
  private def loadDict: Set[String] = {
    val br: BufferedReader = Files.newBufferedReader(Paths.get(dict), StandardCharsets.UTF_8)
    val words = Set[String]()

    var count = 0

    while (br.ready()) {
      words += br.readLine()
      count += 1
    }

    println(s"load med words: $count")

    words
  }

  override protected def createTransformFunc: Seq[String] => Seq[String] = (words: Seq[String]) => {
    // ?? "???", arr ?????????, c ??????? word
    words.foldLeft(List[String]())((arr, c) => {
      val newC = wordsSet.contains(c) match {
        case true => List(c, "_MED_")
        case false => List(c)
      }
      arr ++ newC
    })
  }

  override protected def validateInputType(inputType: DataType): Unit = {
    require(inputType.isInstanceOf[ArrayType],
      s"The input column must be ArrayType, but got $inputType.")
  }

  override protected def outputDataType: DataType = new ArrayType(StringType, true)

  override def copy(extra: ParamMap): MedicineProcess = defaultCopy(extra)
} 
开发者ID:warlock-china,项目名称:spark-meepo,代码行数:59,代码来源:MedicineProcess.scala

示例2: Problem

//设置package包名称以及导入依赖的类
object Problem {

  def main(args: Array[String]) {

    import scala.collection.mutable.Set

    // ????? ????
    def isAbundant(num: Int): Boolean = {
      val ls: Set[Int] = Set()
      for { a <- 1 to num; if (num % a == 0) }
        ls += (a, num / a)
      (ls - num).sum > num
    }

    // ????? ?? ??? ???
    def getAbundantsComb(ab: List[Int], numbers: Array[Boolean]): Array[Boolean] = {
      if (ab.length < 1)
        numbers
      else {
        ab.foreach((x) => numbers(x + ab.head) = true)
        getAbundantsComb(ab.tail, numbers) // ??
      }
    }

    val abundants = (for { i <- 1 until 28123; if (isAbundant(i)) } yield i).toList
    val numbers = getAbundantsComb(abundants, new Array[Boolean](28123 * 2))

    val result = (for { i <- 1 until numbers.length; if (!numbers(i) && i <= 28123) }
      yield i).toList.sum
    println(result)
  }
} 
开发者ID:johngrib,项目名称:project_euler,代码行数:33,代码来源:Problem023.scala

示例3: KthMultiple

//设置package包名称以及导入依赖的类
package org.pfcoperez.cci.hard

object KthMultiple extends App {

  def kthMultiple(k: Int, primes: Set[Long]): Long = {
    import scala.collection.mutable.Set

    val multiples = Set.empty[Long]
    var scout: Long = 1
    var lastMultiple: Long = scout

    multiples.add(scout)
    multiples.add(1)

    while(multiples.size < k) {
      if(primes.exists(p => scout % p == 0 && multiples.contains(scout/p))) {
        multiples.add(scout)
        lastMultiple = scout
      }
      scout += 1
    }

    lastMultiple

  }

  (1 to 10) foreach { i =>
    println(kthMultiple(i, Set(3,5,7)))
  }

} 
开发者ID:pfcoperez,项目名称:cci,代码行数:32,代码来源:KthMultiple.scala

示例4: StreetActor

//设置package包名称以及导入依赖的类
package ch.becompany.akka.demo.actor

import scala.collection.mutable.Set
import akka.actor.{Actor, ActorLogging, ActorRef, Props}
import ch.becompany.akka.demo.actor.StreetActor.{Initialize, LeaveQueue}

class StreetActor(val maximum: Int = 15, val barsNumber: Int = 1) extends Actor with ActorLogging {
  var bars = scala.collection.mutable.ArrayBuffer.empty[ActorRef]
  var queue = Set[ActorRef]()
  var counter = 0

  override def receive = {
    case Initialize => {
      log.info("Street is being created.")
      for (i <- 0 until barsNumber ) {
        bars += context.actorOf(BarActor.props, "bar" + i)
        log.info(s"Created 'bar$i'.")
      }
      bars map (actor => actor ! Initialize)
    }
    case LeaveQueue => {
      queue.remove(sender())
    }
    case customerName: String =>  {
      if (queue.size < maximum) {
        counter += 1
        val customerActor = context.actorOf(CustomerActor.props(customerName), "customer" + counter)
        queue += customerActor
        log.info(s"The customer '$customerName' is in the queue. Queue size: ${queue.size}")

        customerActor ! Initialize
      } else {
        log.warning(s"Customer '$customerName' has to leave because queue is full.")
      }
    }
    case unknown => log.error(s"Actor name '$unknown' not recognized.")
  }
}

object StreetActor {
  def props(maximum: Int) = Props(new StreetActor(maximum))
  case object Initialize
  case object LeaveQueue
} 
开发者ID:becompany,项目名称:cooking-with-akka,代码行数:45,代码来源:StreetActor.scala

示例5: PageTracker

//设置package包名称以及导入依赖的类
import akka.actor.Actor
import scala.collection.mutable.{HashSet, Set}

class PageTracker extends Actor {
  var pages: Set[Page] = new HashSet[Page]()

  def receive = {

    case PageCheck(page, replyTo) => {
      if (pages.contains(page)) {
        replyTo ! DoNotCrawl(page)
      } else {
        pages.add(page)
        replyTo ! DoCrawl(page)
      }
    }
    case RemovePage(page) => {
       pages.remove(page)
    }
  }
} 
开发者ID:rzrelyea,项目名称:scala-akka-web-crawler,代码行数:22,代码来源:PageTracker.scala

示例6: LinkQueueActor

//设置package包名称以及导入依赖的类
package cs220.actors

import scala.collection.mutable.Queue
import scala.collection.mutable.Set
import akka.actor.{Actor, ActorRef, ActorLogging}


class LinkQueueActor(parseQueue: ActorRef) extends Actor with ActorLogging {
  // We have provided some definitions below which will help you with
  // you implementation. You are welcome to modify these, however, this
  // is what we used for our implementation.
  log.info("LinkQueueActor created")
  val queue        = Queue[String]()
  val fetchers     = Set[ActorRef]()
  var limit        = 500

  def receive = {

    case NeedLink =>     if(limit == 0)
                             context.system.shutdown()
                         else {
                               if(queue.isEmpty)
                                  sender ! NoLinks
                                  else
                                  {
                                   println(limit + " more links to do")
                                    limit = limit -1
                                    sender ! FetchLink(queue.dequeue)
                                  }
                                }


    case Page(url,html)    =>  parseQueue ! Page(url,html)

    case QueueLink(url)    => queue.enqueue(url)
  }

} 
开发者ID:juconghe,项目名称:web-crawler,代码行数:39,代码来源:LinkQueueActor.scala

示例7: ChatRoom

//设置package包名称以及导入依赖的类
package chatup.server

import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorRef
import scala.collection.mutable.Set
import play.Logger

class ChatRoom(name: String, var available: Set[ActorRef]) extends Actor with ActorLogging {

  override def receive = {
    case joined: Join => {
      available = available + sender
      val broadcast = Notification(s"${joined.member} joined the chat room")
      (available - sender).foreach { actor => actor ! broadcast }
      Logger.info("Joined 1 member. # of Available members " + available.size)
    }
    case leave: Leave => {
      val broadcast = Notification(s"<i>@${leave.member}</i> left the chat room")
      available = available - sender
      available.foreach { actor => actor ! broadcast }
      
    }
    case msg: BroadCastMessage => {
      available.foreach { actor => actor ! msg }
    }
  }
}

trait Message
case class Join(member: String) extends Message
case class Leave(member: String) extends Message
case class BroadCastMessage(author : String, msg: String,color : String) extends Message
case class Notification(message : String) extends Message 
开发者ID:amezng,项目名称:akka-chat,代码行数:35,代码来源:ChatRoom.scala

示例8: ChatManager

//设置package包名称以及导入依赖的类
package chatup.server

import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorRef
import akka.actor.ActorSystem
import akka.actor.Props
import scala.collection.mutable.Set
import play.Logger

case class ChatManager(val chatRooms: List[ActorRef]) {
  //Work in progress
  // Add feature to initialize list of chat rooms

}

object ChatManager {

  def getChatRoom(roomName: String)(implicit system: ActorSystem) = {
    Logger.info("Creating the chat room")
    system.actorOf(Props(classOf[ChatRoom], roomName, Set()), name = roomName)
  }

}

case class ClientActor(color : String, member: String, out: ActorRef, chat: ActorRef) extends Actor with ActorLogging {

  chat ! Join(member)
  Logger.info("Joined the chat")
  
  override def postStop() = {
    Logger.info("leaving the chat room ")
    chat ! Leave(member)
  }

  def receive = {
    case message: String           => chat ! BroadCastMessage(member,message,color)
    case BroadCastMessage(author, message,color) => out ! s"$color:$author : $message"
    case Notification(message) => out ! s"#fff:Admin : $message"
  }

} 
开发者ID:amezng,项目名称:akka-chat,代码行数:43,代码来源:ChatManager.scala

示例9: GossipingBestEffortBroadcastComponent

//设置package包名称以及导入依赖的类
package se.kth.app.broadcast

import com.typesafe.scalalogging.StrictLogging
import se.kth.app.events.{HistoryRequest, _}
import se.kth.app.ports.{GossipingBestEffortBroadcast, PerfectLink}
import se.sics.kompics.{KompicsEvent, Start}
import se.sics.kompics.sl._
import se.sics.ktoolbox.croupier.CroupierPort
import se.sics.ktoolbox.croupier.event.CroupierSample
import se.sics.ktoolbox.util.network.KAddress

import scala.collection.JavaConversions._
import scala.collection.mutable.Set


class GossipingBestEffortBroadcastComponent(init: Init[GossipingBestEffortBroadcastComponent]) extends ComponentDefinition with StrictLogging{
  val gbeb: NegativePort[GossipingBestEffortBroadcast] = provides[GossipingBestEffortBroadcast]
  val pLink: PositivePort[PerfectLink] = requires[PerfectLink]
  val croupier: PositivePort[CroupierPort] = requires[CroupierPort]

  var self: KAddress = init match {case Init(self:KAddress) => self}
  var past: Set[(KAddress, KompicsEvent)] = Set.empty[(KAddress, KompicsEvent)]

  ctrl uponEvent {
    case _:Start => handle {
      logger.info("Starting...")
      past = Set.empty[(KAddress, KompicsEvent)]
    }
  }

  gbeb uponEvent {
    case GBEB_Broadcast(payload: KompicsEvent) => handle {
      past += ((self, payload))
    }
  }

  croupier uponEvent {
    case  sample:CroupierSample[_] => handle {
      logger.info("Croupier sample received")
      if(!sample.publicSample.isEmpty){
        val nodes = sample.publicSample.values().map{ x => x.getSource}
        for (p <- nodes) trigger(PL_Send(p, new HistoryRequest) -> pLink)

      }
    }
  }

  pLink uponEvent {
    case  PL_Deliver(src: KAddress, _:HistoryRequest) => handle {
      trigger(PL_Send(src, HistoryResponse(past)) -> pLink)
    }
    case PL_Deliver(_:KAddress, HistoryResponse(history)) => handle {
      val unseen = history.diff(past)

      for ((pp, m) <- unseen) trigger(GBEB_Deliver(pp, m) -> gbeb)
      past ++= unseen
    }
  }

} 
开发者ID:reginbald,项目名称:p2p-crdt,代码行数:61,代码来源:GossipingBestEffortBroadcastComponent.scala

示例10: Function

//设置package包名称以及导入依赖的类
package scanalyzer
package cfg

import scala.collection.mutable.{Set, Queue}

sealed class Function(funName: String) extends Iterable[BasicBlock] {
  private val _name: String = funName
  private var _first: BasicBlock = null

  def name: String = _name

  def first: BasicBlock = _first

  def first_=(bb: BasicBlock): Unit = _first = bb

  override def iterator: Iterator[BasicBlock] = new Iterator[BasicBlock] {
    private val visited = Set[BasicBlock]()
    private val queue = new Queue[BasicBlock]() += first

    def hasNext = ! queue.isEmpty

    def next = {
      val res = queue.dequeue
      visited += res
      res foreach {
        case B(cond, ifBB, elseBB) => {
          if (! (visited contains ifBB) && ! (queue contains ifBB)) {
            queue += ifBB
          }
          if (! (visited contains elseBB) && ! (queue contains elseBB)) {
            queue += elseBB
          }
        }
        case _ =>
      }
      res
    }
  }

  
  def traverseInstructions(action: Instruction => Unit): Unit =
    traverseBB(bb => bb foreach action)

  override def toString(): String = {
    var res = "fun " + name + " {\n"
    this foreach (bb => res += "" + bb + "\n")
    res += "}\n"
    res
  }
} 
开发者ID:fabian-r,项目名称:scanalyzer,代码行数:51,代码来源:Function.scala

示例11: getMapping

//设置package包名称以及导入依赖的类
package scanalyzer
package analysis
package dominance

import cfg._
import util._

import scala.collection.mutable.{Set, Map, Queue}


  def getMapping(): Map[BasicBlock, Set[BasicBlock]] = {
    blocktab.clone
  }

  override def getResult(): String = {
    var res = ""
    for ((k, v) <- blocktab)
      res += k.Name + " -> " + Util.strItBB(v) + "\n"
    res
  }
} 
开发者ID:fabian-r,项目名称:scanalyzer,代码行数:22,代码来源:DominanceAnalysis.scala

示例12:

//设置package包名称以及导入依赖的类
package scanalyzer
package analysis

import cfg._
import util._

import scala.collection.mutable.{Set, Queue, Map}


    val depMap = Map[Named, Set[Named]]()

    setUpDependencyMap(depMap)

    Util.dbgmsg("Dependencies:")
    if (Util.dbg) {
      depMap foreach {
        case (Named(n), s) => Util.dbgmsg("  " + n + " ->" + Util.strIt(s))
        case _ =>
      }
    }

    val queue = new Queue[Named]

    queue ++= depMap.keys

    while (! queue.isEmpty) {
      Util.dbgmsg("Queue: " + Util.strIt(queue))

      val current = queue.dequeue
      val before = symtab(current.Name)
      eval(current)
      val after = symtab(current.Name)

      Util.dbgmsg("Transform `" + current.Name + "` from `" + before +
        "` to `" + after)

      if (after != before) {
        val add = (depMap(current) filterNot (queue contains _))
        Util.dbgmsg("  ~> Adding `" + Util.strIt(add) + "` to queue")
        queue ++= add
      }
    }
  }
} 
开发者ID:fabian-r,项目名称:scanalyzer,代码行数:45,代码来源:SimpleValueIterationAnalysis.scala

示例13: Auth

//设置package包名称以及导入依赖的类
package model

import scala.collection.mutable.Set
import twitter4j.auth.AccessToken
import twitter4j.conf.PropertyConfiguration

class Auth private(val token: AccessToken) {
	def id = token.getUserId
	def remove {
		Auth.accounts -= id
		Auth.pref.remove(Auth.ATOKEN.format(id))
		Auth.pref.remove(Auth.SECRET.format(id))
		Auth.put("ids", Auth.accounts.toSeq)
	}
}

object Auth extends Conf("authentication") {
	val keys = Mbed.stream("rabbit.key")
	val conf = new PropertyConfiguration(keys)
	keys.close
	private val accounts = Set[Long]()
	val ATOKEN = "atoken.%d"
	val SECRET = "secret.%d"
	accounts ++= seq("ids").map(_.toLong)
	def apply(id: Long): Auth = {
		val a = pref.get(ATOKEN.format(id), "")
		val s = pref.get(SECRET.format(id), "")
		new Auth(new AccessToken(a, s))
	}
	def add(token: AccessToken): Auth = {
		val a = token.getToken
		val s = token.getTokenSecret
		val id = token.getUserId
		pref.put(ATOKEN.format(id), a)
		pref.put(SECRET.format(id), s)
		accounts += id
		put("ids", accounts.toSeq)
		new Auth(token)
	}
	def ids = accounts.toSeq
	def all = accounts.map(Auth(_)).toSeq
	def selfs = all.map(new Self(_)(Auth.conf))
} 
开发者ID:nextzlog,项目名称:nabe,代码行数:44,代码来源:Auth.scala

示例14: LinkQueueActor

//设置package包名称以及导入依赖的类
package cs220.actors

import scala.collection.mutable.Queue
import scala.collection.mutable.Set
import akka.actor.{Actor, ActorRef, ActorLogging}


class LinkQueueActor(parseQueue: ActorRef) extends Actor with ActorLogging {
  // We have provided some definitions below which will help you with
  // you implementation. You are welcome to modify these, however, this
  // is what we used for our implementation.
  log.info("LinkQueueActor created")
  val queue        = Queue[String]()
  val fetchers     = Set[ActorRef]()
  var limit        = 500

  def receive = {
    case NeedLink =>   {   println("LinkQueueActor receive NeedLink Message\n" + sender)
                            if(limit == 0){
                             context.system.shutdown() }
                             else {
                               limit = limit -1;
                               if(queue.isEmpty)
                                  sender ! NoLinks
                                  else{
                                  sender ! FetchLink(queue.dequeue)
                                }
                             }
                           }

    case Page(url,html)    =>    { println("LinkQueueActor receive Page Message\n" + sender)
                                  parseQueue ! Page(url,html)
                                }

    case QueueLink(url) =>      {
      println("LinkQueueActor receive QueueLink Message\n" + sender)
      queue.enqueue(url)
      println(queue.size)
    }
  }

} 
开发者ID:amherst-takeout,项目名称:asn-inverted-index-student-master,代码行数:43,代码来源:LinkQueueActor.scala

示例15: UntypedTaskEventBus

//设置package包名称以及导入依赖的类
package org.kneelawk.simplecursemodpackdownloader

import scala.collection.mutable.HashMap
import scala.collection.mutable.MultiMap
import scala.collection.mutable.Set
import scala.reflect.ClassTag


class UntypedTaskEventBus(task: UntypedTaskEventBus => Unit) {
  val listeners = new HashMap[Class[_], Set[EventListener[_]]] with MultiMap[Class[_], EventListener[_]]

  def onEvent[EventType](listener: EventType => Unit)(implicit ct: ClassTag[EventType]) {
    listeners.addBinding(ct.runtimeClass, new EventListener[EventType](listener))
  }

  def sendEvent(event: AnyRef) {
    val eventClass = event.getClass
    if (listeners.contains(eventClass)) {
      for (listener <- listeners.get(eventClass).get) {
        listener(event)
      }
    }
  }

  def startTask = task(this)
}

class EventListener[EventType: ClassTag](listener: EventType => Unit) {
  def apply(event: AnyRef) {
    listener(event.asInstanceOf[EventType])
  }
} 
开发者ID:Kneelawk,项目名称:SimpleCurseModpackDownloader,代码行数:33,代码来源:UntypedTaskEventBus.scala


注:本文中的scala.collection.mutable.Set类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。