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

Scala Map类代码示例

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

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



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

示例1: ConcordanceParser

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

import scala.util.parsing.combinator._
import scala.util.parsing.input.Positional
import scala.io.Source
import scala.collection.immutable.Map


class ConcordanceParser extends RegexParsers {
  val rWord = """[\w’]+[,;\.\-\?\!\—]?""".r
  def word: Parser[PositionalString] = positioned(regex(rWord) ^^ {w => PositionalString(w)})
  def sentence: Parser[Seq[PositionalString]] = rep(word)
}

case class PositionalString(s: String) extends Positional

object ConcordanceParser {
 
  def main(args: Array[String]): Unit = {
    val docs = for (f <- args) yield Source.fromFile(f).mkString
    val concordance = for (i <- 0 to docs.length-1) yield (args(i),parseDoc(docs(i)))
    println(concordance)
    // an alternative way of looking at the data (gives doc, page, line and char numbers with each string)
    val q = for {(d,xxxx) <- concordance; (p,xxx) <- xxxx; (l,xx) <- xxx; (_,c,x) <- xx} yield (d, p,l,c,x)
    println(q)
    // yet another way to look at the data
    val concordanceMap = concordance.toMap
    println(concordanceMap)
  }
  
  def parseDoc(content: String) = {
    val pages = for (p <- content.split("/p")) yield p
    for (i <- 0 to pages.length-1) yield (i+1,parsePage(pages(i)))
  }

  def parsePage(content: String) = {
    val lines = for (l <- content.split("\n")) yield l
    for (i <- 0 to lines.length-1) yield (i+1,parseLine(lines(i)))
  }

  def parseLine(line: String): Seq[(Int,Int,String)] = {
    def tidy(s: String) = s.replaceAll("""[,;\.\-\?\!\—]""", "")
    val p = new ConcordanceParser
    val r = p.parseAll(p.sentence,line) match {
      case p.Success(ws,_) => ws
      case p.Failure(e,_) => println(e); List()
      case _ => println("PositionalParser: logic error"); List()
    }
    r map {case p @ PositionalString(s) => (p.pos.line,p.pos.column,tidy(s).toLowerCase)}
  }
} 
开发者ID:menezesl,项目名称:Scala-repo,代码行数:52,代码来源:ConcordanceParser.scala


示例2: Players

//设置package包名称以及导入依赖的类
package de.htwg.se.SevenSteps.model.player.mockImpl

import de.htwg.se.SevenSteps.model.player.{IPlayer, IPlayers}

import scala.collection.immutable.Map
import scala.util.{Success, Try}
import scala.xml.Elem

case class Players() extends IPlayers {
  def push(name: String): IPlayers = this
  def pop(): IPlayers = this
  def length: Int = 1
  def updateCurPlayer(player: IPlayer): IPlayers = this
  def next(): IPlayers = this
  def nonEmpty: Boolean = true
  def getCurPlayer: IPlayer = Player()
  def setColors(colors: List[Char]): IPlayers = this
  def setAllStonesTo(num: Int): IPlayers = this
  def apply(i: Int): IPlayer = Player()
  def haveNoStones: Boolean = false
  def getAllPossibleColorsFromAllPlayers: List[Char] = List()
  def reset: IPlayers = this
  def toXML: Vector[Elem] = Vector(<el el=""></el>)

}

case class Player() extends IPlayer {
  def getStoneNumber: Int = 2
  def placeStone(color: Char, height: Int): Try[IPlayer] = Success(this)
  def incPoints(delta: Int): IPlayer = this
  def incColor(color: Char, delta: Int): IPlayer = this
  def name: String = "Hans"
  def points: Int = 10
  def map: Option[Map[String, Double]] = None
  def haveNoStones: Boolean = true
  def toXML: Elem = <el el=""></el>

} 
开发者ID:GrimmT,项目名称:de.htwg.se.SevenSteps,代码行数:39,代码来源:PlayerMock.scala


示例3: reset

//设置package包名称以及导入依赖的类
package de.htwg.se.SevenSteps.model.player

import scala.collection.immutable.Map
import scala.util.Try

trait IPlayers {
  def reset: IPlayers
  def push(name: String): IPlayers
  def pop(): IPlayers
  def length: Int
  def updateCurPlayer(player: IPlayer): IPlayers
  def next(): IPlayers
  def nonEmpty: Boolean
  def getCurPlayer: IPlayer
  def setColors(colors: List[Char]): IPlayers
  def setAllStonesTo(num: Int): IPlayers
  def apply(i: Int): IPlayer
  def haveNoStones: Boolean
  def getAllPossibleColorsFromAllPlayers: List[Char]
  def toXML(): Vector[scala.xml.Elem]
}

