• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala HashMap类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: Problem021

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

  def main(args: Array[String]) {

    import scala.collection.mutable.HashMap
    var map = HashMap.empty[Int, Int]

    def getDivSum(num: Int): Int = {
      if (!(map contains num))
        map(num) = (for { a <- 1 until num; if (num % a == 0) } yield a).toList.sum

      map(num)
    }

    def isAmicable(num: Int): Boolean = {
      val fst = getDivSum(num)
      num == getDivSum(fst) && num != fst
    }

    val result = (for {
      i <- 1 to 10000;
      sum = getDivSum(i);
      if (isAmicable(sum))
    } yield sum).toSet

    println(result.sum)
  }
} 
开发者ID:johngrib,项目名称:project_euler,代码行数:29,代码来源:Problem021.scala


示例2: ProblemFourteen

//设置package包名称以及导入依赖的类
package org.nason.euler.ten

import scala.collection.mutable.HashMap


import org.nason.euler.EulerUtils
import org.nason.euler.NumberUtils

object ProblemFourteen {
  def main(args: Array[String]) {
    println( solution4 )
  }
  
  
  def solution4 =
  {
    // memoize function lookup
    val fLengths = new HashMap[BigInt,Int]()
    fLengths(1) = 1
    def f( n:BigInt ) =
    {
      var g = n
      var l = 1
      while( g!=1 )
      {
        if ( fLengths contains g )
        {
          l += fLengths(g) - 1
          g = 1
        }
        else
        {
          (g%2).toInt match
          {
            case 0 => g = g/2
            case 1 => g = BigInt(3)*g + BigInt(1)
          }
          l += 1
        }
      }
      fLengths(n) = l
      l
    }
    NumberUtils seqMax( (1 to 999999) map ( i => (f(i),i) ) )
  }
} 
开发者ID:drkeoni,项目名称:euler-jms-scala,代码行数:47,代码来源:ProblemFourteen.scala


示例3: ProblemTen

//设置package包名称以及导入依赖的类
package org.nason.euler.ten

import scala.collection.mutable.HashMap

object ProblemTen {
  def main(args: Array[String]) {
    println( solution )
  }
  
  def solution =
  {
    val MAX = BigInt(2000000)
    def primes( max : BigInt ) =
    {
      var prime = new HashMap[BigInt,Boolean]
      for( i<-BigInt(2) to max )
        prime(i) = true
      val m = Math ceil (Math sqrt( max toDouble )) toInt
      var stride = BigInt(2)
      while( stride<=m )
      {
        var i = BigInt(2)*stride
        while( i<=max )
        {
          prime( i ) = false
          i += stride
        }
        stride += 1
        while( stride<=m && !prime(stride) )
        {
          stride += 1
        }
      }
      prime filter { a => a._2 } map { a => a._1 }
    }
    primes(MAX) reduceLeft { (a,b) => a+b }
    // for debugging
    //(primes(MAX) toList).sort( (a,b) => a < b )
  }
} 
开发者ID:drkeoni,项目名称:euler-jms-scala,代码行数:41,代码来源:ProblemTen.scala


示例4: table

//设置package包名称以及导入依赖的类
import scala.collection.mutable.HashMap

sealed trait STMap[S,K,V] {
  protected def table: HashMap[K,V]

  def size: ST[S,Int] = ST(table.size)

  // Get the value under a key
  def apply(k: K): ST[S,V] = ST(table(k))

  // Get the value under a key, or None if the key does not exist
  def get(k: K): ST[S, Option[V]] = ST(table.get(k))

  // Add a value under a key
  def +=(kv: (K, V)): ST[S,Unit] = ST(table += kv)

  // Remove a key
  def -=(k: K): ST[S,Unit] = ST(table -= k)
}

object STMap {
  def empty[S,K,V]: ST[S, STMap[S,K,V]] = ST(new STMap[S,K,V] {
    val table = HashMap.empty[K,V]
  })

  def fromMap[S,K,V](m: Map[K,V]): ST[S, STMap[S,K,V]] = ST(new STMap[S,K,V] {
    val table = (HashMap.newBuilder[K,V] ++= m).result
  })
} 
开发者ID:F-kinungi,项目名称:Solutions,代码行数:30,代码来源:03.answer.scala