trait IPlayer {
  def getStoneNumber: Int
  def placeStone(color: Char, height: Int): Try[IPlayer]
  def incPoints(delta: Int): IPlayer
  def incColor(color: Char, delta: Int): IPlayer
  def name: String
  def points: Int
  def map: Option[Map[String, Double]]
  def haveNoStones: Boolean
  def toXML(): scala.xml.Elem
} 
开发者ID:GrimmT,项目名称:de.htwg.se.SevenSteps,代码行数:34,代码来源:IPlayers.scala


示例4: Args

//设置package包名称以及导入依赖的类
//$ scala -classpath ~/.m2/repository/org/jboss/jbossset/bugclerk/0.5.2.Final/bugclerk-0.5.2.Final.jar

import scala.collection.JavaConversions._
import scala.collection.immutable.Map
import java.util._

import org.jboss.set.aphrodite.Aphrodite
import org.jboss.set.aphrodite.config._
import org.jboss.set.aphrodite.domain._

import com.beust.jcommander.JCommander
import com.beust.jcommander.Parameter
import com.beust.jcommander.ParameterException

object Args {

    @Parameter(names = Array( "-i", "--bug-id" ), variableArity = true, description = "bug id", required = true)
    var bugId : List[String] = new java.util.ArrayList[String](0)
}

new JCommander(Args, args.toArray: _*)

def printIssueIfDevAckMissing(issue: Issue) = println(formatIssue(issue))
def formatIssue(issue: Issue) = issue.getTrackerId.get + " (" + aggregateAllThreeFlags(issue.getStage()) + "): " + issue.getSummary.get + "[" + issue.getType() + "]"
def aggregateAllThreeFlags(stage: Stage):String = (for ( f <- stage.getStateMap.keySet() ) yield(f.toString + stage.getStatus(f).getSymbol + ",")).mkString.dropRight(1)

def onlyReleasesFrom(issue: Issue) = {
  if ( issue.getReleases().isEmpty )
    "No Target Release"
  else
    (for (release <- issue.getReleases()) yield(release.getVersion.get())).mkString(",")
}

val aphrodite = Aphrodite.instance()

def getUrls(listAsString : java.util.List[String]) = {
  val coll : java.util.Collection[java.net.URL] = new java.util.ArrayList[java.net.URL](listAsString.length)
  import collection.JavaConverters._
  for ( item <- listAsString.asScala)
    coll.add(new java.net.URL(item))
  coll
}

def printLine(issue: Issue) = {
  val url = issue.getURL
  val status = issue.getStatus
  val releases = onlyReleasesFrom(issue)
  val stream = issue.getStreamStatus.keySet.iterator.next
  val summary = issue.getSummary.get

  println(f"$url%-43s $status%-8s $stream - $summary%-20s")
}

val issues = aphrodite.getIssues( getUrls(Args.bugId) )
import collection.JavaConverters._
for ( issue <- issues.asScala ) printLine(issue)
aphrodite.close() 
开发者ID:rpelisse,项目名称:in-bed-with-aphrodite,代码行数:58,代码来源:issue-status.scala


示例5: ACLMessage

//设置package包名称以及导入依赖的类
package br.unb.cic.sma.sade.fipa

import scala.collection.immutable.Map
import akka.actor.ActorRef

class ACLMessage(parameters: Map[ACLMessageParameter.ACLMessageParameter, Any]){
  def frame = "fipa-acl-message"
  def ontology = "fipa-acl"
  def sender = parameters.get(ACLMessageParameter.SENDER).orNull.asInstanceOf[ActorRef]
  def receiver = parameters.get(ACLMessageParameter.RECEIVER).orNull.asInstanceOf[ActorRef]
  def reply_to = if(parameters.contains(ACLMessageParameter.REPLY_TO)){ 
              parameters.get(ACLMessageParameter.REPLY_TO).orNull.asInstanceOf[ActorRef]
            } else { parameters.get(ACLMessageParameter.SENDER).orNull.asInstanceOf[ActorRef] }
  def content = parameters.get(ACLMessageParameter.CONTENT).orNull
  def performative = parameters.get(ACLMessageParameter.PERFORMATIVE).orNull.asInstanceOf[Performative.Performative]
  def getParameters = parameters
  
  def reply(performative: Performative.Performative, contentTo: Any): ACLMessage = {
    val par = (parameters - ACLMessageParameter.PERFORMATIVE - 
                 ACLMessageParameter.CONTENT - ACLMessageParameter.SENDER - 
                 ACLMessageParameter.RECEIVER - ACLMessageParameter.REPLY_TO) + 
                 (ACLMessageParameter.SENDER -> parameters.get(ACLMessageParameter.RECEIVER).get) +
                 (ACLMessageParameter.REPLY_TO -> parameters.get(ACLMessageParameter.RECEIVER).get) +
                 (ACLMessageParameter.RECEIVER -> reply_to) +
                 (ACLMessageParameter.PERFORMATIVE -> performative) +
                 (ACLMessageParameter.CONTENT -> contentTo)
    new ACLMessage(par)
  }
} 
开发者ID:brenoxp,项目名称:SADE,代码行数:30,代码来源:ACLMessage.scala


示例6: MesosContainer

//设置package包名称以及导入依赖的类
package mesosphere.marathon
package core.pod

import mesosphere.marathon.plugin.ContainerSpec
import mesosphere.marathon.raml.{ Artifact, Endpoint, Image, Lifecycle, MesosExec, Resources, VolumeMount }

import scala.collection.immutable.Map

case class MesosContainer(
  name: String,
  exec: Option[MesosExec] = None,
  resources: Resources,
  endpoints: scala.collection.immutable.Seq[Endpoint] = Nil,
  image: Option[Image] = None,
  env: Map[String, state.EnvVarValue] = Map.empty,
  user: Option[String] = None,
  healthCheck: Option[core.health.MesosHealthCheck] = None,
  volumeMounts: Seq[VolumeMount] = Nil,
  artifacts: Seq[Artifact] = Nil, //TODO(PODS): use FetchUri
  labels: Map[String, String] = Map.empty,
  lifecycle: Option[Lifecycle] = None) extends ContainerSpec 
开发者ID:xiaozai512,项目名称:marathon,代码行数:22,代码来源:MesosContainer.scala


示例7: EnvVarConversion

//设置package包名称以及导入依赖的类
package mesosphere.marathon.raml

import mesosphere.marathon.state

import scala.collection.immutable.Map

trait EnvVarConversion {
  implicit val envVarRamlWrites: Writes[Map[String, state.EnvVarValue], Map[String, EnvVarValueOrSecret]] =
    Writes {
      _.mapValues {
        case (state.EnvVarString(v)) => EnvVarValue(v)
        case (state.EnvVarSecretRef(v)) => EnvVarSecretRef(v)
      }
    }

  implicit val envVarReads: Reads[Map[String, EnvVarValueOrSecret], Map[String, state.EnvVarValue]] =
    Reads {
      _.mapValues {
        case EnvVarValue(v) => state.EnvVarString(v)
        case EnvVarSecretRef(v) => state.EnvVarSecretRef(v)
      }
    }
}

object EnvVarConversion extends EnvVarConversion 
开发者ID:xiaozai512,项目名称:marathon,代码行数:26,代码来源:EnvVarConversion.scala


示例8: ConcordanceParser

//设置package包名称以及导入依赖的类
package edu.neu.coe.scala.parse

import scala.util.parsing.combinator._
import scala.io.Source
import scala.collection.immutable.Map


class ConcordanceParser extends RegexParsers {
  val rWord = """[\w’]+[,;\.\-\?\!\—]?""".r
  def word: Parser[(Int,String)] = new PositionalParser(regex(rWord) ^^ { case w => w })
  def sentence: Parser[Seq[(Int,String)]] = rep(word) ^^ { case s: Seq[(Int,String)] => s }
    
  class PositionalParser(p: Parser[String]) extends Parser[(Int,String)] {
    def apply(in: Input): ParseResult[(Int,String)] =
      p.apply(in) match {
        case Success(w,pos) => Success((pos.offset-w.length+1,w),pos)
        case f @ Failure(_,_) => f
        case _ => Failure("PositionalParser: logic error",in)
      }
    }  
}

object ConcordanceParser {
 
  def main(args: Array[String]): Unit = {
    val docs = for (f <- args) yield Source.fromFile(f).mkString
    val concordance = for (i <- 0 to docs.length-1) yield (args(i),parseDoc(docs(i)))
    println(concordance)
    // an alternative way of looking at the data (gives doc, page, line and char numbers with each string)
    val q = for {(d,xxxx) <- concordance; (p,xxx) <- xxxx; (l,xx) <- xxx; (c,x) <- xx} yield (d, p,l,c,x)
    println(q)
    // yet another way to look at the data
    val concordanceMap = concordance.toMap
    println(concordanceMap)
  }
  
  def parseDoc(content: String) = {
    val pages = for (p <- content.split("/p")) yield p
    for (i <- 0 to pages.length-1) yield (i+1,parsePage(pages(i)))
  }

  def parsePage(content: String) = {
    val lines = for (l <- content.split("\n")) yield l
    for (i <- 0 to lines.length-1) yield (i+1,parseLine(lines(i)))
  }