示例5: Schema

//设置package包名称以及导入依赖的类
package eu.stratosphere.benchmarks.systemml.cli.command.visualizationUtil

import scala.collection.mutable.HashMap
import scala.collection.mutable.ArrayBuffer


class Schema(listc: ArrayBuffer[Metric], mapc: HashMap[String, Int]) {

  var list: ArrayBuffer[Metric] = listc
  var epochID = -1

  def this (listt: ArrayBuffer[Metric]) {
    this(listt, new HashMap[String, Int]())
    
    for (m <- list) {
      if (m.isEpoch()) {
        epochID = m.id
      }
    }
  }
  
  def size() : Int = {
    list.size
  }
} 
开发者ID:fschueler,项目名称:sysml-benchmark,代码行数:26,代码来源:Schema.scala


示例6: GlobalDeviceSet

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

import Chisel.log2Ceil
import cde.{Parameters, Field}
import scala.collection.mutable.HashMap
import junctions._

case object GlobalDeviceSet extends Field[DeviceSet]

case class Device(name: String, size: Int, dtype: String,
  readable: Boolean = true, writeable: Boolean = true)

class DeviceSet {
  val deviceMap = new HashMap[String, Device]()

  def addDevice(name: String, size: Int, dtype: String, readable: Boolean = true, writeable: Boolean = true): Unit =
      addDevice(Device(name, size, dtype, readable, writeable))

  def addDevice(dev: Device): Unit =
    deviceMap(dev.name) = dev

  def toSeq: Seq[Device] = deviceMap.values.toSeq

  def getAddrMap: AddrMap = {
    val devices = this.toSeq.sortWith((a, b) => a.size > b.size)
    val entries = devices.map { case Device(name, size, _, readable, writeable) =>
      val prot = (if (readable) AddrMapProt.R else 0) | (if (writeable) AddrMapProt.W else 0)
      AddrMapEntry(name, MemSize(size, MemAttr(prot)))
    }
    new AddrMap(entries)
  }
} 
开发者ID:shunshou,项目名称:testrocket-chip,代码行数:33,代码来源:DeviceSet.scala


示例7: AkkademyDb

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

import akka.actor.Actor
import akka.event.Logging
import akka.actor.Status
import scala.collection.mutable.HashMap

import com.akkademy.messages._

class AkkademyDb extends Actor {
    val map = new HashMap[String, Object]
    val log = Logging(context.system, this)

    override def receive = {
        case SetRequest(key, value) => {
            log.info("received SetRequest - key: {}  - value: {}", key, value)
            map.put(key, value)
            sender() ! Status.Success(key)
        }
        case SetIfNotExistsRequest(key, value) => {
            log.info("received SetIfNotExistsRequest - key: {}  - value: {}", key, value)
            if (!map.contains(key)) map.put(key, value)
            sender() ! Status.Success(key)
        }
        case GetRequest(key) => {
            log.info("received GetRequest - key {}", key)
            map.get(key) match {
                case Some(value) => sender() ! value
                case None => sender() ! Status.Failure (KeyNotFoundException(key))
            }
        }
        case DeleteRequest(key) => {
            log.info("received DeleteRequest - key {}", key)
            if (map.contains(key)) {
                map -= key
                sender() ! Status.Success(key)
            } else {
                sender() ! Status.Failure(KeyNotFoundException(key))
            }
        }
        case o => {
            log.info("received unknown message: {}", o);
            sender() ! Status.Failure (new ClassNotFoundException)
        }
    }
} 
开发者ID:miguelsaddress,项目名称:akkademy-db,代码行数:47,代码来源:AkkademyDb.scala


示例8: CSPElementEqual

//设置package包名称以及导入依赖的类
package gregd.cspsolve.constraint

import gregd.cspsolve.log.MyLogger
import gregd.cspsolve.solve.CSPVar
import gregd.cspsolve.solve.CSPConstraint
import gregd.cspsolve.solve.CSPElement
import scala.collection.mutable.HashMap