  def parseLine(line: String): Seq[(Int,String)] = {
    def tidy(s: String) = s.replaceAll("""[.,;-?!]""", "")
    val p = new ConcordanceParser
    val r = p.parseAll(p.sentence,line) match {
      case p.Success(ws,_) => ws
      case p.Failure(e,_) => println(e); List()
      case _ => println("PositionalParser: logic error"); List()
    }
    r map {case (i,s) => (i,tidy(s).toLowerCase)}
  }
} 
开发者ID:menezesl,项目名称:Scala-repo,代码行数:58,代码来源:ConcordanceParser.scala


示例9: ArrayUtils1

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

import Array._
import scala.util.control.Breaks._
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.HashMap
import scala.collection.immutable.Map
import scala.collection.mutable.Map


object ArrayUtils1 {
  
  
  def main(args: Array[String]) {
      var array = new  Array[Int](5)//?????[Int] ????
      var array1 = Array(1,2,3,4,5)//????????
      var array2 = Array.apply(1,2,3,4,5)//???????
      for(item<- array) println(item)  //????
      
      var ab =  ArrayBuffer[Int]();
      ab += 1
      ab += (2,3,4,5)//????5???,????1?2?3?4?5
      println(ab.length)
    
      ab ++= Array(1,2,3)
      ab.insert(3, 100,200)//???3 ?? 100 200
      ab.remove(4)  //????4
      
      ab.toArray
      
      var newArray = for(item<- array1) yield item+1 // yield  ???????????????????
      for(item<- newArray) println(item)//2,3,4,5,6
      
      println(newArray.filter { x => x%2==0}.mkString(" "))  //2?4?6
      println(newArray.filter { x => x%2==0}.map { x => x*100 }.mkString(" "))// 200 400 600
      println(newArray.filter { _%2==0}.map { _*100 }.mkString(" "))//?????????????
      
      var map1 = new HashMap
      //var map2 = Map
  }
  
} 
开发者ID:jacktomcat,项目名称:scala-practice,代码行数:43,代码来源:ArrayUtils1.scala


示例10: Interpreter

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

import ir.ast._
import scala.collection.immutable.Map

object Interpreter {

  type ValueMap = scala.collection.immutable.Map[Param, Any]

  def apply(f: Lambda) = new {

    private def argsArrayToVector(argsWithArrays: Seq[Any]): Seq[Any] =
      argsWithArrays.map(arrayToVector)

    private def arrayToVector(arg: Any): Any = {
      arg match {
        case a: Array[_] => a.map(arrayToVector).toVector : Vector[_]
        case a: Any => a
      }
    }

    def ->[R] = new {
      def run(args: Any*): R = {
        val res = f.eval(Map[Param, Any](), argsArrayToVector(args): _*).asInstanceOf[R]
        res
      }

      def runAndFlatten(args: Any*)(implicit can: CanFlatten[R]): Seq[can.Elem] = {
        can.flatten(run(args:_*))
      }
    }
  }

  sealed trait InnerMost {
    implicit def innerSeq[A]: CanFlatten[Vector[A]] { type Elem = A } =
      new CanFlatten[Vector[A]] {
        type Elem = A
        def flatten(v: Vector[A]): Vector[A] = v
      }
  }
  object CanFlatten extends InnerMost {
    implicit def nestedI[A](implicit inner: CanFlatten[A])
    : CanFlatten[Vector[A]] { type Elem = inner.Elem } =
      new CanFlatten[Vector[A]] {
        type Elem = inner.Elem
        def flatten(v: Vector[A]) : Vector[inner.Elem] = v.flatMap(vi => inner.flatten(vi))
      }
  }
  sealed trait CanFlatten[-A] {
    type Elem
    def flatten(v: A): Vector[Elem]
  }

} 
开发者ID:lift-project,项目名称:lift,代码行数:55,代码来源:Interpreter.scala


示例11: TweetService

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

import dto.SimilarTweetsResult
import model.Tweet
import play.api.Logger
import repository.TweetRepository

import scala.concurrent.ExecutionContext.Implicits.global
import scala.collection.immutable.Map
import scala.concurrent.Future


object TweetService {
  type SimilarTweets = Map[Int, Set[Tweet]]

  def searchSimilarTweets(id: Long, count: Int): Option[SimilarTweetsResult] = {
    TweetRepository.getTweet(id).map(tweet => searchSimilarTweets(tweet, count))
  }

  def searchSimilarTweets(tweet: Tweet, count: Int): SimilarTweetsResult = {
    val indexSize = TweetIndexedStorage.getSize
    Logger.info(s"Searching tweets in Index ( keys - ${indexSize._1}, values - ${indexSize._2} ) similar to $tweet")

    SimilarTweetsResult(tweet, TweetIndexedStorage.getSimilarInIndex(tweet))
  }