object CSPElementEqual {
  val logger = new MyLogger("CSPElementEqual") 
}


class CSPElementEqual(varRange : Array[CSPVar], el : CSPElement, count : Int) extends CSPConstraint {
	val vars = new scala.collection.immutable.HashSet[CSPVar]() ++ varRange
  
    def getSatisfaction(varsEls : HashMap[CSPVar, scala.collection.mutable.HashSet[CSPElement]]) : Double = {
	  
	  val elCount = vars.:\((0, 0)){
	    (curVar, curCount) => 
	      val (ofOneCount, multCount) = curCount
	    val domain = varsEls.get(curVar).getOrElse{
	      CSPElementEqual.logger.error("mapping of variables does not contain CSPVar " + curVar)
	      throw new IllegalArgumentException("map does not contain necessary variable")
	    }
	    
	     (domain.contains(el), domain.size == 1) match {
	       case (true, true) => (ofOneCount + 1, multCount + 1)
	       case (true, false) => (ofOneCount, multCount + 1)
	       case _ => curCount
	     }
	  }
	  
	  val (oneElement, multElements) = elCount
	  
      if (oneElement > count || multElements < count) 0.0
      else 1.0
    }

	
    def getEffectedVars() : scala.collection.immutable.HashSet[CSPVar] = vars  
} 
开发者ID:gdicristofaro,项目名称:CSPSolver,代码行数:43,代码来源:CSPElementEqual.scala


示例9: CSPElementMax

//设置package包名称以及导入依赖的类
package gregd.cspsolve.constraint

import gregd.cspsolve.log.MyLogger
import gregd.cspsolve.solve.CSPElement
import gregd.cspsolve.solve.CSPVar
import gregd.cspsolve.solve.CSPConstraint
import scala.collection.mutable.HashMap

object CSPElementMax {
  val logger = new MyLogger("CSPElementMax") 
}


class CSPElementMax(varRange : Array[CSPVar], el : CSPElement, count : Int) extends CSPConstraint {
	val vars = new scala.collection.immutable.HashSet[CSPVar]() ++ varRange
  
    def getSatisfaction(varsEls : HashMap[CSPVar, scala.collection.mutable.HashSet[CSPElement]]) : Double = {
	  
	  val elCount = vars.:\(0){
	    (curVar, curCount) => 
	    val domain = varsEls.get(curVar).getOrElse{
	      CSPElementMax.logger.error("mapping of variables does not contain CSPVar " + curVar)
	      throw new IllegalArgumentException("map does not contain necessary variable")
	    }
	    
	     if (domain.size == 1 && domain.contains(el)) curCount + 1
	     else curCount
	  }
      if (elCount > count) 0.0
      else 1.0
    }

	
    def getEffectedVars() : scala.collection.immutable.HashSet[CSPVar] = vars  
} 
开发者ID:gdicristofaro,项目名称:CSPSolver,代码行数:36,代码来源:CSPElementMax.scala


示例10: CSPPairEither

//设置package包名称以及导入依赖的类
package gregd.cspsolve.constraint

import gregd.cspsolve.log.MyLogger
import gregd.cspsolve.solve.CSPVar
import gregd.cspsolve.solve.CSPConstraint
import scala.collection.mutable.HashMap
import gregd.cspsolve.solve.CSPElement

object CSPPairEither {
	val logger = new MyLogger("CSPPairEither")	
}

class CSPPairEither(var1 : CSPVar, var2 : CSPVar) extends CSPConstraint {
	val vars = scala.collection.immutable.HashSet[CSPVar](var1, var2)
  
    def getSatisfaction(varsEls : HashMap[CSPVar, scala.collection.mutable.HashSet[CSPElement]]) : Double = {
	  val var1Dom = varsEls.get(var1).getOrElse{
		  CSPPairEither.logger.error("mapping of variables does not contain CSPVar 1")
	      throw new IllegalArgumentException("map does not contain necessary variable")}
	      
	  val var2Dom = varsEls.get(var2).getOrElse{
		  CSPPairEither.logger.error("mapping of variables does not contain CSPVar 2")
	      throw new IllegalArgumentException("map does not contain necessary variable")}
	  
	  val toReturn =
	    if (var1Dom.size > 1 || var2Dom.size > 1 || var1Dom != var2Dom) 1.0
	    else 0.0
	  
	  CSPPairEither.logger.debug(
	      "var 1: " + var1 + " domain is " + var1Dom + 
	      "var 2: " + var2 + " domain is " + var2Dom +
	      " resulting score is " + toReturn + " (absolute: " + isAbsolute + ")")
	      
	  toReturn
    }