  def searchSimilarTweets(tweet: Tweet): SimilarTweetsResult = searchSimilarTweets(tweet, -1)

  def createTweets(tweets: Set[Tweet]): Future[Set[Tweet]] = {
    val result = for {
      created <- Future { TweetRepository.createCollection(tweets) }
      indexed <- Future { TweetIndexedStorage.addTweets(tweets) }
    } yield created

    result map {
      case createdTweets: Set[Tweet] => createdTweets
      case _ => Set.empty
    }
  }

  def indexTweet(token: String, tweet: Tweet) = TweetIndexedStorage.addTweet(token, tweet)

  def reindexAll() = TweetIndexedStorage.addTweets(TweetRepository.getAll)
} 
开发者ID:mumukiller,项目名称:scala-course-two,代码行数:45,代码来源:TweetService.scala


示例12: SearchAlgorithmTest

//设置package包名称以及导入依赖的类
import model.Tweet
import org.scalatest.{BeforeAndAfterEach, FlatSpec, Matchers}
import service.{TweetIndexedStorage, TweetService}

import scala.collection.immutable.Map


class SearchAlgorithmTest extends FlatSpec with Matchers with BeforeAndAfterEach {


  override protected def beforeEach(): Unit = {
    TweetIndexedStorage.clear()
  }

  "A TweetService" should "find empty map for empty index" in {
    val result = TweetService.searchSimilarTweets(Tweet(1, "aa", "author", "link"))
    assert(result.tweets equals Map.empty[Int, Iterable[Tweet]])
  }

  "A TweetService" should "find tweet itself for index which contains this tweet" in {
    val tweet = Tweet(1, "aa", "author", "link")
    TweetIndexedStorage.addTweets(Set(tweet))

    val result = TweetService.searchSimilarTweets(tweet)
    assert(result.tweets.keys.size equals 1)
    assert(result.tweets.contains(1))
    result.tweets.get(1).foreach(v => assert(v.contains(tweet)))
  }

  "A TweetService" should "find both tweets with distance 1" in {
    val tweetOne = Tweet(2, "aa bb", "author", "link")
    val tweetTwo = Tweet(3, "aa", "author", "link")
    TweetIndexedStorage.addTweets(Set(tweetOne, tweetTwo))

    val result = TweetService.searchSimilarTweets(Tweet(1, "aa", "author", "link"))
    assert(result.tweets.keys.size equals 1)
    assert(result.tweets.contains(1))
    result.tweets.get(1).foreach(v => assert(v.contains(tweetOne) && v.contains(tweetTwo)))
  }

  "A TweetService" should "find tweets with distance 1 and both tweets 2" in {
    val tweetInDistanceOne = Tweet(2, "aa", "author", "link")
    val tweetInDistanceTwo = Tweet(3, "aa bb", "author", "link")
    val anotherTweetInDistanceTwo = Tweet(3, "~~ AA BB CC", "author", "link")
    TweetIndexedStorage.addTweets(Set(tweetInDistanceOne, tweetInDistanceTwo, anotherTweetInDistanceTwo))

    val result = TweetService.searchSimilarTweets(Tweet(1, "aa bb", "author", "link"))
    assert(result.tweets.keys.size equals 2)
    assert(result.tweets.contains(1))
    assert(result.tweets.contains(2))
    result.tweets.get(1).foreach(v => assert(v.contains(tweetInDistanceOne)))
    result.tweets.get(2).foreach(v => assert(v.contains(tweetInDistanceTwo) && v.contains(anotherTweetInDistanceTwo)))
  }
} 
开发者ID:mumukiller,项目名称:scala-course-two,代码行数:55,代码来源:SearchAlgorithmTest.scala


示例13: FlightsPopover

//设置package包名称以及导入依赖的类
package drt.client.components

import diode.data.Pot
import diode.react.ReactConnectProxy
import japgolly.scalajs.react.vdom.html_<^._
import japgolly.scalajs.react._
import drt.client.modules.{FlightsView, PopoverWrapper}
import drt.shared.AirportInfo
import drt.shared.FlightsApi.{Flights, FlightsWithSplits}
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.html_<^._
import japgolly.scalajs.react.vdom.TagOf

import scala.collection.immutable.Map
import scala.scalajs.js

object FlightsPopover {

  case class FlightsPopoverState(hovered: Boolean = false)

  def apply(trigger: String,
            matchingFlights: Pot[FlightsWithSplits],
            airportInfos: ReactConnectProxy[Map[String, Pot[AirportInfo]]]) = ScalaComponent.builder[Unit]("HoverPopover")
    .initialStateFromProps((p) =>
      FlightsPopoverState()
    ).renderS((scope, state) => {
    val popover = <.div(
      ^.onMouseEnter ==> ((e: ReactEvent) => scope.modState(s => s.copy(hovered = true))),
      ^.onMouseLeave ==> ((e: ReactEvent) => scope.modState(_.copy(hovered = false))),
      showIfHovered(trigger, matchingFlights, airportInfos, state))
    popover
  }).build