    def getEffectedVars() : scala.collection.immutable.HashSet[CSPVar] = vars
} 
开发者ID:gdicristofaro,项目名称:CSPSolver,代码行数:39,代码来源:CSPPairEither.scala


示例11: CSPElementMin

//设置package包名称以及导入依赖的类
package gregd.cspsolve.constraint

import gregd.cspsolve.log.MyLogger
import gregd.cspsolve.solve.CSPVar
import gregd.cspsolve.solve.CSPElement
import gregd.cspsolve.solve.CSPConstraint
import scala.collection.mutable.HashMap

object CSPElementMin {
  val logger = new MyLogger("CSPElementMin") 
}


class CSPElementMin(varRange : Array[CSPVar], el : CSPElement, count : Int) extends CSPConstraint {
	val vars = new scala.collection.immutable.HashSet[CSPVar]() ++ varRange
  
    def getSatisfaction(varsEls : HashMap[CSPVar, scala.collection.mutable.HashSet[CSPElement]]) : Double = {
	  
	  val elCount = vars.:\(0){
	    (curVar, curCount) => 
	    val domain = varsEls.get(curVar).getOrElse{
	      CSPElementMin.logger.error("mapping of variables does not contain CSPVar " + curVar)
	      throw new IllegalArgumentException("map does not contain necessary variable")
	    }
	    
	     if (domain.contains(el)) curCount + 1
	     else curCount
	  }
      if (elCount < count) 0.0
      else 1.0
    }

	
    def getEffectedVars() : scala.collection.immutable.HashSet[CSPVar] = vars  
} 
开发者ID:gdicristofaro,项目名称:CSPSolver,代码行数:36,代码来源:CSPElementMin.scala


示例12: CSPDifferentElementInRange

//设置package包名称以及导入依赖的类
package gregd.cspsolve.constraint

import gregd.cspsolve.log.MyLogger
import gregd.cspsolve.solve.CSPConstraint
import gregd.cspsolve.solve.CSPElement
import gregd.cspsolve.solve.CSPVar
import scala.collection.mutable.HashMap

object CSPDifferentElementInRange {
  val logger = new MyLogger("CSPDifferentElementInRange") 
}


class CSPDifferentElementInRange(varRange : List[CSPVar], el : List[CSPElement], count : Int) extends CSPConstraint {
	val vars = new scala.collection.immutable.HashSet[CSPVar]() ++ varRange
	
	val checkEls = new scala.collection.immutable.HashSet[CSPElement]() ++ el
  
	private def overList(allVars : HashMap[CSPVar, scala.collection.mutable.HashSet[CSPElement]], 
	    vars : List[CSPVar], checkEls :scala.collection.immutable.HashSet[CSPElement], els : scala.collection.immutable.HashSet[CSPElement], countLeft : Int) : Double = {
	  vars match {
	    case Nil => 1.0
	    case v :: tl =>
	      val curDomain = allVars.get(v).getOrElse{
		      CSPElementMax.logger.error("mapping of variables does not contain CSPVar " + v)
		      throw new IllegalArgumentException("map does not contain necessary variable")
		    }
	      
	      //CSPDifferentElementInRange.logger.debug("curDomain is " + curDomain + " size is " + curDomain.size + " contained )
	      
	      
	      if (curDomain.size == 1 && checkEls.contains(curDomain.head) && !els.contains(curDomain.head)) {	        
	        if (countLeft <= 0) 0.0
	        else overList(allVars, tl, checkEls, els ++ curDomain, countLeft - 1)
	      }
	      else overList(allVars, tl, checkEls, els, countLeft)
	  }
	}
	