  private def showIfHovered(trigger: String, matchingFlights: Pot[FlightsWithSplits],
                            airportInfos: ReactConnectProxy[Map[String, Pot[AirportInfo]]],
                            state: FlightsPopoverState) = {

    val popoverWrapper = airportInfos(airportInfo =>
      if (state.hovered) {
        val flightsTable = FlightsTable(FlightsView.Props(matchingFlights, airportInfo.value))
        <.span(PopoverWrapper.component(PopoverWrapper.props(trigger))(flightsTable))
      } else {
        <.span(trigger)
      }
    )
    <.div(popoverWrapper)
    //    trigger
  }
} 
开发者ID:UKHomeOffice,项目名称:drt-scalajs-spa-exploration,代码行数:50,代码来源:FlightsPopover.scala


示例14: UserDeskRecFixtures

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

import diode.data.Ready
import drt.client.services.{DeskRecTimeSlots, DeskRecTimeslot}
import drt.shared.FlightsApi.QueueName

import scala.collection.immutable.Map

object UserDeskRecFixtures {
  def makeUserDeskRecs(queueName: QueueName, userDesks: Int): Map[QueueName, Ready[DeskRecTimeSlots]] = {
    makeUserDeskRecs(queueName, oneHourOfDeskRecs(userDesks))
  }

  def makeUserDeskRecs(queueName: QueueName, recs: List[Int]): Map[QueueName, Ready[DeskRecTimeSlots]] = {
    val userDeskRecs = Map(
      queueName ->
        Ready(DeskRecTimeSlots(
          Stream.from(0, 60000 * 15).zip(recs).map {
            case (millisSinceEpoch, dr) =>
              DeskRecTimeslot(millisSinceEpoch, dr)
          }.toVector)
        ))
    userDeskRecs
  }

  def oneHourOfDeskRecs(userDesksNonEea: Int): List[Int] = {
    //desk recs are currently in 15 minute blocks
    List.fill(4)(userDesksNonEea)
  }
} 
开发者ID:UKHomeOffice,项目名称:drt-scalajs-spa-exploration,代码行数:31,代码来源:UserDeskRecFixtures.scala


示例15: WorkloadsTests

//设置package包名称以及导入依赖的类
package drt.client.services

import drt.shared.FlightsApi._
import drt.shared._
import utest._

import scala.collection.immutable.{IndexedSeq, Map}
import scala.scalajs.js.Date

object WorkloadsTests extends TestSuite {

  def tests = TestSuite {

    "Given workloads, " - {
      "we need a label per minute, starting at midnight of today" - {
        val firstTime = Date.parse("2016-11-01T07:20Z").toLong
        val workloads = Workloads(
          Map("T1" ->
            Map("eeaDesk" ->
              (List(WL(firstTime, 99)), List(Pax(firstTime, 10))))))
        val labels: IndexedSeq[TerminalName] = workloads.labels.take(5)
        assert(labels  == List(
          "00:00",
          "00:01",
          "00:02",
          "00:03",
          "00:04"
        ))
      }
      "it doesn't matter what terminal we have in workloads we need a label per minute" - {
        val firstTime = Date.parse("2016-11-01T07:20Z").toLong
        val workloads = Workloads(
          Map("A1" ->
            Map("eeaDesk" ->
              (List(WL(firstTime, 99)), List(Pax(firstTime, 10))))))
        val labels: IndexedSeq[TerminalName] = workloads.labels.take(5)
        assert(labels  == List(
          "00:00",
          "00:01",
          "00:02",
          "00:03",
          "00:04"
        ))
      }
      "the labels are in 24H format" - {
        val firstTime = Date.parse("2016-11-01T14:20Z").toLong
        val workloads = Workloads(
          Map("A1" ->
            Map("eeaDesk" ->
              (List(WL(firstTime, 99)), List(Pax(firstTime, 10))))))
        val labels: IndexedSeq[TerminalName] = workloads.labels.drop(800).take(5)
        assert(labels  == List(
          "13:20", "13:21", "13:22", "13:23", "13:24"
        ))
      }
    }
  }
} 
开发者ID:UKHomeOffice,项目名称:drt-scalajs-spa-exploration,代码行数:59,代码来源:WorkloadsTests.scala


示例16: ThriftResponsesProtocol

//设置package包名称以及导入依赖的类
package io.livingston.ditto.thrift

import java.util.Base64

import io.livingston.ditto.{Latency, Responses}
import net.jcazevedo.moultingyaml._

import scala.collection.immutable.Map

object ThriftResponsesProtocol extends DefaultYamlProtocol {
  implicit val thriftLatencyFormat = yamlFormat2(Latency)
  implicit object ThriftEndpointYamlFormat extends YamlFormat[ThriftEndpoint] {
    def write(e: ThriftEndpoint): YamlValue = {
      def encode(bytes: Array[Byte]): String = Base64.getEncoder.encodeToString(bytes)
      YamlObject(
        Map[YamlValue, YamlValue](
          YamlString("msg") -> YamlString(e.msg),
          YamlString("body") -> YamlString(encode(e.body.toArray)),
          YamlString("latency") -> thriftLatencyFormat.write(e.latency)
        )
      )
    }

    def read(value: YamlValue): ThriftEndpoint = {
      def decode(str: String): Array[Byte] = Base64.getDecoder.decode(str)
      value match {
        case YamlObject(map) =>
          val msg = map(YamlString("msg")) match {
            case YamlString(msg) => msg
            case _ => deserializationError("msg key expected to be a string")
          }
          val body = map(YamlString("body")) match {
            case YamlString(body) => decode(body).toList
            case _ => deserializationError("body key expected to be a string")
          }
          val latency = thriftLatencyFormat.read(map(YamlString("latency")))
          ThriftEndpoint(msg, body, latency)

        case _ => deserializationError("ThriftEndpoint expected")
      }
    }
  }
  implicit val thriftServerConfigFormat = yamlFormat2(ThriftServerConfig)
  implicit val thriftResponseFormat = yamlFormat1(ThriftResponses)
}

case class ThriftResponses(thrift: List[ThriftServerConfig]) extends Responses
case class ThriftServerConfig(port: Int, endpoints: List[ThriftEndpoint])
case class ThriftEndpoint(msg: String, body: List[Byte], latency: Latency) 
开发者ID:scottlivingston,项目名称:ditto,代码行数:50,代码来源:ThriftResponses.scala


示例17: HubEffectItem

//设置package包名称以及导入依赖的类
package net.thereturningvoid.hubeffect

import org.bukkit.{Bukkit, ChatColor, Material, World}
import org.bukkit.inventory.ItemStack
import org.bukkit.potion.PotionEffectType
import net.thereturningvoid.hubeffect.Predefs._
import org.bukkit.configuration.file.FileConfiguration

import scala.collection.immutable.Map
import collection.JavaConversions._


case class HubEffectItem(name: String, offItem: ItemStack, onItem: ItemStack, effects: List[(PotionEffectType, Int)],
                         invincibility: Boolean, doubleJump: Boolean, enableMsg: String, disableMsg: String,
                         world: String)

object HubEffectItem {
  def getItemsFromConfigValues(config: FileConfiguration): List[HubEffectItem] = {
    val items: Map[String, AnyRef] = config.getConfigurationSection("items").getValues(false).toMap
    items map { case (k, v) =>
      val key: String = s"items.$k"
      val offMaterial: Material = Material.matchMaterial(config.getString(s"$key.offItem.type"))
      val offName: String = ChatColor.translateAlternateColorCodes('&', config.getString(s"$key.offItem.name"))
      val off: ItemStack = new ItemStack(offMaterial) tap {i =>
        i.setItemMeta(i.getItemMeta tap {m =>
          m.setDisplayName(offName)
        })
      }

      val onMaterial: Material = Material.matchMaterial(config.getString(s"$key.onItem.type"))
      val onName: String = ChatColor.translateAlternateColorCodes('&', config.getString(s"$key.onItem.name"))
      val on: ItemStack = new ItemStack(onMaterial) tap {i =>
        i.setItemMeta(i.getItemMeta tap {m =>
          m.setDisplayName(onName)
        })
      }

      val effects: List[(PotionEffectType, Int)] = config.getStringList(s"$key.effects") map {e =>
        val split: Array[String] = e.split('|')
        (PotionEffectType.getByName(split(0).toUpperCase), split(1).toInt)
      } toList

      val itemWorld: Option[String] = Bukkit.getWorlds.collectFirst{ case w if w.getName == config.getString(s"$key.world") => w.getName }

      new HubEffectItem(k, off, on, effects, config.getBoolean(s"$key.invincible", false), config.getBoolean(s"$key.doublejump", false),
        ChatColor.translateAlternateColorCodes('&', config.getString(s"$key.enablemsg")),
        ChatColor.translateAlternateColorCodes('&', config.getString(s"$key.disablemsg")), itemWorld.getOrElse(""))
    } toList
  }
} 
开发者ID:TheReturningVoid,项目名称:hubeffect,代码行数:51,代码来源:HubEffectItem.scala