    def getSatisfaction(varsEls : HashMap[CSPVar, scala.collection.mutable.HashSet[CSPElement]]) : Double = {
		overList(varsEls, varRange, checkEls, new scala.collection.immutable.HashSet[CSPElement], count)
    }

	
    def getEffectedVars() : scala.collection.immutable.HashSet[CSPVar] = vars  
} 
开发者ID:gdicristofaro,项目名称:CSPSolver,代码行数:47,代码来源:CSPDifferentElementInRange.scala


示例13: CSPPairBoth

//设置package包名称以及导入依赖的类
package gregd.cspsolve.constraint

import gregd.cspsolve.log.MyLogger
import gregd.cspsolve.model.ModelConstraint
import gregd.cspsolve.constraintarg.VarArg
import gregd.cspsolve.constraintarg.ConstraintArg
import gregd.cspsolve.solve.CSPConstraint
import gregd.cspsolve.solve.CSPVar
import scala.collection.mutable.HashMap
import gregd.cspsolve.solve.CSPElement


object CSPPairBoth {
	val logger = new MyLogger("CSPPairBoth")	
}

class CSPPairBoth(var1 : CSPVar, var2 : CSPVar, els : List[CSPElement]) extends CSPConstraint {
	val vars = scala.collection.immutable.HashSet[CSPVar](var1, var2)
	
	val consideredEls = scala.collection.immutable.HashSet[CSPElement]() ++ els
  
    def getSatisfaction(varsEls : HashMap[CSPVar, scala.collection.mutable.HashSet[CSPElement]]) : Double = {
	  val var1Dom = varsEls.get(var1).getOrElse{
		  CSPPairBoth.logger.error("mapping of variables does not contain CSPVar 1 " + var1)
	      throw new IllegalArgumentException("map does not contain necessary variable")}
	      
	  val var2Dom = varsEls.get(var2).getOrElse{
		  CSPPairBoth.logger.error("mapping of variables does not contain CSPVar 2 " + var2)
	      throw new IllegalArgumentException("map does not contain necessary variable")}
	  
	  //println("getting here...")
	  
	  //if the only elements in a domain are the elements to be considered, then do a check
	  //otherwise it could be fine
	  if ((var1Dom.intersect(consideredEls).size == var1Dom.size)
	      || (var2Dom.intersect(consideredEls).size == var2Dom.size)) {
	    
	      if (var1Dom.intersect(var2Dom).size > 0) 1.0
		  else {
		    //println("dom of " + var1 + " is + " + var1Dom + " and for " + var2 + " is " + var2Dom + " with included dom of " + consideredEls)
		    0.0
		  }
	  }
	  else 1.0 
    }

    def getEffectedVars() : scala.collection.immutable.HashSet[CSPVar] = vars
}






 
开发者ID:gdicristofaro,项目名称:CSPSolver,代码行数:49,代码来源:CSPPairBoth.scala


示例14: AkkademyDb

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

import akka.actor.{Actor, Status}
import akka.event.Logging

import scala.collection.mutable.HashMap



class AkkademyDb extends Actor{
  val map = new HashMap[String, Object]
  val log = Logging(context.system, this)

  override def receive = {
    case SetRequest(key, value) => {
      log.info(s"received SetRequest - key: {$key} value: {$value}")
      map.put(key,value)
    }
    case others => log.info(s"received unknown messages: {$others}")
  }

}

class ScalaPongActor extends Actor{
  override def receive: Receive = {
    case "ping" => sender() ! "pong"
    case _ => sender() ! Status.Failure(new Exception("unknow message"))
  }
} 
开发者ID:hanchenyi,项目名称:FirstAkkaProject,代码行数:30,代码来源:AkkademyDb.scala


示例15: Matrix

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

import scala.collection.mutable.HashMap
import scala.collection._

class Matrix[N <: AnyVal](val rows: Int, val cols: Int) {

  private var entries: HashMap[Tuple2[Int, Int], N] = new HashMap()

  def shape: Tuple2[Int, Int] = (rows, cols)