示例18:

//设置package包名称以及导入依赖的类
package geotrellis.osme.core

import java.io.{BufferedWriter, FileWriter, File}

import com.vividsolutions.jts.geom.{LineString, MultiLineString}
import geotrellis.raster.io.geotiff.SinglebandGeoTiff
import geotrellis.vector.io.json.{GeoJson, JsonFeatureCollection}
import scala.collection.immutable.Map
import spray.json._
import DefaultJsonProtocol._
import geotrellis.vector.io.json.FeatureFormats.writeFeatureJson
import geotrellis.vector.io.json.GeometryFormats._
import geotrellis.vector.densify.DensifyMethods
import geotrellis.vector.dissolve.DissolveMethods
import geotrellis.vector._



    val segmentsFeatures = segments.map { segment =>
       val center = segment.centroid match {
         case PointResult(p) => p
         case NoResult => throw new Exception("No result found in PointOrNoResult")
       }
       val (col, row) = rasterExtent.mapToGrid(center)
       val elevation = geotiff.tile.getDouble(col, row)
       val meanvMap: Map[String, Double] = Map("MEANV" -> elevation)
       LineFeature(segment, meanvMap)
     }

    return segmentsFeatures.toTraversable


  }
} 
开发者ID:geotrellis,项目名称:geotrellis-osm-elevation,代码行数:35,代码来源:ElevationOverlay.scala


示例19: toPaddedKeySortedDenseVector

//设置package包名称以及导入依赖的类
package fordm.math.breezeextra

import breeze.linalg.DenseVector
import cats.data.NonEmptyList
import fordm.catsextra.RichNonEmptyList._
import fordm.math.DoubleValue

import scala.collection.immutable.{Map, SortedMap}
import scala.math.Ordering
import scala.reflect.ClassTag


    def toPaddedKeySortedDenseVector(keyList: NonEmptyList[K], padValue: Double)
                                    (implicit ord: Ordering[K]): DenseVector[Double] = {
      val x: NonEmptyList[Double] = keyList.sorted.map { a => m.get(a).map((b: V) => b.value).getOrElse(padValue) }
      DenseVector(x.toList.toArray)
    }

    def toNaNPaddedKeySortedDenseVector(keyList: NonEmptyList[K])
                                       (implicit ord: Ordering[K]): DenseVector[Double] =
      m.toPaddedKeySortedDenseVector(keyList, Double.NaN)

    def toZeroPaddedKeySortedDenseVector(keyList: NonEmptyList[K])
                                        (implicit ord: Ordering[K]): DenseVector[Double] =
      m.toPaddedKeySortedDenseVector(keyList, 0.0)

    def toPositiveInfinityPaddedKeySortedDenseVector(keyList: NonEmptyList[K])
                                                    (implicit ord: Ordering[K]): DenseVector[Double] =
      m.toPaddedKeySortedDenseVector(keyList, Double.PositiveInfinity)
  }
} 
开发者ID:fordm,项目名称:bits,代码行数:32,代码来源:RichVectorMap.scala


示例20: SelectorExample

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

import scala.annotation.tailrec
import scala.collection.immutable.Map


object SelectorExample {

  def selector(path: Symbol*): (Map[Symbol, Any] => Option[Any]) = {

    if(path.size <= 0) throw new IllegalArgumentException("path must not be empty")

    @tailrec
    def selectorHelper(path: Seq[Symbol], ds: Map[Symbol, Any]): Option[Any] =
      if(path.size == 1) {
        ds.get(path(0))
      }else{
        val currentPiece = ds.get(path.head)
        currentPiece match {
          case Some(currentMap: Map[Symbol, Any]) =>
            selectorHelper(path.tail, currentMap)
          case None => None
          case _ => None
        }
      }

    (ds: Map[Symbol, Any]) => selectorHelper(path.toSeq, ds)
  }

  def run(): Unit = {
    println("SelectorExample :")
    val simplePerspon = Map('name -> "Yourtion Guo")
    val name = selector('name)
    println("name from simplePerson: " + name(simplePerspon))
    val moreComplexPerson = Map('name -> Map('First -> "Yourtion", 'last -> "Guo"))
    val firstName = selector('name, 'first)
    println("firstName from moreComplexPerson: " + firstName(moreComplexPerson))
    val middleName = selector('name, 'middle)
    println("middleName from moreComplexPerson: " + middleName(moreComplexPerson))
  }

} 
开发者ID:yourtion,项目名称:LearningFunctionalProgramming,代码行数:43,代码来源:SelectorExample.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala PreparedStatement类代码示例发布时间:2022-05-23
下一篇:
Scala TimerTask类代码示例发布时间: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