  def shapeAsString: String = rows + "×" + cols

  
  def apply(i: Int, j: Int) = {
    if (0 <= i && i < rows && 0 <= j && j < cols) {
      if (entries contains (i, j))
        entries(i, j)
      else 0
    }
    throw new IndexOutOfBoundsException("Index " + (i, j) + " is invalid for a " + shapeAsString + " matrix")
  }

  def isSquare: Boolean = (rows == cols)

}

abstract class MatrixIterator[N <: AnyVal](val m: Matrix[N]) extends AbstractIterator[N] {
  private var i: Int = 0
  private var j: Int = 0

  override def hasNext = (i >= m.rows && j >= m.cols)

  override def next = {
    // Moving horizontally
    val res = m(i, j)
    j += 1
    // then vertically
    // I'd love a way to signal the end of a row, but () (type Unit) won't work because it extends AnyRef, not AnyVal.
    if (j >= m.cols) {
      j = 0  // CR
      i += 1 // LF
    }
    res
  }
} 
开发者ID:aidan-fitz,项目名称:math2941,代码行数:47,代码来源:matrix.scala


示例16: AkkademyDB

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

import com.akkademy.messages._
import akka.actor.{Props, ActorSystem, Status, Actor}
import akka.event.Logging
import scala.collection.mutable.HashMap

class AkkademyDB extends Actor
{
  val map = new HashMap[String,Object]
  val log = Logging(context.system, this)
  override def receive() = 
  {
    case SetRequest(key, value) =>
        log.info("Received SetRequest - key: {} value {}", key, value)
        map.put(key, value)
	sender() ! Status.Success
    case GetRequest(key) =>
	log.info("received GetRequest - key: {}", key)
	val response: Option[Object] = map.get(key)
	response match
		{
			case Some(x) => sender() ! x
			case None => sender() ! Status.Failure(new KeyNotFoundException(key))
		}
    case o => Status.Failure(new ClassNotFoundException)
  }
}

object Main extends App {
	val system = ActorSystem("akkademy")
	system.actorOf(Props[AkkademyDB], name = "akkademy-db")
} 
开发者ID:Edmond1983,项目名称:akkademydb-ch2,代码行数:34,代码来源:AkkademyDB.scala


示例17: ScraperController

//设置package包名称以及导入依赖的类
import akka.actor.{Actor, Cancellable, ActorRef, Props}
import UnitsScraper.{Scan, SearchResults}
import scala.collection.mutable.{HashMap, HashSet}
import scala.concurrent.duration._

//TODO: schedule checkup/removal at endtime. Future: bid-bot
class ScraperController extends Actor { //TODO: implement persistence in case of crash
  import ScraperController._ //case classes defined in companion object
  val searchCancelActorMap = new HashMap[SearchTerm, (ActorRef, Cancellable)]
  val oldCategorizedResults = new HashMap[SearchTerm, Set[AuctionObject]]
  val oldObjects = new HashSet[AuctionObject]
  val serverActor = context.actorOf(Props[WebServer], name = "Server")
  val pushbullet = context.actorOf(Props[PushAPI], name = "Pushbullet")
  val system = akka.actor.ActorSystem("system")

  def receive = {
    case SearchResults(result) => {
      val searchTerm = sender.path.name
      val newObjectsInCategory = result -- oldCategorizedResults.getOrElse(SearchTerm(searchTerm), new HashSet[AuctionObject])
      serverActor ! NewCategoryResults(searchTerm, newObjectsInCategory)
      if (Preferences.isPushbulletActive && !Preferences.NeedtoConfigure) {
        for (obj <- newObjectsInCategory) {
          pushbullet ! pushLink(s"""New auction object in search "$searchTerm": ${obj.title}""", obj.link)
        }
      }
      oldCategorizedResults(SearchTerm(searchTerm)) = result
    }
    case NewSearchTerm(s) => {
      val sT = SearchTerm(s)
      //creates an actor in this context, i.e. a child actor
      val actor = context.actorOf(Props[UnitsScraper], name = s)
      //sets the ExecutionContext for the message sending task
      import system.dispatcher
      //sets a schedule to scan the search page every 5 minutes, starting in 200 milliseconds
      val cancel: Cancellable = system.scheduler.schedule(200 milliseconds, 5 minutes, actor, Scan)(sender = context.self, executor = system.dispatcher)
      searchCancelActorMap += (sT -> ((actor, cancel)))
    }
    case DeleteSearchTerm(s) => {
      val sT = SearchTerm(s)
      val actorCancelTuple = searchCancelActorMap(sT)
      actorCancelTuple._2.cancel
      context stop actorCancelTuple._1
      searchCancelActorMap -= sT
    }
    case WebServer.Shutdown => context.system.terminate
  }
}

object ScraperController {
  case class SearchTerm(s: String)
  case class NewSearchTerm(s: String)
  case class DeleteSearchTerm(s: String)
  case class NewCategoryResults(searchTerm: String, objects: Set[AuctionObject])
} 
开发者ID:hnrklssn,项目名称:units-toolbox,代码行数:55,代码来源:ScraperController.scala


示例18: MemoryChatStorage

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

import akka.actor.Actor
import akka.event.Logging
import scala.collection.mutable.HashMap
import scala.collection.mutable.ListBuffer


trait ChatStorage extends Actor

class MemoryChatStorage extends ChatStorage {
  //self.lifeCycle = Permanent

  private var chatLog: ListBuffer[String] = ListBuffer("< Room >")
  val friends: HashMap[String, ListBuffer[String]] = HashMap[String, ListBuffer[String]]()
  private val chatMessageStorage: HashMap[String, HashMap[String, ListBuffer[String]]] = HashMap[String, HashMap[String, ListBuffer[String]]]()

  val log = Logging(context.system, this)
  log.info("Memory-based chat storage is starting up...")

  def receive = {
    case msg @ ChatMessage(from, message) =>
      log.info("New chat message [%s] from sender : %s".format(message, sender()))
      chatLog += message
      if (chatLog.size >= 10) {
        val messageList = chatLog.slice(chatLog.size - 10, chatLog.size)
        sender() ! ChatLog(messageList)
      } else {
        val messageList = chatLog
        sender() ! ChatLog(messageList)
      }

    case msg @ ChatMessageTo(from, to, message) =>
      log.info("New chat message (%s->%s) [%s] from sender : %s".format(from, to, message, sender()))
      val fromUserMap = chatMessageStorage.getOrElseUpdate(from, HashMap[String, ListBuffer[String]]())
      val msgs = fromUserMap.getOrElseUpdate(to, ListBuffer[String]("< " + to + " >")) += message
      //add message to target MessabBox map
      val toUserMap = chatMessageStorage.getOrElseUpdate(to, HashMap[String, ListBuffer[String]]())
      val msgTo = toUserMap.getOrElseUpdate(from, ListBuffer[String]("< " + from + " >")) += message

      sender() ! ChatLog(msgs)

    case msg @ GetChatMessageTo(from, to) =>
      val fromUserMap = chatMessageStorage.getOrElseUpdate(from, HashMap[String, ListBuffer[String]]())
      val msgs = fromUserMap.getOrElseUpdate(to, ListBuffer[String]("< " + to + " >"))
      sender() ! ChatLog(msgs)

    case GetChatLog(_) =>
      val messageList = chatLog
      sender() ! ChatLog(messageList)

    case msg @ AddFriend(user, friend) =>
      log.info("AddFriend message %s->%s from sender : %s".format(user, friend, sender()))
      val friendList = friends.getOrElseUpdate(user, ListBuffer[String]("<Friend List>")) += friend
      sender() ! ChatLog(friendList)

  }

  override def postRestart(reason: Throwable) = chatLog = ListBuffer()
} 
开发者ID:Chehao,项目名称:Akkala,代码行数:61,代码来源:MemoryChatStorage.scala


示例19: ApplicantDataSpec

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

import org.scalatest.FlatSpec
import org.scalatest.MustMatchers._
import scala.collection.mutable.{LinkedHashMap, ListBuffer, HashMap}


 class ApplicantDataSpec extends FlatSpec {
   val input: LinkedHashMap[(String, String),(String, String)] = LinkedHashMap[(String, String),(String, String)]()

   input += (("person" -> "jason frederick") -> ("person" -> "Jason Frederick"))
   input += (("title" -> "web develoer") -> ("title" -> "Web Developer"))
   input += (("organization" -> "american financial group, inc.") -> ("organization" -> "American Financial Group, Inc."))
   input += (("location" -> "thousand oaks, ca") -> ("location" -> "Thousand Oaks, CA"))
   input += (("title" -> "etl developer") ->("title" -> "ETL Developer"))
   input += (("organization" -> "alaska air group, inc.") -> ("organization" -> "Alaska Air Group, Inc."))
   input += (("location" -> "columbus, ga") -> ("location" -> "Columbus, GA"))
   input += (("webapp" -> "javascript") -> ("webapp" -> "JavaScript"))
   input += (("degree" -> "bs biology") -> ("degree" -> "BS Biology"))
   input += (("school" -> "harvard university") -> ("school" -> "Harvard University"))

   val applicant: ApplicantData = ApplicantData(input, "Wow what a good resume name", "This is totally the text that gave us these entities :D")
   val map = applicant.toMap()

   "ApplicantData" must "store the name" in {
     map.get("name").get mustBe ("Jason Frederick")
   }

   "ApplicantData" must "store the first title" in {
     map.get("currentLocation").get.asInstanceOf[HashMap[String, String]].get("title") mustBe (Some("Web Developer"))
   }

   "ApplicantData" must "store the first location" in {
     map.get("currentLocation").get.asInstanceOf[HashMap[String, String]].get("location") mustBe (Some("Thousand Oaks, CA"))
   }

   "ApplicantData" must "store the first organization" in {
     map.get("currentLocation").get.asInstanceOf[HashMap[String, String]].get("organization") mustBe (Some("American Financial Group, Inc."))
   }

   "ApplicantData" must "store the first degree" in {
     map.get("education").get.asInstanceOf[HashMap[String, String]].get("degree") mustBe (Some("BS Biology"))
   }

   "ApplicantData" must "store the first school" in {
     map.get("education").get.asInstanceOf[HashMap[String, String]].get("school") mustBe (Some("Harvard University"))
   }

   "ApplicantData" must "add JavaScript to the webapp list" in {
     map.get("skills").get.asInstanceOf[HashMap[String, ListBuffer[String]]].get("webapp").get.contains("JavaScript") mustBe (true)
   }

   "ApplicantData" must "store the resume text" in {
     map.get("additionalInfo").get.asInstanceOf[HashMap[String, String]].get("resume") mustBe (Some("This is totally the text that gave us these entities :D"))
   }
} 
开发者ID:dataworks,项目名称:internship-2016,代码行数:57,代码来源:ApplicantDataSpec.scala


示例20: KeywordFeature

//设置package包名称以及导入依赖的类
package applicant.ml.regression.features

import applicant.etl.ApplicantData
import applicant.nlp.LuceneTokenizer
import applicant.ml.regression.FeatureSetting
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.HashMap

class KeywordFeature(newSetting: FeatureSetting) extends BaseFeature {
  val setting = newSetting

  
  def getFeatureScore(applicant: ApplicantData): Double = {
    val keywordList: ListBuffer[String] = newSetting.values.asInstanceOf[ListBuffer[String]]

    val tokenizer = new LuceneTokenizer()
    val resumeArray = tokenizer.tokenize(applicant.fullText) //Converts to lowercase
    var matches : Double = 0.0

    val map = HashMap.empty[String, Int]

    for (item <- keywordList) {
      map += (item.toLowerCase -> 0)
    }

    resumeArray.foreach { word =>
      if (map.contains(word)){
        val currentWordCount = map(word)
        map += (word -> (currentWordCount + 1))
      }
    }

    map.foreach{ case (k,v) =>
      if (v >= 2){
        if (v > 5) {
          matches += 5.0
        }
        else {
          matches += v.toDouble
        }
      }
    }

    val rawScore = matches/(map.size*4.0)

    return if (rawScore > 1.0) 1.0 else rawScore
  }
} 
开发者ID:dataworks,项目名称:internship-2016,代码行数:49,代码来源:KeywordFeature.scala



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala Specification类代码示例发布时间:2022-05-23
下一篇:
Scala LocalDateTime类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap